summaryrefslogtreecommitdiff
path: root/usr/src/lib/libsldap/common/ns_connect.c
blob: 514c802b3452df96c1574c80c7e75a2e2eabda3a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <synch.h>
#include <time.h>
#include <libintl.h>
#include <thread.h>
#include <syslog.h>
#include <sys/mman.h>
#include <nsswitch.h>
#include <nss_dbdefs.h>
#include "solaris-priv.h"
#include "solaris-int.h"
#include "ns_sldap.h"
#include "ns_internal.h"
#include "ns_cache_door.h"
#include "ldappr.h"
#include <sys/stat.h>
#include <fcntl.h>
#include <procfs.h>
#include <unistd.h>

extern unsigned int _sleep(unsigned int);
extern int ldap_sasl_cram_md5_bind_s(LDAP *, char *, struct berval *,
		LDAPControl **, LDAPControl **);
extern int ldapssl_install_gethostbyaddr(LDAP *ld, const char *skip);

static int openConnection(LDAP **, const char *, const ns_cred_t *,
		int, ns_ldap_error_t **, int, int);
/*
 * sessionLock, wait4session, sessionTid
 * are variables to synchronize the creation/retrieval of a connection.
 * MTperCon is a flag to enable/disable multiple threads sharing the same
 * connection.
 * sessionPoolLock is a mutex lock for the connection pool.
 */
static mutex_t	sessionLock = DEFAULTMUTEX;
static int	wait4session = 0;
static thread_t sessionTid = 0;
int	MTperConn = 1;
static rwlock_t sessionPoolLock = DEFAULTRWLOCK;

static Connection **sessionPool = NULL;
static int sessionPoolSize = 0;


static mutex_t	nscdLock = DEFAULTMUTEX;
static int	nscdChecked = 0;
static pid_t	checkedPid = -1;
static int	isNscd = 0;
/*
 * SSF values are for SASL integrity & privacy.
 * JES DS5.2 does not support this feature but DS6 does.
 * The values between 0 and 65535 can work with both server versions.
 */
#define	MAX_SASL_SSF	65535
#define	MIN_SASL_SSF	0

/* Number of hostnames to allocate memory for */
#define	NUMTOMALLOC	32
/*
 * ns_mtckey is for sharing a ldap connection among multiple
 * threads; created by ns_ldap_init() in ns_init.c
 */
extern thread_key_t ns_mtckey;

/* Per thread LDAP error resides in thread-specific data. */
struct ldap_error {
	int	le_errno;
	char	*le_matched;
	char	*le_errmsg;
};

/* destructor */
void
ns_tsd_cleanup(void *key) {
	struct ldap_error *le = (struct ldap_error *)key;

	if (le == NULL)
		return;
	if (le->le_matched != NULL) {
		ldap_memfree(le->le_matched);
	}
	if (le->le_errmsg != NULL) {
		ldap_memfree(le->le_errmsg);
	}
	free(le);
}

/* Callback function for allocating a mutex */
static void *
ns_mutex_alloc(void)
{
	mutex_t *mutexp = NULL;

	if ((mutexp = malloc(sizeof (mutex_t))) != NULL) {
		if (mutex_init(mutexp, USYNC_THREAD, NULL) != 0) {
			free(mutexp);
			mutexp = NULL;
		}
	}
	return (mutexp);
}

/* Callback function for freeing a mutex */
static void
ns_mutex_free(void *mutexp)
{
	(void) mutex_destroy((mutex_t *)mutexp);
	free(mutexp);
}

/*
 * Function for setting up thread-specific data
 * where per thread LDAP error is stored
 */
static int
tsd_setup()
{
	void	*tsd;
	int	rc;

	/* return success if TSD already set */
	rc = thr_getspecific(ns_mtckey, &tsd);
	if (rc == 0 && tsd != NULL)
		return (0);

	/* allocate and set TSD */
	tsd = (void *) calloc(1, sizeof (struct ldap_error));
	if (tsd == NULL)
		return (-1);
	rc = thr_setspecific(ns_mtckey, tsd);
	if (rc != 0) { /* must be ENOMEM */
		free(tsd);
		return (-1);
	}
	return (0);


}

/* Callback function for setting the per thread LDAP error */
/*ARGSUSED*/
static void
set_ld_error(int err, char *matched, char *errmsg, void *dummy)
{
	struct ldap_error	*le;

	if (thr_getspecific(ns_mtckey, (void **)&le) != 0) {
		syslog(LOG_ERR, "set_ld_error: thr_getspecific failed. errno"
				" %d", errno);
		return;
	}
	le->le_errno = err;
	if (le->le_matched != NULL) {
		ldap_memfree(le->le_matched);
	}
	le->le_matched = matched;
	if (le->le_errmsg != NULL) {
		ldap_memfree(le->le_errmsg);
	}
	le->le_errmsg = errmsg;
}

/* Callback function for getting the per thread LDAP error */
/*ARGSUSED*/
static int
get_ld_error(char **matched, char **errmsg, void *dummy)
{
	struct ldap_error	*le;

	if (thr_getspecific(ns_mtckey, (void **)&le) != 0) {
		syslog(LOG_ERR, "get_ld_error: thr_getspecific failed. errno"
				" %d", errno);
		return (errno);
	}
	if (matched != NULL) {
		*matched = le->le_matched;
	}
	if (errmsg != NULL) {
		*errmsg = le->le_errmsg;
	}
	return (le->le_errno);
}

/* Callback function for setting per thread errno */
static void
set_errno(int err)
{
	errno = err;
}

/* Callback function for getting per thread errno */
static int
get_errno(void)
{
	return (errno);
}

/*
 * set up to allow multiple threads to use the same ldap connection
 */
static int
setup_mt_conn(LDAP *ld)
{

	struct ldap_thread_fns		tfns;
	struct ldap_extra_thread_fns	extrafns;
	int				rc;

	/*
	 * Set the function pointers for dealing with mutexes
	 * and error information
	 */
	(void) memset(&tfns, '\0', sizeof (struct ldap_thread_fns));
	tfns.ltf_mutex_alloc = (void *(*)(void)) ns_mutex_alloc;
	tfns.ltf_mutex_free = (void (*)(void *)) ns_mutex_free;
	tfns.ltf_mutex_lock = (int (*)(void *)) mutex_lock;
	tfns.ltf_mutex_unlock = (int (*)(void *)) mutex_unlock;
	tfns.ltf_get_errno = get_errno;
	tfns.ltf_set_errno = set_errno;
	tfns.ltf_get_lderrno = get_ld_error;
	tfns.ltf_set_lderrno = set_ld_error;
	tfns.ltf_lderrno_arg = NULL;

	/*
	 * Set up this session to use those function pointers
	 */
	rc = ldap_set_option(ld, LDAP_OPT_THREAD_FN_PTRS,
		(void *) &tfns);
	if (rc < 0) {
		syslog(LOG_WARNING, "libsldap: ldap_set_option "
		"(LDAP_OPT_THREAD_FN_PTRS)");
		return (-1);
	}

	/*
	 * Set the function pointers for working with semaphores
	 */
	(void) memset(&extrafns, '\0',
		sizeof (struct ldap_extra_thread_fns));
	extrafns.ltf_threadid_fn = (void * (*)(void))thr_self;
	extrafns.ltf_mutex_trylock = NULL;
	extrafns.ltf_sema_alloc = NULL;
	extrafns.ltf_sema_free = NULL;
	extrafns.ltf_sema_wait = NULL;
	extrafns.ltf_sema_post = NULL;

	/* Set up this session to use those function pointers */
	rc = ldap_set_option(ld, LDAP_OPT_EXTRA_THREAD_FN_PTRS,
		(void *) &extrafns);
	if (rc < 0) {
		syslog(LOG_WARNING, "libsldap: ldap_set_option "
		"(LDAP_OPT_EXTRA_THREAD_FN_PTRS)");
		return (-1);
	}

	return (0);
}

static void
ns_setup_mt_conn_and_tsd(LDAP *ld) {
	thread_t t = thr_self();
	void *tsd;
	/* set up to share this connection among threads */
	if (MTperConn == 1) {
		if (tsd_setup() == -1) {
			syslog(LOG_ERR, "tid= %d: unable "
				"to set up TSD\n", t);
		} else {
			if (setup_mt_conn(ld) == -1) {
			/* multiple threads per connection not supported */
				syslog(LOG_ERR, "tid= %d: multiple "
					"threads per connection not "
					"supported\n", t);
				(void) thr_getspecific(ns_mtckey, &tsd);
				ns_tsd_cleanup(tsd);
				(void) thr_setspecific(ns_mtckey, NULL);
				MTperConn = 0;
			}
		}
	}
}

/*
 * Check /proc/PID/psinfo to see if this process is nscd
 * If it is, treat connection as NS_LDAP_KEEP_CONN, to reduce
 * constant reconnects for many operations.
 * A more complete solution is to develop true connection pooling.
 * However, this is much better than a new connection for every request.
 */
static int
nscd_proc()
{
	pid_t		my_pid;
	psinfo_t	pinfo;
	char		fname[BUFSIZ];
	int		ret;
	int		fd;

	/* Don't bother checking if this process isn't root. */
	/* It can't be nscd */
	if (getuid() != 0)
		return (0);

	my_pid = getpid();
	if (nscdChecked && (my_pid == checkedPid)) {
		return (isNscd);
	}
	(void) mutex_lock(&nscdLock);
	if (nscdChecked && (my_pid == checkedPid)) {
		(void) mutex_unlock(&nscdLock);
		return (isNscd);
	}
	nscdChecked = 1;
	checkedPid = my_pid;
	isNscd = 0;
	if (snprintf(fname, BUFSIZ, "/proc/%d/psinfo", my_pid) != 0) {
		if ((fd = open(fname,  O_RDONLY)) > 0) {
			ret = read(fd, &pinfo, sizeof (psinfo_t));
			(void) close(fd);
			if (ret == sizeof (psinfo_t) &&
			    (strcmp(pinfo.pr_fname, "nscd") == 0)) {
				/* process runs as root and is named nscd */
				/* that's good enough for now */
				isNscd = 1;
			}
		}
	}
	(void) mutex_unlock(&nscdLock);
	return (isNscd);
}

/*
 * This function requests a server from the cache manager through
 * the door functionality
 */

