xref: /titanic_51/usr/src/lib/libadutils/common/adutils.c (revision 37d6e2456ee4a15f47fa97a2a2eae60a9b22bd87)
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;
867 
868 	for (i = 0; i < ad->num_known_domains; i++) {
869 		if (domain_eq(domain, ad->known_domains[i].name))
870 			return (1);
871 	}
872 
873 	return ((i == 0) ? 1 : 0);
874 }
875 
876 
877 /*
878  * Check that this AD supports the SID prefix.
879  * The SID prefix should match the domain SID.
880  * If there are no known domains assume that the
881  * SID prefix is supported by this AD.
882  *
883  * Returns 1 if this sid prefix is supported by this AD
884  * else returns 0;
885  */
886 
887 int
888 adutils_lookup_check_sid_prefix(adutils_query_state_t *qs, const char *sid)
889 {
890 	adutils_ad_t *ad = qs->qadh->owner;
891 	int i;
892 
893 
894 	for (i = 0; i < ad->num_known_domains; i++) {
895 		if (strcmp(sid, ad->known_domains[i].sid) == 0)
896 			return (1);
897 	}
898 
899 	return ((i == 0) ? 1 : 0);
900 }
901 
902 
903 adutils_rc
904 adutils_lookup_batch_start(adutils_ad_t *ad, int nqueries,
905 	adutils_ldap_res_search_cb ldap_res_search_cb,
906 	void *ldap_res_search_argp,
907 	adutils_query_state_t **state)
908 {
909 	adutils_query_state_t	*new_state;
910 	adutils_host_t		*adh = NULL;
911 
912 	if (ad == NULL)
913 		return (ADUTILS_ERR_INTERNAL);
914 
915 	*state = NULL;
916 	adh = get_conn(ad);
917 	if (adh == NULL)
918 		return (ADUTILS_ERR_RETRIABLE_NET_ERR);
919 
920 	new_state = calloc(1, sizeof (adutils_query_state_t) +
921 	    (nqueries - 1) * sizeof (adutils_q_t));
922 	if (new_state == NULL)
923 		return (ADUTILS_ERR_MEMORY);
924 
925 	/*
926 	 * Save default domain from the ad object so that we don't
927 	 * have to access the 'ad' object later.
928 	 */
929 	new_state->default_domain = strdup(adh->owner->dflt_w2k_dom);
930 	if (new_state->default_domain == NULL) {
931 		free(new_state);
932 		return (ADUTILS_ERR_MEMORY);
933 	}
934 
935 	if (ad->partition == ADUTILS_AD_DATA)
936 		new_state->basedn = adutils_dns2dn(new_state->default_domain);
937 	else
938 		new_state->basedn = strdup("");
939 	if (new_state->basedn == NULL) {
940 		free(new_state->default_domain);
941 		free(new_state);
942 		return (ADUTILS_ERR_MEMORY);
943 	}
944 
945 	new_state->ref_cnt = 1;
946 	new_state->qadh = adh;
947 	new_state->qsize = nqueries;
948 	new_state->qadh_gen = adh->generation;
949 	new_state->qcount = 0;
950 	new_state->ldap_res_search_cb = ldap_res_search_cb;
951 	new_state->ldap_res_search_argp = ldap_res_search_argp;
952 	(void) pthread_cond_init(&new_state->cv, NULL);
953 
954 	(void) pthread_mutex_lock(&qstatelock);
955 	new_state->next = qstatehead;
956 	qstatehead = new_state;
957 	(void) pthread_mutex_unlock(&qstatelock);
958 	*state = new_state;
959 
960 	return (ADUTILS_SUCCESS);
961 }
962 
963 /*
964  * Find the adutils_query_state_t to which a given LDAP result msgid on a
965  * given connection belongs. This routine increaments the reference count
966  * so that the object can not be freed. adutils_lookup_batch_unlock()
967  * must be called to decreament the reference count.
968  */
969 static
970 int
971 msgid2query(adutils_host_t *adh, int msgid,
972 	adutils_query_state_t **state, int *qid)
973 {
974 	adutils_query_state_t	*p;
975 	int			i;
976 	int			ret;
977 
978 	(void) pthread_mutex_lock(&qstatelock);
979 	for (p = qstatehead; p != NULL; p = p->next) {
980 		if (p->qadh != adh || adh->generation != p->qadh_gen)
981 			continue;
982 		for (i = 0; i < p->qcount; i++) {
983 			if ((p->queries[i]).msgid == msgid) {
984 				if (!p->qdead) {
985 					p->ref_cnt++;
986 					*state = p;
987 					*qid = i;
988 					ret = 1;
989 				} else
990 					ret = 0;
991 				(void) pthread_mutex_unlock(&qstatelock);
992 				return (ret);
993 			}
994 		}
995 	}
996 	(void) pthread_mutex_unlock(&qstatelock);
997 	return (0);
998 }
999 
1000 static
1001 int
1002 check_for_binary_attrs(const char *attr)
1003 {
1004 	int i;
1005 	for (i = 0; binattrs[i].name != NULL; i++) {
1006 		if (strcasecmp(binattrs[i].name, attr) == 0)
1007 			return (i);
1008 	}
1009 	return (-1);
1010 }
1011 
1012 static
1013 void
1014 free_entry(adutils_entry_t *entry)
1015 {
1016 	int		i, j;
1017 	adutils_attr_t	*ap;
1018 
1019 	if (entry == NULL)
1020 		return;
1021 	if (entry->attr_nvpairs == NULL) {
1022 		free(entry);
1023 		return;
1024 	}
1025 	for (i = 0; i < entry->num_nvpairs; i++) {
1026 		ap = &entry->attr_nvpairs[i];
1027 		if (ap->attr_name == NULL) {
1028 			ldap_value_free(ap->attr_values);
1029 			continue;
1030 		}
1031 		if (check_for_binary_attrs(ap->attr_name) >= 0) {
1032 			free(ap->attr_name);
1033 			if (ap->attr_values == NULL)
1034 				continue;
1035 			for (j = 0; j < ap->num_values; j++)
1036 				free(ap->attr_values[j]);
1037 			free(ap->attr_values);
1038 		} else if (strcasecmp(ap->attr_name, "dn") == 0) {
1039 			free(ap->attr_name);
1040 			ldap_memfree(ap->attr_values[0]);
1041 			free(ap->attr_values);
1042 		} else {
1043 			free(ap->attr_name);
1044 			ldap_value_free(ap->attr_values);
1045 		}
1046 	}
1047 	free(entry->attr_nvpairs);
1048 	free(entry);
1049 }
1050 
1051 void
1052 adutils_freeresult(adutils_result_t **result)
1053 {
1054 	adutils_entry_t	*e, *next;
1055 
1056 	if (result == NULL || *result == NULL)
1057 		return;
1058 	if ((*result)->entries == NULL) {
1059 		free(*result);
1060 		*result = NULL;
1061 		return;
1062 	}
1063 	for (e = (*result)->entries; e != NULL; e = next) {
1064 		next = e->next;
1065 		free_entry(e);
1066 	}
1067 	free(*result);
1068 	*result = NULL;
1069 }
1070 
1071 const adutils_entry_t *
1072 adutils_getfirstentry(adutils_result_t *result)
1073 {
1074 	if (result != NULL)
1075 		return (result->entries);
1076 	return (NULL);
1077 }
1078 
1079 
1080 char **
1081 adutils_getattr(const adutils_entry_t *entry, const char *attrname)
1082 {
1083 	int		i;
1084 	adutils_attr_t	*ap;
1085 
1086 	if (entry == NULL || entry->attr_nvpairs == NULL)
1087 		return (NULL);
1088 	for (i = 0; i < entry->num_nvpairs; i++) {
1089 		ap = &entry->attr_nvpairs[i];
1090 		if (ap->attr_name != NULL &&
1091 		    strcasecmp(ap->attr_name, attrname) == 0)
1092 			return (ap->attr_values);
1093 	}
1094 	return (NULL);
1095 }
1096 
1097 
1098 /*
1099  * Queue LDAP result for the given query.
1100  *
1101  * Return values:
1102  *  0 success
1103  * -1 ignore result
1104  * -2 error
1105  */
1106 static
1107 int
1108 make_entry(adutils_q_t *q, adutils_host_t *adh, LDAPMessage *search_res,
1109 	adutils_entry_t **entry)
1110 {
1111 	BerElement	*ber = NULL;
1112 	BerValue	**bvalues = NULL;
1113 	char		**strvalues;
1114 	char		*attr = NULL, *dn = NULL, *domain = NULL;
1115 	adutils_entry_t	*ep;
1116 	adutils_attr_t	*ap;
1117 	int		i, j, b, ret = -2;
1118 
1119 	*entry = NULL;
1120 
1121 	/* Check that this is the domain that we were looking for */
1122 	if ((dn = ldap_get_dn(adh->ld, search_res)) == NULL)
1123 		return (-2);
1124 	if ((domain = adutils_dn2dns(dn)) == NULL) {
1125 		ldap_memfree(dn);
1126 		return (-2);
1127 	}
1128 	if (q->edomain != NULL) {
1129 		if (!domain_eq(q->edomain, domain)) {
1130 			ldap_memfree(dn);
1131 			free(domain);
1132 			return (-1);
1133 		}
1134 	}
1135 	free(domain);
1136 
1137 	/* Allocate memory for the entry */
1138 	if ((ep = calloc(1, sizeof (*ep))) == NULL)
1139 		goto out;
1140 
1141 	/* For 'dn' */
1142 	ep->num_nvpairs = 1;
1143 
1144 	/* Count the number of name-value pairs for this entry */
1145 	for (attr = ldap_first_attribute(adh->ld, search_res, &ber);
1146 	    attr != NULL;
1147 	    attr = ldap_next_attribute(adh->ld, search_res, ber)) {
1148 		ep->num_nvpairs++;
1149 		ldap_memfree(attr);
1150 	}
1151 	ber_free(ber, 0);
1152 	ber = NULL;
1153 
1154 	/* Allocate array for the attribute name-value pairs */
1155 	ep->attr_nvpairs = calloc(ep->num_nvpairs, sizeof (*ep->attr_nvpairs));
1156 	if (ep->attr_nvpairs == NULL) {
1157 		ep->num_nvpairs = 0;
1158 		goto out;
1159 	}
1160 
1161 	/* For dn */
1162 	ap = &ep->attr_nvpairs[0];
1163 	if ((ap->attr_name = strdup("dn")) == NULL)
1164 		goto out;
1165 	ap->num_values = 1;
1166 	ap->attr_values = calloc(ap->num_values, sizeof (*ap->attr_values));
1167 	if (ap->attr_values == NULL) {
1168 		ap->num_values = 0;
1169 		goto out;
1170 	}
1171 	ap->attr_values[0] = dn;
1172 	dn = NULL;
1173 
1174 	for (attr = ldap_first_attribute(adh->ld, search_res, &ber), i = 1;
1175 	    attr != NULL;
1176 	    ldap_memfree(attr), i++,
1177 	    attr = ldap_next_attribute(adh->ld, search_res, ber)) {
1178 		ap = &ep->attr_nvpairs[i];
1179 		if ((ap->attr_name = strdup(attr)) == NULL)
1180 			goto out;
1181 
1182 		if ((b = check_for_binary_attrs(attr)) >= 0) {
1183 			bvalues =
1184 			    ldap_get_values_len(adh->ld, search_res, attr);
1185 			if (bvalues == NULL)
1186 				continue;
1187 			ap->num_values = ldap_count_values_len(bvalues);
1188 			if (ap->num_values == 0) {
1189 				ldap_value_free_len(bvalues);
1190 				bvalues = NULL;
1191 				continue;
1192 			}
1193 			ap->attr_values = calloc(ap->num_values,
1194 			    sizeof (*ap->attr_values));
1195 			if (ap->attr_values == NULL) {
1196 				ap->num_values = 0;
1197 				goto out;
1198 			}
1199 			for (j = 0; j < ap->num_values; j++) {
1200 				ap->attr_values[j] =
1201 				    binattrs[b].ber2str(bvalues[j]);
1202 				if (ap->attr_values[j] == NULL)
1203 					goto out;
1204 			}
1205 			ldap_value_free_len(bvalues);
1206 			bvalues = NULL;
1207 			continue;
1208 		}
1209 
1210 		strvalues = ldap_get_values(adh->ld, search_res, attr);
1211 		if (strvalues == NULL)
1212 			continue;
1213 		ap->num_values = ldap_count_values(strvalues);
1214 		if (ap->num_values == 0) {
1215 			ldap_value_free(strvalues);
1216 			continue;
1217 		}
1218 		ap->attr_values = strvalues;
1219 	}
1220 
1221 	ret = 0;
1222 out:
1223 	ldap_memfree(attr);
1224 	ldap_memfree(dn);
1225 	ber_free(ber, 0);
1226 	ldap_value_free_len(bvalues);
1227 	if (ret < 0)
1228 		free_entry(ep);
1229 	else
1230 		*entry = ep;
1231 	return (ret);
1232 }
1233 
1234 /*
1235  * Put the search result onto the given adutils_q_t.
1236  * Returns:	  0 success
1237  *		< 0 error
1238  */
1239 static
1240 int
1241 add_entry(adutils_host_t *adh, adutils_q_t *q, LDAPMessage *search_res)
1242 {
1243 	int			ret = -1;
1244 	adutils_entry_t		*entry = NULL;
1245 	adutils_result_t	*res;
1246 
1247 	ret = make_entry(q, adh, search_res, &entry);
1248 	if (ret < -1) {
1249 		*q->rc = ADUTILS_ERR_MEMORY;
1250 		goto out;
1251 	} else if (ret == -1) {
1252 		/* ignore result */
1253 		goto out;
1254 	}
1255 	if (*q->result == NULL) {
1256 		res = calloc(1, sizeof (*res));
1257 		if (res == NULL) {
1258 			*q->rc = ADUTILS_ERR_MEMORY;
1259 			goto out;
1260 		}
1261 		res->num_entries = 1;
1262 		res->entries = entry;
1263 		*q->result = res;
1264 	} else {
1265 		res = *q->result;
1266 		entry->next = res->entries;
1267 		res->entries = entry;
1268 		res->num_entries++;
1269 	}
1270 	*q->rc = ADUTILS_SUCCESS;
1271 	entry = NULL;
1272 	ret = 0;
1273 
1274 out:
1275 	free_entry(entry);
1276 	return (ret);
1277 }
1278 
1279 /*
1280  * Try to get a result; if there is one, find the corresponding
1281  * adutils_q_t and process the result.
1282  *
1283  * Returns:	0 success
1284  *		-1 error
1285  */
1286 static
1287 int
1288 get_adobject_batch(adutils_host_t *adh, struct timeval *timeout)
1289 {
1290 	adutils_query_state_t	*query_state;
1291 	LDAPMessage		*res = NULL;
1292 	int			rc, ret, msgid, qid;
1293 	adutils_q_t		*que;
1294 	int			num;
1295 
1296 	(void) pthread_mutex_lock(&adh->lock);
1297 	if (adh->dead || adh->num_requests == 0) {
1298 		ret = (adh->dead) ? -1 : -2;
1299 		(void) pthread_mutex_unlock(&adh->lock);
1300 		return (ret);
1301 	}
1302 
1303 	/* Get one result */
1304 	rc = ldap_result(adh->ld, LDAP_RES_ANY, 0, timeout, &res);
1305 	if ((timeout != NULL && timeout->tv_sec > 0 && rc == LDAP_SUCCESS) ||
1306 	    rc < 0)
1307 		adh->dead = 1;
1308 
1309 	if (rc == LDAP_RES_SEARCH_RESULT && adh->num_requests > 0)
1310 		adh->num_requests--;
1311 	if (adh->dead) {
1312 		num = adh->num_requests;
1313 		(void) pthread_mutex_unlock(&adh->lock);
1314 		logger(LOG_DEBUG,
1315 		    "AD ldap_result error - %d queued requests", num);
1316 		return (-1);
1317 	}
1318 
1319 	switch (rc) {
1320 	case LDAP_RES_SEARCH_RESULT:
1321 		msgid = ldap_msgid(res);
1322 		if (msgid2query(adh, msgid, &query_state, &qid)) {
1323 			if (query_state->ldap_res_search_cb != NULL) {
1324 				/*
1325 				 * We use the caller-provided callback
1326 				 * to process the result.
1327 				 */
1328 				query_state->ldap_res_search_cb(
1329 				    adh->ld, &res, rc, qid,
1330 				    query_state->ldap_res_search_argp);
1331 				(void) pthread_mutex_unlock(&adh->lock);
1332 			} else {
1333 				/*
1334 				 * No callback. We fallback to our
1335 				 * default behaviour. All the entries
1336 				 * gotten from this search have been
1337 				 * added to the result list during
1338 				 * LDAP_RES_SEARCH_ENTRY (see below).
1339 				 * Here we set the return status to
1340 				 * notfound if the result is still empty.
1341 				 */
1342 				(void) pthread_mutex_unlock(&adh->lock);
1343 				que = &(query_state->queries[qid]);
1344 				if (*que->result == NULL)
1345 					*que->rc = ADUTILS_ERR_NOTFOUND;
1346 			}
1347 			atomic_dec_32(&query_state->qinflight);
1348 			adutils_lookup_batch_unlock(&query_state);
1349 		} else {
1350 			num = adh->num_requests;
1351 			(void) pthread_mutex_unlock(&adh->lock);
1352 			logger(LOG_DEBUG,
1353 			    "AD cannot find message ID (%d) "
1354 			    "- %d queued requests",
1355 			    msgid, num);
1356 		}
1357 		(void) ldap_msgfree(res);
1358 		ret = 0;
1359 		break;
1360 
1361 	case LDAP_RES_SEARCH_ENTRY:
1362 		msgid = ldap_msgid(res);
1363 		if (msgid2query(adh, msgid, &query_state, &qid)) {
1364 			if (query_state->ldap_res_search_cb != NULL) {
1365 				/*
1366 				 * We use the caller-provided callback
1367 				 * to process the entry.
1368 				 */
1369 				query_state->ldap_res_search_cb(
1370 				    adh->ld, &res, rc, qid,
1371 				    query_state->ldap_res_search_argp);
1372 				(void) pthread_mutex_unlock(&adh->lock);
1373 			} else {
1374 				/*
1375 				 * No callback. We fallback to our
1376 				 * default behaviour. This entry
1377 				 * will be added to the result list.
1378 				 */
1379 				que = &(query_state->queries[qid]);
1380 				rc = add_entry(adh, que, res);
1381 				(void) pthread_mutex_unlock(&adh->lock);
1382 				if (rc < 0) {
1383 					logger(LOG_DEBUG,
1384 					    "Failed to queue entry by "
1385 					    "message ID (%d) "
1386 					    "- %d queued requests",
1387 					    msgid, num);
1388 				}
1389 			}
1390 			adutils_lookup_batch_unlock(&query_state);
1391 		} else {
1392 			num = adh->num_requests;
1393 			(void) pthread_mutex_unlock(&adh->lock);
1394 			logger(LOG_DEBUG,
1395 			    "AD cannot find message ID (%d) "
1396 			    "- %d queued requests",
1397 			    msgid, num);
1398 		}
1399 		(void) ldap_msgfree(res);
1400 		ret = 0;
1401 		break;
1402 
1403 	case LDAP_RES_SEARCH_REFERENCE:
1404 		/*
1405 		 * We have no need for these at the moment.  Eventually,
1406 		 * when we query things that we can't expect to find in
1407 		 * the Global Catalog then we'll need to learn to follow
1408 		 * references.
1409 		 */
1410 		(void) pthread_mutex_unlock(&adh->lock);
1411 		(void) ldap_msgfree(res);
1412 		ret = 0;
1413 		break;
1414 
1415 	default:
1416 		/* timeout or error; treat the same */
1417 		(void) pthread_mutex_unlock(&adh->lock);
1418 		ret = -1;
1419 		break;
1420 	}
1421 
1422 	return (ret);
1423 }
1424 
1425 /*
1426  * This routine decreament the reference count of the
1427  * adutils_query_state_t
1428  */
1429 static void
1430 adutils_lookup_batch_unlock(adutils_query_state_t **state)
1431 {
1432 	/*
1433 	 * Decrement reference count with qstatelock locked
1434 	 */
1435 	(void) pthread_mutex_lock(&qstatelock);
1436 	(*state)->ref_cnt--;
1437 	/*
1438 	 * If there are no references wakup the allocating thread
1439 	 */
1440 	if ((*state)->ref_cnt <= 1)
1441 		(void) pthread_cond_signal(&(*state)->cv);
1442 	(void) pthread_mutex_unlock(&qstatelock);
1443 	*state = NULL;
1444 }
1445 
1446 /*
1447  * This routine frees the adutils_query_state_t structure
1448  * If the reference count is greater than 1 it waits
1449  * for the other threads to finish using it.
1450  */
1451 void
1452 adutils_lookup_batch_release(adutils_query_state_t **state)
1453 {
1454 	adutils_query_state_t **p;
1455 	int			i;
1456 
1457 	if (state == NULL || *state == NULL)
1458 		return;
1459 
1460 	/*
1461 	 * Set state to dead to stop further operations.
1462 	 * Wait for reference count with qstatelock locked
1463 	 * to get to one.
1464 	 */
1465 	(void) pthread_mutex_lock(&qstatelock);
1466 	(*state)->qdead = 1;
1467 	while ((*state)->ref_cnt > 1) {
1468 		(void) pthread_cond_wait(&(*state)->cv, &qstatelock);
1469 	}
1470 
1471 	/* Remove this state struct from the list of state structs */
1472 	for (p = &qstatehead; *p != NULL; p = &(*p)->next) {
1473 		if (*p == (*state)) {
1474 			*p = (*state)->next;
1475 			break;
1476 		}
1477 	}
1478 	(void) pthread_mutex_unlock(&qstatelock);
1479 	(void) pthread_cond_destroy(&(*state)->cv);
1480 	release_conn((*state)->qadh);
1481 
1482 	/* Clear results for queries that failed */
1483 	for (i = 0; i < (*state)->qcount; i++) {
1484 		if (*(*state)->queries[i].rc != ADUTILS_SUCCESS) {
1485 			adutils_freeresult((*state)->queries[i].result);
1486 		}
1487 	}
1488 	free((*state)->default_domain);
1489 	free((*state)->basedn);
1490 	free(*state);
1491 	*state = NULL;
1492 }
1493 
1494 
1495 /*
1496  * This routine waits for other threads using the
1497  * adutils_query_state_t structure to finish.
1498  * If the reference count is greater than 1 it waits
1499  * for the other threads to finish using it.
1500  */
1501 static
1502 void
1503 adutils_lookup_batch_wait(adutils_query_state_t *state)
1504 {
1505 	/*
1506 	 * Set state to dead to stop further operation.
1507 	 * stating.
1508 	 * Wait for reference count to get to one
1509 	 * with qstatelock locked.
1510 	 */
1511 	(void) pthread_mutex_lock(&qstatelock);
1512 	state->qdead = 1;
1513 	while (state->ref_cnt > 1) {
1514 		(void) pthread_cond_wait(&state->cv, &qstatelock);
1515 	}
1516 	(void) pthread_mutex_unlock(&qstatelock);
1517 }
1518 
1519 /*
1520  * Process active queries in the AD lookup batch and then finalize the
1521  * result.
1522  */
1523 adutils_rc
1524 adutils_lookup_batch_end(adutils_query_state_t **state)
1525 {
1526 	int		    rc = LDAP_SUCCESS;
1527 	adutils_rc	    ad_rc = ADUTILS_SUCCESS;
1528 	struct timeval	    tv;
1529 
1530 	tv.tv_sec = ADUTILS_SEARCH_TIMEOUT;
1531 	tv.tv_usec = 0;
1532 
1533 	/* Process results until done or until timeout, if given */
1534 	while ((*state)->qinflight > 0) {
1535 		if ((rc = get_adobject_batch((*state)->qadh,
1536 		    &tv)) != 0)
1537 			break;
1538 	}
1539 	(*state)->qdead = 1;
1540 	/* Wait for other threads processing search result to finish */
1541 	adutils_lookup_batch_wait(*state);
1542 	if (rc == -1 || (*state)->qinflight != 0)
1543 		ad_rc = ADUTILS_ERR_RETRIABLE_NET_ERR;
1544 	adutils_lookup_batch_release(state);
1545 	return (ad_rc);
1546 }
1547 
1548 const char *
1549 adutils_lookup_batch_getdefdomain(adutils_query_state_t *state)
1550 {
1551 	return (state->default_domain);
1552 }
1553 
1554 /*
1555  * Send one prepared search, queue up msgid, process what results are
1556  * available
1557  */
1558 adutils_rc
1559 adutils_lookup_batch_add(adutils_query_state_t *state,
1560 	const char *filter, const char * const *attrs, const char *edomain,
1561 	adutils_result_t **result, adutils_rc *rc)
1562 {
1563 	adutils_rc	retcode = ADUTILS_SUCCESS;
1564 	int		lrc, qid;
1565 	int		num;
1566 	int		dead;
1567 	struct timeval	tv;
1568 	adutils_q_t	*q;
1569 
1570 	qid = atomic_inc_32_nv(&state->qcount) - 1;
1571 	q = &(state->queries[qid]);
1572 
1573 	assert(qid < state->qsize);
1574 
1575 	/*
1576 	 * Remember the expected domain so we can check the results
1577 	 * against it
1578 	 */
1579 	q->edomain = edomain;
1580 
1581 	/* Remember where to put the results */
1582 	q->result = result;
1583 	q->rc = rc;
1584 
1585 	/*
1586 	 * Provide sane defaults for the results in case we never hear
1587 	 * back from the DS before closing the connection.
1588 	 */
1589 	*rc = ADUTILS_ERR_RETRIABLE_NET_ERR;
1590 	if (result != NULL)
1591 		*result = NULL;
1592 
1593 	/* Check the number of queued requests first */
1594 	tv.tv_sec = ADUTILS_SEARCH_TIMEOUT;
1595 	tv.tv_usec = 0;
1596 	while (!state->qadh->dead &&
1597 	    state->qadh->num_requests > state->qadh->max_requests) {
1598 		if (get_adobject_batch(state->qadh, &tv) != 0)
1599 			break;
1600 	}
1601 
1602 	/* Send this lookup, don't wait for a result here */
1603 	lrc = LDAP_SUCCESS;
1604 	(void) pthread_mutex_lock(&state->qadh->lock);
1605 
1606 	if (!state->qadh->dead) {
1607 		state->qadh->idletime = time(NULL);
1608 		lrc = ldap_search_ext(state->qadh->ld, state->basedn,
1609 		    LDAP_SCOPE_SUBTREE, filter, (char **)attrs,
1610 		    0, NULL, NULL, NULL, -1, &q->msgid);
1611 
1612 		if (lrc == LDAP_SUCCESS) {
1613 			state->qadh->num_requests++;
1614 		} else if (lrc == LDAP_BUSY || lrc == LDAP_UNAVAILABLE ||
1615 		    lrc == LDAP_CONNECT_ERROR || lrc == LDAP_SERVER_DOWN ||
1616 		    lrc == LDAP_UNWILLING_TO_PERFORM) {
1617 			retcode = ADUTILS_ERR_RETRIABLE_NET_ERR;
1618 			state->qadh->dead = 1;
1619 		} else {
1620 			retcode = ADUTILS_ERR_OTHER;
1621 			state->qadh->dead = 1;
1622 		}
1623 	}
1624 	dead = state->qadh->dead;
1625 	num = state->qadh->num_requests;
1626 	(void) pthread_mutex_unlock(&state->qadh->lock);
1627 
1628 	if (dead) {
1629 		if (lrc != LDAP_SUCCESS)
1630 			logger(LOG_DEBUG,
1631 			    "AD ldap_search_ext error (%s) "
1632 			    "- %d queued requests",
1633 			    ldap_err2string(lrc), num);
1634 		return (retcode);
1635 	}
1636 
1637 	atomic_inc_32(&state->qinflight);
1638 
1639 	/*
1640 	 * Reap as many requests as we can _without_ waiting to prevent
1641 	 * any possible TCP socket buffer starvation deadlocks.
1642 	 */
1643 	(void) memset(&tv, 0, sizeof (tv));
1644 	while (get_adobject_batch(state->qadh, &tv) == 0)
1645 		;
1646 
1647 	return (ADUTILS_SUCCESS);
1648 }
1649 
1650 /*
1651  * Single AD lookup request implemented on top of the batch API.
1652  */
1653 adutils_rc
1654 adutils_lookup(adutils_ad_t *ad, const char *filter, const char **attrs,
1655 		const char *domain, adutils_result_t **result)
1656 {
1657 	adutils_rc		rc, brc;
1658 	adutils_query_state_t	*qs;
1659 
1660 	rc = adutils_lookup_batch_start(ad, 1, NULL, NULL, &qs);
1661 	if (rc != ADUTILS_SUCCESS)
1662 		return (rc);
1663 
1664 	rc = adutils_lookup_batch_add(qs, filter, attrs, domain, result, &brc);
1665 	if (rc != ADUTILS_SUCCESS) {
1666 		adutils_lookup_batch_release(&qs);
1667 		return (rc);
1668 	}
1669 
1670 	rc = adutils_lookup_batch_end(&qs);
1671 	if (rc != ADUTILS_SUCCESS)
1672 		return (rc);
1673 	return (brc);
1674 }
1675 
1676 boolean_t
1677 domain_eq(const char *a, const char *b)
1678 {
1679 	int err;
1680 
1681 	return (u8_strcmp(a, b, 0, U8_STRCMP_CI_LOWER, U8_UNICODE_LATEST, &err)
1682 	    == 0 && err == 0);
1683 }
1684