xref: /illumos-gate/usr/src/cmd/idmap/idmapd/adutils.c (revision c5c4113dfcabb1eed3d4bdf7609de5170027a794)
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 2007 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 "idmapd.h"
51 
52 /*
53  * Internal data structures for this code
54  */
55 
56 /* Attribute names and filter format strings */
57 #define	OBJECTSID	"objectSid"
58 #define	OBJECTSIDFILTER	"(objectSid=%s)"
59 #define	SAMACCOUNTNAME	"sAMAccountName"
60 #define	SANFILTER	"(sAMAccountName=%.*s)"
61 #define	OBJECTCLASS	"objectClass"
62 
63 /*
64  * This should really be in some <sys/sid.h> file or so; we have a
65  * private version of sid_t, and so must other components of ON until we
66  * rationalize this.
67  */
68 typedef struct sid {
69 	uchar_t		version;
70 	uchar_t		sub_authority_count;
71 	uint64_t	authority;  /* really, 48-bits */
72 	rid_t		sub_authorities[SID_MAX_SUB_AUTHORITIES];
73 } sid_t;
74 
75 /* A single DS */
76 typedef struct ad_host {
77 	struct ad_host		*next;
78 	ad_t			*owner;		/* ad_t to which this belongs */
79 	pthread_mutex_t		lock;
80 	LDAP			*ld;		/* LDAP connection */
81 	uint32_t		ref;		/* ref count */
82 	time_t			idletime;	/* time since last activity */
83 	int			dead;		/* error on LDAP connection */
84 	/*
85 	 * Used to distinguish between different instances of LDAP
86 	 * connections to this same DS.  We need this so we never mix up
87 	 * results for a given msgID from one connection with those of
88 	 * another earlier connection where two batch state structures
89 	 * share this ad_host object but used different LDAP connections
90 	 * to send their LDAP searches.
91 	 */
92 	uint64_t		generation;
93 
94 	/* LDAP DS info */
95 	char			*host;
96 	int			port;
97 
98 	/* hardwired to SASL GSSAPI only for now */
99 	char			*saslmech;
100 	unsigned		saslflags;
101 } ad_host_t;
102 
103 /* A set of DSs for a given AD partition; ad_t typedef comes from  adutil.h */
104 struct ad {
105 	char			*dflt_w2k_dom;	/* used to qualify bare names */
106 	char			*basedn;	/* derived from dflt domain */
107 	pthread_mutex_t		lock;
108 	uint32_t		ref;
109 	idmap_ad_partition_t	partition;	/* Data or global catalog? */
110 };
111 
112 /*
113  * A place to put the results of a batched (async) query
114  *
115  * There is one of these for every query added to a batch object
116  * (idmap_query_state, see below).
117  */
118 typedef struct idmap_q {
119 	char			**result;	/* name or stringified SID */
120 	char			**domain;	/* name of domain of object */
121 	rid_t			*rid;		/* for n2s, if not NULL */
122 	int			*sid_type;	/* if not NULL */
123 	idmap_retcode		*rc;
124 	int			msgid;		/* LDAP message ID */
125 	/*
126 	 * Bitfield containing state needed to know when we're done
127 	 * processing search results related to this query's LDAP
128 	 * searches.  Mostly self-explanatory.
129 	 */
130 	uint16_t		n2s : 1;	/* name->SID or SID->name? */
131 	uint16_t		got_reply : 1;
132 	uint16_t		got_results : 1;
133 	uint16_t		got_objectSid : 1;
134 	uint16_t		got_objectClass : 1;
135 	uint16_t		got_samAcctName : 1;
136 } idmap_q_t;
137 
138 /* Batch context structure; typedef is in header file */
139 struct idmap_query_state {
140 	idmap_query_state_t	*next;
141 	int			qcount;		/* how many queries */
142 	uint32_t		qlastsent;
143 	uint32_t		qinflight;	/* how many queries in flight */
144 	uint16_t		qdead;		/* oops, lost LDAP connection */
145 	ad_host_t		*qadh;		/* LDAP connection */
146 	uint64_t		qadh_gen;	/* same as qadh->generation */
147 	idmap_q_t		queries[1];	/* array of query results */
148 };
149 
150 /*
151  * List of query state structs -- needed so we can "route" LDAP results
152  * to the right context if multiple threads should be using the same
153  * connection concurrently
154  */
155 static idmap_query_state_t	*qstatehead = NULL;
156 static pthread_mutex_t		qstatelock = PTHREAD_MUTEX_INITIALIZER;
157 
158 /*
159  * List of DSs, needed by the idle connection reaper thread
160  */
161 static ad_host_t	*host_head = NULL;
162 static pthread_t	reaperid = (pthread_t)-1;
163 static pthread_mutex_t	adhostlock = PTHREAD_MUTEX_INITIALIZER;
164 
165 /*ARGSUSED*/
166 static int
167 idmap_saslcallback(LDAP *ld, unsigned flags, void *defaults, void *prompts) {
168 	sasl_interact_t	*interact;
169 
170 	if (prompts == NULL || flags != LDAP_SASL_INTERACTIVE)
171 		return (LDAP_PARAM_ERROR);
172 
173 	/* There should be no extra arguemnts for SASL/GSSAPI authentication */
174 	for (interact = prompts; interact->id != SASL_CB_LIST_END;
175 			interact++) {
176 		interact->result = NULL;
177 		interact->len = 0;
178 	}
179 	return (LDAP_SUCCESS);
180 }
181 
182 /* Turn "foo.bar.com" into "dc=foo,dc=bar,dc=com" */
183 static
184 char *
185 dns2dn(const char *dns)
186 {
187 	int nameparts;
188 
189 	/* Sigh, ldap_dns_to_dn()'s first arg should be a const char * */
190 	return (ldap_dns_to_dn((char *)dns, &nameparts));
191 }
192 
193 /*
194  * Turn "dc=foo,dc=bar,dc=com" into "foo.bar.com"; ignores any other
195  * attributes (CN, etc...)
196  */
197 static
198 char *
199 dn2dns(const char *dn)
200 {
201 	char **rdns = NULL;
202 	char **attrs = NULL;
203 	char **labels = NULL;
204 	char *dns = NULL;
205 	char **rdn, **attr, **label;
206 	int maxlabels = 5;
207 	int nlabels = 0;
208 	int dnslen;
209 
210 	/*
211 	 * There is no reverse of ldap_dns_to_dn() in our libldap, so we
212 	 * have to do the hard work here for now.
213 	 */
214 
215 	/*
216 	 * This code is much too liberal: it looks for "dc" attributes
217 	 * in all RDNs of the DN.  In theory this could cause problems
218 	 * if people were to use "dc" in nodes other than the root of
219 	 * the tree, but in practice noone, least of all Active
220 	 * Directory, does that.
221 	 *
222 	 * On the other hand, this code is much too conservative: it
223 	 * does not make assumptions about ldap_explode_dn(), and _that_
224 	 * is the true for looking at every attr of every RDN.
225 	 *
226 	 * Since we only ever look at dc and those must be DNS labels,
227 	 * at least until we get around to supporting IDN here we
228 	 * shouldn't see escaped labels from AD nor from libldap, though
229 	 * the spec (RFC2253) does allow libldap to escape things that
230 	 * don't need escaping -- if that should ever happen then
231 	 * libldap will need a spanking, and we can take care of that.
232 	 */
233 
234 	/* Explode a DN into RDNs */
235 	if ((rdns = ldap_explode_dn(dn, 0)) == NULL)
236 		return (NULL);
237 
238 	labels = calloc(maxlabels + 1, sizeof (char *));
239 	label = labels;
240 
241 	for (rdn = rdns; *rdn != NULL; rdn++) {
242 		if (attrs != NULL)
243 			ldap_value_free(attrs);
244 
245 		/* Explode each RDN, look for DC attr, save val as DNS label */
246 		if ((attrs = ldap_explode_rdn(rdn[0], 0)) == NULL)
247 			goto done;
248 
249 		for (attr = attrs; *attr != NULL; attr++) {
250 			if (strncasecmp(*attr, "dc=", 3) != 0)
251 				continue;
252 
253 			/* Found a DNS label */
254 			labels[nlabels++] = strdup((*attr) + 3);
255 
256 			if (nlabels == maxlabels) {
257 				char **tmp;
258 				tmp = realloc(labels,
259 				    sizeof (char *) * (maxlabels + 1));
260 
261 				if (tmp == NULL)
262 					goto done;
263 
264 				labels = tmp;
265 				labels[nlabels] = NULL;
266 			}
267 
268 			/* There should be just one DC= attr per-RDN */
269 			break;
270 		}
271 	}
272 
273 	/*
274 	 * Got all the labels, now join with '.'
275 	 *
276 	 * We need room for nlabels - 1 periods ('.'), one nul
277 	 * terminator, and the strlen() of each label.
278 	 */
279 	dnslen = nlabels;
280 	for (label = labels; *label != NULL; label++)
281 		dnslen += strlen(*label);
282 
283 	if ((dns = malloc(dnslen)) == NULL)
284 		goto done;
285 
286 	*dns = '\0';
287 
288 	for (label = labels; *label != NULL; label++) {
289 		(void) strlcat(dns, *label, dnslen);
290 		/*
291 		 * NOTE: the last '.' won't be appended -- there's no room
292 		 * for it!
293 		 */
294 		(void) strlcat(dns, ".", dnslen);
295 	}
296 
297 done:
298 	if (labels != NULL) {
299 		for (label = labels; *label != NULL; label++)
300 			free(*label);
301 		free(labels);
302 	}
303 	if (attrs != NULL)
304 		ldap_value_free(attrs);
305 	if (rdns != NULL)
306 		ldap_value_free(rdns);
307 
308 	return (dns);
309 }
310 
311 /*
312  * Keep connection management simple for now, extend or replace later
313  * with updated libsldap code.
314  */
315 #define	ADREAPERSLEEP	60
316 #define	ADCONN_TIME	300
317 
318 /*
319  * Idle connection reaping side of connection management
320  *
321  * Every minute wake up and look for connections that have been idle for
322  * five minutes or more and close them.
323  */
324 /*ARGSUSED*/
325 static
326 void
327 adreaper(void *arg)
328 {
329 	ad_host_t	*adh;
330 	time_t		now;
331 	timespec_t	ts;
332 
333 	ts.tv_sec = ADREAPERSLEEP;
334 	ts.tv_nsec = 0;
335 
336 	for (;;) {
337 		/*
338 		 * nanosleep(3RT) is thead-safe (no SIGALRM) and more
339 		 * portable than usleep(3C)
340 		 */
341 		(void) nanosleep(&ts, NULL);
342 		(void) pthread_mutex_lock(&adhostlock);
343 		now = time(NULL);
344 		for (adh = host_head; adh != NULL; adh = adh->next) {
345 			(void) pthread_mutex_lock(&adh->lock);
346 			if (adh->ref == 0 && adh->idletime != 0 &&
347 			    adh->idletime + ADCONN_TIME < now) {
348 				if (adh->ld) {
349 					(void) ldap_unbind(adh->ld);
350 					adh->ld = NULL;
351 					adh->idletime = 0;
352 					adh->ref = 0;
353 				}
354 			}
355 			(void) pthread_mutex_unlock(&adh->lock);
356 		}
357 		(void) pthread_mutex_unlock(&adhostlock);
358 	}
359 }
360 
361 int
362 idmap_ad_alloc(ad_t **new_ad, const char *default_domain,
363 		idmap_ad_partition_t part)
364 {
365 	ad_t *ad;
366 
367 	*new_ad = NULL;
368 
369 	if ((default_domain == NULL || *default_domain == '\0') &&
370 	    part != IDMAP_AD_GLOBAL_CATALOG)
371 		return (-1);
372 
373 	if ((ad = calloc(1, sizeof (ad_t))) == NULL)
374 		return (-1);
375 
376 	ad->ref = 1;
377 	ad->partition = part;
378 
379 	/*
380 	 * If default_domain is NULL, deal, deferring errors until
381 	 * idmap_lookup_batch_start() -- this makes it easier on the
382 	 * caller, who can simply observe lookups failing as opposed to
383 	 * having to conditionalize calls to lookups according to
384 	 * whether it has a non-NULL ad_t *.
385 	 */
386 	if (default_domain == NULL)
387 		default_domain = "";
388 
389 	if ((ad->dflt_w2k_dom = strdup(default_domain)) == NULL)
390 		goto err;
391 
392 	/* If default_domain is empty, deal; see above */
393 	if (*default_domain == '\0') {
394 		if ((ad->basedn = strdup("")) == NULL)
395 			goto err;
396 	} else if ((ad->basedn = dns2dn(default_domain)) == NULL) {
397 		goto err;
398 	}
399 
400 	if (pthread_mutex_init(&ad->lock, NULL) != 0)
401 		goto err;
402 
403 	*new_ad = ad;
404 
405 	return (0);
406 err:
407 	if (ad->dflt_w2k_dom != NULL)
408 		free(ad->dflt_w2k_dom);
409 	if (ad->basedn != NULL)
410 		free(ad->basedn);
411 	free(ad);
412 	return (-1);
413 }
414 
415 
416 void
417 idmap_ad_free(ad_t **ad)
418 {
419 	ad_host_t *p;
420 
421 	if (ad == NULL || *ad == NULL)
422 		return;
423 
424 	(void) pthread_mutex_lock(&(*ad)->lock);
425 
426 	if (atomic_dec_32_nv(&(*ad)->ref) > 0) {
427 		(void) pthread_mutex_unlock(&(*ad)->lock);
428 		*ad = NULL;
429 		return;
430 	}
431 
432 	for (p = host_head; p != NULL; p = p->next) {
433 		if (p->owner != (*ad))
434 			continue;
435 		idmap_delete_ds((*ad), p->host, p->port);
436 	}
437 
438 	free((*ad)->basedn);
439 
440 	(void) pthread_mutex_unlock(&(*ad)->lock);
441 	(void) pthread_mutex_destroy(&(*ad)->lock);
442 
443 	free(*ad);
444 
445 	*ad = NULL;
446 }
447 
448 static
449 int
450 idmap_open_conn(ad_host_t *adh)
451 {
452 	int	rc, ldversion;
453 
454 	if (adh->dead && adh->ld != NULL) {
455 		(void) ldap_unbind(adh->ld);
456 		adh->ld = NULL;
457 		adh->dead = 0;
458 	}
459 
460 	if (adh->ld == NULL) {
461 		int zero = 0;
462 		int timeoutms = 30 * 1000;
463 
464 		atomic_inc_64(&adh->generation);
465 		adh->ld = ldap_init(adh->host, adh->port);
466 		if (adh->ld == NULL)
467 			return (-1);
468 
469 		ldversion = LDAP_VERSION3;
470 		(void) ldap_set_option(adh->ld, LDAP_OPT_PROTOCOL_VERSION,
471 		    &ldversion);
472 
473 		(void) ldap_set_option(adh->ld, LDAP_OPT_REFERRALS,
474 		    LDAP_OPT_OFF);
475 		(void) ldap_set_option(adh->ld, LDAP_OPT_TIMELIMIT, &zero);
476 		(void) ldap_set_option(adh->ld, LDAP_OPT_SIZELIMIT, &zero);
477 		/* setup TCP/IP connect timeout */
478 		(void) ldap_set_option(adh->ld, LDAP_X_OPT_CONNECT_TIMEOUT,
479 		    &timeoutms);
480 		(void) ldap_set_option(adh->ld, LDAP_OPT_RESTART, LDAP_OPT_ON);
481 		rc = ldap_sasl_interactive_bind_s(adh->ld,
482 		    "" /* binddn */, adh->saslmech, NULL, NULL, adh->saslflags,
483 		    &idmap_saslcallback, NULL /* defaults */);
484 
485 		if (rc != LDAP_SUCCESS) {
486 			idmapdlog(LOG_ERR, "Could not authenticate to the "
487 			    "LDAP server.  (Check that the host keys are "
488 			    "correct?)");
489 			return (rc);
490 		}
491 	}
492 
493 	adh->idletime = time(NULL);
494 
495 	return (LDAP_SUCCESS);
496 }
497 
498 
499 /*
500  * Connection management: find an open connection or open one
501  */
502 static
503 ad_host_t *
504 idmap_get_conn(const ad_t *ad)
505 {
506 	ad_host_t	*adh = NULL;
507 	int		rc;
508 
509 	(void) pthread_mutex_lock(&adhostlock);
510 
511 	/*
512 	 * Search for any ad_host_t, preferably one with an open
513 	 * connection
514 	 */
515 	for (adh = host_head; adh != NULL; adh = adh->next) {
516 		if (adh->owner == ad) {
517 			break;
518 		}
519 	}
520 
521 	if (adh != NULL)
522 		atomic_inc_32(&adh->ref);
523 
524 	(void) pthread_mutex_unlock(&adhostlock);
525 
526 	if (adh == NULL)
527 		return (NULL);
528 
529 	/* found connection, open it if not opened */
530 	(void) pthread_mutex_lock(&adh->lock);
531 	rc = idmap_open_conn(adh);
532 	(void) pthread_mutex_unlock(&adh->lock);
533 	if (rc != LDAP_SUCCESS)
534 		return (NULL);
535 
536 	return (adh);
537 }
538 
539 static
540 void
541 idmap_release_conn(ad_host_t *adh)
542 {
543 	(void) pthread_mutex_lock(&adh->lock);
544 	if (atomic_dec_32_nv(&adh->ref) == 0)
545 		adh->idletime = time(NULL);
546 	(void) pthread_mutex_unlock(&adh->lock);
547 }
548 
549 /*
550  * Take ad_host_config_t information, create a ad_host_t,
551  * populate it and add it to the list of hosts.
552  */
553 
554 int
555 idmap_add_ds(ad_t *ad, const char *host, int port)
556 {
557 	ad_host_t	*p;
558 	ad_host_t	*new = NULL;
559 	int		ret = -1;
560 
561 	if (port == 0)
562 		port = (int)ad->partition;
563 
564 	(void) pthread_mutex_lock(&adhostlock);
565 	for (p = host_head; p != NULL; p = p->next) {
566 		if (p->owner != ad)
567 			continue;
568 
569 		if (strcmp(host, p->host) == 0 && p->port == port) {
570 			/* already added */
571 			ret = -2;
572 			goto err;
573 		}
574 	}
575 
576 	/* add new entry */
577 	new = (ad_host_t *)calloc(1, sizeof (ad_host_t));
578 	if (new == NULL)
579 		goto err;
580 	new->owner = ad;
581 	new->port = port;
582 	new->dead = 0;
583 	if ((new->host = strdup(host)) == NULL)
584 		goto err;
585 
586 	/* default to SASL GSSAPI only for now */
587 	new->saslflags = LDAP_SASL_INTERACTIVE;
588 	new->saslmech = "GSSAPI";
589 
590 	if ((ret = pthread_mutex_init(&new->lock, NULL)) != 0) {
591 		free(new->host);
592 		new->host = NULL;
593 		errno = ret;
594 		ret = -1;
595 		goto err;
596 	}
597 
598 	/* link in */
599 	new->next = host_head;
600 	host_head = new;
601 
602 	/* Start reaper if it doesn't exist */
603 	if (reaperid == 0)
604 		(void) pthread_create(&reaperid, NULL,
605 		    (void *(*)(void *))adreaper, (void *)NULL);
606 
607 err:
608 	(void) pthread_mutex_unlock(&adhostlock);
609 
610 	if (ret != 0 && new != NULL) {
611 		if (new->host != NULL) {
612 			(void) pthread_mutex_destroy(&new->lock);
613 			free(new->host);
614 		}
615 		free(new);
616 	}
617 
618 	return (ret);
619 }
620 
621 /*
622  * free a DS configuration
623  */
624 void
625 idmap_delete_ds(ad_t *ad, const char *host, int port)
626 {
627 	ad_host_t	**p, *q;
628 
629 	(void) pthread_mutex_lock(&adhostlock);
630 	for (p = &host_head; *p != NULL; p = &((*p)->next)) {
631 		if ((*p)->owner != ad || strcmp(host, (*p)->host) != 0 ||
632 		    (*p)->port != port)
633 			continue;
634 		/* found */
635 		if (atomic_dec_32_nv(&((*p)->ref)) > 0)
636 			break;	/* still in use */
637 
638 		q = *p;
639 		*p = (*p)->next;
640 
641 		(void) pthread_mutex_destroy(&q->lock);
642 
643 		if (q->ld)
644 			(void) ldap_unbind(q->ld);
645 		if (q->host)
646 			free(q->host);
647 		free(q);
648 		break;
649 	}
650 	(void) pthread_mutex_unlock(&adhostlock);
651 }
652 
653 /*
654  * Convert a binary SID in a BerValue to a sid_t
655  */
656 static
657 int
658 idmap_getsid(BerValue *bval, sid_t *sidp)
659 {
660 	int		i, j;
661 	uchar_t		*v;
662 	uint32_t	a;
663 
664 	/*
665 	 * The binary format of a SID is as follows:
666 	 *
667 	 * byte #0: version, always 0x01
668 	 * byte #1: RID count, always <= 0x0f
669 	 * bytes #2-#7: SID authority, big-endian 48-bit unsigned int
670 	 *
671 	 * followed by RID count RIDs, each a little-endian, unsigned
672 	 * 32-bit int.
673 	 */
674 	/*
675 	 * Sanity checks: must have at least one RID, version must be
676 	 * 0x01, and the length must be 8 + rid count * 4
677 	 */
678 	if (bval->bv_len > 8 && bval->bv_val[0] == 0x01 &&
679 	    bval->bv_len == 1 + 1 + 6 + bval->bv_val[1] * 4) {
680 		v = (uchar_t *)bval->bv_val;
681 		sidp->version = v[0];
682 		sidp->sub_authority_count = v[1];
683 		sidp->authority =
684 		    /* big endian -- so start from the left */
685 		    ((u_longlong_t)v[2] << 40) |
686 		    ((u_longlong_t)v[3] << 32) |
687 		    ((u_longlong_t)v[4] << 24) |
688 		    ((u_longlong_t)v[5] << 16) |
689 		    ((u_longlong_t)v[6] << 8) |
690 		    (u_longlong_t)v[7];
691 		for (i = 0; i < sidp->sub_authority_count; i++) {
692 			j = 8 + (i * 4);
693 			/* little endian -- so start from the right */
694 			a = (v[j + 3] << 24) | (v[j + 2] << 16) |
695 			    (v[j + 1] << 8) | (v[j]);
696 			sidp->sub_authorities[i] = a;
697 		}
698 		return (0);
699 	}
700 	return (-1);
701 }
702 
703 /*
704  * Convert a sid_t to S-1-...
705  */
706 static
707 char *
708 idmap_sid2txt(sid_t *sidp)
709 {
710 	int	rlen, i, len;
711 	char	*str, *cp;
712 
713 	if (sidp->version != 1)
714 		return (NULL);
715 
716 	len = sizeof ("S-1-") - 1;
717 
718 	/*
719 	 * We could optimize like so, but, why?
720 	 *	if (sidp->authority < 10)
721 	 *		len += 2;
722 	 *	else if (sidp->authority < 100)
723 	 *		len += 3;
724 	 *	else
725 	 *		len += snprintf(NULL, 0"%llu", sidp->authority);
726 	 */
727 	len += snprintf(NULL, 0, "%llu", sidp->authority);
728 
729 	/* Max length of a uint32_t printed out in ASCII is 10 bytes */
730 	len += 1 + (sidp->sub_authority_count + 1) * 10;
731 
732 	if ((cp = str = malloc(len)) == NULL)
733 		return (NULL);
734 
735 	rlen = snprintf(str, len, "S-1-%llu", sidp->authority);
736 
737 	cp += rlen;
738 	len -= rlen;
739 
740 	for (i = 0; i < sidp->sub_authority_count; i++) {
741 		assert(len > 0);
742 		rlen = snprintf(cp, len, "-%u", sidp->sub_authorities[i]);
743 		cp += rlen;
744 		len -= rlen;
745 		assert(len >= 0);
746 	}
747 
748 	return (str);
749 }
750 
751 /*
752  * Convert a sid_t to on-the-wire encoding
753  */
754 static
755 int
756 idmap_sid2binsid(sid_t *sid, uchar_t *binsid, int binsidlen)
757 {
758 	uchar_t		*p;
759 	int		i;
760 	uint64_t	a;
761 	uint32_t	r;
762 
763 	if (sid->version != 1 ||
764 	    binsidlen != (1 + 1 + 6 + sid->sub_authority_count * 4))
765 		return (-1);
766 
767 	p = binsid;
768 	*p++ = 0x01;		/* version */
769 	/* sub authority count */
770 	*p++ = sid->sub_authority_count;
771 	/* Authority */
772 	a = sid->authority;
773 	/* big-endian -- start from left */
774 	*p++ = (a >> 40) & 0xFF;
775 	*p++ = (a >> 32) & 0xFF;
776 	*p++ = (a >> 24) & 0xFF;
777 	*p++ = (a >> 16) & 0xFF;
778 	*p++ = (a >> 8) & 0xFF;
779 	*p++ = a & 0xFF;
780 
781 	/* sub-authorities */
782 	for (i = 0; i < sid->sub_authority_count; i++) {
783 		r = sid->sub_authorities[i];
784 		/* little-endian -- start from right */
785 		*p++ = (r & 0x000000FF);
786 		*p++ = (r & 0x0000FF00) >> 8;
787 		*p++ = (r & 0x00FF0000) >> 16;
788 		*p++ = (r & 0xFF000000) >> 24;
789 	}
790 
791 	return (0);
792 }
793 
794 /*
795  * Convert a stringified SID (S-1-...) into a hex-encoded version of the
796  * on-the-wire encoding, but with each pair of hex digits pre-pended
797  * with a '\', so we can pass this to libldap.
798  */
799 static
800 int
801 idmap_txtsid2hexbinsid(const char *txt, const rid_t *rid,
802 	char *hexbinsid, int hexbinsidlen)
803 {
804 	sid_t		sid = { 0 };
805 	int		i, j;
806 	const char	*cp;
807 	char		*ecp;
808 	u_longlong_t	a;
809 	unsigned long	r;
810 	uchar_t		*binsid, b, hb;
811 
812 	/* Only version 1 SIDs please */
813 	if (strncmp(txt, "S-1-", strlen("S-1-")) != 0)
814 		return (-1);
815 
816 	if (strlen(txt) < (strlen("S-1-") + 1))
817 		return (-1);
818 
819 	/* count '-'s */
820 	for (j = 0, cp = strchr(txt, '-');
821 	    cp != NULL && *cp != '\0';
822 	    j++, cp = strchr(cp + 1, '-')) {
823 		/* can't end on a '-' */
824 		if (*(cp + 1) == '\0')
825 			return (-1);
826 	}
827 
828 	/* must have at least one RID, but not too many */
829 	if (j < 3 || (j - 1) > SID_MAX_SUB_AUTHORITIES ||
830 	    (rid != NULL && j > SID_MAX_SUB_AUTHORITIES))
831 		return (-1);
832 
833 	/* check that we only have digits and '-' */
834 	if (strspn(txt + 1, "0123456789-") < (strlen(txt) - 1))
835 		return (-1);
836 
837 	/* we know the version number and RID count */
838 	sid.version = 1;
839 	sid.sub_authority_count = j - 2;
840 
841 	cp = txt + strlen("S-1-");
842 
843 	/* 64-bit safe parsing of unsigned 48-bit authority value */
844 	errno = 0;
845 	a = strtoull(cp, &ecp, 10);
846 
847 	/* errors parsing the authority or too many bits */
848 	if (cp == ecp || (a == 0 && errno == EINVAL) ||
849 	    (a == ULLONG_MAX && errno == ERANGE) ||
850 	    (a & 0x0000ffffffffffffULL) != a)
851 		return (-1);
852 
853 	cp = ecp;
854 
855 	sid.authority = (uint64_t)a;
856 
857 	for (i = 0; i < sid.sub_authority_count; i++) {
858 		if (*cp++ != '-')
859 			return (-1);
860 		/* 64-bit safe parsing of unsigned 32-bit RID */
861 		errno = 0;
862 		r = strtoul(cp, &ecp, 10);
863 		/* errors parsing the RID or too many bits */
864 		if (cp == ecp || (r == 0 && errno == EINVAL) ||
865 		    (r == ULONG_MAX && errno == ERANGE) ||
866 		    (r & 0xffffffffUL) != r)
867 			return (-1);
868 		sid.sub_authorities[i] = (uint32_t)r;
869 		cp = ecp;
870 	}
871 
872 	/* check that all of the string SID has been consumed */
873 	if (*cp != '\0')
874 		return (-1);
875 
876 	if (rid != NULL) {
877 		sid.sub_authorities[sid.sub_authority_count++] = *rid;
878 	}
879 
880 	j = 1 + 1 + 6 + sid.sub_authority_count * 4;
881 
882 	if (hexbinsidlen < (j * 3))
883 		return (-2);
884 
885 	/* binary encode the SID */
886 	binsid = (uchar_t *)alloca(j);
887 	(void) idmap_sid2binsid(&sid, binsid, j);
888 
889 	/* hex encode, with a backslash before each byte */
890 	for (ecp = hexbinsid, i = 0; i < j; i++) {
891 		b = binsid[i];
892 		*ecp++ = '\\';
893 		hb = (b >> 4) & 0xF;
894 		*ecp++ = (hb <= 0x9 ? hb + '0' : hb - 10 + 'A');
895 		hb = b & 0xF;
896 		*ecp++ = (hb <= 0x9 ? hb + '0' : hb - 10 + 'A');
897 	}
898 	*ecp = '\0';
899 
900 	return (0);
901 }
902 
903 static
904 char *
905 convert_bval2sid(BerValue *bval, rid_t *rid)
906 {
907 	sid_t	sid;
908 
909 	if (idmap_getsid(bval, &sid) < 0)
910 		return (NULL);
911 
912 	/*
913 	 * If desired and if the SID is what should be a domain/computer
914 	 * user or group SID (i.e., S-1-5-w-x-y-z-<user/group RID>) then
915 	 * save the last RID and truncate the SID
916 	 */
917 	if (rid != NULL && sid.authority == 5 && sid.sub_authority_count == 5)
918 		*rid = sid.sub_authorities[--sid.sub_authority_count];
919 	return (idmap_sid2txt(&sid));
920 }
921 
922 
923 idmap_retcode
924 idmap_lookup_batch_start(ad_t *ad, int nqueries, idmap_query_state_t **state)
925 {
926 	idmap_query_state_t *new_state;
927 	ad_host_t	*adh = NULL;
928 
929 	*state = NULL;
930 
931 	if (*ad->dflt_w2k_dom == '\0')
932 		return (-1);
933 
934 	adh = idmap_get_conn(ad);
935 	if (adh == NULL)
936 		return (IDMAP_ERR_OTHER);
937 
938 	new_state = calloc(1, sizeof (idmap_query_state_t) +
939 	    (nqueries - 1) * sizeof (idmap_q_t));
940 
941 	if (new_state == NULL)
942 		return (IDMAP_ERR_MEMORY);
943 
944 	new_state->qadh = adh;
945 	new_state->qcount = nqueries;
946 	new_state->qadh_gen = adh->generation;
947 	/* should be -1, but the atomic routines want unsigned */
948 	new_state->qlastsent = 0;
949 
950 	(void) pthread_mutex_lock(&qstatelock);
951 	new_state->next = qstatehead;
952 	qstatehead = new_state;
953 	(void) pthread_mutex_unlock(&qstatelock);
954 
955 	*state = new_state;
956 
957 	return (IDMAP_SUCCESS);
958 }
959 
960 /*
961  * Find the idmap_query_state_t to which a given LDAP result msgid on a
962  * given connection belongs
963  */
964 static
965 int
966 idmap_msgid2query(ad_host_t *adh, int msgid,
967 	idmap_query_state_t **state, int *qid)
968 {
969 	idmap_query_state_t *p;
970 	int		    i;
971 
972 	(void) pthread_mutex_lock(&qstatelock);
973 	for (p = qstatehead; p != NULL; p = p->next) {
974 		if (p->qadh != adh || adh->generation != p->qadh_gen)
975 			continue;
976 		for (i = 0; i < p->qcount; i++) {
977 			if ((p->queries[i]).msgid == msgid) {
978 				*state = p;
979 				*qid = i;
980 				(void) pthread_mutex_unlock(&qstatelock);
981 				return (1);
982 			}
983 		}
984 	}
985 	(void) pthread_mutex_unlock(&qstatelock);
986 	return (0);
987 }
988 
989 /*
990  * Handle an objectSid attr from a result
991  */
992 static
993 void
994 idmap_bv_objsid2sidstr(BerValue **bvalues, idmap_q_t *q)
995 {
996 	if (bvalues == NULL)
997 		return;
998 	/* objectSid is single valued */
999 	*(q->result) = convert_bval2sid(bvalues[0], q->rid);
1000 	q->got_objectSid = 1;
1001 }
1002 
1003 /*
1004  * Handle a sAMAccountName attr from a result
1005  */
1006 static
1007 void
1008 idmap_bv_samaccountname2name(BerValue **bvalues, idmap_q_t *q, const char *dn)
1009 {
1010 	char *result, *domain;
1011 	int len;
1012 
1013 	if (bvalues == NULL)
1014 		return;
1015 
1016 	if ((domain = dn2dns(dn)) == NULL)
1017 		return;
1018 
1019 	if (bvalues == NULL || bvalues[0] == NULL ||
1020 	    bvalues[0]->bv_val == NULL)
1021 		return;
1022 
1023 	len = bvalues[0]->bv_len + 1;
1024 
1025 	if (q->domain != NULL)
1026 		*(q->domain) = domain;
1027 	else
1028 		len += strlen(domain) + 1;
1029 
1030 	if ((result = malloc(len)) == NULL) {
1031 		if (q->domain != NULL)
1032 			*(q->domain) = NULL;
1033 		free(domain);
1034 		return;
1035 	}
1036 
1037 	(void) memcpy(result, bvalues[0]->bv_val, (size_t)bvalues[0]->bv_len);
1038 	result[bvalues[0]->bv_len] = '\0';
1039 
1040 	if (q->domain == NULL) {
1041 		(void) strlcat(result, "@", len);
1042 		(void) strlcat(result, domain, len);
1043 		free(domain);
1044 	}
1045 
1046 	*(q->result) = result;
1047 	q->got_samAcctName = 1;
1048 }
1049 
1050 
1051 #define	BVAL_CASEEQ(bv, str) \
1052 		(((*(bv))->bv_len == (sizeof (str) - 1)) && \
1053 		    strncasecmp((*(bv))->bv_val, str, (*(bv))->bv_len) == 0)
1054 
1055 /*
1056  * Handle an objectClass attr from a result
1057  */
1058 static
1059 void
1060 idmap_bv_objclass2sidtype(BerValue **bvalues, idmap_q_t *q)
1061 {
1062 	BerValue	**cbval;
1063 
1064 	if (bvalues == NULL)
1065 		return;
1066 
1067 	for (cbval = bvalues; *cbval != NULL; cbval++) {
1068 		/* don't clobber sid_type */
1069 		if (*(q->sid_type) == _IDMAP_T_COMPUTER ||
1070 		    *(q->sid_type) == _IDMAP_T_GROUP ||
1071 		    *(q->sid_type) == _IDMAP_T_USER)
1072 			continue;
1073 
1074 		if (BVAL_CASEEQ(cbval, "Computer")) {
1075 			*(q->sid_type) = _IDMAP_T_COMPUTER;
1076 			return;
1077 		} else if (BVAL_CASEEQ(cbval, "Group")) {
1078 			*(q->sid_type) = _IDMAP_T_GROUP;
1079 		} else if (BVAL_CASEEQ(cbval, "USER")) {
1080 			*(q->sid_type) = _IDMAP_T_USER;
1081 		} else
1082 			*(q->sid_type) = _IDMAP_T_OTHER;
1083 		q->got_objectClass = 1;
1084 	}
1085 }
1086 
1087 /*
1088  * Handle a given search result entry
1089  */
1090 static
1091 void
1092 idmap_extract_object(idmap_query_state_t *state, int qid, LDAPMessage *res)
1093 {
1094 	char			*dn, *attr;
1095 	BerElement		*ber = NULL;
1096 	BerValue		**bvalues;
1097 	ad_host_t		*adh;
1098 	idmap_q_t		*q;
1099 	idmap_retcode		orc;
1100 
1101 	adh = state->qadh;
1102 
1103 	(void) pthread_mutex_lock(&adh->lock);
1104 
1105 	if (adh->dead || (dn = ldap_get_dn(adh->ld, res)) == NULL) {
1106 		(void) pthread_mutex_unlock(&adh->lock);
1107 		return;
1108 	}
1109 
1110 	q = &(state->queries[qid]);
1111 
1112 	for (attr = ldap_first_attribute(adh->ld, res, &ber); attr != NULL;
1113 	    attr = ldap_next_attribute(adh->ld, res, ber)) {
1114 		orc = *q->rc;
1115 		bvalues = NULL;	/* for memory management below */
1116 
1117 		/*
1118 		 * If this is an attribute we are looking for and
1119 		 * haven't seen it yet, parse it
1120 		 */
1121 		if (orc != IDMAP_SUCCESS && q->n2s && !q->got_objectSid &&
1122 		    strcasecmp(attr, OBJECTSID) == 0) {
1123 			bvalues = ldap_get_values_len(adh->ld, res, attr);
1124 			idmap_bv_objsid2sidstr(bvalues, q);
1125 		} else if (orc != IDMAP_SUCCESS && !q->n2s &&
1126 		    !q->got_samAcctName &&
1127 		    strcasecmp(attr, SAMACCOUNTNAME) == 0) {
1128 			bvalues = ldap_get_values_len(adh->ld, res, attr);
1129 			idmap_bv_samaccountname2name(bvalues, q, dn);
1130 		} else if (orc != IDMAP_SUCCESS && !q->got_objectClass &&
1131 		    strcasecmp(attr, OBJECTCLASS) == 0) {
1132 			bvalues = ldap_get_values_len(adh->ld, res, attr);
1133 			idmap_bv_objclass2sidtype(bvalues, q);
1134 		}
1135 
1136 		if (bvalues != NULL)
1137 			ldap_value_free_len(bvalues);
1138 		ldap_memfree(attr);
1139 
1140 		if (q->n2s)
1141 			*q->rc = (q->got_objectSid &&
1142 			    q->got_objectClass) ?
1143 			    IDMAP_SUCCESS : IDMAP_ERR_NORESULT;
1144 		else
1145 			*q->rc = (q->got_samAcctName &&
1146 			    q->got_objectClass) ?
1147 			    IDMAP_SUCCESS : IDMAP_ERR_NORESULT;
1148 
1149 		if (*q->rc == IDMAP_SUCCESS && *q->result == NULL)
1150 			*q->rc = IDMAP_ERR_NORESULT;
1151 	}
1152 	(void) pthread_mutex_unlock(&adh->lock);
1153 
1154 	/*
1155 	 * If there should be multiple partial results for different
1156 	 * entities (there should not be, but, if it should happen) then
1157 	 * it's possible that they could get mixed up here and we could
1158 	 * get bogus results.  We just mark the query's results as
1159 	 * toxic (IDMAP_ERR_INTERNAL).
1160 	 *
1161 	 * Between this and ignoring results when we've already filled
1162 	 * out a query's results we should be OK.  The first full reply
1163 	 * wins.  In practice we should never get multiple results.
1164 	 */
1165 	if (orc == IDMAP_ERR_INTERNAL)
1166 		*q->rc = IDMAP_ERR_INTERNAL;
1167 	else if (*q->rc != IDMAP_SUCCESS)
1168 		*q->rc = IDMAP_ERR_INTERNAL;
1169 
1170 	if (ber != NULL)
1171 		ber_free(ber, 0);
1172 
1173 	ldap_memfree(dn);
1174 }
1175 
1176 /*
1177  * Try to get a result; if there is one, find the corresponding
1178  * idmap_q_t and process the result.
1179  */
1180 static
1181 int
1182 idmap_get_adobject_batch(ad_host_t *adh, struct timeval *timeout)
1183 {
1184 	idmap_query_state_t	*query_state;
1185 	LDAPMessage		*res = NULL;
1186 	int			rc, ret, msgid, qid;
1187 
1188 	(void) pthread_mutex_lock(&adh->lock);
1189 	if (adh->dead) {
1190 		(void) pthread_mutex_unlock(&adh->lock);
1191 		return (-1);
1192 	}
1193 
1194 	/* Get one result */
1195 	rc = ldap_result(adh->ld, LDAP_RES_ANY, 0,
1196 	    timeout, &res);
1197 	if (rc == LDAP_UNAVAILABLE || rc == LDAP_UNWILLING_TO_PERFORM ||
1198 	    rc == LDAP_CONNECT_ERROR || rc == LDAP_SERVER_DOWN ||
1199 	    rc == LDAP_BUSY)
1200 		adh->dead = 1;
1201 	(void) pthread_mutex_unlock(&adh->lock);
1202 
1203 	if (adh->dead)
1204 		return (-1);
1205 
1206 	switch (rc) {
1207 	case LDAP_RES_SEARCH_RESULT:
1208 		/* We have all the LDAP replies for some search... */
1209 		msgid = ldap_msgid(res);
1210 		if (idmap_msgid2query(adh, msgid,
1211 		    &query_state, &qid)) {
1212 			/* ...so we can decrement qinflight */
1213 			atomic_dec_32(&query_state->qinflight);
1214 			/* we saw at least one reply */
1215 			query_state->queries[qid].got_reply = 1;
1216 		}
1217 		(void) ldap_msgfree(res);
1218 		ret = 0;
1219 		break;
1220 	case LDAP_RES_SEARCH_REFERENCE:
1221 		/*
1222 		 * We have no need for these at the moment.  Eventually,
1223 		 * when we query things that we can't expect to find in
1224 		 * the Global Catalog then we'll need to learn to follow
1225 		 * references.
1226 		 */
1227 		(void) ldap_msgfree(res);
1228 		ret = 0;
1229 		break;
1230 	case LDAP_RES_SEARCH_ENTRY:
1231 		/* Got a result */
1232 		msgid = ldap_msgid(res);
1233 		if (idmap_msgid2query(adh, msgid,
1234 		    &query_state, &qid)) {
1235 			idmap_extract_object(query_state, qid, res);
1236 			/* we saw at least one result */
1237 			query_state->queries[qid].got_reply = 1;
1238 			query_state->queries[qid].got_results = 1;
1239 		}
1240 		(void) ldap_msgfree(res);
1241 		ret = 0;
1242 		break;
1243 	default:
1244 		/* timeout or error; treat the same */
1245 		ret = -1;
1246 		break;
1247 	}
1248 
1249 	return (ret);
1250 }
1251 
1252 void
1253 idmap_lookup_free_batch(idmap_query_state_t **state)
1254 {
1255 	idmap_query_state_t **p;
1256 
1257 	idmap_release_conn((*state)->qadh);
1258 
1259 	/* Remove this state struct from the list of state structs */
1260 	(void) pthread_mutex_lock(&qstatelock);
1261 	for (p = &qstatehead; *p != NULL; p = &(*p)->next) {
1262 		if (*p == (*state)) {
1263 			*p = (*state)->next;
1264 			break;
1265 		}
1266 	}
1267 	(void) pthread_mutex_unlock(&qstatelock);
1268 
1269 	free(*state);
1270 	*state = NULL;
1271 }
1272 
1273 idmap_retcode
1274 idmap_lookup_batch_end(idmap_query_state_t **state,
1275 	struct timeval *timeout)
1276 {
1277 	idmap_q_t	    *q;
1278 	int		    i;
1279 	int		    rc = LDAP_SUCCESS;
1280 	idmap_retcode	    retcode = IDMAP_SUCCESS;
1281 
1282 	(*state)->qdead = 1;
1283 
1284 	/* Process results until done or until timeout, if given */
1285 	while ((*state)->qinflight > 0) {
1286 		if ((rc = idmap_get_adobject_batch((*state)->qadh,
1287 		    timeout)) != 0)
1288 			break;
1289 	}
1290 
1291 	if (rc == LDAP_UNAVAILABLE || rc == LDAP_UNWILLING_TO_PERFORM ||
1292 	    rc == LDAP_CONNECT_ERROR || rc == LDAP_SERVER_DOWN ||
1293 	    rc == LDAP_BUSY) {
1294 		retcode = IDMAP_ERR_RETRIABLE_NET_ERR;
1295 		(*state)->qadh->dead = 1;
1296 	}
1297 
1298 	for (i = 0; i < (*state)->qcount; i++) {
1299 		q = &((*state)->queries[i]);
1300 		if (q->got_reply && !q->got_results) {
1301 			if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
1302 				*q->rc = IDMAP_ERR_RETRIABLE_NET_ERR;
1303 			else
1304 				*q->rc = IDMAP_ERR_NOTFOUND;
1305 		}
1306 	}
1307 
1308 	idmap_lookup_free_batch(state);
1309 
1310 	return (retcode);
1311 }
1312 
1313 /*
1314  * Send one prepared search, queue up msgid, process what results are
1315  * available
1316  */
1317 static
1318 idmap_retcode
1319 idmap_batch_add1(idmap_query_state_t *state, int n2s,
1320 	const char *filter, const char *basedn,
1321 	char **result, char **dname, rid_t *rid, int *sid_type,
1322 	idmap_retcode *rc)
1323 {
1324 	idmap_retcode	retcode = IDMAP_SUCCESS;
1325 	int		lrc, qid;
1326 	struct timeval	tv;
1327 	idmap_q_t	*q;
1328 
1329 	if (state->qdead) {
1330 		*rc = IDMAP_ERR_NORESULT;
1331 		return (IDMAP_ERR_RETRIABLE_NET_ERR);
1332 	}
1333 
1334 	qid = atomic_inc_32_nv(&state->qlastsent) - 1;
1335 
1336 	q = &(state->queries[qid]);
1337 
1338 	/* Remember where to put the results */
1339 	q->result = result;
1340 	q->domain = dname;
1341 	q->rid = rid;
1342 	q->sid_type = sid_type;
1343 	q->rc = rc;
1344 	q->n2s = n2s ? 1 : 0;
1345 	q->got_objectSid = 0;
1346 	q->got_objectClass = 0;
1347 	q->got_samAcctName = 0;
1348 
1349 	/*
1350 	 * Provide sane defaults for the results in case we never hear
1351 	 * back from the DS before closing the connection.
1352 	 */
1353 	*rc = IDMAP_ERR_RETRIABLE_NET_ERR;
1354 	*sid_type = _IDMAP_T_OTHER;
1355 	*result = NULL;
1356 	if (dname != NULL)
1357 		*dname = NULL;
1358 	if (rid != NULL)
1359 		*rid = 0;
1360 
1361 	/* Send this lookup, don't wait for a result here */
1362 	(void) pthread_mutex_lock(&state->qadh->lock);
1363 
1364 	if (!state->qadh->dead) {
1365 		state->qadh->idletime = time(NULL);
1366 		lrc = ldap_search_ext(state->qadh->ld, basedn,
1367 		    LDAP_SCOPE_SUBTREE, filter, NULL, 0, NULL, NULL,
1368 		    NULL, -1, &q->msgid);
1369 		if (lrc == LDAP_BUSY || lrc == LDAP_UNAVAILABLE ||
1370 		    lrc == LDAP_CONNECT_ERROR || lrc == LDAP_SERVER_DOWN ||
1371 		    lrc == LDAP_UNWILLING_TO_PERFORM) {
1372 			retcode = IDMAP_ERR_RETRIABLE_NET_ERR;
1373 			state->qadh->dead = 1;
1374 		} else if (lrc != LDAP_SUCCESS) {
1375 			retcode = IDMAP_ERR_OTHER;
1376 			state->qadh->dead = 1;
1377 		}
1378 	}
1379 	(void) pthread_mutex_unlock(&state->qadh->lock);
1380 
1381 	if (state->qadh->dead)
1382 		return (retcode);
1383 
1384 	atomic_inc_32(&state->qinflight);
1385 
1386 	/*
1387 	 * Reap as many requests as we can _without_ waiting
1388 	 *
1389 	 * We do this to prevent any possible TCP socket buffer
1390 	 * starvation deadlocks.
1391 	 */
1392 	(void) memset(&tv, 0, sizeof (tv));
1393 	while (idmap_get_adobject_batch(state->qadh, &tv) == 0)
1394 		;
1395 
1396 	return (IDMAP_SUCCESS);
1397 }
1398 
1399 idmap_retcode
1400 idmap_name2sid_batch_add1(idmap_query_state_t *state,
1401 	const char *name, const char *dname,
1402 	char **sid, rid_t *rid, int *sid_type, idmap_retcode *rc)
1403 {
1404 	idmap_retcode	retcode;
1405 	int		flen, samAcctNameLen;
1406 	char		*filter = NULL;
1407 	char		*basedn = NULL;
1408 	char		*cp;
1409 
1410 	/*
1411 	 * Strategy: search [the global catalog] for user/group by
1412 	 * sAMAccountName = user/groupname with base DN derived from the
1413 	 * domain name.  The objectSid and objectClass of the result are
1414 	 * all we need to figure out the SID of the user/group and
1415 	 * whether it is a user or a group.
1416 	 */
1417 
1418 	/*
1419 	 * Handle optional domain parameter and default domain
1420 	 * semantics.  The get a basedn from the domainname.
1421 	 */
1422 	if (dname == NULL || *dname != '\0') {
1423 		/* domain name not given separately */
1424 		if ((cp = strchr(name, '@')) == NULL) {
1425 			/* nor is the name qualified */
1426 			dname = state->qadh->owner->dflt_w2k_dom;
1427 			basedn = state->qadh->owner->basedn;
1428 			samAcctNameLen = strlen(name);
1429 		} else {
1430 			/* the name is qualified */
1431 			/* LINTED */
1432 			samAcctNameLen = cp - name;
1433 			dname = cp + 1;
1434 		}
1435 	}
1436 
1437 	if (basedn == NULL)
1438 		basedn = dns2dn(dname);
1439 
1440 	/* Assemble filter */
1441 	flen = snprintf(NULL, 0, SANFILTER, samAcctNameLen, name) + 1;
1442 	if ((filter = (char *)malloc(flen)) == NULL) {
1443 		if (basedn != state->qadh->owner->basedn)
1444 			free(basedn);
1445 		return (IDMAP_ERR_MEMORY);
1446 	}
1447 	(void) snprintf(filter, flen, SANFILTER, samAcctNameLen, name);
1448 
1449 	retcode = idmap_batch_add1(state, 1, filter, basedn,
1450 	    sid, NULL, rid, sid_type, rc);
1451 
1452 	if (basedn != state->qadh->owner->basedn)
1453 		free(basedn);
1454 	free(filter);
1455 
1456 	return (retcode);
1457 }
1458 
1459 idmap_retcode
1460 idmap_sid2name_batch_add1(idmap_query_state_t *state,
1461 	const char *sid, const rid_t *rid,
1462 	char **name, char **dname, int *sid_type, idmap_retcode *rc)
1463 {
1464 	idmap_retcode	retcode;
1465 	int		flen, ret;
1466 	char		*filter = NULL;
1467 	char		cbinsid[MAXHEXBINSID + 1];
1468 
1469 	/*
1470 	 * Strategy: search [the global catalog] for user/group by
1471 	 * objectSid = SID with empty base DN.  The DN, sAMAccountName
1472 	 * and objectClass of the result are all we need to figure out
1473 	 * the name of the SID and whether it is a user, a group or a
1474 	 * computer.
1475 	 */
1476 
1477 	ret = idmap_txtsid2hexbinsid(sid, rid, &cbinsid[0], sizeof (cbinsid));
1478 	if (ret != 0)
1479 		return (IDMAP_ERR_SID);
1480 
1481 	/* Assemble filter */
1482 	flen = snprintf(NULL, 0, OBJECTSIDFILTER, cbinsid) + 1;
1483 	if ((filter = (char *)malloc(flen)) == NULL)
1484 		return (IDMAP_ERR_MEMORY);
1485 	(void) snprintf(filter, flen, OBJECTSIDFILTER, cbinsid);
1486 
1487 	retcode = idmap_batch_add1(state, 0, filter, NULL, name, dname,
1488 	    NULL, sid_type, rc);
1489 
1490 	free(filter);
1491 
1492 	return (retcode);
1493 }
1494