static int
__s_api_requestServer(const char *request, const char *server,
	ns_server_info_t *ret, ns_ldap_error_t **error,  const char *addrType)
{
	union {
		ldap_data_t	s_d;
		char		s_b[DOORBUFFERSIZE];
	} space;
	ldap_data_t	*sptr;
	int		ndata;
	int		adata;
	char		errstr[MAXERROR];
	const char	*ireq;
	char		*rbuf, *ptr, *rest;
	char		*dptr;
	char		**mptr, **mptr1, **cptr, **cptr1;
	int		mcnt, ccnt;
	char		**servers;
	int		rc, len;

	if (ret == NULL || error == NULL) {
		return (NS_LDAP_OP_FAILED);
	}
	(void) memset(ret, 0, sizeof (ns_server_info_t));
	*error = NULL;

	(void) memset(space.s_b, 0, DOORBUFFERSIZE);

	if (request == NULL)
		ireq = NS_CACHE_NEW;
	else
		ireq = request;

	adata = (sizeof (ldap_call_t) + strlen(ireq) + strlen(addrType) + 1);
	if (server != NULL) {
		adata += strlen(DOORLINESEP) + 1;
		adata += strlen(server) + 1;
	}
	ndata = sizeof (space);
	len = sizeof (space) - sizeof (space.s_d.ldap_call.ldap_callnumber);
	space.s_d.ldap_call.ldap_callnumber = GETLDAPSERVER;
	if (strlcpy(space.s_d.ldap_call.ldap_u.domainname, ireq, len) >= len)
		return (NS_LDAP_MEMORY);
	if (strlcat(space.s_d.ldap_call.ldap_u.domainname, addrType, len) >=
			len)
		return (NS_LDAP_MEMORY);
	if (server != NULL) {
		if (strlcat(space.s_d.ldap_call.ldap_u.domainname,
			DOORLINESEP, len) >= len)
			return (NS_LDAP_MEMORY);
		if (strlcat(space.s_d.ldap_call.ldap_u.domainname, server,
			len) >= len)
			return (NS_LDAP_MEMORY);
	}
	sptr = &space.s_d;

	switch (__ns_ldap_trydoorcall(&sptr, &ndata, &adata)) {
	case SUCCESS:
		break;
	/* this case is for when the $mgr is not running, but ldapclient */
	/* is trying to initialize things */
	case NOSERVER:
		/* get first server from config list unavailable otherwise */
		servers = NULL;
		rc = __s_api_getServers(&servers, error);
		if (rc != NS_LDAP_SUCCESS) {
			if (servers != NULL) {
				__s_api_free2dArray(servers);
				servers = NULL;
			}
			return (rc);
		}
		if (servers == NULL || servers[0] == NULL) {
			__s_api_free2dArray(servers);
			servers = NULL;
			(void) sprintf(errstr,
				gettext("No server found in configuration"));
			MKERROR(LOG_ERR, *error, NS_CONFIG_NODEFAULT,
				strdup(errstr), NULL);
			return (NS_LDAP_CONFIG);
		}
		ret->server = strdup(servers[0]);
		if (ret->server == NULL) {
			__s_api_free2dArray(servers);
			return (NS_LDAP_MEMORY);
		}
		ret->saslMechanisms = NULL;
		ret->controls = NULL;
		__s_api_free2dArray(servers);
		servers = NULL;
		return (NS_LDAP_SUCCESS);
	case NOTFOUND:
	default:
		return (NS_LDAP_OP_FAILED);
	}

	/* copy info from door call return structure here */
	rbuf =  space.s_d.ldap_ret.ldap_u.config;

	/* Get the host */
	ptr = strtok_r(rbuf, DOORLINESEP, &rest);
	if (ptr == NULL) {
		(void) sprintf(errstr, gettext("No server returned from "
			"ldap_cachemgr"));
		MKERROR(LOG_WARNING, *error, NS_CONFIG_CACHEMGR,
			strdup(errstr), NULL);
		return (NS_LDAP_OP_FAILED);
	}
	ret->server = strdup(ptr);
	if (ret->server == NULL) {
		return (NS_LDAP_MEMORY);
	}

	/* get the Supported Controls/SASL mechs */
	mptr = NULL;
	mcnt = 0;
	cptr = NULL;
	ccnt = 0;
	for (; ; ) {
		ptr = strtok_r(NULL, DOORLINESEP, &rest);
		if (ptr == NULL)
			break;
		if (strncasecmp(ptr, _SASLMECHANISM,
				_SASLMECHANISM_LEN) == 0) {
			dptr = strchr(ptr, '=');
			if (dptr == NULL)
				continue;
			dptr++;
			mptr1 = (char **)realloc((void *)mptr,
					sizeof (char *) * (mcnt+2));
			if (mptr1 == NULL) {
				__s_api_free2dArray(mptr);
				if (sptr != &space.s_d) {
				    (void) munmap((char *)sptr, ndata);
				}
				__s_api_free2dArray(cptr);
				free(ret->server);
				ret->server = NULL;
				return (NS_LDAP_MEMORY);
			}
			mptr = mptr1;
			mptr[mcnt] = strdup(dptr);
			if (mptr[mcnt] == NULL) {
				if (sptr != &space.s_d) {
				    (void) munmap((char *)sptr, ndata);
				}
				__s_api_free2dArray(cptr);
				cptr = NULL;
				__s_api_free2dArray(mptr);
				mptr = NULL;
				free(ret->server);
				ret->server = NULL;
				return (NS_LDAP_MEMORY);
			}
			mcnt++;
			mptr[mcnt] = NULL;
		}
		if (strncasecmp(ptr, _SUPPORTEDCONTROL,
			_SUPPORTEDCONTROL_LEN) == 0) {
			dptr = strchr(ptr, '=');
			if (dptr == NULL)
				continue;
			dptr++;
			cptr1 = (char **)realloc((void *)cptr,
					sizeof (char *) * (ccnt+2));
			if (cptr1 == NULL) {
				if (sptr != &space.s_d) {
				    (void) munmap((char *)sptr, ndata);
				}
				__s_api_free2dArray(cptr);
				__s_api_free2dArray(mptr);
				mptr = NULL;
				free(ret->server);
				ret->server = NULL;
				return (NS_LDAP_MEMORY);
			}
			cptr = cptr1;
			cptr[ccnt] = strdup(dptr);
			if (cptr[ccnt] == NULL) {
				if (sptr != &space.s_d) {
				    (void) munmap((char *)sptr, ndata);
				}
				__s_api_free2dArray(cptr);
				cptr = NULL;
				__s_api_free2dArray(mptr);
				mptr = NULL;
				free(ret->server);
				ret->server = NULL;
				return (NS_LDAP_MEMORY);
			}
			ccnt++;
			cptr[ccnt] = NULL;
		}
	}
	if (mptr != NULL) {
		ret->saslMechanisms = mptr;
	}
	if (cptr != NULL) {
		ret->controls = cptr;
	}


	/* clean up door call */
	if (sptr != &space.s_d) {
		(void) munmap((char *)sptr, ndata);
	}
	*error = NULL;

	return (NS_LDAP_SUCCESS);
}


/*
 * printCred(): prints the credential structure
 */
static void
printCred(int pri, const ns_cred_t *cred)
{
	thread_t	t = thr_self();

	if (cred == NULL) {
		syslog(LOG_ERR, "tid= %d: printCred: cred is NULL\n", t);
		return;
	}

	syslog(pri, "tid= %d: AuthType=%d", t, cred->auth.type);
	syslog(pri, "tid= %d: TlsType=%d", t, cred->auth.tlstype);
	syslog(pri, "tid= %d: SaslMech=%d", t, cred->auth.saslmech);
	syslog(pri, "tid= %d: SaslOpt=%d", t, cred->auth.saslopt);
	if (cred->hostcertpath)
		syslog(pri, "tid= %d: hostCertPath=%s\n",
			t, cred->hostcertpath);
	if (cred->cred.unix_cred.userID)
		syslog(pri, "tid= %d: userID=%s\n",
			t, cred->cred.unix_cred.userID);
	if (cred->cred.unix_cred.passwd)
		syslog(pri, "tid= %d: passwd=%s\n",
			t, cred->cred.unix_cred.passwd);
}

/*
 * printConnection(): prints the connection structure
 */
static void
printConnection(int pri, Connection *con)
{
	thread_t	t = thr_self();

	if (con == NULL)
		return;

	syslog(pri, "tid= %d: connectionID=%d\n", t, con->connectionId);
	syslog(pri, "tid= %d: shared=%d\n", t, con->shared);
	syslog(pri, "tid= %d: usedBit=%d\n", t, con->usedBit);
	syslog(pri, "tid= %d: threadID=%d\n", t, con->threadID);
	if (con->serverAddr) {
		syslog(pri, "tid= %d: serverAddr=%s\n",
			t, con->serverAddr);
	}
	printCred(pri, con->auth);
}



/*
 * addConnection(): set up a connection so that it can be shared
 * among multiple threads and then insert the connection in the
 * connection list.
 * Returns: -1 = failure, new Connection ID = success
 *
 * This function could exit with sessionLock locked. It will be
 * be unlocked in __s_api_getConnection() when it exits without getting a
 * connection.
 */
static int
addConnection(Connection *con)
{
	int i, noMTperC = 0;
	thread_t t = thr_self();
	struct ldap_thread_fns tfns;
	void *tsd;

	if (!con)
		return (-1);

	syslog(LOG_DEBUG, "tid= %d: Adding connection (serverAddr=%s)",
			t, con->serverAddr);

	if (MTperConn == 1) {
		/*
		 * Make sure ld has proper thread functions and tsd
		 * is set up.
		 */
		(void) memset(&tfns, 0, sizeof (struct ldap_thread_fns));
		/*
		 * ldap_init sets ltf_get_lderrno and ltf_set_lderrno to NULLs.
		 * It's supposed to be overwritten by ns_setup_mt_conn_and_tsd.
		 */
		if (ldap_get_option(con->ld, LDAP_OPT_THREAD_FN_PTRS,
				(void *)&tfns) != 0 ||
				tfns.ltf_get_lderrno != get_ld_error ||
				tfns.ltf_set_lderrno != set_ld_error) {
			MTperConn = 0;
			noMTperC = 1;
		} else {
			if (thr_getspecific(ns_mtckey, &tsd) != 0 ||
					tsd == NULL)
				noMTperC = 1;
		}

	} else {
		noMTperC = 1;
	}

	(void) rw_wrlock(&sessionPoolLock);
	if (sessionPool == NULL) {
		sessionPoolSize = SESSION_CACHE_INC;
		sessionPool = calloc(sessionPoolSize,
				sizeof (struct connection **));
		if (!sessionPool) {
			(void) rw_unlock(&sessionPoolLock);
			return (-1);
		}

		syslog(LOG_DEBUG, "tid= %d: Initialized sessionPool", t);
	}
	for (i = 0; (i < sessionPoolSize) && (sessionPool[i] != NULL); ++i)
		;
	if (i == sessionPoolSize) {
		/* run out of array, need to increase sessionPool */
		Connection **cl;
		cl = (Connection **) realloc(sessionPool,
			(sessionPoolSize + SESSION_CACHE_INC) *
			sizeof (Connection *));
		if (!cl) {
			(void) rw_unlock(&sessionPoolLock);
			return (-1);
		}
		(void) memset(cl + sessionPoolSize, 0,
			SESSION_CACHE_INC * sizeof (struct connection *));
		sessionPool = cl;
		sessionPoolSize += SESSION_CACHE_INC;
		syslog(LOG_DEBUG, "tid: %d: Increased "
				"sessionPoolSize to: %d\n",
				t, sessionPoolSize);
	}
	sessionPool[i] = con;
	if (noMTperC == 0)
		con->shared++;
	else
		con->usedBit = B_TRUE;

	(void) rw_unlock(&sessionPoolLock);

	con->connectionId = i + CONID_OFFSET;

	syslog(LOG_DEBUG, "tid= %d: Connection added [%d]\n",
			t, i);
	printConnection(LOG_DEBUG, con);

	/*
	 * A connection can be shared now, unlock
	 * the session mutex and let other
	 * threads try to use this connection or
	 * get their own.
	 */
	if (wait4session != 0 && sessionTid == thr_self()) {
		wait4session = 0;
		sessionTid = 0;
		syslog(LOG_DEBUG, "tid= %d: unlocking sessionLock\n", t);
		(void) mutex_unlock(&sessionLock);
	}

	return (i + CONID_OFFSET);
}

