xref: /illumos-gate/usr/src/lib/libsldap/common/ns_connect.c (revision ca9327a6de44d69ddab3668cc1e143ce781387a3)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <errno.h>
31 #include <string.h>
32 #include <synch.h>
33 #include <time.h>
34 #include <libintl.h>
35 #include <thread.h>
36 #include <syslog.h>
37 #include <sys/mman.h>
38 #include <nsswitch.h>
39 #include <nss_dbdefs.h>
40 #include "solaris-priv.h"
41 #include "solaris-int.h"
42 #include "ns_sldap.h"
43 #include "ns_internal.h"
44 #include "ns_cache_door.h"
45 #include "ldappr.h"
46 #include <sys/stat.h>
47 #include <fcntl.h>
48 #include <procfs.h>
49 #include <unistd.h>
50 
51 extern unsigned int _sleep(unsigned int);
52 extern int ldap_sasl_cram_md5_bind_s(LDAP *, char *, struct berval *,
53 		LDAPControl **, LDAPControl **);
54 extern int ldapssl_install_gethostbyaddr(LDAP *ld, const char *skip);
55 
56 static int openConnection(LDAP **, const char *, const ns_cred_t *,
57 		int, ns_ldap_error_t **, int, int);
58 static void
59 _DropConnection(ConnectionID cID, int flag, int fini);
60 /*
61  * sessionLock, wait4session, sessionTid
62  * are variables to synchronize the creation/retrieval of a connection.
63  * MTperCon is a flag to enable/disable multiple threads sharing the same
64  * connection.
65  * sessionPoolLock is a mutex lock for the connection pool.
66  * sharedConnNumber is the number of sharable connections in the pool.
67  * sharedConnNumberLock is a mutex for sharedConnNumber.
68  */
69 static mutex_t	sessionLock = DEFAULTMUTEX;
70 static int	wait4session = 0;
71 static thread_t sessionTid = 0;
72 int	MTperConn = 1;
73 static rwlock_t sessionPoolLock = DEFAULTRWLOCK;
74 
75 static Connection **sessionPool = NULL;
76 static int sessionPoolSize = 0;
77 static int sharedConnNumber = 0;
78 static mutex_t sharedConnNumberLock = DEFAULTMUTEX;
79 
80 static int check_nscd_proc(pid_t pid, boolean_t check_uid);
81 
82 /*
83  * SSF values are for SASL integrity & privacy.
84  * JES DS5.2 does not support this feature but DS6 does.
85  * The values between 0 and 65535 can work with both server versions.
86  */
87 #define	MAX_SASL_SSF	65535
88 #define	MIN_SASL_SSF	0
89 
90 /* Number of hostnames to allocate memory for */
91 #define	NUMTOMALLOC	32
92 /*
93  * ns_mtckey is for sharing a ldap connection among multiple
94  * threads; created by ns_ldap_init() in ns_init.c
95  */
96 extern thread_key_t ns_mtckey;
97 
98 /* Per thread LDAP error resides in thread-specific data. */
99 struct ldap_error {
100 	int	le_errno;
101 	char	*le_matched;
102 	char	*le_errmsg;
103 };
104 
105 static struct ldap_error ldap_error_NULL = { LDAP_SUCCESS, NULL, NULL};
106 
107 /* destructor */
108 void
109 ns_tsd_cleanup(void *key) {
110 	struct ldap_error *le = (struct ldap_error *)key;
111 
112 	if (le == NULL)
113 		return;
114 	if (le->le_matched != NULL) {
115 		ldap_memfree(le->le_matched);
116 	}
117 	if (le->le_errmsg != NULL) {
118 		ldap_memfree(le->le_errmsg);
119 	}
120 	free(le);
121 }
122 
123 /* Callback function for allocating a mutex */
124 static void *
125 ns_mutex_alloc(void)
126 {
127 	mutex_t *mutexp = NULL;
128 
129 	if ((mutexp = malloc(sizeof (mutex_t))) != NULL) {
130 		if (mutex_init(mutexp, USYNC_THREAD, NULL) != 0) {
131 			free(mutexp);
132 			mutexp = NULL;
133 		}
134 	}
135 	return (mutexp);
136 }
137 
138 /* Callback function for freeing a mutex */
139 static void
140 ns_mutex_free(void *mutexp)
141 {
142 	(void) mutex_destroy((mutex_t *)mutexp);
143 	free(mutexp);
144 }
145 
146 /*
147  * Function for setting up thread-specific data
148  * where per thread LDAP error is stored
149  */
150 static int
151 tsd_setup()
152 {
153 	void	*tsd;
154 	int	rc;
155 
156 	/* return success if TSD already set */
157 	rc = thr_getspecific(ns_mtckey, &tsd);
158 	if (rc == 0 && tsd != NULL)
159 		return (0);
160 
161 	/* allocate and set TSD */
162 	tsd = (void *) calloc(1, sizeof (struct ldap_error));
163 	if (tsd == NULL)
164 		return (-1);
165 	rc = thr_setspecific(ns_mtckey, tsd);
166 	if (rc != 0) { /* must be ENOMEM */
167 		free(tsd);
168 		return (-1);
169 	}
170 	return (0);
171 
172 
173 }
174 
175 /* Callback function for setting the per thread LDAP error */
176 /*ARGSUSED*/
177 static void
178 set_ld_error(int err, char *matched, char *errmsg, void *dummy)
179 {
180 	struct ldap_error	*le;
181 
182 	if (thr_getspecific(ns_mtckey, (void **)&le) != 0) {
183 		syslog(LOG_ERR, "set_ld_error: thr_getspecific failed. errno"
184 		    " %d", errno);
185 		return;
186 	}
187 
188 	/* play safe, do nothing if TSD pointer is NULL */
189 	if (le == NULL)
190 		return;
191 
192 	le->le_errno = err;
193 	if (le->le_matched != NULL) {
194 		ldap_memfree(le->le_matched);
195 	}
196 	le->le_matched = matched;
197 	if (le->le_errmsg != NULL) {
198 		ldap_memfree(le->le_errmsg);
199 	}
200 	le->le_errmsg = errmsg;
201 }
202 
203 int
204 /* check and allocate the thread-specific data for using a shared connection */
205 __s_api_check_MTC_tsd()
206 {
207 	if (tsd_setup() != 0)
208 		return (NS_LDAP_MEMORY);
209 
210 	return (NS_LDAP_SUCCESS);
211 }
212 
213 /* Callback function for getting the per thread LDAP error */
214 /*ARGSUSED*/
215 static int
216 get_ld_error(char **matched, char **errmsg, void *dummy)
217 {
218 	struct ldap_error	*le;
219 
220 	if (thr_getspecific(ns_mtckey, (void **)&le) != 0) {
221 		syslog(LOG_ERR, "get_ld_error: thr_getspecific failed. errno"
222 		    " %d", errno);
223 		return (errno);
224 	}
225 
226 	/* play safe, return NULL error data, if TSD pointer is NULL */
227 	if (le == NULL)
228 		le = &ldap_error_NULL;
229 
230 	if (matched != NULL) {
231 		*matched = le->le_matched;
232 	}
233 	if (errmsg != NULL) {
234 		*errmsg = le->le_errmsg;
235 	}
236 	return (le->le_errno);
237 }
238 
239 /* Callback function for setting per thread errno */
240 static void
241 set_errno(int err)
242 {
243 	errno = err;
244 }
245 
246 /* Callback function for getting per thread errno */
247 static int
248 get_errno(void)
249 {
250 	return (errno);
251 }
252 
253 /*
254  * set up to allow multiple threads to use the same ldap connection
255  */
256 static int
257 setup_mt_conn(LDAP *ld)
258 {
259 
260 	struct ldap_thread_fns		tfns;
261 	struct ldap_extra_thread_fns	extrafns;
262 	int				rc;
263 
264 	/*
265 	 * Set the function pointers for dealing with mutexes
266 	 * and error information
267 	 */
268 	(void) memset(&tfns, '\0', sizeof (struct ldap_thread_fns));
269 	tfns.ltf_mutex_alloc = (void *(*)(void)) ns_mutex_alloc;
270 	tfns.ltf_mutex_free = (void (*)(void *)) ns_mutex_free;
271 	tfns.ltf_mutex_lock = (int (*)(void *)) mutex_lock;
272 	tfns.ltf_mutex_unlock = (int (*)(void *)) mutex_unlock;
273 	tfns.ltf_get_errno = get_errno;
274 	tfns.ltf_set_errno = set_errno;
275 	tfns.ltf_get_lderrno = get_ld_error;
276 	tfns.ltf_set_lderrno = set_ld_error;
277 	tfns.ltf_lderrno_arg = NULL;
278 
279 	/*
280 	 * Set up this session to use those function pointers
281 	 */
282 	rc = ldap_set_option(ld, LDAP_OPT_THREAD_FN_PTRS,
283 	    (void *) &tfns);
284 	if (rc < 0) {
285 		syslog(LOG_WARNING, "libsldap: ldap_set_option "
286 		"(LDAP_OPT_THREAD_FN_PTRS)");
287 		return (-1);
288 	}
289 
290 	/*
291 	 * Set the function pointers for working with semaphores
292 	 */
293 	(void) memset(&extrafns, '\0',
294 	    sizeof (struct ldap_extra_thread_fns));
295 	extrafns.ltf_threadid_fn = (void * (*)(void))thr_self;
296 	extrafns.ltf_mutex_trylock = NULL;
297 	extrafns.ltf_sema_alloc = NULL;
298 	extrafns.ltf_sema_free = NULL;
299 	extrafns.ltf_sema_wait = NULL;
300 	extrafns.ltf_sema_post = NULL;
301 
302 	/* Set up this session to use those function pointers */
303 	rc = ldap_set_option(ld, LDAP_OPT_EXTRA_THREAD_FN_PTRS,
304 	    (void *) &extrafns);
305 	if (rc < 0) {
306 		syslog(LOG_WARNING, "libsldap: ldap_set_option "
307 		"(LDAP_OPT_EXTRA_THREAD_FN_PTRS)");
308 		return (-1);
309 	}
310 
311 	return (0);
312 }
313 
314 static void
315 ns_setup_mt_conn_and_tsd(LDAP *ld) {
316 	thread_t t = thr_self();
317 	void *tsd;
318 	/* set up to share this connection among threads */
319 	if (MTperConn == 1) {
320 		if (tsd_setup() == -1) {
321 			syslog(LOG_ERR, "tid= %d: unable "
322 				"to set up TSD\n", t);
323 		} else {
324 			if (setup_mt_conn(ld) == -1) {
325 			/* multiple threads per connection not supported */
326 				syslog(LOG_ERR, "tid= %d: multiple "
327 					"threads per connection not "
328 					"supported\n", t);
329 				(void) thr_getspecific(ns_mtckey, &tsd);
330 				ns_tsd_cleanup(tsd);
331 				(void) thr_setspecific(ns_mtckey, NULL);
332 				MTperConn = 0;
333 			}
334 		}
335 	}
336 }
337 
338 /*
339  * Check name and UID of process, if it is nscd.
340  *
341  * Input:
342  *   pid	: PID of checked process
343  *   check_uid	: check if UID == 0
344  * Output:
345  *   1	: nscd detected
346  *   0	: nscd not confirmed
347  */
348 static int
349 check_nscd_proc(pid_t pid, boolean_t check_uid)
350 {
351 	psinfo_t	pinfo;
352 	char		fname[MAXPATHLEN];
353 	ssize_t		ret;
354 	int		fd;
355 
356 	if (snprintf(fname, MAXPATHLEN, "/proc/%d/psinfo", pid) > 0) {
357 		if ((fd = open(fname,  O_RDONLY)) >= 0) {
358 			ret = read(fd, &pinfo, sizeof (psinfo_t));
359 			(void) close(fd);
360 			if ((ret == sizeof (psinfo_t)) &&
361 			    (strcmp(pinfo.pr_fname, "nscd") == 0)) {
362 				if (check_uid && (pinfo.pr_uid != 0))
363 					return (0);
364 				return (1);
365 			}
366 		}
367 	}
368 	return (0);
369 }
370 
371 /*
372  * Check if this process is peruser nscd.
373  */
374 int
375 __s_api_peruser_proc(void)
376 {
377 	pid_t		my_ppid;
378 	static mutex_t	nscdLock = DEFAULTMUTEX;
379 	static pid_t	checkedPpid = (pid_t)-1;
380 	static int	isPeruserNscd = 0;
381 
382 	my_ppid = getppid();
383 
384 	/*
385 	 * Already checked before for this process? If yes, return cached
386 	 * response.
387 	 */
388 	if (my_ppid == checkedPpid) {
389 		return (isPeruserNscd);
390 	}
391 
392 	(void) mutex_lock(&nscdLock);
393 
394 	/* Check once more incase another thread has just complete this. */
395 	if (my_ppid == checkedPpid) {
396 		(void) mutex_unlock(&nscdLock);
397 		return (isPeruserNscd);
398 	}
399 
400 	/* Reinitialize to be sure there is no residue after fork. */
401 	isPeruserNscd = 0;
402 
403 	/* Am I the nscd process? */
404 	if (check_nscd_proc(getpid(), B_FALSE)) {
405 		/* Is my parent the nscd process with UID == 0. */
406 		isPeruserNscd = check_nscd_proc(my_ppid, B_TRUE);
407 	}
408 
409 	/* Remeber for whom isPeruserNscd is. */
410 	checkedPpid = my_ppid;
411 
412 	(void) mutex_unlock(&nscdLock);
413 	return (isPeruserNscd);
414 }
415 
416 /*
417  * Check if this process is main nscd.
418  */
419 int
420 __s_api_nscd_proc(void)
421 {
422 	pid_t		my_pid;
423 	static mutex_t	nscdLock = DEFAULTMUTEX;
424 	static pid_t	checkedPid = (pid_t)-1;
425 	static int	isMainNscd = 0;
426 
427 	/*
428 	 * Don't bother checking if this process isn't root, this cannot
429 	 * be main nscd.
430 	 */
431 	if (getuid() != 0)
432 		return (0);
433 
434 	my_pid = getpid();
435 
436 	/*
437 	 * Already checked before for this process? If yes, return cached
438 	 * response.
439 	 */
440 	if (my_pid == checkedPid) {
441 		return (isMainNscd);
442 	}
443 
444 	(void) mutex_lock(&nscdLock);
445 
446 	/* Check once more incase another thread has just done this. */
447 	if (my_pid == checkedPid) {
448 		(void) mutex_unlock(&nscdLock);
449 		return (isMainNscd);
450 	}
451 
452 	/*
453 	 * Am I the nscd process? UID is already checked, not needed from
454 	 * psinfo.
455 	 */
456 	isMainNscd = check_nscd_proc(my_pid, B_FALSE);
457 
458 	/* Remeber for whom isMainNscd is. */
459 	checkedPid = my_pid;
460 
461 	(void) mutex_unlock(&nscdLock);
462 	return (isMainNscd);
463 }
464 
465 /*
466  * This function requests a server from the cache manager through
467  * the door functionality
468  */
469 
470 static int
471 __s_api_requestServer(const char *request, const char *server,
472 	ns_server_info_t *ret, ns_ldap_error_t **error,  const char *addrType)
473 {
474 	union {
475 		ldap_data_t	s_d;
476 		char		s_b[DOORBUFFERSIZE];
477 	} space;
478 	ldap_data_t	*sptr;
479 	int		ndata;
480 	int		adata;
481 	char		errstr[MAXERROR];
482 	const char	*ireq;
483 	char		*rbuf, *ptr, *rest;
484 	char		*dptr;
485 	char		**mptr, **mptr1, **cptr, **cptr1;
486 	int		mcnt, ccnt;
487 	char		**servers;
488 	int		rc, len;
489 
490 	if (ret == NULL || error == NULL) {
491 		return (NS_LDAP_OP_FAILED);
492 	}
493 	(void) memset(ret, 0, sizeof (ns_server_info_t));
494 	*error = NULL;
495 
496 	(void) memset(space.s_b, 0, DOORBUFFERSIZE);
497 
498 	if (request == NULL)
499 		ireq = NS_CACHE_NEW;
500 	else
501 		ireq = request;
502 
503 	adata = (sizeof (ldap_call_t) + strlen(ireq) + strlen(addrType) + 1);
504 	if (server != NULL) {
505 		adata += strlen(DOORLINESEP) + 1;
506 		adata += strlen(server) + 1;
507 	}
508 	ndata = sizeof (space);
509 	len = sizeof (space) - sizeof (space.s_d.ldap_call.ldap_callnumber);
510 	space.s_d.ldap_call.ldap_callnumber = GETLDAPSERVER;
511 	if (strlcpy(space.s_d.ldap_call.ldap_u.domainname, ireq, len) >= len)
512 		return (NS_LDAP_MEMORY);
513 	if (strlcat(space.s_d.ldap_call.ldap_u.domainname, addrType, len) >=
514 	    len)
515 		return (NS_LDAP_MEMORY);
516 	if (server != NULL) {
517 		if (strlcat(space.s_d.ldap_call.ldap_u.domainname,
518 		    DOORLINESEP, len) >= len)
519 			return (NS_LDAP_MEMORY);
520 		if (strlcat(space.s_d.ldap_call.ldap_u.domainname, server,
521 		    len) >= len)
522 			return (NS_LDAP_MEMORY);
523 	}
524 	sptr = &space.s_d;
525 
526 	switch (__ns_ldap_trydoorcall(&sptr, &ndata, &adata)) {
527 	case SUCCESS:
528 		break;
529 	/* this case is for when the $mgr is not running, but ldapclient */
530 	/* is trying to initialize things */
531 	case NOSERVER:
532 		/* get first server from config list unavailable otherwise */
533 		servers = NULL;
534 		rc = __s_api_getServers(&servers, error);
535 		if (rc != NS_LDAP_SUCCESS) {
536 			if (servers != NULL) {
537 				__s_api_free2dArray(servers);
538 				servers = NULL;
539 			}
540 			return (rc);
541 		}
542 		if (servers == NULL || servers[0] == NULL) {
543 			__s_api_free2dArray(servers);
544 			servers = NULL;
545 			(void) sprintf(errstr,
546 			    gettext("No server found in configuration"));
547 			MKERROR(LOG_ERR, *error, NS_CONFIG_NODEFAULT,
548 			    strdup(errstr), NULL);
549 			return (NS_LDAP_CONFIG);
550 		}
551 		ret->server = strdup(servers[0]);
552 		if (ret->server == NULL) {
553 			__s_api_free2dArray(servers);
554 			return (NS_LDAP_MEMORY);
555 		}
556 		ret->saslMechanisms = NULL;
557 		ret->controls = NULL;
558 		__s_api_free2dArray(servers);
559 		servers = NULL;
560 		return (NS_LDAP_SUCCESS);
561 	case NOTFOUND:
562 	default:
563 		return (NS_LDAP_OP_FAILED);
564 	}
565 
566 	/* copy info from door call return structure here */
567 	rbuf =  space.s_d.ldap_ret.ldap_u.config;
568 
569 	/* Get the host */
570 	ptr = strtok_r(rbuf, DOORLINESEP, &rest);
571 	if (ptr == NULL) {
572 		(void) sprintf(errstr, gettext("No server returned from "
573 		    "ldap_cachemgr"));
574 		MKERROR(LOG_WARNING, *error, NS_CONFIG_CACHEMGR,
575 		    strdup(errstr), NULL);
576 		return (NS_LDAP_OP_FAILED);
577 	}
578 	ret->server = strdup(ptr);
579 	if (ret->server == NULL) {
580 		return (NS_LDAP_MEMORY);
581 	}
582 	/* Get the host FQDN format */
583 	if (strcmp(addrType, NS_CACHE_ADDR_HOSTNAME) == 0) {
584 		ptr = strtok_r(NULL, DOORLINESEP, &rest);
585 		if (ptr == NULL) {
586 			(void) sprintf(errstr, gettext("No server FQDN format "
587 			    "returned from ldap_cachemgr"));
588 			MKERROR(LOG_WARNING, *error, NS_CONFIG_CACHEMGR,
589 			    strdup(errstr), NULL);
590 			free(ret->server);
591 			ret->server = NULL;
592 			return (NS_LDAP_OP_FAILED);
593 		}
594 		ret->serverFQDN = strdup(ptr);
595 		if (ret->serverFQDN == NULL) {
596 			free(ret->server);
597 			ret->server = NULL;
598 			return (NS_LDAP_MEMORY);
599 		}
600 	}
601 
602 	/* get the Supported Controls/SASL mechs */
603 	mptr = NULL;
604 	mcnt = 0;
605 	cptr = NULL;
606 	ccnt = 0;
607 	for (; ; ) {
608 		ptr = strtok_r(NULL, DOORLINESEP, &rest);
609 		if (ptr == NULL)
610 			break;
611 		if (strncasecmp(ptr, _SASLMECHANISM,
612 		    _SASLMECHANISM_LEN) == 0) {
613 			dptr = strchr(ptr, '=');
614 			if (dptr == NULL)
615 				continue;
616 			dptr++;
617 			mptr1 = (char **)realloc((void *)mptr,
618 			    sizeof (char *) * (mcnt+2));
619 			if (mptr1 == NULL) {
620 				__s_api_free2dArray(mptr);
621 				if (sptr != &space.s_d) {
622 					(void) munmap((char *)sptr, ndata);
623 				}
624 				__s_api_free2dArray(cptr);
625 				__s_api_free_server_info(ret);
626 				return (NS_LDAP_MEMORY);
627 			}
628 			mptr = mptr1;
629 			mptr[mcnt] = strdup(dptr);
630 			if (mptr[mcnt] == NULL) {
631 				if (sptr != &space.s_d) {
632 					(void) munmap((char *)sptr, ndata);
633 				}
634 				__s_api_free2dArray(cptr);
635 				cptr = NULL;
636 				__s_api_free2dArray(mptr);
637 				mptr = NULL;
638 				__s_api_free_server_info(ret);
639 				return (NS_LDAP_MEMORY);
640 			}
641 			mcnt++;
642 			mptr[mcnt] = NULL;
643 		}
644 		if (strncasecmp(ptr, _SUPPORTEDCONTROL,
645 		    _SUPPORTEDCONTROL_LEN) == 0) {
646 			dptr = strchr(ptr, '=');
647 			if (dptr == NULL)
648 				continue;
649 			dptr++;
650 			cptr1 = (char **)realloc((void *)cptr,
651 			    sizeof (char *) * (ccnt+2));
652 			if (cptr1 == NULL) {
653 				if (sptr != &space.s_d) {
654 					(void) munmap((char *)sptr, ndata);
655 				}
656 				__s_api_free2dArray(cptr);
657 				__s_api_free2dArray(mptr);
658 				mptr = NULL;
659 				__s_api_free_server_info(ret);
660 				return (NS_LDAP_MEMORY);
661 			}
662 			cptr = cptr1;
663 			cptr[ccnt] = strdup(dptr);
664 			if (cptr[ccnt] == NULL) {
665 				if (sptr != &space.s_d) {
666 					(void) munmap((char *)sptr, ndata);
667 				}
668 				__s_api_free2dArray(cptr);
669 				cptr = NULL;
670 				__s_api_free2dArray(mptr);
671 				mptr = NULL;
672 				__s_api_free_server_info(ret);
673 				return (NS_LDAP_MEMORY);
674 			}
675 			ccnt++;
676 			cptr[ccnt] = NULL;
677 		}
678 	}
679 	if (mptr != NULL) {
680 		ret->saslMechanisms = mptr;
681 	}
682 	if (cptr != NULL) {
683 		ret->controls = cptr;
684 	}
685 
686 
687 	/* clean up door call */
688 	if (sptr != &space.s_d) {
689 		(void) munmap((char *)sptr, ndata);
690 	}
691 	*error = NULL;
692 
693 	return (NS_LDAP_SUCCESS);
694 }
695 
696 
697 /*
698  * printCred(): prints the credential structure
699  */
700 static void
701 printCred(int pri, const ns_cred_t *cred)
702 {
703 	thread_t	t = thr_self();
704 
705 	if (cred == NULL) {
706 		syslog(LOG_ERR, "tid= %d: printCred: cred is NULL\n", t);
707 		return;
708 	}
709 
710 	syslog(pri, "tid= %d: AuthType=%d", t, cred->auth.type);
711 	syslog(pri, "tid= %d: TlsType=%d", t, cred->auth.tlstype);
712 	syslog(pri, "tid= %d: SaslMech=%d", t, cred->auth.saslmech);
713 	syslog(pri, "tid= %d: SaslOpt=%d", t, cred->auth.saslopt);
714 	if (cred->hostcertpath)
715 		syslog(pri, "tid= %d: hostCertPath=%s\n",
716 		    t, cred->hostcertpath);
717 	if (cred->cred.unix_cred.userID)
718 		syslog(pri, "tid= %d: userID=%s\n",
719 		    t, cred->cred.unix_cred.userID);
720 #ifdef DEBUG
721 	if (cred->cred.unix_cred.passwd)
722 		syslog(pri, "tid= %d: passwd=%s\n",
723 		    t, cred->cred.unix_cred.passwd);
724 #endif
725 }
726 
727 /*
728  * printConnection(): prints the connection structure
729  */
730 static void
731 printConnection(int pri, Connection *con)
732 {
733 	thread_t	t = thr_self();
734 
735 	if (con == NULL)
736 		return;
737 
738 	syslog(pri, "tid= %d: connectionID=%d\n", t, con->connectionId);
739 	syslog(pri, "tid= %d: shared=%d\n", t, con->shared);
740 	syslog(pri, "tid= %d: usedBit=%d\n", t, con->usedBit);
741 	syslog(pri, "tid= %d: threadID=%d\n", t, con->threadID);
742 	if (con->serverAddr) {
743 		syslog(pri, "tid= %d: serverAddr=%s\n",
744 		    t, con->serverAddr);
745 	}
746 	printCred(pri, con->auth);
747 }
748 
749 
750 
751 /*
752  * addConnection(): set up a connection so that it can be shared
753  * among multiple threads and then insert the connection in the
754  * connection list.
755  * Returns: -1 = failure, new Connection ID = success
756  *
757  * This function could exit with sessionLock locked. It will be
758  * be unlocked in __s_api_getConnection() when it exits without getting a
759  * connection.
760  */
761 static int
762 addConnection(Connection *con)
763 {
764 	int i, noMTperC = 0;
765 	thread_t t = thr_self();
766 	struct ldap_thread_fns tfns;
767 	void *tsd;
768 
769 	if (!con)
770 		return (-1);
771 
772 	syslog(LOG_DEBUG, "tid= %d: Adding connection (serverAddr=%s)",
773 	    t, con->serverAddr);
774 
775 	if (MTperConn == 1) {
776 		/*
777 		 * Make sure ld has proper thread functions and tsd
778 		 * is set up.
779 		 */
780 		(void) memset(&tfns, 0, sizeof (struct ldap_thread_fns));
781 		/*
782 		 * ldap_init sets ltf_get_lderrno and ltf_set_lderrno to NULLs.
783 		 * It's supposed to be overwritten by ns_setup_mt_conn_and_tsd.
784 		 */
785 		if (ldap_get_option(con->ld, LDAP_OPT_THREAD_FN_PTRS,
786 		    (void *)&tfns) != 0 ||
787 		    tfns.ltf_get_lderrno != get_ld_error ||
788 		    tfns.ltf_set_lderrno != set_ld_error) {
789 			MTperConn = 0;
790 			noMTperC = 1;
791 		} else {
792 			if (thr_getspecific(ns_mtckey, &tsd) != 0 ||
793 			    tsd == NULL)
794 				noMTperC = 1;
795 		}
796 
797 	} else {
798 		noMTperC = 1;
799 	}
800 
801 	(void) rw_wrlock(&sessionPoolLock);
802 	if (sessionPool == NULL) {
803 		sessionPoolSize = SESSION_CACHE_INC;
804 		sessionPool = calloc(sessionPoolSize,
805 		    sizeof (struct connection **));
806 		if (!sessionPool) {
807 			(void) rw_unlock(&sessionPoolLock);
808 			return (-1);
809 		}
810 
811 		syslog(LOG_DEBUG, "tid= %d: Initialized sessionPool", t);
812 	}
813 	for (i = 0; (i < sessionPoolSize) && (sessionPool[i] != NULL); ++i)
814 		;
815 	if (i == sessionPoolSize) {
816 		/* run out of array, need to increase sessionPool */
817 		Connection **cl;
818 		cl = (Connection **) realloc(sessionPool,
819 		    (sessionPoolSize + SESSION_CACHE_INC) *
820 		    sizeof (Connection *));
821 		if (!cl) {
822 			(void) rw_unlock(&sessionPoolLock);
823 			return (-1);
824 		}
825 		(void) memset(cl + sessionPoolSize, 0,
826 		    SESSION_CACHE_INC * sizeof (struct connection *));
827 		sessionPool = cl;
828 		sessionPoolSize += SESSION_CACHE_INC;
829 		syslog(LOG_DEBUG, "tid: %d: Increased "
830 		    "sessionPoolSize to: %d\n",
831 		    t, sessionPoolSize);
832 	}
833 	sessionPool[i] = con;
834 	if (noMTperC == 0) {
835 		con->shared++;
836 		con->pid = getpid();
837 		(void) mutex_lock(&sharedConnNumberLock);
838 		sharedConnNumber++;
839 		(void) mutex_unlock(&sharedConnNumberLock);
840 	} else
841 		con->usedBit = B_TRUE;
842 
843 	(void) rw_unlock(&sessionPoolLock);
844 
845 	con->connectionId = i + CONID_OFFSET;
846 
847 	syslog(LOG_DEBUG, "tid= %d: Connection added [%d]\n",
848 	    t, i);
849 	printConnection(LOG_DEBUG, con);
850 
851 	/*
852 	 * A connection can be shared now, unlock
853 	 * the session mutex and let other
854 	 * threads try to use this connection or
855 	 * get their own.
856 	 */
857 	if (wait4session != 0 && sessionTid == thr_self()) {
858 		wait4session = 0;
859 		sessionTid = 0;
860 		syslog(LOG_DEBUG, "tid= %d: unlocking sessionLock\n", t);
861 		(void) mutex_unlock(&sessionLock);
862 	}
863 
864 	return (i + CONID_OFFSET);
865 }
866 
867 /*
868  * See if the specified session matches a currently available
869  */
870 
871 static int
872 findConnectionById(int flags, const ns_cred_t *auth, ConnectionID cID,
873 	Connection **conp)
874 {
875 	Connection *cp;
876 	int id;
877 
878 	if ((conp == NULL) || (auth == NULL) || cID < CONID_OFFSET)
879 		return (-1);
880 
881 	/*
882 	 * If a new connection is requested, no need to continue.
883 	 * If the process is not nscd and is not requesting keep connections
884 	 * alive, no need to continue.
885 	 */
886 	if ((flags & NS_LDAP_NEW_CONN) || (!__s_api_nscd_proc() &&
887 	    !__s_api_peruser_proc() && !(flags & NS_LDAP_KEEP_CONN)))
888 		return (-1);
889 
890 	*conp = NULL;
891 	if (sessionPool == NULL)
892 		return (-1);
893 	id = cID - CONID_OFFSET;
894 	if (id < 0 || id >= sessionPoolSize)
895 		return (-1);
896 
897 	(void) rw_rdlock(&sessionPoolLock);
898 	if (sessionPool[id] == NULL) {
899 		(void) rw_unlock(&sessionPoolLock);
900 		return (-1);
901 	}
902 	cp = sessionPool[id];
903 
904 	/*
905 	 * Make sure the connection has the same type of authentication method
906 	 */
907 	if ((cp->usedBit) ||
908 	    (cp->notAvail) ||
909 	    (cp->auth->auth.type != auth->auth.type) ||
910 	    (cp->auth->auth.tlstype != auth->auth.tlstype) ||
911 	    (cp->auth->auth.saslmech != auth->auth.saslmech) ||
912 	    (cp->auth->auth.saslopt != auth->auth.saslopt)) {
913 		(void) rw_unlock(&sessionPoolLock);
914 		return (-1);
915 	}
916 	if ((((cp->auth->auth.type == NS_LDAP_AUTH_SASL) &&
917 	    ((cp->auth->auth.saslmech == NS_LDAP_SASL_CRAM_MD5) ||
918 	    (cp->auth->auth.saslmech == NS_LDAP_SASL_DIGEST_MD5))) ||
919 	    (cp->auth->auth.type == NS_LDAP_AUTH_SIMPLE)) &&
920 	    ((cp->auth->cred.unix_cred.userID == NULL) ||
921 	    (strcasecmp(cp->auth->cred.unix_cred.userID,
922 	    auth->cred.unix_cred.userID) != 0))) {
923 		(void) rw_unlock(&sessionPoolLock);
924 		return (-1);
925 	}
926 
927 	/* An existing connection is found but it needs to be reset */
928 	if (flags & NS_LDAP_NEW_CONN) {
929 		(void) rw_unlock(&sessionPoolLock);
930 		DropConnection(cID, 0);
931 		return (-1);
932 	}
933 	/* found an available connection */
934 	cp->usedBit = B_TRUE;
935 	(void) rw_unlock(&sessionPoolLock);
936 	cp->threadID = thr_self();
937 	*conp = cp;
938 	return (cID);
939 }
940 
941 /*
942  * findConnection(): find an available connection from the list
943  * that matches the criteria specified in Connection structure.
944  * If serverAddr is NULL, then find a connection to any server
945  * as long as it matches the rest of the parameters.
946  * Returns: -1 = failure, the Connection ID found = success.
947  *
948  * This function could exit with sessionLock locked. It will be
949  * be unlocked in addConnection() when this thread adds the connection
950  * to the pool or in __s_api_getConnection() when it exits without getting a
951  * connection.
952  */
953 #define	TRY_TIMES	10
954 static int
955 findConnection(int flags, const char *serverAddr,
956 	const ns_cred_t *auth, Connection **conp)
957 {
958 	Connection *cp;
959 	int i, j, conn_server_index, up_server_index, drop_conn;
960 	int rc;
961 	int try;
962 	ns_server_info_t sinfo;
963 	ns_ldap_error_t *errorp = NULL;
964 	char **servers;
965 	void **paramVal = NULL;
966 #ifdef DEBUG
967 	thread_t t = thr_self();
968 #endif /* DEBUG */
969 
970 	if (auth == NULL || conp == NULL)
971 		return (-1);
972 	*conp = NULL;
973 
974 	/*
975 	 * If a new connection is requested, no need to continue.
976 	 * If the process is not nscd and is not requesting keep connections
977 	 * alive, no need to continue.
978 	 */
979 	if ((flags & NS_LDAP_NEW_CONN) || (!__s_api_nscd_proc() &&
980 	    !__s_api_peruser_proc() && !(flags & NS_LDAP_KEEP_CONN)))
981 		return (-1);
982 
983 #ifdef DEBUG
984 	(void) fprintf(stderr, "tid= %d: Find connection\n", t);
985 	(void) fprintf(stderr, "tid= %d: Looking for ....\n", t);
986 	if (serverAddr && *serverAddr)
987 		(void) fprintf(stderr, "tid= %d: serverAddr=%s\n",
988 		    t, serverAddr);
989 	else
990 		(void) fprintf(stderr, "tid= %d: serverAddr=NULL\n", t);
991 	printCred(LOG_DEBUG, auth);
992 	fflush(stderr);
993 #endif /* DEBUG */
994 
995 	/*
996 	 * If multiple threads per connection not supported,
997 	 * no sessionPool means no connection
998 	 */
999 	(void) rw_rdlock(&sessionPoolLock);
1000 	if (MTperConn == 0 && sessionPool == NULL) {
1001 		(void) rw_unlock(&sessionPoolLock);
1002 		return (-1);
1003 	}
1004 
1005 	/*
1006 	 * If no sharable connections in cache, then serialize the opening
1007 	 * of connections. Make sure only one is being opened
1008 	 * at a time. Otherwise, we may end up with more
1009 	 * connections than we want (if multiple threads get
1010 	 * here at the same time)
1011 	 */
1012 	(void) mutex_lock(&sharedConnNumberLock);
1013 	if (sessionPool == NULL || (sharedConnNumber == 0 && MTperConn == 1)) {
1014 		(void) mutex_unlock(&sharedConnNumberLock);
1015 		(void) rw_unlock(&sessionPoolLock);
1016 		(void) mutex_lock(&sessionLock);
1017 		(void) mutex_lock(&sharedConnNumberLock);
1018 		if (sessionPool == NULL || (sharedConnNumber == 0 &&
1019 		    MTperConn == 1)) {
1020 			(void) mutex_unlock(&sharedConnNumberLock);
1021 			wait4session = 1;
1022 			sessionTid = thr_self();
1023 #ifdef DEBUG
1024 			(void) fprintf(stderr, "tid= %d: get "
1025 			    "connection ... \n", t);
1026 			fflush(stderr);
1027 #endif /* DEBUG */
1028 			/*
1029 			 * Exit with sessionLock locked. It will be
1030 			 * be unlocked in addConnection() when this
1031 			 * thread adds the connection to the pool or
1032 			 * in __s_api_getConnection() when it exits
1033 			 * without getting a connection.
1034 			 */
1035 			return (-1);
1036 		}
1037 
1038 #ifdef DEBUG
1039 		(void) fprintf(stderr, "tid= %d: shareable connections "
1040 		    "exist\n", t);
1041 		fflush(stderr);
1042 #endif /* DEBUG */
1043 		(void) mutex_unlock(&sharedConnNumberLock);
1044 		/*
1045 		 * There are sharable connections, check to see if
1046 		 * one can be shared.
1047 		 */
1048 		(void) mutex_unlock(&sessionLock);
1049 		(void) rw_rdlock(&sessionPoolLock);
1050 	} else
1051 		(void) mutex_unlock(&sharedConnNumberLock);
1052 
1053 	try = 0;
1054 	check_again:
1055 
1056 	for (i = 0; i < sessionPoolSize; ++i) {
1057 		if (sessionPool[i] == NULL)
1058 			continue;
1059 		cp = sessionPool[i];
1060 #ifdef DEBUG
1061 		(void) fprintf(stderr, "tid= %d: checking connection "
1062 		    "[%d] ....\n", t, i);
1063 		printConnection(LOG_DEBUG, cp);
1064 #endif /* DEBUG */
1065 		if ((cp->usedBit) || (cp->notAvail) ||
1066 		    (cp->auth->auth.type != auth->auth.type) ||
1067 		    (cp->auth->auth.tlstype != auth->auth.tlstype) ||
1068 		    (cp->auth->auth.saslmech != auth->auth.saslmech) ||
1069 		    (cp->auth->auth.saslopt != auth->auth.saslopt) ||
1070 		    (serverAddr && *serverAddr &&
1071 		    (strcasecmp(serverAddr, cp->serverAddr) != 0)))
1072 			continue;
1073 		if ((((cp->auth->auth.type == NS_LDAP_AUTH_SASL) &&
1074 		    ((cp->auth->auth.saslmech == NS_LDAP_SASL_CRAM_MD5) ||
1075 		    (cp->auth->auth.saslmech == NS_LDAP_SASL_DIGEST_MD5))) ||
1076 		    (cp->auth->auth.type == NS_LDAP_AUTH_SIMPLE)) &&
1077 		    ((cp->auth->cred.unix_cred.userID == NULL) ||
1078 		    (cp->auth->cred.unix_cred.passwd == NULL) ||
1079 		    ((strcasecmp(cp->auth->cred.unix_cred.userID,
1080 		    auth->cred.unix_cred.userID) != 0)) ||
1081 		    ((strcmp(cp->auth->cred.unix_cred.passwd,
1082 		    auth->cred.unix_cred.passwd) != 0))))
1083 				continue;
1084 		if (!(serverAddr && *serverAddr)) {
1085 			/*
1086 			 * Get preferred server list.
1087 			 * When preferred servers are merged with default
1088 			 * servers (S_LDAP_SERVER_P) by __s_api_getServer,
1089 			 * preferred servers are copied sequencially.
1090 			 * The order should be the same as the order retrieved
1091 			 * by __ns_ldap_getParam.
1092 			 */
1093 			if ((rc = __ns_ldap_getParam(NS_LDAP_SERVER_PREF_P,
1094 			    &paramVal, &errorp)) != NS_LDAP_SUCCESS) {
1095 				(void) __ns_ldap_freeError(&errorp);
1096 				(void) __ns_ldap_freeParam(&paramVal);
1097 				(void) rw_unlock(&sessionPoolLock);
1098 				return (-1);
1099 			}
1100 			servers = (char **)paramVal;
1101 			/*
1102 			 * Do fallback only if preferred servers are defined.
1103 			 */
1104 			if (servers != NULL) {
1105 				/*
1106 				 * Find the 1st available server
1107 				 */
1108 				rc = __s_api_requestServer(NS_CACHE_NEW, NULL,
1109 				    &sinfo, &errorp, NS_CACHE_ADDR_IP);
1110 				if (rc != NS_LDAP_SUCCESS) {
1111 					/*
1112 					 * Drop the connection.
1113 					 * Pass 1 to fini so it won't be locked
1114 					 * inside _DropConnection
1115 					 */
1116 					_DropConnection(
1117 					    cp->connectionId,
1118 					    NS_LDAP_NEW_CONN, 1);
1119 					(void) rw_unlock(
1120 					    &sessionPoolLock);
1121 					(void) __ns_ldap_freeError(&errorp);
1122 					(void) __ns_ldap_freeParam(
1123 					    (void ***)&servers);
1124 					return (-1);
1125 				}
1126 
1127 				if (sinfo.server) {
1128 					/*
1129 					 * Test if cp->serverAddr is a
1130 					 * preferred server.
1131 					 */
1132 					conn_server_index = -1;
1133 					for (j = 0; servers[j] != NULL; j++) {
1134 						if (strcasecmp(servers[j],
1135 						    cp->serverAddr) == 0) {
1136 							conn_server_index = j;
1137 							break;
1138 						}
1139 					}
1140 					/*
1141 					 * Test if sinfo.server is a preferred
1142 					 * server.
1143 					 */
1144 					up_server_index = -1;
1145 					for (j = 0; servers[j] != NULL; j++) {
1146 						if (strcasecmp(sinfo.server,
1147 						    servers[j]) == 0) {
1148 							up_server_index = j;
1149 							break;
1150 						}
1151 					}
1152 
1153 					/*
1154 					 * The following code is to fall back
1155 					 * to preferred servers if servers
1156 					 * are previously down but are up now.
1157 					 * If cp->serverAddr is a preferred
1158 					 * server, it falls back to the servers
1159 					 * ahead of it. If cp->serverAddr is
1160 					 * not a preferred server, it falls
1161 					 * back to any of preferred servers
1162 					 * returned by ldap_cachemgr.
1163 					 */
1164 					if (conn_server_index >= 0 &&
1165 					    up_server_index >= 0) {
1166 						/*
1167 						 * cp->serverAddr and
1168 						 * sinfo.server are preferred
1169 						 * servers.
1170 						 */
1171 						if (up_server_index ==
1172 						    conn_server_index)
1173 							/*
1174 							 * sinfo.server is the
1175 							 * same as
1176 							 * cp->serverAddr.
1177 							 * Keep the connection.
1178 							 */
1179 							drop_conn = 0;
1180 						else
1181 							/*
1182 							 * 1.
1183 							 * up_server_index <
1184 							 * conn_server_index
1185 							 *
1186 							 * sinfo is ahead of
1187 							 * cp->serverAddr in
1188 							 * Need to fall back.
1189 							 * 2.
1190 							 * up_server_index >
1191 							 * conn_server_index
1192 							 * cp->serverAddr is
1193 							 * down. Drop it.
1194 							 */
1195 							drop_conn = 1;
1196 					} else if (conn_server_index >= 0 &&
1197 					    up_server_index == -1) {
1198 						/*
1199 						 * cp->serverAddr is a preferred
1200 						 * server but sinfo.server is
1201 						 * not. Preferred servers are
1202 						 * ahead of default servers.
1203 						 * This means cp->serverAddr is
1204 						 * down. Drop it.
1205 						 */
1206 						drop_conn = 1;
1207 					} else if (conn_server_index == -1 &&
1208 					    up_server_index >= 0) {
1209 						/*
1210 						 * cp->serverAddr is not a
1211 						 * preferred server but
1212 						 * sinfo.server is.
1213 						 * Fall back.
1214 						 */
1215 						drop_conn = 1;
1216 					} else {
1217 						/*
1218 						 * Both index are -1
1219 						 * cp->serverAddr and
1220 						 * sinfo.server are not
1221 						 * preferred servers.
1222 						 * No fallback.
1223 						 */
1224 						drop_conn = 0;
1225 					}
1226 					if (drop_conn) {
1227 						/*
1228 						 * Drop the connection so the
1229 						 * new conection can fall back
1230 						 * to a new server later.
1231 						 * Pass 1 to fini so it won't
1232 						 * be locked inside
1233 						 * _DropConnection
1234 						 */
1235 						_DropConnection(
1236 						    cp->connectionId,
1237 						    NS_LDAP_NEW_CONN, 1);
1238 						(void) rw_unlock(
1239 						    &sessionPoolLock);
1240 						(void) __ns_ldap_freeParam(
1241 						    (void ***)&servers);
1242 						__s_api_free_server_info(
1243 						    &sinfo);
1244 						return (-1);
1245 					} else {
1246 						/*
1247 						 * Keep the connection
1248 						 */
1249 						(void) __ns_ldap_freeParam(
1250 						    (void ***)&servers);
1251 						__s_api_free_server_info(
1252 						    &sinfo);
1253 					}
1254 				} else {
1255 					(void) rw_unlock(&sessionPoolLock);
1256 					syslog(LOG_WARNING, "libsldap: Null "
1257 					    "sinfo.server from "
1258 					    "__s_api_requestServer");
1259 					(void) __ns_ldap_freeParam(
1260 					    (void ***)&servers);
1261 					return (-1);
1262 				}
1263 			}
1264 		}
1265 
1266 		/* found an available connection */
1267 		if (MTperConn == 0)
1268 			cp->usedBit = B_TRUE;
1269 		else {
1270 			/*
1271 			 * if connection was established in a different
1272 			 * process, drop it and get a new one
1273 			 */
1274 			if (cp->pid != getpid()) {
1275 				(void) rw_unlock(&sessionPoolLock);
1276 				DropConnection(cp->connectionId,
1277 				    NS_LDAP_NEW_CONN);
1278 
1279 				goto get_conn;
1280 			}
1281 			/* allocate TSD for per thread ldap error */
1282 			rc = tsd_setup();
1283 
1284 			/* if we got TSD, this connection is shared */
1285 			if (rc != -1)
1286 				cp->shared++;
1287 			else if (cp->shared == 0) {
1288 				cp->usedBit = B_TRUE;
1289 				cp->threadID = thr_self();
1290 				(void) rw_unlock(&sessionPoolLock);
1291 				return (-1);
1292 			}
1293 		}
1294 		(void) rw_unlock(&sessionPoolLock);
1295 
1296 		*conp = cp;
1297 #ifdef DEBUG
1298 		(void) fprintf(stderr, "tid= %d: Connection found "
1299 		    "cID=%d, shared =%d\n", t, i, cp->shared);
1300 		fflush(stderr);
1301 #endif /* DEBUG */
1302 		return (i + CONID_OFFSET);
1303 	}
1304 
1305 	get_conn:
1306 
1307 	(void) rw_unlock(&sessionPoolLock);
1308 
1309 	/*
1310 	 * If multiple threads per connection not supported,
1311 	 * we are done, just return -1 to tell the caller to
1312 	 * proceed with opening a connection
1313 	 */
1314 	if (MTperConn == 0)
1315 		return (-1);
1316 
1317 	/*
1318 	 * No connection can be shared, test to see if
1319 	 * one is being opened. If trylock returns
1320 	 * EBUSY then it is, so wait until the opening
1321 	 * is done and try to see if the new connection
1322 	 * can be shared.
1323 	 */
1324 	rc = mutex_trylock(&sessionLock);
1325 	if (rc == EBUSY) {
1326 		(void) mutex_lock(&sessionLock);
1327 		(void) mutex_unlock(&sessionLock);
1328 		(void) rw_rdlock(&sessionPoolLock);
1329 #ifdef DEBUG
1330 		(void) fprintf(stderr, "tid= %d: check session "
1331 		    "pool again\n", t);
1332 		fflush(stderr);
1333 #endif /* DEBUG */
1334 		if (try < TRY_TIMES) {
1335 			try++;
1336 			goto check_again;
1337 		} else {
1338 			syslog(LOG_WARNING, "libsldap: mutex_trylock "
1339 			    "%d times. Stop.", TRY_TIMES);
1340 			(void) rw_unlock(&sessionPoolLock);
1341 			return (-1);
1342 		}
1343 	} else if (rc == 0) {
1344 		/*
1345 		 * No connection can be shared, none being opened,
1346 		 * exit with sessionLock locked to open one. The
1347 		 * mutex will be unlocked in addConnection() when
1348 		 * this thread adds the new connection to the pool
1349 		 * or in __s_api_getConnection() when it exits
1350 		 * without getting a connection.
1351 		 */
1352 		wait4session = 1;
1353 		sessionTid = thr_self();
1354 #ifdef DEBUG
1355 		(void) fprintf(stderr, "tid= %d: no connection found, "
1356 		    "none being opened, get connection ...\n", t);
1357 		fflush(stderr);
1358 #endif /* DEBUG */
1359 		return (-1);
1360 	} else {
1361 		syslog(LOG_WARNING, "libsldap: mutex_trylock unexpected "
1362 		    "error %d", rc);
1363 		return (-1);
1364 	}
1365 }
1366 
1367 /*
1368  * Free a Connection structure
1369  */
1370 static void
1371 freeConnection(Connection *con)
1372 {
1373 	if (con == NULL)
1374 		return;
1375 	if (con->serverAddr)
1376 		free(con->serverAddr);
1377 	if (con->auth)
1378 		(void) __ns_ldap_freeCred(&(con->auth));
1379 	if (con->saslMechanisms) {
1380 		__s_api_free2dArray(con->saslMechanisms);
1381 	}
1382 	if (con->controls) {
1383 		__s_api_free2dArray(con->controls);
1384 	}
1385 	free(con);
1386 }
1387 
1388 /*
1389  * Find a connection matching the passed in criteria.  If an open
1390  * connection with that criteria exists use it, otherwise open a
1391  * new connection.
1392  * Success: returns the pointer to the Connection structure
1393  * Failure: returns NULL, error code and message should be in errorp
1394  */
1395 
1396 static int
1397 makeConnection(Connection **conp, const char *serverAddr,
1398 	const ns_cred_t *auth, ConnectionID *cID, int timeoutSec,
1399 	ns_ldap_error_t **errorp, int fail_if_new_pwd_reqd,
1400 	int nopasswd_acct_mgmt, int flags, char ***badsrvrs)
1401 {
1402 	Connection *con = NULL;
1403 	ConnectionID id;
1404 	char errmsg[MAXERROR];
1405 	int rc, exit_rc = NS_LDAP_SUCCESS;
1406 	ns_server_info_t sinfo;
1407 	char *hReq, *host = NULL;
1408 	LDAP *ld = NULL;
1409 	int passwd_mgmt = 0;
1410 	int totalbad = 0; /* Number of servers contacted unsuccessfully */
1411 	short	memerr = 0; /* Variable for tracking memory allocation */
1412 	char *serverAddrType = NULL, **bindHost = NULL;
1413 
1414 
1415 	if (conp == NULL || errorp == NULL || auth == NULL)
1416 		return (NS_LDAP_INVALID_PARAM);
1417 	*errorp = NULL;
1418 	*conp = NULL;
1419 	(void) memset(&sinfo, 0, sizeof (sinfo));
1420 
1421 	if ((wait4session == 0 || sessionTid != thr_self()) &&
1422 	    (id = findConnection(flags, serverAddr, auth, &con)) != -1) {
1423 		/* connection found in cache */
1424 #ifdef DEBUG
1425 		(void) fprintf(stderr, "tid= %d: connection found in "
1426 		    "cache %d\n", thr_self(), id);
1427 		fflush(stderr);
1428 #endif /* DEBUG */
1429 		*cID = id;
1430 		*conp = con;
1431 		return (NS_LDAP_SUCCESS);
1432 	}
1433 
1434 	if (auth->auth.saslmech == NS_LDAP_SASL_GSSAPI) {
1435 		serverAddrType = NS_CACHE_ADDR_HOSTNAME;
1436 		bindHost = &sinfo.serverFQDN;
1437 	} else {
1438 		serverAddrType = NS_CACHE_ADDR_IP;
1439 		bindHost = &sinfo.server;
1440 	}
1441 
1442 	if (serverAddr) {
1443 		/*
1444 		 * We're given the server address, just use it.
1445 		 * In case of sasl/GSSAPI, serverAddr would need to be a FQDN.
1446 		 * We assume this is the case for now.
1447 		 *
1448 		 * Only the server address fields of sinfo structure are filled
1449 		 * in since these are the only relevant data that we have. Other
1450 		 * fields of this structure (controls, saslMechanisms) are
1451 		 * kept to NULL.
1452 		 */
1453 		sinfo.server = strdup(serverAddr);
1454 		if (sinfo.server == NULL)  {
1455 			return (NS_LDAP_MEMORY);
1456 		}
1457 		if (auth->auth.saslmech == NS_LDAP_SASL_GSSAPI) {
1458 			sinfo.serverFQDN = strdup(serverAddr);
1459 			if (sinfo.serverFQDN == NULL) {
1460 				free(sinfo.server);
1461 				return (NS_LDAP_MEMORY);
1462 			}
1463 		}
1464 		rc = openConnection(&ld, *bindHost, auth, timeoutSec, errorp,
1465 		    fail_if_new_pwd_reqd, passwd_mgmt);
1466 		if (rc == NS_LDAP_SUCCESS || rc ==
1467 		    NS_LDAP_SUCCESS_WITH_INFO) {
1468 			exit_rc = rc;
1469 			goto create_con;
1470 		} else {
1471 			if (auth->auth.saslmech == NS_LDAP_SASL_GSSAPI) {
1472 				(void) snprintf(errmsg, sizeof (errmsg),
1473 				    "%s %s", gettext("makeConnection: "
1474 				    "failed to open connection using "
1475 				    "sasl/GSSAPI to"), *bindHost);
1476 			} else {
1477 				(void) snprintf(errmsg, sizeof (errmsg),
1478 				    "%s %s", gettext("makeConnection: "
1479 				    "failed to open connection to"),
1480 				    *bindHost);
1481 			}
1482 			syslog(LOG_ERR, "libsldap: %s", errmsg);
1483 			__s_api_free_server_info(&sinfo);
1484 			return (rc);
1485 		}
1486 	}
1487 
1488 	/* No cached connection, create one */
1489 	for (; ; ) {
1490 		if (host == NULL)
1491 			hReq = NS_CACHE_NEW;
1492 		else
1493 			hReq = NS_CACHE_NEXT;
1494 		rc = __s_api_requestServer(hReq, host, &sinfo, errorp,
1495 		    serverAddrType);
1496 		if ((rc != NS_LDAP_SUCCESS) || (sinfo.server == NULL) ||
1497 		    (host && (strcasecmp(host, sinfo.server) == 0))) {
1498 			/* Log the error */
1499 			if (*errorp) {
1500 				(void) snprintf(errmsg, sizeof (errmsg),
1501 				"%s: (%s)", gettext("makeConnection: "
1502 				"unable to make LDAP connection, "
1503 				"request for a server failed"),
1504 				    (*errorp)->message);
1505 				syslog(LOG_ERR, "libsldap: %s", errmsg);
1506 			}
1507 
1508 			__s_api_free_server_info(&sinfo);
1509 			if (host)
1510 				free(host);
1511 			return (NS_LDAP_OP_FAILED);
1512 		}
1513 		if (host)
1514 			free(host);
1515 		host = strdup(sinfo.server);
1516 		if (host == NULL) {
1517 			__s_api_free_server_info(&sinfo);
1518 			return (NS_LDAP_MEMORY);
1519 		}
1520 
1521 		/* check if server supports password management */
1522 		passwd_mgmt = __s_api_contain_passwd_control_oid(
1523 		    sinfo.controls);
1524 		/* check if server supports password less account mgmt */
1525 		if (nopasswd_acct_mgmt &&
1526 		    !__s_api_contain_account_usable_control_oid(
1527 		    sinfo.controls)) {
1528 			syslog(LOG_WARNING, "libsldap: server %s does not "
1529 			    "provide account information without password",
1530 			    host);
1531 			free(host);
1532 			__s_api_free_server_info(&sinfo);
1533 			return (NS_LDAP_OP_FAILED);
1534 		}
1535 		/* make the connection */
1536 		rc = openConnection(&ld, *bindHost, auth, timeoutSec, errorp,
1537 		    fail_if_new_pwd_reqd, passwd_mgmt);
1538 		/* if success, go to create connection structure */
1539 		if (rc == NS_LDAP_SUCCESS ||
1540 		    rc == NS_LDAP_SUCCESS_WITH_INFO) {
1541 			exit_rc = rc;
1542 			break;
1543 		}
1544 
1545 		/*
1546 		 * If not able to reach the server, inform the ldap
1547 		 * cache manager that the server should be removed
1548 		 * from its server list. Thus, the manager will not
1549 		 * return this server on the next get-server request
1550 		 * and will also reduce the server list refresh TTL,
1551 		 * so that it will find out sooner when the server
1552 		 * is up again.
1553 		 */
1554 		if (rc == NS_LDAP_INTERNAL && *errorp != NULL) {
1555 			if ((*errorp)->status == LDAP_CONNECT_ERROR ||
1556 			    (*errorp)->status == LDAP_SERVER_DOWN) {
1557 				/* Reset memory allocation error */
1558 				memerr = 0;
1559 				/*
1560 				 * We contacted a server that we could
1561 				 * not either authenticate to or contact.
1562 				 * If it is due to authentication, then
1563 				 * we need to try the server again. So,
1564 				 * do not remove the server yet, but
1565 				 * add it to the bad server list.
1566 				 * The caller routine will remove
1567 				 * the servers if:
1568 				 *	a). A good server is found or
1569 				 *	b). All the possible methods
1570 				 *	    are tried without finding
1571 				 *	    a good server
1572 				 */
1573 				if (*badsrvrs == NULL) {
1574 					if (!(*badsrvrs = (char **)malloc
1575 					    (sizeof (char *) * NUMTOMALLOC))) {
1576 						memerr = 1;
1577 					}
1578 				/* Allocate memory in chunks of NUMTOMALLOC */
1579 				} else if ((totalbad % NUMTOMALLOC) ==
1580 				    NUMTOMALLOC - 1) {
1581 					char **tmpptr;
1582 					if (!(tmpptr = (char **)realloc(
1583 					    *badsrvrs,
1584 					    (sizeof (char *) * NUMTOMALLOC *
1585 					    ((totalbad/NUMTOMALLOC) + 2))))) {
1586 						memerr = 1;
1587 					} else {
1588 						*badsrvrs = tmpptr;
1589 					}
1590 				}
1591 				/*
1592 				 * Store host only if there were no unsuccessful
1593 				 * memory allocations above
1594 				 */
1595 				if (!memerr &&
1596 				    !((*badsrvrs)[totalbad++] = strdup(host))) {
1597 					memerr = 1;
1598 					totalbad--;
1599 				}
1600 				(*badsrvrs)[totalbad] = NULL;
1601 			}
1602 		}
1603 
1604 		/* else, cleanup and go for the next server */
1605 		__s_api_free_server_info(&sinfo);
1606 
1607 		/* Return if we had memory allocation errors */
1608 		if (memerr)
1609 			return (NS_LDAP_MEMORY);
1610 		if (*errorp) {
1611 			/*
1612 			 * If openConnection() failed due to
1613 			 * password policy, or invalid credential,
1614 			 * keep *errorp and exit
1615 			 */
1616 			if ((*errorp)->pwd_mgmt.status != NS_PASSWD_GOOD ||
1617 			    (*errorp)->status == LDAP_INVALID_CREDENTIALS) {
1618 				free(host);
1619 				return (rc);
1620 			} else {
1621 				(void) __ns_ldap_freeError(errorp);
1622 				*errorp = NULL;
1623 			}
1624 		}
1625 	}
1626 
1627 create_con:
1628 	/* we have created ld, setup con structure */
1629 	if (host)
1630 		free(host);
1631 	if ((con = calloc(1, sizeof (Connection))) == NULL) {
1632 		__s_api_free_server_info(&sinfo);
1633 		/*
1634 		 * If password control attached in **errorp,
1635 		 * e.g. rc == NS_LDAP_SUCCESS_WITH_INFO,
1636 		 * free the error structure
1637 		 */
1638 		if (*errorp) {
1639 			(void) __ns_ldap_freeError(errorp);
1640 			*errorp = NULL;
1641 		}
1642 		(void) ldap_unbind(ld);
1643 		return (NS_LDAP_MEMORY);
1644 	}
1645 
1646 	con->serverAddr = sinfo.server; /* Store original format */
1647 	if (sinfo.serverFQDN != NULL) {
1648 		free(sinfo.serverFQDN);
1649 		sinfo.serverFQDN = NULL;
1650 	}
1651 	con->saslMechanisms = sinfo.saslMechanisms;
1652 	con->controls = sinfo.controls;
1653 
1654 	con->auth = __ns_ldap_dupAuth(auth);
1655 	if (con->auth == NULL) {
1656 		(void) ldap_unbind(ld);
1657 		freeConnection(con);
1658 		/*
1659 		 * If password control attached in **errorp,
1660 		 * e.g. rc == NS_LDAP_SUCCESS_WITH_INFO,
1661 		 * free the error structure
1662 		 */
1663 		if (*errorp) {
1664 			(void) __ns_ldap_freeError(errorp);
1665 			*errorp = NULL;
1666 		}
1667 		return (NS_LDAP_MEMORY);
1668 	}
1669 
1670 	con->threadID = thr_self();
1671 	con->pid = getpid();
1672 
1673 	con->ld = ld;
1674 	if ((id = addConnection(con)) == -1) {
1675 		(void) ldap_unbind(ld);
1676 		freeConnection(con);
1677 		/*
1678 		 * If password control attached in **errorp,
1679 		 * e.g. rc == NS_LDAP_SUCCESS_WITH_INFO,
1680 		 * free the error structure
1681 		 */
1682 		if (*errorp) {
1683 			(void) __ns_ldap_freeError(errorp);
1684 			*errorp = NULL;
1685 		}
1686 		return (NS_LDAP_MEMORY);
1687 	}
1688 #ifdef DEBUG
1689 	(void) fprintf(stderr, "tid= %d: connection added into "
1690 	    "cache %d\n", thr_self(), id);
1691 	fflush(stderr);
1692 #endif /* DEBUG */
1693 	*cID = id;
1694 	*conp = con;
1695 	return (exit_rc);
1696 }
1697 
1698 /*
1699  * Return the specified connection to the pool.  If necessary
1700  * delete the connection.
1701  */
1702 
1703 static void
1704 _DropConnection(ConnectionID cID, int flag, int fini)
1705 {
1706 	Connection *cp;
1707 	int id;
1708 	int use_lock = !fini;
1709 #ifdef DEBUG
1710 	thread_t t = thr_self();
1711 #endif /* DEBUG */
1712 
1713 	id = cID - CONID_OFFSET;
1714 	if (id < 0 || id >= sessionPoolSize)
1715 		return;
1716 #ifdef DEBUG
1717 	(void) fprintf(stderr, "tid= %d: "
1718 	    "Dropping connection cID=%d flag=0x%x, fini = %d\n",
1719 	    t, cID, flag, fini);
1720 	fflush(stderr);
1721 #endif /* DEBUG */
1722 	if (use_lock)
1723 		(void) rw_wrlock(&sessionPoolLock);
1724 
1725 	cp = sessionPool[id];
1726 	/* sanity check before removing */
1727 	if (!cp || (!fini && !cp->shared && !cp->usedBit)) {
1728 #ifdef DEBUG
1729 		if (cp == NULL)
1730 			(void) fprintf(stderr, "tid= %d: no "
1731 			    "need to remove (fini = %d, cp = %p)\n", t,
1732 			    fini, cp);
1733 		else
1734 			(void) fprintf(stderr, "tid= %d: no "
1735 			    "need to remove (fini = %d, cp = %p, shared = %d)"
1736 			    "\n", t, fini, cp, cp->shared);
1737 		fflush(stderr);
1738 #endif /* DEBUG */
1739 		if (use_lock)
1740 			(void) rw_unlock(&sessionPoolLock);
1741 		return;
1742 	}
1743 
1744 	if (!fini &&
1745 	    ((flag & NS_LDAP_NEW_CONN) == 0) && !cp->notAvail &&
1746 	    ((flag & NS_LDAP_KEEP_CONN) || __s_api_nscd_proc() ||
1747 	    __s_api_peruser_proc())) {
1748 #ifdef DEBUG
1749 		(void) fprintf(stderr, "tid= %d: keep alive (fini = %d "
1750 		    "shared = %d)\n", t, fini, cp->shared);
1751 #endif /* DEBUG */
1752 		/* release Connection (keep alive) */
1753 		if (cp->shared)
1754 			cp->shared--;
1755 		cp->usedBit = B_FALSE;
1756 		cp->threadID = 0;	/* unmark the threadID */
1757 		if (use_lock)
1758 			(void) rw_unlock(&sessionPoolLock);
1759 	} else {
1760 		/* delete Connection (disconnect) */
1761 		if (cp->shared > 0) {
1762 #ifdef DEBUG
1763 		(void) fprintf(stderr, "tid= %d: Connection no "
1764 		    "longer available (fini = %d, shared = %d)\n",
1765 		    t, fini, cp->shared);
1766 		fflush(stderr);
1767 #endif /* DEBUG */
1768 			cp->shared--;
1769 			/*
1770 			 * Mark this connection not available and decrement
1771 			 * sharedConnNumber. There could be multiple threads
1772 			 * sharing this connection so decrement
1773 			 * sharedConnNumber only once per connection.
1774 			 */
1775 			if (cp->notAvail == 0) {
1776 				cp->notAvail = 1;
1777 				(void) mutex_lock(&sharedConnNumberLock);
1778 				sharedConnNumber--;
1779 				(void) mutex_unlock(&sharedConnNumberLock);
1780 			}
1781 		}
1782 
1783 		if (cp->shared <= 0) {
1784 #ifdef DEBUG
1785 			(void) fprintf(stderr, "tid= %d: unbind "
1786 			    "(fini = %d, shared = %d)\n",
1787 			    t, fini, cp->shared);
1788 			fflush(stderr);
1789 #endif /* DEBUG */
1790 			sessionPool[id] = NULL;
1791 			(void) ldap_unbind(cp->ld);
1792 			freeConnection(cp);
1793 		}
1794 
1795 		if (use_lock)
1796 			(void) rw_unlock(&sessionPoolLock);
1797 	}
1798 }
1799 
1800 void
1801 DropConnection(ConnectionID cID, int flag)
1802 {
1803 	_DropConnection(cID, flag, 0);
1804 }
1805 
1806 /*
1807  * This routine is called after a bind operation is
1808  * done in openConnection() to process the password
1809  * management information, if any.
1810  *
1811  * Input:
1812  *   bind_type: "simple" or "sasl/DIGEST-MD5"
1813  *   ldaprc   : ldap rc from the ldap bind operation
1814  *   controls : controls returned by the server
1815  *   errmsg   : error message from the server
1816  *   fail_if_new_pwd_reqd:
1817  *              flag indicating if connection should be open
1818  *              when password needs to change immediately
1819  *   passwd_mgmt:
1820  *              flag indicating if server supports password
1821  *              policy/management
1822  *
1823  * Output     : ns_ldap_error structure, which may contain
1824  *              password status and number of seconds until
1825  *              expired
1826  *
1827  * return rc:
1828  * NS_LDAP_EXTERNAL: error, connection should not open
1829  * NS_LDAP_SUCCESS_WITH_INFO: OK to open but password info attached
1830  * NS_LDAP_SUCCESS: OK to open connection
1831  *
1832  */
1833 
1834 static int
1835 process_pwd_mgmt(char *bind_type, int ldaprc,
1836 		LDAPControl **controls,
1837 		char *errmsg, ns_ldap_error_t **errorp,
1838 		int fail_if_new_pwd_reqd,
1839 		int passwd_mgmt)
1840 {
1841 	char		errstr[MAXERROR];
1842 	LDAPControl	**ctrl = NULL;
1843 	int		exit_rc;
1844 	ns_ldap_passwd_status_t	pwd_status = NS_PASSWD_GOOD;
1845 	int		sec_until_exp = 0;
1846 
1847 	/*
1848 	 * errmsg may be an empty string,
1849 	 * even if ldaprc is LDAP_SUCCESS,
1850 	 * free the empty string if that's the case
1851 	 */
1852 	if (errmsg &&
1853 	    (*errmsg == '\0' || ldaprc == LDAP_SUCCESS)) {
1854 		ldap_memfree(errmsg);
1855 		errmsg = NULL;
1856 	}
1857 
1858 	if (ldaprc != LDAP_SUCCESS) {
1859 		/*
1860 		 * try to map ldap rc and error message to
1861 		 * a password status
1862 		 */
1863 		if (errmsg) {
1864 			if (passwd_mgmt)
1865 				pwd_status =
1866 				    __s_api_set_passwd_status(
1867 				    ldaprc, errmsg);
1868 			ldap_memfree(errmsg);
1869 		}
1870 
1871 		(void) snprintf(errstr, sizeof (errstr),
1872 		    gettext("openConnection: "
1873 		    "%s bind failed "
1874 		    "- %s"), bind_type, ldap_err2string(ldaprc));
1875 
1876 		if (pwd_status != NS_PASSWD_GOOD) {
1877 			MKERROR_PWD_MGMT(*errorp,
1878 			    ldaprc, strdup(errstr),
1879 			    pwd_status, 0, NULL);
1880 		} else {
1881 			MKERROR(LOG_ERR, *errorp, ldaprc, strdup(errstr),
1882 			    NULL);
1883 		}
1884 		if (controls)
1885 			ldap_controls_free(controls);
1886 
1887 		return (NS_LDAP_INTERNAL);
1888 	}
1889 
1890 	/*
1891 	 * ldaprc is LDAP_SUCCESS,
1892 	 * process the password management controls, if any
1893 	 */
1894 	exit_rc = NS_LDAP_SUCCESS;
1895 	if (controls && passwd_mgmt) {
1896 		/*
1897 		 * The control with the OID
1898 		 * 2.16.840.1.113730.3.4.4 (or
1899 		 * LDAP_CONTROL_PWEXPIRED, as defined
1900 		 * in the ldap.h header file) is the
1901 		 * expired password control.
1902 		 *
1903 		 * This control is used if the server
1904 		 * is configured to require users to
1905 		 * change their passwords when first
1906 		 * logging in and whenever the
1907 		 * passwords are reset.
1908 		 *
1909 		 * If the user is logging in for the
1910 		 * first time or if the user's
1911 		 * password has been reset, the
1912 		 * server sends this control to
1913 		 * indicate that the client needs to
1914 		 * change the password immediately.
1915 		 *
1916 		 * At this point, the only operation
1917 		 * that the client can perform is to
1918 		 * change the user's password. If the
1919 		 * client requests any other LDAP
1920 		 * operation, the server sends back
1921 		 * an LDAP_UNWILLING_TO_PERFORM
1922 		 * result code with an expired
1923 		 * password control.
1924 		 *
1925 		 * The control with the OID
1926 		 * 2.16.840.1.113730.3.4.5 (or
1927 		 * LDAP_CONTROL_PWEXPIRING, as
1928 		 * defined in the ldap.h header file)
1929 		 * is the password expiration warning
1930 		 * control.
1931 		 *
1932 		 * This control is used if the server
1933 		 * is configured to expire user
1934 		 * passwords after a certain amount
1935 		 * of time.
1936 		 *
1937 		 * The server sends this control back
1938 		 * to the client if the client binds
1939 		 * using a password that will soon
1940 		 * expire.  The ldctl_value field of
1941 		 * the LDAPControl structure
1942 		 * specifies the number of seconds
1943 		 * before the password will expire.
1944 		 */
1945 		for (ctrl = controls; *ctrl; ctrl++) {
1946 
1947 			if (strcmp((*ctrl)->ldctl_oid,
1948 			    LDAP_CONTROL_PWEXPIRED) == 0) {
1949 				/*
1950 				 * if the caller wants this bind
1951 				 * to fail, set up the error info.
1952 				 * If call to this function is
1953 				 * for searching the LDAP directory,
1954 				 * e.g., __ns_ldap_list(),
1955 				 * there's really no sense to
1956 				 * let a connection open and
1957 				 * then fail immediately afterward
1958 				 * on the LDAP search operation with
1959 				 * the LDAP_UNWILLING_TO_PERFORM rc
1960 				 */
1961 				pwd_status =
1962 				    NS_PASSWD_CHANGE_NEEDED;
1963 				if (fail_if_new_pwd_reqd) {
1964 					(void) snprintf(errstr,
1965 					    sizeof (errstr),
1966 					    gettext(
1967 					    "openConnection: "
1968 					    "%s bind "
1969 					    "failed "
1970 					    "- password "
1971 					    "expired. It "
1972 					    " needs to change "
1973 					    "immediately!"),
1974 					    bind_type);
1975 					MKERROR_PWD_MGMT(*errorp,
1976 					    LDAP_SUCCESS,
1977 					    strdup(errstr),
1978 					    pwd_status,
1979 					    0,
1980 					    NULL);
1981 					exit_rc = NS_LDAP_INTERNAL;
1982 				} else {
1983 					MKERROR_PWD_MGMT(*errorp,
1984 					    LDAP_SUCCESS,
1985 					    NULL,
1986 					    pwd_status,
1987 					    0,
1988 					    NULL);
1989 					exit_rc =
1990 					    NS_LDAP_SUCCESS_WITH_INFO;
1991 				}
1992 				break;
1993 			} else if (strcmp((*ctrl)->ldctl_oid,
1994 			    LDAP_CONTROL_PWEXPIRING) == 0) {
1995 				pwd_status =
1996 				    NS_PASSWD_ABOUT_TO_EXPIRE;
1997 				if ((*ctrl)->
1998 				    ldctl_value.bv_len > 0 &&
1999 				    (*ctrl)->
2000 				    ldctl_value.bv_val)
2001 					sec_until_exp =
2002 					    atoi((*ctrl)->
2003 					    ldctl_value.bv_val);
2004 				MKERROR_PWD_MGMT(*errorp,
2005 				    LDAP_SUCCESS,
2006 				    NULL,
2007 				    pwd_status,
2008 				    sec_until_exp,
2009 				    NULL);
2010 				exit_rc =
2011 				    NS_LDAP_SUCCESS_WITH_INFO;
2012 				break;
2013 			}
2014 		}
2015 	}
2016 
2017 	if (controls)
2018 		ldap_controls_free(controls);
2019 
2020 	return (exit_rc);
2021 }
2022 
2023 static int
2024 ldap_in_hosts_switch()
2025 {
2026 	enum __nsw_parse_err		pserr;
2027 	struct __nsw_switchconfig	*conf;
2028 	struct __nsw_lookup		*lkp;
2029 	const char			*name;
2030 	int				found = 0;
2031 
2032 	conf = __nsw_getconfig("hosts", &pserr);
2033 	if (conf == NULL) {
2034 		return (-1);
2035 	}
2036 
2037 	/* check for skip and count other backends */
2038 	for (lkp = conf->lookups; lkp != NULL; lkp = lkp->next) {
2039 		name = lkp->service_name;
2040 		if (strcmp(name, "ldap") == 0) {
2041 			found = 1;
2042 			break;
2043 		}
2044 	}
2045 	__nsw_freeconfig(conf);
2046 	return (found);
2047 }
2048 
2049 static int
2050 openConnection(LDAP **ldp, const char *serverAddr, const ns_cred_t *auth,
2051 	int timeoutSec, ns_ldap_error_t **errorp,
2052 	int fail_if_new_pwd_reqd, int passwd_mgmt)
2053 {
2054 	LDAP		*ld = NULL;
2055 	char		*binddn, *passwd;
2056 	char		*digest_md5_name;
2057 	const char	*s;
2058 	int		ldapVersion = LDAP_VERSION3;
2059 	int		derefOption = LDAP_DEREF_ALWAYS;
2060 	int		zero = 0;
2061 	int		rc;
2062 	char		errstr[MAXERROR];
2063 	int		errnum = 0;
2064 	LDAPMessage	*resultMsg;
2065 	int		msgId;
2066 	int		useSSL = 0, port = 0;
2067 	struct timeval	tv;
2068 	AuthType_t	bindType;
2069 	int		timeoutMilliSec = timeoutSec * 1000;
2070 	struct berval	cred;
2071 	char		*sslServerAddr;
2072 	char		*s1;
2073 	char		*errmsg, *end = NULL;
2074 	LDAPControl	**controls;
2075 	int		pwd_rc, min_ssf = MIN_SASL_SSF, max_ssf = MAX_SASL_SSF;
2076 	ns_sasl_cb_param_t	sasl_param;
2077 
2078 	*errorp = NULL;
2079 	*ldp = NULL;
2080 
2081 	switch (auth->auth.type) {
2082 		case NS_LDAP_AUTH_NONE:
2083 		case NS_LDAP_AUTH_SIMPLE:
2084 		case NS_LDAP_AUTH_SASL:
2085 			bindType = auth->auth.type;
2086 			break;
2087 		case NS_LDAP_AUTH_TLS:
2088 			useSSL = 1;
2089 			switch (auth->auth.tlstype) {
2090 				case NS_LDAP_TLS_NONE:
2091 					bindType = NS_LDAP_AUTH_NONE;
2092 					break;
2093 				case NS_LDAP_TLS_SIMPLE:
2094 					bindType = NS_LDAP_AUTH_SIMPLE;
2095 					break;
2096 				case NS_LDAP_TLS_SASL:
2097 					bindType = NS_LDAP_AUTH_SASL;
2098 					break;
2099 				default:
2100 					(void) sprintf(errstr,
2101 					gettext("openConnection: unsupported "
2102 					    "TLS authentication method "
2103 					    "(%d)"), auth->auth.tlstype);
2104 					MKERROR(LOG_WARNING, *errorp,
2105 					    LDAP_AUTH_METHOD_NOT_SUPPORTED,
2106 					    strdup(errstr), NULL);
2107 					return (NS_LDAP_INTERNAL);
2108 			}
2109 			break;
2110 		default:
2111 			(void) sprintf(errstr,
2112 			    gettext("openConnection: unsupported "
2113 			    "authentication method (%d)"), auth->auth.type);
2114 			MKERROR(LOG_WARNING, *errorp,
2115 			    LDAP_AUTH_METHOD_NOT_SUPPORTED, strdup(errstr),
2116 			    NULL);
2117 			return (NS_LDAP_INTERNAL);
2118 	}
2119 
2120 	if (useSSL) {
2121 		const char	*hostcertpath;
2122 		char		*alloc_hcp = NULL;
2123 #ifdef DEBUG
2124 		(void) fprintf(stderr, "tid= %d: +++TLS transport\n",
2125 		    thr_self());
2126 #endif /* DEBUG */
2127 
2128 		if (prldap_set_session_option(NULL, NULL,
2129 		    PRLDAP_OPT_IO_MAX_TIMEOUT,
2130 		    timeoutMilliSec) != LDAP_SUCCESS) {
2131 			(void) snprintf(errstr, sizeof (errstr),
2132 			    gettext("openConnection: failed to initialize "
2133 			    "TLS security"));
2134 			MKERROR(LOG_WARNING, *errorp, LDAP_CONNECT_ERROR,
2135 			    strdup(errstr), NULL);
2136 			return (NS_LDAP_INTERNAL);
2137 		}
2138 
2139 		hostcertpath = auth->hostcertpath;
2140 		if (hostcertpath == NULL) {
2141 			alloc_hcp = __s_get_hostcertpath();
2142 			hostcertpath = alloc_hcp;
2143 		}
2144 
2145 		if (hostcertpath == NULL)
2146 			return (NS_LDAP_MEMORY);
2147 
2148 		if ((rc = ldapssl_client_init(hostcertpath, NULL)) < 0) {
2149 			if (alloc_hcp)
2150 				free(alloc_hcp);
2151 			(void) snprintf(errstr, sizeof (errstr),
2152 			    gettext("openConnection: failed to initialize "
2153 			    "TLS security (%s)"),
2154 			    ldapssl_err2string(rc));
2155 			MKERROR(LOG_WARNING, *errorp, LDAP_CONNECT_ERROR,
2156 			    strdup(errstr), NULL);
2157 			return (NS_LDAP_INTERNAL);
2158 		}
2159 		if (alloc_hcp)
2160 			free(alloc_hcp);
2161 
2162 		/* determine if the host name contains a port number */
2163 		s = strchr(serverAddr, ']');	/* skip over ipv6 addr */
2164 		if (s == NULL)
2165 			s = serverAddr;
2166 		s = strchr(s, ':');
2167 		if (s != NULL) {
2168 			/*
2169 			 * If we do get a port number, we will try stripping
2170 			 * it. At present, referrals will always have a
2171 			 * port number.
2172 			 */
2173 			sslServerAddr = strdup(serverAddr);
2174 			if (sslServerAddr == NULL)
2175 				return (NS_LDAP_MEMORY);
2176 			s1 = strrchr(sslServerAddr, ':');
2177 			if (s1 != NULL)
2178 				*s1 = '\0';
2179 			(void) snprintf(errstr, sizeof (errstr),
2180 			    gettext("openConnection: cannot use tls with %s. "
2181 			    "Trying %s"),
2182 			    serverAddr, sslServerAddr);
2183 			syslog(LOG_ERR, "libsldap: %s", errstr);
2184 		} else
2185 			sslServerAddr = (char *)serverAddr;
2186 
2187 		ld = ldapssl_init(sslServerAddr, LDAPS_PORT, 1);
2188 
2189 		if (sslServerAddr != serverAddr)
2190 			free(sslServerAddr);
2191 
2192 		if (ld == NULL ||
2193 		    ldapssl_install_gethostbyaddr(ld, "ldap") != 0) {
2194 			(void) snprintf(errstr, sizeof (errstr),
2195 			    gettext("openConnection: failed to connect "
2196 			    "using TLS (%s)"), strerror(errno));
2197 			MKERROR(LOG_WARNING, *errorp, LDAP_CONNECT_ERROR,
2198 			    strdup(errstr), NULL);
2199 			return (NS_LDAP_INTERNAL);
2200 		}
2201 	} else {
2202 #ifdef DEBUG
2203 		(void) fprintf(stderr, "tid= %d: +++Unsecure transport\n",
2204 		    thr_self());
2205 #endif /* DEBUG */
2206 		port = LDAP_PORT;
2207 		if (auth->auth.saslmech == NS_LDAP_SASL_GSSAPI &&
2208 		    (end = strchr(serverAddr, ':')) != NULL) {
2209 			/*
2210 			 * The IP is converted to hostname so it's a
2211 			 * hostname:port up to this point.
2212 			 *
2213 			 * libldap passes hostname:port to the sasl layer.
2214 			 * The ldap service principal is constructed as
2215 			 * ldap/hostname:port@REALM. Kerberos authentication
2216 			 * will fail. So it needs to be parsed to construct
2217 			 * a valid principal ldap/hostname@REALM.
2218 			 *
2219 			 * For useSSL case above, it already parses port so
2220 			 * no need to parse serverAddr
2221 			 */
2222 			*end = '\0';
2223 			port = atoi(end + 1);
2224 		}
2225 
2226 		/* Warning message IF cannot connect to host(s) */
2227 		if ((ld = ldap_init((char *)serverAddr, port)) == NULL) {
2228 			char *p = strerror(errno);
2229 			MKERROR(LOG_WARNING, *errorp, LDAP_CONNECT_ERROR,
2230 			    strdup(p), NULL);
2231 			if (end)
2232 				*end = ':';
2233 			return (NS_LDAP_INTERNAL);
2234 		} else {
2235 			if (end)
2236 				*end = ':';
2237 			/* check and avoid gethostname recursion */
2238 			if (ldap_in_hosts_switch() > 0 &&
2239 			    ! __s_api_isipv4((char *)serverAddr) &&
2240 			    ! __s_api_isipv6((char *)serverAddr)) {
2241 				/* host: ldap - found, attempt to recover */
2242 				if (ldap_set_option(ld, LDAP_X_OPT_DNS_SKIPDB,
2243 				    "ldap") != 0) {
2244 					(void) snprintf(errstr, sizeof (errstr),
2245 					    gettext("openConnection: "
2246 					    "unrecoverable gethostname "
2247 					    "recursion detected "
2248 					    "in /etc/nsswitch.conf"));
2249 					MKERROR(LOG_WARNING, *errorp,
2250 					    LDAP_CONNECT_ERROR,
2251 					    strdup(errstr), NULL);
2252 					(void) ldap_unbind(ld);
2253 					return (NS_LDAP_INTERNAL);
2254 				}
2255 			}
2256 		}
2257 	}
2258 
2259 	ns_setup_mt_conn_and_tsd(ld);
2260 	(void) ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &ldapVersion);
2261 	(void) ldap_set_option(ld, LDAP_OPT_DEREF, &derefOption);
2262 	/*
2263 	 * set LDAP_OPT_REFERRALS to OFF.
2264 	 * This library will handle the referral itself
2265 	 * based on API flags or configuration file
2266 	 * specification. If this option is not set
2267 	 * to OFF, libldap will never pass the
2268 	 * referral info up to this library
2269 	 */
2270 	(void) ldap_set_option(ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF);
2271 	(void) ldap_set_option(ld, LDAP_OPT_TIMELIMIT, &zero);
2272 	(void) ldap_set_option(ld, LDAP_OPT_SIZELIMIT, &zero);
2273 	/* setup TCP/IP connect timeout */
2274 	(void) ldap_set_option(ld, LDAP_X_OPT_CONNECT_TIMEOUT,
2275 	    &timeoutMilliSec);
2276 	/* retry if LDAP I/O was interrupted */
2277 	(void) ldap_set_option(ld, LDAP_OPT_RESTART, LDAP_OPT_ON);
2278 
2279 	switch (bindType) {
2280 	case NS_LDAP_AUTH_NONE:
2281 #ifdef DEBUG
2282 		(void) fprintf(stderr, "tid= %d: +++Anonymous bind\n",
2283 		    thr_self());
2284 #endif /* DEBUG */
2285 		break;
2286 	case NS_LDAP_AUTH_SIMPLE:
2287 		binddn = auth->cred.unix_cred.userID;
2288 		passwd = auth->cred.unix_cred.passwd;
2289 		if (passwd == NULL || *passwd == '\0' ||
2290 		    binddn == NULL || *binddn == '\0') {
2291 			(void) sprintf(errstr, gettext("openConnection: "
2292 			    "missing credentials for Simple bind"));
2293 			MKERROR(LOG_WARNING, *errorp, LDAP_INVALID_CREDENTIALS,
2294 			    strdup(errstr), NULL);
2295 			(void) ldap_unbind(ld);
2296 			return (NS_LDAP_INTERNAL);
2297 		}
2298 
2299 #ifdef DEBUG
2300 		(void) fprintf(stderr, "tid= %d: +++Simple bind\n",
2301 		    thr_self());
2302 #endif /* DEBUG */
2303 		msgId = ldap_simple_bind(ld, binddn, passwd);
2304 
2305 		if (msgId == -1) {
2306 			(void) ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER,
2307 			    (void *)&errnum);
2308 			(void) snprintf(errstr, sizeof (errstr),
2309 			    gettext("openConnection: simple bind failed "
2310 			    "- %s"), ldap_err2string(errnum));
2311 			(void) ldap_unbind(ld);
2312 			MKERROR(LOG_WARNING, *errorp, errnum, strdup(errstr),
2313 			    NULL);
2314 			return (NS_LDAP_INTERNAL);
2315 		}
2316 
2317 		tv.tv_sec = timeoutSec;
2318 		tv.tv_usec = 0;
2319 		rc = ldap_result(ld, msgId, 0, &tv, &resultMsg);
2320 
2321 		if ((rc == -1) || (rc == 0)) {
2322 			(void) ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER,
2323 			    (void *)&errnum);
2324 			(void) snprintf(errstr, sizeof (errstr),
2325 			    gettext("openConnection: simple bind failed "
2326 			    "- %s"), ldap_err2string(errnum));
2327 			(void) ldap_msgfree(resultMsg);
2328 			(void) ldap_unbind(ld);
2329 			MKERROR(LOG_WARNING, *errorp, errnum, strdup(errstr),
2330 			    NULL);
2331 			return (NS_LDAP_INTERNAL);
2332 		}
2333 
2334 		/*
2335 		 * get ldaprc, controls, and error msg
2336 		 */
2337 		rc = ldap_parse_result(ld, resultMsg, &errnum, NULL,
2338 		    &errmsg, NULL, &controls, 1);
2339 
2340 		if (rc != LDAP_SUCCESS) {
2341 			(void) snprintf(errstr, sizeof (errstr),
2342 			    gettext("openConnection: simple bind failed "
2343 			    "- unable to parse result"));
2344 			(void) ldap_unbind(ld);
2345 			MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL,
2346 			    strdup(errstr), NULL);
2347 			return (NS_LDAP_INTERNAL);
2348 		}
2349 
2350 		/* process the password management info, if any */
2351 		pwd_rc = process_pwd_mgmt("simple",
2352 		    errnum, controls, errmsg,
2353 		    errorp,
2354 		    fail_if_new_pwd_reqd,
2355 		    passwd_mgmt);
2356 
2357 		if (pwd_rc == NS_LDAP_INTERNAL) {
2358 			(void) ldap_unbind(ld);
2359 			return (pwd_rc);
2360 		}
2361 
2362 		if (pwd_rc == NS_LDAP_SUCCESS_WITH_INFO) {
2363 			*ldp = ld;
2364 			return (pwd_rc);
2365 		}
2366 
2367 		break;
2368 	case NS_LDAP_AUTH_SASL:
2369 		if (auth->auth.saslopt != NS_LDAP_SASLOPT_NONE &&
2370 		    auth->auth.saslmech != NS_LDAP_SASL_GSSAPI) {
2371 			(void) sprintf(errstr,
2372 			    gettext("openConnection: SASL options are "
2373 			    "not supported (%d) for non-GSSAPI sasl bind"),
2374 			    auth->auth.saslopt);
2375 			MKERROR(LOG_WARNING, *errorp,
2376 			    LDAP_AUTH_METHOD_NOT_SUPPORTED,
2377 			    strdup(errstr), NULL);
2378 			(void) ldap_unbind(ld);
2379 			return (NS_LDAP_INTERNAL);
2380 		}
2381 		if (auth->auth.saslmech != NS_LDAP_SASL_GSSAPI) {
2382 			binddn = auth->cred.unix_cred.userID;
2383 			passwd = auth->cred.unix_cred.passwd;
2384 			if (passwd == NULL || *passwd == '\0' ||
2385 			    binddn == NULL || *binddn == '\0') {
2386 				(void) sprintf(errstr,
2387 				    gettext("openConnection: missing "
2388 				    "credentials for SASL bind"));
2389 				MKERROR(LOG_WARNING, *errorp,
2390 				    LDAP_INVALID_CREDENTIALS,
2391 				    strdup(errstr), NULL);
2392 				(void) ldap_unbind(ld);
2393 				return (NS_LDAP_INTERNAL);
2394 			}
2395 			cred.bv_val = passwd;
2396 			cred.bv_len = strlen(passwd);
2397 		}
2398 
2399 		switch (auth->auth.saslmech) {
2400 		case NS_LDAP_SASL_CRAM_MD5:
2401 			/*
2402 			 * NOTE: if iDS changes to support cram_md5,
2403 			 * please add password management code here.
2404 			 * Since ldap_sasl_cram_md5_bind_s does not
2405 			 * return anything that could be used to
2406 			 * extract the ldap rc/errmsg/control to
2407 			 * determine if bind failed due to password
2408 			 * policy, a new cram_md5_bind API will need
2409 			 * to be introduced. See
2410 			 * ldap_x_sasl_digest_md5_bind() and case
2411 			 * NS_LDAP_SASL_DIGEST_MD5 below for details.
2412 			 */
2413 			if ((rc = ldap_sasl_cram_md5_bind_s(ld, binddn,
2414 			    &cred, NULL, NULL)) != LDAP_SUCCESS) {
2415 				(void) ldap_get_option(ld,
2416 				    LDAP_OPT_ERROR_NUMBER, (void *)&errnum);
2417 				(void) snprintf(errstr, sizeof (errstr),
2418 				    gettext("openConnection: "
2419 				    "sasl/CRAM-MD5 bind failed - %s"),
2420 				    ldap_err2string(errnum));
2421 				MKERROR(LOG_WARNING, *errorp, errnum,
2422 				    strdup(errstr), NULL);
2423 				(void) ldap_unbind(ld);
2424 				return (NS_LDAP_INTERNAL);
2425 			}
2426 			break;
2427 		case NS_LDAP_SASL_DIGEST_MD5:
2428 			digest_md5_name = malloc(strlen(binddn) + 5);
2429 			/* 5 = strlen("dn: ") + 1 */
2430 			if (digest_md5_name == NULL) {
2431 				(void) ldap_unbind(ld);
2432 				return (NS_LDAP_MEMORY);
2433 			}
2434 			(void) strcpy(digest_md5_name, "dn: ");
2435 			(void) strcat(digest_md5_name, binddn);
2436 
2437 			tv.tv_sec = timeoutSec;
2438 			tv.tv_usec = 0;
2439 			rc = ldap_x_sasl_digest_md5_bind(ld,
2440 			    digest_md5_name, &cred, NULL, NULL,
2441 			    &tv, &resultMsg);
2442 
2443 			if (resultMsg == NULL) {
2444 				free(digest_md5_name);
2445 				(void) ldap_get_option(ld,
2446 				    LDAP_OPT_ERROR_NUMBER, (void *)&errnum);
2447 				(void) snprintf(errstr, sizeof (errstr),
2448 				    gettext("openConnection: "
2449 				    "DIGEST-MD5 bind failed - %s"),
2450 				    ldap_err2string(errnum));
2451 				(void) ldap_unbind(ld);
2452 				MKERROR(LOG_WARNING, *errorp, errnum,
2453 				    strdup(errstr), NULL);
2454 				return (NS_LDAP_INTERNAL);
2455 			}
2456 
2457 			/*
2458 			 * get ldaprc, controls, and error msg
2459 			 */
2460 			rc = ldap_parse_result(ld, resultMsg, &errnum, NULL,
2461 			    &errmsg, NULL, &controls, 1);
2462 
2463 			if (rc != LDAP_SUCCESS) {
2464 				free(digest_md5_name);
2465 				(void) snprintf(errstr, sizeof (errstr),
2466 				    gettext("openConnection: "
2467 				    "DIGEST-MD5 bind failed "
2468 				    "- unable to parse result"));
2469 				(void) ldap_unbind(ld);
2470 				MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL,
2471 				    strdup(errstr), NULL);
2472 				return (NS_LDAP_INTERNAL);
2473 			}
2474 
2475 			/* process the password management info, if any */
2476 			pwd_rc = process_pwd_mgmt("sasl/DIGEST-MD5",
2477 			    errnum, controls, errmsg,
2478 			    errorp,
2479 			    fail_if_new_pwd_reqd,
2480 			    passwd_mgmt);
2481 
2482 			if (pwd_rc == NS_LDAP_INTERNAL) {
2483 				free(digest_md5_name);
2484 				(void) ldap_unbind(ld);
2485 				return (pwd_rc);
2486 			}
2487 
2488 			if (pwd_rc == NS_LDAP_SUCCESS_WITH_INFO) {
2489 				*ldp = ld;
2490 				return (pwd_rc);
2491 			}
2492 
2493 			free(digest_md5_name);
2494 			break;
2495 		case NS_LDAP_SASL_GSSAPI:
2496 			if (sasl_gssapi_inited == 0) {
2497 				rc = __s_api_sasl_gssapi_init();
2498 				if (rc != NS_LDAP_SUCCESS) {
2499 					(void) snprintf(errstr, sizeof (errstr),
2500 					    gettext("openConnection: "
2501 					    "GSSAPI initialization "
2502 					    "failed"));
2503 					(void) ldap_unbind(ld);
2504 					MKERROR(LOG_WARNING, *errorp, rc,
2505 					    strdup(errstr), NULL);
2506 					return (rc);
2507 				}
2508 			}
2509 			(void) memset(&sasl_param, 0,
2510 			    sizeof (ns_sasl_cb_param_t));
2511 			sasl_param.authid = NULL;
2512 			sasl_param.authzid = "";
2513 			(void) ldap_set_option(ld, LDAP_OPT_X_SASL_SSF_MIN,
2514 			    (void *)&min_ssf);
2515 			(void) ldap_set_option(ld, LDAP_OPT_X_SASL_SSF_MAX,
2516 			    (void *)&max_ssf);
2517 
2518 			rc = ldap_sasl_interactive_bind_s(
2519 			    ld, NULL, "GSSAPI",
2520 			    NULL, NULL, LDAP_SASL_INTERACTIVE,
2521 			    __s_api_sasl_bind_callback,
2522 			    &sasl_param);
2523 
2524 			if (rc != LDAP_SUCCESS) {
2525 				(void) snprintf(errstr, sizeof (errstr),
2526 				    gettext("openConnection: "
2527 				    "GSSAPI bind failed "
2528 				    "- %d %s"), rc, ldap_err2string(rc));
2529 				(void) ldap_unbind(ld);
2530 				MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL,
2531 				    strdup(errstr), NULL);
2532 				return (NS_LDAP_INTERNAL);
2533 			}
2534 
2535 			break;
2536 		default:
2537 			(void) ldap_unbind(ld);
2538 			(void) sprintf(errstr,
2539 			    gettext("openConnection: unsupported SASL "
2540 			    "mechanism (%d)"), auth->auth.saslmech);
2541 			MKERROR(LOG_WARNING, *errorp,
2542 			    LDAP_AUTH_METHOD_NOT_SUPPORTED, strdup(errstr),
2543 			    NULL);
2544 			return (NS_LDAP_INTERNAL);
2545 		}
2546 	}
2547 
2548 	*ldp = ld;
2549 	return (NS_LDAP_SUCCESS);
2550 }
2551 
2552 /*
2553  * FUNCTION:	__s_api_getDefaultAuth
2554  *
2555  *	Constructs a credential for authentication using the config module.
2556  *
2557  * RETURN VALUES:
2558  *
2559  * NS_LDAP_SUCCESS	If successful
2560  * NS_LDAP_CONFIG	If there are any config errors.
2561  * NS_LDAP_MEMORY	Memory errors.
2562  * NS_LDAP_OP_FAILED	If there are no more authentication methods so can
2563  *			not build a new authp.
2564  * NS_LDAP_INVALID_PARAM This overloaded return value means that some of the
2565  *			necessary fields of a cred for a given auth method
2566  *			are not provided.
2567  * INPUT:
2568  *
2569  * cLevel	Currently requested credential level to be tried
2570  *
2571  * aMethod	Currently requested authentication method to be tried
2572  *
2573  * OUTPUT:
2574  *
2575  * authp		authentication method to use.
2576  */
2577 static int
2578 __s_api_getDefaultAuth(
2579 	int	*cLevel,
2580 	ns_auth_t *aMethod,
2581 	ns_cred_t **authp)
2582 {
2583 	void		**paramVal = NULL;
2584 	char		*modparamVal = NULL;
2585 	int		getUid = 0;
2586 	int		getPasswd = 0;
2587 	int		getCertpath = 0;
2588 	int		rc = 0;
2589 	ns_ldap_error_t	*errorp = NULL;
2590 
2591 #ifdef DEBUG
2592 	(void) fprintf(stderr, "__s_api_getDefaultAuth START\n");
2593 #endif
2594 
2595 	if (aMethod == NULL) {
2596 		/* Require an Auth */
2597 		return (NS_LDAP_INVALID_PARAM);
2598 
2599 	}
2600 	/*
2601 	 * credential level "self" can work with auth method sasl/GSSAPI only
2602 	 */
2603 	if (cLevel && *cLevel == NS_LDAP_CRED_SELF &&
2604 	    aMethod->saslmech != NS_LDAP_SASL_GSSAPI)
2605 		return (NS_LDAP_INVALID_PARAM);
2606 
2607 	*authp = (ns_cred_t *)calloc(1, sizeof (ns_cred_t));
2608 	if ((*authp) == NULL)
2609 		return (NS_LDAP_MEMORY);
2610 
2611 	(*authp)->auth = *aMethod;
2612 
2613 	switch (aMethod->type) {
2614 		case NS_LDAP_AUTH_NONE:
2615 			return (NS_LDAP_SUCCESS);
2616 		case NS_LDAP_AUTH_SIMPLE:
2617 			getUid++;
2618 			getPasswd++;
2619 			break;
2620 		case NS_LDAP_AUTH_SASL:
2621 			if ((aMethod->saslmech == NS_LDAP_SASL_DIGEST_MD5) ||
2622 			    (aMethod->saslmech == NS_LDAP_SASL_CRAM_MD5)) {
2623 				getUid++;
2624 				getPasswd++;
2625 			} else if (aMethod->saslmech != NS_LDAP_SASL_GSSAPI) {
2626 				(void) __ns_ldap_freeCred(authp);
2627 				*authp = NULL;
2628 				return (NS_LDAP_INVALID_PARAM);
2629 			}
2630 			break;
2631 		case NS_LDAP_AUTH_TLS:
2632 			if ((aMethod->tlstype == NS_LDAP_TLS_SIMPLE) ||
2633 			    ((aMethod->tlstype == NS_LDAP_TLS_SASL) &&
2634 			    ((aMethod->saslmech == NS_LDAP_SASL_DIGEST_MD5) ||
2635 			    (aMethod->saslmech == NS_LDAP_SASL_CRAM_MD5)))) {
2636 				getUid++;
2637 				getPasswd++;
2638 				getCertpath++;
2639 			} else if (aMethod->tlstype == NS_LDAP_TLS_NONE) {
2640 				getCertpath++;
2641 			} else {
2642 				(void) __ns_ldap_freeCred(authp);
2643 				*authp = NULL;
2644 				return (NS_LDAP_INVALID_PARAM);
2645 			}
2646 			break;
2647 	}
2648 
2649 	if (getUid) {
2650 		paramVal = NULL;
2651 		if ((rc = __ns_ldap_getParam(NS_LDAP_BINDDN_P,
2652 		    &paramVal, &errorp)) != NS_LDAP_SUCCESS) {
2653 			(void) __ns_ldap_freeCred(authp);
2654 			(void) __ns_ldap_freeError(&errorp);
2655 			*authp = NULL;
2656 			return (rc);
2657 		}
2658 
2659 		if (paramVal == NULL || *paramVal == NULL) {
2660 			(void) __ns_ldap_freeCred(authp);
2661 			*authp = NULL;
2662 			return (NS_LDAP_INVALID_PARAM);
2663 		}
2664 
2665 		(*authp)->cred.unix_cred.userID = strdup((char *)*paramVal);
2666 		(void) __ns_ldap_freeParam(&paramVal);
2667 		if ((*authp)->cred.unix_cred.userID == NULL) {
2668 			(void) __ns_ldap_freeCred(authp);
2669 			*authp = NULL;
2670 			return (NS_LDAP_MEMORY);
2671 		}
2672 	}
2673 	if (getPasswd) {
2674 		paramVal = NULL;
2675 		if ((rc = __ns_ldap_getParam(NS_LDAP_BINDPASSWD_P,
2676 		    &paramVal, &errorp)) != NS_LDAP_SUCCESS) {
2677 			(void) __ns_ldap_freeCred(authp);
2678 			(void) __ns_ldap_freeError(&errorp);
2679 			*authp = NULL;
2680 			return (rc);
2681 		}
2682 
2683 		if (paramVal == NULL || *paramVal == NULL) {
2684 			(void) __ns_ldap_freeCred(authp);
2685 			*authp = NULL;
2686 			return (NS_LDAP_INVALID_PARAM);
2687 		}
2688 
2689 		modparamVal = dvalue((char *)*paramVal);
2690 		(void) __ns_ldap_freeParam(&paramVal);
2691 		if (modparamVal == NULL || (strlen((char *)modparamVal) == 0)) {
2692 			(void) __ns_ldap_freeCred(authp);
2693 			if (modparamVal != NULL)
2694 				free(modparamVal);
2695 			*authp = NULL;
2696 			return (NS_LDAP_INVALID_PARAM);
2697 		}
2698 
2699 		(*authp)->cred.unix_cred.passwd = modparamVal;
2700 	}
2701 	if (getCertpath) {
2702 		paramVal = NULL;
2703 		if ((rc = __ns_ldap_getParam(NS_LDAP_HOST_CERTPATH_P,
2704 		    &paramVal, &errorp)) != NS_LDAP_SUCCESS) {
2705 			(void) __ns_ldap_freeCred(authp);
2706 			(void) __ns_ldap_freeError(&errorp);
2707 			*authp = NULL;
2708 			return (rc);
2709 		}
2710 
2711 		if (paramVal == NULL || *paramVal == NULL) {
2712 			(void) __ns_ldap_freeCred(authp);
2713 			*authp = NULL;
2714 			return (NS_LDAP_INVALID_PARAM);
2715 		}
2716 
2717 		(*authp)->hostcertpath = strdup((char *)*paramVal);
2718 		(void) __ns_ldap_freeParam(&paramVal);
2719 		if ((*authp)->hostcertpath == NULL) {
2720 			(void) __ns_ldap_freeCred(authp);
2721 			*authp = NULL;
2722 			return (NS_LDAP_MEMORY);
2723 		}
2724 	}
2725 	return (NS_LDAP_SUCCESS);
2726 }
2727 
2728 /*
2729  * FUNCTION:	__s_api_getConnection
2730  *
2731  *	Bind to the specified server or one from the server
2732  *	list and return the pointer.
2733  *
2734  *	This function can rebind or not (NS_LDAP_HARD), it can require a
2735  *	credential or bind anonymously
2736  *
2737  *	This function follows the DUA configuration schema algorithm
2738  *
2739  * RETURN VALUES:
2740  *
2741  * NS_LDAP_SUCCESS	A connection was made successfully.
2742  * NS_LDAP_SUCCESS_WITH_INFO
2743  * 			A connection was made successfully, but with
2744  *			password management info in *errorp
2745  * NS_LDAP_INVALID_PARAM If any invalid arguments were passed to the function.
2746  * NS_LDAP_CONFIG	If there are any config errors.
2747  * NS_LDAP_MEMORY	Memory errors.
2748  * NS_LDAP_INTERNAL	If there was a ldap error.
2749  *
2750  * INPUT:
2751  *
2752  * server	Bind to this LDAP server only
2753  * flags	If NS_LDAP_HARD is set function will not return until it has
2754  *		a connection unless there is a authentication problem.
2755  *		If NS_LDAP_NEW_CONN is set the function must force a new
2756  *              connection to be created
2757  *		If NS_LDAP_KEEP_CONN is set the connection is to be kept open
2758  * auth		Credentials for bind. This could be NULL in which case
2759  *		a default cred built from the config module is used.
2760  * sessionId	cookie that points to a previous session
2761  * fail_if_new_pwd_reqd
2762  *		a flag indicating this function should fail if the passwd
2763  *		in auth needs to change immediately
2764  * nopasswd_acct_mgmt
2765  *		a flag indicating that makeConnection should check before
2766  *		binding if server supports LDAP V3 password less
2767  *		account management
2768  *
2769  * OUTPUT:
2770  *
2771  * session	pointer to a session with connection information
2772  * errorp	Set if there are any INTERNAL, or CONFIG error.
2773  */
2774 int
2775 __s_api_getConnection(
2776 	const char *server,
2777 	const int flags,
2778 	const ns_cred_t *cred,		/* credentials for bind */
2779 	ConnectionID *sessionId,
2780 	Connection **session,
2781 	ns_ldap_error_t **errorp,
2782 	int fail_if_new_pwd_reqd,
2783 	int nopasswd_acct_mgmt)
2784 {
2785 	char		errmsg[MAXERROR];
2786 	ns_auth_t	**aMethod = NULL;
2787 	ns_auth_t	**aNext = NULL;
2788 	int		**cLevel = NULL;
2789 	int		**cNext = NULL;
2790 	int		timeoutSec = NS_DEFAULT_BIND_TIMEOUT;
2791 	int		rc;
2792 	Connection	*con = NULL;
2793 	int		sec = 1;
2794 	ns_cred_t 	*authp = NULL;
2795 	ns_cred_t	anon;
2796 	int		version = NS_LDAP_V2, self_gssapi_only = 0;
2797 	void		**paramVal = NULL;
2798 	char		**badSrvrs = NULL; /* List of problem hostnames */
2799 
2800 	if ((session == NULL) || (sessionId == NULL)) {
2801 		return (NS_LDAP_INVALID_PARAM);
2802 	}
2803 	*session = NULL;
2804 
2805 	/* if we already have a session id try to reuse connection */
2806 	if (*sessionId > 0) {
2807 		rc = findConnectionById(flags, cred, *sessionId, &con);
2808 		if (rc == *sessionId && con) {
2809 			*session = con;
2810 			return (NS_LDAP_SUCCESS);
2811 		}
2812 		*sessionId = 0;
2813 	}
2814 
2815 	/* get profile version number */
2816 	if ((rc = __ns_ldap_getParam(NS_LDAP_FILE_VERSION_P,
2817 	    &paramVal, errorp)) != NS_LDAP_SUCCESS)
2818 		return (rc);
2819 	if (paramVal == NULL) {
2820 		(void) sprintf(errmsg, gettext("getConnection: no file "
2821 		    "version"));
2822 		MKERROR(LOG_WARNING, *errorp, NS_CONFIG_FILE, strdup(errmsg),
2823 		    NS_LDAP_CONFIG);
2824 		return (NS_LDAP_CONFIG);
2825 	}
2826 	if (strcasecmp((char *)*paramVal, NS_LDAP_VERSION_1) == 0)
2827 		version = NS_LDAP_V1;
2828 	(void) __ns_ldap_freeParam((void ***)&paramVal);
2829 
2830 	/* Get the bind timeout value */
2831 	(void) __ns_ldap_getParam(NS_LDAP_BIND_TIME_P, &paramVal, errorp);
2832 	if (paramVal != NULL && *paramVal != NULL) {
2833 		timeoutSec = **((int **)paramVal);
2834 		(void) __ns_ldap_freeParam(&paramVal);
2835 	}
2836 	if (*errorp)
2837 		(void) __ns_ldap_freeError(errorp);
2838 
2839 	if (cred == NULL) {
2840 		/* Get the authentication method list */
2841 		if ((rc = __ns_ldap_getParam(NS_LDAP_AUTH_P,
2842 		    (void ***)&aMethod, errorp)) != NS_LDAP_SUCCESS)
2843 			return (rc);
2844 		if (aMethod == NULL) {
2845 			aMethod = (ns_auth_t **)calloc(2, sizeof (ns_auth_t *));
2846 			if (aMethod == NULL)
2847 				return (NS_LDAP_MEMORY);
2848 			aMethod[0] = (ns_auth_t *)calloc(1, sizeof (ns_auth_t));
2849 			if (aMethod[0] == NULL) {
2850 				free(aMethod);
2851 				return (NS_LDAP_MEMORY);
2852 			}
2853 			if (version == NS_LDAP_V1)
2854 				(aMethod[0])->type = NS_LDAP_AUTH_SIMPLE;
2855 			else {
2856 				(aMethod[0])->type = NS_LDAP_AUTH_SASL;
2857 				(aMethod[0])->saslmech =
2858 				    NS_LDAP_SASL_DIGEST_MD5;
2859 				(aMethod[0])->saslopt = NS_LDAP_SASLOPT_NONE;
2860 			}
2861 		}
2862 
2863 		/* Get the credential level list */
2864 		if ((rc = __ns_ldap_getParam(NS_LDAP_CREDENTIAL_LEVEL_P,
2865 		    (void ***)&cLevel, errorp)) != NS_LDAP_SUCCESS) {
2866 			(void) __ns_ldap_freeParam((void ***)&aMethod);
2867 			return (rc);
2868 		}
2869 		if (cLevel == NULL) {
2870 			cLevel = (int **)calloc(2, sizeof (int *));
2871 			if (cLevel == NULL)
2872 				return (NS_LDAP_MEMORY);
2873 			cLevel[0] = (int *)calloc(1, sizeof (int));
2874 			if (cLevel[0] == NULL)
2875 				return (NS_LDAP_MEMORY);
2876 			if (version == NS_LDAP_V1)
2877 				*(cLevel[0]) = NS_LDAP_CRED_PROXY;
2878 			else
2879 				*(cLevel[0]) = NS_LDAP_CRED_ANON;
2880 		}
2881 	}
2882 
2883 	/* setup the anon credential for anonymous connection */
2884 	(void) memset(&anon, 0, sizeof (ns_cred_t));
2885 	anon.auth.type = NS_LDAP_AUTH_NONE;
2886 
2887 	for (; ; ) {
2888 		if (cred != NULL) {
2889 			/* using specified auth method */
2890 			rc = makeConnection(&con, server, cred,
2891 			    sessionId, timeoutSec, errorp,
2892 			    fail_if_new_pwd_reqd,
2893 			    nopasswd_acct_mgmt, flags, &badSrvrs);
2894 			/* not using bad server if credentials were supplied */
2895 			if (badSrvrs && *badSrvrs) {
2896 				__s_api_free2dArray(badSrvrs);
2897 				badSrvrs = NULL;
2898 			}
2899 			if (rc == NS_LDAP_SUCCESS ||
2900 			    rc == NS_LDAP_SUCCESS_WITH_INFO) {
2901 				*session = con;
2902 				break;
2903 			}
2904 		} else {
2905 			self_gssapi_only = __s_api_self_gssapi_only_get();
2906 			/* for every cred level */
2907 			for (cNext = cLevel; *cNext != NULL; cNext++) {
2908 				if (self_gssapi_only &&
2909 				    **cNext != NS_LDAP_CRED_SELF)
2910 					continue;
2911 				if (**cNext == NS_LDAP_CRED_ANON) {
2912 					/*
2913 					 * make connection anonymously
2914 					 * Free the down server list before
2915 					 * looping through
2916 					 */
2917 					if (badSrvrs && *badSrvrs) {
2918 						__s_api_free2dArray(badSrvrs);
2919 						badSrvrs = NULL;
2920 					}
2921 					rc = makeConnection(&con, server, &anon,
2922 					    sessionId, timeoutSec, errorp,
2923 					    fail_if_new_pwd_reqd,
2924 					    nopasswd_acct_mgmt, flags,
2925 					    &badSrvrs);
2926 					if (rc == NS_LDAP_SUCCESS ||
2927 					    rc ==
2928 					    NS_LDAP_SUCCESS_WITH_INFO) {
2929 						*session = con;
2930 						goto done;
2931 					}
2932 					continue;
2933 				}
2934 				/* for each cred level */
2935 				for (aNext = aMethod; *aNext != NULL; aNext++) {
2936 					if (self_gssapi_only &&
2937 					    (*aNext)->saslmech !=
2938 					    NS_LDAP_SASL_GSSAPI)
2939 						continue;
2940 					/*
2941 					 * self coexists with sasl/GSSAPI only
2942 					 * and non-self coexists with non-gssapi
2943 					 * only
2944 					 */
2945 					if ((**cNext == NS_LDAP_CRED_SELF &&
2946 					    (*aNext)->saslmech !=
2947 					    NS_LDAP_SASL_GSSAPI) ||
2948 					    (**cNext != NS_LDAP_CRED_SELF &&
2949 					    (*aNext)->saslmech ==
2950 					    NS_LDAP_SASL_GSSAPI))
2951 						continue;
2952 					/* make connection and authenticate */
2953 					/* with default credentials */
2954 					authp = NULL;
2955 					rc = __s_api_getDefaultAuth(*cNext,
2956 					    *aNext, &authp);
2957 					if (rc != NS_LDAP_SUCCESS) {
2958 						continue;
2959 					}
2960 					/*
2961 					 * Free the down server list before
2962 					 * looping through
2963 					 */
2964 					if (badSrvrs && *badSrvrs) {
2965 						__s_api_free2dArray(badSrvrs);
2966 						badSrvrs = NULL;
2967 					}
2968 					rc = makeConnection(&con, server, authp,
2969 					    sessionId, timeoutSec, errorp,
2970 					    fail_if_new_pwd_reqd,
2971 					    nopasswd_acct_mgmt, flags,
2972 					    &badSrvrs);
2973 					(void) __ns_ldap_freeCred(&authp);
2974 					if (rc == NS_LDAP_SUCCESS ||
2975 					    rc ==
2976 					    NS_LDAP_SUCCESS_WITH_INFO) {
2977 						*session = con;
2978 						goto done;
2979 					}
2980 				}
2981 			}
2982 		}
2983 		if (flags & NS_LDAP_HARD) {
2984 			if (sec < LDAPMAXHARDLOOKUPTIME)
2985 				sec *= 2;
2986 			_sleep(sec);
2987 		} else {
2988 			break;
2989 		}
2990 	}
2991 
2992 done:
2993 	/*
2994 	 * If unable to get a connection, and this is
2995 	 * the thread opening the shared connection,
2996 	 * unlock the session mutex and let other
2997 	 * threads try to get their own connection.
2998 	 */
2999 	if (wait4session != 0 && sessionTid == thr_self()) {
3000 		wait4session = 0;
3001 		sessionTid = 0;
3002 #ifdef DEBUG
3003 		(void) fprintf(stderr, "tid= %d: __s_api_getConnection: "
3004 		    "unlocking sessionLock \n", thr_self());
3005 		fflush(stderr);
3006 #endif /* DEBUG */
3007 		(void) mutex_unlock(&sessionLock);
3008 	}
3009 	if (self_gssapi_only && rc == NS_LDAP_SUCCESS && *session == NULL) {
3010 		/*
3011 		 * self_gssapi_only is true but no self/sasl/gssapi is
3012 		 * configured
3013 		 */
3014 		rc = NS_LDAP_CONFIG;
3015 	}
3016 
3017 	(void) __ns_ldap_freeParam((void ***)&aMethod);
3018 	(void) __ns_ldap_freeParam((void ***)&cLevel);
3019 
3020 	if (badSrvrs && *badSrvrs) {
3021 		/*
3022 		 * At this point, either we have a successful
3023 		 * connection or exhausted all the possible auths.
3024 		 * and creds. Mark the problem servers as down
3025 		 * so that the problem servers are not contacted
3026 		 * again until the refresh_ttl expires.
3027 		 */
3028 		(void) __s_api_removeBadServers(badSrvrs);
3029 		__s_api_free2dArray(badSrvrs);
3030 	}
3031 	return (rc);
3032 }
3033 
3034 #pragma fini(_free_sessionPool)
3035 static void
3036 _free_sessionPool()
3037 {
3038 	int id;
3039 
3040 	(void) rw_wrlock(&sessionPoolLock);
3041 	if (sessionPool != NULL) {
3042 		for (id = 0; id < sessionPoolSize; id++)
3043 			_DropConnection(id + CONID_OFFSET, 0, 1);
3044 		free(sessionPool);
3045 		sessionPool = NULL;
3046 		sessionPoolSize = 0;
3047 	}
3048 	(void) rw_unlock(&sessionPoolLock);
3049 }
3050