14520Snw141292 /*
24520Snw141292  * CDDL HEADER START
34520Snw141292  *
44520Snw141292  * The contents of this file are subject to the terms of the
54520Snw141292  * Common Development and Distribution License (the "License").
64520Snw141292  * You may not use this file except in compliance with the License.
74520Snw141292  *
84520Snw141292  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
94520Snw141292  * or http://www.opensolaris.org/os/licensing.
104520Snw141292  * See the License for the specific language governing permissions
114520Snw141292  * and limitations under the License.
124520Snw141292  *
134520Snw141292  * When distributing Covered Code, include this CDDL HEADER in each
144520Snw141292  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
154520Snw141292  * If applicable, add the following below this CDDL HEADER, with the
164520Snw141292  * fields enclosed by brackets "[]" replaced with your own identifying
174520Snw141292  * information: Portions Copyright [yyyy] [name of copyright owner]
184520Snw141292  *
194520Snw141292  * CDDL HEADER END
204520Snw141292  */
214520Snw141292 
224520Snw141292 /*
234520Snw141292  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
244520Snw141292  * Use is subject to license terms.
254520Snw141292  */
264520Snw141292 
274520Snw141292 #pragma ident	"%Z%%M%	%I%	%E% SMI"
284520Snw141292 
294520Snw141292 /*
304520Snw141292  * Processes name2sid & sid2name batched lookups for a given user or
314520Snw141292  * computer from an AD Directory server using GSSAPI authentication
324520Snw141292  */
334520Snw141292 
344520Snw141292 #include <stdio.h>
354520Snw141292 #include <stdlib.h>
364520Snw141292 #include <alloca.h>
374520Snw141292 #include <string.h>
384520Snw141292 #include <strings.h>
394520Snw141292 #include <lber.h>
404520Snw141292 #include <ldap.h>
414520Snw141292 #include <sasl/sasl.h>
424520Snw141292 #include <string.h>
434520Snw141292 #include <ctype.h>
444520Snw141292 #include <pthread.h>
454520Snw141292 #include <synch.h>
464520Snw141292 #include <atomic.h>
474520Snw141292 #include <errno.h>
484520Snw141292 #include <assert.h>
494520Snw141292 #include <limits.h>
504520Snw141292 #include "idmapd.h"
514520Snw141292 
524520Snw141292 /*
534520Snw141292  * Internal data structures for this code
544520Snw141292  */
554520Snw141292 
564520Snw141292 /* Attribute names and filter format strings */
57*5447Snw141292 #define	SAN		"sAMAccountName"
58*5447Snw141292 #define	OBJSID		"objectSid"
59*5447Snw141292 #define	OBJCLASS	"objectClass"
604520Snw141292 #define	SANFILTER	"(sAMAccountName=%.*s)"
61*5447Snw141292 #define	OBJSIDFILTER	"(objectSid=%s)"
624520Snw141292 
634520Snw141292 /*
644520Snw141292  * This should really be in some <sys/sid.h> file or so; we have a
654520Snw141292  * private version of sid_t, and so must other components of ON until we
664520Snw141292  * rationalize this.
674520Snw141292  */
684520Snw141292 typedef struct sid {
694520Snw141292 	uchar_t		version;
704520Snw141292 	uchar_t		sub_authority_count;
714520Snw141292 	uint64_t	authority;  /* really, 48-bits */
724520Snw141292 	rid_t		sub_authorities[SID_MAX_SUB_AUTHORITIES];
734520Snw141292 } sid_t;
744520Snw141292 
754520Snw141292 /* A single DS */
764520Snw141292 typedef struct ad_host {
774520Snw141292 	struct ad_host		*next;
784520Snw141292 	ad_t			*owner;		/* ad_t to which this belongs */
794520Snw141292 	pthread_mutex_t		lock;
804520Snw141292 	LDAP			*ld;		/* LDAP connection */
814520Snw141292 	uint32_t		ref;		/* ref count */
824520Snw141292 	time_t			idletime;	/* time since last activity */
834520Snw141292 	int			dead;		/* error on LDAP connection */
844520Snw141292 	/*
854520Snw141292 	 * Used to distinguish between different instances of LDAP
864520Snw141292 	 * connections to this same DS.  We need this so we never mix up
874520Snw141292 	 * results for a given msgID from one connection with those of
884520Snw141292 	 * another earlier connection where two batch state structures
894520Snw141292 	 * share this ad_host object but used different LDAP connections
904520Snw141292 	 * to send their LDAP searches.
914520Snw141292 	 */
924520Snw141292 	uint64_t		generation;
934520Snw141292 
944520Snw141292 	/* LDAP DS info */
954520Snw141292 	char			*host;
964520Snw141292 	int			port;
974520Snw141292 
984520Snw141292 	/* hardwired to SASL GSSAPI only for now */
994520Snw141292 	char			*saslmech;
1004520Snw141292 	unsigned		saslflags;
1014520Snw141292 } ad_host_t;
1024520Snw141292 
1034520Snw141292 /* A set of DSs for a given AD partition; ad_t typedef comes from  adutil.h */
1044520Snw141292 struct ad {
1054520Snw141292 	char			*dflt_w2k_dom;	/* used to qualify bare names */
1064520Snw141292 	pthread_mutex_t		lock;
1074520Snw141292 	uint32_t		ref;
1085317Sjp151216 	ad_host_t		*last_adh;
1094520Snw141292 	idmap_ad_partition_t	partition;	/* Data or global catalog? */
1104520Snw141292 };
1114520Snw141292 
1124520Snw141292 /*
1134520Snw141292  * A place to put the results of a batched (async) query
1144520Snw141292  *
1154520Snw141292  * There is one of these for every query added to a batch object
1164520Snw141292  * (idmap_query_state, see below).
1174520Snw141292  */
1184520Snw141292 typedef struct idmap_q {
119*5447Snw141292 	/*
120*5447Snw141292 	 * data used for validating search result entries for name->SID
121*5447Snw141292 	 * loopups
122*5447Snw141292 	 */
123*5447Snw141292 	char			*n2s_cname;	/* expected canon name@domain */
124*5447Snw141292 	/* results */
1254520Snw141292 	char			**result;	/* name or stringified SID */
1264520Snw141292 	char			**domain;	/* name of domain of object */
1274520Snw141292 	rid_t			*rid;		/* for n2s, if not NULL */
1284520Snw141292 	int			*sid_type;	/* if not NULL */
1294520Snw141292 	idmap_retcode		*rc;
130*5447Snw141292 
131*5447Snw141292 	/* lookup state */
1324520Snw141292 	int			msgid;		/* LDAP message ID */
1334520Snw141292 } idmap_q_t;
1344520Snw141292 
1354520Snw141292 /* Batch context structure; typedef is in header file */
1364520Snw141292 struct idmap_query_state {
1374520Snw141292 	idmap_query_state_t	*next;
1384520Snw141292 	int			qcount;		/* how many queries */
1394884Sjp151216 	int			ref_cnt;	/* reference count */
1404884Sjp151216 	pthread_cond_t		cv;		/* Condition wait variable */
1414520Snw141292 	uint32_t		qlastsent;
1424520Snw141292 	uint32_t		qinflight;	/* how many queries in flight */
1434520Snw141292 	uint16_t		qdead;		/* oops, lost LDAP connection */
1444520Snw141292 	ad_host_t		*qadh;		/* LDAP connection */
1454520Snw141292 	uint64_t		qadh_gen;	/* same as qadh->generation */
1464520Snw141292 	idmap_q_t		queries[1];	/* array of query results */
1474520Snw141292 };
1484520Snw141292 
1494520Snw141292 /*
1504520Snw141292  * List of query state structs -- needed so we can "route" LDAP results
1514520Snw141292  * to the right context if multiple threads should be using the same
1524520Snw141292  * connection concurrently
1534520Snw141292  */
1544520Snw141292 static idmap_query_state_t	*qstatehead = NULL;
1554520Snw141292 static pthread_mutex_t		qstatelock = PTHREAD_MUTEX_INITIALIZER;
1564520Snw141292 
1574520Snw141292 /*
1584520Snw141292  * List of DSs, needed by the idle connection reaper thread
1594520Snw141292  */
1604520Snw141292 static ad_host_t	*host_head = NULL;
1614644Sbaban static pthread_t	reaperid = 0;
1624520Snw141292 static pthread_mutex_t	adhostlock = PTHREAD_MUTEX_INITIALIZER;
1634520Snw141292 
1644884Sjp151216 
1654884Sjp151216 static void
1664884Sjp151216 idmap_lookup_unlock_batch(idmap_query_state_t **state);
1674884Sjp151216 
1685317Sjp151216 static void
1695317Sjp151216 delete_ds(ad_t *ad, const char *host, int port);
1704884Sjp151216 
1714520Snw141292 /*ARGSUSED*/
1724520Snw141292 static int
1734520Snw141292 idmap_saslcallback(LDAP *ld, unsigned flags, void *defaults, void *prompts) {
1744520Snw141292 	sasl_interact_t	*interact;
1754520Snw141292 
1764520Snw141292 	if (prompts == NULL || flags != LDAP_SASL_INTERACTIVE)
1774520Snw141292 		return (LDAP_PARAM_ERROR);
1784520Snw141292 
1794520Snw141292 	/* There should be no extra arguemnts for SASL/GSSAPI authentication */
1804520Snw141292 	for (interact = prompts; interact->id != SASL_CB_LIST_END;
1814520Snw141292 			interact++) {
1824520Snw141292 		interact->result = NULL;
1834520Snw141292 		interact->len = 0;
1844520Snw141292 	}
1854520Snw141292 	return (LDAP_SUCCESS);
1864520Snw141292 }
1874520Snw141292 
1884520Snw141292 
1894520Snw141292 /*
1904520Snw141292  * Turn "dc=foo,dc=bar,dc=com" into "foo.bar.com"; ignores any other
191*5447Snw141292  * attributes (CN, etc...).  We don't need the reverse, for now.
1924520Snw141292  */
1934520Snw141292 static
1944520Snw141292 char *
1954520Snw141292 dn2dns(const char *dn)
1964520Snw141292 {
1974520Snw141292 	char **rdns = NULL;
1984520Snw141292 	char **attrs = NULL;
1994520Snw141292 	char **labels = NULL;
2004520Snw141292 	char *dns = NULL;
2014520Snw141292 	char **rdn, **attr, **label;
2024520Snw141292 	int maxlabels = 5;
2034520Snw141292 	int nlabels = 0;
2044520Snw141292 	int dnslen;
2054520Snw141292 
2064520Snw141292 	/*
2074520Snw141292 	 * There is no reverse of ldap_dns_to_dn() in our libldap, so we
2084520Snw141292 	 * have to do the hard work here for now.
2094520Snw141292 	 */
2104520Snw141292 
2114520Snw141292 	/*
2124520Snw141292 	 * This code is much too liberal: it looks for "dc" attributes
2134520Snw141292 	 * in all RDNs of the DN.  In theory this could cause problems
2144520Snw141292 	 * if people were to use "dc" in nodes other than the root of
2154520Snw141292 	 * the tree, but in practice noone, least of all Active
2164520Snw141292 	 * Directory, does that.
2174520Snw141292 	 *
2184520Snw141292 	 * On the other hand, this code is much too conservative: it
2194520Snw141292 	 * does not make assumptions about ldap_explode_dn(), and _that_
2204520Snw141292 	 * is the true for looking at every attr of every RDN.
2214520Snw141292 	 *
2224520Snw141292 	 * Since we only ever look at dc and those must be DNS labels,
2234520Snw141292 	 * at least until we get around to supporting IDN here we
2244520Snw141292 	 * shouldn't see escaped labels from AD nor from libldap, though
2254520Snw141292 	 * the spec (RFC2253) does allow libldap to escape things that
2264520Snw141292 	 * don't need escaping -- if that should ever happen then
2274520Snw141292 	 * libldap will need a spanking, and we can take care of that.
2284520Snw141292 	 */
2294520Snw141292 
2304520Snw141292 	/* Explode a DN into RDNs */
2314520Snw141292 	if ((rdns = ldap_explode_dn(dn, 0)) == NULL)
2324520Snw141292 		return (NULL);
2334520Snw141292 
2344520Snw141292 	labels = calloc(maxlabels + 1, sizeof (char *));
2354520Snw141292 	label = labels;
2364520Snw141292 
2374520Snw141292 	for (rdn = rdns; *rdn != NULL; rdn++) {
2384520Snw141292 		if (attrs != NULL)
2394520Snw141292 			ldap_value_free(attrs);
2404520Snw141292 
2414520Snw141292 		/* Explode each RDN, look for DC attr, save val as DNS label */
2424520Snw141292 		if ((attrs = ldap_explode_rdn(rdn[0], 0)) == NULL)
2434520Snw141292 			goto done;
2444520Snw141292 
2454520Snw141292 		for (attr = attrs; *attr != NULL; attr++) {
2464520Snw141292 			if (strncasecmp(*attr, "dc=", 3) != 0)
2474520Snw141292 				continue;
2484520Snw141292 
2494520Snw141292 			/* Found a DNS label */
2504520Snw141292 			labels[nlabels++] = strdup((*attr) + 3);
2514520Snw141292 
2524520Snw141292 			if (nlabels == maxlabels) {
2534520Snw141292 				char **tmp;
2544520Snw141292 				tmp = realloc(labels,
2554520Snw141292 				    sizeof (char *) * (maxlabels + 1));
2564520Snw141292 
2574520Snw141292 				if (tmp == NULL)
2584520Snw141292 					goto done;
2594520Snw141292 
2604520Snw141292 				labels = tmp;
2614520Snw141292 				labels[nlabels] = NULL;
2624520Snw141292 			}
2634520Snw141292 
2644520Snw141292 			/* There should be just one DC= attr per-RDN */
2654520Snw141292 			break;
2664520Snw141292 		}
2674520Snw141292 	}
2684520Snw141292 
2694520Snw141292 	/*
2704520Snw141292 	 * Got all the labels, now join with '.'
2714520Snw141292 	 *
2724520Snw141292 	 * We need room for nlabels - 1 periods ('.'), one nul
2734520Snw141292 	 * terminator, and the strlen() of each label.
2744520Snw141292 	 */
2754520Snw141292 	dnslen = nlabels;
2764520Snw141292 	for (label = labels; *label != NULL; label++)
2774520Snw141292 		dnslen += strlen(*label);
2784520Snw141292 
2794520Snw141292 	if ((dns = malloc(dnslen)) == NULL)
2804520Snw141292 		goto done;
2814520Snw141292 
2824520Snw141292 	*dns = '\0';
2834520Snw141292 
2844520Snw141292 	for (label = labels; *label != NULL; label++) {
2854520Snw141292 		(void) strlcat(dns, *label, dnslen);
2864520Snw141292 		/*
2874520Snw141292 		 * NOTE: the last '.' won't be appended -- there's no room
2884520Snw141292 		 * for it!
2894520Snw141292 		 */
2904520Snw141292 		(void) strlcat(dns, ".", dnslen);
2914520Snw141292 	}
2924520Snw141292 
2934520Snw141292 done:
2944520Snw141292 	if (labels != NULL) {
2954520Snw141292 		for (label = labels; *label != NULL; label++)
2964520Snw141292 			free(*label);
2974520Snw141292 		free(labels);
2984520Snw141292 	}
2994520Snw141292 	if (attrs != NULL)
3004520Snw141292 		ldap_value_free(attrs);
3014520Snw141292 	if (rdns != NULL)
3024520Snw141292 		ldap_value_free(rdns);
3034520Snw141292 
3044520Snw141292 	return (dns);
3054520Snw141292 }
3064520Snw141292 
3074520Snw141292 /*
308*5447Snw141292  * Check whether a given object's DN matches the given domain name.
309*5447Snw141292  *
310*5447Snw141292  * Used for validating search result entries for name->SID lookups.
311*5447Snw141292  */
312*5447Snw141292 static
313*5447Snw141292 int
314*5447Snw141292 dn_matches(const char *dn, const char *dname)
315*5447Snw141292 {
316*5447Snw141292 	char *dn_dname;
317*5447Snw141292 	int match = 0;
318*5447Snw141292 
319*5447Snw141292 	dn_dname = dn2dns(dn);
320*5447Snw141292 
321*5447Snw141292 	match = (strcmp(dn_dname, dname) == 0) ? 1 : 0;
322*5447Snw141292 
323*5447Snw141292 	free(dn_dname);
324*5447Snw141292 	return (match);
325*5447Snw141292 }
326*5447Snw141292 
327*5447Snw141292 /*
3284520Snw141292  * Keep connection management simple for now, extend or replace later
3294520Snw141292  * with updated libsldap code.
3304520Snw141292  */
3314520Snw141292 #define	ADREAPERSLEEP	60
3324520Snw141292 #define	ADCONN_TIME	300
3334520Snw141292 
3344520Snw141292 /*
3354520Snw141292  * Idle connection reaping side of connection management
3364520Snw141292  *
3374520Snw141292  * Every minute wake up and look for connections that have been idle for
3384520Snw141292  * five minutes or more and close them.
3394520Snw141292  */
3404520Snw141292 /*ARGSUSED*/
3414520Snw141292 static
3424520Snw141292 void
3434520Snw141292 adreaper(void *arg)
3444520Snw141292 {
3454520Snw141292 	ad_host_t	*adh;
3464520Snw141292 	time_t		now;
3474520Snw141292 	timespec_t	ts;
3484520Snw141292 
3494520Snw141292 	ts.tv_sec = ADREAPERSLEEP;
3504520Snw141292 	ts.tv_nsec = 0;
3514520Snw141292 
3524520Snw141292 	for (;;) {
3534520Snw141292 		/*
3544520Snw141292 		 * nanosleep(3RT) is thead-safe (no SIGALRM) and more
3554520Snw141292 		 * portable than usleep(3C)
3564520Snw141292 		 */
3574520Snw141292 		(void) nanosleep(&ts, NULL);
3584520Snw141292 		(void) pthread_mutex_lock(&adhostlock);
3594520Snw141292 		now = time(NULL);
3604520Snw141292 		for (adh = host_head; adh != NULL; adh = adh->next) {
3614520Snw141292 			(void) pthread_mutex_lock(&adh->lock);
3624520Snw141292 			if (adh->ref == 0 && adh->idletime != 0 &&
3634520Snw141292 			    adh->idletime + ADCONN_TIME < now) {
3644520Snw141292 				if (adh->ld) {
3654520Snw141292 					(void) ldap_unbind(adh->ld);
3664520Snw141292 					adh->ld = NULL;
3674520Snw141292 					adh->idletime = 0;
3684520Snw141292 					adh->ref = 0;
3694520Snw141292 				}
3704520Snw141292 			}
3714520Snw141292 			(void) pthread_mutex_unlock(&adh->lock);
3724520Snw141292 		}
3734520Snw141292 		(void) pthread_mutex_unlock(&adhostlock);
3744520Snw141292 	}
3754520Snw141292 }
3764520Snw141292 
3774520Snw141292 int
3784520Snw141292 idmap_ad_alloc(ad_t **new_ad, const char *default_domain,
3794520Snw141292 		idmap_ad_partition_t part)
3804520Snw141292 {
3814520Snw141292 	ad_t *ad;
3824520Snw141292 
3834520Snw141292 	*new_ad = NULL;
3844520Snw141292 
3854520Snw141292 	if ((default_domain == NULL || *default_domain == '\0') &&
3864520Snw141292 	    part != IDMAP_AD_GLOBAL_CATALOG)
3874520Snw141292 		return (-1);
3884520Snw141292 
3894520Snw141292 	if ((ad = calloc(1, sizeof (ad_t))) == NULL)
3904520Snw141292 		return (-1);
3914520Snw141292 
3924520Snw141292 	ad->ref = 1;
3934520Snw141292 	ad->partition = part;
3944520Snw141292 
3954520Snw141292 	/*
3964520Snw141292 	 * If default_domain is NULL, deal, deferring errors until
3974520Snw141292 	 * idmap_lookup_batch_start() -- this makes it easier on the
3984520Snw141292 	 * caller, who can simply observe lookups failing as opposed to
3994520Snw141292 	 * having to conditionalize calls to lookups according to
4004520Snw141292 	 * whether it has a non-NULL ad_t *.
4014520Snw141292 	 */
4024520Snw141292 	if (default_domain == NULL)
4034520Snw141292 		default_domain = "";
4044520Snw141292 
4054520Snw141292 	if ((ad->dflt_w2k_dom = strdup(default_domain)) == NULL)
4064520Snw141292 		goto err;
4074520Snw141292 
4084520Snw141292 	if (pthread_mutex_init(&ad->lock, NULL) != 0)
4094520Snw141292 		goto err;
4104520Snw141292 
4114520Snw141292 	*new_ad = ad;
4124520Snw141292 
4134520Snw141292 	return (0);
4144520Snw141292 err:
4154520Snw141292 	if (ad->dflt_w2k_dom != NULL)
4164520Snw141292 		free(ad->dflt_w2k_dom);
4174520Snw141292 	free(ad);
4184520Snw141292 	return (-1);
4194520Snw141292 }
4204520Snw141292 
4214520Snw141292 
4224520Snw141292 void
4234520Snw141292 idmap_ad_free(ad_t **ad)
4244520Snw141292 {
4254520Snw141292 	ad_host_t *p;
4265317Sjp151216 	ad_host_t *prev;
4274520Snw141292 
4284520Snw141292 	if (ad == NULL || *ad == NULL)
4294520Snw141292 		return;
4304520Snw141292 
4314520Snw141292 	(void) pthread_mutex_lock(&(*ad)->lock);
4324520Snw141292 
4334520Snw141292 	if (atomic_dec_32_nv(&(*ad)->ref) > 0) {
4344520Snw141292 		(void) pthread_mutex_unlock(&(*ad)->lock);
4354520Snw141292 		*ad = NULL;
4364520Snw141292 		return;
4374520Snw141292 	}
4384520Snw141292 
4395317Sjp151216 	(void) pthread_mutex_lock(&adhostlock);
4405317Sjp151216 	prev = NULL;
4415317Sjp151216 	p = host_head;
4425317Sjp151216 	while (p != NULL) {
4435317Sjp151216 		if (p->owner != (*ad)) {
4445317Sjp151216 			prev = p;
4455317Sjp151216 			p = p->next;
4464520Snw141292 			continue;
4475317Sjp151216 		} else {
4485317Sjp151216 			delete_ds((*ad), p->host, p->port);
4495317Sjp151216 			if (prev == NULL)
4505317Sjp151216 				p = host_head;
4515317Sjp151216 			else
4525317Sjp151216 				p = prev->next;
4535317Sjp151216 		}
4544520Snw141292 	}
4555317Sjp151216 	(void) pthread_mutex_unlock(&adhostlock);
4564520Snw141292 
4574520Snw141292 	(void) pthread_mutex_unlock(&(*ad)->lock);
4584520Snw141292 	(void) pthread_mutex_destroy(&(*ad)->lock);
4594520Snw141292 
460*5447Snw141292 	free((*ad)->dflt_w2k_dom);
4614520Snw141292 	free(*ad);
4624520Snw141292 
4634520Snw141292 	*ad = NULL;
4644520Snw141292 }
4654520Snw141292 
4665317Sjp151216 
4674520Snw141292 static
4684520Snw141292 int
4694520Snw141292 idmap_open_conn(ad_host_t *adh)
4704520Snw141292 {
4715317Sjp151216 	int zero = 0;
4725317Sjp151216 	int timeoutms = 30 * 1000;
4735317Sjp151216 	int ldversion, rc;
4745317Sjp151216 
4755317Sjp151216 	if (adh == NULL)
4765317Sjp151216 		return (0);
4774520Snw141292 
4785317Sjp151216 	(void) pthread_mutex_lock(&adh->lock);
4795317Sjp151216 
4805317Sjp151216 	if (!adh->dead && adh->ld != NULL)
4815317Sjp151216 		/* done! */
4825317Sjp151216 		goto out;
4835317Sjp151216 
4845317Sjp151216 	if (adh->ld != NULL) {
4854520Snw141292 		(void) ldap_unbind(adh->ld);
4864520Snw141292 		adh->ld = NULL;
4874520Snw141292 	}
4884520Snw141292 
4895317Sjp151216 	atomic_inc_64(&adh->generation);
4904520Snw141292 
4915317Sjp151216 	/* Open and bind an LDAP connection */
4925317Sjp151216 	adh->ld = ldap_init(adh->host, adh->port);
4935317Sjp151216 	if (adh->ld == NULL) {
4945317Sjp151216 		idmapdlog(LOG_INFO, "ldap_init() to server "
4955317Sjp151216 		    "%s port %d failed. (%s)", adh->host,
4965317Sjp151216 		    adh->port, strerror(errno));
4975317Sjp151216 		goto out;
4985317Sjp151216 	}
4995317Sjp151216 	ldversion = LDAP_VERSION3;
5005317Sjp151216 	(void) ldap_set_option(adh->ld, LDAP_OPT_PROTOCOL_VERSION, &ldversion);
5015317Sjp151216 	(void) ldap_set_option(adh->ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF);
5025317Sjp151216 	(void) ldap_set_option(adh->ld, LDAP_OPT_TIMELIMIT, &zero);
5035317Sjp151216 	(void) ldap_set_option(adh->ld, LDAP_OPT_SIZELIMIT, &zero);
5045317Sjp151216 	(void) ldap_set_option(adh->ld, LDAP_X_OPT_CONNECT_TIMEOUT, &timeoutms);
5055317Sjp151216 	(void) ldap_set_option(adh->ld, LDAP_OPT_RESTART, LDAP_OPT_ON);
5065317Sjp151216 	rc = ldap_sasl_interactive_bind_s(adh->ld, "" /* binddn */,
5075317Sjp151216 	    adh->saslmech, NULL, NULL, adh->saslflags, &idmap_saslcallback,
5085317Sjp151216 	    NULL);
5094520Snw141292 
5105317Sjp151216 	if (rc != LDAP_SUCCESS) {
5115317Sjp151216 		(void) ldap_unbind(adh->ld);
5125317Sjp151216 		adh->ld = NULL;
5135317Sjp151216 		idmapdlog(LOG_INFO, "ldap_sasl_interactive_bind_s() to server "
5145317Sjp151216 		    "%s port %d failed. (%s)", adh->host, adh->port,
5155317Sjp151216 		    ldap_err2string(rc));
5164520Snw141292 	}
5174520Snw141292 
5185317Sjp151216 	idmapdlog(LOG_DEBUG, "Using global catalog server %s:%d",
5195317Sjp151216 	    adh->host, adh->port);
5204520Snw141292 
5215317Sjp151216 out:
5225317Sjp151216 	if (adh->ld != NULL) {
5235317Sjp151216 		atomic_inc_32(&adh->ref);
5245317Sjp151216 		adh->idletime = time(NULL);
5255317Sjp151216 		adh->dead = 0;
5265317Sjp151216 		(void) pthread_mutex_unlock(&adh->lock);
5275317Sjp151216 		return (1);
5285317Sjp151216 	}
5295317Sjp151216 
5305317Sjp151216 	(void) pthread_mutex_unlock(&adh->lock);
5315317Sjp151216 	return (0);
5324520Snw141292 }
5334520Snw141292 
5344520Snw141292 
5354520Snw141292 /*
5364520Snw141292  * Connection management: find an open connection or open one
5374520Snw141292  */
5384520Snw141292 static
5394520Snw141292 ad_host_t *
5405317Sjp151216 idmap_get_conn(ad_t *ad)
5414520Snw141292 {
5424520Snw141292 	ad_host_t	*adh = NULL;
5435317Sjp151216 	ad_host_t	*first_adh, *next_adh;
5445317Sjp151216 	int		seen_last;
5455317Sjp151216 	int		tries = -1;
5464520Snw141292 
5475317Sjp151216 retry:
5484520Snw141292 	(void) pthread_mutex_lock(&adhostlock);
5494520Snw141292 
5505317Sjp151216 	if (host_head == NULL)
5515317Sjp151216 		goto out;
5525317Sjp151216 
5535317Sjp151216 	/* Try as many DSs as we have, once each; count them once */
5545317Sjp151216 	if (tries < 0) {
5555317Sjp151216 		for (adh = host_head, tries = 0; adh != NULL; adh = adh->next)
5565317Sjp151216 			tries++;
5574520Snw141292 	}
5584520Snw141292 
5595317Sjp151216 	/*
5605317Sjp151216 	 * Find a suitable ad_host_t (one associated with this ad_t,
5615317Sjp151216 	 * preferably one that's already connected and not dead),
5625317Sjp151216 	 * possibly round-robining through the ad_host_t list.
5635317Sjp151216 	 *
5645317Sjp151216 	 * If we can't find a non-dead ad_host_t and we've had one
5655317Sjp151216 	 * before (ad->last_adh != NULL) then pick the next one or, if
5665317Sjp151216 	 * there is no next one, the first one (i.e., round-robin).
5675317Sjp151216 	 *
5685317Sjp151216 	 * If we've never had one then (ad->last_adh == NULL) then pick
5695317Sjp151216 	 * the first one.
5705317Sjp151216 	 *
5715317Sjp151216 	 * If we ever want to be more clever, such as preferring DSes
5725317Sjp151216 	 * with better average response times, adjusting for weights
5735317Sjp151216 	 * from SRV RRs, and so on, then this is the place to do it.
5745317Sjp151216 	 */
5755317Sjp151216 
5765317Sjp151216 	for (adh = host_head, first_adh = NULL, next_adh = NULL, seen_last = 0;
5775317Sjp151216 	    adh != NULL; adh = adh->next) {
5785317Sjp151216 		if (adh->owner != ad)
5795317Sjp151216 			continue;
5805317Sjp151216 		if (first_adh == NULL)
5815317Sjp151216 			first_adh = adh;
5825317Sjp151216 		if (adh == ad->last_adh)
5835317Sjp151216 			seen_last++;
5845317Sjp151216 		else if (seen_last)
5855317Sjp151216 			next_adh = adh;
5865317Sjp151216 
5875317Sjp151216 		/* First time or current adh is live -> done */
5885317Sjp151216 		if (ad->last_adh == NULL || (!adh->dead && adh->ld != NULL))
5895317Sjp151216 			break;
5905317Sjp151216 	}
5915317Sjp151216 
5925317Sjp151216 	/* Round-robin */
5935317Sjp151216 	if (adh == NULL)
5945317Sjp151216 		adh = (next_adh != NULL) ? next_adh : first_adh;
5955317Sjp151216 
5964520Snw141292 	if (adh != NULL)
5975317Sjp151216 		ad->last_adh = adh;
5984520Snw141292 
5995317Sjp151216 out:
6004520Snw141292 	(void) pthread_mutex_unlock(&adhostlock);
6014520Snw141292 
6025317Sjp151216 	/* Found suitable DS, open it if not already opened */
6035317Sjp151216 	if (idmap_open_conn(adh))
6045317Sjp151216 		return (adh);
6054520Snw141292 
6065317Sjp151216 	if (tries-- > 0)
6075317Sjp151216 		goto retry;
6084520Snw141292 
6095317Sjp151216 	idmapdlog(LOG_ERR, "Couldn't open an LDAP connection to any global "
6105317Sjp151216 	    "catalog server!");
6115317Sjp151216 
6125317Sjp151216 	return (NULL);
6134520Snw141292 }
6144520Snw141292 
6154520Snw141292 static
6164520Snw141292 void
6174520Snw141292 idmap_release_conn(ad_host_t *adh)
6184520Snw141292 {
6194520Snw141292 	(void) pthread_mutex_lock(&adh->lock);
6204520Snw141292 	if (atomic_dec_32_nv(&adh->ref) == 0)
6214520Snw141292 		adh->idletime = time(NULL);
6224520Snw141292 	(void) pthread_mutex_unlock(&adh->lock);
6234520Snw141292 }
6244520Snw141292 
6254520Snw141292 /*
6264520Snw141292  * Take ad_host_config_t information, create a ad_host_t,
6274520Snw141292  * populate it and add it to the list of hosts.
6284520Snw141292  */
6294520Snw141292 
6304520Snw141292 int
6314520Snw141292 idmap_add_ds(ad_t *ad, const char *host, int port)
6324520Snw141292 {
6334520Snw141292 	ad_host_t	*p;
6344520Snw141292 	ad_host_t	*new = NULL;
6354520Snw141292 	int		ret = -1;
6364520Snw141292 
6374520Snw141292 	if (port == 0)
6384520Snw141292 		port = (int)ad->partition;
6394520Snw141292 
6404520Snw141292 	(void) pthread_mutex_lock(&adhostlock);
6414520Snw141292 	for (p = host_head; p != NULL; p = p->next) {
6424520Snw141292 		if (p->owner != ad)
6434520Snw141292 			continue;
6444520Snw141292 
6454520Snw141292 		if (strcmp(host, p->host) == 0 && p->port == port) {
6464520Snw141292 			/* already added */
6475317Sjp151216 			ret = 0;
6484520Snw141292 			goto err;
6494520Snw141292 		}
6504520Snw141292 	}
6514520Snw141292 
6524520Snw141292 	/* add new entry */
6534520Snw141292 	new = (ad_host_t *)calloc(1, sizeof (ad_host_t));
6544520Snw141292 	if (new == NULL)
6554520Snw141292 		goto err;
6564520Snw141292 	new->owner = ad;
6574520Snw141292 	new->port = port;
6584520Snw141292 	new->dead = 0;
6594520Snw141292 	if ((new->host = strdup(host)) == NULL)
6604520Snw141292 		goto err;
6614520Snw141292 
6624520Snw141292 	/* default to SASL GSSAPI only for now */
6634520Snw141292 	new->saslflags = LDAP_SASL_INTERACTIVE;
6644520Snw141292 	new->saslmech = "GSSAPI";
6654520Snw141292 
6664520Snw141292 	if ((ret = pthread_mutex_init(&new->lock, NULL)) != 0) {
6674520Snw141292 		free(new->host);
6684520Snw141292 		new->host = NULL;
6694520Snw141292 		errno = ret;
6704520Snw141292 		ret = -1;
6714520Snw141292 		goto err;
6724520Snw141292 	}
6734520Snw141292 
6744520Snw141292 	/* link in */
6754520Snw141292 	new->next = host_head;
6764520Snw141292 	host_head = new;
6774520Snw141292 
6784520Snw141292 	/* Start reaper if it doesn't exist */
6794520Snw141292 	if (reaperid == 0)
6804520Snw141292 		(void) pthread_create(&reaperid, NULL,
6814520Snw141292 		    (void *(*)(void *))adreaper, (void *)NULL);
6824520Snw141292 
6834520Snw141292 err:
6844520Snw141292 	(void) pthread_mutex_unlock(&adhostlock);
6854520Snw141292 
6864520Snw141292 	if (ret != 0 && new != NULL) {
6874520Snw141292 		if (new->host != NULL) {
6884520Snw141292 			(void) pthread_mutex_destroy(&new->lock);
6894520Snw141292 			free(new->host);
6904520Snw141292 		}
6914520Snw141292 		free(new);
6924520Snw141292 	}
6934520Snw141292 
6944520Snw141292 	return (ret);
6954520Snw141292 }
6964520Snw141292 
6974520Snw141292 /*
6985317Sjp151216  * Free a DS configuration.
6995317Sjp151216  * Caller must lock the adhostlock mutex
7004520Snw141292  */
7015317Sjp151216 static void
7025317Sjp151216 delete_ds(ad_t *ad, const char *host, int port)
7034520Snw141292 {
7044520Snw141292 	ad_host_t	**p, *q;
7054520Snw141292 
7064520Snw141292 	for (p = &host_head; *p != NULL; p = &((*p)->next)) {
7074520Snw141292 		if ((*p)->owner != ad || strcmp(host, (*p)->host) != 0 ||
7084520Snw141292 		    (*p)->port != port)
7094520Snw141292 			continue;
7104520Snw141292 		/* found */
7115317Sjp151216 		if ((*p)->ref > 0)
7124520Snw141292 			break;	/* still in use */
7134520Snw141292 
7144520Snw141292 		q = *p;
7154520Snw141292 		*p = (*p)->next;
7164520Snw141292 
7174520Snw141292 		(void) pthread_mutex_destroy(&q->lock);
7184520Snw141292 
7194520Snw141292 		if (q->ld)
7204520Snw141292 			(void) ldap_unbind(q->ld);
7214520Snw141292 		if (q->host)
7224520Snw141292 			free(q->host);
7234520Snw141292 		free(q);
7244520Snw141292 		break;
7254520Snw141292 	}
7265317Sjp151216 
7274520Snw141292 }
7284520Snw141292 
7295317Sjp151216 
7304520Snw141292 /*
7314520Snw141292  * Convert a binary SID in a BerValue to a sid_t
7324520Snw141292  */
7334520Snw141292 static
7344520Snw141292 int
7354520Snw141292 idmap_getsid(BerValue *bval, sid_t *sidp)
7364520Snw141292 {
7374520Snw141292 	int		i, j;
7384520Snw141292 	uchar_t		*v;
7394520Snw141292 	uint32_t	a;
7404520Snw141292 
7414520Snw141292 	/*
7424520Snw141292 	 * The binary format of a SID is as follows:
7434520Snw141292 	 *
7444520Snw141292 	 * byte #0: version, always 0x01
7454520Snw141292 	 * byte #1: RID count, always <= 0x0f
7464520Snw141292 	 * bytes #2-#7: SID authority, big-endian 48-bit unsigned int
7474520Snw141292 	 *
7484520Snw141292 	 * followed by RID count RIDs, each a little-endian, unsigned
7494520Snw141292 	 * 32-bit int.
7504520Snw141292 	 */
7514520Snw141292 	/*
7524520Snw141292 	 * Sanity checks: must have at least one RID, version must be
7534520Snw141292 	 * 0x01, and the length must be 8 + rid count * 4
7544520Snw141292 	 */
7554520Snw141292 	if (bval->bv_len > 8 && bval->bv_val[0] == 0x01 &&
7564520Snw141292 	    bval->bv_len == 1 + 1 + 6 + bval->bv_val[1] * 4) {
7574520Snw141292 		v = (uchar_t *)bval->bv_val;
7584520Snw141292 		sidp->version = v[0];
7594520Snw141292 		sidp->sub_authority_count = v[1];
7604520Snw141292 		sidp->authority =
7614520Snw141292 		    /* big endian -- so start from the left */
7624520Snw141292 		    ((u_longlong_t)v[2] << 40) |
7634520Snw141292 		    ((u_longlong_t)v[3] << 32) |
7644520Snw141292 		    ((u_longlong_t)v[4] << 24) |
7654520Snw141292 		    ((u_longlong_t)v[5] << 16) |
7664520Snw141292 		    ((u_longlong_t)v[6] << 8) |
7674520Snw141292 		    (u_longlong_t)v[7];
7684520Snw141292 		for (i = 0; i < sidp->sub_authority_count; i++) {
7694520Snw141292 			j = 8 + (i * 4);
7704520Snw141292 			/* little endian -- so start from the right */
7714520Snw141292 			a = (v[j + 3] << 24) | (v[j + 2] << 16) |
7724520Snw141292 			    (v[j + 1] << 8) | (v[j]);
7734520Snw141292 			sidp->sub_authorities[i] = a;
7744520Snw141292 		}
7754520Snw141292 		return (0);
7764520Snw141292 	}
7774520Snw141292 	return (-1);
7784520Snw141292 }
7794520Snw141292 
7804520Snw141292 /*
7814520Snw141292  * Convert a sid_t to S-1-...
7824520Snw141292  */
7834520Snw141292 static
7844520Snw141292 char *
7854520Snw141292 idmap_sid2txt(sid_t *sidp)
7864520Snw141292 {
7874520Snw141292 	int	rlen, i, len;
7884520Snw141292 	char	*str, *cp;
7894520Snw141292 
7904520Snw141292 	if (sidp->version != 1)
7914520Snw141292 		return (NULL);
7924520Snw141292 
7934520Snw141292 	len = sizeof ("S-1-") - 1;
7944520Snw141292 
7954520Snw141292 	/*
7964520Snw141292 	 * We could optimize like so, but, why?
7974520Snw141292 	 *	if (sidp->authority < 10)
7984520Snw141292 	 *		len += 2;
7994520Snw141292 	 *	else if (sidp->authority < 100)
8004520Snw141292 	 *		len += 3;
8014520Snw141292 	 *	else
8024520Snw141292 	 *		len += snprintf(NULL, 0"%llu", sidp->authority);
8034520Snw141292 	 */
8044520Snw141292 	len += snprintf(NULL, 0, "%llu", sidp->authority);
8054520Snw141292 
8064520Snw141292 	/* Max length of a uint32_t printed out in ASCII is 10 bytes */
8074520Snw141292 	len += 1 + (sidp->sub_authority_count + 1) * 10;
8084520Snw141292 
8094520Snw141292 	if ((cp = str = malloc(len)) == NULL)
8104520Snw141292 		return (NULL);
8114520Snw141292 
8124520Snw141292 	rlen = snprintf(str, len, "S-1-%llu", sidp->authority);
8134520Snw141292 
8144520Snw141292 	cp += rlen;
8154520Snw141292 	len -= rlen;
8164520Snw141292 
8174520Snw141292 	for (i = 0; i < sidp->sub_authority_count; i++) {
8184520Snw141292 		assert(len > 0);
8194520Snw141292 		rlen = snprintf(cp, len, "-%u", sidp->sub_authorities[i]);
8204520Snw141292 		cp += rlen;
8214520Snw141292 		len -= rlen;
8224520Snw141292 		assert(len >= 0);
8234520Snw141292 	}
8244520Snw141292 
8254520Snw141292 	return (str);
8264520Snw141292 }
8274520Snw141292 
8284520Snw141292 /*
8294520Snw141292  * Convert a sid_t to on-the-wire encoding
8304520Snw141292  */
8314520Snw141292 static
8324520Snw141292 int
8334520Snw141292 idmap_sid2binsid(sid_t *sid, uchar_t *binsid, int binsidlen)
8344520Snw141292 {
8354520Snw141292 	uchar_t		*p;
8364520Snw141292 	int		i;
8374520Snw141292 	uint64_t	a;
8384520Snw141292 	uint32_t	r;
8394520Snw141292 
8404520Snw141292 	if (sid->version != 1 ||
8414520Snw141292 	    binsidlen != (1 + 1 + 6 + sid->sub_authority_count * 4))
8424520Snw141292 		return (-1);
8434520Snw141292 
8444520Snw141292 	p = binsid;
8454520Snw141292 	*p++ = 0x01;		/* version */
8464520Snw141292 	/* sub authority count */
8474520Snw141292 	*p++ = sid->sub_authority_count;
8484520Snw141292 	/* Authority */
8494520Snw141292 	a = sid->authority;
8504520Snw141292 	/* big-endian -- start from left */
8514520Snw141292 	*p++ = (a >> 40) & 0xFF;
8524520Snw141292 	*p++ = (a >> 32) & 0xFF;
8534520Snw141292 	*p++ = (a >> 24) & 0xFF;
8544520Snw141292 	*p++ = (a >> 16) & 0xFF;
8554520Snw141292 	*p++ = (a >> 8) & 0xFF;
8564520Snw141292 	*p++ = a & 0xFF;
8574520Snw141292 
8584520Snw141292 	/* sub-authorities */
8594520Snw141292 	for (i = 0; i < sid->sub_authority_count; i++) {
8604520Snw141292 		r = sid->sub_authorities[i];
8614520Snw141292 		/* little-endian -- start from right */
8624520Snw141292 		*p++ = (r & 0x000000FF);
8634520Snw141292 		*p++ = (r & 0x0000FF00) >> 8;
8644520Snw141292 		*p++ = (r & 0x00FF0000) >> 16;
8654520Snw141292 		*p++ = (r & 0xFF000000) >> 24;
8664520Snw141292 	}
8674520Snw141292 
8684520Snw141292 	return (0);
8694520Snw141292 }
8704520Snw141292 
8714520Snw141292 /*
8724520Snw141292  * Convert a stringified SID (S-1-...) into a hex-encoded version of the
8734520Snw141292  * on-the-wire encoding, but with each pair of hex digits pre-pended
8744520Snw141292  * with a '\', so we can pass this to libldap.
8754520Snw141292  */
8764520Snw141292 static
8774520Snw141292 int
8784520Snw141292 idmap_txtsid2hexbinsid(const char *txt, const rid_t *rid,
8794520Snw141292 	char *hexbinsid, int hexbinsidlen)
8804520Snw141292 {
8814520Snw141292 	sid_t		sid = { 0 };
8824520Snw141292 	int		i, j;
8834520Snw141292 	const char	*cp;
8844520Snw141292 	char		*ecp;
8854520Snw141292 	u_longlong_t	a;
8864520Snw141292 	unsigned long	r;
8874520Snw141292 	uchar_t		*binsid, b, hb;
8884520Snw141292 
8894520Snw141292 	/* Only version 1 SIDs please */
8904520Snw141292 	if (strncmp(txt, "S-1-", strlen("S-1-")) != 0)
8914520Snw141292 		return (-1);
8924520Snw141292 
8934520Snw141292 	if (strlen(txt) < (strlen("S-1-") + 1))
8944520Snw141292 		return (-1);
8954520Snw141292 
8964520Snw141292 	/* count '-'s */
8974520Snw141292 	for (j = 0, cp = strchr(txt, '-');
8984520Snw141292 	    cp != NULL && *cp != '\0';
8994520Snw141292 	    j++, cp = strchr(cp + 1, '-')) {
9004520Snw141292 		/* can't end on a '-' */
9014520Snw141292 		if (*(cp + 1) == '\0')
9024520Snw141292 			return (-1);
9034520Snw141292 	}
9044520Snw141292 
9054864Sbaban 	/* Adjust count for version and authority */
9064864Sbaban 	j -= 2;
9074864Sbaban 
9084864Sbaban 	/* we know the version number and RID count */
9094864Sbaban 	sid.version = 1;
9104864Sbaban 	sid.sub_authority_count = (rid != NULL) ? j + 1 : j;
9114864Sbaban 
9124520Snw141292 	/* must have at least one RID, but not too many */
9134864Sbaban 	if (sid.sub_authority_count < 1 ||
9144864Sbaban 	    sid.sub_authority_count > SID_MAX_SUB_AUTHORITIES)
9154520Snw141292 		return (-1);
9164520Snw141292 
9174520Snw141292 	/* check that we only have digits and '-' */
9184520Snw141292 	if (strspn(txt + 1, "0123456789-") < (strlen(txt) - 1))
9194520Snw141292 		return (-1);
9204520Snw141292 
9214520Snw141292 	cp = txt + strlen("S-1-");
9224520Snw141292 
9234520Snw141292 	/* 64-bit safe parsing of unsigned 48-bit authority value */
9244520Snw141292 	errno = 0;
9254520Snw141292 	a = strtoull(cp, &ecp, 10);
9264520Snw141292 
9274520Snw141292 	/* errors parsing the authority or too many bits */
9284520Snw141292 	if (cp == ecp || (a == 0 && errno == EINVAL) ||
9294520Snw141292 	    (a == ULLONG_MAX && errno == ERANGE) ||
9304520Snw141292 	    (a & 0x0000ffffffffffffULL) != a)
9314520Snw141292 		return (-1);
9324520Snw141292 
9334520Snw141292 	cp = ecp;
9344520Snw141292 
9354520Snw141292 	sid.authority = (uint64_t)a;
9364520Snw141292 
9374864Sbaban 	for (i = 0; i < j; i++) {
9384520Snw141292 		if (*cp++ != '-')
9394520Snw141292 			return (-1);
9404520Snw141292 		/* 64-bit safe parsing of unsigned 32-bit RID */
9414520Snw141292 		errno = 0;
9424520Snw141292 		r = strtoul(cp, &ecp, 10);
9434520Snw141292 		/* errors parsing the RID or too many bits */
9444520Snw141292 		if (cp == ecp || (r == 0 && errno == EINVAL) ||
9454520Snw141292 		    (r == ULONG_MAX && errno == ERANGE) ||
9464520Snw141292 		    (r & 0xffffffffUL) != r)
9474520Snw141292 			return (-1);
9484520Snw141292 		sid.sub_authorities[i] = (uint32_t)r;
9494520Snw141292 		cp = ecp;
9504520Snw141292 	}
9514520Snw141292 
9524520Snw141292 	/* check that all of the string SID has been consumed */
9534520Snw141292 	if (*cp != '\0')
9544520Snw141292 		return (-1);
9554520Snw141292 
9564864Sbaban 	if (rid != NULL)
9574864Sbaban 		sid.sub_authorities[j] = *rid;
9584520Snw141292 
9594520Snw141292 	j = 1 + 1 + 6 + sid.sub_authority_count * 4;
9604520Snw141292 
9614520Snw141292 	if (hexbinsidlen < (j * 3))
9624520Snw141292 		return (-2);
9634520Snw141292 
9644520Snw141292 	/* binary encode the SID */
9654520Snw141292 	binsid = (uchar_t *)alloca(j);
9664520Snw141292 	(void) idmap_sid2binsid(&sid, binsid, j);
9674520Snw141292 
9684520Snw141292 	/* hex encode, with a backslash before each byte */
9694520Snw141292 	for (ecp = hexbinsid, i = 0; i < j; i++) {
9704520Snw141292 		b = binsid[i];
9714520Snw141292 		*ecp++ = '\\';
9724520Snw141292 		hb = (b >> 4) & 0xF;
9734520Snw141292 		*ecp++ = (hb <= 0x9 ? hb + '0' : hb - 10 + 'A');
9744520Snw141292 		hb = b & 0xF;
9754520Snw141292 		*ecp++ = (hb <= 0x9 ? hb + '0' : hb - 10 + 'A');
9764520Snw141292 	}
9774520Snw141292 	*ecp = '\0';
9784520Snw141292 
9794520Snw141292 	return (0);
9804520Snw141292 }
9814520Snw141292 
9824520Snw141292 static
9834520Snw141292 char *
9844520Snw141292 convert_bval2sid(BerValue *bval, rid_t *rid)
9854520Snw141292 {
9864520Snw141292 	sid_t	sid;
9874520Snw141292 
9884520Snw141292 	if (idmap_getsid(bval, &sid) < 0)
9894520Snw141292 		return (NULL);
9904520Snw141292 
9914520Snw141292 	/*
9924520Snw141292 	 * If desired and if the SID is what should be a domain/computer
9934520Snw141292 	 * user or group SID (i.e., S-1-5-w-x-y-z-<user/group RID>) then
9944520Snw141292 	 * save the last RID and truncate the SID
9954520Snw141292 	 */
9964520Snw141292 	if (rid != NULL && sid.authority == 5 && sid.sub_authority_count == 5)
9974520Snw141292 		*rid = sid.sub_authorities[--sid.sub_authority_count];
9984520Snw141292 	return (idmap_sid2txt(&sid));
9994520Snw141292 }
10004520Snw141292 
10014520Snw141292 
10024520Snw141292 idmap_retcode
10034520Snw141292 idmap_lookup_batch_start(ad_t *ad, int nqueries, idmap_query_state_t **state)
10044520Snw141292 {
10054520Snw141292 	idmap_query_state_t *new_state;
10064520Snw141292 	ad_host_t	*adh = NULL;
10074520Snw141292 
10084520Snw141292 	*state = NULL;
10094520Snw141292 
10104520Snw141292 	if (*ad->dflt_w2k_dom == '\0')
10114520Snw141292 		return (-1);
10124520Snw141292 
10134520Snw141292 	adh = idmap_get_conn(ad);
10144520Snw141292 	if (adh == NULL)
10154520Snw141292 		return (IDMAP_ERR_OTHER);
10164520Snw141292 
10174520Snw141292 	new_state = calloc(1, sizeof (idmap_query_state_t) +
10184520Snw141292 	    (nqueries - 1) * sizeof (idmap_q_t));
10194520Snw141292 
10204520Snw141292 	if (new_state == NULL)
10214520Snw141292 		return (IDMAP_ERR_MEMORY);
10224520Snw141292 
10234884Sjp151216 	new_state->ref_cnt = 1;
10244520Snw141292 	new_state->qadh = adh;
10254520Snw141292 	new_state->qcount = nqueries;
10264520Snw141292 	new_state->qadh_gen = adh->generation;
10274520Snw141292 	/* should be -1, but the atomic routines want unsigned */
10284520Snw141292 	new_state->qlastsent = 0;
10294884Sjp151216 	(void) pthread_cond_init(&new_state->cv, NULL);
10304520Snw141292 
10314520Snw141292 	(void) pthread_mutex_lock(&qstatelock);
10324520Snw141292 	new_state->next = qstatehead;
10334520Snw141292 	qstatehead = new_state;
10344520Snw141292 	(void) pthread_mutex_unlock(&qstatelock);
10354520Snw141292 
10364520Snw141292 	*state = new_state;
10374520Snw141292 
10384520Snw141292 	return (IDMAP_SUCCESS);
10394520Snw141292 }
10404520Snw141292 
10414520Snw141292 /*
10424520Snw141292  * Find the idmap_query_state_t to which a given LDAP result msgid on a
10434884Sjp151216  * given connection belongs. This routine increaments the reference count
10444884Sjp151216  * so that the object can not be freed. idmap_lookup_unlock_batch()
10454884Sjp151216  * must be called to decreament the reference count.
10464520Snw141292  */
10474520Snw141292 static
10484520Snw141292 int
10494520Snw141292 idmap_msgid2query(ad_host_t *adh, int msgid,
10504520Snw141292 	idmap_query_state_t **state, int *qid)
10514520Snw141292 {
10524520Snw141292 	idmap_query_state_t *p;
10534520Snw141292 	int		    i;
10544520Snw141292 
10554520Snw141292 	(void) pthread_mutex_lock(&qstatelock);
10564520Snw141292 	for (p = qstatehead; p != NULL; p = p->next) {
10574520Snw141292 		if (p->qadh != adh || adh->generation != p->qadh_gen)
10584520Snw141292 			continue;
10594520Snw141292 		for (i = 0; i < p->qcount; i++) {
10604520Snw141292 			if ((p->queries[i]).msgid == msgid) {
10614884Sjp151216 				p->ref_cnt++;
10624520Snw141292 				*state = p;
10634520Snw141292 				*qid = i;
10644520Snw141292 				(void) pthread_mutex_unlock(&qstatelock);
10654520Snw141292 				return (1);
10664520Snw141292 			}
10674520Snw141292 		}
10684520Snw141292 	}
10694520Snw141292 	(void) pthread_mutex_unlock(&qstatelock);
10704520Snw141292 	return (0);
10714520Snw141292 }
10724520Snw141292 
10734520Snw141292 /*
10744520Snw141292  * Handle an objectSid attr from a result
10754520Snw141292  */
10764520Snw141292 static
1077*5447Snw141292 int
10784520Snw141292 idmap_bv_objsid2sidstr(BerValue **bvalues, idmap_q_t *q)
10794520Snw141292 {
10804520Snw141292 	if (bvalues == NULL)
1081*5447Snw141292 		return (0);
10824520Snw141292 	/* objectSid is single valued */
1083*5447Snw141292 	if ((*(q->result) = convert_bval2sid(bvalues[0], q->rid)) == NULL)
1084*5447Snw141292 		return (0);
1085*5447Snw141292 	return (1);
10864520Snw141292 }
10874520Snw141292 
10884520Snw141292 /*
10894520Snw141292  * Handle a sAMAccountName attr from a result
10904520Snw141292  */
10914520Snw141292 static
1092*5447Snw141292 int
10934520Snw141292 idmap_bv_samaccountname2name(BerValue **bvalues, idmap_q_t *q, const char *dn)
10944520Snw141292 {
1095*5447Snw141292 	char *result, *domain, *s;
10964520Snw141292 	int len;
10974520Snw141292 
10984520Snw141292 	if (bvalues == NULL || bvalues[0] == NULL ||
10994520Snw141292 	    bvalues[0]->bv_val == NULL)
1100*5447Snw141292 		return (0);
1101*5447Snw141292 
1102*5447Snw141292 	/*
1103*5447Snw141292 	 * In the name->SID case we check that the SAN and DN of any
1104*5447Snw141292 	 * result entry match the the lookup we were doing.
1105*5447Snw141292 	 */
1106*5447Snw141292 	if (q->n2s_cname != NULL) {
1107*5447Snw141292 		/* get the domain part of the winname we were looking up */
1108*5447Snw141292 		s = strchr(q->n2s_cname, '@');
1109*5447Snw141292 		assert(s != NULL);
1110*5447Snw141292 		/* get the length of the user/group name part */
1111*5447Snw141292 		len = s - q->n2s_cname;
1112*5447Snw141292 		/* eat the '@' */
1113*5447Snw141292 		s++;
1114*5447Snw141292 
1115*5447Snw141292 		/* Compare the username part */
1116*5447Snw141292 		if (len != bvalues[0]->bv_len ||
1117*5447Snw141292 		    strncmp(q->n2s_cname, bvalues[0]->bv_val, len) != 0)
1118*5447Snw141292 			return (0);
1119*5447Snw141292 
1120*5447Snw141292 		/* Compare the domain name part to the DN */
1121*5447Snw141292 		if (!dn_matches(dn, s))
1122*5447Snw141292 			return (0);
1123*5447Snw141292 
1124*5447Snw141292 		return (1);
1125*5447Snw141292 	}
1126*5447Snw141292 
1127*5447Snw141292 	/* SID->name */
1128*5447Snw141292 	assert(*q->result == NULL);
1129*5447Snw141292 	assert(q->domain == NULL || *q->domain == NULL);
1130*5447Snw141292 
1131*5447Snw141292 	if ((domain = dn2dns(dn)) == NULL)
1132*5447Snw141292 		return (0);
11334520Snw141292 
11344520Snw141292 	len = bvalues[0]->bv_len + 1;
11354520Snw141292 
11364520Snw141292 	if (q->domain != NULL)
11374520Snw141292 		*(q->domain) = domain;
11384520Snw141292 	else
11394520Snw141292 		len += strlen(domain) + 1;
11404520Snw141292 
11414520Snw141292 	if ((result = malloc(len)) == NULL) {
11424520Snw141292 		if (q->domain != NULL)
11434520Snw141292 			*(q->domain) = NULL;
11444520Snw141292 		free(domain);
1145*5447Snw141292 		return (0);
11464520Snw141292 	}
11474520Snw141292 
11484520Snw141292 	(void) memcpy(result, bvalues[0]->bv_val, (size_t)bvalues[0]->bv_len);
11494520Snw141292 	result[bvalues[0]->bv_len] = '\0';
11504520Snw141292 
11514520Snw141292 	if (q->domain == NULL) {
11524520Snw141292 		(void) strlcat(result, "@", len);
11534520Snw141292 		(void) strlcat(result, domain, len);
11544520Snw141292 		free(domain);
11554520Snw141292 	}
11564520Snw141292 
11574520Snw141292 	*(q->result) = result;
1158*5447Snw141292 	return (1);
11594520Snw141292 }
11604520Snw141292 
11614520Snw141292 
11624520Snw141292 #define	BVAL_CASEEQ(bv, str) \
11634520Snw141292 		(((*(bv))->bv_len == (sizeof (str) - 1)) && \
11644520Snw141292 		    strncasecmp((*(bv))->bv_val, str, (*(bv))->bv_len) == 0)
11654520Snw141292 
11664520Snw141292 /*
11674520Snw141292  * Handle an objectClass attr from a result
11684520Snw141292  */
11694520Snw141292 static
1170*5447Snw141292 int
11714520Snw141292 idmap_bv_objclass2sidtype(BerValue **bvalues, idmap_q_t *q)
11724520Snw141292 {
11734520Snw141292 	BerValue	**cbval;
11744520Snw141292 
11754520Snw141292 	if (bvalues == NULL)
1176*5447Snw141292 		return (0);
11774520Snw141292 
11784520Snw141292 	for (cbval = bvalues; *cbval != NULL; cbval++) {
11794520Snw141292 		/* don't clobber sid_type */
11804520Snw141292 		if (*(q->sid_type) == _IDMAP_T_COMPUTER ||
11814520Snw141292 		    *(q->sid_type) == _IDMAP_T_GROUP ||
11824520Snw141292 		    *(q->sid_type) == _IDMAP_T_USER)
11834520Snw141292 			continue;
11844520Snw141292 
11854520Snw141292 		if (BVAL_CASEEQ(cbval, "Computer")) {
11864520Snw141292 			*(q->sid_type) = _IDMAP_T_COMPUTER;
1187*5447Snw141292 			return (0);
11884520Snw141292 		} else if (BVAL_CASEEQ(cbval, "Group")) {
11894520Snw141292 			*(q->sid_type) = _IDMAP_T_GROUP;
11904520Snw141292 		} else if (BVAL_CASEEQ(cbval, "USER")) {
11914520Snw141292 			*(q->sid_type) = _IDMAP_T_USER;
11924520Snw141292 		} else
11934520Snw141292 			*(q->sid_type) = _IDMAP_T_OTHER;
11944520Snw141292 	}
1195*5447Snw141292 
1196*5447Snw141292 	return (1);
11974520Snw141292 }
11984520Snw141292 
11994520Snw141292 /*
12004520Snw141292  * Handle a given search result entry
12014520Snw141292  */
12024520Snw141292 static
12034520Snw141292 void
12044520Snw141292 idmap_extract_object(idmap_query_state_t *state, int qid, LDAPMessage *res)
12054520Snw141292 {
12064520Snw141292 	char			*dn, *attr;
12074520Snw141292 	BerElement		*ber = NULL;
12084520Snw141292 	BerValue		**bvalues;
12094520Snw141292 	ad_host_t		*adh;
12104520Snw141292 	idmap_q_t		*q;
12114520Snw141292 	idmap_retcode		orc;
1212*5447Snw141292 	int			has_class, has_san, has_sid;
12134520Snw141292 
12144520Snw141292 	adh = state->qadh;
12154520Snw141292 
12164520Snw141292 	(void) pthread_mutex_lock(&adh->lock);
12174520Snw141292 
1218*5447Snw141292 	q = &(state->queries[qid]);
1219*5447Snw141292 
1220*5447Snw141292 	if (*q->rc == IDMAP_SUCCESS || adh->dead ||
1221*5447Snw141292 	    (dn = ldap_get_dn(adh->ld, res)) == NULL) {
12224520Snw141292 		(void) pthread_mutex_unlock(&adh->lock);
12234520Snw141292 		return;
12244520Snw141292 	}
12254520Snw141292 
1226*5447Snw141292 	assert(*q->result == NULL);
1227*5447Snw141292 	assert(q->domain == NULL || *q->domain == NULL);
12284520Snw141292 
1229*5447Snw141292 	orc = *q->rc;
1230*5447Snw141292 
1231*5447Snw141292 	has_class = has_san = has_sid = 0;
12324520Snw141292 	for (attr = ldap_first_attribute(adh->ld, res, &ber); attr != NULL;
12334520Snw141292 	    attr = ldap_next_attribute(adh->ld, res, ber)) {
12344520Snw141292 		bvalues = NULL;	/* for memory management below */
12354520Snw141292 
12364520Snw141292 		/*
12374520Snw141292 		 * If this is an attribute we are looking for and
12384520Snw141292 		 * haven't seen it yet, parse it
12394520Snw141292 		 */
1240*5447Snw141292 		if (q->n2s_cname != NULL && !has_sid &&
1241*5447Snw141292 		    strcasecmp(attr, OBJSID) == 0) {
12424520Snw141292 			bvalues = ldap_get_values_len(adh->ld, res, attr);
1243*5447Snw141292 			has_sid = idmap_bv_objsid2sidstr(bvalues, q);
1244*5447Snw141292 		} else if (!has_san && strcasecmp(attr, SAN) == 0) {
12454520Snw141292 			bvalues = ldap_get_values_len(adh->ld, res, attr);
1246*5447Snw141292 			has_san = idmap_bv_samaccountname2name(bvalues, q, dn);
1247*5447Snw141292 		} else if (!has_class && strcasecmp(attr, OBJCLASS) == 0) {
12484520Snw141292 			bvalues = ldap_get_values_len(adh->ld, res, attr);
1249*5447Snw141292 			has_class = idmap_bv_objclass2sidtype(bvalues, q);
12504520Snw141292 		}
12514520Snw141292 
12524520Snw141292 		if (bvalues != NULL)
12534520Snw141292 			ldap_value_free_len(bvalues);
12544520Snw141292 		ldap_memfree(attr);
12554520Snw141292 
1256*5447Snw141292 		orc = (has_class && has_san &&
1257*5447Snw141292 		    (!q->n2s_cname != NULL || has_sid)) ?  IDMAP_SUCCESS : orc;
12584520Snw141292 
1259*5447Snw141292 		if (orc == IDMAP_SUCCESS)
1260*5447Snw141292 			break;
12614520Snw141292 	}
12624520Snw141292 
1263*5447Snw141292 	if (orc != IDMAP_SUCCESS) {
1264*5447Snw141292 		/*
1265*5447Snw141292 		 * Failure (e.g., SAN & DN did not match n2s query); clean up
1266*5447Snw141292 		 * results.
1267*5447Snw141292 		 */
1268*5447Snw141292 		free(*q->result);
1269*5447Snw141292 		q->result = NULL;
1270*5447Snw141292 		if (q->domain != NULL)
1271*5447Snw141292 			free(*q->domain);
1272*5447Snw141292 		q->domain = NULL;
1273*5447Snw141292 	}
1274*5447Snw141292 
1275*5447Snw141292 	if (orc == IDMAP_SUCCESS)
1276*5447Snw141292 		*q->rc = IDMAP_SUCCESS;
1277*5447Snw141292 
1278*5447Snw141292 	(void) pthread_mutex_unlock(&adh->lock);
12794520Snw141292 
12804520Snw141292 	if (ber != NULL)
12814520Snw141292 		ber_free(ber, 0);
12824520Snw141292 
12834520Snw141292 	ldap_memfree(dn);
12844520Snw141292 }
12854520Snw141292 
12864520Snw141292 /*
12874520Snw141292  * Try to get a result; if there is one, find the corresponding
12884520Snw141292  * idmap_q_t and process the result.
12894520Snw141292  */
12904520Snw141292 static
12914520Snw141292 int
12924520Snw141292 idmap_get_adobject_batch(ad_host_t *adh, struct timeval *timeout)
12934520Snw141292 {
12944520Snw141292 	idmap_query_state_t	*query_state;
12954520Snw141292 	LDAPMessage		*res = NULL;
12964520Snw141292 	int			rc, ret, msgid, qid;
12974520Snw141292 
12984520Snw141292 	(void) pthread_mutex_lock(&adh->lock);
12994520Snw141292 	if (adh->dead) {
13004520Snw141292 		(void) pthread_mutex_unlock(&adh->lock);
13014520Snw141292 		return (-1);
13024520Snw141292 	}
13034520Snw141292 
13044520Snw141292 	/* Get one result */
13054520Snw141292 	rc = ldap_result(adh->ld, LDAP_RES_ANY, 0,
13064520Snw141292 	    timeout, &res);
13074520Snw141292 	if (rc == LDAP_UNAVAILABLE || rc == LDAP_UNWILLING_TO_PERFORM ||
13084520Snw141292 	    rc == LDAP_CONNECT_ERROR || rc == LDAP_SERVER_DOWN ||
13094520Snw141292 	    rc == LDAP_BUSY)
13104520Snw141292 		adh->dead = 1;
13114520Snw141292 	(void) pthread_mutex_unlock(&adh->lock);
13124520Snw141292 
13134520Snw141292 	if (adh->dead)
13144520Snw141292 		return (-1);
13154520Snw141292 
13164520Snw141292 	switch (rc) {
13174520Snw141292 	case LDAP_RES_SEARCH_RESULT:
13184520Snw141292 		/* We have all the LDAP replies for some search... */
13194520Snw141292 		msgid = ldap_msgid(res);
13204520Snw141292 		if (idmap_msgid2query(adh, msgid,
13214520Snw141292 		    &query_state, &qid)) {
13224520Snw141292 			/* ...so we can decrement qinflight */
13234520Snw141292 			atomic_dec_32(&query_state->qinflight);
1324*5447Snw141292 			/* We've seen all the result entries we'll see */
1325*5447Snw141292 			if (*query_state->queries[qid].rc != IDMAP_SUCCESS)
1326*5447Snw141292 				*query_state->queries[qid].rc =
1327*5447Snw141292 				    IDMAP_ERR_NOTFOUND;
13284884Sjp151216 			idmap_lookup_unlock_batch(&query_state);
13294520Snw141292 		}
13304520Snw141292 		(void) ldap_msgfree(res);
13314520Snw141292 		ret = 0;
13324520Snw141292 		break;
13334520Snw141292 	case LDAP_RES_SEARCH_REFERENCE:
13344520Snw141292 		/*
13354520Snw141292 		 * We have no need for these at the moment.  Eventually,
13364520Snw141292 		 * when we query things that we can't expect to find in
13374520Snw141292 		 * the Global Catalog then we'll need to learn to follow
13384520Snw141292 		 * references.
13394520Snw141292 		 */
13404520Snw141292 		(void) ldap_msgfree(res);
13414520Snw141292 		ret = 0;
13424520Snw141292 		break;
13434520Snw141292 	case LDAP_RES_SEARCH_ENTRY:
13444520Snw141292 		/* Got a result */
13454520Snw141292 		msgid = ldap_msgid(res);
13464520Snw141292 		if (idmap_msgid2query(adh, msgid,
13474520Snw141292 		    &query_state, &qid)) {
13484520Snw141292 			idmap_extract_object(query_state, qid, res);
13494520Snw141292 			/* we saw at least one result */
13504884Sjp151216 			idmap_lookup_unlock_batch(&query_state);
13514520Snw141292 		}
13524520Snw141292 		(void) ldap_msgfree(res);
13534520Snw141292 		ret = 0;
13544520Snw141292 		break;
13554520Snw141292 	default:
13564520Snw141292 		/* timeout or error; treat the same */
13574520Snw141292 		ret = -1;
13584520Snw141292 		break;
13594520Snw141292 	}
13604520Snw141292 
13614520Snw141292 	return (ret);
13624520Snw141292 }
13634520Snw141292 
13644884Sjp151216 /*
13654884Sjp151216  * This routine decreament the reference count of the
13664884Sjp151216  * idmap_query_state_t
13674884Sjp151216  */
13684884Sjp151216 static void
13694884Sjp151216 idmap_lookup_unlock_batch(idmap_query_state_t **state)
13704884Sjp151216 {
13714884Sjp151216 	/*
13724884Sjp151216 	 * Decrement reference count with qstatelock locked
13734884Sjp151216 	 */
13744884Sjp151216 	(void) pthread_mutex_lock(&qstatelock);
13754884Sjp151216 	(*state)->ref_cnt--;
13764884Sjp151216 	/*
13774884Sjp151216 	 * If there are no references wakup the allocating thread
13784884Sjp151216 	 */
13794884Sjp151216 	if ((*state)->ref_cnt == 0)
13804884Sjp151216 		(void) pthread_cond_signal(&(*state)->cv);
13814884Sjp151216 	(void) pthread_mutex_unlock(&qstatelock);
13824884Sjp151216 	*state = NULL;
13834884Sjp151216 }
13844884Sjp151216 
1385*5447Snw141292 static
1386*5447Snw141292 void
1387*5447Snw141292 idmap_cleanup_batch(idmap_query_state_t *batch)
1388*5447Snw141292 {
1389*5447Snw141292 	int i;
1390*5447Snw141292 
1391*5447Snw141292 	for (i = 0; i < batch->qcount; i++) {
1392*5447Snw141292 		if (batch->queries[i].n2s_cname != NULL)
1393*5447Snw141292 			free(batch->queries[i].n2s_cname);
1394*5447Snw141292 		batch->queries[i].n2s_cname = NULL;
1395*5447Snw141292 	}
1396*5447Snw141292 }
1397*5447Snw141292 
13984884Sjp151216 /*
13994884Sjp151216  * This routine frees the idmap_query_state_t structure
14004884Sjp151216  * If the reference count is greater than 1 it waits
14014884Sjp151216  * for the other threads to finish using it.
14024884Sjp151216  */
14034520Snw141292 void
14044884Sjp151216 idmap_lookup_release_batch(idmap_query_state_t **state)
14054520Snw141292 {
14064520Snw141292 	idmap_query_state_t **p;
14074520Snw141292 
14084884Sjp151216 	/*
14094884Sjp151216 	 * Decrement reference count with qstatelock locked
14104884Sjp151216 	 * and wait for reference count to get to zero
14114884Sjp151216 	 */
14124884Sjp151216 	(void) pthread_mutex_lock(&qstatelock);
14134884Sjp151216 	(*state)->ref_cnt--;
14144884Sjp151216 	while ((*state)->ref_cnt > 0) {
14154884Sjp151216 		(void) pthread_cond_wait(&(*state)->cv, &qstatelock);
14164884Sjp151216 	}
14174520Snw141292 
14184520Snw141292 	/* Remove this state struct from the list of state structs */
14194520Snw141292 	for (p = &qstatehead; *p != NULL; p = &(*p)->next) {
14204520Snw141292 		if (*p == (*state)) {
14214520Snw141292 			*p = (*state)->next;
14224520Snw141292 			break;
14234520Snw141292 		}
14244520Snw141292 	}
1425*5447Snw141292 
1426*5447Snw141292 	idmap_cleanup_batch(*state);
1427*5447Snw141292 
14284520Snw141292 	(void) pthread_mutex_unlock(&qstatelock);
14294520Snw141292 
14304884Sjp151216 	(void) pthread_cond_destroy(&(*state)->cv);
14314884Sjp151216 
14324884Sjp151216 	idmap_release_conn((*state)->qadh);
14334884Sjp151216 
14344520Snw141292 	free(*state);
14354520Snw141292 	*state = NULL;
14364520Snw141292 }
14374520Snw141292 
14384520Snw141292 idmap_retcode
14394520Snw141292 idmap_lookup_batch_end(idmap_query_state_t **state,
14404520Snw141292 	struct timeval *timeout)
14414520Snw141292 {
14424520Snw141292 	int		    rc = LDAP_SUCCESS;
14434520Snw141292 	idmap_retcode	    retcode = IDMAP_SUCCESS;
14444520Snw141292 
14454520Snw141292 	(*state)->qdead = 1;
14464520Snw141292 
14474520Snw141292 	/* Process results until done or until timeout, if given */
14484520Snw141292 	while ((*state)->qinflight > 0) {
14494520Snw141292 		if ((rc = idmap_get_adobject_batch((*state)->qadh,
14504520Snw141292 		    timeout)) != 0)
14514520Snw141292 			break;
14524520Snw141292 	}
14534520Snw141292 
14544520Snw141292 	if (rc == LDAP_UNAVAILABLE || rc == LDAP_UNWILLING_TO_PERFORM ||
14554520Snw141292 	    rc == LDAP_CONNECT_ERROR || rc == LDAP_SERVER_DOWN ||
14564520Snw141292 	    rc == LDAP_BUSY) {
14574520Snw141292 		retcode = IDMAP_ERR_RETRIABLE_NET_ERR;
14584520Snw141292 		(*state)->qadh->dead = 1;
14594520Snw141292 	}
14604520Snw141292 
14614884Sjp151216 	idmap_lookup_release_batch(state);
14624520Snw141292 
14634520Snw141292 	return (retcode);
14644520Snw141292 }
14654520Snw141292 
14664520Snw141292 /*
14674520Snw141292  * Send one prepared search, queue up msgid, process what results are
14684520Snw141292  * available
14694520Snw141292  */
14704520Snw141292 static
14714520Snw141292 idmap_retcode
1472*5447Snw141292 idmap_batch_add1(idmap_query_state_t *state,
1473*5447Snw141292 	const char *filter, char *canonname,
14744520Snw141292 	char **result, char **dname, rid_t *rid, int *sid_type,
14754520Snw141292 	idmap_retcode *rc)
14764520Snw141292 {
14774520Snw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
14784520Snw141292 	int		lrc, qid;
14794520Snw141292 	struct timeval	tv;
14804520Snw141292 	idmap_q_t	*q;
14814520Snw141292 
14824520Snw141292 	if (state->qdead) {
1483*5447Snw141292 		*rc = IDMAP_ERR_RETRIABLE_NET_ERR;
14844520Snw141292 		return (IDMAP_ERR_RETRIABLE_NET_ERR);
14854520Snw141292 	}
14864520Snw141292 
14874520Snw141292 	qid = atomic_inc_32_nv(&state->qlastsent) - 1;
14884520Snw141292 
14894520Snw141292 	q = &(state->queries[qid]);
14904520Snw141292 
1491*5447Snw141292 	/* Remember the canonname so we can check the results agains it */
1492*5447Snw141292 	q->n2s_cname = canonname;
1493*5447Snw141292 
14944520Snw141292 	/* Remember where to put the results */
14954520Snw141292 	q->result = result;
14964520Snw141292 	q->domain = dname;
14974520Snw141292 	q->rid = rid;
14984520Snw141292 	q->sid_type = sid_type;
14994520Snw141292 	q->rc = rc;
15004520Snw141292 
15014520Snw141292 	/*
15024520Snw141292 	 * Provide sane defaults for the results in case we never hear
15034520Snw141292 	 * back from the DS before closing the connection.
1504*5447Snw141292 	 *
1505*5447Snw141292 	 * In particular we default the result to indicate a retriable
1506*5447Snw141292 	 * error.  The first complete matching result entry will cause
1507*5447Snw141292 	 * this to be set to IDMAP_SUCCESS, and the end of the results
1508*5447Snw141292 	 * for this search will cause this to indicate "not found" if no
1509*5447Snw141292 	 * result entries arrived or no complete ones matched the lookup
1510*5447Snw141292 	 * we were doing.
15114520Snw141292 	 */
15124520Snw141292 	*rc = IDMAP_ERR_RETRIABLE_NET_ERR;
15134520Snw141292 	*sid_type = _IDMAP_T_OTHER;
15144520Snw141292 	*result = NULL;
15154520Snw141292 	if (dname != NULL)
15164520Snw141292 		*dname = NULL;
15174520Snw141292 	if (rid != NULL)
15184520Snw141292 		*rid = 0;
15194520Snw141292 
15204520Snw141292 	/* Send this lookup, don't wait for a result here */
15214520Snw141292 	(void) pthread_mutex_lock(&state->qadh->lock);
15224520Snw141292 
15234520Snw141292 	if (!state->qadh->dead) {
15244520Snw141292 		state->qadh->idletime = time(NULL);
1525*5447Snw141292 		lrc = ldap_search_ext(state->qadh->ld, "",
15264520Snw141292 		    LDAP_SCOPE_SUBTREE, filter, NULL, 0, NULL, NULL,
15274520Snw141292 		    NULL, -1, &q->msgid);
15284520Snw141292 		if (lrc == LDAP_BUSY || lrc == LDAP_UNAVAILABLE ||
15294520Snw141292 		    lrc == LDAP_CONNECT_ERROR || lrc == LDAP_SERVER_DOWN ||
15304520Snw141292 		    lrc == LDAP_UNWILLING_TO_PERFORM) {
15314520Snw141292 			retcode = IDMAP_ERR_RETRIABLE_NET_ERR;
15324520Snw141292 			state->qadh->dead = 1;
15334520Snw141292 		} else if (lrc != LDAP_SUCCESS) {
15344520Snw141292 			retcode = IDMAP_ERR_OTHER;
15354520Snw141292 			state->qadh->dead = 1;
15364520Snw141292 		}
15374520Snw141292 	}
15384520Snw141292 	(void) pthread_mutex_unlock(&state->qadh->lock);
15394520Snw141292 
15404520Snw141292 	if (state->qadh->dead)
15414520Snw141292 		return (retcode);
15424520Snw141292 
15434520Snw141292 	atomic_inc_32(&state->qinflight);
15444520Snw141292 
15454520Snw141292 	/*
15464520Snw141292 	 * Reap as many requests as we can _without_ waiting
15474520Snw141292 	 *
15484520Snw141292 	 * We do this to prevent any possible TCP socket buffer
15494520Snw141292 	 * starvation deadlocks.
15504520Snw141292 	 */
15514520Snw141292 	(void) memset(&tv, 0, sizeof (tv));
15524520Snw141292 	while (idmap_get_adobject_batch(state->qadh, &tv) == 0)
15534520Snw141292 		;
15544520Snw141292 
15554520Snw141292 	return (IDMAP_SUCCESS);
15564520Snw141292 }
15574520Snw141292 
15584520Snw141292 idmap_retcode
15594520Snw141292 idmap_name2sid_batch_add1(idmap_query_state_t *state,
15604520Snw141292 	const char *name, const char *dname,
15614520Snw141292 	char **sid, rid_t *rid, int *sid_type, idmap_retcode *rc)
15624520Snw141292 {
15634520Snw141292 	idmap_retcode	retcode;
1564*5447Snw141292 	int		len, samAcctNameLen;
15654520Snw141292 	char		*filter = NULL;
1566*5447Snw141292 	char		*canonname = NULL;
15674520Snw141292 
15684520Snw141292 	/*
1569*5447Snw141292 	 * Strategy: search the global catalog for user/group by
1570*5447Snw141292 	 * sAMAccountName = user/groupname with "" as the base DN and by
1571*5447Snw141292 	 * userPrincipalName = user/groupname@domain.  The result
1572*5447Snw141292 	 * entries will be checked to conform to the name and domain
1573*5447Snw141292 	 * name given here.  The DN, sAMAccountName, userPrincipalName,
1574*5447Snw141292 	 * objectSid and objectClass of the result entries are all we
1575*5447Snw141292 	 * need to figure out which entries match the lookup, the SID of
1576*5447Snw141292 	 * the user/group and whether it is a user or a group.
15774520Snw141292 	 */
15784520Snw141292 
15794520Snw141292 	/*
1580*5447Snw141292 	 * We need the name and the domain name separately and as
1581*5447Snw141292 	 * name@domain.  We also allow the domain to be provided
1582*5447Snw141292 	 * separately.
15834520Snw141292 	 */
15845232Snw141292 	samAcctNameLen = strlen(name);
1585*5447Snw141292 
15865232Snw141292 	if (dname == NULL || *dname == '\0') {
1587*5447Snw141292 		if (strchr(name, '@') != NULL) {
1588*5447Snw141292 			/* 'name' is qualified with a domain name */
1589*5447Snw141292 			if ((canonname = strdup(name)) == NULL)
1590*5447Snw141292 				return (IDMAP_ERR_MEMORY);
1591*5447Snw141292 		} else {
1592*5447Snw141292 			/* 'name' not qualified and dname not given */
15934520Snw141292 			dname = state->qadh->owner->dflt_w2k_dom;
15944520Snw141292 		}
15954520Snw141292 	}
15964520Snw141292 
1597*5447Snw141292 	if (dname == NULL || *dname == '\0') {
1598*5447Snw141292 		/* No default domain and domain not given */
1599*5447Snw141292 		if (canonname != NULL)
1600*5447Snw141292 			free(canonname);
1601*5447Snw141292 		return (IDMAP_ERR_DOMAIN);
1602*5447Snw141292 	}
1603*5447Snw141292 
1604*5447Snw141292 	if (canonname == NULL) {
1605*5447Snw141292 		/*
1606*5447Snw141292 		 * We need name@domain in the query record to match
1607*5447Snw141292 		 * replies to; see elsewhere
1608*5447Snw141292 		 */
1609*5447Snw141292 		len = snprintf(NULL, 0, "%s@%s", name, dname) + 1;
1610*5447Snw141292 		if ((canonname = malloc(len)) == NULL)
1611*5447Snw141292 			return (IDMAP_ERR_MEMORY);
1612*5447Snw141292 		(void) snprintf(canonname, samAcctNameLen + strlen(dname) + 2,
1613*5447Snw141292 		    "%s@%s", name, dname);
1614*5447Snw141292 	}
16154520Snw141292 
16164520Snw141292 	/* Assemble filter */
1617*5447Snw141292 	len = snprintf(NULL, 0, SANFILTER, samAcctNameLen, name) + 1;
1618*5447Snw141292 	if ((filter = (char *)malloc(len)) == NULL) {
1619*5447Snw141292 		free(canonname);
16204520Snw141292 		return (IDMAP_ERR_MEMORY);
16214520Snw141292 	}
1622*5447Snw141292 	(void) snprintf(filter, len, SANFILTER, samAcctNameLen, name);
16234520Snw141292 
1624*5447Snw141292 	retcode = idmap_batch_add1(state, filter, canonname,
16254520Snw141292 	    sid, NULL, rid, sid_type, rc);
16264520Snw141292 
16274520Snw141292 	free(filter);
16284520Snw141292 
16294520Snw141292 	return (retcode);
16304520Snw141292 }
16314520Snw141292 
16324520Snw141292 idmap_retcode
16334520Snw141292 idmap_sid2name_batch_add1(idmap_query_state_t *state,
16344520Snw141292 	const char *sid, const rid_t *rid,
16354520Snw141292 	char **name, char **dname, int *sid_type, idmap_retcode *rc)
16364520Snw141292 {
16374520Snw141292 	idmap_retcode	retcode;
16384520Snw141292 	int		flen, ret;
16394520Snw141292 	char		*filter = NULL;
16404520Snw141292 	char		cbinsid[MAXHEXBINSID + 1];
16414520Snw141292 
16424520Snw141292 	/*
16434520Snw141292 	 * Strategy: search [the global catalog] for user/group by
16444520Snw141292 	 * objectSid = SID with empty base DN.  The DN, sAMAccountName
16454520Snw141292 	 * and objectClass of the result are all we need to figure out
16464520Snw141292 	 * the name of the SID and whether it is a user, a group or a
16474520Snw141292 	 * computer.
16484520Snw141292 	 */
16494520Snw141292 
16504520Snw141292 	ret = idmap_txtsid2hexbinsid(sid, rid, &cbinsid[0], sizeof (cbinsid));
16514520Snw141292 	if (ret != 0)
16524520Snw141292 		return (IDMAP_ERR_SID);
16534520Snw141292 
16544520Snw141292 	/* Assemble filter */
1655*5447Snw141292 	flen = snprintf(NULL, 0, OBJSIDFILTER, cbinsid) + 1;
16564520Snw141292 	if ((filter = (char *)malloc(flen)) == NULL)
16574520Snw141292 		return (IDMAP_ERR_MEMORY);
1658*5447Snw141292 	(void) snprintf(filter, flen, OBJSIDFILTER, cbinsid);
16594520Snw141292 
1660*5447Snw141292 	retcode = idmap_batch_add1(state, filter, NULL, name, dname,
16614520Snw141292 	    NULL, sid_type, rc);
16624520Snw141292 
16634520Snw141292 	free(filter);
16644520Snw141292 
16654520Snw141292 	return (retcode);
16664520Snw141292 }
1667