/*
 * See if the specified session matches a currently available
 */

static int
findConnectionById(int flags, const ns_cred_t *auth, ConnectionID cID,
	Connection **conp)
{
	Connection *cp;
	int id;

	if ((conp == NULL) || (auth == NULL) || cID < CONID_OFFSET)
		return (-1);

	/* if a new connection is requested, no need to continue */
	if (flags & NS_LDAP_NEW_CONN)
		return (-1);

	*conp = NULL;
	if (sessionPool == NULL)
		return (-1);
	id = cID - CONID_OFFSET;
	if (id < 0 || id >= sessionPoolSize)
		return (-1);

	(void) rw_rdlock(&sessionPoolLock);
	if (sessionPool[id] == NULL) {
		(void) rw_unlock(&sessionPoolLock);
		return (-1);
	}
	cp = sessionPool[id];

	/*
	 * Make sure the connection has the same type of authentication method
	 */
	if ((cp->usedBit) ||
	    (cp->notAvail) ||
	    (cp->auth->auth.type != auth->auth.type) ||
	    (cp->auth->auth.tlstype != auth->auth.tlstype) ||
	    (cp->auth->auth.saslmech != auth->auth.saslmech) ||
	    (cp->auth->auth.saslopt != auth->auth.saslopt)) {
		(void) rw_unlock(&sessionPoolLock);
		return (-1);
	}
	if ((((cp->auth->auth.type == NS_LDAP_AUTH_SASL) &&
		((cp->auth->auth.saslmech == NS_LDAP_SASL_CRAM_MD5) ||
		(cp->auth->auth.saslmech == NS_LDAP_SASL_DIGEST_MD5))) ||
		(cp->auth->auth.type == NS_LDAP_AUTH_SIMPLE)) &&
		((cp->auth->cred.unix_cred.userID == NULL) ||
		(strcasecmp(cp->auth->cred.unix_cred.userID,
		auth->cred.unix_cred.userID) != 0))) {
		(void) rw_unlock(&sessionPoolLock);
		return (-1);
	}

	/* An existing connection is found but it needs to be reset */
	if (flags & NS_LDAP_NEW_CONN) {
		(void) rw_unlock(&sessionPoolLock);
		DropConnection(cID, 0);
		return (-1);
	}
	/* found an available connection */
	cp->usedBit = B_TRUE;
	(void) rw_unlock(&sessionPoolLock);
	cp->threadID = thr_self();
	*conp = cp;
	return (cID);
}

/*
 * findConnection(): find an available connection from the list
 * that matches the criteria specified in Connection structure.
 * If serverAddr is NULL, then find a connection to any server
 * as long as it matches the rest of the parameters.
 * Returns: -1 = failure, the Connection ID found = success.
 *
 * This function could exit with sessionLock locked. It will be
 * be unlocked in addConnection() when this thread adds the connection
 * to the pool or in __s_api_getConnection() when it exits without getting a
 * connection.
 */
#define	TRY_TIMES	10
static int
findConnection(int flags, const char *serverAddr,
	const ns_cred_t *auth, Connection **conp)
{
	Connection *cp;
	int i;
	int rc;
	int try;
#ifdef DEBUG
	thread_t t = thr_self();
#endif /* DEBUG */

	if (auth == NULL || conp == NULL)
		return (-1);
	*conp = NULL;

	/* no need to find connection if anonymous */
	if (auth->auth.type == NS_LDAP_AUTH_NONE)
		return (-1);

	/* if a new connection is requested, no need to continue */
	if (flags & NS_LDAP_NEW_CONN)
		return (-1);

#ifdef DEBUG
	(void) fprintf(stderr, "tid= %d: Find connection\n", t);
	(void) fprintf(stderr, "tid= %d: Looking for ....\n", t);
	if (serverAddr && *serverAddr)
		(void) fprintf(stderr, "tid= %d: serverAddr=%s\n",
			t, serverAddr);
	else
		(void) fprintf(stderr, "tid= %d: serverAddr=NULL\n", t);
	printCred(stderr, auth);
	fflush(stderr);
#endif /* DEBUG */

	/*
	 * If multiple threads per connection not supported,
	 * no sessionPool means no connection
	 */
	(void) rw_rdlock(&sessionPoolLock);
	if (MTperConn == 0 && sessionPool == NULL) {
		(void) rw_unlock(&sessionPoolLock);
		return (-1);
	}

	/*
	 * If no connection in cache, then serialize the opening
	 * of connections. Make sure only one is being opened
	 * at a time. Otherwise, we may end up with more
	 * connections than we want (if multiple threads get
	 * here at the same time)
	 */
	if (sessionPool == NULL) {
		(void) rw_unlock(&sessionPoolLock);
		(void) mutex_lock(&sessionLock);
		if (sessionPool == NULL) {
			wait4session = 1;
			sessionTid = thr_self();
#ifdef DEBUG
			(void) fprintf(stderr, "tid= %d: get "
				"connection ... \n", t);
			fflush(stderr);
#endif /* DEBUG */
			/*
			 * Exit with sessionLock locked. It will be
			 * be unlocked in addConnection() when this
			 * thread adds the connection to the pool or
			 * in __s_api_getConnection() when it exits
			 * without getting a connection.
			 */
			return (-1);
		}

#ifdef DEBUG
		(void) fprintf(stderr, "tid= %d: session pool not empty\n", t);
		fflush(stderr);
#endif /* DEBUG */
		/*
		 * connection pool is not empty, check to see if
		 * one can be shared.
		 */
		(void) mutex_unlock(&sessionLock);
		(void) rw_rdlock(&sessionPoolLock);
	}
	try = 0;
	check_again:

	for (i = 0; i < sessionPoolSize; ++i) {
		if (sessionPool[i] == NULL)
			continue;
		cp = sessionPool[i];
#ifdef DEBUG
		(void) fprintf(stderr, "tid= %d: checking connection "
			"[%d] ....\n", t, i);
		printConnection(stderr, cp);
#endif /* DEBUG */
		if ((cp->usedBit) || (cp->notAvail) ||
		    (cp->auth->auth.type != auth->auth.type) ||
		    (cp->auth->auth.tlstype != auth->auth.tlstype) ||
		    (cp->auth->auth.saslmech != auth->auth.saslmech) ||
		    (cp->auth->auth.saslopt != auth->auth.saslopt) ||
		    (serverAddr && *serverAddr &&
		    (strcasecmp(serverAddr, cp->serverAddr) != 0)))
			continue;
		if ((((cp->auth->auth.type == NS_LDAP_AUTH_SASL) &&
		    ((cp->auth->auth.saslmech == NS_LDAP_SASL_CRAM_MD5) ||
		    (cp->auth->auth.saslmech == NS_LDAP_SASL_DIGEST_MD5))) ||
		    (cp->auth->auth.type == NS_LDAP_AUTH_SIMPLE)) &&
		    ((cp->auth->cred.unix_cred.userID == NULL) ||
		    (cp->auth->cred.unix_cred.passwd == NULL) ||
		    ((strcasecmp(cp->auth->cred.unix_cred.userID,
			    auth->cred.unix_cred.userID) != 0)) ||
		    ((strcmp(cp->auth->cred.unix_cred.passwd,
			    auth->cred.unix_cred.passwd) != 0))))
				continue;
		/* found an available connection */
		if (MTperConn == 0)
			cp->usedBit = B_TRUE;
		else {
			/* allocate TSD for per thread ldap error */
			rc = tsd_setup();

			/* if we got TSD, this connection is shared */
			if (rc != -1)
				cp->shared++;
			else if (cp->shared == 0) {
				cp->usedBit = B_TRUE;
				cp->threadID = thr_self();
				(void) rw_unlock(&sessionPoolLock);
				return (-1);
			}
		}
		(void) rw_unlock(&sessionPoolLock);

		*conp = cp;
#ifdef DEBUG
		(void) fprintf(stderr, "tid= %d: Connection found "
			"cID=%d, shared =%d\n", t, i, cp->shared);
		fflush(stderr);
#endif /* DEBUG */
		return (i + CONID_OFFSET);
	}
	(void) rw_unlock(&sessionPoolLock);

	/*
	 * If multiple threads per connection not supported,
	 * we are done, just return -1 to tell the caller to
	 * proceed with opening a connection
	 */
	if (MTperConn == 0)
		return (-1);

	/*
	 * No connection can be shared, test to see if
	 * one is being opened. If trylock returns
	 * EBUSY then it is, so wait until the opening
	 * is done and try to see if the new connection
	 * can be shared.
	 */
	rc = mutex_trylock(&sessionLock);
	if (rc == EBUSY) {
		(void) mutex_lock(&sessionLock);
		(void) mutex_unlock(&sessionLock);
		(void) rw_rdlock(&sessionPoolLock);
#ifdef DEBUG
		(void) fprintf(stderr, "tid= %d: check session "
			"pool again\n", t);
		fflush(stderr);
#endif /* DEBUG */
		if (try < TRY_TIMES) {
			try++;
			goto check_again;
		} else {
			syslog(LOG_WARNING, "libsldap: mutex_trylock "
				"%d times. Stop.", TRY_TIMES);
			return (-1);
		}
	} else if (rc == 0) {
		/*
		 * No connection can be shared, none being opened,
		 * exit with sessionLock locked to open one. The
		 * mutex will be unlocked in addConnection() when
		 * this thread adds the new connection to the pool
		 * or in __s_api_getConnection() when it exits
		 * without getting a connection.
		 */
		wait4session = 1;
		sessionTid = thr_self();
#ifdef DEBUG
		(void) fprintf(stderr, "tid= %d: no connection found, "
			"none being opened, get connection ...\n", t);
		fflush(stderr);
#endif /* DEBUG */
		return (-1);
	} else {
		syslog(LOG_WARNING, "libsldap: mutex_trylock unexpected "
			"error", rc);
		return (-1);
	}
}

/*
 * Free a Connection structure
 */
static void
freeConnection(Connection *con)
{
	if (con == NULL)
		return;
	if (con->serverAddr)
		free(con->serverAddr);
	if (con->auth)
		(void) __ns_ldap_freeCred(&(con->auth));
	if (con->saslMechanisms) {
		__s_api_free2dArray(con->saslMechanisms);
	}
	if (con->controls) {
		__s_api_free2dArray(con->controls);
	}
	free(con);
}

/*
 * Find a connection matching the passed in criteria.  If an open
 * connection with that criteria exists use it, otherwise open a
 * new connection.
 * Success: returns the pointer to the Connection structure
 * Failure: returns NULL, error code and message should be in errorp
 */

