xref: /titanic_50/usr/src/lib/libadutils/common/adutils.c (revision f899e5733f35e45012ad40c8325b2622dcc2b673)
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 /*
400  * Extract an int from the Ber value
401  * Return B_TRUE if a valid integer was found, B_FALSE if not.
402  */
403 boolean_t
404 adutils_bv_uint(BerValue *bval, unsigned int *result)
405 {
406 	char buf[40];	/* big enough for any int */
407 	unsigned int tmp;
408 	char *p;
409 
410 	*result = 0;	/* for error cases */
411 
412 	if (bval == NULL || bval->bv_val == NULL)
413 		return (B_FALSE);
414 	if (bval->bv_len >= sizeof (buf))
415 		return (B_FALSE);
416 
417 	(void) memcpy(buf, bval->bv_val, bval->bv_len);
418 	buf[bval->bv_len] = '\0';
419 
420 	tmp = strtoul(buf, &p, 10);
421 
422 	/* Junk after the number? */
423 	if (*p != '\0')
424 		return (B_FALSE);
425 
426 	*result = tmp;
427 
428 	return (B_TRUE);
429 }
430 
431 /* Return a NUL-terminated string from the Ber value */
432 char *
433 adutils_bv_str(BerValue *bval)
434 {
435 	char *s;
436 
437 	if (bval == NULL || bval->bv_val == NULL)
438 		return (NULL);
439 	if ((s = malloc(bval->bv_len + 1)) == NULL)
440 		return (NULL);
441 	(void) snprintf(s, bval->bv_len + 1, "%.*s", bval->bv_len,
442 	    bval->bv_val);
443 	return (s);
444 }
445 
446 /*ARGSUSED*/
447 int
448 saslcallback(LDAP *ld, unsigned flags, void *defaults, void *prompts)
449 {
450 	sasl_interact_t	*interact;
451 
452 	if (prompts == NULL || flags != LDAP_SASL_INTERACTIVE)
453 		return (LDAP_PARAM_ERROR);
454 
455 	/* There should be no extra arguemnts for SASL/GSSAPI authentication */
456 	for (interact = prompts; interact->id != SASL_CB_LIST_END;
457 	    interact++) {
458 		interact->result = NULL;
459 		interact->len = 0;
460 	}
461 	return (LDAP_SUCCESS);
462 }
463 
464 
465 #define	ADCONN_TIME	300
466 
467 /*
468  * Idle connection reaping side of connection management
469  */
470 void
471 adutils_reap_idle_connections()
472 {
473 	adutils_host_t	*adh;
474 	time_t		now;
475 
476 	(void) pthread_mutex_lock(&adhostlock);
477 	now = time(NULL);
478 	for (adh = host_head; adh != NULL; adh = adh->next) {
479 		(void) pthread_mutex_lock(&adh->lock);
480 		if (adh->ref == 0 && adh->idletime != 0 &&
481 		    adh->idletime + ADCONN_TIME < now) {
482 			if (adh->ld) {
483 				(void) ldap_unbind(adh->ld);
484 				adh->ld = NULL;
485 				adh->idletime = 0;
486 				adh->ref = 0;
487 			}
488 		}
489 		(void) pthread_mutex_unlock(&adh->lock);
490 	}
491 	(void) pthread_mutex_unlock(&adhostlock);
492 }
493 
494 
495 adutils_rc
496 adutils_ad_alloc(adutils_ad_t **new_ad, const char *domain_name,
497 	adutils_ad_partition_t part)
498 {
499 	adutils_ad_t *ad;
500 
501 	*new_ad = NULL;
502 
503 	if ((ad = calloc(1, sizeof (*ad))) == NULL)
504 		return (ADUTILS_ERR_MEMORY);
505 	ad->ref = 1;
506 	ad->partition = part;
507 
508 	/* domain_name is required iff we are talking directly to a DC */
509 	if (part == ADUTILS_AD_DATA) {
510 		assert(domain_name != NULL);
511 		assert(*domain_name != '\0');
512 
513 		ad->basedn = adutils_dns2dn(domain_name);
514 	} else {
515 		assert(domain_name == NULL);
516 		ad->basedn = strdup("");
517 	}
518 	if (ad->basedn == NULL)
519 		goto err;
520 
521 	if (pthread_mutex_init(&ad->lock, NULL) != 0)
522 		goto err;
523 	*new_ad = ad;
524 	return (ADUTILS_SUCCESS);
525 
526 err:
527 	free(ad->basedn);
528 	free(ad);
529 	return (ADUTILS_ERR_MEMORY);
530 }
531 
532 void
533 adutils_ad_free(adutils_ad_t **ad)
534 {
535 	adutils_host_t *p;
536 	adutils_host_t *prev;
537 
538 	if (ad == NULL || *ad == NULL)
539 		return;
540 
541 	(void) pthread_mutex_lock(&(*ad)->lock);
542 
543 	if (atomic_dec_32_nv(&(*ad)->ref) > 0) {
544 		(void) pthread_mutex_unlock(&(*ad)->lock);
545 		*ad = NULL;
546 		return;
547 	}
548 
549 	(void) pthread_mutex_lock(&adhostlock);
550 	prev = NULL;
551 	p = host_head;
552 	while (p != NULL) {
553 		if (p->owner != (*ad)) {
554 			prev = p;
555 			p = p->next;
556 			continue;
557 		} else {
558 			delete_ds((*ad), p->host, p->port);
559 			if (prev == NULL)
560 				p = host_head;
561 			else
562 				p = prev->next;
563 		}
564 	}
565 	(void) pthread_mutex_unlock(&adhostlock);
566 
567 	(void) pthread_mutex_unlock(&(*ad)->lock);
568 	(void) pthread_mutex_destroy(&(*ad)->lock);
569 
570 	if ((*ad)->known_domains)
571 		free((*ad)->known_domains);
572 	free((*ad)->basedn);
573 	free(*ad);
574 
575 	*ad = NULL;
576 }
577 
578 static
579 int
580 open_conn(adutils_host_t *adh, int timeoutsecs)
581 {
582 	int zero = 0;
583 	int ldversion, rc;
584 	int timeoutms = timeoutsecs * 1000;
585 
586 	if (adh == NULL)
587 		return (0);
588 
589 	(void) pthread_mutex_lock(&adh->lock);
590 
591 	if (!adh->dead && adh->ld != NULL)
592 		/* done! */
593 		goto out;
594 
595 	if (adh->ld != NULL) {
596 		(void) ldap_unbind(adh->ld);
597 		adh->ld = NULL;
598 	}
599 	adh->num_requests = 0;
600 
601 	atomic_inc_64(&adh->generation);
602 
603 	/* Open and bind an LDAP connection */
604 	adh->ld = ldap_init(adh->host, adh->port);
605 	if (adh->ld == NULL) {
606 		logger(LOG_INFO, "ldap_init() to server "
607 		    "%s port %d failed. (%s)", adh->host,
608 		    adh->port, strerror(errno));
609 		goto out;
610 	}
611 	ldversion = LDAP_VERSION3;
612 	(void) ldap_set_option(adh->ld, LDAP_OPT_PROTOCOL_VERSION, &ldversion);
613 	(void) ldap_set_option(adh->ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF);
614 	(void) ldap_set_option(adh->ld, LDAP_OPT_TIMELIMIT, &zero);
615 	(void) ldap_set_option(adh->ld, LDAP_OPT_SIZELIMIT, &zero);
616 	(void) ldap_set_option(adh->ld, LDAP_X_OPT_CONNECT_TIMEOUT, &timeoutms);
617 	(void) ldap_set_option(adh->ld, LDAP_OPT_RESTART, LDAP_OPT_ON);
618 	rc = ldap_sasl_interactive_bind_s(adh->ld, "" /* binddn */,
619 	    adh->saslmech, NULL, NULL, adh->saslflags, &saslcallback,
620 	    NULL);
621 
622 	if (rc != LDAP_SUCCESS) {
623 		(void) ldap_unbind(adh->ld);
624 		adh->ld = NULL;
625 		logger(LOG_INFO, "ldap_sasl_interactive_bind_s() to server "
626 		    "%s port %d failed. (%s)", adh->host, adh->port,
627 		    ldap_err2string(rc));
628 		goto out;
629 	}
630 
631 	logger(LOG_DEBUG, "Using server %s:%d",
632 	    adh->host, adh->port);
633 
634 out:
635 	if (adh->ld != NULL) {
636 		atomic_inc_32(&adh->ref);
637 		adh->idletime = time(NULL);
638 		adh->dead = 0;
639 		(void) pthread_mutex_unlock(&adh->lock);
640 		return (1);
641 	}
642 
643 	(void) pthread_mutex_unlock(&adh->lock);
644 	return (0);
645 }
646 
647 
648 /*
649  * Connection management: find an open connection or open one
650  */
651 static
652 adutils_host_t *
653 get_conn(adutils_ad_t *ad)
654 {
655 	adutils_host_t	*adh = NULL;
656 	int		tries;
657 	int		dscount = 0;
658 	int		timeoutsecs = ADUTILS_LDAP_OPEN_TIMEOUT;
659 
660 retry:
661 	(void) pthread_mutex_lock(&adhostlock);
662 
663 	if (host_head == NULL) {
664 		(void) pthread_mutex_unlock(&adhostlock);
665 		goto out;
666 	}
667 
668 	if (dscount == 0) {
669 		/*
670 		 * First try: count the number of DSes.
671 		 *
672 		 * Integer overflow is not an issue -- we can't have so many
673 		 * DSes because they won't fit even DNS over TCP, and SMF
674 		 * shouldn't let you set so many.
675 		 */
676 		for (adh = host_head, tries = 0; adh != NULL; adh = adh->next) {
677 			if (adh->owner == ad)
678 				dscount++;
679 		}
680 
681 		if (dscount == 0) {
682 			(void) pthread_mutex_unlock(&adhostlock);
683 			goto out;
684 		}
685 
686 		tries = dscount * 3;	/* three tries per-ds */
687 
688 		/*
689 		 * Begin round-robin at the next DS in the list after the last
690 		 * one that we had a connection to, else start with the first
691 		 * DS in the list.
692 		 */
693 		adh = ad->last_adh;
694 	}
695 
696 	/*
697 	 * Round-robin -- pick the next one on the list; if the list
698 	 * changes on us, no big deal, we'll just potentially go
699 	 * around the wrong number of times.
700 	 */
701 	for (;;) {
702 		if (adh != NULL && adh->owner == ad && adh->ld != NULL &&
703 		    !adh->dead)
704 			break;
705 		if (adh == NULL || (adh = adh->next) == NULL)
706 			adh = host_head;
707 		if (adh->owner == ad)
708 			break;
709 	}
710 
711 	ad->last_adh = adh;
712 	(void) pthread_mutex_unlock(&adhostlock);
713 
714 	/* Found suitable DS, open it if not already opened */
715 	if (open_conn(adh, timeoutsecs))
716 		return (adh);
717 
718 	tries--;
719 	if ((tries % dscount) == 0)
720 		timeoutsecs *= 2;
721 	if (tries > 0)
722 		goto retry;
723 
724 out:
725 	logger(LOG_NOTICE, "Couldn't open an LDAP connection to any global "
726 	    "catalog server!");
727 	return (NULL);
728 }
729 
730 static
731 void
732 release_conn(adutils_host_t *adh)
733 {
734 	int delete = 0;
735 
736 	(void) pthread_mutex_lock(&adh->lock);
737 	if (atomic_dec_32_nv(&adh->ref) == 0) {
738 		if (adh->owner == NULL)
739 			delete = 1;
740 		adh->idletime = time(NULL);
741 	}
742 	(void) pthread_mutex_unlock(&adh->lock);
743 
744 	/* Free this host if its owner no longer exists. */
745 	if (delete) {
746 		(void) pthread_mutex_lock(&adhostlock);
747 		delete_ds(NULL, adh->host, adh->port);
748 		(void) pthread_mutex_unlock(&adhostlock);
749 	}
750 }
751 
752 /*
753  * Create a adutils_host_t, populate it and add it to the list of hosts.
754  */
755 adutils_rc
756 adutils_add_ds(adutils_ad_t *ad, const char *host, int port)
757 {
758 	adutils_host_t	*p;
759 	adutils_host_t	*new = NULL;
760 	int		ret;
761 	adutils_rc	rc;
762 
763 	(void) pthread_mutex_lock(&adhostlock);
764 	for (p = host_head; p != NULL; p = p->next) {
765 		if (p->owner != ad)
766 			continue;
767 
768 		if (strcmp(host, p->host) == 0 && p->port == port) {
769 			/* already added */
770 			rc = ADUTILS_SUCCESS;
771 			goto err;
772 		}
773 	}
774 
775 	rc = ADUTILS_ERR_MEMORY;
776 
777 	/* add new entry */
778 	new = (adutils_host_t *)calloc(1, sizeof (*new));
779 	if (new == NULL)
780 		goto err;
781 	new->owner = ad;
782 	new->port = port;
783 	new->dead = 0;
784 	new->max_requests = 80;
785 	new->num_requests = 0;
786 	if ((new->host = strdup(host)) == NULL)
787 		goto err;
788 	new->saslflags = LDAP_SASL_INTERACTIVE;
789 	new->saslmech = "GSSAPI";
790 
791 	if ((ret = pthread_mutex_init(&new->lock, NULL)) != 0) {
792 		free(new->host);
793 		new->host = NULL;
794 		errno = ret;
795 		rc = ADUTILS_ERR_INTERNAL;
796 		goto err;
797 	}
798 
799 	/* link in */
800 	rc = ADUTILS_SUCCESS;
801 	new->next = host_head;
802 	host_head = new;
803 
804 err:
805 	(void) pthread_mutex_unlock(&adhostlock);
806 
807 	if (rc != 0 && new != NULL) {
808 		if (new->host != NULL) {
809 			(void) pthread_mutex_destroy(&new->lock);
810 			free(new->host);
811 		}
812 		free(new);
813 	}
814 
815 	return (rc);
816 }
817 
818 /*
819  * Free a DS configuration.
820  * Caller must lock the adhostlock mutex
821  */
822 static
823 void
824 delete_ds(adutils_ad_t *ad, const char *host, int port)
825 {
826 	adutils_host_t	**p, *q;
827 
828 	for (p = &host_head; *p != NULL; p = &((*p)->next)) {
829 		if ((*p)->owner != ad || strcmp(host, (*p)->host) != 0 ||
830 		    (*p)->port != port)
831 			continue;
832 		/* found */
833 
834 		(void) pthread_mutex_lock(&((*p)->lock));
835 		if ((*p)->ref > 0) {
836 			/*
837 			 * Still in use. Set its owner to NULL so
838 			 * that it can be freed when its ref count
839 			 * becomes 0.
840 			 */
841 			(*p)->owner = NULL;
842 			(void) pthread_mutex_unlock(&((*p)->lock));
843 			break;
844 		}
845 		(void) pthread_mutex_unlock(&((*p)->lock));
846 
847 		q = *p;
848 		*p = (*p)->next;
849 
850 		(void) pthread_mutex_destroy(&q->lock);
851 
852 		if (q->ld)
853 			(void) ldap_unbind(q->ld);
854 		if (q->host)
855 			free(q->host);
856 		free(q);
857 		break;
858 	}
859 
860 }
861 /*
862  * Add known domain name and domain SID to AD configuration.
863  */
864 
865 adutils_rc
866 adutils_add_domain(adutils_ad_t *ad, const char *domain, const char *sid)
867 {
868 	struct known_domain *new;
869 	int num = ad->num_known_domains;
870 
871 	ad->num_known_domains++;
872 	new = realloc(ad->known_domains,
873 	    sizeof (struct known_domain) * ad->num_known_domains);
874 	if (new != NULL) {
875 		ad->known_domains = new;
876 		(void) strlcpy(ad->known_domains[num].name, domain,
877 		    sizeof (ad->known_domains[num].name));
878 		(void) strlcpy(ad->known_domains[num].sid, sid,
879 		    sizeof (ad->known_domains[num].sid));
880 		return (ADUTILS_SUCCESS);
881 	} else {
882 		if (ad->known_domains != NULL) {
883 			free(ad->known_domains);
884 			ad->known_domains = NULL;
885 		}
886 		ad->num_known_domains = 0;
887 		return (ADUTILS_ERR_MEMORY);
888 	}
889 }
890 
891 
892 /*
893  * Check that this AD supports this domain.
894  * If there are no known domains assume that the
895  * domain is supported by this AD.
896  *
897  * Returns 1 if this domain is supported by this AD
898  * else returns 0;
899  */
900 
901 int
902 adutils_lookup_check_domain(adutils_query_state_t *qs, const char *domain)
903 {
904 	adutils_ad_t *ad = qs->qadh->owner;
905 	int i;
906 
907 	for (i = 0; i < ad->num_known_domains; i++) {
908 		if (domain_eq(domain, ad->known_domains[i].name))
909 			return (1);
910 	}
911 
912 	return ((i == 0) ? 1 : 0);
913 }
914 
915 
916 /*
917  * Check that this AD supports the SID prefix.
918  * The SID prefix should match the domain SID.
919  * If there are no known domains assume that the
920  * SID prefix is supported by this AD.
921  *
922  * Returns 1 if this sid prefix is supported by this AD
923  * else returns 0;
924  */
925 
926 int
927 adutils_lookup_check_sid_prefix(adutils_query_state_t *qs, const char *sid)
928 {
929 	adutils_ad_t *ad = qs->qadh->owner;
930 	int i;
931 
932 
933 	for (i = 0; i < ad->num_known_domains; i++) {
934 		if (strcmp(sid, ad->known_domains[i].sid) == 0)
935 			return (1);
936 	}
937 
938 	return ((i == 0) ? 1 : 0);
939 }
940 
941 
942 adutils_rc
943 adutils_lookup_batch_start(adutils_ad_t *ad, int nqueries,
944 	adutils_ldap_res_search_cb ldap_res_search_cb,
945 	void *ldap_res_search_argp,
946 	adutils_query_state_t **state)
947 {
948 	adutils_query_state_t	*new_state;
949 	adutils_host_t		*adh = NULL;
950 
951 	if (ad == NULL)
952 		return (ADUTILS_ERR_INTERNAL);
953 
954 	*state = NULL;
955 	adh = get_conn(ad);
956 	if (adh == NULL)
957 		return (ADUTILS_ERR_RETRIABLE_NET_ERR);
958 
959 	new_state = calloc(1, sizeof (adutils_query_state_t) +
960 	    (nqueries - 1) * sizeof (adutils_q_t));
961 	if (new_state == NULL)
962 		return (ADUTILS_ERR_MEMORY);
963 
964 	new_state->ref_cnt = 1;
965 	new_state->qadh = adh;
966 	new_state->qsize = nqueries;
967 	new_state->qadh_gen = adh->generation;
968 	new_state->qcount = 0;
969 	new_state->ldap_res_search_cb = ldap_res_search_cb;
970 	new_state->ldap_res_search_argp = ldap_res_search_argp;
971 	(void) pthread_cond_init(&new_state->cv, NULL);
972 
973 	(void) pthread_mutex_lock(&qstatelock);
974 	new_state->next = qstatehead;
975 	qstatehead = new_state;
976 	(void) pthread_mutex_unlock(&qstatelock);
977 	*state = new_state;
978 
979 	return (ADUTILS_SUCCESS);
980 }
981 
982 /*
983  * Find the adutils_query_state_t to which a given LDAP result msgid on a
984  * given connection belongs. This routine increaments the reference count
985  * so that the object can not be freed. adutils_lookup_batch_unlock()
986  * must be called to decreament the reference count.
987  */
988 static
989 int
990 msgid2query(adutils_host_t *adh, int msgid,
991 	adutils_query_state_t **state, int *qid)
992 {
993 	adutils_query_state_t	*p;
994 	int			i;
995 	int			ret;
996 
997 	(void) pthread_mutex_lock(&qstatelock);
998 	for (p = qstatehead; p != NULL; p = p->next) {
999 		if (p->qadh != adh || adh->generation != p->qadh_gen)
1000 			continue;
1001 		for (i = 0; i < p->qcount; i++) {
1002 			if ((p->queries[i]).msgid == msgid) {
1003 				if (!p->qdead) {
1004 					p->ref_cnt++;
1005 					*state = p;
1006 					*qid = i;
1007 					ret = 1;
1008 				} else
1009 					ret = 0;
1010 				(void) pthread_mutex_unlock(&qstatelock);
1011 				return (ret);
1012 			}
1013 		}
1014 	}
1015 	(void) pthread_mutex_unlock(&qstatelock);
1016 	return (0);
1017 }
1018 
1019 static
1020 int
1021 check_for_binary_attrs(const char *attr)
1022 {
1023 	int i;
1024 	for (i = 0; binattrs[i].name != NULL; i++) {
1025 		if (strcasecmp(binattrs[i].name, attr) == 0)
1026 			return (i);
1027 	}
1028 	return (-1);
1029 }
1030 
1031 static
1032 void
1033 free_entry(adutils_entry_t *entry)
1034 {
1035 	int		i, j;
1036 	adutils_attr_t	*ap;
1037 
1038 	if (entry == NULL)
1039 		return;
1040 	if (entry->attr_nvpairs == NULL) {
1041 		free(entry);
1042 		return;
1043 	}
1044 	for (i = 0; i < entry->num_nvpairs; i++) {
1045 		ap = &entry->attr_nvpairs[i];
1046 		if (ap->attr_name == NULL) {
1047 			ldap_value_free(ap->attr_values);
1048 			continue;
1049 		}
1050 		if (check_for_binary_attrs(ap->attr_name) >= 0) {
1051 			free(ap->attr_name);
1052 			if (ap->attr_values == NULL)
1053 				continue;
1054 			for (j = 0; j < ap->num_values; j++)
1055 				free(ap->attr_values[j]);
1056 			free(ap->attr_values);
1057 		} else if (strcasecmp(ap->attr_name, "dn") == 0) {
1058 			free(ap->attr_name);
1059 			ldap_memfree(ap->attr_values[0]);
1060 			free(ap->attr_values);
1061 		} else {
1062 			free(ap->attr_name);
1063 			ldap_value_free(ap->attr_values);
1064 		}
1065 	}
1066 	free(entry->attr_nvpairs);
1067 	free(entry);
1068 }
1069 
1070 void
1071 adutils_freeresult(adutils_result_t **result)
1072 {
1073 	adutils_entry_t	*e, *next;
1074 
1075 	if (result == NULL || *result == NULL)
1076 		return;
1077 	if ((*result)->entries == NULL) {
1078 		free(*result);
1079 		*result = NULL;
1080 		return;
1081 	}
1082 	for (e = (*result)->entries; e != NULL; e = next) {
1083 		next = e->next;
1084 		free_entry(e);
1085 	}
1086 	free(*result);
1087 	*result = NULL;
1088 }
1089 
1090 const adutils_entry_t *
1091 adutils_getfirstentry(adutils_result_t *result)
1092 {
1093 	if (result != NULL)
1094 		return (result->entries);
1095 	return (NULL);
1096 }
1097 
1098 
1099 char **
1100 adutils_getattr(const adutils_entry_t *entry, const char *attrname)
1101 {
1102 	int		i;
1103 	adutils_attr_t	*ap;
1104 
1105 	if (entry == NULL || entry->attr_nvpairs == NULL)
1106 		return (NULL);
1107 	for (i = 0; i < entry->num_nvpairs; i++) {
1108 		ap = &entry->attr_nvpairs[i];
1109 		if (ap->attr_name != NULL &&
1110 		    strcasecmp(ap->attr_name, attrname) == 0)
1111 			return (ap->attr_values);
1112 	}
1113 	return (NULL);
1114 }
1115 
1116 
1117 /*
1118  * Queue LDAP result for the given query.
1119  *
1120  * Return values:
1121  *  0 success
1122  * -1 ignore result
1123  * -2 error
1124  */
1125 static
1126 int
1127 make_entry(adutils_q_t *q, adutils_host_t *adh, LDAPMessage *search_res,
1128 	adutils_entry_t **entry)
1129 {
1130 	BerElement	*ber = NULL;
1131 	BerValue	**bvalues = NULL;
1132 	char		**strvalues;
1133 	char		*attr = NULL, *dn = NULL, *domain = NULL;
1134 	adutils_entry_t	*ep;
1135 	adutils_attr_t	*ap;
1136 	int		i, j, b, ret = -2;
1137 
1138 	*entry = NULL;
1139 
1140 	/* Check that this is the domain that we were looking for */
1141 	if ((dn = ldap_get_dn(adh->ld, search_res)) == NULL)
1142 		return (-2);
1143 	if ((domain = adutils_dn2dns(dn)) == NULL) {
1144 		ldap_memfree(dn);
1145 		return (-2);
1146 	}
1147 	if (q->edomain != NULL) {
1148 		if (!domain_eq(q->edomain, domain)) {
1149 			ldap_memfree(dn);
1150 			free(domain);
1151 			return (-1);
1152 		}
1153 	}
1154 	free(domain);
1155 
1156 	/* Allocate memory for the entry */
1157 	if ((ep = calloc(1, sizeof (*ep))) == NULL)
1158 		goto out;
1159 
1160 	/* For 'dn' */
1161 	ep->num_nvpairs = 1;
1162 
1163 	/* Count the number of name-value pairs for this entry */
1164 	for (attr = ldap_first_attribute(adh->ld, search_res, &ber);
1165 	    attr != NULL;
1166 	    attr = ldap_next_attribute(adh->ld, search_res, ber)) {
1167 		ep->num_nvpairs++;
1168 		ldap_memfree(attr);
1169 	}
1170 	ber_free(ber, 0);
1171 	ber = NULL;
1172 
1173 	/* Allocate array for the attribute name-value pairs */
1174 	ep->attr_nvpairs = calloc(ep->num_nvpairs, sizeof (*ep->attr_nvpairs));
1175 	if (ep->attr_nvpairs == NULL) {
1176 		ep->num_nvpairs = 0;
1177 		goto out;
1178 	}
1179 
1180 	/* For dn */
1181 	ap = &ep->attr_nvpairs[0];
1182 	if ((ap->attr_name = strdup("dn")) == NULL)
1183 		goto out;
1184 	ap->num_values = 1;
1185 	ap->attr_values = calloc(ap->num_values, sizeof (*ap->attr_values));
1186 	if (ap->attr_values == NULL) {
1187 		ap->num_values = 0;
1188 		goto out;
1189 	}
1190 	ap->attr_values[0] = dn;
1191 	dn = NULL;
1192 
1193 	for (attr = ldap_first_attribute(adh->ld, search_res, &ber), i = 1;
1194 	    attr != NULL;
1195 	    ldap_memfree(attr), i++,
1196 	    attr = ldap_next_attribute(adh->ld, search_res, ber)) {
1197 		ap = &ep->attr_nvpairs[i];
1198 		if ((ap->attr_name = strdup(attr)) == NULL)
1199 			goto out;
1200 
1201 		if ((b = check_for_binary_attrs(attr)) >= 0) {
1202 			bvalues =
1203 			    ldap_get_values_len(adh->ld, search_res, attr);
1204 			if (bvalues == NULL)
1205 				continue;
1206 			ap->num_values = ldap_count_values_len(bvalues);
1207 			if (ap->num_values == 0) {
1208 				ldap_value_free_len(bvalues);
1209 				bvalues = NULL;
1210 				continue;
1211 			}
1212 			ap->attr_values = calloc(ap->num_values,
1213 			    sizeof (*ap->attr_values));
1214 			if (ap->attr_values == NULL) {
1215 				ap->num_values = 0;
1216 				goto out;
1217 			}
1218 			for (j = 0; j < ap->num_values; j++) {
1219 				ap->attr_values[j] =
1220 				    binattrs[b].ber2str(bvalues[j]);
1221 				if (ap->attr_values[j] == NULL)
1222 					goto out;
1223 			}
1224 			ldap_value_free_len(bvalues);
1225 			bvalues = NULL;
1226 			continue;
1227 		}
1228 
1229 		strvalues = ldap_get_values(adh->ld, search_res, attr);
1230 		if (strvalues == NULL)
1231 			continue;
1232 		ap->num_values = ldap_count_values(strvalues);
1233 		if (ap->num_values == 0) {
1234 			ldap_value_free(strvalues);
1235 			continue;
1236 		}
1237 		ap->attr_values = strvalues;
1238 	}
1239 
1240 	ret = 0;
1241 out:
1242 	ldap_memfree(attr);
1243 	ldap_memfree(dn);
1244 	ber_free(ber, 0);
1245 	ldap_value_free_len(bvalues);
1246 	if (ret < 0)
1247 		free_entry(ep);
1248 	else
1249 		*entry = ep;
1250 	return (ret);
1251 }
1252 
1253 /*
1254  * Put the search result onto the given adutils_q_t.
1255  * Returns:	  0 success
1256  *		< 0 error
1257  */
1258 static
1259 int
1260 add_entry(adutils_host_t *adh, adutils_q_t *q, LDAPMessage *search_res)
1261 {
1262 	int			ret = -1;
1263 	adutils_entry_t		*entry = NULL;
1264 	adutils_result_t	*res;
1265 
1266 	ret = make_entry(q, adh, search_res, &entry);
1267 	if (ret < -1) {
1268 		*q->rc = ADUTILS_ERR_MEMORY;
1269 		goto out;
1270 	} else if (ret == -1) {
1271 		/* ignore result */
1272 		goto out;
1273 	}
1274 	if (*q->result == NULL) {
1275 		res = calloc(1, sizeof (*res));
1276 		if (res == NULL) {
1277 			*q->rc = ADUTILS_ERR_MEMORY;
1278 			goto out;
1279 		}
1280 		res->num_entries = 1;
1281 		res->entries = entry;
1282 		*q->result = res;
1283 	} else {
1284 		res = *q->result;
1285 		entry->next = res->entries;
1286 		res->entries = entry;
1287 		res->num_entries++;
1288 	}
1289 	*q->rc = ADUTILS_SUCCESS;
1290 	entry = NULL;
1291 	ret = 0;
1292 
1293 out:
1294 	free_entry(entry);
1295 	return (ret);
1296 }
1297 
1298 /*
1299  * Try to get a result; if there is one, find the corresponding
1300  * adutils_q_t and process the result.
1301  *
1302  * Returns:	0 success
1303  *		-1 error
1304  */
1305 static
1306 int
1307 get_adobject_batch(adutils_host_t *adh, struct timeval *timeout)
1308 {
1309 	adutils_query_state_t	*query_state;
1310 	LDAPMessage		*res = NULL;
1311 	int			rc, ret, msgid, qid;
1312 	adutils_q_t		*que;
1313 	int			num;
1314 
1315 	(void) pthread_mutex_lock(&adh->lock);
1316 	if (adh->dead || adh->num_requests == 0) {
1317 		ret = (adh->dead) ? -1 : -2;
1318 		(void) pthread_mutex_unlock(&adh->lock);
1319 		return (ret);
1320 	}
1321 
1322 	/* Get one result */
1323 	rc = ldap_result(adh->ld, LDAP_RES_ANY, 0, timeout, &res);
1324 	if ((timeout != NULL && timeout->tv_sec > 0 && rc == LDAP_SUCCESS) ||
1325 	    rc < 0)
1326 		adh->dead = 1;
1327 
1328 	if (rc == LDAP_RES_SEARCH_RESULT && adh->num_requests > 0)
1329 		adh->num_requests--;
1330 	if (adh->dead) {
1331 		num = adh->num_requests;
1332 		(void) pthread_mutex_unlock(&adh->lock);
1333 		logger(LOG_DEBUG,
1334 		    "AD ldap_result error - %d queued requests", num);
1335 		return (-1);
1336 	}
1337 
1338 	switch (rc) {
1339 	case LDAP_RES_SEARCH_RESULT:
1340 		msgid = ldap_msgid(res);
1341 		if (msgid2query(adh, msgid, &query_state, &qid)) {
1342 			if (query_state->ldap_res_search_cb != NULL) {
1343 				/*
1344 				 * We use the caller-provided callback
1345 				 * to process the result.
1346 				 */
1347 				query_state->ldap_res_search_cb(
1348 				    adh->ld, &res, rc, qid,
1349 				    query_state->ldap_res_search_argp);
1350 				(void) pthread_mutex_unlock(&adh->lock);
1351 			} else {
1352 				/*
1353 				 * No callback. We fallback to our
1354 				 * default behaviour. All the entries
1355 				 * gotten from this search have been
1356 				 * added to the result list during
1357 				 * LDAP_RES_SEARCH_ENTRY (see below).
1358 				 * Here we set the return status to
1359 				 * notfound if the result is still empty.
1360 				 */
1361 				(void) pthread_mutex_unlock(&adh->lock);
1362 				que = &(query_state->queries[qid]);
1363 				if (*que->result == NULL)
1364 					*que->rc = ADUTILS_ERR_NOTFOUND;
1365 			}
1366 			atomic_dec_32(&query_state->qinflight);
1367 			adutils_lookup_batch_unlock(&query_state);
1368 		} else {
1369 			num = adh->num_requests;
1370 			(void) pthread_mutex_unlock(&adh->lock);
1371 			logger(LOG_DEBUG,
1372 			    "AD cannot find message ID (%d) "
1373 			    "- %d queued requests",
1374 			    msgid, num);
1375 		}
1376 		(void) ldap_msgfree(res);
1377 		ret = 0;
1378 		break;
1379 
1380 	case LDAP_RES_SEARCH_ENTRY:
1381 		msgid = ldap_msgid(res);
1382 		if (msgid2query(adh, msgid, &query_state, &qid)) {
1383 			if (query_state->ldap_res_search_cb != NULL) {
1384 				/*
1385 				 * We use the caller-provided callback
1386 				 * to process the entry.
1387 				 */
1388 				query_state->ldap_res_search_cb(
1389 				    adh->ld, &res, rc, qid,
1390 				    query_state->ldap_res_search_argp);
1391 				(void) pthread_mutex_unlock(&adh->lock);
1392 			} else {
1393 				/*
1394 				 * No callback. We fallback to our
1395 				 * default behaviour. This entry
1396 				 * will be added to the result list.
1397 				 */
1398 				que = &(query_state->queries[qid]);
1399 				rc = add_entry(adh, que, res);
1400 				(void) pthread_mutex_unlock(&adh->lock);
1401 				if (rc < 0) {
1402 					logger(LOG_DEBUG,
1403 					    "Failed to queue entry by "
1404 					    "message ID (%d) "
1405 					    "- %d queued requests",
1406 					    msgid, num);
1407 				}
1408 			}
1409 			adutils_lookup_batch_unlock(&query_state);
1410 		} else {
1411 			num = adh->num_requests;
1412 			(void) pthread_mutex_unlock(&adh->lock);
1413 			logger(LOG_DEBUG,
1414 			    "AD cannot find message ID (%d) "
1415 			    "- %d queued requests",
1416 			    msgid, num);
1417 		}
1418 		(void) ldap_msgfree(res);
1419 		ret = 0;
1420 		break;
1421 
1422 	case LDAP_RES_SEARCH_REFERENCE:
1423 		/*
1424 		 * We have no need for these at the moment.  Eventually,
1425 		 * when we query things that we can't expect to find in
1426 		 * the Global Catalog then we'll need to learn to follow
1427 		 * references.
1428 		 */
1429 		(void) pthread_mutex_unlock(&adh->lock);
1430 		(void) ldap_msgfree(res);
1431 		ret = 0;
1432 		break;
1433 
1434 	default:
1435 		/* timeout or error; treat the same */
1436 		(void) pthread_mutex_unlock(&adh->lock);
1437 		ret = -1;
1438 		break;
1439 	}
1440 
1441 	return (ret);
1442 }
1443 
1444 /*
1445  * This routine decreament the reference count of the
1446  * adutils_query_state_t
1447  */
1448 static void
1449 adutils_lookup_batch_unlock(adutils_query_state_t **state)
1450 {
1451 	/*
1452 	 * Decrement reference count with qstatelock locked
1453 	 */
1454 	(void) pthread_mutex_lock(&qstatelock);
1455 	(*state)->ref_cnt--;
1456 	/*
1457 	 * If there are no references wakup the allocating thread
1458 	 */
1459 	if ((*state)->ref_cnt <= 1)
1460 		(void) pthread_cond_signal(&(*state)->cv);
1461 	(void) pthread_mutex_unlock(&qstatelock);
1462 	*state = NULL;
1463 }
1464 
1465 /*
1466  * This routine frees the adutils_query_state_t structure
1467  * If the reference count is greater than 1 it waits
1468  * for the other threads to finish using it.
1469  */
1470 void
1471 adutils_lookup_batch_release(adutils_query_state_t **state)
1472 {
1473 	adutils_query_state_t **p;
1474 	int			i;
1475 
1476 	if (state == NULL || *state == NULL)
1477 		return;
1478 
1479 	/*
1480 	 * Set state to dead to stop further operations.
1481 	 * Wait for reference count with qstatelock locked
1482 	 * to get to one.
1483 	 */
1484 	(void) pthread_mutex_lock(&qstatelock);
1485 	(*state)->qdead = 1;
1486 	while ((*state)->ref_cnt > 1) {
1487 		(void) pthread_cond_wait(&(*state)->cv, &qstatelock);
1488 	}
1489 
1490 	/* Remove this state struct from the list of state structs */
1491 	for (p = &qstatehead; *p != NULL; p = &(*p)->next) {
1492 		if (*p == (*state)) {
1493 			*p = (*state)->next;
1494 			break;
1495 		}
1496 	}
1497 	(void) pthread_mutex_unlock(&qstatelock);
1498 	(void) pthread_cond_destroy(&(*state)->cv);
1499 	release_conn((*state)->qadh);
1500 
1501 	/* Clear results for queries that failed */
1502 	for (i = 0; i < (*state)->qcount; i++) {
1503 		if (*(*state)->queries[i].rc != ADUTILS_SUCCESS) {
1504 			adutils_freeresult((*state)->queries[i].result);
1505 		}
1506 	}
1507 	free(*state);
1508 	*state = NULL;
1509 }
1510 
1511 
1512 /*
1513  * This routine waits for other threads using the
1514  * adutils_query_state_t structure to finish.
1515  * If the reference count is greater than 1 it waits
1516  * for the other threads to finish using it.
1517  */
1518 static
1519 void
1520 adutils_lookup_batch_wait(adutils_query_state_t *state)
1521 {
1522 	/*
1523 	 * Set state to dead to stop further operation.
1524 	 * stating.
1525 	 * Wait for reference count to get to one
1526 	 * with qstatelock locked.
1527 	 */
1528 	(void) pthread_mutex_lock(&qstatelock);
1529 	state->qdead = 1;
1530 	while (state->ref_cnt > 1) {
1531 		(void) pthread_cond_wait(&state->cv, &qstatelock);
1532 	}
1533 	(void) pthread_mutex_unlock(&qstatelock);
1534 }
1535 
1536 /*
1537  * Process active queries in the AD lookup batch and then finalize the
1538  * result.
1539  */
1540 adutils_rc
1541 adutils_lookup_batch_end(adutils_query_state_t **state)
1542 {
1543 	int		    rc = LDAP_SUCCESS;
1544 	adutils_rc	    ad_rc = ADUTILS_SUCCESS;
1545 	struct timeval	    tv;
1546 
1547 	tv.tv_sec = ADUTILS_SEARCH_TIMEOUT;
1548 	tv.tv_usec = 0;
1549 
1550 	/* Process results until done or until timeout, if given */
1551 	while ((*state)->qinflight > 0) {
1552 		if ((rc = get_adobject_batch((*state)->qadh,
1553 		    &tv)) != 0)
1554 			break;
1555 	}
1556 	(*state)->qdead = 1;
1557 	/* Wait for other threads processing search result to finish */
1558 	adutils_lookup_batch_wait(*state);
1559 	if (rc == -1 || (*state)->qinflight != 0)
1560 		ad_rc = ADUTILS_ERR_RETRIABLE_NET_ERR;
1561 	adutils_lookup_batch_release(state);
1562 	return (ad_rc);
1563 }
1564 
1565 /*
1566  * Send one prepared search, queue up msgid, process what results are
1567  * available
1568  */
1569 adutils_rc
1570 adutils_lookup_batch_add(adutils_query_state_t *state,
1571 	const char *filter, const char * const *attrs, const char *edomain,
1572 	adutils_result_t **result, adutils_rc *rc)
1573 {
1574 	adutils_rc	retcode = ADUTILS_SUCCESS;
1575 	int		lrc, qid;
1576 	int		num;
1577 	int		dead;
1578 	struct timeval	tv;
1579 	adutils_q_t	*q;
1580 
1581 	qid = atomic_inc_32_nv(&state->qcount) - 1;
1582 	q = &(state->queries[qid]);
1583 
1584 	assert(qid < state->qsize);
1585 
1586 	/*
1587 	 * Remember the expected domain so we can check the results
1588 	 * against it
1589 	 */
1590 	q->edomain = edomain;
1591 
1592 	/* Remember where to put the results */
1593 	q->result = result;
1594 	q->rc = rc;
1595 
1596 	/*
1597 	 * Provide sane defaults for the results in case we never hear
1598 	 * back from the DS before closing the connection.
1599 	 */
1600 	*rc = ADUTILS_ERR_RETRIABLE_NET_ERR;
1601 	if (result != NULL)
1602 		*result = NULL;
1603 
1604 	/* Check the number of queued requests first */
1605 	tv.tv_sec = ADUTILS_SEARCH_TIMEOUT;
1606 	tv.tv_usec = 0;
1607 	while (!state->qadh->dead &&
1608 	    state->qadh->num_requests > state->qadh->max_requests) {
1609 		if (get_adobject_batch(state->qadh, &tv) != 0)
1610 			break;
1611 	}
1612 
1613 	/* Send this lookup, don't wait for a result here */
1614 	lrc = LDAP_SUCCESS;
1615 	(void) pthread_mutex_lock(&state->qadh->lock);
1616 
1617 	if (!state->qadh->dead) {
1618 		state->qadh->idletime = time(NULL);
1619 
1620 		lrc = ldap_search_ext(state->qadh->ld,
1621 		    state->qadh->owner->basedn,
1622 		    LDAP_SCOPE_SUBTREE, filter, (char **)attrs,
1623 		    0, NULL, NULL, NULL, -1, &q->msgid);
1624 
1625 		if (lrc == LDAP_SUCCESS) {
1626 			state->qadh->num_requests++;
1627 		} else if (lrc == LDAP_BUSY || lrc == LDAP_UNAVAILABLE ||
1628 		    lrc == LDAP_CONNECT_ERROR || lrc == LDAP_SERVER_DOWN ||
1629 		    lrc == LDAP_UNWILLING_TO_PERFORM) {
1630 			retcode = ADUTILS_ERR_RETRIABLE_NET_ERR;
1631 			state->qadh->dead = 1;
1632 		} else {
1633 			retcode = ADUTILS_ERR_OTHER;
1634 			state->qadh->dead = 1;
1635 		}
1636 	}
1637 	dead = state->qadh->dead;
1638 	num = state->qadh->num_requests;
1639 	(void) pthread_mutex_unlock(&state->qadh->lock);
1640 
1641 	if (dead) {
1642 		if (lrc != LDAP_SUCCESS)
1643 			logger(LOG_DEBUG,
1644 			    "AD ldap_search_ext error (%s) "
1645 			    "- %d queued requests",
1646 			    ldap_err2string(lrc), num);
1647 		return (retcode);
1648 	}
1649 
1650 	atomic_inc_32(&state->qinflight);
1651 
1652 	/*
1653 	 * Reap as many requests as we can _without_ waiting to prevent
1654 	 * any possible TCP socket buffer starvation deadlocks.
1655 	 */
1656 	(void) memset(&tv, 0, sizeof (tv));
1657 	while (get_adobject_batch(state->qadh, &tv) == 0)
1658 		;
1659 
1660 	return (ADUTILS_SUCCESS);
1661 }
1662 
1663 /*
1664  * Single AD lookup request implemented on top of the batch API.
1665  */
1666 adutils_rc
1667 adutils_lookup(adutils_ad_t *ad, const char *filter, const char **attrs,
1668 		const char *domain, adutils_result_t **result)
1669 {
1670 	adutils_rc		rc, brc;
1671 	adutils_query_state_t	*qs;
1672 
1673 	rc = adutils_lookup_batch_start(ad, 1, NULL, NULL, &qs);
1674 	if (rc != ADUTILS_SUCCESS)
1675 		return (rc);
1676 
1677 	rc = adutils_lookup_batch_add(qs, filter, attrs, domain, result, &brc);
1678 	if (rc != ADUTILS_SUCCESS) {
1679 		adutils_lookup_batch_release(&qs);
1680 		return (rc);
1681 	}
1682 
1683 	rc = adutils_lookup_batch_end(&qs);
1684 	if (rc != ADUTILS_SUCCESS)
1685 		return (rc);
1686 	return (brc);
1687 }
1688 
1689 boolean_t
1690 domain_eq(const char *a, const char *b)
1691 {
1692 	int err;
1693 
1694 	return (u8_strcmp(a, b, 0, U8_STRCMP_CI_LOWER, U8_UNICODE_LATEST, &err)
1695 	    == 0 && err == 0);
1696 }
1697