xref: /titanic_52/usr/src/cmd/idmap/idmapd/adutils.c (revision 80feccabd0bc0fca1df2b60bfa50449d9a6e3e09)
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 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * Processes name2sid & sid2name batched lookups for a given user or
31  * computer from an AD Directory server using GSSAPI authentication
32  */
33 
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <alloca.h>
37 #include <string.h>
38 #include <strings.h>
39 #include <lber.h>
40 #include <ldap.h>
41 #include <sasl/sasl.h>
42 #include <string.h>
43 #include <ctype.h>
44 #include <pthread.h>
45 #include <synch.h>
46 #include <atomic.h>
47 #include <errno.h>
48 #include <assert.h>
49 #include <limits.h>
50 #include <sys/u8_textprep.h>
51 #include "idmapd.h"
52 
53 /*
54  * Internal data structures for this code
55  */
56 
57 /* Attribute names and filter format strings */
58 #define	SAN		"sAMAccountName"
59 #define	OBJSID		"objectSid"
60 #define	OBJCLASS	"objectClass"
61 #define	SANFILTER	"(sAMAccountName=%.*s)"
62 #define	OBJSIDFILTER	"(objectSid=%s)"
63 
64 /*
65  * This should really be in some <sys/sid.h> file or so; we have a
66  * private version of sid_t, and so must other components of ON until we
67  * rationalize this.
68  */
69 typedef struct sid {
70 	uchar_t		version;
71 	uchar_t		sub_authority_count;
72 	uint64_t	authority;  /* really, 48-bits */
73 	rid_t		sub_authorities[SID_MAX_SUB_AUTHORITIES];
74 } sid_t;
75 
76 /* A single DS */
77 typedef struct ad_host {
78 	struct ad_host		*next;
79 	ad_t			*owner;		/* ad_t to which this belongs */
80 	pthread_mutex_t		lock;
81 	LDAP			*ld;		/* LDAP connection */
82 	uint32_t		ref;		/* ref count */
83 	time_t			idletime;	/* time since last activity */
84 	int			dead;		/* error on LDAP connection */
85 	/*
86 	 * Used to distinguish between different instances of LDAP
87 	 * connections to this same DS.  We need this so we never mix up
88 	 * results for a given msgID from one connection with those of
89 	 * another earlier connection where two batch state structures
90 	 * share this ad_host object but used different LDAP connections
91 	 * to send their LDAP searches.
92 	 */
93 	uint64_t		generation;
94 
95 	/* LDAP DS info */
96 	char			*host;
97 	int			port;
98 
99 	/* hardwired to SASL GSSAPI only for now */
100 	char			*saslmech;
101 	unsigned		saslflags;
102 } ad_host_t;
103 
104 /* A set of DSs for a given AD partition; ad_t typedef comes from  adutil.h */
105 struct ad {
106 	char			*dflt_w2k_dom;	/* used to qualify bare names */
107 	pthread_mutex_t		lock;
108 	uint32_t		ref;
109 	ad_host_t		*last_adh;
110 	idmap_ad_partition_t	partition;	/* Data or global catalog? */
111 };
112 
113 /*
114  * A place to put the results of a batched (async) query
115  *
116  * There is one of these for every query added to a batch object
117  * (idmap_query_state, see below).
118  */
119 typedef struct idmap_q {
120 	/*
121 	 * data used for validating search result entries for name->SID
122 	 * lookups
123 	 */
124 	char			*ecanonname;	/* expected canon name */
125 	char			*edomain;	/* expected domain name */
126 	int			eunixtype;	/* expected unix type */
127 	/* results */
128 	char			**canonname;	/* actual canon name */
129 	char			**domain;	/* name of domain of object */
130 	char			**sid;		/* stringified SID */
131 	rid_t			*rid;		/* RID */
132 	int			*sid_type;	/* user or group SID? */
133 	char			**unixname;	/* unixname for name mapping */
134 	idmap_retcode		*rc;
135 
136 	/* lookup state */
137 	int			msgid;		/* LDAP message ID */
138 } idmap_q_t;
139 
140 /* Batch context structure; typedef is in header file */
141 struct idmap_query_state {
142 	idmap_query_state_t	*next;
143 	int			qcount;		/* how many queries */
144 	int			ref_cnt;	/* reference count */
145 	pthread_cond_t		cv;		/* Condition wait variable */
146 	uint32_t		qlastsent;
147 	uint32_t		qinflight;	/* how many queries in flight */
148 	uint16_t		qdead;		/* oops, lost LDAP connection */
149 	ad_host_t		*qadh;		/* LDAP connection */
150 	uint64_t		qadh_gen;	/* same as qadh->generation */
151 	const char		*ad_unixuser_attr;
152 	const char		*ad_unixgroup_attr;
153 	idmap_q_t		queries[1];	/* array of query results */
154 };
155 
156 /*
157  * List of query state structs -- needed so we can "route" LDAP results
158  * to the right context if multiple threads should be using the same
159  * connection concurrently
160  */
161 static idmap_query_state_t	*qstatehead = NULL;
162 static pthread_mutex_t		qstatelock = PTHREAD_MUTEX_INITIALIZER;
163 
164 /*
165  * List of DSs, needed by the idle connection reaper thread
166  */
167 static ad_host_t	*host_head = NULL;
168 static pthread_t	reaperid = 0;
169 static pthread_mutex_t	adhostlock = PTHREAD_MUTEX_INITIALIZER;
170 
171 
172 static void
173 idmap_lookup_unlock_batch(idmap_query_state_t **state);
174 
175 static void
176 delete_ds(ad_t *ad, const char *host, int port);
177 
178 /*ARGSUSED*/
179 static int
180 idmap_saslcallback(LDAP *ld, unsigned flags, void *defaults, void *prompts)
181 {
182 	sasl_interact_t	*interact;
183 
184 	if (prompts == NULL || flags != LDAP_SASL_INTERACTIVE)
185 		return (LDAP_PARAM_ERROR);
186 
187 	/* There should be no extra arguemnts for SASL/GSSAPI authentication */
188 	for (interact = prompts; interact->id != SASL_CB_LIST_END;
189 	    interact++) {
190 		interact->result = NULL;
191 		interact->len = 0;
192 	}
193 	return (LDAP_SUCCESS);
194 }
195 
196 
197 /*
198  * Turn "dc=foo,dc=bar,dc=com" into "foo.bar.com"; ignores any other
199  * attributes (CN, etc...).  We don't need the reverse, for now.
200  */
201 static
202 char *
203 dn2dns(const char *dn)
204 {
205 	char **rdns = NULL;
206 	char **attrs = NULL;
207 	char **labels = NULL;
208 	char *dns = NULL;
209 	char **rdn, **attr, **label;
210 	int maxlabels = 5;
211 	int nlabels = 0;
212 	int dnslen;
213 
214 	/*
215 	 * There is no reverse of ldap_dns_to_dn() in our libldap, so we
216 	 * have to do the hard work here for now.
217 	 */
218 
219 	/*
220 	 * This code is much too liberal: it looks for "dc" attributes
221 	 * in all RDNs of the DN.  In theory this could cause problems
222 	 * if people were to use "dc" in nodes other than the root of
223 	 * the tree, but in practice noone, least of all Active
224 	 * Directory, does that.
225 	 *
226 	 * On the other hand, this code is much too conservative: it
227 	 * does not make assumptions about ldap_explode_dn(), and _that_
228 	 * is the true for looking at every attr of every RDN.
229 	 *
230 	 * Since we only ever look at dc and those must be DNS labels,
231 	 * at least until we get around to supporting IDN here we
232 	 * shouldn't see escaped labels from AD nor from libldap, though
233 	 * the spec (RFC2253) does allow libldap to escape things that
234 	 * don't need escaping -- if that should ever happen then
235 	 * libldap will need a spanking, and we can take care of that.
236 	 */
237 
238 	/* Explode a DN into RDNs */
239 	if ((rdns = ldap_explode_dn(dn, 0)) == NULL)
240 		return (NULL);
241 
242 	labels = calloc(maxlabels + 1, sizeof (char *));
243 	label = labels;
244 
245 	for (rdn = rdns; *rdn != NULL; rdn++) {
246 		if (attrs != NULL)
247 			ldap_value_free(attrs);
248 
249 		/* Explode each RDN, look for DC attr, save val as DNS label */
250 		if ((attrs = ldap_explode_rdn(rdn[0], 0)) == NULL)
251 			goto done;
252 
253 		for (attr = attrs; *attr != NULL; attr++) {
254 			if (strncasecmp(*attr, "dc=", 3) != 0)
255 				continue;
256 
257 			/* Found a DNS label */
258 			labels[nlabels++] = strdup((*attr) + 3);
259 
260 			if (nlabels == maxlabels) {
261 				char **tmp;
262 				tmp = realloc(labels,
263 				    sizeof (char *) * (maxlabels + 1));
264 
265 				if (tmp == NULL)
266 					goto done;
267 
268 				labels = tmp;
269 				labels[nlabels] = NULL;
270 			}
271 
272 			/* There should be just one DC= attr per-RDN */
273 			break;
274 		}
275 	}
276 
277 	/*
278 	 * Got all the labels, now join with '.'
279 	 *
280 	 * We need room for nlabels - 1 periods ('.'), one nul
281 	 * terminator, and the strlen() of each label.
282 	 */
283 	dnslen = nlabels;
284 	for (label = labels; *label != NULL; label++)
285 		dnslen += strlen(*label);
286 
287 	if ((dns = malloc(dnslen)) == NULL)
288 		goto done;
289 
290 	*dns = '\0';
291 
292 	for (label = labels; *label != NULL; label++) {
293 		(void) strlcat(dns, *label, dnslen);
294 		/*
295 		 * NOTE: the last '.' won't be appended -- there's no room
296 		 * for it!
297 		 */
298 		(void) strlcat(dns, ".", dnslen);
299 	}
300 
301 done:
302 	if (labels != NULL) {
303 		for (label = labels; *label != NULL; label++)
304 			free(*label);
305 		free(labels);
306 	}
307 	if (attrs != NULL)
308 		ldap_value_free(attrs);
309 	if (rdns != NULL)
310 		ldap_value_free(rdns);
311 
312 	return (dns);
313 }
314 
315 /*
316  * Keep connection management simple for now, extend or replace later
317  * with updated libsldap code.
318  */
319 #define	ADREAPERSLEEP	60
320 #define	ADCONN_TIME	300
321 
322 /*
323  * Idle connection reaping side of connection management
324  *
325  * Every minute wake up and look for connections that have been idle for
326  * five minutes or more and close them.
327  */
328 /*ARGSUSED*/
329 static
330 void
331 adreaper(void *arg)
332 {
333 	ad_host_t	*adh;
334 	time_t		now;
335 	timespec_t	ts;
336 
337 	ts.tv_sec = ADREAPERSLEEP;
338 	ts.tv_nsec = 0;
339 
340 	for (;;) {
341 		/*
342 		 * nanosleep(3RT) is thead-safe (no SIGALRM) and more
343 		 * portable than usleep(3C)
344 		 */
345 		(void) nanosleep(&ts, NULL);
346 		(void) pthread_mutex_lock(&adhostlock);
347 		now = time(NULL);
348 		for (adh = host_head; adh != NULL; adh = adh->next) {
349 			(void) pthread_mutex_lock(&adh->lock);
350 			if (adh->ref == 0 && adh->idletime != 0 &&
351 			    adh->idletime + ADCONN_TIME < now) {
352 				if (adh->ld) {
353 					(void) ldap_unbind(adh->ld);
354 					adh->ld = NULL;
355 					adh->idletime = 0;
356 					adh->ref = 0;
357 				}
358 			}
359 			(void) pthread_mutex_unlock(&adh->lock);
360 		}
361 		(void) pthread_mutex_unlock(&adhostlock);
362 	}
363 }
364 
365 int
366 idmap_ad_alloc(ad_t **new_ad, const char *default_domain,
367 		idmap_ad_partition_t part)
368 {
369 	ad_t *ad;
370 
371 	*new_ad = NULL;
372 
373 	if ((default_domain == NULL || *default_domain == '\0') &&
374 	    part != IDMAP_AD_GLOBAL_CATALOG)
375 		return (-1);
376 
377 	if ((ad = calloc(1, sizeof (ad_t))) == NULL)
378 		return (-1);
379 
380 	ad->ref = 1;
381 	ad->partition = part;
382 
383 	/*
384 	 * If default_domain is NULL, deal, deferring errors until
385 	 * idmap_lookup_batch_start() -- this makes it easier on the
386 	 * caller, who can simply observe lookups failing as opposed to
387 	 * having to conditionalize calls to lookups according to
388 	 * whether it has a non-NULL ad_t *.
389 	 */
390 	if (default_domain == NULL)
391 		default_domain = "";
392 
393 	if ((ad->dflt_w2k_dom = strdup(default_domain)) == NULL)
394 		goto err;
395 
396 	if (pthread_mutex_init(&ad->lock, NULL) != 0)
397 		goto err;
398 
399 	*new_ad = ad;
400 
401 	return (0);
402 err:
403 	if (ad->dflt_w2k_dom != NULL)
404 		free(ad->dflt_w2k_dom);
405 	free(ad);
406 	return (-1);
407 }
408 
409 
410 void
411 idmap_ad_free(ad_t **ad)
412 {
413 	ad_host_t *p;
414 	ad_host_t *prev;
415 
416 	if (ad == NULL || *ad == NULL)
417 		return;
418 
419 	(void) pthread_mutex_lock(&(*ad)->lock);
420 
421 	if (atomic_dec_32_nv(&(*ad)->ref) > 0) {
422 		(void) pthread_mutex_unlock(&(*ad)->lock);
423 		*ad = NULL;
424 		return;
425 	}
426 
427 	(void) pthread_mutex_lock(&adhostlock);
428 	prev = NULL;
429 	p = host_head;
430 	while (p != NULL) {
431 		if (p->owner != (*ad)) {
432 			prev = p;
433 			p = p->next;
434 			continue;
435 		} else {
436 			delete_ds((*ad), p->host, p->port);
437 			if (prev == NULL)
438 				p = host_head;
439 			else
440 				p = prev->next;
441 		}
442 	}
443 	(void) pthread_mutex_unlock(&adhostlock);
444 
445 	(void) pthread_mutex_unlock(&(*ad)->lock);
446 	(void) pthread_mutex_destroy(&(*ad)->lock);
447 
448 	free((*ad)->dflt_w2k_dom);
449 	free(*ad);
450 
451 	*ad = NULL;
452 }
453 
454 
455 static
456 int
457 idmap_open_conn(ad_host_t *adh, int timeoutsecs)
458 {
459 	int zero = 0;
460 	int ldversion, rc;
461 	int timeoutms = timeoutsecs * 1000;
462 
463 	if (adh == NULL)
464 		return (0);
465 
466 	(void) pthread_mutex_lock(&adh->lock);
467 
468 	if (!adh->dead && adh->ld != NULL)
469 		/* done! */
470 		goto out;
471 
472 	if (adh->ld != NULL) {
473 		(void) ldap_unbind(adh->ld);
474 		adh->ld = NULL;
475 	}
476 
477 	atomic_inc_64(&adh->generation);
478 
479 	/* Open and bind an LDAP connection */
480 	adh->ld = ldap_init(adh->host, adh->port);
481 	if (adh->ld == NULL) {
482 		idmapdlog(LOG_INFO, "ldap_init() to server "
483 		    "%s port %d failed. (%s)", adh->host,
484 		    adh->port, strerror(errno));
485 		goto out;
486 	}
487 	ldversion = LDAP_VERSION3;
488 	(void) ldap_set_option(adh->ld, LDAP_OPT_PROTOCOL_VERSION, &ldversion);
489 	(void) ldap_set_option(adh->ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF);
490 	(void) ldap_set_option(adh->ld, LDAP_OPT_TIMELIMIT, &zero);
491 	(void) ldap_set_option(adh->ld, LDAP_OPT_SIZELIMIT, &zero);
492 	(void) ldap_set_option(adh->ld, LDAP_X_OPT_CONNECT_TIMEOUT, &timeoutms);
493 	(void) ldap_set_option(adh->ld, LDAP_OPT_RESTART, LDAP_OPT_ON);
494 	rc = ldap_sasl_interactive_bind_s(adh->ld, "" /* binddn */,
495 	    adh->saslmech, NULL, NULL, adh->saslflags, &idmap_saslcallback,
496 	    NULL);
497 
498 	if (rc != LDAP_SUCCESS) {
499 		(void) ldap_unbind(adh->ld);
500 		adh->ld = NULL;
501 		idmapdlog(LOG_INFO, "ldap_sasl_interactive_bind_s() to server "
502 		    "%s port %d failed. (%s)", adh->host, adh->port,
503 		    ldap_err2string(rc));
504 	}
505 
506 	idmapdlog(LOG_DEBUG, "Using global catalog server %s:%d",
507 	    adh->host, adh->port);
508 
509 out:
510 	if (adh->ld != NULL) {
511 		atomic_inc_32(&adh->ref);
512 		adh->idletime = time(NULL);
513 		adh->dead = 0;
514 		(void) pthread_mutex_unlock(&adh->lock);
515 		return (1);
516 	}
517 
518 	(void) pthread_mutex_unlock(&adh->lock);
519 	return (0);
520 }
521 
522 
523 /*
524  * Connection management: find an open connection or open one
525  */
526 static
527 ad_host_t *
528 idmap_get_conn(ad_t *ad)
529 {
530 	ad_host_t	*adh = NULL;
531 	int		tries;
532 	int		dscount = 0;
533 	int		timeoutsecs = IDMAPD_LDAP_OPEN_TIMEOUT;
534 
535 retry:
536 	(void) pthread_mutex_lock(&adhostlock);
537 
538 	if (host_head == NULL) {
539 		(void) pthread_mutex_unlock(&adhostlock);
540 		goto out;
541 	}
542 
543 	if (dscount == 0) {
544 		/*
545 		 * First try: count the number of DSes.
546 		 *
547 		 * Integer overflow is not an issue -- we can't have so many
548 		 * DSes because they won't fit even DNS over TCP, and SMF
549 		 * shouldn't let you set so many.
550 		 */
551 		for (adh = host_head, tries = 0; adh != NULL; adh = adh->next) {
552 			if (adh->owner == ad)
553 				dscount++;
554 		}
555 
556 		if (dscount == 0) {
557 			(void) pthread_mutex_unlock(&adhostlock);
558 			goto out;
559 		}
560 
561 		tries = dscount * 3;	/* three tries per-ds */
562 
563 		/*
564 		 * Begin round-robin at the next DS in the list after the last
565 		 * one that we had a connection to, else start with the first
566 		 * DS in the list.
567 		 */
568 		adh = ad->last_adh;
569 	}
570 
571 	/*
572 	 * Round-robin -- pick the next one on the list; if the list
573 	 * changes on us, no big deal, we'll just potentially go
574 	 * around the wrong number of times.
575 	 */
576 	for (;;) {
577 		if (adh != NULL && adh->ld != NULL && !adh->dead)
578 			break;
579 		if (adh == NULL || (adh = adh->next) == NULL)
580 			adh = host_head;
581 		if (adh->owner == ad)
582 			break;
583 	}
584 
585 	ad->last_adh = adh;
586 	(void) pthread_mutex_unlock(&adhostlock);
587 
588 
589 	/* Found suitable DS, open it if not already opened */
590 	if (idmap_open_conn(adh, timeoutsecs))
591 		return (adh);
592 
593 	tries--;
594 
595 	if ((tries % dscount) == 0)
596 		timeoutsecs *= 2;
597 
598 	if (tries > 0)
599 		goto retry;
600 
601 out:
602 	idmapdlog(LOG_NOTICE, "Couldn't open an LDAP connection to any global "
603 	    "catalog server!");
604 
605 	return (NULL);
606 }
607 
608 static
609 void
610 idmap_release_conn(ad_host_t *adh)
611 {
612 	(void) pthread_mutex_lock(&adh->lock);
613 	if (atomic_dec_32_nv(&adh->ref) == 0)
614 		adh->idletime = time(NULL);
615 	(void) pthread_mutex_unlock(&adh->lock);
616 }
617 
618 /*
619  * Take ad_host_config_t information, create a ad_host_t,
620  * populate it and add it to the list of hosts.
621  */
622 
623 int
624 idmap_add_ds(ad_t *ad, const char *host, int port)
625 {
626 	ad_host_t	*p;
627 	ad_host_t	*new = NULL;
628 	int		ret = -1;
629 
630 	if (port == 0)
631 		port = (int)ad->partition;
632 
633 	(void) pthread_mutex_lock(&adhostlock);
634 	for (p = host_head; p != NULL; p = p->next) {
635 		if (p->owner != ad)
636 			continue;
637 
638 		if (strcmp(host, p->host) == 0 && p->port == port) {
639 			/* already added */
640 			ret = 0;
641 			goto err;
642 		}
643 	}
644 
645 	/* add new entry */
646 	new = (ad_host_t *)calloc(1, sizeof (ad_host_t));
647 	if (new == NULL)
648 		goto err;
649 	new->owner = ad;
650 	new->port = port;
651 	new->dead = 0;
652 	if ((new->host = strdup(host)) == NULL)
653 		goto err;
654 
655 	/* default to SASL GSSAPI only for now */
656 	new->saslflags = LDAP_SASL_INTERACTIVE;
657 	new->saslmech = "GSSAPI";
658 
659 	if ((ret = pthread_mutex_init(&new->lock, NULL)) != 0) {
660 		free(new->host);
661 		new->host = NULL;
662 		errno = ret;
663 		ret = -1;
664 		goto err;
665 	}
666 
667 	/* link in */
668 	new->next = host_head;
669 	host_head = new;
670 
671 	/* Start reaper if it doesn't exist */
672 	if (reaperid == 0)
673 		(void) pthread_create(&reaperid, NULL,
674 		    (void *(*)(void *))adreaper, (void *)NULL);
675 
676 err:
677 	(void) pthread_mutex_unlock(&adhostlock);
678 
679 	if (ret != 0 && new != NULL) {
680 		if (new->host != NULL) {
681 			(void) pthread_mutex_destroy(&new->lock);
682 			free(new->host);
683 		}
684 		free(new);
685 	}
686 
687 	return (ret);
688 }
689 
690 /*
691  * Free a DS configuration.
692  * Caller must lock the adhostlock mutex
693  */
694 static void
695 delete_ds(ad_t *ad, const char *host, int port)
696 {
697 	ad_host_t	**p, *q;
698 
699 	for (p = &host_head; *p != NULL; p = &((*p)->next)) {
700 		if ((*p)->owner != ad || strcmp(host, (*p)->host) != 0 ||
701 		    (*p)->port != port)
702 			continue;
703 		/* found */
704 		if ((*p)->ref > 0)
705 			break;	/* still in use */
706 
707 		q = *p;
708 		*p = (*p)->next;
709 
710 		(void) pthread_mutex_destroy(&q->lock);
711 
712 		if (q->ld)
713 			(void) ldap_unbind(q->ld);
714 		if (q->host)
715 			free(q->host);
716 		free(q);
717 		break;
718 	}
719 
720 }
721 
722 
723 /*
724  * Convert a binary SID in a BerValue to a sid_t
725  */
726 static
727 int
728 idmap_getsid(BerValue *bval, sid_t *sidp)
729 {
730 	int		i, j;
731 	uchar_t		*v;
732 	uint32_t	a;
733 
734 	/*
735 	 * The binary format of a SID is as follows:
736 	 *
737 	 * byte #0: version, always 0x01
738 	 * byte #1: RID count, always <= 0x0f
739 	 * bytes #2-#7: SID authority, big-endian 48-bit unsigned int
740 	 *
741 	 * followed by RID count RIDs, each a little-endian, unsigned
742 	 * 32-bit int.
743 	 */
744 	/*
745 	 * Sanity checks: must have at least one RID, version must be
746 	 * 0x01, and the length must be 8 + rid count * 4
747 	 */
748 	if (bval->bv_len > 8 && bval->bv_val[0] == 0x01 &&
749 	    bval->bv_len == 1 + 1 + 6 + bval->bv_val[1] * 4) {
750 		v = (uchar_t *)bval->bv_val;
751 		sidp->version = v[0];
752 		sidp->sub_authority_count = v[1];
753 		sidp->authority =
754 		    /* big endian -- so start from the left */
755 		    ((u_longlong_t)v[2] << 40) |
756 		    ((u_longlong_t)v[3] << 32) |
757 		    ((u_longlong_t)v[4] << 24) |
758 		    ((u_longlong_t)v[5] << 16) |
759 		    ((u_longlong_t)v[6] << 8) |
760 		    (u_longlong_t)v[7];
761 		for (i = 0; i < sidp->sub_authority_count; i++) {
762 			j = 8 + (i * 4);
763 			/* little endian -- so start from the right */
764 			a = (v[j + 3] << 24) | (v[j + 2] << 16) |
765 			    (v[j + 1] << 8) | (v[j]);
766 			sidp->sub_authorities[i] = a;
767 		}
768 		return (0);
769 	}
770 	return (-1);
771 }
772 
773 /*
774  * Convert a sid_t to S-1-...
775  */
776 static
777 char *
778 idmap_sid2txt(sid_t *sidp)
779 {
780 	int	rlen, i, len;
781 	char	*str, *cp;
782 
783 	if (sidp->version != 1)
784 		return (NULL);
785 
786 	len = sizeof ("S-1-") - 1;
787 
788 	/*
789 	 * We could optimize like so, but, why?
790 	 *	if (sidp->authority < 10)
791 	 *		len += 2;
792 	 *	else if (sidp->authority < 100)
793 	 *		len += 3;
794 	 *	else
795 	 *		len += snprintf(NULL, 0"%llu", sidp->authority);
796 	 */
797 	len += snprintf(NULL, 0, "%llu", sidp->authority);
798 
799 	/* Max length of a uint32_t printed out in ASCII is 10 bytes */
800 	len += 1 + (sidp->sub_authority_count + 1) * 10;
801 
802 	if ((cp = str = malloc(len)) == NULL)
803 		return (NULL);
804 
805 	rlen = snprintf(str, len, "S-1-%llu", sidp->authority);
806 
807 	cp += rlen;
808 	len -= rlen;
809 
810 	for (i = 0; i < sidp->sub_authority_count; i++) {
811 		assert(len > 0);
812 		rlen = snprintf(cp, len, "-%u", sidp->sub_authorities[i]);
813 		cp += rlen;
814 		len -= rlen;
815 		assert(len >= 0);
816 	}
817 
818 	return (str);
819 }
820 
821 /*
822  * Convert a sid_t to on-the-wire encoding
823  */
824 static
825 int
826 idmap_sid2binsid(sid_t *sid, uchar_t *binsid, int binsidlen)
827 {
828 	uchar_t		*p;
829 	int		i;
830 	uint64_t	a;
831 	uint32_t	r;
832 
833 	if (sid->version != 1 ||
834 	    binsidlen != (1 + 1 + 6 + sid->sub_authority_count * 4))
835 		return (-1);
836 
837 	p = binsid;
838 	*p++ = 0x01;		/* version */
839 	/* sub authority count */
840 	*p++ = sid->sub_authority_count;
841 	/* Authority */
842 	a = sid->authority;
843 	/* big-endian -- start from left */
844 	*p++ = (a >> 40) & 0xFF;
845 	*p++ = (a >> 32) & 0xFF;
846 	*p++ = (a >> 24) & 0xFF;
847 	*p++ = (a >> 16) & 0xFF;
848 	*p++ = (a >> 8) & 0xFF;
849 	*p++ = a & 0xFF;
850 
851 	/* sub-authorities */
852 	for (i = 0; i < sid->sub_authority_count; i++) {
853 		r = sid->sub_authorities[i];
854 		/* little-endian -- start from right */
855 		*p++ = (r & 0x000000FF);
856 		*p++ = (r & 0x0000FF00) >> 8;
857 		*p++ = (r & 0x00FF0000) >> 16;
858 		*p++ = (r & 0xFF000000) >> 24;
859 	}
860 
861 	return (0);
862 }
863 
864 /*
865  * Convert a stringified SID (S-1-...) into a hex-encoded version of the
866  * on-the-wire encoding, but with each pair of hex digits pre-pended
867  * with a '\', so we can pass this to libldap.
868  */
869 static
870 int
871 idmap_txtsid2hexbinsid(const char *txt, const rid_t *rid,
872 	char *hexbinsid, int hexbinsidlen)
873 {
874 	sid_t		sid = { 0 };
875 	int		i, j;
876 	const char	*cp;
877 	char		*ecp;
878 	u_longlong_t	a;
879 	unsigned long	r;
880 	uchar_t		*binsid, b, hb;
881 
882 	/* Only version 1 SIDs please */
883 	if (strncmp(txt, "S-1-", strlen("S-1-")) != 0)
884 		return (-1);
885 
886 	if (strlen(txt) < (strlen("S-1-") + 1))
887 		return (-1);
888 
889 	/* count '-'s */
890 	for (j = 0, cp = strchr(txt, '-');
891 	    cp != NULL && *cp != '\0';
892 	    j++, cp = strchr(cp + 1, '-')) {
893 		/* can't end on a '-' */
894 		if (*(cp + 1) == '\0')
895 			return (-1);
896 	}
897 
898 	/* Adjust count for version and authority */
899 	j -= 2;
900 
901 	/* we know the version number and RID count */
902 	sid.version = 1;
903 	sid.sub_authority_count = (rid != NULL) ? j + 1 : j;
904 
905 	/* must have at least one RID, but not too many */
906 	if (sid.sub_authority_count < 1 ||
907 	    sid.sub_authority_count > SID_MAX_SUB_AUTHORITIES)
908 		return (-1);
909 
910 	/* check that we only have digits and '-' */
911 	if (strspn(txt + 1, "0123456789-") < (strlen(txt) - 1))
912 		return (-1);
913 
914 	cp = txt + strlen("S-1-");
915 
916 	/* 64-bit safe parsing of unsigned 48-bit authority value */
917 	errno = 0;
918 	a = strtoull(cp, &ecp, 10);
919 
920 	/* errors parsing the authority or too many bits */
921 	if (cp == ecp || (a == 0 && errno == EINVAL) ||
922 	    (a == ULLONG_MAX && errno == ERANGE) ||
923 	    (a & 0x0000ffffffffffffULL) != a)
924 		return (-1);
925 
926 	cp = ecp;
927 
928 	sid.authority = (uint64_t)a;
929 
930 	for (i = 0; i < j; i++) {
931 		if (*cp++ != '-')
932 			return (-1);
933 		/* 64-bit safe parsing of unsigned 32-bit RID */
934 		errno = 0;
935 		r = strtoul(cp, &ecp, 10);
936 		/* errors parsing the RID or too many bits */
937 		if (cp == ecp || (r == 0 && errno == EINVAL) ||
938 		    (r == ULONG_MAX && errno == ERANGE) ||
939 		    (r & 0xffffffffUL) != r)
940 			return (-1);
941 		sid.sub_authorities[i] = (uint32_t)r;
942 		cp = ecp;
943 	}
944 
945 	/* check that all of the string SID has been consumed */
946 	if (*cp != '\0')
947 		return (-1);
948 
949 	if (rid != NULL)
950 		sid.sub_authorities[j] = *rid;
951 
952 	j = 1 + 1 + 6 + sid.sub_authority_count * 4;
953 
954 	if (hexbinsidlen < (j * 3))
955 		return (-2);
956 
957 	/* binary encode the SID */
958 	binsid = (uchar_t *)alloca(j);
959 	(void) idmap_sid2binsid(&sid, binsid, j);
960 
961 	/* hex encode, with a backslash before each byte */
962 	for (ecp = hexbinsid, i = 0; i < j; i++) {
963 		b = binsid[i];
964 		*ecp++ = '\\';
965 		hb = (b >> 4) & 0xF;
966 		*ecp++ = (hb <= 0x9 ? hb + '0' : hb - 10 + 'A');
967 		hb = b & 0xF;
968 		*ecp++ = (hb <= 0x9 ? hb + '0' : hb - 10 + 'A');
969 	}
970 	*ecp = '\0';
971 
972 	return (0);
973 }
974 
975 static
976 char *
977 convert_bval2sid(BerValue *bval, rid_t *rid)
978 {
979 	sid_t	sid;
980 
981 	if (idmap_getsid(bval, &sid) < 0)
982 		return (NULL);
983 
984 	/*
985 	 * If desired and if the SID is what should be a domain/computer
986 	 * user or group SID (i.e., S-1-5-w-x-y-z-<user/group RID>) then
987 	 * save the last RID and truncate the SID
988 	 */
989 	if (rid != NULL && sid.authority == 5 && sid.sub_authority_count == 5)
990 		*rid = sid.sub_authorities[--sid.sub_authority_count];
991 	return (idmap_sid2txt(&sid));
992 }
993 
994 
995 idmap_retcode
996 idmap_lookup_batch_start(ad_t *ad, int nqueries, idmap_query_state_t **state)
997 {
998 	idmap_query_state_t *new_state;
999 	ad_host_t	*adh = NULL;
1000 
1001 	*state = NULL;
1002 
1003 	/* Note: ad->dflt_w2k_dom cannot be NULL - see idmap_ad_alloc() */
1004 	if (ad == NULL || *ad->dflt_w2k_dom == '\0')
1005 		return (IDMAP_ERR_INTERNAL);
1006 
1007 	adh = idmap_get_conn(ad);
1008 	if (adh == NULL)
1009 		return (IDMAP_ERR_RETRIABLE_NET_ERR);
1010 
1011 	new_state = calloc(1, sizeof (idmap_query_state_t) +
1012 	    (nqueries - 1) * sizeof (idmap_q_t));
1013 
1014 	if (new_state == NULL)
1015 		return (IDMAP_ERR_MEMORY);
1016 
1017 	new_state->ref_cnt = 1;
1018 	new_state->qadh = adh;
1019 	new_state->qcount = nqueries;
1020 	new_state->qadh_gen = adh->generation;
1021 	/* should be -1, but the atomic routines want unsigned */
1022 	new_state->qlastsent = 0;
1023 	(void) pthread_cond_init(&new_state->cv, NULL);
1024 
1025 	(void) pthread_mutex_lock(&qstatelock);
1026 	new_state->next = qstatehead;
1027 	qstatehead = new_state;
1028 	(void) pthread_mutex_unlock(&qstatelock);
1029 
1030 	*state = new_state;
1031 
1032 	return (IDMAP_SUCCESS);
1033 }
1034 
1035 /*
1036  * Set unixuser_attr and unixgroup_attr for AD-based name mapping
1037  */
1038 void
1039 idmap_lookup_batch_set_unixattr(idmap_query_state_t *state,
1040 		const char *unixuser_attr, const char *unixgroup_attr)
1041 {
1042 	state->ad_unixuser_attr = unixuser_attr;
1043 	state->ad_unixgroup_attr = unixgroup_attr;
1044 }
1045 
1046 /*
1047  * Find the idmap_query_state_t to which a given LDAP result msgid on a
1048  * given connection belongs. This routine increaments the reference count
1049  * so that the object can not be freed. idmap_lookup_unlock_batch()
1050  * must be called to decreament the reference count.
1051  */
1052 static
1053 int
1054 idmap_msgid2query(ad_host_t *adh, int msgid,
1055 	idmap_query_state_t **state, int *qid)
1056 {
1057 	idmap_query_state_t *p;
1058 	int		    i;
1059 
1060 	(void) pthread_mutex_lock(&qstatelock);
1061 	for (p = qstatehead; p != NULL; p = p->next) {
1062 		if (p->qadh != adh || adh->generation != p->qadh_gen)
1063 			continue;
1064 		for (i = 0; i < p->qcount; i++) {
1065 			if ((p->queries[i]).msgid == msgid) {
1066 				p->ref_cnt++;
1067 				*state = p;
1068 				*qid = i;
1069 				(void) pthread_mutex_unlock(&qstatelock);
1070 				return (1);
1071 			}
1072 		}
1073 	}
1074 	(void) pthread_mutex_unlock(&qstatelock);
1075 	return (0);
1076 }
1077 
1078 /*
1079  * Take parsed attribute values from a search result entry and check if
1080  * it is the result that was desired and, if so, set the result fields
1081  * of the given idmap_q_t.
1082  *
1083  * Frees the unused char * values.
1084  */
1085 static
1086 void
1087 idmap_setqresults(idmap_q_t *q, char *san, char *dn, char *sid,
1088 	rid_t rid, int sid_type, char *unixname)
1089 {
1090 	char *domain;
1091 	int err1, err2;
1092 
1093 	assert(dn != NULL);
1094 
1095 	if ((domain = dn2dns(dn)) == NULL)
1096 		goto out;
1097 
1098 	if (q->ecanonname != NULL && san != NULL) {
1099 		/* Check that this is the canonname that we were looking for */
1100 		if (u8_strcmp(q->ecanonname, san, 0,
1101 		    U8_STRCMP_CI_LOWER, /* no normalization, for now */
1102 		    U8_UNICODE_LATEST, &err1) != 0 || err1 != 0)
1103 			goto out;
1104 	}
1105 
1106 	if (q->edomain != NULL) {
1107 		/* Check that this is the domain that we were looking for */
1108 		if (u8_strcmp(q->edomain, domain, 0, U8_STRCMP_CI_LOWER,
1109 		    U8_UNICODE_LATEST, &err2) != 0 || err2 != 0)
1110 			goto out;
1111 	}
1112 
1113 	/* Set results */
1114 	if (q->sid) {
1115 		*q->sid = sid;
1116 		sid = NULL;
1117 	}
1118 	if (q->rid)
1119 		*q->rid = rid;
1120 	if (q->sid_type)
1121 		*q->sid_type = sid_type;
1122 	if (q->unixname) {
1123 		*q->unixname = unixname;
1124 		unixname = NULL;
1125 	}
1126 	if (q->domain != NULL) {
1127 		*q->domain = domain;
1128 		domain = NULL;
1129 	}
1130 	if (q->canonname != NULL) {
1131 		*q->canonname = san;
1132 		san = NULL;
1133 	}
1134 
1135 	/* Always have q->rc; idmap_extract_object() asserts this */
1136 	*q->rc = IDMAP_SUCCESS;
1137 
1138 out:
1139 	/* Free unused attribute values */
1140 	free(san);
1141 	free(sid);
1142 	free(domain);
1143 	free(unixname);
1144 }
1145 
1146 /*
1147  * The following three functions extract objectSid, sAMAccountName and
1148  * objectClass attribute values and, in the case of objectSid and
1149  * objectClass, parse them.
1150  *
1151  * idmap_setqresults() takes care of dealing with the result entry's DN.
1152  */
1153 
1154 /*
1155  * Return a NUL-terminated stringified SID from the value of an
1156  * objectSid attribute and put the last RID in *rid.
1157  */
1158 static
1159 char *
1160 idmap_bv_objsid2sidstr(BerValue **bvalues, rid_t *rid)
1161 {
1162 	char *sid;
1163 
1164 	if (bvalues == NULL)
1165 		return (NULL);
1166 	/* objectSid is single valued */
1167 	if ((sid = convert_bval2sid(bvalues[0], rid)) == NULL)
1168 		return (NULL);
1169 	return (sid);
1170 }
1171 
1172 /*
1173  * Return a NUL-terminated string from the value of a sAMAccountName
1174  * or unixname attribute.
1175  */
1176 static
1177 char *
1178 idmap_bv_name2str(BerValue **bvalues)
1179 {
1180 	char *s;
1181 
1182 	if (bvalues == NULL || bvalues[0] == NULL ||
1183 	    bvalues[0]->bv_val == NULL)
1184 		return (NULL);
1185 
1186 	if ((s = malloc(bvalues[0]->bv_len + 1)) == NULL)
1187 		return (NULL);
1188 
1189 	(void) snprintf(s, bvalues[0]->bv_len + 1, "%.*s", bvalues[0]->bv_len,
1190 	    bvalues[0]->bv_val);
1191 
1192 	return (s);
1193 }
1194 
1195 
1196 #define	BVAL_CASEEQ(bv, str) \
1197 		(((*(bv))->bv_len == (sizeof (str) - 1)) && \
1198 		    strncasecmp((*(bv))->bv_val, str, (*(bv))->bv_len) == 0)
1199 
1200 /*
1201  * Extract the class of the result entry.  Returns 1 on success, 0 on
1202  * failure.
1203  */
1204 static
1205 int
1206 idmap_bv_objclass2sidtype(BerValue **bvalues, int *sid_type)
1207 {
1208 	BerValue	**cbval;
1209 
1210 	*sid_type = _IDMAP_T_OTHER;
1211 	if (bvalues == NULL)
1212 		return (0);
1213 
1214 	/*
1215 	 * We iterate over all the values because computer is a
1216 	 * sub-class of user.
1217 	 */
1218 	for (cbval = bvalues; *cbval != NULL; cbval++) {
1219 		if (BVAL_CASEEQ(cbval, "Computer")) {
1220 			*sid_type = _IDMAP_T_COMPUTER;
1221 			break;
1222 		} else if (BVAL_CASEEQ(cbval, "Group")) {
1223 			*sid_type = _IDMAP_T_GROUP;
1224 			break;
1225 		} else if (BVAL_CASEEQ(cbval, "USER")) {
1226 			*sid_type = _IDMAP_T_USER;
1227 			/* Continue looping -- this may be a computer yet */
1228 		}
1229 		/*
1230 		 * "else if (*sid_type = _IDMAP_T_USER)" then this is a
1231 		 * new sub-class of user -- what to do with it??
1232 		 */
1233 	}
1234 
1235 	return (1);
1236 }
1237 
1238 /*
1239  * Handle a given search result entry
1240  */
1241 static
1242 void
1243 idmap_extract_object(idmap_query_state_t *state, int qid, LDAPMessage *res)
1244 {
1245 	BerElement		*ber = NULL;
1246 	BerValue		**bvalues;
1247 	ad_host_t		*adh;
1248 	idmap_q_t		*q;
1249 	char			*attr;
1250 	const char		*unixuser_attr = NULL;
1251 	const char		*unixgroup_attr = NULL;
1252 	char			*unixuser = NULL;
1253 	char			*unixgroup = NULL;
1254 	char			*dn = NULL;
1255 	char			*san = NULL;
1256 	char			*sid = NULL;
1257 	rid_t			rid = 0;
1258 	int			sid_type = _IDMAP_T_UNDEF;
1259 	int			has_class, has_san, has_sid;
1260 	int			has_unixuser, has_unixgroup;
1261 
1262 	adh = state->qadh;
1263 
1264 	(void) pthread_mutex_lock(&adh->lock);
1265 
1266 	q = &(state->queries[qid]);
1267 
1268 	assert(q->rc != NULL);
1269 
1270 	if (*q->rc == IDMAP_SUCCESS || adh->dead ||
1271 	    (dn = ldap_get_dn(adh->ld, res)) == NULL) {
1272 		(void) pthread_mutex_unlock(&adh->lock);
1273 		return;
1274 	}
1275 
1276 	assert(q->domain == NULL || *q->domain == NULL);
1277 
1278 	/*
1279 	 * If the caller has requested unixname then determine the
1280 	 * AD attribute name that will have the unixname.
1281 	 */
1282 	if (q->unixname != NULL) {
1283 		if (q->eunixtype == _IDMAP_T_USER)
1284 			unixuser_attr = state->ad_unixuser_attr;
1285 		else if (q->eunixtype == _IDMAP_T_GROUP)
1286 			unixgroup_attr = state->ad_unixgroup_attr;
1287 		else if (q->eunixtype == _IDMAP_T_UNDEF) {
1288 			/*
1289 			 * This is the case where we don't know
1290 			 * before hand whether we need unixuser
1291 			 * or unixgroup. This will be determined
1292 			 * by the "sid_type" (i.e whether the given
1293 			 * winname is user or group). If sid_type
1294 			 * turns out to be user we will return
1295 			 * unixuser (if found) and if it is a group
1296 			 * we will return unixgroup (if found). We
1297 			 * lookup for both ad_unixuser_attr and
1298 			 * ad_unixgroup_attr and discard one of them
1299 			 * after we know the "sidtype". This
1300 			 * supports the following type of lookups.
1301 			 *
1302 			 * Example:
1303 			 *   $idmap show -c winname:foo
1304 			 * In the above example, idmap will
1305 			 * return uid if winname is winuser
1306 			 * and gid if winname is wingroup.
1307 			 */
1308 			unixuser_attr = state->ad_unixuser_attr;
1309 			unixgroup_attr = state->ad_unixgroup_attr;
1310 		}
1311 	}
1312 
1313 	has_class = has_san = has_sid = has_unixuser = has_unixgroup = 0;
1314 	for (attr = ldap_first_attribute(adh->ld, res, &ber); attr != NULL;
1315 	    attr = ldap_next_attribute(adh->ld, res, ber)) {
1316 		bvalues = NULL;	/* for memory management below */
1317 
1318 		/*
1319 		 * If this is an attribute we are looking for and
1320 		 * haven't seen it yet, parse it
1321 		 */
1322 		if (q->sid != NULL && !has_sid &&
1323 		    strcasecmp(attr, OBJSID) == 0) {
1324 			bvalues = ldap_get_values_len(adh->ld, res, attr);
1325 			sid = idmap_bv_objsid2sidstr(bvalues, &rid);
1326 			has_sid = (sid != NULL);
1327 		} else if (!has_san && strcasecmp(attr, SAN) == 0) {
1328 			bvalues = ldap_get_values_len(adh->ld, res, attr);
1329 			san = idmap_bv_name2str(bvalues);
1330 			has_san = (san != NULL);
1331 		} else if (!has_class && strcasecmp(attr, OBJCLASS) == 0) {
1332 			bvalues = ldap_get_values_len(adh->ld, res, attr);
1333 			has_class = idmap_bv_objclass2sidtype(bvalues,
1334 			    &sid_type);
1335 			if (has_class && q->unixname != NULL &&
1336 			    q->eunixtype == _IDMAP_T_UNDEF) {
1337 				/*
1338 				 * This is the case where we didn't
1339 				 * know whether we wanted unixuser or
1340 				 * unixgroup as described above.
1341 				 * Now since we know the "sid_type"
1342 				 * we discard the unwanted value
1343 				 * if it was retrieved before we
1344 				 * got here.
1345 				 */
1346 				if (sid_type == _IDMAP_T_USER) {
1347 					free(unixgroup);
1348 					unixgroup_attr = unixgroup = NULL;
1349 				} else if (sid_type == _IDMAP_T_GROUP) {
1350 					free(unixuser);
1351 					unixuser_attr = unixuser = NULL;
1352 				} else {
1353 					free(unixuser);
1354 					free(unixgroup);
1355 					unixuser_attr = unixuser = NULL;
1356 					unixgroup_attr = unixgroup = NULL;
1357 				}
1358 			}
1359 		} else if (!has_unixuser && unixuser_attr != NULL &&
1360 		    strcasecmp(attr, unixuser_attr) == 0) {
1361 			bvalues = ldap_get_values_len(adh->ld, res, attr);
1362 			unixuser = idmap_bv_name2str(bvalues);
1363 			has_unixuser = (unixuser != NULL);
1364 		} else if (!has_unixgroup && unixgroup_attr != NULL &&
1365 		    strcasecmp(attr, unixgroup_attr) == 0) {
1366 			bvalues = ldap_get_values_len(adh->ld, res, attr);
1367 			unixgroup = idmap_bv_name2str(bvalues);
1368 			has_unixgroup = (unixgroup != NULL);
1369 		}
1370 
1371 		if (bvalues != NULL)
1372 			ldap_value_free_len(bvalues);
1373 		ldap_memfree(attr);
1374 
1375 		if (has_class && has_san &&
1376 		    (q->sid == NULL || has_sid) &&
1377 		    (unixuser_attr == NULL || has_unixuser) &&
1378 		    (unixgroup_attr == NULL || has_unixgroup)) {
1379 			/* Got what we need */
1380 			break;
1381 		}
1382 	}
1383 
1384 	if (!has_class) {
1385 		/*
1386 		 * Didn't find objectclass. Something's wrong with our
1387 		 * AD data.
1388 		 */
1389 		free(san);
1390 		free(sid);
1391 		free(unixuser);
1392 		free(unixgroup);
1393 	} else {
1394 		/*
1395 		 * Either we got what we needed and came out of the loop
1396 		 * early OR we completed the loop in which case we didn't
1397 		 * find some attributes that we were looking for. In either
1398 		 * case set the result with what we got.
1399 		 */
1400 		idmap_setqresults(q, san, dn, sid, rid, sid_type,
1401 		    (unixuser != NULL) ? unixuser : unixgroup);
1402 	}
1403 
1404 	(void) pthread_mutex_unlock(&adh->lock);
1405 
1406 	if (ber != NULL)
1407 		ber_free(ber, 0);
1408 
1409 	ldap_memfree(dn);
1410 }
1411 
1412 /*
1413  * Try to get a result; if there is one, find the corresponding
1414  * idmap_q_t and process the result.
1415  */
1416 static
1417 int
1418 idmap_get_adobject_batch(ad_host_t *adh, struct timeval *timeout)
1419 {
1420 	idmap_query_state_t	*query_state;
1421 	LDAPMessage		*res = NULL;
1422 	int			rc, ret, msgid, qid;
1423 
1424 	(void) pthread_mutex_lock(&adh->lock);
1425 	if (adh->dead) {
1426 		(void) pthread_mutex_unlock(&adh->lock);
1427 		return (-1);
1428 	}
1429 
1430 	/* Get one result */
1431 	rc = ldap_result(adh->ld, LDAP_RES_ANY, 0,
1432 	    timeout, &res);
1433 	if ((timeout != NULL && timeout->tv_sec > 0 && rc == LDAP_SUCCESS) ||
1434 	    rc < 0)
1435 		adh->dead = 1;
1436 	(void) pthread_mutex_unlock(&adh->lock);
1437 
1438 	if (adh->dead)
1439 		return (-1);
1440 
1441 	switch (rc) {
1442 	case LDAP_RES_SEARCH_RESULT:
1443 		/* We have all the LDAP replies for some search... */
1444 		msgid = ldap_msgid(res);
1445 		if (idmap_msgid2query(adh, msgid,
1446 		    &query_state, &qid)) {
1447 			/* ...so we can decrement qinflight */
1448 			atomic_dec_32(&query_state->qinflight);
1449 			/* We've seen all the result entries we'll see */
1450 			if (*query_state->queries[qid].rc != IDMAP_SUCCESS)
1451 				*query_state->queries[qid].rc =
1452 				    IDMAP_ERR_NOTFOUND;
1453 			idmap_lookup_unlock_batch(&query_state);
1454 		}
1455 		(void) ldap_msgfree(res);
1456 		ret = 0;
1457 		break;
1458 	case LDAP_RES_SEARCH_REFERENCE:
1459 		/*
1460 		 * We have no need for these at the moment.  Eventually,
1461 		 * when we query things that we can't expect to find in
1462 		 * the Global Catalog then we'll need to learn to follow
1463 		 * references.
1464 		 */
1465 		(void) ldap_msgfree(res);
1466 		ret = 0;
1467 		break;
1468 	case LDAP_RES_SEARCH_ENTRY:
1469 		/* Got a result */
1470 		msgid = ldap_msgid(res);
1471 		if (idmap_msgid2query(adh, msgid,
1472 		    &query_state, &qid)) {
1473 			idmap_extract_object(query_state, qid, res);
1474 			/* we saw at least one result */
1475 			idmap_lookup_unlock_batch(&query_state);
1476 		}
1477 		(void) ldap_msgfree(res);
1478 		ret = 0;
1479 		break;
1480 	default:
1481 		/* timeout or error; treat the same */
1482 		ret = -1;
1483 		break;
1484 	}
1485 
1486 	return (ret);
1487 }
1488 
1489 /*
1490  * This routine decreament the reference count of the
1491  * idmap_query_state_t
1492  */
1493 static void
1494 idmap_lookup_unlock_batch(idmap_query_state_t **state)
1495 {
1496 	/*
1497 	 * Decrement reference count with qstatelock locked
1498 	 */
1499 	(void) pthread_mutex_lock(&qstatelock);
1500 	(*state)->ref_cnt--;
1501 	/*
1502 	 * If there are no references wakup the allocating thread
1503 	 */
1504 	if ((*state)->ref_cnt == 0)
1505 		(void) pthread_cond_signal(&(*state)->cv);
1506 	(void) pthread_mutex_unlock(&qstatelock);
1507 	*state = NULL;
1508 }
1509 
1510 static
1511 void
1512 idmap_cleanup_batch(idmap_query_state_t *batch)
1513 {
1514 	int i;
1515 
1516 	for (i = 0; i < batch->qcount; i++) {
1517 		if (batch->queries[i].ecanonname != NULL)
1518 			free(batch->queries[i].ecanonname);
1519 		batch->queries[i].ecanonname = NULL;
1520 		if (batch->queries[i].edomain != NULL)
1521 			free(batch->queries[i].edomain);
1522 		batch->queries[i].edomain = NULL;
1523 	}
1524 }
1525 
1526 /*
1527  * This routine frees the idmap_query_state_t structure
1528  * If the reference count is greater than 1 it waits
1529  * for the other threads to finish using it.
1530  */
1531 void
1532 idmap_lookup_release_batch(idmap_query_state_t **state)
1533 {
1534 	idmap_query_state_t **p;
1535 
1536 	/*
1537 	 * Decrement reference count with qstatelock locked
1538 	 * and wait for reference count to get to zero
1539 	 */
1540 	(void) pthread_mutex_lock(&qstatelock);
1541 	(*state)->ref_cnt--;
1542 	while ((*state)->ref_cnt > 0) {
1543 		(void) pthread_cond_wait(&(*state)->cv, &qstatelock);
1544 	}
1545 
1546 	/* Remove this state struct from the list of state structs */
1547 	for (p = &qstatehead; *p != NULL; p = &(*p)->next) {
1548 		if (*p == (*state)) {
1549 			*p = (*state)->next;
1550 			break;
1551 		}
1552 	}
1553 
1554 	idmap_cleanup_batch(*state);
1555 
1556 	(void) pthread_mutex_unlock(&qstatelock);
1557 
1558 	(void) pthread_cond_destroy(&(*state)->cv);
1559 
1560 	idmap_release_conn((*state)->qadh);
1561 
1562 	free(*state);
1563 	*state = NULL;
1564 }
1565 
1566 idmap_retcode
1567 idmap_lookup_batch_end(idmap_query_state_t **state)
1568 {
1569 	int		    rc = LDAP_SUCCESS;
1570 	idmap_retcode	    retcode = IDMAP_SUCCESS;
1571 	struct timeval	    timeout;
1572 
1573 	(*state)->qdead = 1;
1574 	timeout.tv_sec = IDMAPD_SEARCH_TIMEOUT;
1575 	timeout.tv_usec = 0;
1576 
1577 	/* Process results until done or until timeout, if given */
1578 	while ((*state)->qinflight > 0) {
1579 		if ((rc = idmap_get_adobject_batch((*state)->qadh,
1580 		    &timeout)) != 0)
1581 			break;
1582 	}
1583 
1584 	if (rc != 0)
1585 		retcode = IDMAP_ERR_RETRIABLE_NET_ERR;
1586 
1587 	idmap_lookup_release_batch(state);
1588 
1589 	return (retcode);
1590 }
1591 
1592 /*
1593  * Send one prepared search, queue up msgid, process what results are
1594  * available
1595  */
1596 static
1597 idmap_retcode
1598 idmap_batch_add1(idmap_query_state_t *state,
1599 	const char *filter, char *ecanonname, char *edomain, int eunixtype,
1600 	char **canonname, char **dname, char **sid, rid_t *rid,
1601 	int *sid_type, char **unixname, idmap_retcode *rc)
1602 {
1603 	idmap_retcode	retcode = IDMAP_SUCCESS;
1604 	int		lrc, qid, i;
1605 	struct timeval	tv;
1606 	idmap_q_t	*q;
1607 	static char	*attrs[] = {
1608 		SAN,
1609 		OBJSID,
1610 		OBJCLASS,
1611 		NULL,	/* placeholder for unixname attr */
1612 		NULL,	/* placeholder for unixname attr */
1613 		NULL
1614 	};
1615 
1616 	qid = atomic_inc_32_nv(&state->qlastsent) - 1;
1617 
1618 	q = &(state->queries[qid]);
1619 
1620 	/*
1621 	 * Remember the expected canonname so we can check the results
1622 	 * agains it
1623 	 */
1624 	q->ecanonname = ecanonname;
1625 	q->edomain = edomain;
1626 	q->eunixtype = eunixtype;
1627 
1628 	/* Remember where to put the results */
1629 	q->canonname = canonname;
1630 	q->sid = sid;
1631 	q->domain = dname;
1632 	q->rid = rid;
1633 	q->sid_type = sid_type;
1634 	q->rc = rc;
1635 	q->unixname = unixname;
1636 
1637 	/* Add unixuser/unixgroup attribute names to the attrs list */
1638 	if (unixname != NULL) {
1639 		i = 3;
1640 		if (eunixtype != _IDMAP_T_GROUP &&
1641 		    state->ad_unixuser_attr != NULL)
1642 			attrs[i++] = (char *)state->ad_unixuser_attr;
1643 		if (eunixtype != _IDMAP_T_USER &&
1644 		    state->ad_unixgroup_attr != NULL)
1645 			attrs[i] = (char *)state->ad_unixgroup_attr;
1646 	}
1647 
1648 	/*
1649 	 * Provide sane defaults for the results in case we never hear
1650 	 * back from the DS before closing the connection.
1651 	 *
1652 	 * In particular we default the result to indicate a retriable
1653 	 * error.  The first complete matching result entry will cause
1654 	 * this to be set to IDMAP_SUCCESS, and the end of the results
1655 	 * for this search will cause this to indicate "not found" if no
1656 	 * result entries arrived or no complete ones matched the lookup
1657 	 * we were doing.
1658 	 */
1659 	*rc = IDMAP_ERR_RETRIABLE_NET_ERR;
1660 	if (sid_type != NULL)
1661 		*sid_type = _IDMAP_T_OTHER;
1662 	if (sid != NULL)
1663 		*sid = NULL;
1664 	if (canonname != NULL)
1665 		*canonname = NULL;
1666 	if (dname != NULL)
1667 		*dname = NULL;
1668 	if (rid != NULL)
1669 		*rid = 0;
1670 
1671 	/* Send this lookup, don't wait for a result here */
1672 	(void) pthread_mutex_lock(&state->qadh->lock);
1673 
1674 	if (!state->qadh->dead) {
1675 		state->qadh->idletime = time(NULL);
1676 		lrc = ldap_search_ext(state->qadh->ld, "",
1677 		    LDAP_SCOPE_SUBTREE, filter, attrs, 0, NULL, NULL,
1678 		    NULL, -1, &q->msgid);
1679 		if (lrc == LDAP_BUSY || lrc == LDAP_UNAVAILABLE ||
1680 		    lrc == LDAP_CONNECT_ERROR || lrc == LDAP_SERVER_DOWN ||
1681 		    lrc == LDAP_UNWILLING_TO_PERFORM) {
1682 			retcode = IDMAP_ERR_RETRIABLE_NET_ERR;
1683 			state->qadh->dead = 1;
1684 		} else if (lrc != LDAP_SUCCESS) {
1685 			retcode = IDMAP_ERR_OTHER;
1686 			state->qadh->dead = 1;
1687 		}
1688 	}
1689 	(void) pthread_mutex_unlock(&state->qadh->lock);
1690 
1691 	if (state->qadh->dead)
1692 		return (retcode);
1693 
1694 	atomic_inc_32(&state->qinflight);
1695 
1696 	/*
1697 	 * Reap as many requests as we can _without_ waiting
1698 	 *
1699 	 * We do this to prevent any possible TCP socket buffer
1700 	 * starvation deadlocks.
1701 	 */
1702 	(void) memset(&tv, 0, sizeof (tv));
1703 	while (idmap_get_adobject_batch(state->qadh, &tv) == 0)
1704 		;
1705 
1706 	return (IDMAP_SUCCESS);
1707 }
1708 
1709 idmap_retcode
1710 idmap_name2sid_batch_add1(idmap_query_state_t *state,
1711 	const char *name, const char *dname, int eunixtype,
1712 	char **canonname, char **sid, rid_t *rid, int *sid_type,
1713 	char **unixname, idmap_retcode *rc)
1714 {
1715 	idmap_retcode	retcode;
1716 	int		len, samAcctNameLen;
1717 	char		*filter = NULL;
1718 	char		*ecanonname, *edomain; /* expected canonname */
1719 
1720 	/*
1721 	 * Strategy: search the global catalog for user/group by
1722 	 * sAMAccountName = user/groupname with "" as the base DN and by
1723 	 * userPrincipalName = user/groupname@domain.  The result
1724 	 * entries will be checked to conform to the name and domain
1725 	 * name given here.  The DN, sAMAccountName, userPrincipalName,
1726 	 * objectSid and objectClass of the result entries are all we
1727 	 * need to figure out which entries match the lookup, the SID of
1728 	 * the user/group and whether it is a user or a group.
1729 	 */
1730 
1731 	/*
1732 	 * We need the name and the domain name separately and as
1733 	 * name@domain.  We also allow the domain to be provided
1734 	 * separately.
1735 	 */
1736 	samAcctNameLen = strlen(name);
1737 
1738 	if ((ecanonname = strdup(name)) == NULL)
1739 		return (IDMAP_ERR_MEMORY);
1740 
1741 	if (dname == NULL || *dname == '\0') {
1742 		if ((dname = strchr(name, '@')) != NULL) {
1743 			/* 'name' is qualified with a domain name */
1744 			if ((edomain = strdup(dname + 1)) == NULL) {
1745 				free(ecanonname);
1746 				return (IDMAP_ERR_MEMORY);
1747 			}
1748 			*strchr(ecanonname, '@') = '\0';
1749 		} else {
1750 			/* 'name' not qualified and dname not given */
1751 			if (state->qadh->owner->dflt_w2k_dom == NULL ||
1752 			    *state->qadh->owner->dflt_w2k_dom == '\0') {
1753 				free(ecanonname);
1754 				return (IDMAP_ERR_DOMAIN);
1755 			}
1756 			edomain = strdup(state->qadh->owner->dflt_w2k_dom);
1757 			if (edomain == NULL) {
1758 				free(ecanonname);
1759 				return (IDMAP_ERR_MEMORY);
1760 			}
1761 		}
1762 	} else {
1763 		if ((edomain = strdup(dname)) == NULL) {
1764 			free(ecanonname);
1765 			return (IDMAP_ERR_MEMORY);
1766 		}
1767 	}
1768 
1769 	/* Assemble filter */
1770 	len = snprintf(NULL, 0, SANFILTER, samAcctNameLen, name) + 1;
1771 	if ((filter = (char *)malloc(len)) == NULL) {
1772 		free(ecanonname);
1773 		return (IDMAP_ERR_MEMORY);
1774 	}
1775 	(void) snprintf(filter, len, SANFILTER, samAcctNameLen, name);
1776 
1777 	retcode = idmap_batch_add1(state, filter, ecanonname, edomain,
1778 	    eunixtype, canonname, NULL, sid, rid, sid_type, unixname, rc);
1779 
1780 	free(filter);
1781 
1782 	return (retcode);
1783 }
1784 
1785 idmap_retcode
1786 idmap_sid2name_batch_add1(idmap_query_state_t *state,
1787 	const char *sid, const rid_t *rid, int eunixtype,
1788 	char **name, char **dname, int *sid_type, char **unixname,
1789 	idmap_retcode *rc)
1790 {
1791 	idmap_retcode	retcode;
1792 	int		flen, ret;
1793 	char		*filter = NULL;
1794 	char		cbinsid[MAXHEXBINSID + 1];
1795 
1796 	/*
1797 	 * Strategy: search [the global catalog] for user/group by
1798 	 * objectSid = SID with empty base DN.  The DN, sAMAccountName
1799 	 * and objectClass of the result are all we need to figure out
1800 	 * the name of the SID and whether it is a user, a group or a
1801 	 * computer.
1802 	 */
1803 
1804 	ret = idmap_txtsid2hexbinsid(sid, rid, &cbinsid[0], sizeof (cbinsid));
1805 	if (ret != 0)
1806 		return (IDMAP_ERR_SID);
1807 
1808 	/* Assemble filter */
1809 	flen = snprintf(NULL, 0, OBJSIDFILTER, cbinsid) + 1;
1810 	if ((filter = (char *)malloc(flen)) == NULL)
1811 		return (IDMAP_ERR_MEMORY);
1812 	(void) snprintf(filter, flen, OBJSIDFILTER, cbinsid);
1813 
1814 	retcode = idmap_batch_add1(state, filter, NULL, NULL, eunixtype,
1815 	    name, dname, NULL, NULL, sid_type, unixname, rc);
1816 
1817 	free(filter);
1818 
1819 	return (retcode);
1820 }
1821 
1822 idmap_retcode
1823 idmap_unixname2sid_batch_add1(idmap_query_state_t *state,
1824 	const char *unixname, int is_user, int is_wuser,
1825 	char **sid, rid_t *rid, char **name, char **dname, int *sid_type,
1826 	idmap_retcode *rc)
1827 {
1828 	idmap_retcode	retcode;
1829 	int		len, ulen;
1830 	char		*filter = NULL;
1831 	const char	*attrname = NULL;
1832 
1833 	/* Get unixuser or unixgroup AD attribute name */
1834 	attrname = (is_user) ?
1835 	    state->ad_unixuser_attr : state->ad_unixgroup_attr;
1836 	if (attrname == NULL)
1837 		return (IDMAP_ERR_NOTFOUND);
1838 
1839 	/*  Assemble filter */
1840 	ulen = strlen(unixname);
1841 	len = snprintf(NULL, 0, "(&(objectclass=%s)(%s=%.*s))",
1842 	    is_wuser ? "user" : "group", attrname, ulen, unixname) + 1;
1843 	if ((filter = (char *)malloc(len)) == NULL)
1844 		return (IDMAP_ERR_MEMORY);
1845 	(void) snprintf(filter, len, "(&(objectclass=%s)(%s=%.*s))",
1846 	    is_wuser ? "user" : "group", attrname, ulen, unixname);
1847 
1848 	retcode = idmap_batch_add1(state, filter, NULL, NULL,
1849 	    _IDMAP_T_UNDEF, name, dname, sid, rid, sid_type, NULL, rc);
1850 
1851 	free(filter);
1852 
1853 	return (retcode);
1854 }
1855