static int
makeConnection(Connection **conp, const char *serverAddr,
	const ns_cred_t *auth, ConnectionID *cID, int timeoutSec,
	ns_ldap_error_t **errorp, int fail_if_new_pwd_reqd,
	int nopasswd_acct_mgmt, int flags, char ***badsrvrs)
{
	Connection *con = NULL;
	ConnectionID id;
	char errmsg[MAXERROR];
	int rc, exit_rc = NS_LDAP_SUCCESS;
	ns_server_info_t sinfo;
	char *hReq, *host = NULL;
	LDAP *ld = NULL;
	int passwd_mgmt = 0;
	int totalbad = 0; /* Number of servers contacted unsuccessfully */
	short	memerr = 0; /* Variable for tracking memory allocation */
	char *serverAddrType = NULL;


	if (conp == NULL || errorp == NULL || auth == NULL)
		return (NS_LDAP_INVALID_PARAM);
	*errorp = NULL;
	*conp = NULL;
	sinfo.server = NULL;
	sinfo.controls = NULL;
	sinfo.saslMechanisms = NULL;

	if ((id = findConnection(flags, serverAddr, auth, &con)) != -1) {
		/* connection found in cache */
#ifdef DEBUG
		(void) fprintf(stderr, "tid= %d: connection found in "
			"cache %d\n", thr_self(), id);
		fflush(stderr);
#endif /* DEBUG */
		*cID = id;
		*conp = con;
		return (NS_LDAP_SUCCESS);
	}

	if (auth->auth.saslmech == NS_LDAP_SASL_GSSAPI)
		serverAddrType = NS_CACHE_ADDR_HOSTNAME;
	else
		serverAddrType = NS_CACHE_ADDR_IP;

	if (serverAddr) {
		rc = __s_api_requestServer(NS_CACHE_NEW, serverAddr,
			&sinfo, errorp, serverAddrType);
		if (rc != NS_LDAP_SUCCESS || sinfo.server == NULL) {
			(void) snprintf(errmsg, sizeof (errmsg),
			gettext("makeConnection: unable to get "
			"server information for %s"), serverAddr);
			syslog(LOG_ERR, "libsldap: %s", errmsg);
			return (NS_LDAP_OP_FAILED);
		}
		rc = openConnection(&ld, sinfo.server, auth, timeoutSec, errorp,
				fail_if_new_pwd_reqd, passwd_mgmt);
		if (rc == NS_LDAP_SUCCESS || rc ==
				NS_LDAP_SUCCESS_WITH_INFO) {
			exit_rc = rc;
			goto create_con;
		} else {
			return (rc);
		}
	}

	/* No cached connection, create one */
	for (; ; ) {
		if (host == NULL)
			hReq = NS_CACHE_NEW;
		else
			hReq = NS_CACHE_NEXT;
		rc = __s_api_requestServer(hReq, host, &sinfo, errorp,
				serverAddrType);
		if ((rc != NS_LDAP_SUCCESS) || (sinfo.server == NULL) ||
			(host && (strcasecmp(host, sinfo.server) == 0))) {
			/* Log the error */
			if (*errorp) {
				(void) snprintf(errmsg, sizeof (errmsg),
				"%s: (%s)", gettext("makeConnection: "
				"unable to make LDAP connection, "
				"request for a server failed"),
				    (*errorp)->message);
				syslog(LOG_ERR, "libsldap: %s", errmsg);
			}

			if (sinfo.server)
				free(sinfo.server);
			__s_api_free2dArray(sinfo.saslMechanisms);
			__s_api_free2dArray(sinfo.controls);
			if (host)
				free(host);
			return (NS_LDAP_OP_FAILED);
		}
		if (host)
			free(host);
		host = strdup(sinfo.server);
		if (host == NULL) {
			free(sinfo.server);
			__s_api_free2dArray(sinfo.saslMechanisms);
			__s_api_free2dArray(sinfo.controls);
			return (NS_LDAP_MEMORY);
		}

		/* check if server supports password management */
		passwd_mgmt = __s_api_contain_passwd_control_oid(
			sinfo.controls);
		/* check if server supports password less account mgmt */
		if (nopasswd_acct_mgmt &&
			!__s_api_contain_account_usable_control_oid(
			sinfo.controls)) {
			syslog(LOG_WARNING, "libsldap: server %s does not "
				"provide account information without password",
				host);
			free(host);
			free(sinfo.server);
			__s_api_free2dArray(sinfo.saslMechanisms);
			__s_api_free2dArray(sinfo.controls);
			return (NS_LDAP_OP_FAILED);
		}
		/* make the connection */
		rc = openConnection(&ld, host, auth, timeoutSec, errorp,
				fail_if_new_pwd_reqd, passwd_mgmt);
		/* if success, go to create connection structure */
		if (rc == NS_LDAP_SUCCESS ||
				rc == NS_LDAP_SUCCESS_WITH_INFO) {
			exit_rc = rc;
			break;
		}

		/*
		 * If not able to reach the server, inform the ldap
		 * cache manager that the server should be removed
		 * from its server list. Thus, the manager will not
		 * return this server on the next get-server request
		 * and will also reduce the server list refresh TTL,
		 * so that it will find out sooner when the server
		 * is up again.
		 */
		if (rc == NS_LDAP_INTERNAL && *errorp != NULL) {
			if ((*errorp)->status == LDAP_CONNECT_ERROR ||
				(*errorp)->status == LDAP_SERVER_DOWN) {
				/* Reset memory allocation error */
				memerr = 0;
				/*
				 * We contacted a server that we could
				 * not either authenticate to or contact.
				 * If it is due to authentication, then
				 * we need to try the server again. So,
				 * do not remove the server yet, but
				 * add it to the bad server list.
				 * The caller routine will remove
				 * the servers if:
				 *	a). A good server is found or
				 *	b). All the possible methods
				 *	    are tried without finding
				 *	    a good server
				 */
				if (*badsrvrs == NULL) {
				    if (!(*badsrvrs = (char **)malloc
					(sizeof (char *) * NUMTOMALLOC))) {
					memerr = 1;
				    }
				/* Allocate memory in chunks of NUMTOMALLOC */
				} else if ((totalbad % NUMTOMALLOC) ==
					    NUMTOMALLOC - 1) {
				    char **tmpptr;
				    if (!(tmpptr = (char **)realloc(*badsrvrs,
					    (sizeof (char *) * NUMTOMALLOC *
					    ((totalbad/NUMTOMALLOC) + 2))))) {
					memerr = 1;
				    } else {
					*badsrvrs = tmpptr;
				    }
				}
				/*
				 * Store host only if there were no unsuccessful
				 * memory allocations above
				 */
				if (!memerr &&
				    !((*badsrvrs)[totalbad++] = strdup(host))) {
					memerr = 1;
					totalbad--;
				}
				(*badsrvrs)[totalbad] = NULL;
			}
		}

		/* else, cleanup and go for the next server */
		if (sinfo.server) {
			free(sinfo.server);
			sinfo.server = NULL;
		}
		__s_api_free2dArray(sinfo.saslMechanisms);
		sinfo.saslMechanisms = NULL;
		__s_api_free2dArray(sinfo.controls);
		sinfo.controls = NULL;
		/* Return if we had memory allocation errors */
		if (memerr)
			return (NS_LDAP_MEMORY);
		if (*errorp) {
			/*
			 * If openConnection() failed due to
			 * password policy, or invalid credential,
			 * keep *errorp and exit
			 */
			if ((*errorp)->pwd_mgmt.status != NS_PASSWD_GOOD ||
			    (*errorp)->status == LDAP_INVALID_CREDENTIALS) {
				free(host);
				return (rc);
			} else {
				(void) __ns_ldap_freeError(errorp);
				*errorp = NULL;
			}
		}
	}

create_con:
	/* we have created ld, setup con structure */
	if (host)
		free(host);
	if ((con = calloc(1, sizeof (Connection))) == NULL) {
		if (sinfo.server)
			free(sinfo.server);
		__s_api_free2dArray(sinfo.saslMechanisms);
		__s_api_free2dArray(sinfo.controls);
		/*
		 * If password control attached in **errorp,
		 * e.g. rc == NS_LDAP_SUCCESS_WITH_INFO,
		 * free the error structure
		 */
		if (*errorp) {
			(void) __ns_ldap_freeError(errorp);
			*errorp = NULL;
		}
		return (NS_LDAP_MEMORY);
	}

	con->serverAddr = sinfo.server;
	con->saslMechanisms = sinfo.saslMechanisms;
	con->controls = sinfo.controls;

	con->auth = __ns_ldap_dupAuth(auth);
	if (con->auth == NULL) {
		free(con);
		/*
		 * If password control attached in **errorp,
		 * e.g. rc == NS_LDAP_SUCCESS_WITH_INFO,
		 * free the error structure
		 */
		if (*errorp) {
			(void) __ns_ldap_freeError(errorp);
			*errorp = NULL;
		}
		return (NS_LDAP_MEMORY);
	}

	con->threadID = thr_self();

	con->ld = ld;
	if ((id = addConnection(con)) == -1) {
		freeConnection(con);
		/*
		 * If password control attached in **errorp,
		 * e.g. rc == NS_LDAP_SUCCESS_WITH_INFO,
		 * free the error structure
		 */
		if (*errorp) {
			(void) __ns_ldap_freeError(errorp);
			*errorp = NULL;
		}
		return (NS_LDAP_MEMORY);
	}
#ifdef DEBUG
	(void) fprintf(stderr, "tid= %d: connection added into "
		"cache %d\n", thr_self(), id);
	fflush(stderr);
#endif /* DEBUG */
	*cID = id;
	*conp = con;
	return (exit_rc);
}

/*
 * Return the specified connection to the pool.  If necessary
 * delete the connection.
 */

static void
_DropConnection(ConnectionID cID, int flag, int fini)
{
	Connection *cp;
	int id;
	int use_lock = !fini;
#ifdef DEBUG
	thread_t t = thr_self();
#endif /* DEBUG */

	id = cID - CONID_OFFSET;
	if (id < 0 || id >= sessionPoolSize)
		return;
#ifdef DEBUG
	(void) fprintf(stderr, "tid= %d: "
		"Dropping connection cID=%d flag=0x%x, fini = %d\n",
			t, cID, flag, fini);
	fflush(stderr);
#endif /* DEBUG */
	if (use_lock)
		(void) rw_wrlock(&sessionPoolLock);

	cp = sessionPool[id];
	/* sanity check before removing */
	if (!cp || (!fini && !cp->shared && (!cp->usedBit ||
		cp->threadID != thr_self()))) {
#ifdef DEBUG
		if (cp == NULL)
			(void) fprintf(stderr, "tid= %d: no "
			"need to remove (fini = %d, cp = %p)\n", t,
			fini, cp);
		else
			(void) fprintf(stderr, "tid= %d: no "
			"need to remove (fini = %d, cp = %p, shared = %d)\n",
			t, fini, cp, cp->shared);
		fflush(stderr);
#endif /* DEBUG */
		if (use_lock)
			(void) rw_unlock(&sessionPoolLock);
		return;
	}

	if (!fini &&
		((flag & NS_LDAP_NEW_CONN) == 0) && !cp->notAvail &&
		((flag & NS_LDAP_KEEP_CONN) ||
			(MTperConn == 0 && nscd_proc()) ||
			MTperConn)) {
#ifdef DEBUG
		(void) fprintf(stderr, "tid= %d: keep alive (fini = %d "
			"shared = %d)\n", t, fini, cp->shared);
#endif /* DEBUG */
		/* release Connection (keep alive) */
		if (cp->shared)
			cp->shared--;
		cp->usedBit = B_FALSE;
		cp->threadID = 0;	/* unmark the threadID */
		if (use_lock)
			(void) rw_unlock(&sessionPoolLock);
	} else {
		/* delete Connection (disconnect) */
		if (cp->shared > 0) {
#ifdef DEBUG
		(void) fprintf(stderr, "tid= %d: Connection no "
			"longer available (fini = %d, shared = %d)\n",
			t, fini, cp->shared);
		fflush(stderr);
#endif /* DEBUG */
			cp->shared--;
			cp->notAvail = 1;
		}

		if (cp->shared <= 0) {
#ifdef DEBUG
			(void) fprintf(stderr, "tid= %d: unbind "
				"(fini = %d, shared = %d)\n",
				t, fini, cp->shared);
			fflush(stderr);
#endif /* DEBUG */
			sessionPool[id] = NULL;
			(void) ldap_unbind(cp->ld);
			freeConnection(cp);
		}

		if (use_lock)
			(void) rw_unlock(&sessionPoolLock);
	}
}

