xref: /titanic_41/usr/src/lib/libadutils/common/adutils.c (revision b509e89b2befbaa42939abad9da1d7f5a8c6aaae)
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 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <alloca.h>
27 #include <string.h>
28 #include <strings.h>
29 #include <lber.h>
30 #include <sasl/sasl.h>
31 #include <string.h>
32 #include <ctype.h>
33 #include <synch.h>
34 #include <atomic.h>
35 #include <errno.h>
36 #include <assert.h>
37 #include <limits.h>
38 #include <syslog.h>
39 #include <sys/u8_textprep.h>
40 #include <sys/varargs.h>
41 #include "libadutils.h"
42 #include "adutils_impl.h"
43 
44 /* List of DSs, needed by the idle connection reaper thread */
45 static pthread_mutex_t	adhostlock = PTHREAD_MUTEX_INITIALIZER;
46 static adutils_host_t	*host_head = NULL;
47 
48 /*
49  * List of query state structs -- needed so we can "route" LDAP results
50  * to the right context if multiple threads should be using the same
51  * connection concurrently
52  */
53 static pthread_mutex_t		qstatelock = PTHREAD_MUTEX_INITIALIZER;
54 static adutils_query_state_t	*qstatehead = NULL;
55 
56 static char *adutils_sid_ber2str(BerValue *bvalues);
57 static void adutils_lookup_batch_unlock(adutils_query_state_t **state);
58 static void delete_ds(adutils_ad_t *ad, const char *host, int port);
59 
60 typedef struct binary_attrs {
61 	const char	*name;
62 	char		*(*ber2str)(BerValue *bvalues);
63 } binary_attrs_t;
64 
65 static binary_attrs_t binattrs[] = {
66 	{"objectSID", adutils_sid_ber2str},
67 	{NULL, NULL}
68 };
69 
70 
71 adutils_logger logger = syslog;
72 
73 
74 void
75 adutils_set_logger(adutils_logger funct)
76 {
77 	logger = funct;
78 }
79 
80 
81 /*
82  * Turn "foo.bar.com" into "dc=foo,dc=bar,dc=com"
83  */
84 static
85 char *
86 adutils_dns2dn(const char *dns)
87 {
88 	int num_parts;
89 
90 	return (ldap_dns_to_dn((char *)dns, &num_parts));
91 }
92 
93 
94 /*
95  * Turn "dc=foo,dc=bar,dc=com" into "foo.bar.com"; ignores any other
96  * attributes (CN, etc...).
97  */
98 char *
99 adutils_dn2dns(const char *dn)
100 {
101 	return (DN_to_DNS(dn));
102 }
103 
104 
105 /*
106  * Convert a binary SID in a BerValue to a adutils_sid_t
107  */
108 int
109 adutils_getsid(BerValue *bval, adutils_sid_t *sidp)
110 {
111 	int		i, j;
112 	uchar_t		*v;
113 	uint32_t	a;
114 
115 	/*
116 	 * The binary format of a SID is as follows:
117 	 *
118 	 * byte #0: version, always 0x01
119 	 * byte #1: RID count, always <= 0x0f
120 	 * bytes #2-#7: SID authority, big-endian 48-bit unsigned int
121 	 *
122 	 * followed by RID count RIDs, each a little-endian, unsigned
123 	 * 32-bit int.
124 	 */
125 	/*
126 	 * Sanity checks: must have at least one RID, version must be
127 	 * 0x01, and the length must be 8 + rid count * 4
128 	 */
129 	if (bval->bv_len > 8 && bval->bv_val[0] == 0x01 &&
130 	    bval->bv_len == 1 + 1 + 6 + bval->bv_val[1] * 4) {
131 		v = (uchar_t *)bval->bv_val;
132 		sidp->version = v[0];
133 		sidp->sub_authority_count = v[1];
134 		sidp->authority =
135 		    /* big endian -- so start from the left */
136 		    ((u_longlong_t)v[2] << 40) |
137 		    ((u_longlong_t)v[3] << 32) |
138 		    ((u_longlong_t)v[4] << 24) |
139 		    ((u_longlong_t)v[5] << 16) |
140 		    ((u_longlong_t)v[6] << 8) |
141 		    (u_longlong_t)v[7];
142 		for (i = 0; i < sidp->sub_authority_count; i++) {
143 			j = 8 + (i * 4);
144 			/* little endian -- so start from the right */
145 			a = (v[j + 3] << 24) | (v[j + 2] << 16) |
146 			    (v[j + 1] << 8) | (v[j]);
147 			sidp->sub_authorities[i] = a;
148 		}
149 		return (0);
150 	}
151 	return (-1);
152 }
153 
154 /*
155  * Convert a adutils_sid_t to S-1-...
156  */
157 char *
158 adutils_sid2txt(adutils_sid_t *sidp)
159 {
160 	int	rlen, i, len;
161 	char	*str, *cp;
162 
163 	if (sidp->version != 1)
164 		return (NULL);
165 
166 	len = sizeof ("S-1-") - 1;
167 
168 	/*
169 	 * We could optimize like so, but, why?
170 	 *	if (sidp->authority < 10)
171 	 *		len += 2;
172 	 *	else if (sidp->authority < 100)
173 	 *		len += 3;
174 	 *	else
175 	 *		len += snprintf(NULL, 0"%llu", sidp->authority);
176 	 */
177 	len += snprintf(NULL, 0, "%llu", sidp->authority);
178 
179 	/* Max length of a uint32_t printed out in ASCII is 10 bytes */
180 	len += 1 + (sidp->sub_authority_count + 1) * 10;
181 
182 	if ((cp = str = malloc(len)) == NULL)
183 		return (NULL);
184 
185 	rlen = snprintf(str, len, "S-1-%llu", sidp->authority);
186 
187 	cp += rlen;
188 	len -= rlen;
189 
190 	for (i = 0; i < sidp->sub_authority_count; i++) {
191 		assert(len > 0);
192 		rlen = snprintf(cp, len, "-%u", sidp->sub_authorities[i]);
193 		cp += rlen;
194 		len -= rlen;
195 		assert(len >= 0);
196 	}
197 
198 	return (str);
199 }
200 
201 /*
202  * Convert a adutils_sid_t to on-the-wire encoding
203  */
204 static
205 int
206 sid2binsid(adutils_sid_t *sid, uchar_t *binsid, int binsidlen)
207 {
208 	uchar_t		*p;
209 	int		i;
210 	uint64_t	a;
211 	uint32_t	r;
212 
213 	if (sid->version != 1 ||
214 	    binsidlen != (1 + 1 + 6 + sid->sub_authority_count * 4))
215 		return (-1);
216 
217 	p = binsid;
218 	*p++ = 0x01;		/* version */
219 	/* sub authority count */
220 	*p++ = sid->sub_authority_count;
221 	/* Authority */
222 	a = sid->authority;
223 	/* big-endian -- start from left */
224 	*p++ = (a >> 40) & 0xFF;
225 	*p++ = (a >> 32) & 0xFF;
226 	*p++ = (a >> 24) & 0xFF;
227 	*p++ = (a >> 16) & 0xFF;
228 	*p++ = (a >> 8) & 0xFF;
229 	*p++ = a & 0xFF;
230 
231 	/* sub-authorities */
232 	for (i = 0; i < sid->sub_authority_count; i++) {
233 		r = sid->sub_authorities[i];
234 		/* little-endian -- start from right */
235 		*p++ = (r & 0x000000FF);
236 		*p++ = (r & 0x0000FF00) >> 8;
237 		*p++ = (r & 0x00FF0000) >> 16;
238 		*p++ = (r & 0xFF000000) >> 24;
239 	}
240 
241 	return (0);
242 }
243 
244 /*
245  * Convert a stringified SID (S-1-...) into a hex-encoded version of the
246  * on-the-wire encoding, but with each pair of hex digits pre-pended
247  * with a '\', so we can pass this to libldap.
248  */
249 int
250 adutils_txtsid2hexbinsid(const char *txt, const uint32_t *rid,
251 	char *hexbinsid, int hexbinsidlen)
252 {
253 	adutils_sid_t	sid = { 0 };
254 	int		i, j;
255 	const char	*cp;
256 	char		*ecp;
257 	u_longlong_t	a;
258 	unsigned long	r;
259 	uchar_t		*binsid, b, hb;
260 
261 	/* Only version 1 SIDs please */
262 	if (strncmp(txt, "S-1-", strlen("S-1-")) != 0)
263 		return (-1);
264 
265 	if (strlen(txt) < (strlen("S-1-") + 1))
266 		return (-1);
267 
268 	/* count '-'s */
269 	for (j = 0, cp = strchr(txt, '-');
270 	    cp != NULL && *cp != '\0';
271 	    j++, cp = strchr(cp + 1, '-')) {
272 		/* can't end on a '-' */
273 		if (*(cp + 1) == '\0')
274 			return (-1);
275 	}
276 
277 	/* Adjust count for version and authority */
278 	j -= 2;
279 
280 	/* we know the version number and RID count */
281 	sid.version = 1;
282 	sid.sub_authority_count = (rid != NULL) ? j + 1 : j;
283 
284 	/* must have at least one RID, but not too many */
285 	if (sid.sub_authority_count < 1 ||
286 	    sid.sub_authority_count > ADUTILS_SID_MAX_SUB_AUTHORITIES)
287 		return (-1);
288 
289 	/* check that we only have digits and '-' */
290 	if (strspn(txt + 1, "0123456789-") < (strlen(txt) - 1))
291 		return (-1);
292 
293 	cp = txt + strlen("S-1-");
294 
295 	/* 64-bit safe parsing of unsigned 48-bit authority value */
296 	errno = 0;
297 	a = strtoull(cp, &ecp, 10);
298 
299 	/* errors parsing the authority or too many bits */
300 	if (cp == ecp || (a == 0 && errno == EINVAL) ||
301 	    (a == ULLONG_MAX && errno == ERANGE) ||
302 	    (a & 0x0000ffffffffffffULL) != a)
303 		return (-1);
304 
305 	cp = ecp;
306 
307 	sid.authority = (uint64_t)a;
308 
309 	for (i = 0; i < j; i++) {
310 		if (*cp++ != '-')
311 			return (-1);
312 		/* 64-bit safe parsing of unsigned 32-bit RID */
313 		errno = 0;
314 		r = strtoul(cp, &ecp, 10);
315 		/* errors parsing the RID or too many bits */
316 		if (cp == ecp || (r == 0 && errno == EINVAL) ||
317 		    (r == ULONG_MAX && errno == ERANGE) ||
318 		    (r & 0xffffffffUL) != r)
319 			return (-1);
320 		sid.sub_authorities[i] = (uint32_t)r;
321 		cp = ecp;
322 	}
323 
324 	/* check that all of the string SID has been consumed */
325 	if (*cp != '\0')
326 		return (-1);
327 
328 	if (rid != NULL)
329 		sid.sub_authorities[j] = *rid;
330 
331 	j = 1 + 1 + 6 + sid.sub_authority_count * 4;
332 
333 	if (hexbinsidlen < (j * 3))
334 		return (-2);
335 
336 	/* binary encode the SID */
337 	binsid = (uchar_t *)alloca(j);
338 	(void) sid2binsid(&sid, binsid, j);
339 
340 	/* hex encode, with a backslash before each byte */
341 	for (ecp = hexbinsid, i = 0; i < j; i++) {
342 		b = binsid[i];
343 		*ecp++ = '\\';
344 		hb = (b >> 4) & 0xF;
345 		*ecp++ = (hb <= 0x9 ? hb + '0' : hb - 10 + 'A');
346 		hb = b & 0xF;
347 		*ecp++ = (hb <= 0x9 ? hb + '0' : hb - 10 + 'A');
348 	}
349 	*ecp = '\0';
350 
351 	return (0);
352 }
353 
354 static
355 char *
356 convert_bval2sid(BerValue *bval, uint32_t *rid)
357 {
358 	adutils_sid_t	sid;
359 
360 	if (adutils_getsid(bval, &sid) < 0)
361 		return (NULL);
362 
363 	/*
364 	 * If desired and if the SID is what should be a domain/computer
365 	 * user or group SID (i.e., S-1-5-w-x-y-z-<user/group RID>) then
366 	 * save the last RID and truncate the SID
367 	 */
368 	if (rid != NULL && sid.authority == 5 && sid.sub_authority_count == 5)
369 		*rid = sid.sub_authorities[--sid.sub_authority_count];
370 	return (adutils_sid2txt(&sid));
371 }
372 
373 
374 /*
375  * Return a NUL-terminated stringified SID from the value of an
376  * objectSid attribute and put the last RID in *rid.
377  */
378 char *
379 adutils_bv_objsid2sidstr(BerValue *bval, uint32_t *rid)
380 {
381 	char *sid;
382 
383 	if (bval == NULL)
384 		return (NULL);
385 	/* objectSid is single valued */
386 	if ((sid = convert_bval2sid(bval, rid)) == NULL)
387 		return (NULL);
388 	return (sid);
389 }
390 
391 static
392 char *
393 adutils_sid_ber2str(BerValue *bval)
394 {
395 	return (adutils_bv_objsid2sidstr(bval, NULL));
396 }
397 
398 
399 /* Return a NUL-terminated string from the Ber value */
400 char *
401 adutils_bv_name2str(BerValue *bval)
402 {
403 	char *s;
404 
405 	if (bval == NULL || bval->bv_val == NULL)
406 		return (NULL);
407 	if ((s = malloc(bval->bv_len + 1)) == NULL)
408 		return (NULL);
409 	(void) snprintf(s, bval->bv_len + 1, "%.*s", bval->bv_len,
410 	    bval->bv_val);
411 	return (s);
412 }
413 
414 /*ARGSUSED*/
415 int
416 saslcallback(LDAP *ld, unsigned flags, void *defaults, void *prompts)
417 {
418 	sasl_interact_t	*interact;
419 
420 	if (prompts == NULL || flags != LDAP_SASL_INTERACTIVE)
421 		return (LDAP_PARAM_ERROR);
422 
423 	/* There should be no extra arguemnts for SASL/GSSAPI authentication */
424 	for (interact = prompts; interact->id != SASL_CB_LIST_END;
425 	    interact++) {
426 		interact->result = NULL;
427 		interact->len = 0;
428 	}
429 	return (LDAP_SUCCESS);
430 }
431 
432 
433 #define	ADCONN_TIME	300
434 
435 /*
436  * Idle connection reaping side of connection management
437  */
438 void
439 adutils_reap_idle_connections()
440 {
441 	adutils_host_t	*adh;
442 	time_t		now;
443 
444 	(void) pthread_mutex_lock(&adhostlock);
445 	now = time(NULL);
446 	for (adh = host_head; adh != NULL; adh = adh->next) {
447 		(void) pthread_mutex_lock(&adh->lock);
448 		if (adh->ref == 0 && adh->idletime != 0 &&
449 		    adh->idletime + ADCONN_TIME < now) {
450 			if (adh->ld) {
451 				(void) ldap_unbind(adh->ld);
452 				adh->ld = NULL;
453 				adh->idletime = 0;
454 				adh->ref = 0;
455 			}
456 		}
457 		(void) pthread_mutex_unlock(&adh->lock);
458 	}
459 	(void) pthread_mutex_unlock(&adhostlock);
460 }
461 
462 
463 adutils_rc
464 adutils_ad_alloc(adutils_ad_t **new_ad, const char *default_domain,
465 	adutils_ad_partition_t part)
466 {
467 	adutils_ad_t *ad;
468 
469 	*new_ad = NULL;
470 
471 	if ((default_domain == NULL || *default_domain == '\0') &&
472 	    part != ADUTILS_AD_GLOBAL_CATALOG)
473 		return (ADUTILS_ERR_DOMAIN);
474 	if ((ad = calloc(1, sizeof (*ad))) == NULL)
475 		return (ADUTILS_ERR_MEMORY);
476 	ad->ref = 1;
477 	ad->partition = part;
478 	if (default_domain == NULL)
479 		default_domain = "";
480 	if ((ad->dflt_w2k_dom = strdup(default_domain)) == NULL)
481 		goto err;
482 	if (pthread_mutex_init(&ad->lock, NULL) != 0)
483 		goto err;
484 	*new_ad = ad;
485 	return (ADUTILS_SUCCESS);
486 
487 err:
488 	if (ad->dflt_w2k_dom != NULL)
489 		free(ad->dflt_w2k_dom);
490 	free(ad);
491 	return (ADUTILS_ERR_MEMORY);
492 }
493 
494 void
495 adutils_ad_free(adutils_ad_t **ad)
496 {
497 	adutils_host_t *p;
498 	adutils_host_t *prev;
499 
500 	if (ad == NULL || *ad == NULL)
501 		return;
502 
503 	(void) pthread_mutex_lock(&(*ad)->lock);
504 
505 	if (atomic_dec_32_nv(&(*ad)->ref) > 0) {
506 		(void) pthread_mutex_unlock(&(*ad)->lock);
507 		*ad = NULL;
508 		return;
509 	}
510 
511 	(void) pthread_mutex_lock(&adhostlock);
512 	prev = NULL;
513 	p = host_head;
514 	while (p != NULL) {
515 		if (p->owner != (*ad)) {
516 			prev = p;
517 			p = p->next;
518 			continue;
519 		} else {
520 			delete_ds((*ad), p->host, p->port);
521 			if (prev == NULL)
522 				p = host_head;
523 			else
524 				p = prev->next;
525 		}
526 	}
527 	(void) pthread_mutex_unlock(&adhostlock);
528 
529 	(void) pthread_mutex_unlock(&(*ad)->lock);
530 	(void) pthread_mutex_destroy(&(*ad)->lock);
531 
532 	if ((*ad)->known_domains)
533 		free((*ad)->known_domains);
534 	free((*ad)->dflt_w2k_dom);
535 	free(*ad);
536 
537 	*ad = NULL;
538 }
539 
540 static
541 int
542 open_conn(adutils_host_t *adh, int timeoutsecs)
543 {
544 	int zero = 0;
545 	int ldversion, rc;
546 	int timeoutms = timeoutsecs * 1000;
547 
548 	if (adh == NULL)
549 		return (0);
550 
551 	(void) pthread_mutex_lock(&adh->lock);
552 
553 	if (!adh->dead && adh->ld != NULL)
554 		/* done! */
555 		goto out;
556 
557 	if (adh->ld != NULL) {
558 		(void) ldap_unbind(adh->ld);
559 		adh->ld = NULL;
560 	}
561 	adh->num_requests = 0;
562 
563 	atomic_inc_64(&adh->generation);
564 
565 	/* Open and bind an LDAP connection */
566 	adh->ld = ldap_init(adh->host, adh->port);
567 	if (adh->ld == NULL) {
568 		logger(LOG_INFO, "ldap_init() to server "
569 		    "%s port %d failed. (%s)", adh->host,
570 		    adh->port, strerror(errno));
571 		goto out;
572 	}
573 	ldversion = LDAP_VERSION3;
574 	(void) ldap_set_option(adh->ld, LDAP_OPT_PROTOCOL_VERSION, &ldversion);
575 	(void) ldap_set_option(adh->ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF);
576 	(void) ldap_set_option(adh->ld, LDAP_OPT_TIMELIMIT, &zero);
577 	(void) ldap_set_option(adh->ld, LDAP_OPT_SIZELIMIT, &zero);
578 	(void) ldap_set_option(adh->ld, LDAP_X_OPT_CONNECT_TIMEOUT, &timeoutms);
579 	(void) ldap_set_option(adh->ld, LDAP_OPT_RESTART, LDAP_OPT_ON);
580 	rc = ldap_sasl_interactive_bind_s(adh->ld, "" /* binddn */,
581 	    adh->saslmech, NULL, NULL, adh->saslflags, &saslcallback,
582 	    NULL);
583 
584 	if (rc != LDAP_SUCCESS) {
585 		(void) ldap_unbind(adh->ld);
586 		adh->ld = NULL;
587 		logger(LOG_INFO, "ldap_sasl_interactive_bind_s() to server "
588 		    "%s port %d failed. (%s)", adh->host, adh->port,
589 		    ldap_err2string(rc));
590 	}
591 
592 	logger(LOG_DEBUG, "Using global catalog server %s:%d",
593 	    adh->host, adh->port);
594 
595 out:
596 	if (adh->ld != NULL) {
597 		atomic_inc_32(&adh->ref);
598 		adh->idletime = time(NULL);
599 		adh->dead = 0;
600 		(void) pthread_mutex_unlock(&adh->lock);
601 		return (1);
602 	}
603 
604 	(void) pthread_mutex_unlock(&adh->lock);
605 	return (0);
606 }
607 
608 
609 /*
610  * Connection management: find an open connection or open one
611  */
612 static
613 adutils_host_t *
614 get_conn(adutils_ad_t *ad)
615 {
616 	adutils_host_t	*adh = NULL;
617 	int		tries;
618 	int		dscount = 0;
619 	int		timeoutsecs = ADUTILS_LDAP_OPEN_TIMEOUT;
620 
621 retry:
622 	(void) pthread_mutex_lock(&adhostlock);
623 
624 	if (host_head == NULL) {
625 		(void) pthread_mutex_unlock(&adhostlock);
626 		goto out;
627 	}
628 
629 	if (dscount == 0) {
630 		/*
631 		 * First try: count the number of DSes.
632 		 *
633 		 * Integer overflow is not an issue -- we can't have so many
634 		 * DSes because they won't fit even DNS over TCP, and SMF
635 		 * shouldn't let you set so many.
636 		 */
637 		for (adh = host_head, tries = 0; adh != NULL; adh = adh->next) {
638 			if (adh->owner == ad)
639 				dscount++;
640 		}
641 
642 		if (dscount == 0) {
643 			(void) pthread_mutex_unlock(&adhostlock);
644 			goto out;
645 		}
646 
647 		tries = dscount * 3;	/* three tries per-ds */
648 
649 		/*
650 		 * Begin round-robin at the next DS in the list after the last
651 		 * one that we had a connection to, else start with the first
652 		 * DS in the list.
653 		 */
654 		adh = ad->last_adh;
655 	}
656 
657 	/*
658 	 * Round-robin -- pick the next one on the list; if the list
659 	 * changes on us, no big deal, we'll just potentially go
660 	 * around the wrong number of times.
661 	 */
662 	for (;;) {
663 		if (adh != NULL && adh->owner == ad && adh->ld != NULL &&
664 		    !adh->dead)
665 			break;
666 		if (adh == NULL || (adh = adh->next) == NULL)
667 			adh = host_head;
668 		if (adh->owner == ad)
669 			break;
670 	}
671 
672 	ad->last_adh = adh;
673 	(void) pthread_mutex_unlock(&adhostlock);
674 
675 	/* Found suitable DS, open it if not already opened */
676 	if (open_conn(adh, timeoutsecs))
677 		return (adh);
678 
679 	tries--;
680 	if ((tries % dscount) == 0)
681 		timeoutsecs *= 2;
682 	if (tries > 0)
683 		goto retry;
684 
685 out:
686 	logger(LOG_NOTICE, "Couldn't open an LDAP connection to any global "
687 	    "catalog server!");
688 	return (NULL);
689 }
690 
691 static
692 void
693 release_conn(adutils_host_t *adh)
694 {
695 	int delete = 0;
696 
697 	(void) pthread_mutex_lock(&adh->lock);
698 	if (atomic_dec_32_nv(&adh->ref) == 0) {
699 		if (adh->owner == NULL)
700 			delete = 1;
701 		adh->idletime = time(NULL);
702 	}
703 	(void) pthread_mutex_unlock(&adh->lock);
704 
705 	/* Free this host if its owner no longer exists. */
706 	if (delete) {
707 		(void) pthread_mutex_lock(&adhostlock);
708 		delete_ds(NULL, adh->host, adh->port);
709 		(void) pthread_mutex_unlock(&adhostlock);
710 	}
711 }
712 
713 /*
714  * Create a adutils_host_t, populate it and add it to the list of hosts.
715  */
716 adutils_rc
717 adutils_add_ds(adutils_ad_t *ad, const char *host, int port)
718 {
719 	adutils_host_t	*p;
720 	adutils_host_t	*new = NULL;
721 	int		ret;
722 	adutils_rc	rc;
723 
724 	(void) pthread_mutex_lock(&adhostlock);
725 	for (p = host_head; p != NULL; p = p->next) {
726 		if (p->owner != ad)
727 			continue;
728 
729 		if (strcmp(host, p->host) == 0 && p->port == port) {
730 			/* already added */
731 			rc = ADUTILS_SUCCESS;
732 			goto err;
733 		}
734 	}
735 
736 	rc = ADUTILS_ERR_MEMORY;
737 
738 	/* add new entry */
739 	new = (adutils_host_t *)calloc(1, sizeof (*new));
740 	if (new == NULL)
741 		goto err;
742 	new->owner = ad;
743 	new->port = port;
744 	new->dead = 0;
745 	new->max_requests = 80;
746 	new->num_requests = 0;
747 	if ((new->host = strdup(host)) == NULL)
748 		goto err;
749 	new->saslflags = LDAP_SASL_INTERACTIVE;
750 	new->saslmech = "GSSAPI";
751 
752 	if ((ret = pthread_mutex_init(&new->lock, NULL)) != 0) {
753 		free(new->host);
754 		new->host = NULL;
755 		errno = ret;
756 		rc = ADUTILS_ERR_INTERNAL;
757 		goto err;
758 	}
759 
760 	/* link in */
761 	rc = ADUTILS_SUCCESS;
762 	new->next = host_head;
763 	host_head = new;
764 
765 err:
766 	(void) pthread_mutex_unlock(&adhostlock);
767 
768 	if (rc != 0 && new != NULL) {
769 		if (new->host != NULL) {
770 			(void) pthread_mutex_destroy(&new->lock);
771 			free(new->host);
772 		}
773 		free(new);
774 	}
775 
776 	return (rc);
777 }
778 
779 /*
780  * Free a DS configuration.
781  * Caller must lock the adhostlock mutex
782  */
783 static
784 void
785 delete_ds(adutils_ad_t *ad, const char *host, int port)
786 {
787 	adutils_host_t	**p, *q;
788 
789 	for (p = &host_head; *p != NULL; p = &((*p)->next)) {
790 		if ((*p)->owner != ad || strcmp(host, (*p)->host) != 0 ||
791 		    (*p)->port != port)
792 			continue;
793 		/* found */
794 
795 		(void) pthread_mutex_lock(&((*p)->lock));
796 		if ((*p)->ref > 0) {
797 			/*
798 			 * Still in use. Set its owner to NULL so
799 			 * that it can be freed when its ref count
800 			 * becomes 0.
801 			 */
802 			(*p)->owner = NULL;
803 			(void) pthread_mutex_unlock(&((*p)->lock));
804 			break;
805 		}
806 		(void) pthread_mutex_unlock(&((*p)->lock));
807 
808 		q = *p;
809 		*p = (*p)->next;
810 
811 		(void) pthread_mutex_destroy(&q->lock);
812 
813 		if (q->ld)
814 			(void) ldap_unbind(q->ld);
815 		if (q->host)
816 			free(q->host);
817 		free(q);
818 		break;
819 	}
820 
821 }
822 /*
823  * Add known domain name and domain SID to AD configuration.
824  */
825 
826 adutils_rc
827 adutils_add_domain(adutils_ad_t *ad, const char *domain, const char *sid)
828 {
829 	struct known_domain *new;
830 	int num = ad->num_known_domains;
831 
832 	ad->num_known_domains++;
833 	new = realloc(ad->known_domains,
834 	    sizeof (struct known_domain) * ad->num_known_domains);
835 	if (new != NULL) {
836 		ad->known_domains = new;
837 		(void) strlcpy(ad->known_domains[num].name, domain,
838 		    sizeof (ad->known_domains[num].name));
839 		(void) strlcpy(ad->known_domains[num].sid, sid,
840 		    sizeof (ad->known_domains[num].sid));
841 		return (ADUTILS_SUCCESS);
842 	} else {
843 		if (ad->known_domains != NULL) {
844 			free(ad->known_domains);
845 			ad->known_domains = NULL;
846 		}
847 		ad->num_known_domains = 0;
848 		return (ADUTILS_ERR_MEMORY);
849 	}
850 }
851 
852 
853 /*
854  * Check that this AD supports this domain.
855  * If there are no known domains assume that the
856  * domain is supported by this AD.
857  *
858  * Returns 1 if this domain is supported by this AD
859  * else returns 0;
860  */
861 
862 int
863 adutils_lookup_check_domain(adutils_query_state_t *qs, const char *domain)
864 {
865 	adutils_ad_t *ad = qs->qadh->owner;
866 	int i, err;
867 
868 	for (i = 0; i < ad->num_known_domains; i++) {
869 		if (u8_strcmp(domain, ad->known_domains[i].name, 0,
870 		    U8_STRCMP_CI_LOWER, U8_UNICODE_LATEST, &err) == 0 &&
871 		    err == 0)
872 			return (1);
873 	}
874 
875 	return ((i == 0) ? 1 : 0);
876 }
877 
878 
879 /*
880  * Check that this AD supports the SID prefix.
881  * The SID prefix should match the domain SID.
882  * If there are no known domains assume that the
883  * SID prefix is supported by this AD.
884  *
885  * Returns 1 if this sid prefix is supported by this AD
886  * else returns 0;
887  */
888 
889 int
890 adutils_lookup_check_sid_prefix(adutils_query_state_t *qs, const char *sid)
891 {
892 	adutils_ad_t *ad = qs->qadh->owner;
893 	int i;
894 
895 
896 	for (i = 0; i < ad->num_known_domains; i++) {
897 		if (strcmp(sid, ad->known_domains[i].sid) == 0)
898 			return (1);
899 	}
900 
901 	return ((i == 0) ? 1 : 0);
902 }
903 
904 
905 adutils_rc
906 adutils_lookup_batch_start(adutils_ad_t *ad, int nqueries,
907 	adutils_ldap_res_search_cb ldap_res_search_cb,
908 	void *ldap_res_search_argp,
909 	adutils_query_state_t **state)
910 {
911 	adutils_query_state_t	*new_state;
912 	adutils_host_t		*adh = NULL;
913 
914 	if (ad == NULL)
915 		return (ADUTILS_ERR_INTERNAL);
916 
917 	*state = NULL;
918 	adh = get_conn(ad);
919 	if (adh == NULL)
920 		return (ADUTILS_ERR_RETRIABLE_NET_ERR);
921 
922 	new_state = calloc(1, sizeof (adutils_query_state_t) +
923 	    (nqueries - 1) * sizeof (adutils_q_t));
924 	if (new_state == NULL)
925 		return (ADUTILS_ERR_MEMORY);
926 
927 	/*
928 	 * Save default domain from the ad object so that we don't
929 	 * have to access the 'ad' object later.
930 	 */
931 	new_state->default_domain = strdup(adh->owner->dflt_w2k_dom);
932 	if (new_state->default_domain == NULL) {
933 		free(new_state);
934 		return (ADUTILS_ERR_MEMORY);
935 	}
936 
937 	if (ad->partition == ADUTILS_AD_DATA)
938 		new_state->basedn = adutils_dns2dn(new_state->default_domain);
939 	else
940 		new_state->basedn = strdup("");
941 	if (new_state->basedn == NULL) {
942 		free(new_state->default_domain);
943 		free(new_state);
944 		return (ADUTILS_ERR_MEMORY);
945 	}
946 
947 	new_state->ref_cnt = 1;
948 	new_state->qadh = adh;
949 	new_state->qsize = nqueries;
950 	new_state->qadh_gen = adh->generation;
951 	new_state->qcount = 0;
952 	new_state->ldap_res_search_cb = ldap_res_search_cb;
953 	new_state->ldap_res_search_argp = ldap_res_search_argp;
954 	(void) pthread_cond_init(&new_state->cv, NULL);
955 
956 	(void) pthread_mutex_lock(&qstatelock);
957 	new_state->next = qstatehead;
958 	qstatehead = new_state;
959 	(void) pthread_mutex_unlock(&qstatelock);
960 	*state = new_state;
961 
962 	return (ADUTILS_SUCCESS);
963 }
964 
965 /*
966  * Find the adutils_query_state_t to which a given LDAP result msgid on a
967  * given connection belongs. This routine increaments the reference count
968  * so that the object can not be freed. adutils_lookup_batch_unlock()
969  * must be called to decreament the reference count.
970  */
971 static
972 int
973 msgid2query(adutils_host_t *adh, int msgid,
974 	adutils_query_state_t **state, int *qid)
975 {
976 	adutils_query_state_t	*p;
977 	int			i;
978 	int			ret;
979 
980 	(void) pthread_mutex_lock(&qstatelock);
981 	for (p = qstatehead; p != NULL; p = p->next) {
982 		if (p->qadh != adh || adh->generation != p->qadh_gen)
983 			continue;
984 		for (i = 0; i < p->qcount; i++) {
985 			if ((p->queries[i]).msgid == msgid) {
986 				if (!p->qdead) {
987 					p->ref_cnt++;
988 					*state = p;
989 					*qid = i;
990 					ret = 1;
991 				} else
992 					ret = 0;
993 				(void) pthread_mutex_unlock(&qstatelock);
994 				return (ret);
995 			}
996 		}
997 	}
998 	(void) pthread_mutex_unlock(&qstatelock);
999 	return (0);
1000 }
1001 
1002 static
1003 int
1004 check_for_binary_attrs(const char *attr)
1005 {
1006 	int i;
1007 	for (i = 0; binattrs[i].name != NULL; i++) {
1008 		if (strcasecmp(binattrs[i].name, attr) == 0)
1009 			return (i);
1010 	}
1011 	return (-1);
1012 }
1013 
1014 static
1015 void
1016 free_entry(adutils_entry_t *entry)
1017 {
1018 	int		i, j;
1019 	adutils_attr_t	*ap;
1020 
1021 	if (entry == NULL)
1022 		return;
1023 	if (entry->attr_nvpairs == NULL) {
1024 		free(entry);
1025 		return;
1026 	}
1027 	for (i = 0; i < entry->num_nvpairs; i++) {
1028 		ap = &entry->attr_nvpairs[i];
1029 		if (ap->attr_name == NULL) {
1030 			ldap_value_free(ap->attr_values);
1031 			continue;
1032 		}
1033 		if (check_for_binary_attrs(ap->attr_name) >= 0) {
1034 			free(ap->attr_name);
1035 			if (ap->attr_values == NULL)
1036 				continue;
1037 			for (j = 0; j < ap->num_values; j++)
1038 				free(ap->attr_values[j]);
1039 			free(ap->attr_values);
1040 		} else if (strcasecmp(ap->attr_name, "dn") == 0) {
1041 			free(ap->attr_name);
1042 			ldap_memfree(ap->attr_values[0]);
1043 			free(ap->attr_values);
1044 		} else {
1045 			free(ap->attr_name);
1046 			ldap_value_free(ap->attr_values);
1047 		}
1048 	}
1049 	free(entry->attr_nvpairs);
1050 	free(entry);
1051 }
1052 
1053 void
1054 adutils_freeresult(adutils_result_t **result)
1055 {
1056 	adutils_entry_t	*e, *next;
1057 
1058 	if (result == NULL || *result == NULL)
1059 		return;
1060 	if ((*result)->entries == NULL) {
1061 		free(*result);
1062 		*result = NULL;
1063 		return;
1064 	}
1065 	for (e = (*result)->entries; e != NULL; e = next) {
1066 		next = e->next;
1067 		free_entry(e);
1068 	}
1069 	free(*result);
1070 	*result = NULL;
1071 }
1072 
1073 const adutils_entry_t *
1074 adutils_getfirstentry(adutils_result_t *result)
1075 {
1076 	if (result != NULL)
1077 		return (result->entries);
1078 	return (NULL);
1079 }
1080 
1081 
1082 char **
1083 adutils_getattr(const adutils_entry_t *entry, const char *attrname)
1084 {
1085 	int		i;
1086 	adutils_attr_t	*ap;
1087 
1088 	if (entry == NULL || entry->attr_nvpairs == NULL)
1089 		return (NULL);
1090 	for (i = 0; i < entry->num_nvpairs; i++) {
1091 		ap = &entry->attr_nvpairs[i];
1092 		if (ap->attr_name != NULL &&
1093 		    strcasecmp(ap->attr_name, attrname) == 0)
1094 			return (ap->attr_values);
1095 	}
1096 	return (NULL);
1097 }
1098 
1099 
1100 /*
1101  * Queue LDAP result for the given query.
1102  *
1103  * Return values:
1104  *  0 success
1105  * -1 ignore result
1106  * -2 error
1107  */
1108 static
1109 int
1110 make_entry(adutils_q_t *q, adutils_host_t *adh, LDAPMessage *search_res,
1111 	adutils_entry_t **entry)
1112 {
1113 	BerElement	*ber = NULL;
1114 	BerValue	**bvalues = NULL;
1115 	char		**strvalues;
1116 	char		*attr = NULL, *dn = NULL, *domain = NULL;
1117 	adutils_entry_t	*ep;
1118 	adutils_attr_t	*ap;
1119 	int		i, j, b, err = 0, ret = -2;
1120 
1121 	*entry = NULL;
1122 
1123 	/* Check that this is the domain that we were looking for */
1124 	if ((dn = ldap_get_dn(adh->ld, search_res)) == NULL)
1125 		return (-2);
1126 	if ((domain = adutils_dn2dns(dn)) == NULL) {
1127 		ldap_memfree(dn);
1128 		return (-2);
1129 	}
1130 	if (q->edomain != NULL) {
1131 		if (u8_strcmp(q->edomain, domain, 0, U8_STRCMP_CI_LOWER,
1132 		    U8_UNICODE_LATEST, &err) != 0 || err != 0) {
1133 			ldap_memfree(dn);
1134 			free(domain);
1135 			return (-1);
1136 		}
1137 	}
1138 	free(domain);
1139 
1140 	/* Allocate memory for the entry */
1141 	if ((ep = calloc(1, sizeof (*ep))) == NULL)
1142 		goto out;
1143 
1144 	/* For 'dn' */
1145 	ep->num_nvpairs = 1;
1146 
1147 	/* Count the number of name-value pairs for this entry */
1148 	for (attr = ldap_first_attribute(adh->ld, search_res, &ber);
1149 	    attr != NULL;
1150 	    attr = ldap_next_attribute(adh->ld, search_res, ber)) {
1151 		ep->num_nvpairs++;
1152 		ldap_memfree(attr);
1153 	}
1154 	ber_free(ber, 0);
1155 	ber = NULL;
1156 
1157 	/* Allocate array for the attribute name-value pairs */
1158 	ep->attr_nvpairs = calloc(ep->num_nvpairs, sizeof (*ep->attr_nvpairs));
1159 	if (ep->attr_nvpairs == NULL) {
1160 		ep->num_nvpairs = 0;
1161 		goto out;
1162 	}
1163 
1164 	/* For dn */
1165 	ap = &ep->attr_nvpairs[0];
1166 	if ((ap->attr_name = strdup("dn")) == NULL)
1167 		goto out;
1168 	ap->num_values = 1;
1169 	ap->attr_values = calloc(ap->num_values, sizeof (*ap->attr_values));
1170 	if (ap->attr_values == NULL) {
1171 		ap->num_values = 0;
1172 		goto out;
1173 	}
1174 	ap->attr_values[0] = dn;
1175 	dn = NULL;
1176 
1177 	for (attr = ldap_first_attribute(adh->ld, search_res, &ber), i = 1;
1178 	    attr != NULL;
1179 	    ldap_memfree(attr), i++,
1180 	    attr = ldap_next_attribute(adh->ld, search_res, ber)) {
1181 		ap = &ep->attr_nvpairs[i];
1182 		if ((ap->attr_name = strdup(attr)) == NULL)
1183 			goto out;
1184 
1185 		if ((b = check_for_binary_attrs(attr)) >= 0) {
1186 			bvalues =
1187 			    ldap_get_values_len(adh->ld, search_res, attr);
1188 			if (bvalues == NULL)
1189 				continue;
1190 			ap->num_values = ldap_count_values_len(bvalues);
1191 			if (ap->num_values == 0) {
1192 				ldap_value_free_len(bvalues);
1193 				bvalues = NULL;
1194 				continue;
1195 			}
1196 			ap->attr_values = calloc(ap->num_values,
1197 			    sizeof (*ap->attr_values));
1198 			if (ap->attr_values == NULL) {
1199 				ap->num_values = 0;
1200 				goto out;
1201 			}
1202 			for (j = 0; j < ap->num_values; j++) {
1203 				ap->attr_values[j] =
1204 				    binattrs[b].ber2str(bvalues[j]);
1205 				if (ap->attr_values[j] == NULL)
1206 					goto out;
1207 			}
1208 			ldap_value_free_len(bvalues);
1209 			bvalues = NULL;
1210 			continue;
1211 		}
1212 
1213 		strvalues = ldap_get_values(adh->ld, search_res, attr);
1214 		if (strvalues == NULL)
1215 			continue;
1216 		ap->num_values = ldap_count_values(strvalues);
1217 		if (ap->num_values == 0) {
1218 			ldap_value_free(strvalues);
1219 			continue;
1220 		}
1221 		ap->attr_values = strvalues;
1222 	}
1223 
1224 	ret = 0;
1225 out:
1226 	ldap_memfree(attr);
1227 	ldap_memfree(dn);
1228 	ber_free(ber, 0);
1229 	ldap_value_free_len(bvalues);
1230 	if (ret < 0)
1231 		free_entry(ep);
1232 	else
1233 		*entry = ep;
1234 	return (ret);
1235 }
1236 
1237 /*
1238  * Put the search result onto the given adutils_q_t.
1239  * Returns:	  0 success
1240  *		< 0 error
1241  */
1242 static
1243 int
1244 add_entry(adutils_host_t *adh, adutils_q_t *q, LDAPMessage *search_res)
1245 {
1246 	int			ret = -1;
1247 	adutils_entry_t		*entry = NULL;
1248 	adutils_result_t	*res;
1249 
1250 	ret = make_entry(q, adh, search_res, &entry);
1251 	if (ret < -1) {
1252 		*q->rc = ADUTILS_ERR_MEMORY;
1253 		goto out;
1254 	} else if (ret == -1) {
1255 		/* ignore result */
1256 		goto out;
1257 	}
1258 	if (*q->result == NULL) {
1259 		res = calloc(1, sizeof (*res));
1260 		if (res == NULL) {
1261 			*q->rc = ADUTILS_ERR_MEMORY;
1262 			goto out;
1263 		}
1264 		res->num_entries = 1;
1265 		res->entries = entry;
1266 		*q->result = res;
1267 	} else {
1268 		res = *q->result;
1269 		entry->next = res->entries;
1270 		res->entries = entry;
1271 		res->num_entries++;
1272 	}
1273 	*q->rc = ADUTILS_SUCCESS;
1274 	entry = NULL;
1275 	ret = 0;
1276 
1277 out:
1278 	free_entry(entry);
1279 	return (ret);
1280 }
1281 
1282 /*
1283  * Try to get a result; if there is one, find the corresponding
1284  * adutils_q_t and process the result.
1285  *
1286  * Returns:	0 success
1287  *		-1 error
1288  */
1289 static
1290 int
1291 get_adobject_batch(adutils_host_t *adh, struct timeval *timeout)
1292 {
1293 	adutils_query_state_t	*query_state;
1294 	LDAPMessage		*res = NULL;
1295 	int			rc, ret, msgid, qid;
1296 	adutils_q_t		*que;
1297 	int			num;
1298 
1299 	(void) pthread_mutex_lock(&adh->lock);
1300 	if (adh->dead || adh->num_requests == 0) {
1301 		ret = (adh->dead) ? -1 : -2;
1302 		(void) pthread_mutex_unlock(&adh->lock);
1303 		return (ret);
1304 	}
1305 
1306 	/* Get one result */
1307 	rc = ldap_result(adh->ld, LDAP_RES_ANY, 0, timeout, &res);
1308 	if ((timeout != NULL && timeout->tv_sec > 0 && rc == LDAP_SUCCESS) ||
1309 	    rc < 0)
1310 		adh->dead = 1;
1311 
1312 	if (rc == LDAP_RES_SEARCH_RESULT && adh->num_requests > 0)
1313 		adh->num_requests--;
1314 	if (adh->dead) {
1315 		num = adh->num_requests;
1316 		(void) pthread_mutex_unlock(&adh->lock);
1317 		logger(LOG_DEBUG,
1318 		    "AD ldap_result error - %d queued requests", num);
1319 		return (-1);
1320 	}
1321 
1322 	switch (rc) {
1323 	case LDAP_RES_SEARCH_RESULT:
1324 		msgid = ldap_msgid(res);
1325 		if (msgid2query(adh, msgid, &query_state, &qid)) {
1326 			if (query_state->ldap_res_search_cb != NULL) {
1327 				/*
1328 				 * We use the caller-provided callback
1329 				 * to process the result.
1330 				 */
1331 				query_state->ldap_res_search_cb(
1332 				    adh->ld, &res, rc, qid,
1333 				    query_state->ldap_res_search_argp);
1334 				(void) pthread_mutex_unlock(&adh->lock);
1335 			} else {
1336 				/*
1337 				 * No callback. We fallback to our
1338 				 * default behaviour. All the entries
1339 				 * gotten from this search have been
1340 				 * added to the result list during
1341 				 * LDAP_RES_SEARCH_ENTRY (see below).
1342 				 * Here we set the return status to
1343 				 * notfound if the result is still empty.
1344 				 */
1345 				(void) pthread_mutex_unlock(&adh->lock);
1346 				que = &(query_state->queries[qid]);
1347 				if (*que->result == NULL)
1348 					*que->rc = ADUTILS_ERR_NOTFOUND;
1349 			}
1350 			atomic_dec_32(&query_state->qinflight);
1351 			adutils_lookup_batch_unlock(&query_state);
1352 		} else {
1353 			num = adh->num_requests;
1354 			(void) pthread_mutex_unlock(&adh->lock);
1355 			logger(LOG_DEBUG,
1356 			    "AD cannot find message ID (%d) "
1357 			    "- %d queued requests",
1358 			    msgid, num);
1359 		}
1360 		(void) ldap_msgfree(res);
1361 		ret = 0;
1362 		break;
1363 
1364 	case LDAP_RES_SEARCH_ENTRY:
1365 		msgid = ldap_msgid(res);
1366 		if (msgid2query(adh, msgid, &query_state, &qid)) {
1367 			if (query_state->ldap_res_search_cb != NULL) {
1368 				/*
1369 				 * We use the caller-provided callback
1370 				 * to process the entry.
1371 				 */
1372 				query_state->ldap_res_search_cb(
1373 				    adh->ld, &res, rc, qid,
1374 				    query_state->ldap_res_search_argp);
1375 				(void) pthread_mutex_unlock(&adh->lock);
1376 			} else {
1377 				/*
1378 				 * No callback. We fallback to our
1379 				 * default behaviour. This entry
1380 				 * will be added to the result list.
1381 				 */
1382 				que = &(query_state->queries[qid]);
1383 				rc = add_entry(adh, que, res);
1384 				(void) pthread_mutex_unlock(&adh->lock);
1385 				if (rc < 0) {
1386 					logger(LOG_DEBUG,
1387 					    "Failed to queue entry by "
1388 					    "message ID (%d) "
1389 					    "- %d queued requests",
1390 					    msgid, num);
1391 				}
1392 			}
1393 			adutils_lookup_batch_unlock(&query_state);
1394 		} else {
1395 			num = adh->num_requests;
1396 			(void) pthread_mutex_unlock(&adh->lock);
1397 			logger(LOG_DEBUG,
1398 			    "AD cannot find message ID (%d) "
1399 			    "- %d queued requests",
1400 			    msgid, num);
1401 		}
1402 		(void) ldap_msgfree(res);
1403 		ret = 0;
1404 		break;
1405 
1406 	case LDAP_RES_SEARCH_REFERENCE:
1407 		/*
1408 		 * We have no need for these at the moment.  Eventually,
1409 		 * when we query things that we can't expect to find in
1410 		 * the Global Catalog then we'll need to learn to follow
1411 		 * references.
1412 		 */
1413 		(void) pthread_mutex_unlock(&adh->lock);
1414 		(void) ldap_msgfree(res);
1415 		ret = 0;
1416 		break;
1417 
1418 	default:
1419 		/* timeout or error; treat the same */
1420 		(void) pthread_mutex_unlock(&adh->lock);
1421 		ret = -1;
1422 		break;
1423 	}
1424 
1425 	return (ret);
1426 }
1427 
1428 /*
1429  * This routine decreament the reference count of the
1430  * adutils_query_state_t
1431  */
1432 static void
1433 adutils_lookup_batch_unlock(adutils_query_state_t **state)
1434 {
1435 	/*
1436 	 * Decrement reference count with qstatelock locked
1437 	 */
1438 	(void) pthread_mutex_lock(&qstatelock);
1439 	(*state)->ref_cnt--;
1440 	/*
1441 	 * If there are no references wakup the allocating thread
1442 	 */
1443 	if ((*state)->ref_cnt <= 1)
1444 		(void) pthread_cond_signal(&(*state)->cv);
1445 	(void) pthread_mutex_unlock(&qstatelock);
1446 	*state = NULL;
1447 }
1448 
1449 /*
1450  * This routine frees the adutils_query_state_t structure
1451  * If the reference count is greater than 1 it waits
1452  * for the other threads to finish using it.
1453  */
1454 void
1455 adutils_lookup_batch_release(adutils_query_state_t **state)
1456 {
1457 	adutils_query_state_t **p;
1458 	int			i;
1459 
1460 	if (state == NULL || *state == NULL)
1461 		return;
1462 
1463 	/*
1464 	 * Set state to dead to stop further operations.
1465 	 * Wait for reference count with qstatelock locked
1466 	 * to get to one.
1467 	 */
1468 	(void) pthread_mutex_lock(&qstatelock);
1469 	(*state)->qdead = 1;
1470 	while ((*state)->ref_cnt > 1) {
1471 		(void) pthread_cond_wait(&(*state)->cv, &qstatelock);
1472 	}
1473 
1474 	/* Remove this state struct from the list of state structs */
1475 	for (p = &qstatehead; *p != NULL; p = &(*p)->next) {
1476 		if (*p == (*state)) {
1477 			*p = (*state)->next;
1478 			break;
1479 		}
1480 	}
1481 	(void) pthread_mutex_unlock(&qstatelock);
1482 	(void) pthread_cond_destroy(&(*state)->cv);
1483 	release_conn((*state)->qadh);
1484 
1485 	/* Clear results for queries that failed */
1486 	for (i = 0; i < (*state)->qcount; i++) {
1487 		if (*(*state)->queries[i].rc != ADUTILS_SUCCESS) {
1488 			adutils_freeresult((*state)->queries[i].result);
1489 		}
1490 	}
1491 	free((*state)->default_domain);
1492 	free((*state)->basedn);
1493 	free(*state);
1494 	*state = NULL;
1495 }
1496 
1497 
1498 /*
1499  * This routine waits for other threads using the
1500  * adutils_query_state_t structure to finish.
1501  * If the reference count is greater than 1 it waits
1502  * for the other threads to finish using it.
1503  */
1504 static
1505 void
1506 adutils_lookup_batch_wait(adutils_query_state_t *state)
1507 {
1508 	/*
1509 	 * Set state to dead to stop further operation.
1510 	 * stating.
1511 	 * Wait for reference count to get to one
1512 	 * with qstatelock locked.
1513 	 */
1514 	(void) pthread_mutex_lock(&qstatelock);
1515 	state->qdead = 1;
1516 	while (state->ref_cnt > 1) {
1517 		(void) pthread_cond_wait(&state->cv, &qstatelock);
1518 	}
1519 	(void) pthread_mutex_unlock(&qstatelock);
1520 }
1521 
1522 /*
1523  * Process active queries in the AD lookup batch and then finalize the
1524  * result.
1525  */
1526 adutils_rc
1527 adutils_lookup_batch_end(adutils_query_state_t **state)
1528 {
1529 	int		    rc = LDAP_SUCCESS;
1530 	adutils_rc	    ad_rc = ADUTILS_SUCCESS;
1531 	struct timeval	    tv;
1532 
1533 	tv.tv_sec = ADUTILS_SEARCH_TIMEOUT;
1534 	tv.tv_usec = 0;
1535 
1536 	/* Process results until done or until timeout, if given */
1537 	while ((*state)->qinflight > 0) {
1538 		if ((rc = get_adobject_batch((*state)->qadh,
1539 		    &tv)) != 0)
1540 			break;
1541 	}
1542 	(*state)->qdead = 1;
1543 	/* Wait for other threads processing search result to finish */
1544 	adutils_lookup_batch_wait(*state);
1545 	if (rc == -1 || (*state)->qinflight != 0)
1546 		ad_rc = ADUTILS_ERR_RETRIABLE_NET_ERR;
1547 	adutils_lookup_batch_release(state);
1548 	return (ad_rc);
1549 }
1550 
1551 const char *
1552 adutils_lookup_batch_getdefdomain(adutils_query_state_t *state)
1553 {
1554 	return (state->default_domain);
1555 }
1556 
1557 /*
1558  * Send one prepared search, queue up msgid, process what results are
1559  * available
1560  */
1561 adutils_rc
1562 adutils_lookup_batch_add(adutils_query_state_t *state,
1563 	const char *filter, const char **attrs, const char *edomain,
1564 	adutils_result_t **result, adutils_rc *rc)
1565 {
1566 	adutils_rc	retcode = ADUTILS_SUCCESS;
1567 	int		lrc, qid;
1568 	int		num;
1569 	int		dead;
1570 	struct timeval	tv;
1571 	adutils_q_t	*q;
1572 
1573 	qid = atomic_inc_32_nv(&state->qcount) - 1;
1574 	q = &(state->queries[qid]);
1575 
1576 	assert(qid < state->qsize);
1577 
1578 	/*
1579 	 * Remember the expected domain so we can check the results
1580 	 * against it
1581 	 */
1582 	q->edomain = edomain;
1583 
1584 	/* Remember where to put the results */
1585 	q->result = result;
1586 	q->rc = rc;
1587 
1588 	/*
1589 	 * Provide sane defaults for the results in case we never hear
1590 	 * back from the DS before closing the connection.
1591 	 */
1592 	*rc = ADUTILS_ERR_RETRIABLE_NET_ERR;
1593 	if (result != NULL)
1594 		*result = NULL;
1595 
1596 	/* Check the number of queued requests first */
1597 	tv.tv_sec = ADUTILS_SEARCH_TIMEOUT;
1598 	tv.tv_usec = 0;
1599 	while (!state->qadh->dead &&
1600 	    state->qadh->num_requests > state->qadh->max_requests) {
1601 		if (get_adobject_batch(state->qadh, &tv) != 0)
1602 			break;
1603 	}
1604 
1605 	/* Send this lookup, don't wait for a result here */
1606 	lrc = LDAP_SUCCESS;
1607 	(void) pthread_mutex_lock(&state->qadh->lock);
1608 
1609 	if (!state->qadh->dead) {
1610 		state->qadh->idletime = time(NULL);
1611 		lrc = ldap_search_ext(state->qadh->ld, state->basedn,
1612 		    LDAP_SCOPE_SUBTREE, filter, (char **)attrs,
1613 		    0, NULL, NULL, NULL, -1, &q->msgid);
1614 
1615 		if (lrc == LDAP_SUCCESS) {
1616 			state->qadh->num_requests++;
1617 		} else if (lrc == LDAP_BUSY || lrc == LDAP_UNAVAILABLE ||
1618 		    lrc == LDAP_CONNECT_ERROR || lrc == LDAP_SERVER_DOWN ||
1619 		    lrc == LDAP_UNWILLING_TO_PERFORM) {
1620 			retcode = ADUTILS_ERR_RETRIABLE_NET_ERR;
1621 			state->qadh->dead = 1;
1622 		} else {
1623 			retcode = ADUTILS_ERR_OTHER;
1624 			state->qadh->dead = 1;
1625 		}
1626 	}
1627 	dead = state->qadh->dead;
1628 	num = state->qadh->num_requests;
1629 	(void) pthread_mutex_unlock(&state->qadh->lock);
1630 
1631 	if (dead) {
1632 		if (lrc != LDAP_SUCCESS)
1633 			logger(LOG_DEBUG,
1634 			    "AD ldap_search_ext error (%s) "
1635 			    "- %d queued requests",
1636 			    ldap_err2string(lrc), num);
1637 		return (retcode);
1638 	}
1639 
1640 	atomic_inc_32(&state->qinflight);
1641 
1642 	/*
1643 	 * Reap as many requests as we can _without_ waiting to prevent
1644 	 * any possible TCP socket buffer starvation deadlocks.
1645 	 */
1646 	(void) memset(&tv, 0, sizeof (tv));
1647 	while (get_adobject_batch(state->qadh, &tv) == 0)
1648 		;
1649 
1650 	return (ADUTILS_SUCCESS);
1651 }
1652 
1653 /*
1654  * Single AD lookup request implemented on top of the batch API.
1655  */
1656 adutils_rc
1657 adutils_lookup(adutils_ad_t *ad, const char *filter, const char **attrs,
1658 		const char *domain, adutils_result_t **result)
1659 {
1660 	adutils_rc		rc, brc;
1661 	adutils_query_state_t	*qs;
1662 
1663 	rc = adutils_lookup_batch_start(ad, 1, NULL, NULL, &qs);
1664 	if (rc != ADUTILS_SUCCESS)
1665 		return (rc);
1666 
1667 	rc = adutils_lookup_batch_add(qs, filter, attrs, domain, result, &brc);
1668 	if (rc != ADUTILS_SUCCESS) {
1669 		adutils_lookup_batch_release(&qs);
1670 		return (rc);
1671 	}
1672 
1673 	rc = adutils_lookup_batch_end(&qs);
1674 	if (rc != ADUTILS_SUCCESS)
1675 		return (rc);
1676 	return (brc);
1677 }
1678