void
DropConnection(ConnectionID cID, int flag)
{
	_DropConnection(cID, flag, 0);
}

/*
 * This routine is called after a bind operation is
 * done in openConnection() to process the password
 * management information, if any.
 *
 * Input:
 *   bind_type: "simple" or "sasl/DIGEST-MD5"
 *   ldaprc   : ldap rc from the ldap bind operation
 *   controls : controls returned by the server
 *   errmsg   : error message from the server
 *   fail_if_new_pwd_reqd:
 *              flag indicating if connection should be open
 *              when password needs to change immediately
 *   passwd_mgmt:
 *              flag indicating if server supports password
 *              policy/management
 *
 * Output     : ns_ldap_error structure, which may contain
 *              password status and number of seconds until
 *              expired
 *
 * return rc:
 * NS_LDAP_EXTERNAL: error, connection should not open
 * NS_LDAP_SUCCESS_WITH_INFO: OK to open but password info attached
 * NS_LDAP_SUCCESS: OK to open connection
 *
 */

static int
process_pwd_mgmt(char *bind_type, int ldaprc,
		LDAPControl **controls,
		char *errmsg, ns_ldap_error_t **errorp,
		int fail_if_new_pwd_reqd,
		int passwd_mgmt)
{
	char		errstr[MAXERROR];
	LDAPControl	**ctrl = NULL;
	int		exit_rc;
	ns_ldap_passwd_status_t	pwd_status = NS_PASSWD_GOOD;
	int		sec_until_exp = 0;

	/*
	 * errmsg may be an empty string,
	 * even if ldaprc is LDAP_SUCCESS,
	 * free the empty string if that's the case
	 */
	if (errmsg &&
		(*errmsg == '\0' || ldaprc == LDAP_SUCCESS)) {
		ldap_memfree(errmsg);
		errmsg = NULL;
	}

	if (ldaprc != LDAP_SUCCESS) {
		/*
		 * try to map ldap rc and error message to
		 * a password status
		 */
		if (errmsg) {
			if (passwd_mgmt)
				pwd_status =
					__s_api_set_passwd_status(
					ldaprc, errmsg);
			ldap_memfree(errmsg);
		}

		(void) snprintf(errstr, sizeof (errstr),
			gettext("openConnection: "
			"%s bind failed "
			"- %s"), bind_type, ldap_err2string(ldaprc));

		if (pwd_status != NS_PASSWD_GOOD) {
			MKERROR_PWD_MGMT(*errorp,
				ldaprc, strdup(errstr),
				pwd_status, 0, NULL);
		} else {
			MKERROR(LOG_ERR, *errorp, ldaprc, strdup(errstr),
				NULL);
		}
		if (controls)
			ldap_controls_free(controls);

		return (NS_LDAP_INTERNAL);
	}

	/*
	 * ldaprc is LDAP_SUCCESS,
	 * process the password management controls, if any
	 */
	exit_rc = NS_LDAP_SUCCESS;
	if (controls && passwd_mgmt) {
		/*
		 * The control with the OID
		 * 2.16.840.1.113730.3.4.4 (or
		 * LDAP_CONTROL_PWEXPIRED, as defined
		 * in the ldap.h header file) is the
		 * expired password control.
		 *
		 * This control is used if the server
		 * is configured to require users to
		 * change their passwords when first
		 * logging in and whenever the
		 * passwords are reset.
		 *
		 * If the user is logging in for the
		 * first time or if the user's
		 * password has been reset, the
		 * server sends this control to
		 * indicate that the client needs to
		 * change the password immediately.
		 *
		 * At this point, the only operation
		 * that the client can perform is to
		 * change the user's password. If the
		 * client requests any other LDAP
		 * operation, the server sends back
		 * an LDAP_UNWILLING_TO_PERFORM
		 * result code with an expired
		 * password control.
		 *
		 * The control with the OID
		 * 2.16.840.1.113730.3.4.5 (or
		 * LDAP_CONTROL_PWEXPIRING, as
		 * defined in the ldap.h header file)
		 * is the password expiration warning
		 * control.
		 *
		 * This control is used if the server
		 * is configured to expire user
		 * passwords after a certain amount
		 * of time.
		 *
		 * The server sends this control back
		 * to the client if the client binds
		 * using a password that will soon
		 * expire.  The ldctl_value field of
		 * the LDAPControl structure
		 * specifies the number of seconds
		 * before the password will expire.
		 */
		for (ctrl = controls; *ctrl; ctrl++) {

			if (strcmp((*ctrl)->ldctl_oid,
				LDAP_CONTROL_PWEXPIRED) == 0) {
				/*
				 * if the caller wants this bind
				 * to fail, set up the error info.
				 * If call to this function is
				 * for searching the LDAP directory,
				 * e.g., __ns_ldap_list(),
				 * there's really no sense to
				 * let a connection open and
				 * then fail immediately afterward
				 * on the LDAP search operation with
				 * the LDAP_UNWILLING_TO_PERFORM rc
				 */
				pwd_status =
					NS_PASSWD_CHANGE_NEEDED;
				if (fail_if_new_pwd_reqd) {
					(void) snprintf(errstr,
						sizeof (errstr),
						gettext(
						"openConnection: "
						"%s bind "
						"failed "
						"- password "
						"expired. It "
						" needs to change "
						"immediately!"),
						bind_type);
					MKERROR_PWD_MGMT(*errorp,
						LDAP_SUCCESS,
						strdup(errstr),
						pwd_status,
						0,
						NULL);
					exit_rc = NS_LDAP_INTERNAL;
				} else {
					MKERROR_PWD_MGMT(*errorp,
						LDAP_SUCCESS,
						NULL,
						pwd_status,
						0,
						NULL);
					exit_rc =
					NS_LDAP_SUCCESS_WITH_INFO;
				}
				break;
			} else if (strcmp((*ctrl)->ldctl_oid,
				LDAP_CONTROL_PWEXPIRING) == 0) {
				pwd_status =
					NS_PASSWD_ABOUT_TO_EXPIRE;
				if ((*ctrl)->
					ldctl_value.bv_len > 0 &&
					(*ctrl)->
						ldctl_value.bv_val)
					sec_until_exp =
						atoi((*ctrl)->
						ldctl_value.bv_val);
				MKERROR_PWD_MGMT(*errorp,
					LDAP_SUCCESS,
					NULL,
					pwd_status,
					sec_until_exp,
					NULL);
				exit_rc =
					NS_LDAP_SUCCESS_WITH_INFO;
				break;
			}
		}
	}

	if (controls)
		ldap_controls_free(controls);

	return (exit_rc);
}

static int
ldap_in_hosts_switch()
{
	enum __nsw_parse_err		pserr;
	struct __nsw_switchconfig	*conf;
	struct __nsw_lookup		*lkp;
	const char			*name;
	int				found = 0;

	conf = __nsw_getconfig("hosts", &pserr);
	if (conf == NULL) {
		return (-1);
	}

	/* check for skip and count other backends */
	for (lkp = conf->lookups; lkp != NULL; lkp = lkp->next) {
		name = lkp->service_name;
		if (strcmp(name, "ldap") == 0) {
			found = 1;
			break;
		}
	}
	__nsw_freeconfig(conf);
	return (found);
}

static int
openConnection(LDAP **ldp, const char *serverAddr, const ns_cred_t *auth,
	int timeoutSec, ns_ldap_error_t **errorp,
	int fail_if_new_pwd_reqd, int passwd_mgmt)
{
	LDAP		*ld = NULL;
	char		*binddn, *passwd;
	char		*digest_md5_name;
	const char	*s;
	int		ldapVersion = LDAP_VERSION3;
	int		derefOption = LDAP_DEREF_ALWAYS;
	int		zero = 0;
	int		rc;
	char		errstr[MAXERROR];
	int		errnum = 0;
	LDAPMessage	*resultMsg;
	int		msgId;
	int		useSSL = 0, port = 0;
	struct timeval	tv;
	AuthType_t	bindType;
	int		timeoutMilliSec = timeoutSec * 1000;
	struct berval	cred;
	char		*sslServerAddr;
	char		*s1;
	char		*errmsg, *end = NULL;
	LDAPControl	**controls;
	int		pwd_rc, min_ssf = MIN_SASL_SSF, max_ssf = MAX_SASL_SSF;
	ns_sasl_cb_param_t	sasl_param;

	*errorp = NULL;
	*ldp = NULL;

	switch (auth->auth.type) {
		case NS_LDAP_AUTH_NONE:
		case NS_LDAP_AUTH_SIMPLE:
		case NS_LDAP_AUTH_SASL:
			bindType = auth->auth.type;
			break;
		case NS_LDAP_AUTH_TLS:
			useSSL = 1;
			switch (auth->auth.tlstype) {
				case NS_LDAP_TLS_NONE:
					bindType = NS_LDAP_AUTH_NONE;
					break;
				case NS_LDAP_TLS_SIMPLE:
					bindType = NS_LDAP_AUTH_SIMPLE;
					break;
				case NS_LDAP_TLS_SASL:
					bindType = NS_LDAP_AUTH_SASL;
					break;
				default:
					(void) sprintf(errstr,
					gettext("openConnection: unsupported "
						"TLS authentication method "
						"(%d)"), auth->auth.tlstype);
					MKERROR(LOG_WARNING, *errorp,
						LDAP_AUTH_METHOD_NOT_SUPPORTED,
						strdup(errstr), NULL);
					return (NS_LDAP_INTERNAL);
			}
			break;
		default:
			(void) sprintf(errstr,
				gettext("openConnection: unsupported "
				"authentication method (%d)"), auth->auth.type);
			MKERROR(LOG_WARNING, *errorp,
				LDAP_AUTH_METHOD_NOT_SUPPORTED, strdup(errstr),
				NULL);
			return (NS_LDAP_INTERNAL);
	}

	if (useSSL) {
		const char	*hostcertpath;
		char		*alloc_hcp = NULL;
#ifdef DEBUG
		(void) fprintf(stderr, "tid= %d: +++TLS transport\n",
			thr_self());
#endif /* DEBUG */

		if (prldap_set_session_option(NULL, NULL,
		    PRLDAP_OPT_IO_MAX_TIMEOUT,
		    timeoutMilliSec) != LDAP_SUCCESS) {
			(void) snprintf(errstr, sizeof (errstr),
				gettext("openConnection: failed to initialize "
				"TLS security"));
			MKERROR(LOG_WARNING, *errorp, LDAP_CONNECT_ERROR,
				strdup(errstr), NULL);
			return (NS_LDAP_INTERNAL);
		}

		hostcertpath = auth->hostcertpath;
		if (hostcertpath == NULL) {
			alloc_hcp = __s_get_hostcertpath();
			hostcertpath = alloc_hcp;
		}

		if (hostcertpath == NULL)
			return (NS_LDAP_MEMORY);

		if ((rc = ldapssl_client_init(hostcertpath, NULL)) < 0) {
			if (alloc_hcp)
				free(alloc_hcp);
			(void) snprintf(errstr, sizeof (errstr),
				gettext("openConnection: failed to initialize "
				"TLS security (%s)"),
				ldapssl_err2string(rc));
			MKERROR(LOG_WARNING, *errorp, LDAP_CONNECT_ERROR,
				strdup(errstr), NULL);
			return (NS_LDAP_INTERNAL);
		}
		if (alloc_hcp)
			free(alloc_hcp);

		/* determine if the host name contains a port number */
		s = strchr(serverAddr, ']');	/* skip over ipv6 addr */
		if (s == NULL)
			s = serverAddr;
		s = strchr(s, ':');
		if (s != NULL) {
			/*
			 * If we do get a port number, we will try stripping
			 * it. At present, referrals will always have a
			 * port number.
			 */
			sslServerAddr = strdup(serverAddr);
			if (sslServerAddr == NULL)
				return (NS_LDAP_MEMORY);
			s1 = strrchr(sslServerAddr, ':');
			if (s1 != NULL)
				*s1 = '\0';
			(void) snprintf(errstr, sizeof (errstr),
			    gettext("openConnection: cannot use tls with %s. "
				"Trying %s"),
				serverAddr, sslServerAddr);
			syslog(LOG_ERR, "libsldap: %s", errstr);
		} else
			sslServerAddr = (char *)serverAddr;

		ld = ldapssl_init(sslServerAddr, LDAPS_PORT, 1);

		if (sslServerAddr != serverAddr)
			free(sslServerAddr);

		if (ld == NULL ||
		    ldapssl_install_gethostbyaddr(ld, "ldap") != 0) {
			(void) snprintf(errstr, sizeof (errstr),
				gettext("openConnection: failed to connect "
				"using TLS (%s)"), strerror(errno));
			MKERROR(LOG_WARNING, *errorp, LDAP_CONNECT_ERROR,
				strdup(errstr), NULL);
			return (NS_LDAP_INTERNAL);
		}
	} else {
#ifdef DEBUG
		(void) fprintf(stderr, "tid= %d: +++Unsecure transport\n",
				thr_self());
#endif /* DEBUG */
		port = LDAP_PORT;
		if (auth->auth.saslmech == NS_LDAP_SASL_GSSAPI &&
			(end = strchr(serverAddr, ':')) != NULL) {
			/*
			 * The IP is converted to hostname so it's a
			 * hostname:port up to this point.
			 *
			 * libldap passes hostname:port to the sasl layer.
			 * The ldap service principal is constructed as
			 * ldap/hostname:port@REALM. Kerberos authentication
			 * will fail. So it needs to be parsed to construct
			 * a valid principal ldap/hostname@REALM.
			 *
			 * For useSSL case above, it already parses port so
			 * no need to parse serverAddr
			 */
			*end = '\0';
			port = atoi(end + 1);
		}

		/* Warning message IF cannot connect to host(s) */
		if ((ld = ldap_init((char *)serverAddr, port)) == NULL) {
			char *p = strerror(errno);
			MKERROR(LOG_WARNING, *errorp, LDAP_CONNECT_ERROR,
				strdup(p), NULL);
			if (end)
				*end = ':';
			return (NS_LDAP_INTERNAL);
		} else {
			if (end)
				*end = ':';
			/* check and avoid gethostname recursion */
			if (ldap_in_hosts_switch() > 0 &&
				! __s_api_isipv4((char *)serverAddr) &&
				! __s_api_isipv6((char *)serverAddr)) {
				/* host: ldap - found, attempt to recover */
				if (ldap_set_option(ld, LDAP_X_OPT_DNS_SKIPDB,
						    "ldap") != 0) {
				    (void) snprintf(errstr, sizeof (errstr),
					    gettext("openConnection: "
					    "unrecoverable gethostname "
					    "recursion detected "
					    "in /etc/nsswitch.conf"));
				    MKERROR(LOG_WARNING, *errorp,
					    LDAP_CONNECT_ERROR,
					    strdup(errstr), NULL);
				    (void) ldap_unbind(ld);
				    return (NS_LDAP_INTERNAL);
				}
			}
		}
	}

	ns_setup_mt_conn_and_tsd(ld);
	(void) ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &ldapVersion);
	(void) ldap_set_option(ld, LDAP_OPT_DEREF, &derefOption);
	/*
	 * set LDAP_OPT_REFERRALS to OFF.
	 * This library will handle the referral itself
	 * based on API flags or configuration file
	 * specification. If this option is not set
	 * to OFF, libldap will never pass the
	 * referral info up to this library
	 */
	(void) ldap_set_option(ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF);
	(void) ldap_set_option(ld, LDAP_OPT_TIMELIMIT, &zero);
	(void) ldap_set_option(ld, LDAP_OPT_SIZELIMIT, &zero);
	/* setup TCP/IP connect timeout */
	(void) ldap_set_option(ld, LDAP_X_OPT_CONNECT_TIMEOUT,
							&timeoutMilliSec);
	/* retry if LDAP I/O was interrupted */
	(void) ldap_set_option(ld, LDAP_OPT_RESTART, LDAP_OPT_ON);

	switch (bindType) {
	case NS_LDAP_AUTH_NONE:
#ifdef DEBUG
		(void) fprintf(stderr, "tid= %d: +++Anonymous bind\n",
			thr_self());
#endif /* DEBUG */
		break;
	case NS_LDAP_AUTH_SIMPLE:
		binddn = auth->cred.unix_cred.userID;
		passwd = auth->cred.unix_cred.passwd;
		if (passwd == NULL || *passwd == '\0' ||
		    binddn == NULL || *binddn == '\0') {
			(void) sprintf(errstr, gettext("openConnection: "
				"missing credentials for Simple bind"));
			MKERROR(LOG_WARNING, *errorp, LDAP_INVALID_CREDENTIALS,
				strdup(errstr), NULL);
			(void) ldap_unbind(ld);
			return (NS_LDAP_INTERNAL);
		}

#ifdef DEBUG
		(void) fprintf(stderr, "tid= %d: +++Simple bind\n",
			thr_self());
#endif /* DEBUG */
		msgId = ldap_simple_bind(ld, binddn, passwd);

		if (msgId == -1) {
			(void) ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER,
				(void *)&errnum);
			(void) snprintf(errstr, sizeof (errstr),
				gettext("openConnection: simple bind failed "
				"- %s"), ldap_err2string(errnum));
			(void) ldap_unbind(ld);
			MKERROR(LOG_WARNING, *errorp, errnum, strdup(errstr),
				NULL);
			return (NS_LDAP_INTERNAL);
		}

		tv.tv_sec = timeoutSec;
		tv.tv_usec = 0;
		rc = ldap_result(ld, msgId, 0, &tv, &resultMsg);

		if ((rc == -1) || (rc == 0)) {
			(void) ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER,
				(void *)&errnum);
			(void) snprintf(errstr, sizeof (errstr),
				gettext("openConnection: simple bind failed "
				"- %s"), ldap_err2string(errnum));
			(void) ldap_msgfree(resultMsg);
			(void) ldap_unbind(ld);
			MKERROR(LOG_WARNING, *errorp, errnum, strdup(errstr),
				NULL);
			return (NS_LDAP_INTERNAL);
		}

		/*
		 * get ldaprc, controls, and error msg
		 */
		rc = ldap_parse_result(ld, resultMsg, &errnum, NULL,
				&errmsg, NULL, &controls, 1);

		if (rc != LDAP_SUCCESS) {
			(void) snprintf(errstr, sizeof (errstr),
				gettext("openConnection: simple bind failed "
				"- unable to parse result"));
			(void) ldap_unbind(ld);
			MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL,
					strdup(errstr), NULL);
			return (NS_LDAP_INTERNAL);
		}

		/* process the password management info, if any */
		pwd_rc = process_pwd_mgmt("simple",
					errnum, controls, errmsg,
					errorp,
					fail_if_new_pwd_reqd,
					passwd_mgmt);

		if (pwd_rc == NS_LDAP_INTERNAL) {
			(void) ldap_unbind(ld);
			return (pwd_rc);
		}

		if (pwd_rc == NS_LDAP_SUCCESS_WITH_INFO) {
			*ldp = ld;
			return (pwd_rc);
		}

		break;
	case NS_LDAP_AUTH_SASL:
		if (auth->auth.saslopt != NS_LDAP_SASLOPT_NONE &&
				auth->auth.saslmech != NS_LDAP_SASL_GSSAPI) {
			(void) sprintf(errstr,
				gettext("openConnection: SASL options are "
				"not supported (%d) for non-GSSAPI sasl bind"),
				auth->auth.saslopt);
			MKERROR(LOG_WARNING, *errorp,
				LDAP_AUTH_METHOD_NOT_SUPPORTED,
				strdup(errstr), NULL);
			(void) ldap_unbind(ld);
			return (NS_LDAP_INTERNAL);
		}
		if (auth->auth.saslmech != NS_LDAP_SASL_GSSAPI) {
			binddn = auth->cred.unix_cred.userID;
			passwd = auth->cred.unix_cred.passwd;
			if (passwd == NULL || *passwd == '\0' ||
				binddn == NULL || *binddn == '\0') {
				(void) sprintf(errstr,
				gettext("openConnection: missing credentials "
				"for SASL bind"));
				MKERROR(LOG_WARNING, *errorp,
					LDAP_INVALID_CREDENTIALS,
					strdup(errstr), NULL);
				(void) ldap_unbind(ld);
				return (NS_LDAP_INTERNAL);
			}
			cred.bv_val = passwd;
			cred.bv_len = strlen(passwd);
		}

		switch (auth->auth.saslmech) {
		case NS_LDAP_SASL_CRAM_MD5:
			/*
			 * NOTE: if iDS changes to support cram_md5,
			 * please add password management code here.
			 * Since ldap_sasl_cram_md5_bind_s does not
			 * return anything that could be used to
			 * extract the ldap rc/errmsg/control to
			 * determine if bind failed due to password
			 * policy, a new cram_md5_bind API will need
			 * to be introduced. See
			 * ldap_x_sasl_digest_md5_bind() and case
			 * NS_LDAP_SASL_DIGEST_MD5 below for details.
			 */
			if ((rc = ldap_sasl_cram_md5_bind_s(ld, binddn,
				&cred, NULL, NULL)) != LDAP_SUCCESS) {
				(void) ldap_get_option(ld,
					LDAP_OPT_ERROR_NUMBER, (void *)&errnum);
				(void) snprintf(errstr, sizeof (errstr),
					gettext("openConnection: "
					"sasl/CRAM-MD5 bind failed - %s"),
					ldap_err2string(errnum));
				MKERROR(LOG_WARNING, *errorp, errnum,
					strdup(errstr), NULL);
				(void) ldap_unbind(ld);
				return (NS_LDAP_INTERNAL);
			}
			break;
		case NS_LDAP_SASL_DIGEST_MD5:
			digest_md5_name = malloc(strlen(binddn) + 5);
			/* 5 = strlen("dn: ") + 1 */
			if (digest_md5_name == NULL) {
				(void) ldap_unbind(ld);
				return (NS_LDAP_MEMORY);
			}
			(void) strcpy(digest_md5_name, "dn: ");
			(void) strcat(digest_md5_name, binddn);

			tv.tv_sec = timeoutSec;
			tv.tv_usec = 0;
			rc = ldap_x_sasl_digest_md5_bind(ld,
				digest_md5_name, &cred, NULL, NULL,
				&tv, &resultMsg);

			if (resultMsg == NULL) {
				free(digest_md5_name);
				(void) ldap_get_option(ld,
					LDAP_OPT_ERROR_NUMBER, (void *)&errnum);
				(void) snprintf(errstr, sizeof (errstr),
					gettext("openConnection: "
					"DIGEST-MD5 bind failed - %s"),
					ldap_err2string(errnum));
				(void) ldap_unbind(ld);
				MKERROR(LOG_WARNING, *errorp, errnum,
						strdup(errstr), NULL);
				return (NS_LDAP_INTERNAL);
			}

			/*
			 * get ldaprc, controls, and error msg
			 */
			rc = ldap_parse_result(ld, resultMsg, &errnum, NULL,
				&errmsg, NULL, &controls, 1);

			if (rc != LDAP_SUCCESS) {
				free(digest_md5_name);
				(void) snprintf(errstr, sizeof (errstr),
					gettext("openConnection: "
					"DIGEST-MD5 bind failed "
					"- unable to parse result"));
				(void) ldap_unbind(ld);
				MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL,
						strdup(errstr), NULL);
				return (NS_LDAP_INTERNAL);
			}

			/* process the password management info, if any */
			pwd_rc = process_pwd_mgmt("sasl/DIGEST-MD5",
						errnum, controls, errmsg,
						errorp,
						fail_if_new_pwd_reqd,
						passwd_mgmt);

			if (pwd_rc == NS_LDAP_INTERNAL) {
				free(digest_md5_name);
				(void) ldap_unbind(ld);
				return (pwd_rc);
			}

			if (pwd_rc == NS_LDAP_SUCCESS_WITH_INFO) {
				*ldp = ld;
				return (pwd_rc);
			}

			free(digest_md5_name);
			break;
		case NS_LDAP_SASL_GSSAPI:
			if (sasl_gssapi_inited == 0) {
				rc = __s_api_sasl_gssapi_init();
				if (rc != NS_LDAP_SUCCESS) {
					(void) snprintf(errstr, sizeof (errstr),
						gettext("openConnection: "
						"GSSAPI initialization "
						"failed"));
					(void) ldap_unbind(ld);
					MKERROR(LOG_WARNING, *errorp, rc,
						strdup(errstr), NULL);
					return (rc);
				}
			}
			(void) memset(&sasl_param, 0,
					sizeof (ns_sasl_cb_param_t));
			sasl_param.authid = NULL;
			sasl_param.authzid = "";
			(void) ldap_set_option(ld, LDAP_OPT_X_SASL_SSF_MIN,
						(void *)&min_ssf);
			(void) ldap_set_option(ld, LDAP_OPT_X_SASL_SSF_MAX,
						(void *)&max_ssf);

			rc = ldap_sasl_interactive_bind_s(
				ld, NULL, "GSSAPI",
				NULL, NULL, LDAP_SASL_INTERACTIVE,
				__s_api_sasl_bind_callback,
				&sasl_param);

			if (rc != LDAP_SUCCESS) {
				(void) snprintf(errstr, sizeof (errstr),
					gettext("openConnection: "
					"GSSAPI bind failed "
					"- %d %s"), rc, ldap_err2string(rc));
				(void) ldap_unbind(ld);
				MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL,
						strdup(errstr), NULL);
				return (NS_LDAP_INTERNAL);
			}

			break;
		default:
			(void) ldap_unbind(ld);
			(void) sprintf(errstr,
				gettext("openConnection: unsupported SASL "
				"mechanism (%d)"), auth->auth.saslmech);
			MKERROR(LOG_WARNING, *errorp,
				LDAP_AUTH_METHOD_NOT_SUPPORTED, strdup(errstr),
				NULL);
			return (NS_LDAP_INTERNAL);
		}
	}

	*ldp = ld;
	return (NS_LDAP_SUCCESS);
}

/*
 * FUNCTION:	__s_api_getDefaultAuth
 *
 *	Constructs a credential for authentication using the config module.
 *
 * RETURN VALUES:
 *
 * NS_LDAP_SUCCESS	If successful
 * NS_LDAP_CONFIG	If there are any config errors.
 * NS_LDAP_MEMORY	Memory errors.
 * NS_LDAP_OP_FAILED	If there are no more authentication methods so can
 *			not build a new authp.
 * NS_LDAP_INVALID_PARAM This overloaded return value means that some of the
 *			necessary fields of a cred for a given auth method
 *			are not provided.
 * INPUT:
 *
 * cLevel	Currently requested credential level to be tried
 *
 * aMethod	Currently requested authentication method to be tried
 *
 * OUTPUT:
 *
 * authp		authentication method to use.
 */
static int
__s_api_getDefaultAuth(
	int	*cLevel,
	ns_auth_t *aMethod,
	ns_cred_t **authp)
{
	void		**paramVal = NULL;
	char		*modparamVal = NULL;
	int		getUid = 0;
	int		getPasswd = 0;
	int		getCertpath = 0;
	int		rc = 0;
	ns_ldap_error_t	*errorp = NULL;

#ifdef DEBUG
	(void) fprintf(stderr, "__s_api_getDefaultAuth START\n");
#endif

	if (aMethod == NULL) {
		/* Require an Auth */
		return (NS_LDAP_INVALID_PARAM);

	}
	/*
	 * credential level "self" can work with auth method sasl/GSSAPI only
	 */
	if (cLevel && *cLevel == NS_LDAP_CRED_SELF &&
			aMethod->saslmech != NS_LDAP_SASL_GSSAPI)
		return (NS_LDAP_INVALID_PARAM);

	*authp = (ns_cred_t *)calloc(1, sizeof (ns_cred_t));
	if ((*authp) == NULL)
		return (NS_LDAP_MEMORY);

	(*authp)->auth = *aMethod;

	switch (aMethod->type) {
		case NS_LDAP_AUTH_NONE:
			return (NS_LDAP_SUCCESS);
		case NS_LDAP_AUTH_SIMPLE:
			getUid++;
			getPasswd++;
			break;
		case NS_LDAP_AUTH_SASL:
			if ((aMethod->saslmech == NS_LDAP_SASL_DIGEST_MD5) ||
			    (aMethod->saslmech == NS_LDAP_SASL_CRAM_MD5)) {
				getUid++;
				getPasswd++;
			} else if (aMethod->saslmech != NS_LDAP_SASL_GSSAPI) {
				(void) __ns_ldap_freeCred(authp);
				*authp = NULL;
				return (NS_LDAP_INVALID_PARAM);
			}
			break;
		case NS_LDAP_AUTH_TLS:
			if ((aMethod->tlstype == NS_LDAP_TLS_SIMPLE) ||
			    ((aMethod->tlstype == NS_LDAP_TLS_SASL) &&
			    ((aMethod->saslmech == NS_LDAP_SASL_DIGEST_MD5) ||
			    (aMethod->saslmech == NS_LDAP_SASL_CRAM_MD5)))) {
				getUid++;
				getPasswd++;
				getCertpath++;
			} else if (aMethod->tlstype == NS_LDAP_TLS_NONE) {
				getCertpath++;
			} else {
				(void) __ns_ldap_freeCred(authp);
				*authp = NULL;
				return (NS_LDAP_INVALID_PARAM);
			}
			break;
	}

	if (getUid) {
		paramVal = NULL;
		if ((rc = __ns_ldap_getParam(NS_LDAP_BINDDN_P,
			&paramVal, &errorp)) != NS_LDAP_SUCCESS) {
			(void) __ns_ldap_freeCred(authp);
			(void) __ns_ldap_freeError(&errorp);
			*authp = NULL;
			return (rc);
		}

		if (paramVal == NULL || *paramVal == NULL) {
			(void) __ns_ldap_freeCred(authp);
			*authp = NULL;
			return (NS_LDAP_INVALID_PARAM);
		}

		(*authp)->cred.unix_cred.userID = strdup((char *)*paramVal);
		(void) __ns_ldap_freeParam(&paramVal);
		if ((*authp)->cred.unix_cred.userID == NULL) {
			(void) __ns_ldap_freeCred(authp);
			*authp = NULL;
			return (NS_LDAP_MEMORY);
		}
	}
	if (getPasswd) {
		paramVal = NULL;
		if ((rc = __ns_ldap_getParam(NS_LDAP_BINDPASSWD_P,
			&paramVal, &errorp)) != NS_LDAP_SUCCESS) {
			(void) __ns_ldap_freeCred(authp);
			(void) __ns_ldap_freeError(&errorp);
			*authp = NULL;
			return (rc);
		}

		if (paramVal == NULL || *paramVal == NULL) {
			(void) __ns_ldap_freeCred(authp);
			*authp = NULL;
			return (NS_LDAP_INVALID_PARAM);
		}

		modparamVal = dvalue((char *)*paramVal);
		(void) __ns_ldap_freeParam(&paramVal);
		if (modparamVal == NULL || (strlen((char *)modparamVal) == 0)) {
			(void) __ns_ldap_freeCred(authp);
			if (modparamVal != NULL)
				free(modparamVal);
			*authp = NULL;
			return (NS_LDAP_INVALID_PARAM);
		}

		(*authp)->cred.unix_cred.passwd = modparamVal;
	}
	if (getCertpath) {
		paramVal = NULL;
		if ((rc = __ns_ldap_getParam(NS_LDAP_HOST_CERTPATH_P,
			&paramVal, &errorp)) != NS_LDAP_SUCCESS) {
			(void) __ns_ldap_freeCred(authp);
			(void) __ns_ldap_freeError(&errorp);
			*authp = NULL;
			return (rc);
		}

		if (paramVal == NULL || *paramVal == NULL) {
			(void) __ns_ldap_freeCred(authp);
			*authp = NULL;
			return (NS_LDAP_INVALID_PARAM);
		}

		(*authp)->hostcertpath = strdup((char *)*paramVal);
		(void) __ns_ldap_freeParam(&paramVal);
		if ((*authp)->hostcertpath == NULL) {
			(void) __ns_ldap_freeCred(authp);
			*authp = NULL;
			return (NS_LDAP_MEMORY);
		}
	}
	return (NS_LDAP_SUCCESS);
}

/*
 * FUNCTION:	__s_api_getConnection
 *
 *	Bind to the specified server or one from the server
 *	list and return the pointer.
 *
 *	This function can rebind or not (NS_LDAP_HARD), it can require a
 *	credential or bind anonymously
 *
 *	This function follows the DUA configuration schema algorithm
 *
 * RETURN VALUES:
 *
 * NS_LDAP_SUCCESS	A connection was made successfully.
 * NS_LDAP_SUCCESS_WITH_INFO
 * 			A connection was made successfully, but with
 *			password management info in *errorp
 * NS_LDAP_INVALID_PARAM If any invalid arguments were passed to the function.
 * NS_LDAP_CONFIG	If there are any config errors.
 * NS_LDAP_MEMORY	Memory errors.
 * NS_LDAP_INTERNAL	If there was a ldap error.
 *
 * INPUT:
 *
 * server	Bind to this LDAP server only
 * flags	If NS_LDAP_HARD is set function will not return until it has
 *		a connection unless there is a authentication problem.
 *		If NS_LDAP_NEW_CONN is set the function must force a new
 *              connection to be created
 *		If NS_LDAP_KEEP_CONN is set the connection is to be kept open
 * auth		Credentials for bind. This could be NULL in which case
 *		a default cred built from the config module is used.
 * sessionId	cookie that points to a previous session
 * fail_if_new_pwd_reqd
 *		a flag indicating this function should fail if the passwd
 *		in auth needs to change immediately
 * nopasswd_acct_mgmt
 *		a flag indicating that makeConnection should check before
 *		binding if server supports LDAP V3 password less
 *		account management
 *
 * OUTPUT:
 *
 * session	pointer to a session with connection information
 * errorp	Set if there are any INTERNAL, or CONFIG error.
 */
int
__s_api_getConnection(
	const char *server,
	const int flags,
	const ns_cred_t *cred,		/* credentials for bind */
	ConnectionID *sessionId,
	Connection **session,
	ns_ldap_error_t **errorp,
	int fail_if_new_pwd_reqd,
	int nopasswd_acct_mgmt)
{
	char		errmsg[MAXERROR];
	ns_auth_t	**aMethod = NULL;
	ns_auth_t	**aNext = NULL;
	int		**cLevel = NULL;
	int		**cNext = NULL;
	int		timeoutSec = NS_DEFAULT_BIND_TIMEOUT;
	int		rc;
	Connection	*con = NULL;
	int		sec = 1;
	ns_cred_t 	*authp = NULL;
	ns_cred_t	anon;
	int		version = NS_LDAP_V2, self_gssapi_only = 0;
	void		**paramVal = NULL;
	char		**badSrvrs = NULL; /* List of problem hostnames */

	if ((session == NULL) || (sessionId == NULL)) {
		return (NS_LDAP_INVALID_PARAM);
	}
	*session = NULL;

	/* if we already have a session id try to reuse connection */
	if (*sessionId > 0) {
		rc = findConnectionById(flags, cred, *sessionId, &con);
		if (rc == *sessionId && con) {
			*session = con;
			return (NS_LDAP_SUCCESS);
		}
		*sessionId = 0;
	}

	/* get profile version number */
	if ((rc = __ns_ldap_getParam(NS_LDAP_FILE_VERSION_P,
			&paramVal, errorp)) != NS_LDAP_SUCCESS)
		return (rc);
	if (paramVal == NULL) {
		(void) sprintf(errmsg, gettext("getConnection: no file "
			"version"));
		MKERROR(LOG_WARNING, *errorp, NS_CONFIG_FILE, strdup(errmsg),
			NS_LDAP_CONFIG);
		return (NS_LDAP_CONFIG);
	}
	if (strcasecmp((char *)*paramVal, NS_LDAP_VERSION_1) == 0)
		version = NS_LDAP_V1;
	(void) __ns_ldap_freeParam((void ***)&paramVal);

	/* Get the bind timeout value */
	(void) __ns_ldap_getParam(NS_LDAP_BIND_TIME_P, &paramVal, errorp);
	if (paramVal != NULL && *paramVal != NULL) {
		timeoutSec = **((int **)paramVal);
		(void) __ns_ldap_freeParam(&paramVal);
	}
	if (*errorp)
		(void) __ns_ldap_freeError(errorp);

	if (cred == NULL) {
		/* Get the authentication method list */
		if ((rc = __ns_ldap_getParam(NS_LDAP_AUTH_P,
			(void ***)&aMethod, errorp)) != NS_LDAP_SUCCESS)
			return (rc);
		if (aMethod == NULL) {
			aMethod = (ns_auth_t **)calloc(2, sizeof (ns_auth_t *));
			if (aMethod == NULL)
				return (NS_LDAP_MEMORY);
			aMethod[0] = (ns_auth_t *)calloc(1, sizeof (ns_auth_t));
			if (aMethod[0] == NULL) {
				free(aMethod);
				return (NS_LDAP_MEMORY);
			}
			if (version == NS_LDAP_V1)
				(aMethod[0])->type = NS_LDAP_AUTH_SIMPLE;
			else {
				(aMethod[0])->type = NS_LDAP_AUTH_SASL;
				(aMethod[0])->saslmech =
					NS_LDAP_SASL_DIGEST_MD5;
				(aMethod[0])->saslopt = NS_LDAP_SASLOPT_NONE;
			}
		}

		/* Get the credential level list */
		if ((rc = __ns_ldap_getParam(NS_LDAP_CREDENTIAL_LEVEL_P,
			(void ***)&cLevel, errorp)) != NS_LDAP_SUCCESS) {
			(void) __ns_ldap_freeParam((void ***)&aMethod);
			return (rc);
		}
		if (cLevel == NULL) {
			cLevel = (int **)calloc(2, sizeof (int *));
			if (cLevel == NULL)
				return (NS_LDAP_MEMORY);
			cLevel[0] = (int *)calloc(1, sizeof (int));
			if (cLevel[0] == NULL)
				return (NS_LDAP_MEMORY);
			if (version == NS_LDAP_V1)
				*(cLevel[0]) = NS_LDAP_CRED_PROXY;
			else
				*(cLevel[0]) = NS_LDAP_CRED_ANON;
		}
	}

	/* setup the anon credential for anonymous connection */
	(void) memset(&anon, 0, sizeof (ns_cred_t));
	anon.auth.type = NS_LDAP_AUTH_NONE;

	for (; ; ) {
		if (cred != NULL) {
			/* using specified auth method */
			rc = makeConnection(&con, server, cred,
				sessionId, timeoutSec, errorp,
				fail_if_new_pwd_reqd,
				nopasswd_acct_mgmt, flags, &badSrvrs);
			if (rc == NS_LDAP_SUCCESS ||
				rc == NS_LDAP_SUCCESS_WITH_INFO) {
				*session = con;
				break;
			}
		} else {
			self_gssapi_only = __s_api_self_gssapi_only_get();
			/* for every cred level */
			for (cNext = cLevel; *cNext != NULL; cNext++) {
				if (self_gssapi_only &&
					**cNext != NS_LDAP_CRED_SELF)
					continue;
				if (**cNext == NS_LDAP_CRED_ANON) {
					/*
					 * make connection anonymously
					 * Free the down server list before
					 * looping through
					 */
					if (badSrvrs && *badSrvrs) {
						__s_api_free2dArray(badSrvrs);
						badSrvrs = NULL;
					}
					rc = makeConnection(&con, server, &anon,
						sessionId, timeoutSec, errorp,
						fail_if_new_pwd_reqd,
						nopasswd_acct_mgmt, flags,
						&badSrvrs);
					if (rc == NS_LDAP_SUCCESS ||
						rc ==
						NS_LDAP_SUCCESS_WITH_INFO) {
						*session = con;
						goto done;
					}
					continue;
				}
				/* for each cred level */
				for (aNext = aMethod; *aNext != NULL; aNext++) {
					if (self_gssapi_only &&
						(*aNext)->saslmech !=
						NS_LDAP_SASL_GSSAPI)
						continue;
					/*
					 * self coexists with sasl/GSSAPI only
					 * and non-self coexists with non-gssapi
					 * only
					 */
					if ((**cNext == NS_LDAP_CRED_SELF &&
						(*aNext)->saslmech !=
						NS_LDAP_SASL_GSSAPI) ||
						(**cNext != NS_LDAP_CRED_SELF &&
						(*aNext)->saslmech ==
						NS_LDAP_SASL_GSSAPI))
						continue;
					/* make connection and authenticate */
					/* with default credentials */
					authp = NULL;
					rc = __s_api_getDefaultAuth(*cNext,
						*aNext, &authp);
					if (rc != NS_LDAP_SUCCESS) {
						continue;
					}
					/*
					 * Free the down server list before
					 * looping through
					 */
					if (badSrvrs && *badSrvrs) {
						__s_api_free2dArray(badSrvrs);
						badSrvrs = NULL;
					}
					rc = makeConnection(&con, server, authp,
						sessionId, timeoutSec, errorp,
						fail_if_new_pwd_reqd,
						nopasswd_acct_mgmt, flags,
						&badSrvrs);
					(void) __ns_ldap_freeCred(&authp);
					if (rc == NS_LDAP_SUCCESS ||
						rc ==
						NS_LDAP_SUCCESS_WITH_INFO) {
						*session = con;
						goto done;
					}
				}
			}
		}
		if (flags & NS_LDAP_HARD) {
			if (sec < LDAPMAXHARDLOOKUPTIME)
				sec *= 2;
			_sleep(sec);
		} else {
			break;
		}
	}

done:
	/*
	 * If unable to get a connection, and this is
	 * the thread opening the shared connection,
	 * unlock the session mutex and let other
	 * threads try to get their own connection.
	 */
	if (wait4session != 0 && sessionTid == thr_self()) {
		wait4session = 0;
		sessionTid = 0;
#ifdef DEBUG
		(void) fprintf(stderr, "tid= %d: __s_api_getConnection: "
			"unlocking sessionLock \n", thr_self());
		fflush(stderr);
#endif /* DEBUG */
		(void) mutex_unlock(&sessionLock);
	}
	if (self_gssapi_only && rc == NS_LDAP_SUCCESS && *session == NULL) {
		/*
		 * self_gssapi_only is true but no self/sasl/gssapi is
		 * configured
		 */
		rc = NS_LDAP_CONFIG;
	}

	(void) __ns_ldap_freeParam((void ***)&aMethod);
	(void) __ns_ldap_freeParam((void ***)&cLevel);

	if (badSrvrs && *badSrvrs) {
		/*
		 * At this point, either we have a successful
		 * connection or exhausted all the possible auths.
		 * and creds. Mark the problem servers as down
		 * so that the problem servers are not contacted
		 * again until the refresh_ttl expires.
		 */
		(void) __s_api_removeBadServers(badSrvrs);
		__s_api_free2dArray(badSrvrs);
	}
	return (rc);
}

#pragma fini(_free_sessionPool)
static void
_free_sessionPool()
{
	int id;

	(void) rw_wrlock(&sessionPoolLock);
	if (sessionPool != NULL) {
		for (id = 0; id < sessionPoolSize; id++)
			_DropConnection(id + CONID_OFFSET, 0, 1);
		free(sessionPool);
		sessionPool = NULL;
		sessionPoolSize = 0;
	}
	(void) rw_unlock(&sessionPoolLock);
}