xref: /titanic_50/usr/src/cmd/idmap/idmapd/dbutils.c (revision e8c27ec857e6e2db8c4fe56938b70a89b5bed9f3)
1c5c4113dSnw141292 /*
2c5c4113dSnw141292  * CDDL HEADER START
3c5c4113dSnw141292  *
4c5c4113dSnw141292  * The contents of this file are subject to the terms of the
5c5c4113dSnw141292  * Common Development and Distribution License (the "License").
6c5c4113dSnw141292  * You may not use this file except in compliance with the License.
7c5c4113dSnw141292  *
8c5c4113dSnw141292  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9c5c4113dSnw141292  * or http://www.opensolaris.org/os/licensing.
10c5c4113dSnw141292  * See the License for the specific language governing permissions
11c5c4113dSnw141292  * and limitations under the License.
12c5c4113dSnw141292  *
13c5c4113dSnw141292  * When distributing Covered Code, include this CDDL HEADER in each
14c5c4113dSnw141292  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15c5c4113dSnw141292  * If applicable, add the following below this CDDL HEADER, with the
16c5c4113dSnw141292  * fields enclosed by brackets "[]" replaced with your own identifying
17c5c4113dSnw141292  * information: Portions Copyright [yyyy] [name of copyright owner]
18c5c4113dSnw141292  *
19c5c4113dSnw141292  * CDDL HEADER END
20c5c4113dSnw141292  */
21c5c4113dSnw141292 /*
22c5c4113dSnw141292  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23c5c4113dSnw141292  * Use is subject to license terms.
24c5c4113dSnw141292  */
25c5c4113dSnw141292 
26c5c4113dSnw141292 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27c5c4113dSnw141292 
28c5c4113dSnw141292 /*
29c5c4113dSnw141292  * Database related utility routines
30c5c4113dSnw141292  */
31c5c4113dSnw141292 
32c8e26105Sjp151216 #include <atomic.h>
33c5c4113dSnw141292 #include <stdio.h>
34c5c4113dSnw141292 #include <stdlib.h>
35c5c4113dSnw141292 #include <string.h>
36c5c4113dSnw141292 #include <errno.h>
37c5c4113dSnw141292 #include <sys/types.h>
38c5c4113dSnw141292 #include <sys/stat.h>
39c5c4113dSnw141292 #include <rpc/rpc.h>
40c5c4113dSnw141292 #include <sys/sid.h>
41c5c4113dSnw141292 #include <time.h>
42c5c4113dSnw141292 #include <pwd.h>
43c5c4113dSnw141292 #include <grp.h>
4484decf41Sjp151216 #include <pthread.h>
4584decf41Sjp151216 #include <assert.h>
46cd37da74Snw141292 #include <sys/u8_textprep.h>
47c5c4113dSnw141292 
48c5c4113dSnw141292 #include "idmapd.h"
49c5c4113dSnw141292 #include "adutils.h"
50c5c4113dSnw141292 #include "string.h"
51c5c4113dSnw141292 #include "idmap_priv.h"
52cd37da74Snw141292 #include "schema.h"
53*e8c27ec8Sbaban #include "nldaputils.h"
54c5c4113dSnw141292 
5584decf41Sjp151216 
56c8e26105Sjp151216 static int degraded = 0;	/* whether the FMRI has been marked degraded */
57c8e26105Sjp151216 
58c5c4113dSnw141292 static idmap_retcode sql_compile_n_step_once(sqlite *, char *,
59c5c4113dSnw141292 		sqlite_vm **, int *, int, const char ***);
60cd37da74Snw141292 static idmap_retcode lookup_wksids_name2sid(const char *, char **, char **,
6162c60062Sbaban 		idmap_rid_t *, int *);
62*e8c27ec8Sbaban static idmap_retcode ad_lookup(lookup_state_t *, idmap_mapping *,
63*e8c27ec8Sbaban 		idmap_id_res *, int, int, int);
64*e8c27ec8Sbaban static idmap_retcode lookup_localsid2pid(idmap_mapping *, idmap_id_res *);
65*e8c27ec8Sbaban static idmap_retcode lookup_cache_name2sid(sqlite *, const char *,
66*e8c27ec8Sbaban 		const char *, char **, char **, idmap_rid_t *, int *);
67*e8c27ec8Sbaban 
68c5c4113dSnw141292 
69c5c4113dSnw141292 #define	EMPTY_NAME(name)	(*name == 0 || strcmp(name, "\"\"") == 0)
70c5c4113dSnw141292 
71c5c4113dSnw141292 #define	DO_NOT_ALLOC_NEW_ID_MAPPING(req)\
72c5c4113dSnw141292 		(req->flag & IDMAP_REQ_FLG_NO_NEW_ID_ALLOC)
73c5c4113dSnw141292 
74c5c4113dSnw141292 #define	AVOID_NAMESERVICE(req)\
75c5c4113dSnw141292 		(req->flag & IDMAP_REQ_FLG_NO_NAMESERVICE)
76c5c4113dSnw141292 
77*e8c27ec8Sbaban #define	IS_EPHEMERAL(pid)	(pid > INT32_MAX && pid != SENTINEL_PID)
78c5c4113dSnw141292 
79c5c4113dSnw141292 #define	LOCALRID_MIN	1000
80c5c4113dSnw141292 
81c5c4113dSnw141292 
82c5c4113dSnw141292 typedef enum init_db_option {
83c5c4113dSnw141292 	FAIL_IF_CORRUPT = 0,
84c5c4113dSnw141292 	REMOVE_IF_CORRUPT = 1
85c5c4113dSnw141292 } init_db_option_t;
86c5c4113dSnw141292 
8784decf41Sjp151216 /*
88*e8c27ec8Sbaban  * Data structure to store well-known SIDs and
89*e8c27ec8Sbaban  * associated mappings (if any)
90*e8c27ec8Sbaban  */
91*e8c27ec8Sbaban typedef struct wksids_table {
92*e8c27ec8Sbaban 	const char	*sidprefix;
93*e8c27ec8Sbaban 	uint32_t	rid;
94*e8c27ec8Sbaban 	const char	*winname;
95*e8c27ec8Sbaban 	int		is_wuser;
96*e8c27ec8Sbaban 	uid_t		pid;
97*e8c27ec8Sbaban 	int		is_user;
98*e8c27ec8Sbaban 	int		direction;
99*e8c27ec8Sbaban } wksids_table_t;
100*e8c27ec8Sbaban 
101*e8c27ec8Sbaban /*
10284decf41Sjp151216  * Thread specfic data to hold the database handles so that the
10384decf41Sjp151216  * databaes are not opened and closed for every request. It also
10484decf41Sjp151216  * contains the sqlite busy handler structure.
10584decf41Sjp151216  */
10684decf41Sjp151216 
10784decf41Sjp151216 struct idmap_busy {
10884decf41Sjp151216 	const char *name;
10984decf41Sjp151216 	const int *delays;
11084decf41Sjp151216 	int delay_size;
11184decf41Sjp151216 	int total;
11284decf41Sjp151216 	int sec;
11384decf41Sjp151216 };
11484decf41Sjp151216 
11584decf41Sjp151216 
11684decf41Sjp151216 typedef struct idmap_tsd {
11784decf41Sjp151216 	sqlite *db_db;
11884decf41Sjp151216 	sqlite *cache_db;
11984decf41Sjp151216 	struct idmap_busy cache_busy;
12084decf41Sjp151216 	struct idmap_busy db_busy;
12184decf41Sjp151216 } idmap_tsd_t;
12284decf41Sjp151216 
12384decf41Sjp151216 
12484decf41Sjp151216 
12584decf41Sjp151216 static const int cache_delay_table[] =
12684decf41Sjp151216 		{ 1, 2, 5, 10, 15, 20, 25, 30,  35,  40,
12784decf41Sjp151216 		50,  50, 60, 70, 80, 90, 100};
12884decf41Sjp151216 
12984decf41Sjp151216 static const int db_delay_table[] =
13084decf41Sjp151216 		{ 5, 10, 15, 20, 30,  40,  55,  70, 100};
13184decf41Sjp151216 
13284decf41Sjp151216 
13384decf41Sjp151216 static pthread_key_t	idmap_tsd_key;
13484decf41Sjp151216 
13584decf41Sjp151216 void
13684decf41Sjp151216 idmap_tsd_destroy(void *key)
13784decf41Sjp151216 {
13884decf41Sjp151216 
13984decf41Sjp151216 	idmap_tsd_t	*tsd = (idmap_tsd_t *)key;
14084decf41Sjp151216 	if (tsd) {
14184decf41Sjp151216 		if (tsd->db_db)
14284decf41Sjp151216 			(void) sqlite_close(tsd->db_db);
14384decf41Sjp151216 		if (tsd->cache_db)
14484decf41Sjp151216 			(void) sqlite_close(tsd->cache_db);
14584decf41Sjp151216 		free(tsd);
14684decf41Sjp151216 	}
14784decf41Sjp151216 }
14884decf41Sjp151216 
14984decf41Sjp151216 int
150cd37da74Snw141292 idmap_init_tsd_key(void)
151cd37da74Snw141292 {
15284decf41Sjp151216 	return (pthread_key_create(&idmap_tsd_key, idmap_tsd_destroy));
15384decf41Sjp151216 }
15484decf41Sjp151216 
15584decf41Sjp151216 
15684decf41Sjp151216 
15784decf41Sjp151216 idmap_tsd_t *
15884decf41Sjp151216 idmap_get_tsd(void)
15984decf41Sjp151216 {
16084decf41Sjp151216 	idmap_tsd_t	*tsd;
16184decf41Sjp151216 
16284decf41Sjp151216 	if ((tsd = pthread_getspecific(idmap_tsd_key)) == NULL) {
16384decf41Sjp151216 		/* No thread specific data so create it */
16484decf41Sjp151216 		if ((tsd = malloc(sizeof (*tsd))) != NULL) {
16584decf41Sjp151216 			/* Initialize thread specific data */
16684decf41Sjp151216 			(void) memset(tsd, 0, sizeof (*tsd));
16784decf41Sjp151216 			/* save the trhread specific data */
16884decf41Sjp151216 			if (pthread_setspecific(idmap_tsd_key, tsd) != 0) {
16984decf41Sjp151216 				/* Can't store key */
17084decf41Sjp151216 				free(tsd);
17184decf41Sjp151216 				tsd = NULL;
17284decf41Sjp151216 			}
17384decf41Sjp151216 		} else {
17484decf41Sjp151216 			tsd = NULL;
17584decf41Sjp151216 		}
17684decf41Sjp151216 	}
17784decf41Sjp151216 
17884decf41Sjp151216 	return (tsd);
17984decf41Sjp151216 }
18084decf41Sjp151216 
181cd37da74Snw141292 static
182cd37da74Snw141292 const char *
183cd37da74Snw141292 get_fmri(void)
184cd37da74Snw141292 {
185cd37da74Snw141292 	static char *fmri = NULL;
186cd37da74Snw141292 	static char buf[60];
187cd37da74Snw141292 	char *s;
188cd37da74Snw141292 
189cd37da74Snw141292 	membar_consumer();
190cd37da74Snw141292 	s = fmri;
191cd37da74Snw141292 	if (s != NULL && *s == '\0')
192cd37da74Snw141292 		return (NULL);
193cd37da74Snw141292 	else if (s != NULL)
194cd37da74Snw141292 		return (s);
195cd37da74Snw141292 
196cd37da74Snw141292 	if ((s = getenv("SMF_FMRI")) == NULL || strlen(s) >= sizeof (buf))
197cd37da74Snw141292 		buf[0] = '\0';
198cd37da74Snw141292 	else
199cd37da74Snw141292 		(void) strlcpy(buf, s, sizeof (buf));
200cd37da74Snw141292 
201cd37da74Snw141292 	membar_producer();
202cd37da74Snw141292 	fmri = buf;
203cd37da74Snw141292 
204cd37da74Snw141292 	return (get_fmri());
205cd37da74Snw141292 }
206cd37da74Snw141292 
207c8e26105Sjp151216 /*
208c8e26105Sjp151216  * Wrappers for smf_degrade/restore_instance()
209c8e26105Sjp151216  *
210c8e26105Sjp151216  * smf_restore_instance() is too heavy duty to be calling every time we
211c8e26105Sjp151216  * have a successful AD name<->SID lookup.
212c8e26105Sjp151216  */
213c8e26105Sjp151216 void
214c8e26105Sjp151216 degrade_svc(void)
215c8e26105Sjp151216 {
216cd37da74Snw141292 	const char *fmri;
217cd37da74Snw141292 
218cd37da74Snw141292 	if ((fmri = get_fmri()) == NULL)
219cd37da74Snw141292 		return;
220cd37da74Snw141292 
221c8e26105Sjp151216 	membar_consumer();
222c8e26105Sjp151216 	if (degraded)
223c8e26105Sjp151216 		return;
224cd37da74Snw141292 	(void) smf_degrade_instance(fmri, 0);
225c8e26105Sjp151216 	membar_producer();
226c8e26105Sjp151216 	degraded = 1;
227c8e26105Sjp151216 }
228c8e26105Sjp151216 
229c8e26105Sjp151216 
230c8e26105Sjp151216 void
231c8e26105Sjp151216 restore_svc(void)
232c8e26105Sjp151216 {
233cd37da74Snw141292 	const char *fmri;
234cd37da74Snw141292 
235cd37da74Snw141292 	if ((fmri = get_fmri()) == NULL)
236cd37da74Snw141292 		return;
237cd37da74Snw141292 
238c8e26105Sjp151216 	membar_consumer();
239c8e26105Sjp151216 	if (!degraded)
240c8e26105Sjp151216 		return;
241cd37da74Snw141292 	(void) smf_restore_instance(fmri);
242c8e26105Sjp151216 	membar_producer();
243c8e26105Sjp151216 	degraded = 0;
244c8e26105Sjp151216 }
24584decf41Sjp151216 
246cd37da74Snw141292 /*
247cd37da74Snw141292  * A simple wrapper around u8_textprep_str() that returns the Unicode
248cd37da74Snw141292  * lower-case version of some string.  The result must be freed.
249cd37da74Snw141292  */
250cd37da74Snw141292 char *
251cd37da74Snw141292 tolower_u8(const char *s)
252cd37da74Snw141292 {
253cd37da74Snw141292 	char *res = NULL;
254cd37da74Snw141292 	char *outs;
255cd37da74Snw141292 	size_t inlen, outlen, inbytesleft, outbytesleft;
256cd37da74Snw141292 	int rc, err;
257cd37da74Snw141292 
258cd37da74Snw141292 	/*
259cd37da74Snw141292 	 * u8_textprep_str() does not allocate memory.  The input and
260cd37da74Snw141292 	 * output buffers may differ in size (though that would be more
261cd37da74Snw141292 	 * likely when normalization is done).  We have to loop over it...
262cd37da74Snw141292 	 *
263cd37da74Snw141292 	 * To improve the chances that we can avoid looping we add 10
264cd37da74Snw141292 	 * bytes of output buffer room the first go around.
265cd37da74Snw141292 	 */
266cd37da74Snw141292 	inlen = inbytesleft = strlen(s);
267cd37da74Snw141292 	outlen = outbytesleft = inlen + 10;
268cd37da74Snw141292 	if ((res = malloc(outlen)) == NULL)
269cd37da74Snw141292 		return (NULL);
270cd37da74Snw141292 	outs = res;
271cd37da74Snw141292 
272cd37da74Snw141292 	while ((rc = u8_textprep_str((char *)s, &inbytesleft, outs,
273cd37da74Snw141292 	    &outbytesleft, U8_TEXTPREP_TOLOWER, U8_UNICODE_LATEST, &err)) < 0 &&
274cd37da74Snw141292 	    err == E2BIG) {
275cd37da74Snw141292 		if ((res = realloc(res, outlen + inbytesleft)) == NULL)
276cd37da74Snw141292 			return (NULL);
277cd37da74Snw141292 		/* adjust input/output buffer pointers */
278cd37da74Snw141292 		s += (inlen - inbytesleft);
279cd37da74Snw141292 		outs = res + outlen - outbytesleft;
280cd37da74Snw141292 		/* adjust outbytesleft and outlen */
281cd37da74Snw141292 		outlen += inbytesleft;
282cd37da74Snw141292 		outbytesleft += inbytesleft;
283cd37da74Snw141292 	}
284cd37da74Snw141292 
285cd37da74Snw141292 	if (rc < 0) {
286cd37da74Snw141292 		free(res);
287cd37da74Snw141292 		res = NULL;
288cd37da74Snw141292 		return (NULL);
289cd37da74Snw141292 	}
290cd37da74Snw141292 
291cd37da74Snw141292 	res[outlen - outbytesleft] = '\0';
292cd37da74Snw141292 
293cd37da74Snw141292 	return (res);
294cd37da74Snw141292 }
295cd37da74Snw141292 
296cd37da74Snw141292 static int sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
297cd37da74Snw141292 	const char *while_doing);
298cd37da74Snw141292 
299c5c4113dSnw141292 
300c5c4113dSnw141292 /*
301c5c4113dSnw141292  * Initialize 'dbname' using 'sql'
302c5c4113dSnw141292  */
303cd37da74Snw141292 static
304cd37da74Snw141292 int
305cd37da74Snw141292 init_db_instance(const char *dbname, int version,
306cd37da74Snw141292 	const char *detect_version_sql, char * const *sql,
307cd37da74Snw141292 	init_db_option_t opt, int *created, int *upgraded)
308c5c4113dSnw141292 {
309cd37da74Snw141292 	int rc, curr_version;
310cd37da74Snw141292 	int tries = 1;
311cd37da74Snw141292 	int prio = LOG_NOTICE;
312c5c4113dSnw141292 	sqlite *db = NULL;
313cd37da74Snw141292 	char *errmsg = NULL;
314c5c4113dSnw141292 
315cd37da74Snw141292 	*created = 0;
316cd37da74Snw141292 	*upgraded = 0;
317c5c4113dSnw141292 
318cd37da74Snw141292 	if (opt == REMOVE_IF_CORRUPT)
319cd37da74Snw141292 		tries = 3;
320cd37da74Snw141292 
321cd37da74Snw141292 rinse_repeat:
322cd37da74Snw141292 	if (tries == 0) {
323cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to initialize db %s", dbname);
324c5c4113dSnw141292 		return (-1);
325cd37da74Snw141292 	}
326cd37da74Snw141292 	if (tries-- == 1)
327cd37da74Snw141292 		/* Last try, log errors */
328cd37da74Snw141292 		prio = LOG_ERR;
329c5c4113dSnw141292 
330cd37da74Snw141292 	db = sqlite_open(dbname, 0600, &errmsg);
331cd37da74Snw141292 	if (db == NULL) {
332cd37da74Snw141292 		idmapdlog(prio, "Error creating database %s (%s)",
333cd37da74Snw141292 		    dbname, CHECK_NULL(errmsg));
334cd37da74Snw141292 		sqlite_freemem(errmsg);
335cd37da74Snw141292 		if (opt == REMOVE_IF_CORRUPT)
336c5c4113dSnw141292 			(void) unlink(dbname);
337cd37da74Snw141292 		goto rinse_repeat;
338c5c4113dSnw141292 	}
339c5c4113dSnw141292 
340c5c4113dSnw141292 	sqlite_busy_timeout(db, 3000);
341cd37da74Snw141292 
342cd37da74Snw141292 	/* Detect current version of schema in the db, if any */
343cd37da74Snw141292 	curr_version = 0;
344cd37da74Snw141292 	if (detect_version_sql != NULL) {
345cd37da74Snw141292 		char *end, **results;
346cd37da74Snw141292 		int nrow;
347cd37da74Snw141292 
348cd37da74Snw141292 #ifdef	IDMAPD_DEBUG
349cd37da74Snw141292 		(void) fprintf(stderr, "Schema version detection SQL: %s\n",
350cd37da74Snw141292 		    detect_version_sql);
351cd37da74Snw141292 #endif	/* IDMAPD_DEBUG */
352cd37da74Snw141292 		rc = sqlite_get_table(db, detect_version_sql, &results,
353cd37da74Snw141292 		    &nrow, NULL, &errmsg);
354cd37da74Snw141292 		if (rc != SQLITE_OK) {
355cd37da74Snw141292 			idmapdlog(prio,
356cd37da74Snw141292 			    "Error detecting schema version of db %s (%s)",
357cd37da74Snw141292 			    dbname, errmsg);
358cd37da74Snw141292 			sqlite_freemem(errmsg);
359cd37da74Snw141292 			sqlite_free_table(results);
360c5c4113dSnw141292 			sqlite_close(db);
361cd37da74Snw141292 			return (-1);
362cd37da74Snw141292 		}
363cd37da74Snw141292 		if (nrow != 1) {
364cd37da74Snw141292 			idmapdlog(prio,
365cd37da74Snw141292 			    "Error detecting schema version of db %s", dbname);
366cd37da74Snw141292 			sqlite_close(db);
367cd37da74Snw141292 			sqlite_free_table(results);
368cd37da74Snw141292 			return (-1);
369cd37da74Snw141292 		}
370cd37da74Snw141292 		curr_version = strtol(results[1], &end, 10);
371cd37da74Snw141292 		sqlite_free_table(results);
372c5c4113dSnw141292 	}
373c5c4113dSnw141292 
374cd37da74Snw141292 	if (curr_version < 0) {
375cd37da74Snw141292 		if (opt == REMOVE_IF_CORRUPT)
376cd37da74Snw141292 			(void) unlink(dbname);
377cd37da74Snw141292 		goto rinse_repeat;
378c5c4113dSnw141292 	}
379c5c4113dSnw141292 
380cd37da74Snw141292 	if (curr_version == version)
381cd37da74Snw141292 		goto done;
382cd37da74Snw141292 
383cd37da74Snw141292 	/* Install or upgrade schema */
384cd37da74Snw141292 #ifdef	IDMAPD_DEBUG
385cd37da74Snw141292 	(void) fprintf(stderr, "Schema init/upgrade SQL: %s\n",
386cd37da74Snw141292 	    sql[curr_version]);
387cd37da74Snw141292 #endif	/* IDMAPD_DEBUG */
388cd37da74Snw141292 	rc = sql_exec_tran_no_cb(db, sql[curr_version], dbname,
389cd37da74Snw141292 	    (curr_version == 0) ? "installing schema" : "upgrading schema");
390cd37da74Snw141292 	if (rc != 0) {
391cd37da74Snw141292 		idmapdlog(prio, "Error %s schema for db %s", dbname,
392cd37da74Snw141292 		    (curr_version == 0) ? "installing schema" :
393cd37da74Snw141292 		    "upgrading schema");
394cd37da74Snw141292 		if (opt == REMOVE_IF_CORRUPT)
395cd37da74Snw141292 			(void) unlink(dbname);
396cd37da74Snw141292 		goto rinse_repeat;
397c5c4113dSnw141292 	}
398c5c4113dSnw141292 
399cd37da74Snw141292 	*upgraded = (curr_version > 0);
400cd37da74Snw141292 	*created = (curr_version == 0);
401cd37da74Snw141292 
402cd37da74Snw141292 done:
403c5c4113dSnw141292 	(void) sqlite_close(db);
404cd37da74Snw141292 	return (0);
405c5c4113dSnw141292 }
406c5c4113dSnw141292 
40784decf41Sjp151216 
40884decf41Sjp151216 /*
40984decf41Sjp151216  * This is the SQLite database busy handler that retries the SQL
41084decf41Sjp151216  * operation until it is successful.
41184decf41Sjp151216  */
41284decf41Sjp151216 int
41384decf41Sjp151216 /* LINTED E_FUNC_ARG_UNUSED */
41484decf41Sjp151216 idmap_sqlite_busy_handler(void *arg, const char *table_name, int count)
41584decf41Sjp151216 {
41684decf41Sjp151216 	struct idmap_busy	*busy = arg;
41784decf41Sjp151216 	int			delay;
41884decf41Sjp151216 	struct timespec		rqtp;
41984decf41Sjp151216 
42084decf41Sjp151216 	if (count == 1)  {
42184decf41Sjp151216 		busy->total = 0;
42284decf41Sjp151216 		busy->sec = 2;
42384decf41Sjp151216 	}
42484decf41Sjp151216 	if (busy->total > 1000 * busy->sec) {
42584decf41Sjp151216 		idmapdlog(LOG_ERR,
42684decf41Sjp151216 		    "Thread %d waited %d sec for the %s database",
42784decf41Sjp151216 		    pthread_self(), busy->sec, busy->name);
42884decf41Sjp151216 		busy->sec++;
42984decf41Sjp151216 	}
43084decf41Sjp151216 
43184decf41Sjp151216 	if (count <= busy->delay_size) {
43284decf41Sjp151216 		delay = busy->delays[count-1];
43384decf41Sjp151216 	} else {
43484decf41Sjp151216 		delay = busy->delays[busy->delay_size - 1];
43584decf41Sjp151216 	}
43684decf41Sjp151216 	busy->total += delay;
43784decf41Sjp151216 	rqtp.tv_sec = 0;
43884decf41Sjp151216 	rqtp.tv_nsec = delay * (NANOSEC / MILLISEC);
43984decf41Sjp151216 	(void) nanosleep(&rqtp, NULL);
44084decf41Sjp151216 	return (1);
44184decf41Sjp151216 }
44284decf41Sjp151216 
44384decf41Sjp151216 
444c5c4113dSnw141292 /*
445c5c4113dSnw141292  * Get the database handle
446c5c4113dSnw141292  */
447c5c4113dSnw141292 idmap_retcode
448cd37da74Snw141292 get_db_handle(sqlite **db)
449cd37da74Snw141292 {
450c5c4113dSnw141292 	char		*errmsg;
45184decf41Sjp151216 	idmap_tsd_t	*tsd;
452c5c4113dSnw141292 
453c5c4113dSnw141292 	/*
45484decf41Sjp151216 	 * Retrieve the db handle from thread-specific storage
455c5c4113dSnw141292 	 * If none exists, open and store in thread-specific storage.
456c5c4113dSnw141292 	 */
45784decf41Sjp151216 	if ((tsd = idmap_get_tsd()) == NULL) {
45884decf41Sjp151216 		idmapdlog(LOG_ERR,
459cd37da74Snw141292 		    "Error getting thread specific data for %s", IDMAP_DBNAME);
46084decf41Sjp151216 		return (IDMAP_ERR_MEMORY);
46184decf41Sjp151216 	}
462c5c4113dSnw141292 
46384decf41Sjp151216 	if (tsd->db_db == NULL) {
46484decf41Sjp151216 		tsd->db_db = sqlite_open(IDMAP_DBNAME, 0, &errmsg);
46584decf41Sjp151216 		if (tsd->db_db == NULL) {
466cd37da74Snw141292 			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
467c5c4113dSnw141292 			    IDMAP_DBNAME, CHECK_NULL(errmsg));
468c5c4113dSnw141292 			sqlite_freemem(errmsg);
469cd37da74Snw141292 			return (IDMAP_ERR_DB);
470c5c4113dSnw141292 		}
471cd37da74Snw141292 
47284decf41Sjp151216 		tsd->db_busy.name = IDMAP_DBNAME;
47384decf41Sjp151216 		tsd->db_busy.delays = db_delay_table;
47484decf41Sjp151216 		tsd->db_busy.delay_size = sizeof (db_delay_table) /
47584decf41Sjp151216 		    sizeof (int);
47684decf41Sjp151216 		sqlite_busy_handler(tsd->db_db, idmap_sqlite_busy_handler,
47784decf41Sjp151216 		    &tsd->db_busy);
47884decf41Sjp151216 	}
47984decf41Sjp151216 	*db = tsd->db_db;
480c5c4113dSnw141292 	return (IDMAP_SUCCESS);
481c5c4113dSnw141292 }
482c5c4113dSnw141292 
483c5c4113dSnw141292 /*
484c5c4113dSnw141292  * Get the cache handle
485c5c4113dSnw141292  */
486c5c4113dSnw141292 idmap_retcode
487cd37da74Snw141292 get_cache_handle(sqlite **cache)
488cd37da74Snw141292 {
489c5c4113dSnw141292 	char		*errmsg;
49084decf41Sjp151216 	idmap_tsd_t	*tsd;
491c5c4113dSnw141292 
492c5c4113dSnw141292 	/*
49384decf41Sjp151216 	 * Retrieve the db handle from thread-specific storage
494c5c4113dSnw141292 	 * If none exists, open and store in thread-specific storage.
495c5c4113dSnw141292 	 */
49684decf41Sjp151216 	if ((tsd = idmap_get_tsd()) == NULL) {
497cd37da74Snw141292 		idmapdlog(LOG_ERR, "Error getting thread specific data for %s",
49884decf41Sjp151216 		    IDMAP_DBNAME);
49984decf41Sjp151216 		return (IDMAP_ERR_MEMORY);
50084decf41Sjp151216 	}
501c5c4113dSnw141292 
50284decf41Sjp151216 	if (tsd->cache_db == NULL) {
50384decf41Sjp151216 		tsd->cache_db = sqlite_open(IDMAP_CACHENAME, 0, &errmsg);
50484decf41Sjp151216 		if (tsd->cache_db == NULL) {
505cd37da74Snw141292 			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
506c5c4113dSnw141292 			    IDMAP_CACHENAME, CHECK_NULL(errmsg));
507c5c4113dSnw141292 			sqlite_freemem(errmsg);
508cd37da74Snw141292 			return (IDMAP_ERR_DB);
509c5c4113dSnw141292 		}
510cd37da74Snw141292 
51184decf41Sjp151216 		tsd->cache_busy.name = IDMAP_CACHENAME;
51284decf41Sjp151216 		tsd->cache_busy.delays = cache_delay_table;
51384decf41Sjp151216 		tsd->cache_busy.delay_size = sizeof (cache_delay_table) /
51484decf41Sjp151216 		    sizeof (int);
51584decf41Sjp151216 		sqlite_busy_handler(tsd->cache_db, idmap_sqlite_busy_handler,
51684decf41Sjp151216 		    &tsd->cache_busy);
51784decf41Sjp151216 	}
51884decf41Sjp151216 	*cache = tsd->cache_db;
519c5c4113dSnw141292 	return (IDMAP_SUCCESS);
520c5c4113dSnw141292 }
521c5c4113dSnw141292 
522c5c4113dSnw141292 /*
523c5c4113dSnw141292  * Initialize cache and db
524c5c4113dSnw141292  */
525c5c4113dSnw141292 int
526cd37da74Snw141292 init_dbs()
527cd37da74Snw141292 {
528cd37da74Snw141292 	char *sql[2];
529cd37da74Snw141292 	int created, upgraded;
530cd37da74Snw141292 
531c5c4113dSnw141292 	/* name-based mappings; probably OK to blow away in a pinch(?) */
532cd37da74Snw141292 	sql[0] = DB_INSTALL_SQL;
533cd37da74Snw141292 	sql[1] = DB_UPGRADE_FROM_v1_SQL;
534cd37da74Snw141292 
535cd37da74Snw141292 	if (init_db_instance(IDMAP_DBNAME, DB_VERSION, DB_VERSION_SQL, sql,
536cd37da74Snw141292 	    FAIL_IF_CORRUPT, &created, &upgraded) < 0)
537c5c4113dSnw141292 		return (-1);
538c5c4113dSnw141292 
539c5c4113dSnw141292 	/* mappings, name/SID lookup cache + ephemeral IDs; OK to blow away */
540cd37da74Snw141292 	sql[0] = CACHE_INSTALL_SQL;
541cd37da74Snw141292 	sql[1] = CACHE_UPGRADE_FROM_v1_SQL;
542cd37da74Snw141292 	if (init_db_instance(IDMAP_CACHENAME, CACHE_VERSION, CACHE_VERSION_SQL,
543cd37da74Snw141292 	    sql, REMOVE_IF_CORRUPT, &created, &upgraded) < 0)
544c5c4113dSnw141292 		return (-1);
545c5c4113dSnw141292 
546cd37da74Snw141292 	_idmapdstate.new_eph_db = (created || upgraded) ? 1 : 0;
547cd37da74Snw141292 
548c5c4113dSnw141292 	return (0);
549c5c4113dSnw141292 }
550c5c4113dSnw141292 
551c5c4113dSnw141292 /*
552c5c4113dSnw141292  * Finalize databases
553c5c4113dSnw141292  */
554c5c4113dSnw141292 void
555cd37da74Snw141292 fini_dbs()
556cd37da74Snw141292 {
557c5c4113dSnw141292 }
558c5c4113dSnw141292 
559c5c4113dSnw141292 /*
560*e8c27ec8Sbaban  * This table is a listing of status codes that will be returned to the
561c5c4113dSnw141292  * client when a SQL command fails with the corresponding error message.
562c5c4113dSnw141292  */
563c5c4113dSnw141292 static msg_table_t sqlmsgtable[] = {
56462c60062Sbaban 	{IDMAP_ERR_U2W_NAMERULE_CONFLICT,
565c5c4113dSnw141292 	"columns unixname, is_user, u2w_order are not unique"},
56662c60062Sbaban 	{IDMAP_ERR_W2U_NAMERULE_CONFLICT,
567cd37da74Snw141292 	"columns winname, windomain, is_user, is_wuser, w2u_order are not"
568cd37da74Snw141292 	" unique"},
569cd37da74Snw141292 	{IDMAP_ERR_W2U_NAMERULE_CONFLICT, "Conflicting w2u namerules"},
570c5c4113dSnw141292 	{-1, NULL}
571c5c4113dSnw141292 };
572c5c4113dSnw141292 
573c5c4113dSnw141292 /*
574c5c4113dSnw141292  * idmapd's version of string2stat to map SQLite messages to
575c5c4113dSnw141292  * status codes
576c5c4113dSnw141292  */
577c5c4113dSnw141292 idmap_retcode
578cd37da74Snw141292 idmapd_string2stat(const char *msg)
579cd37da74Snw141292 {
580c5c4113dSnw141292 	int i;
581c5c4113dSnw141292 	for (i = 0; sqlmsgtable[i].msg; i++) {
582c5c4113dSnw141292 		if (strcasecmp(sqlmsgtable[i].msg, msg) == 0)
583c5c4113dSnw141292 			return (sqlmsgtable[i].retcode);
584c5c4113dSnw141292 	}
585c5c4113dSnw141292 	return (IDMAP_ERR_OTHER);
586c5c4113dSnw141292 }
587c5c4113dSnw141292 
588c5c4113dSnw141292 /*
589cd37da74Snw141292  * Executes some SQL in a transaction.
590cd37da74Snw141292  *
591cd37da74Snw141292  * Returns 0 on success, -1 if it failed but the rollback succeeded, -2
592cd37da74Snw141292  * if the rollback failed.
593cd37da74Snw141292  */
594cd37da74Snw141292 static
595cd37da74Snw141292 int
596cd37da74Snw141292 sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
597cd37da74Snw141292 	const char *while_doing)
598cd37da74Snw141292 {
599cd37da74Snw141292 	char		*errmsg = NULL;
600cd37da74Snw141292 	int		rc;
601cd37da74Snw141292 
602cd37da74Snw141292 	rc = sqlite_exec(db, "BEGIN TRANSACTION;", NULL, NULL, &errmsg);
603cd37da74Snw141292 	if (rc != SQLITE_OK) {
604cd37da74Snw141292 		idmapdlog(LOG_ERR, "Begin transaction failed (%s) "
605cd37da74Snw141292 		    "while %s (%s)", errmsg, while_doing, dbname);
606cd37da74Snw141292 		sqlite_freemem(errmsg);
607cd37da74Snw141292 		return (-1);
608cd37da74Snw141292 	}
609cd37da74Snw141292 
610cd37da74Snw141292 	rc = sqlite_exec(db, sql, NULL, NULL, &errmsg);
611cd37da74Snw141292 	if (rc != SQLITE_OK) {
612cd37da74Snw141292 		idmapdlog(LOG_ERR, "Database error (%s) while %s (%s)", errmsg,
613cd37da74Snw141292 		    while_doing, dbname);
614cd37da74Snw141292 		sqlite_freemem(errmsg);
615cd37da74Snw141292 		errmsg = NULL;
616cd37da74Snw141292 		goto rollback;
617cd37da74Snw141292 	}
618cd37da74Snw141292 
619cd37da74Snw141292 	rc = sqlite_exec(db, "COMMIT TRANSACTION", NULL, NULL, &errmsg);
620cd37da74Snw141292 	if (rc == SQLITE_OK) {
621cd37da74Snw141292 		sqlite_freemem(errmsg);
622cd37da74Snw141292 		return (0);
623cd37da74Snw141292 	}
624cd37da74Snw141292 
625cd37da74Snw141292 	idmapdlog(LOG_ERR, "Database commit error (%s) while s (%s)",
626cd37da74Snw141292 	    errmsg, while_doing, dbname);
627cd37da74Snw141292 	sqlite_freemem(errmsg);
628cd37da74Snw141292 	errmsg = NULL;
629cd37da74Snw141292 
630cd37da74Snw141292 rollback:
631cd37da74Snw141292 	rc = sqlite_exec(db, "ROLLBACK TRANSACTION", NULL, NULL, &errmsg);
632cd37da74Snw141292 	if (rc != SQLITE_OK) {
633cd37da74Snw141292 		idmapdlog(LOG_ERR, "Rollback failed (%s) while %s (%s)",
634cd37da74Snw141292 		    errmsg, while_doing, dbname);
635cd37da74Snw141292 		sqlite_freemem(errmsg);
636cd37da74Snw141292 		return (-2);
637cd37da74Snw141292 	}
638cd37da74Snw141292 	sqlite_freemem(errmsg);
639cd37da74Snw141292 
640cd37da74Snw141292 	return (-1);
641cd37da74Snw141292 }
642cd37da74Snw141292 
643cd37da74Snw141292 /*
644c5c4113dSnw141292  * Execute the given SQL statment without using any callbacks
645c5c4113dSnw141292  */
646c5c4113dSnw141292 idmap_retcode
647cd37da74Snw141292 sql_exec_no_cb(sqlite *db, char *sql)
648cd37da74Snw141292 {
649c5c4113dSnw141292 	char		*errmsg = NULL;
65084decf41Sjp151216 	int		r;
651c5c4113dSnw141292 	idmap_retcode	retcode;
652c5c4113dSnw141292 
653c5c4113dSnw141292 	r = sqlite_exec(db, sql, NULL, NULL, &errmsg);
65484decf41Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
655c5c4113dSnw141292 
656c5c4113dSnw141292 	if (r != SQLITE_OK) {
657cd37da74Snw141292 		idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
658cd37da74Snw141292 		    CHECK_NULL(errmsg));
659c5c4113dSnw141292 		retcode = idmapd_string2stat(errmsg);
66062c60062Sbaban 		if (errmsg != NULL)
661c5c4113dSnw141292 			sqlite_freemem(errmsg);
662c5c4113dSnw141292 		return (retcode);
663c5c4113dSnw141292 	}
664c5c4113dSnw141292 
665c5c4113dSnw141292 	return (IDMAP_SUCCESS);
666c5c4113dSnw141292 }
667c5c4113dSnw141292 
668c5c4113dSnw141292 /*
669c5c4113dSnw141292  * Generate expression that can be used in WHERE statements.
670c5c4113dSnw141292  * Examples:
671c5c4113dSnw141292  * <prefix> <col>      <op> <value>   <suffix>
672c5c4113dSnw141292  * ""       "unixuser" "="  "foo" "AND"
673c5c4113dSnw141292  */
674c5c4113dSnw141292 idmap_retcode
675cd37da74Snw141292 gen_sql_expr_from_rule(idmap_namerule *rule, char **out)
676cd37da74Snw141292 {
677cd37da74Snw141292 	char	*s_windomain = NULL, *s_winname = NULL;
678cd37da74Snw141292 	char	*s_unixname = NULL;
679cd37da74Snw141292 	char	*lower_winname;
680cd37da74Snw141292 	int	retcode = IDMAP_SUCCESS;
681cd37da74Snw141292 
682c5c4113dSnw141292 	if (out == NULL)
683c5c4113dSnw141292 		return (IDMAP_ERR_ARG);
684c5c4113dSnw141292 
685c5c4113dSnw141292 
686cd37da74Snw141292 	if (!EMPTY_STRING(rule->windomain)) {
687cd37da74Snw141292 		s_windomain =  sqlite_mprintf("AND windomain = %Q ",
688cd37da74Snw141292 		    rule->windomain);
689cd37da74Snw141292 		if (s_windomain == NULL) {
690cd37da74Snw141292 			retcode = IDMAP_ERR_MEMORY;
691cd37da74Snw141292 			goto out;
692c5c4113dSnw141292 		}
693cd37da74Snw141292 	}
694cd37da74Snw141292 
695cd37da74Snw141292 	if (!EMPTY_STRING(rule->winname)) {
696cd37da74Snw141292 		if ((lower_winname = tolower_u8(rule->winname)) == NULL)
697cd37da74Snw141292 			lower_winname = rule->winname;
698cd37da74Snw141292 		s_winname = sqlite_mprintf(
699cd37da74Snw141292 		    "AND winname = %Q AND is_wuser = %d ",
700cd37da74Snw141292 		    lower_winname, rule->is_wuser ? 1 : 0);
701cd37da74Snw141292 		if (lower_winname != rule->winname)
702cd37da74Snw141292 			free(lower_winname);
703cd37da74Snw141292 		if (s_winname == NULL) {
704cd37da74Snw141292 			retcode = IDMAP_ERR_MEMORY;
705cd37da74Snw141292 			goto out;
706cd37da74Snw141292 		}
707cd37da74Snw141292 	}
708cd37da74Snw141292 
709cd37da74Snw141292 	if (!EMPTY_STRING(rule->unixname)) {
710cd37da74Snw141292 		s_unixname = sqlite_mprintf(
711cd37da74Snw141292 		    "AND unixname = %Q AND is_user = %d ",
712cd37da74Snw141292 		    rule->unixname, rule->is_user ? 1 : 0);
713cd37da74Snw141292 		if (s_unixname == NULL) {
714cd37da74Snw141292 			retcode = IDMAP_ERR_MEMORY;
715cd37da74Snw141292 			goto out;
716cd37da74Snw141292 		}
717cd37da74Snw141292 	}
718cd37da74Snw141292 
719cd37da74Snw141292 	*out = sqlite_mprintf("%s %s %s",
720cd37da74Snw141292 	    s_windomain ? s_windomain : "",
721cd37da74Snw141292 	    s_winname ? s_winname : "",
722cd37da74Snw141292 	    s_unixname ? s_unixname : "");
723cd37da74Snw141292 
724cd37da74Snw141292 	if (*out == NULL) {
725cd37da74Snw141292 		retcode = IDMAP_ERR_MEMORY;
726cd37da74Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
727cd37da74Snw141292 		goto out;
728cd37da74Snw141292 	}
729cd37da74Snw141292 
730cd37da74Snw141292 out:
731cd37da74Snw141292 	if (s_windomain != NULL)
732cd37da74Snw141292 		sqlite_freemem(s_windomain);
733cd37da74Snw141292 	if (s_winname != NULL)
734cd37da74Snw141292 		sqlite_freemem(s_winname);
735cd37da74Snw141292 	if (s_unixname != NULL)
736cd37da74Snw141292 		sqlite_freemem(s_unixname);
737cd37da74Snw141292 
738cd37da74Snw141292 	return (retcode);
739cd37da74Snw141292 }
740cd37da74Snw141292 
741cd37da74Snw141292 
742c5c4113dSnw141292 
743c5c4113dSnw141292 /*
744c5c4113dSnw141292  * Generate and execute SQL statement for LIST RPC calls
745c5c4113dSnw141292  */
746c5c4113dSnw141292 idmap_retcode
747c5c4113dSnw141292 process_list_svc_sql(sqlite *db, char *sql, uint64_t limit,
748cd37da74Snw141292 		list_svc_cb cb, void *result)
749cd37da74Snw141292 {
750c5c4113dSnw141292 	list_cb_data_t	cb_data;
751c5c4113dSnw141292 	char		*errmsg = NULL;
75284decf41Sjp151216 	int		r;
753c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_ERR_INTERNAL;
754c5c4113dSnw141292 
755c5c4113dSnw141292 	(void) memset(&cb_data, 0, sizeof (cb_data));
756c5c4113dSnw141292 	cb_data.result = result;
757c5c4113dSnw141292 	cb_data.limit = limit;
758c5c4113dSnw141292 
75984decf41Sjp151216 
760c5c4113dSnw141292 	r = sqlite_exec(db, sql, cb, &cb_data, &errmsg);
76184decf41Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
762c5c4113dSnw141292 	switch (r) {
763c5c4113dSnw141292 	case SQLITE_OK:
764c5c4113dSnw141292 		retcode = IDMAP_SUCCESS;
76584decf41Sjp151216 		break;
76684decf41Sjp151216 
767c5c4113dSnw141292 	default:
768c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
769cd37da74Snw141292 		idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
770cd37da74Snw141292 		    CHECK_NULL(errmsg));
77184decf41Sjp151216 		break;
772c5c4113dSnw141292 	}
77362c60062Sbaban 	if (errmsg != NULL)
774c5c4113dSnw141292 		sqlite_freemem(errmsg);
775c5c4113dSnw141292 	return (retcode);
776c5c4113dSnw141292 }
777c5c4113dSnw141292 
778c5c4113dSnw141292 /*
779c5c4113dSnw141292  * This routine is called by callbacks that process the results of
780c5c4113dSnw141292  * LIST RPC calls to validate data and to allocate memory for
781c5c4113dSnw141292  * the result array.
782c5c4113dSnw141292  */
783c5c4113dSnw141292 idmap_retcode
784c5c4113dSnw141292 validate_list_cb_data(list_cb_data_t *cb_data, int argc, char **argv,
785cd37da74Snw141292 		int ncol, uchar_t **list, size_t valsize)
786cd37da74Snw141292 {
787c5c4113dSnw141292 	size_t	nsize;
788c5c4113dSnw141292 	void	*tmplist;
789c5c4113dSnw141292 
790c5c4113dSnw141292 	if (cb_data->limit > 0 && cb_data->next == cb_data->limit)
791c5c4113dSnw141292 		return (IDMAP_NEXT);
792c5c4113dSnw141292 
793c5c4113dSnw141292 	if (argc < ncol || argv == NULL) {
794c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Invalid data");
795c5c4113dSnw141292 		return (IDMAP_ERR_INTERNAL);
796c5c4113dSnw141292 	}
797c5c4113dSnw141292 
798c5c4113dSnw141292 	/* alloc in bulk to reduce number of reallocs */
799c5c4113dSnw141292 	if (cb_data->next >= cb_data->len) {
800c5c4113dSnw141292 		nsize = (cb_data->len + SIZE_INCR) * valsize;
801c5c4113dSnw141292 		tmplist = realloc(*list, nsize);
802c5c4113dSnw141292 		if (tmplist == NULL) {
803c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
804c5c4113dSnw141292 			return (IDMAP_ERR_MEMORY);
805c5c4113dSnw141292 		}
806c5c4113dSnw141292 		*list = tmplist;
807c5c4113dSnw141292 		(void) memset(*list + (cb_data->len * valsize), 0,
808c5c4113dSnw141292 		    SIZE_INCR * valsize);
809c5c4113dSnw141292 		cb_data->len += SIZE_INCR;
810c5c4113dSnw141292 	}
811c5c4113dSnw141292 	return (IDMAP_SUCCESS);
812c5c4113dSnw141292 }
813c5c4113dSnw141292 
814cd37da74Snw141292 static
815cd37da74Snw141292 idmap_retcode
816c5c4113dSnw141292 get_namerule_order(char *winname, char *windomain, char *unixname,
817cd37da74Snw141292 	int direction, int is_diagonal, int *w2u_order, int *u2w_order)
818cd37da74Snw141292 {
819c5c4113dSnw141292 	*w2u_order = 0;
820c5c4113dSnw141292 	*u2w_order = 0;
821c5c4113dSnw141292 
822c5c4113dSnw141292 	/*
823c5c4113dSnw141292 	 * Windows to UNIX lookup order:
824c5c4113dSnw141292 	 *  1. winname@domain (or winname) to ""
825c5c4113dSnw141292 	 *  2. winname@domain (or winname) to unixname
826c5c4113dSnw141292 	 *  3. winname@* to ""
827c5c4113dSnw141292 	 *  4. winname@* to unixname
828c5c4113dSnw141292 	 *  5. *@domain (or *) to *
829c5c4113dSnw141292 	 *  6. *@domain (or *) to ""
830c5c4113dSnw141292 	 *  7. *@domain (or *) to unixname
831c5c4113dSnw141292 	 *  8. *@* to *
832c5c4113dSnw141292 	 *  9. *@* to ""
833c5c4113dSnw141292 	 * 10. *@* to unixname
834c5c4113dSnw141292 	 *
835c5c4113dSnw141292 	 * winname is a special case of winname@domain when domain is the
836c5c4113dSnw141292 	 * default domain. Similarly * is a special case of *@domain when
837c5c4113dSnw141292 	 * domain is the default domain.
838c5c4113dSnw141292 	 *
839c5c4113dSnw141292 	 * Note that "" has priority over specific names because "" inhibits
840c5c4113dSnw141292 	 * mappings and traditionally deny rules always had higher priority.
841c5c4113dSnw141292 	 */
842651c0131Sbaban 	if (direction != IDMAP_DIRECTION_U2W) {
843651c0131Sbaban 		/* bi-directional or from windows to unix */
844c5c4113dSnw141292 		if (winname == NULL)
845c5c4113dSnw141292 			return (IDMAP_ERR_W2U_NAMERULE);
846c5c4113dSnw141292 		else if (unixname == NULL)
847c5c4113dSnw141292 			return (IDMAP_ERR_W2U_NAMERULE);
848c5c4113dSnw141292 		else if (EMPTY_NAME(winname))
849c5c4113dSnw141292 			return (IDMAP_ERR_W2U_NAMERULE);
850c5c4113dSnw141292 		else if (*winname == '*' && windomain && *windomain == '*') {
851c5c4113dSnw141292 			if (*unixname == '*')
852c5c4113dSnw141292 				*w2u_order = 8;
853c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
854c5c4113dSnw141292 				*w2u_order = 9;
855c5c4113dSnw141292 			else /* unixname == name */
856c5c4113dSnw141292 				*w2u_order = 10;
857c5c4113dSnw141292 		} else if (*winname == '*') {
858c5c4113dSnw141292 			if (*unixname == '*')
859c5c4113dSnw141292 				*w2u_order = 5;
860c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
861c5c4113dSnw141292 				*w2u_order = 6;
862c5c4113dSnw141292 			else /* name */
863c5c4113dSnw141292 				*w2u_order = 7;
86462c60062Sbaban 		} else if (windomain != NULL && *windomain == '*') {
865c5c4113dSnw141292 			/* winname == name */
866c5c4113dSnw141292 			if (*unixname == '*')
867c5c4113dSnw141292 				return (IDMAP_ERR_W2U_NAMERULE);
868c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
869c5c4113dSnw141292 				*w2u_order = 3;
870c5c4113dSnw141292 			else /* name */
871c5c4113dSnw141292 				*w2u_order = 4;
872c5c4113dSnw141292 		} else  {
873c5c4113dSnw141292 			/* winname == name && windomain == null or name */
874c5c4113dSnw141292 			if (*unixname == '*')
875c5c4113dSnw141292 				return (IDMAP_ERR_W2U_NAMERULE);
876c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
877c5c4113dSnw141292 				*w2u_order = 1;
878c5c4113dSnw141292 			else /* name */
879c5c4113dSnw141292 				*w2u_order = 2;
880c5c4113dSnw141292 		}
881cd37da74Snw141292 
882c5c4113dSnw141292 	}
883c5c4113dSnw141292 
884c5c4113dSnw141292 	/*
885cd37da74Snw141292 	 * 1. unixname to "", non-diagonal
886cd37da74Snw141292 	 * 2. unixname to winname@domain (or winname), non-diagonal
887cd37da74Snw141292 	 * 3. unixname to "", diagonal
888cd37da74Snw141292 	 * 4. unixname to winname@domain (or winname), diagonal
889cd37da74Snw141292 	 * 5. * to *@domain (or *), non-diagonal
890cd37da74Snw141292 	 * 5. * to *@domain (or *), diagonal
891cd37da74Snw141292 	 * 7. * to ""
892cd37da74Snw141292 	 * 8. * to winname@domain (or winname)
893cd37da74Snw141292 	 * 9. * to "", non-diagonal
894cd37da74Snw141292 	 * 10. * to winname@domain (or winname), diagonal
895c5c4113dSnw141292 	 */
896651c0131Sbaban 	if (direction != IDMAP_DIRECTION_W2U) {
897cd37da74Snw141292 		int diagonal = is_diagonal ? 1 : 0;
898cd37da74Snw141292 
899651c0131Sbaban 		/* bi-directional or from unix to windows */
900c5c4113dSnw141292 		if (unixname == NULL || EMPTY_NAME(unixname))
901c5c4113dSnw141292 			return (IDMAP_ERR_U2W_NAMERULE);
902c5c4113dSnw141292 		else if (winname == NULL)
903c5c4113dSnw141292 			return (IDMAP_ERR_U2W_NAMERULE);
90462c60062Sbaban 		else if (windomain != NULL && *windomain == '*')
905651c0131Sbaban 			return (IDMAP_ERR_U2W_NAMERULE);
906c5c4113dSnw141292 		else if (*unixname == '*') {
907c5c4113dSnw141292 			if (*winname == '*')
908cd37da74Snw141292 				*u2w_order = 5 + diagonal;
909c5c4113dSnw141292 			else if (EMPTY_NAME(winname))
910cd37da74Snw141292 				*u2w_order = 7 + 2 * diagonal;
911c5c4113dSnw141292 			else
912cd37da74Snw141292 				*u2w_order = 8 + 2 * diagonal;
913c5c4113dSnw141292 		} else {
914c5c4113dSnw141292 			if (*winname == '*')
915c5c4113dSnw141292 				return (IDMAP_ERR_U2W_NAMERULE);
916c5c4113dSnw141292 			else if (EMPTY_NAME(winname))
917cd37da74Snw141292 				*u2w_order = 1 + 2 * diagonal;
918c5c4113dSnw141292 			else
919cd37da74Snw141292 				*u2w_order = 2 + 2 * diagonal;
920c5c4113dSnw141292 		}
921c5c4113dSnw141292 	}
922c5c4113dSnw141292 	return (IDMAP_SUCCESS);
923c5c4113dSnw141292 }
924c5c4113dSnw141292 
925c5c4113dSnw141292 /*
926c5c4113dSnw141292  * Generate and execute SQL statement to add name-based mapping rule
927c5c4113dSnw141292  */
928c5c4113dSnw141292 idmap_retcode
929cd37da74Snw141292 add_namerule(sqlite *db, idmap_namerule *rule)
930cd37da74Snw141292 {
931c5c4113dSnw141292 	char		*sql = NULL;
932c5c4113dSnw141292 	idmap_stat	retcode;
9338e228215Sdm199847 	char		*dom = NULL;
934c5c4113dSnw141292 	int		w2u_order, u2w_order;
935c5c4113dSnw141292 	char		w2ubuf[11], u2wbuf[11];
936c5c4113dSnw141292 
9378e228215Sdm199847 	retcode = get_namerule_order(rule->winname, rule->windomain,
938cd37da74Snw141292 	    rule->unixname, rule->direction,
939cd37da74Snw141292 	    rule->is_user == rule->is_wuser ? 0 : 1, &w2u_order, &u2w_order);
940c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
941c5c4113dSnw141292 		goto out;
942c5c4113dSnw141292 
943c5c4113dSnw141292 	if (w2u_order)
944c5c4113dSnw141292 		(void) snprintf(w2ubuf, sizeof (w2ubuf), "%d", w2u_order);
945c5c4113dSnw141292 	if (u2w_order)
946c5c4113dSnw141292 		(void) snprintf(u2wbuf, sizeof (u2wbuf), "%d", u2w_order);
947c5c4113dSnw141292 
94862c60062Sbaban 	/*
94962c60062Sbaban 	 * For the triggers on namerules table to work correctly:
95062c60062Sbaban 	 * 1) Use NULL instead of 0 for w2u_order and u2w_order
95162c60062Sbaban 	 * 2) Use "" instead of NULL for "no domain"
95262c60062Sbaban 	 */
95362c60062Sbaban 
954*e8c27ec8Sbaban 	if (!EMPTY_STRING(rule->windomain))
9558e228215Sdm199847 		dom = rule->windomain;
956cd37da74Snw141292 	else if (lookup_wksids_name2sid(rule->winname, NULL, NULL, NULL, NULL)
95762c60062Sbaban 	    == IDMAP_SUCCESS) {
95862c60062Sbaban 		/* well-known SIDs don't need domain */
95962c60062Sbaban 		dom = "";
96062c60062Sbaban 	}
961c5c4113dSnw141292 
962c5c4113dSnw141292 	RDLOCK_CONFIG();
96362c60062Sbaban 	if (dom == NULL) {
964c8e26105Sjp151216 		if (_idmapdstate.cfg->pgcfg.default_domain)
965c8e26105Sjp151216 			dom = _idmapdstate.cfg->pgcfg.default_domain;
966c5c4113dSnw141292 		else
967c5c4113dSnw141292 			dom = "";
96862c60062Sbaban 	}
96984decf41Sjp151216 	sql = sqlite_mprintf("INSERT into namerules "
970cd37da74Snw141292 	    "(is_user, is_wuser, windomain, winname_display, is_nt4, "
971c5c4113dSnw141292 	    "unixname, w2u_order, u2w_order) "
972cd37da74Snw141292 	    "VALUES(%d, %d, %Q, %Q, %d, %Q, %q, %q);",
973cd37da74Snw141292 	    rule->is_user ? 1 : 0, rule->is_wuser ? 1 : 0, dom,
974cd37da74Snw141292 	    rule->winname, rule->is_nt4 ? 1 : 0, rule->unixname,
975cd37da74Snw141292 	    w2u_order ? w2ubuf : NULL, u2w_order ? u2wbuf : NULL);
976c5c4113dSnw141292 	UNLOCK_CONFIG();
977c5c4113dSnw141292 
978c5c4113dSnw141292 	if (sql == NULL) {
979c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
980c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
981c5c4113dSnw141292 		goto out;
982c5c4113dSnw141292 	}
983c5c4113dSnw141292 
984c5c4113dSnw141292 	retcode = sql_exec_no_cb(db, sql);
985c5c4113dSnw141292 
986c5c4113dSnw141292 	if (retcode == IDMAP_ERR_OTHER)
987c5c4113dSnw141292 		retcode = IDMAP_ERR_CFG;
988c5c4113dSnw141292 
989c5c4113dSnw141292 out:
99062c60062Sbaban 	if (sql != NULL)
991c5c4113dSnw141292 		sqlite_freemem(sql);
992c5c4113dSnw141292 	return (retcode);
993c5c4113dSnw141292 }
994c5c4113dSnw141292 
995c5c4113dSnw141292 /*
996c5c4113dSnw141292  * Flush name-based mapping rules
997c5c4113dSnw141292  */
998c5c4113dSnw141292 idmap_retcode
999cd37da74Snw141292 flush_namerules(sqlite *db)
1000cd37da74Snw141292 {
1001c5c4113dSnw141292 	idmap_stat	retcode;
1002c5c4113dSnw141292 
1003cd37da74Snw141292 	retcode = sql_exec_no_cb(db, "DELETE FROM namerules;");
1004c5c4113dSnw141292 
1005c5c4113dSnw141292 	return (retcode);
1006c5c4113dSnw141292 }
1007c5c4113dSnw141292 
1008c5c4113dSnw141292 /*
1009c5c4113dSnw141292  * Generate and execute SQL statement to remove a name-based mapping rule
1010c5c4113dSnw141292  */
1011c5c4113dSnw141292 idmap_retcode
1012cd37da74Snw141292 rm_namerule(sqlite *db, idmap_namerule *rule)
1013cd37da74Snw141292 {
1014c5c4113dSnw141292 	char		*sql = NULL;
1015c5c4113dSnw141292 	idmap_stat	retcode;
1016c5c4113dSnw141292 	char		buf[80];
1017cd37da74Snw141292 	char		*expr = NULL;
1018c5c4113dSnw141292 
10198e228215Sdm199847 	if (rule->direction < 0 && EMPTY_STRING(rule->windomain) &&
10208e228215Sdm199847 	    EMPTY_STRING(rule->winname) && EMPTY_STRING(rule->unixname))
1021c5c4113dSnw141292 		return (IDMAP_SUCCESS);
1022c5c4113dSnw141292 
1023c5c4113dSnw141292 	buf[0] = 0;
1024cd37da74Snw141292 
1025cd37da74Snw141292 	if (rule->direction == IDMAP_DIRECTION_BI)
1026c5c4113dSnw141292 		(void) snprintf(buf, sizeof (buf), "AND w2u_order > 0"
1027c5c4113dSnw141292 		    " AND u2w_order > 0");
1028cd37da74Snw141292 	else if (rule->direction == IDMAP_DIRECTION_W2U)
1029c5c4113dSnw141292 		(void) snprintf(buf, sizeof (buf), "AND w2u_order > 0"
1030c5c4113dSnw141292 		    " AND (u2w_order = 0 OR u2w_order ISNULL)");
1031cd37da74Snw141292 	else if (rule->direction == IDMAP_DIRECTION_U2W)
1032c5c4113dSnw141292 		(void) snprintf(buf, sizeof (buf), "AND u2w_order > 0"
1033c5c4113dSnw141292 		    " AND (w2u_order = 0 OR w2u_order ISNULL)");
1034c5c4113dSnw141292 
1035cd37da74Snw141292 	retcode = gen_sql_expr_from_rule(rule, &expr);
1036cd37da74Snw141292 	if (retcode != IDMAP_SUCCESS)
1037c5c4113dSnw141292 		goto out;
1038c5c4113dSnw141292 
1039cd37da74Snw141292 	sql = sqlite_mprintf("DELETE FROM namerules WHERE 1 %s %s;", expr,
1040c5c4113dSnw141292 	    buf);
1041c5c4113dSnw141292 
1042c5c4113dSnw141292 	if (sql == NULL) {
1043c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
1044c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
1045c5c4113dSnw141292 		goto out;
1046c5c4113dSnw141292 	}
1047c5c4113dSnw141292 
1048cd37da74Snw141292 
1049c5c4113dSnw141292 	retcode = sql_exec_no_cb(db, sql);
1050c5c4113dSnw141292 
1051c5c4113dSnw141292 out:
1052cd37da74Snw141292 	if (expr != NULL)
1053cd37da74Snw141292 		sqlite_freemem(expr);
105462c60062Sbaban 	if (sql != NULL)
1055c5c4113dSnw141292 		sqlite_freemem(sql);
1056c5c4113dSnw141292 	return (retcode);
1057c5c4113dSnw141292 }
1058c5c4113dSnw141292 
1059c5c4113dSnw141292 /*
1060c5c4113dSnw141292  * Compile the given SQL query and step just once.
1061c5c4113dSnw141292  *
1062c5c4113dSnw141292  * Input:
1063c5c4113dSnw141292  * db  - db handle
1064c5c4113dSnw141292  * sql - SQL statement
1065c5c4113dSnw141292  *
1066c5c4113dSnw141292  * Output:
1067c5c4113dSnw141292  * vm     -  virtual SQL machine
1068c5c4113dSnw141292  * ncol   - number of columns in the result
1069c5c4113dSnw141292  * values - column values
1070c5c4113dSnw141292  *
1071c5c4113dSnw141292  * Return values:
1072c5c4113dSnw141292  * IDMAP_SUCCESS
1073c5c4113dSnw141292  * IDMAP_ERR_NOTFOUND
1074c5c4113dSnw141292  * IDMAP_ERR_INTERNAL
1075c5c4113dSnw141292  */
1076c5c4113dSnw141292 
1077cd37da74Snw141292 static
1078cd37da74Snw141292 idmap_retcode
1079c5c4113dSnw141292 sql_compile_n_step_once(sqlite *db, char *sql, sqlite_vm **vm, int *ncol,
1080cd37da74Snw141292 		int reqcol, const char ***values)
1081cd37da74Snw141292 {
1082c5c4113dSnw141292 	char		*errmsg = NULL;
108384decf41Sjp151216 	int		r;
1084c5c4113dSnw141292 
108584decf41Sjp151216 	if ((r = sqlite_compile(db, sql, NULL, vm, &errmsg)) != SQLITE_OK) {
1086cd37da74Snw141292 		idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
1087cd37da74Snw141292 		    CHECK_NULL(errmsg));
1088c5c4113dSnw141292 		sqlite_freemem(errmsg);
1089c5c4113dSnw141292 		return (IDMAP_ERR_INTERNAL);
1090c5c4113dSnw141292 	}
1091c5c4113dSnw141292 
1092c5c4113dSnw141292 	r = sqlite_step(*vm, ncol, values, NULL);
109384decf41Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
1094c5c4113dSnw141292 
109584decf41Sjp151216 	if (r == SQLITE_ROW) {
109662c60062Sbaban 		if (ncol != NULL && *ncol < reqcol) {
1097c5c4113dSnw141292 			(void) sqlite_finalize(*vm, NULL);
1098c5c4113dSnw141292 			*vm = NULL;
1099c5c4113dSnw141292 			return (IDMAP_ERR_INTERNAL);
1100c5c4113dSnw141292 		}
1101c5c4113dSnw141292 		/* Caller will call finalize after using the results */
1102c5c4113dSnw141292 		return (IDMAP_SUCCESS);
1103c5c4113dSnw141292 	} else if (r == SQLITE_DONE) {
1104c5c4113dSnw141292 		(void) sqlite_finalize(*vm, NULL);
1105c5c4113dSnw141292 		*vm = NULL;
1106c5c4113dSnw141292 		return (IDMAP_ERR_NOTFOUND);
1107c5c4113dSnw141292 	}
1108c5c4113dSnw141292 
1109c5c4113dSnw141292 	(void) sqlite_finalize(*vm, &errmsg);
1110c5c4113dSnw141292 	*vm = NULL;
1111cd37da74Snw141292 	idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
1112cd37da74Snw141292 	    CHECK_NULL(errmsg));
1113c5c4113dSnw141292 	sqlite_freemem(errmsg);
1114c5c4113dSnw141292 	return (IDMAP_ERR_INTERNAL);
1115c5c4113dSnw141292 }
1116c5c4113dSnw141292 
111762c60062Sbaban /*
1118*e8c27ec8Sbaban  * Update nm_siduid and nm_sidgid fields in the lookup state.
1119*e8c27ec8Sbaban  *
1120*e8c27ec8Sbaban  * state->nm_siduid represents mode used by sid2uid and uid2sid
1121*e8c27ec8Sbaban  * requests for directory-based name mappings. Similarly,
1122*e8c27ec8Sbaban  * state->nm_sidgid represents mode used by sid2gid and gid2sid
1123*e8c27ec8Sbaban  * requests.
1124*e8c27ec8Sbaban  *
1125*e8c27ec8Sbaban  * sid2uid/uid2sid:
1126*e8c27ec8Sbaban  * none       -> ds_name_mapping_enabled != true
1127*e8c27ec8Sbaban  * AD-mode    -> !nldap_winname_attr && ad_unixuser_attr
1128*e8c27ec8Sbaban  * nldap-mode -> nldap_winname_attr && !ad_unixuser_attr
1129*e8c27ec8Sbaban  * mixed-mode -> nldap_winname_attr && ad_unixuser_attr
1130*e8c27ec8Sbaban  *
1131*e8c27ec8Sbaban  * sid2gid/gid2sid:
1132*e8c27ec8Sbaban  * none       -> ds_name_mapping_enabled != true
1133*e8c27ec8Sbaban  * AD-mode    -> !nldap_winname_attr && ad_unixgroup_attr
1134*e8c27ec8Sbaban  * nldap-mode -> nldap_winname_attr && !ad_unixgroup_attr
1135*e8c27ec8Sbaban  * mixed-mode -> nldap_winname_attr && ad_unixgroup_attr
1136*e8c27ec8Sbaban  */
1137*e8c27ec8Sbaban idmap_retcode
1138*e8c27ec8Sbaban get_ds_namemap_type(lookup_state_t *state)
1139*e8c27ec8Sbaban {
1140*e8c27ec8Sbaban 	state->nm_siduid = IDMAP_NM_NONE;
1141*e8c27ec8Sbaban 	state->nm_sidgid = IDMAP_NM_NONE;
1142*e8c27ec8Sbaban 	RDLOCK_CONFIG();
1143*e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.ds_name_mapping_enabled == FALSE) {
1144*e8c27ec8Sbaban 		UNLOCK_CONFIG();
1145*e8c27ec8Sbaban 		return (IDMAP_SUCCESS);
1146*e8c27ec8Sbaban 	}
1147*e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.nldap_winname_attr != NULL) {
1148*e8c27ec8Sbaban 		state->nm_siduid =
1149*e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
1150*e8c27ec8Sbaban 		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
1151*e8c27ec8Sbaban 		state->nm_sidgid =
1152*e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
1153*e8c27ec8Sbaban 		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
1154*e8c27ec8Sbaban 	} else {
1155*e8c27ec8Sbaban 		state->nm_siduid =
1156*e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
1157*e8c27ec8Sbaban 		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
1158*e8c27ec8Sbaban 		state->nm_sidgid =
1159*e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
1160*e8c27ec8Sbaban 		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
1161*e8c27ec8Sbaban 	}
1162*e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL) {
1163*e8c27ec8Sbaban 		state->ad_unixuser_attr =
1164*e8c27ec8Sbaban 		    strdup(_idmapdstate.cfg->pgcfg.ad_unixuser_attr);
1165*e8c27ec8Sbaban 		if (state->ad_unixuser_attr == NULL) {
1166*e8c27ec8Sbaban 			UNLOCK_CONFIG();
1167*e8c27ec8Sbaban 			return (IDMAP_ERR_MEMORY);
1168*e8c27ec8Sbaban 		}
1169*e8c27ec8Sbaban 	}
1170*e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL) {
1171*e8c27ec8Sbaban 		state->ad_unixgroup_attr =
1172*e8c27ec8Sbaban 		    strdup(_idmapdstate.cfg->pgcfg.ad_unixgroup_attr);
1173*e8c27ec8Sbaban 		if (state->ad_unixgroup_attr == NULL) {
1174*e8c27ec8Sbaban 			UNLOCK_CONFIG();
1175*e8c27ec8Sbaban 			return (IDMAP_ERR_MEMORY);
1176*e8c27ec8Sbaban 		}
1177*e8c27ec8Sbaban 	}
1178*e8c27ec8Sbaban 	UNLOCK_CONFIG();
1179*e8c27ec8Sbaban 	return (IDMAP_SUCCESS);
1180*e8c27ec8Sbaban }
1181*e8c27ec8Sbaban 
1182*e8c27ec8Sbaban /*
118362c60062Sbaban  * Table for well-known SIDs.
118462c60062Sbaban  *
118562c60062Sbaban  * Background:
118662c60062Sbaban  *
118776b27f93Sbaban  * Some of the well-known principals are stored under:
118862c60062Sbaban  * cn=WellKnown Security Principals, cn=Configuration, dc=<forestRootDomain>
118962c60062Sbaban  * They belong to objectClass "foreignSecurityPrincipal". They don't have
119062c60062Sbaban  * "samAccountName" nor "userPrincipalName" attributes. Their names are
119162c60062Sbaban  * available in "cn" and "name" attributes. Some of these principals have a
119262c60062Sbaban  * second entry under CN=ForeignSecurityPrincipals,dc=<forestRootDomain> and
119362c60062Sbaban  * these duplicate entries have the stringified SID in the "name" and "cn"
119462c60062Sbaban  * attributes instead of the actual name.
119562c60062Sbaban  *
119676b27f93Sbaban  * Those of the form S-1-5-32-X are Builtin groups and are stored in the
119776b27f93Sbaban  * cn=builtin container (except, Power Users which is not stored in AD)
119862c60062Sbaban  *
119976b27f93Sbaban  * These principals are and will remain constant. Therefore doing AD lookups
120076b27f93Sbaban  * provides no benefit. Also, using hard-coded table (and thus avoiding AD
120176b27f93Sbaban  * lookup) improves performance and avoids additional complexity in the
120276b27f93Sbaban  * adutils.c code. Moreover these SIDs can be used when no Active Directory
120376b27f93Sbaban  * is available (such as the CIFS server's "workgroup" mode).
120476b27f93Sbaban  *
120576b27f93Sbaban  * Notes:
120676b27f93Sbaban  * 1. Currently we don't support localization of well-known SID names,
120762c60062Sbaban  * unlike Windows.
120862c60062Sbaban  *
120976b27f93Sbaban  * 2. Other well-known SIDs i.e. S-1-5-<domain>-<w-k RID> are not stored
121076b27f93Sbaban  * here. AD does have normal user/group objects for these objects and
121176b27f93Sbaban  * can be looked up using the existing AD lookup code.
1212*e8c27ec8Sbaban  *
1213*e8c27ec8Sbaban  * 3. See comments above lookup_wksids_sid2pid() for more information
1214*e8c27ec8Sbaban  * on how we lookup the wksids table.
121562c60062Sbaban  */
121662c60062Sbaban static wksids_table_t wksids[] = {
1217*e8c27ec8Sbaban 	{"S-1-0", 0, "Nobody", 0, SENTINEL_PID, -1, 1},
1218*e8c27ec8Sbaban 	{"S-1-1", 0, "Everyone", 0, SENTINEL_PID, -1, -1},
1219*e8c27ec8Sbaban 	{"S-1-3", 0, "Creator Owner", 1, IDMAP_WK_CREATOR_OWNER_UID, 1, 0},
1220*e8c27ec8Sbaban 	{"S-1-3", 1, "Creator Group", 0, IDMAP_WK_CREATOR_GROUP_GID, 0, 0},
1221*e8c27ec8Sbaban 	{"S-1-3", 2, "Creator Owner Server", 1, SENTINEL_PID, -1, -1},
1222*e8c27ec8Sbaban 	{"S-1-3", 3, "Creator Group Server", 0, SENTINEL_PID, -1, 1},
1223*e8c27ec8Sbaban 	{"S-1-3", 4, "Owner Rights", 0, SENTINEL_PID, -1, -1},
1224*e8c27ec8Sbaban 	{"S-1-5", 1, "Dialup", 0, SENTINEL_PID, -1, -1},
1225*e8c27ec8Sbaban 	{"S-1-5", 2, "Network", 0, SENTINEL_PID, -1, -1},
1226*e8c27ec8Sbaban 	{"S-1-5", 3, "Batch", 0, SENTINEL_PID, -1, -1},
1227*e8c27ec8Sbaban 	{"S-1-5", 4, "Interactive", 0, SENTINEL_PID, -1, -1},
1228*e8c27ec8Sbaban 	{"S-1-5", 6, "Service", 0, SENTINEL_PID, -1, -1},
1229*e8c27ec8Sbaban 	{"S-1-5", 7, "Anonymous Logon", 0, GID_NOBODY, 0, 0},
1230*e8c27ec8Sbaban 	{"S-1-5", 7, "Anonymous Logon", 0, UID_NOBODY, 1, 0},
1231*e8c27ec8Sbaban 	{"S-1-5", 8, "Proxy", 0, SENTINEL_PID, -1, -1},
1232*e8c27ec8Sbaban 	{"S-1-5", 9, "Enterprise Domain Controllers", 0, SENTINEL_PID, -1, -1},
1233*e8c27ec8Sbaban 	{"S-1-5", 10, "Self", 0, SENTINEL_PID, -1, -1},
1234*e8c27ec8Sbaban 	{"S-1-5", 11, "Authenticated Users", 0, SENTINEL_PID, -1, -1},
1235*e8c27ec8Sbaban 	{"S-1-5", 12, "Restricted Code", 0, SENTINEL_PID, -1, -1},
1236*e8c27ec8Sbaban 	{"S-1-5", 13, "Terminal Server User", 0, SENTINEL_PID, -1, -1},
1237*e8c27ec8Sbaban 	{"S-1-5", 14, "Remote Interactive Logon", 0, SENTINEL_PID, -1, -1},
1238*e8c27ec8Sbaban 	{"S-1-5", 15, "This Organization", 0, SENTINEL_PID, -1, -1},
1239*e8c27ec8Sbaban 	{"S-1-5", 17, "IUSR", 0, SENTINEL_PID, -1, -1},
1240*e8c27ec8Sbaban 	{"S-1-5", 18, "Local System", 0, IDMAP_WK_LOCAL_SYSTEM_GID, 0, 0},
1241*e8c27ec8Sbaban 	{"S-1-5", 19, "Local Service", 0, SENTINEL_PID, -1, -1},
1242*e8c27ec8Sbaban 	{"S-1-5", 20, "Network Service", 0, SENTINEL_PID, -1, -1},
1243*e8c27ec8Sbaban 	{"S-1-5", 1000, "Other Organization", 0, SENTINEL_PID, -1, -1},
1244*e8c27ec8Sbaban 	{"S-1-5-32", 544, "Administrators", 0, SENTINEL_PID, -1, -1},
1245*e8c27ec8Sbaban 	{"S-1-5-32", 545, "Users", 0, SENTINEL_PID, -1, -1},
1246*e8c27ec8Sbaban 	{"S-1-5-32", 546, "Guests", 0, SENTINEL_PID, -1, -1},
1247*e8c27ec8Sbaban 	{"S-1-5-32", 547, "Power Users", 0, SENTINEL_PID, -1, -1},
1248*e8c27ec8Sbaban 	{"S-1-5-32", 548, "Account Operators", 0, SENTINEL_PID, -1, -1},
1249*e8c27ec8Sbaban 	{"S-1-5-32", 549, "Server Operators", 0, SENTINEL_PID, -1, -1},
1250*e8c27ec8Sbaban 	{"S-1-5-32", 550, "Print Operators", 0, SENTINEL_PID, -1, -1},
1251*e8c27ec8Sbaban 	{"S-1-5-32", 551, "Backup Operators", 0, SENTINEL_PID, -1, -1},
1252*e8c27ec8Sbaban 	{"S-1-5-32", 552, "Replicator", 0, SENTINEL_PID, -1, -1},
125376b27f93Sbaban 	{"S-1-5-32", 554, "Pre-Windows 2000 Compatible Access", 0,
1254*e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1255*e8c27ec8Sbaban 	{"S-1-5-32", 555, "Remote Desktop Users", 0, SENTINEL_PID, -1, -1},
125676b27f93Sbaban 	{"S-1-5-32", 556, "Network Configuration Operators", 0,
1257*e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
125876b27f93Sbaban 	{"S-1-5-32", 557, "Incoming Forest Trust Builders", 0,
1259*e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1260*e8c27ec8Sbaban 	{"S-1-5-32", 558, "Performance Monitor Users", 0, SENTINEL_PID, -1, -1},
1261*e8c27ec8Sbaban 	{"S-1-5-32", 559, "Performance Log Users", 0, SENTINEL_PID, -1, -1},
126276b27f93Sbaban 	{"S-1-5-32", 560, "Windows Authorization Access Group", 0,
1263*e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
126476b27f93Sbaban 	{"S-1-5-32", 561, "Terminal Server License Servers", 0,
1265*e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1266*e8c27ec8Sbaban 	{"S-1-5-32", 561, "Distributed COM Users", 0, SENTINEL_PID, -1, -1},
1267*e8c27ec8Sbaban 	{"S-1-5-32", 568, "IIS_IUSRS", 0, SENTINEL_PID, -1, -1},
1268*e8c27ec8Sbaban 	{"S-1-5-32", 569, "Cryptographic Operators", 0, SENTINEL_PID, -1, -1},
1269*e8c27ec8Sbaban 	{"S-1-5-32", 573, "Event Log Readers", 0, SENTINEL_PID, -1, -1},
127076b27f93Sbaban 	{"S-1-5-32", 574, "Certificate Service DCOM Access", 0,
1271*e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1272*e8c27ec8Sbaban 	{"S-1-5-64", 21, "Digest Authentication", 0, SENTINEL_PID, -1, -1},
1273*e8c27ec8Sbaban 	{"S-1-5-64", 10, "NTLM Authentication", 0, SENTINEL_PID, -1, -1},
1274*e8c27ec8Sbaban 	{"S-1-5-64", 14, "SChannel Authentication", 0, SENTINEL_PID, -1, -1},
1275*e8c27ec8Sbaban 	{NULL, UINT32_MAX, NULL, -1, SENTINEL_PID, -1, -1}
1276c5c4113dSnw141292 };
1277c5c4113dSnw141292 
1278*e8c27ec8Sbaban /*
1279*e8c27ec8Sbaban  * Lookup well-known SIDs table either by winname or by SID.
1280*e8c27ec8Sbaban  * If the given winname or SID is a well-known SID then we set wksid
1281*e8c27ec8Sbaban  * variable and then proceed to see if the SID has a hard mapping to
1282*e8c27ec8Sbaban  * a particular UID/GID (Ex: Creator Owner/Creator Group mapped to
1283*e8c27ec8Sbaban  * fixed ephemeral ids). If we find such mapping then we return
1284*e8c27ec8Sbaban  * success otherwise notfound. If a well-known SID is mapped to
1285*e8c27ec8Sbaban  * SENTINEL_PID and the direction field is set (bi-directional or
1286*e8c27ec8Sbaban  * win2unix) then we treat it as inhibited mapping and return no
1287*e8c27ec8Sbaban  * mapping (Ex. S-1-0-0).
1288*e8c27ec8Sbaban  */
1289cd37da74Snw141292 static
1290cd37da74Snw141292 idmap_retcode
1291*e8c27ec8Sbaban lookup_wksids_sid2pid(idmap_mapping *req, idmap_id_res *res, int *wksid)
1292cd37da74Snw141292 {
1293c5c4113dSnw141292 	int i;
129462c60062Sbaban 
1295*e8c27ec8Sbaban 	*wksid = 0;
1296*e8c27ec8Sbaban 
1297*e8c27ec8Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
1298*e8c27ec8Sbaban 		if (req->id1.idmap_id_u.sid.prefix != NULL) {
1299*e8c27ec8Sbaban 			if ((strcasecmp(wksids[i].sidprefix,
1300*e8c27ec8Sbaban 			    req->id1.idmap_id_u.sid.prefix) != 0) ||
1301*e8c27ec8Sbaban 			    wksids[i].rid != req->id1.idmap_id_u.sid.rid)
1302*e8c27ec8Sbaban 				/* this is not our SID */
1303*e8c27ec8Sbaban 				continue;
1304*e8c27ec8Sbaban 			if (req->id1name == NULL) {
1305*e8c27ec8Sbaban 				req->id1name = strdup(wksids[i].winname);
1306*e8c27ec8Sbaban 				if (req->id1name == NULL)
1307*e8c27ec8Sbaban 					return (IDMAP_ERR_MEMORY);
1308*e8c27ec8Sbaban 			}
1309*e8c27ec8Sbaban 		} else if (req->id1name != NULL) {
1310*e8c27ec8Sbaban 			if (strcasecmp(wksids[i].winname, req->id1name) != 0)
1311*e8c27ec8Sbaban 				/* this is not our winname */
1312*e8c27ec8Sbaban 				continue;
1313*e8c27ec8Sbaban 			req->id1.idmap_id_u.sid.prefix =
1314*e8c27ec8Sbaban 			    strdup(wksids[i].sidprefix);
1315*e8c27ec8Sbaban 			if (req->id1.idmap_id_u.sid.prefix == NULL)
1316*e8c27ec8Sbaban 				return (IDMAP_ERR_MEMORY);
1317*e8c27ec8Sbaban 			req->id1.idmap_id_u.sid.rid = wksids[i].rid;
1318*e8c27ec8Sbaban 		}
1319*e8c27ec8Sbaban 
1320*e8c27ec8Sbaban 		*wksid = 1;
1321*e8c27ec8Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
1322*e8c27ec8Sbaban 
1323*e8c27ec8Sbaban 		req->id1.idtype = (wksids[i].is_wuser) ?
1324*e8c27ec8Sbaban 		    IDMAP_USID : IDMAP_GSID;
1325*e8c27ec8Sbaban 
1326*e8c27ec8Sbaban 		if (wksids[i].pid == SENTINEL_PID) {
1327*e8c27ec8Sbaban 			if (wksids[i].direction == IDMAP_DIRECTION_BI ||
1328*e8c27ec8Sbaban 			    wksids[i].direction == IDMAP_DIRECTION_W2U)
1329*e8c27ec8Sbaban 				/* Inhibited */
1330*e8c27ec8Sbaban 				return (IDMAP_ERR_NOMAPPING);
1331*e8c27ec8Sbaban 			/* Not mapped */
1332*e8c27ec8Sbaban 			return (IDMAP_ERR_NOTFOUND);
1333*e8c27ec8Sbaban 		} else if (wksids[i].direction == IDMAP_DIRECTION_U2W)
133462c60062Sbaban 			continue;
133562c60062Sbaban 
1336*e8c27ec8Sbaban 		switch (res->id.idtype) {
1337c5c4113dSnw141292 		case IDMAP_UID:
133862c60062Sbaban 			if (wksids[i].is_user == 0)
133962c60062Sbaban 				continue;
134062c60062Sbaban 			res->id.idmap_id_u.uid = wksids[i].pid;
134162c60062Sbaban 			res->direction = wksids[i].direction;
1342c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1343c5c4113dSnw141292 		case IDMAP_GID:
134462c60062Sbaban 			if (wksids[i].is_user == 1)
134562c60062Sbaban 				continue;
134662c60062Sbaban 			res->id.idmap_id_u.gid = wksids[i].pid;
134762c60062Sbaban 			res->direction = wksids[i].direction;
1348c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1349c5c4113dSnw141292 		case IDMAP_POSIXID:
135062c60062Sbaban 			res->id.idmap_id_u.uid = wksids[i].pid;
135162c60062Sbaban 			res->id.idtype = (!wksids[i].is_user) ?
1352c5c4113dSnw141292 			    IDMAP_GID : IDMAP_UID;
135362c60062Sbaban 			res->direction = wksids[i].direction;
1354c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1355c5c4113dSnw141292 		default:
1356c5c4113dSnw141292 			return (IDMAP_ERR_NOTSUPPORTED);
1357c5c4113dSnw141292 		}
1358c5c4113dSnw141292 	}
1359c5c4113dSnw141292 	return (IDMAP_ERR_NOTFOUND);
1360c5c4113dSnw141292 }
1361c5c4113dSnw141292 
1362cd37da74Snw141292 
1363cd37da74Snw141292 static
1364cd37da74Snw141292 idmap_retcode
1365cd37da74Snw141292 lookup_wksids_pid2sid(idmap_mapping *req, idmap_id_res *res, int is_user)
1366cd37da74Snw141292 {
1367c5c4113dSnw141292 	int i;
1368*e8c27ec8Sbaban 	if (req->id1.idmap_id_u.uid == SENTINEL_PID)
1369*e8c27ec8Sbaban 		return (IDMAP_ERR_NOTFOUND);
137062c60062Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
137162c60062Sbaban 		if (wksids[i].pid == req->id1.idmap_id_u.uid &&
137262c60062Sbaban 		    wksids[i].is_user == is_user &&
137362c60062Sbaban 		    wksids[i].direction != IDMAP_DIRECTION_W2U) {
1374*e8c27ec8Sbaban 			if (res->id.idtype == IDMAP_SID) {
1375*e8c27ec8Sbaban 				res->id.idtype = (wksids[i].is_wuser) ?
1376*e8c27ec8Sbaban 				    IDMAP_USID : IDMAP_GSID;
1377*e8c27ec8Sbaban 			}
137862c60062Sbaban 			res->id.idmap_id_u.sid.rid = wksids[i].rid;
1379c5c4113dSnw141292 			res->id.idmap_id_u.sid.prefix =
138062c60062Sbaban 			    strdup(wksids[i].sidprefix);
1381c5c4113dSnw141292 			if (res->id.idmap_id_u.sid.prefix == NULL) {
1382c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1383c5c4113dSnw141292 				return (IDMAP_ERR_MEMORY);
1384c5c4113dSnw141292 			}
138562c60062Sbaban 			res->direction = wksids[i].direction;
1386c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1387c5c4113dSnw141292 		}
1388c5c4113dSnw141292 	}
138962c60062Sbaban 	return (IDMAP_ERR_NOTFOUND);
139062c60062Sbaban }
139162c60062Sbaban 
1392cd37da74Snw141292 static
1393cd37da74Snw141292 idmap_retcode
1394cd37da74Snw141292 lookup_wksids_name2sid(const char *name, char **canonname, char **sidprefix,
1395cd37da74Snw141292 	idmap_rid_t *rid, int *type)
1396cd37da74Snw141292 {
139762c60062Sbaban 	int i;
139862c60062Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
1399*e8c27ec8Sbaban 		if (strcasecmp(wksids[i].winname, name) != 0)
1400*e8c27ec8Sbaban 			continue;
1401*e8c27ec8Sbaban 		if (sidprefix != NULL &&
1402*e8c27ec8Sbaban 		    (*sidprefix = strdup(wksids[i].sidprefix)) == NULL) {
140362c60062Sbaban 			idmapdlog(LOG_ERR, "Out of memory");
140462c60062Sbaban 			return (IDMAP_ERR_MEMORY);
140562c60062Sbaban 		}
1406cd37da74Snw141292 		if (canonname != NULL &&
1407cd37da74Snw141292 		    (*canonname = strdup(wksids[i].winname)) == NULL) {
1408cd37da74Snw141292 			idmapdlog(LOG_ERR, "Out of memory");
1409*e8c27ec8Sbaban 			if (sidprefix != NULL) {
1410*e8c27ec8Sbaban 				free(*sidprefix);
1411*e8c27ec8Sbaban 				*sidprefix = NULL;
1412*e8c27ec8Sbaban 			}
1413cd37da74Snw141292 			return (IDMAP_ERR_MEMORY);
1414cd37da74Snw141292 		}
141562c60062Sbaban 		if (type != NULL)
1416*e8c27ec8Sbaban 			*type = (wksids[i].is_wuser) ?
141762c60062Sbaban 			    _IDMAP_T_USER : _IDMAP_T_GROUP;
141862c60062Sbaban 		if (rid != NULL)
141962c60062Sbaban 			*rid = wksids[i].rid;
142062c60062Sbaban 		return (IDMAP_SUCCESS);
142162c60062Sbaban 	}
1422c5c4113dSnw141292 	return (IDMAP_ERR_NOTFOUND);
1423c5c4113dSnw141292 }
1424c5c4113dSnw141292 
1425cd37da74Snw141292 static
1426cd37da74Snw141292 idmap_retcode
1427cd37da74Snw141292 lookup_cache_sid2pid(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
1428cd37da74Snw141292 {
1429c5c4113dSnw141292 	char		*end;
1430c5c4113dSnw141292 	char		*sql = NULL;
1431c5c4113dSnw141292 	const char	**values;
1432c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
1433c5c4113dSnw141292 	int		ncol, is_user;
1434c5c4113dSnw141292 	uid_t		pid;
1435c5c4113dSnw141292 	time_t		curtime, exp;
1436c5c4113dSnw141292 	idmap_retcode	retcode;
1437cd37da74Snw141292 	char *is_user_string;
1438c5c4113dSnw141292 
1439c5c4113dSnw141292 	/* Current time */
1440c5c4113dSnw141292 	errno = 0;
1441c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
1442cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
1443c5c4113dSnw141292 		    strerror(errno));
1444c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
1445c5c4113dSnw141292 		goto out;
1446c5c4113dSnw141292 	}
1447c5c4113dSnw141292 
1448*e8c27ec8Sbaban 	switch (res->id.idtype) {
1449cd37da74Snw141292 	case IDMAP_UID:
1450cd37da74Snw141292 		is_user_string = "1";
1451cd37da74Snw141292 		break;
1452cd37da74Snw141292 	case IDMAP_GID:
1453cd37da74Snw141292 		is_user_string = "0";
1454cd37da74Snw141292 		break;
1455cd37da74Snw141292 	case IDMAP_POSIXID:
1456cd37da74Snw141292 		/* the non-diagonal mapping */
1457cd37da74Snw141292 		is_user_string = "is_wuser";
1458cd37da74Snw141292 		break;
1459cd37da74Snw141292 	default:
1460cd37da74Snw141292 		retcode = IDMAP_ERR_NOTSUPPORTED;
1461cd37da74Snw141292 		goto out;
1462cd37da74Snw141292 	}
1463cd37da74Snw141292 
1464c5c4113dSnw141292 	/* SQL to lookup the cache */
1465*e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
1466*e8c27ec8Sbaban 		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
1467*e8c27ec8Sbaban 		    "unixname, u2w, is_wuser "
1468cd37da74Snw141292 		    "FROM idmap_cache WHERE is_user = %s AND "
1469c5c4113dSnw141292 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
1470c5c4113dSnw141292 		    "(pid >= 2147483648 OR "
1471c5c4113dSnw141292 		    "(expiration = 0 OR expiration ISNULL OR "
1472c5c4113dSnw141292 		    "expiration > %d));",
1473*e8c27ec8Sbaban 		    is_user_string, req->id1.idmap_id_u.sid.prefix,
1474*e8c27ec8Sbaban 		    req->id1.idmap_id_u.sid.rid, curtime);
1475*e8c27ec8Sbaban 	} else if (req->id1name != NULL) {
1476*e8c27ec8Sbaban 		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
1477*e8c27ec8Sbaban 		    "unixname, u2w, is_wuser "
1478*e8c27ec8Sbaban 		    "FROM idmap_cache WHERE is_user = %s AND "
1479*e8c27ec8Sbaban 		    "winname = %Q AND windomain = %Q AND w2u = 1 AND "
1480*e8c27ec8Sbaban 		    "(pid >= 2147483648 OR "
1481*e8c27ec8Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
1482*e8c27ec8Sbaban 		    "expiration > %d));",
1483*e8c27ec8Sbaban 		    is_user_string, req->id1name, req->id1domain, curtime);
1484*e8c27ec8Sbaban 	} else {
1485*e8c27ec8Sbaban 		retcode = IDMAP_ERR_ARG;
1486*e8c27ec8Sbaban 		goto out;
1487*e8c27ec8Sbaban 	}
1488*e8c27ec8Sbaban 
1489c5c4113dSnw141292 	if (sql == NULL) {
1490c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
1491c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
1492c5c4113dSnw141292 		goto out;
1493c5c4113dSnw141292 	}
1494*e8c27ec8Sbaban 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 6, &values);
1495c5c4113dSnw141292 	sqlite_freemem(sql);
1496c5c4113dSnw141292 
1497c5c4113dSnw141292 	if (retcode == IDMAP_ERR_NOTFOUND) {
1498c5c4113dSnw141292 		goto out;
1499c5c4113dSnw141292 	} else if (retcode == IDMAP_SUCCESS) {
1500c5c4113dSnw141292 		/* sanity checks */
1501c5c4113dSnw141292 		if (values[0] == NULL || values[1] == NULL) {
1502c5c4113dSnw141292 			retcode = IDMAP_ERR_CACHE;
1503c5c4113dSnw141292 			goto out;
1504c5c4113dSnw141292 		}
1505c5c4113dSnw141292 
1506c5c4113dSnw141292 		pid = strtoul(values[0], &end, 10);
1507c5c4113dSnw141292 		is_user = strncmp(values[1], "0", 2) ? 1 : 0;
1508c5c4113dSnw141292 
1509cd37da74Snw141292 		if (is_user) {
1510cd37da74Snw141292 			res->id.idtype = IDMAP_UID;
1511cd37da74Snw141292 			res->id.idmap_id_u.uid = pid;
1512cd37da74Snw141292 		} else {
1513cd37da74Snw141292 			res->id.idtype = IDMAP_GID;
1514cd37da74Snw141292 			res->id.idmap_id_u.gid = pid;
1515cd37da74Snw141292 		}
1516cd37da74Snw141292 
1517c5c4113dSnw141292 		/*
1518c5c4113dSnw141292 		 * We may have an expired ephemeral mapping. Consider
1519c5c4113dSnw141292 		 * the expired entry as valid if we are not going to
1520c5c4113dSnw141292 		 * perform name-based mapping. But do not renew the
1521c5c4113dSnw141292 		 * expiration.
1522c5c4113dSnw141292 		 * If we will be doing name-based mapping then store the
1523c5c4113dSnw141292 		 * ephemeral pid in the result so that we can use it
1524c5c4113dSnw141292 		 * if we end up doing dynamic mapping again.
1525c5c4113dSnw141292 		 */
1526c5c4113dSnw141292 		if (!DO_NOT_ALLOC_NEW_ID_MAPPING(req) &&
1527cd37da74Snw141292 		    !AVOID_NAMESERVICE(req) &&
1528cd37da74Snw141292 		    IS_EPHEMERAL(pid) && values[2] != NULL) {
1529c5c4113dSnw141292 			exp = strtoll(values[2], &end, 10);
1530c5c4113dSnw141292 			if (exp && exp <= curtime) {
1531c5c4113dSnw141292 				/* Store the ephemeral pid */
1532651c0131Sbaban 				res->direction = IDMAP_DIRECTION_BI;
1533cd37da74Snw141292 				req->direction |= is_user
1534cd37da74Snw141292 				    ? _IDMAP_F_EXP_EPH_UID
1535cd37da74Snw141292 				    : _IDMAP_F_EXP_EPH_GID;
1536c5c4113dSnw141292 				retcode = IDMAP_ERR_NOTFOUND;
1537c5c4113dSnw141292 			}
1538c5c4113dSnw141292 		}
1539c5c4113dSnw141292 	}
1540c5c4113dSnw141292 
1541c5c4113dSnw141292 out:
1542c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
154362c60062Sbaban 		if (values[4] != NULL)
1544c5c4113dSnw141292 			res->direction =
1545651c0131Sbaban 			    (strtol(values[4], &end, 10) == 0)?
1546651c0131Sbaban 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
1547c5c4113dSnw141292 		else
1548651c0131Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
1549c5c4113dSnw141292 
155062c60062Sbaban 		if (values[3] != NULL) {
1551*e8c27ec8Sbaban 			if (req->id2name != NULL)
1552*e8c27ec8Sbaban 				free(req->id2name);
15538e228215Sdm199847 			req->id2name = strdup(values[3]);
15548e228215Sdm199847 			if (req->id2name == NULL) {
1555c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1556c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
1557c5c4113dSnw141292 			}
1558c5c4113dSnw141292 		}
1559*e8c27ec8Sbaban 
1560*e8c27ec8Sbaban 		req->id1.idtype = strncmp(values[5], "0", 2) ?
1561*e8c27ec8Sbaban 		    IDMAP_USID : IDMAP_GSID;
1562c5c4113dSnw141292 	}
156362c60062Sbaban 	if (vm != NULL)
1564c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
1565c5c4113dSnw141292 	return (retcode);
1566c5c4113dSnw141292 }
1567c5c4113dSnw141292 
1568cd37da74Snw141292 static
1569cd37da74Snw141292 idmap_retcode
157062c60062Sbaban lookup_cache_sid2name(sqlite *cache, const char *sidprefix, idmap_rid_t rid,
1571cd37da74Snw141292 		char **name, char **domain, int *type)
1572cd37da74Snw141292 {
1573c5c4113dSnw141292 	char		*end;
1574c5c4113dSnw141292 	char		*sql = NULL;
1575c5c4113dSnw141292 	const char	**values;
1576c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
1577c5c4113dSnw141292 	int		ncol;
1578c5c4113dSnw141292 	time_t		curtime;
1579c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
1580c5c4113dSnw141292 
1581c5c4113dSnw141292 	/* Get current time */
1582c5c4113dSnw141292 	errno = 0;
1583c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
1584cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
1585c5c4113dSnw141292 		    strerror(errno));
1586c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
1587c5c4113dSnw141292 		goto out;
1588c5c4113dSnw141292 	}
1589c5c4113dSnw141292 
1590c5c4113dSnw141292 	/* SQL to lookup the cache */
1591cd37da74Snw141292 	sql = sqlite_mprintf("SELECT canon_name, domain, type "
1592cd37da74Snw141292 	    "FROM name_cache WHERE "
1593c5c4113dSnw141292 	    "sidprefix = %Q AND rid = %u AND "
1594c5c4113dSnw141292 	    "(expiration = 0 OR expiration ISNULL OR "
1595c5c4113dSnw141292 	    "expiration > %d);",
1596c5c4113dSnw141292 	    sidprefix, rid, curtime);
1597c5c4113dSnw141292 	if (sql == NULL) {
1598c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
1599c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
1600c5c4113dSnw141292 		goto out;
1601c5c4113dSnw141292 	}
1602c5c4113dSnw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 3, &values);
1603c5c4113dSnw141292 	sqlite_freemem(sql);
1604c5c4113dSnw141292 
1605c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
160662c60062Sbaban 		if (type != NULL) {
1607c5c4113dSnw141292 			if (values[2] == NULL) {
1608c5c4113dSnw141292 				retcode = IDMAP_ERR_CACHE;
1609c5c4113dSnw141292 				goto out;
1610c5c4113dSnw141292 			}
1611c5c4113dSnw141292 			*type = strtol(values[2], &end, 10);
1612c5c4113dSnw141292 		}
1613c5c4113dSnw141292 
161462c60062Sbaban 		if (name != NULL && values[0] != NULL) {
1615c5c4113dSnw141292 			if ((*name = strdup(values[0])) == NULL) {
1616c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1617c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
1618c5c4113dSnw141292 				goto out;
1619c5c4113dSnw141292 			}
1620c5c4113dSnw141292 		}
1621c5c4113dSnw141292 
162262c60062Sbaban 		if (domain != NULL && values[1] != NULL) {
1623c5c4113dSnw141292 			if ((*domain = strdup(values[1])) == NULL) {
162462c60062Sbaban 				if (name != NULL && *name) {
1625c5c4113dSnw141292 					free(*name);
1626c5c4113dSnw141292 					*name = NULL;
1627c5c4113dSnw141292 				}
1628c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1629c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
1630c5c4113dSnw141292 				goto out;
1631c5c4113dSnw141292 			}
1632c5c4113dSnw141292 		}
1633c5c4113dSnw141292 	}
1634c5c4113dSnw141292 
1635c5c4113dSnw141292 out:
163662c60062Sbaban 	if (vm != NULL)
1637c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
1638c5c4113dSnw141292 	return (retcode);
1639c5c4113dSnw141292 }
1640c5c4113dSnw141292 
1641c5c4113dSnw141292 /*
1642*e8c27ec8Sbaban  * Given SID, find winname using name_cache OR
1643*e8c27ec8Sbaban  * Given winname, find SID using name_cache.
1644*e8c27ec8Sbaban  * Used when mapping win to unix i.e. req->id1 is windows id and
1645*e8c27ec8Sbaban  * req->id2 is unix id
1646c5c4113dSnw141292  */
1647cd37da74Snw141292 static
1648cd37da74Snw141292 idmap_retcode
1649*e8c27ec8Sbaban lookup_name_cache(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
1650cd37da74Snw141292 {
1651c5c4113dSnw141292 	int		type = -1;
1652c5c4113dSnw141292 	idmap_retcode	retcode;
1653*e8c27ec8Sbaban 	char		*sidprefix = NULL;
1654c5c4113dSnw141292 	idmap_rid_t	rid;
1655c5c4113dSnw141292 	char		*name = NULL, *domain = NULL;
1656c5c4113dSnw141292 
1657*e8c27ec8Sbaban 	/* Done if we've both sid and winname */
1658*e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL && req->id1name != NULL)
1659*e8c27ec8Sbaban 		return (IDMAP_SUCCESS);
1660c5c4113dSnw141292 
1661*e8c27ec8Sbaban 	/* Lookup sid to winname */
1662*e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
1663*e8c27ec8Sbaban 		retcode = lookup_cache_sid2name(cache,
1664*e8c27ec8Sbaban 		    req->id1.idmap_id_u.sid.prefix,
1665*e8c27ec8Sbaban 		    req->id1.idmap_id_u.sid.rid, &name, &domain, &type);
166662c60062Sbaban 		goto out;
1667*e8c27ec8Sbaban 	}
166862c60062Sbaban 
1669*e8c27ec8Sbaban 	/* Lookup winame to sid */
1670*e8c27ec8Sbaban 	retcode = lookup_cache_name2sid(cache, req->id1name, req->id1domain,
1671*e8c27ec8Sbaban 	    &name, &sidprefix, &rid, &type);
1672c5c4113dSnw141292 
167362c60062Sbaban out:
1674*e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
1675c5c4113dSnw141292 		free(name);
1676c5c4113dSnw141292 		free(domain);
1677*e8c27ec8Sbaban 		free(sidprefix);
1678*e8c27ec8Sbaban 		return (retcode);
1679*e8c27ec8Sbaban 	}
1680*e8c27ec8Sbaban 
1681*e8c27ec8Sbaban 	if (res->id.idtype == IDMAP_POSIXID) {
1682*e8c27ec8Sbaban 		res->id.idtype = (type == _IDMAP_T_USER) ?
1683*e8c27ec8Sbaban 		    IDMAP_UID : IDMAP_GID;
1684*e8c27ec8Sbaban 	}
1685*e8c27ec8Sbaban 	req->id1.idtype = (type == _IDMAP_T_USER) ?
1686*e8c27ec8Sbaban 	    IDMAP_USID : IDMAP_GSID;
1687*e8c27ec8Sbaban 
1688*e8c27ec8Sbaban 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
1689*e8c27ec8Sbaban 	if (name != NULL) {
1690*e8c27ec8Sbaban 		free(req->id1name);	/* Free existing winname */
1691*e8c27ec8Sbaban 		req->id1name = name;	/* and use canonical name instead */
1692*e8c27ec8Sbaban 	}
1693*e8c27ec8Sbaban 	if (req->id1domain == NULL)
1694*e8c27ec8Sbaban 		req->id1domain = domain;
1695*e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix == NULL) {
1696*e8c27ec8Sbaban 		req->id1.idmap_id_u.sid.prefix = sidprefix;
1697*e8c27ec8Sbaban 		req->id1.idmap_id_u.sid.rid = rid;
1698c5c4113dSnw141292 	}
1699c5c4113dSnw141292 	return (retcode);
1700c5c4113dSnw141292 }
1701c5c4113dSnw141292 
1702*e8c27ec8Sbaban /*
1703*e8c27ec8Sbaban  * Batch AD lookups
1704*e8c27ec8Sbaban  */
1705c5c4113dSnw141292 idmap_retcode
1706*e8c27ec8Sbaban ad_lookup_batch(lookup_state_t *state, idmap_mapping_batch *batch,
1707cd37da74Snw141292 		idmap_ids_res *result)
1708cd37da74Snw141292 {
1709c5c4113dSnw141292 	idmap_retcode	retcode;
1710*e8c27ec8Sbaban 	int		i, add, type, is_wuser, is_user;
1711*e8c27ec8Sbaban 	int		retries = 0, eunixtype;
1712*e8c27ec8Sbaban 	char		**unixname;
1713c5c4113dSnw141292 	idmap_mapping	*req;
1714c5c4113dSnw141292 	idmap_id_res	*res;
1715*e8c27ec8Sbaban 	idmap_query_state_t	*qs = NULL;
1716*e8c27ec8Sbaban 
1717*e8c27ec8Sbaban 	/*
1718*e8c27ec8Sbaban 	 * Since req->id2.idtype is unused, we will use it here
1719*e8c27ec8Sbaban 	 * to retrieve the value of sid_type. But it needs to be
1720*e8c27ec8Sbaban 	 * reset to IDMAP_NONE before we return to prevent xdr
1721*e8c27ec8Sbaban 	 * from mis-interpreting req->id2 when it tries to free
1722*e8c27ec8Sbaban 	 * the input argument. Other option is to allocate an
1723*e8c27ec8Sbaban 	 * array of integers and use it instead for the batched
1724*e8c27ec8Sbaban 	 * call. But why un-necessarily allocate memory. That may
1725*e8c27ec8Sbaban 	 * be an option if req->id2.idtype cannot be re-used in
1726*e8c27ec8Sbaban 	 * future.
1727*e8c27ec8Sbaban 	 */
1728c5c4113dSnw141292 
1729c5c4113dSnw141292 	if (state->ad_nqueries == 0)
1730c5c4113dSnw141292 		return (IDMAP_SUCCESS);
1731c5c4113dSnw141292 
1732c5c4113dSnw141292 retry:
1733*e8c27ec8Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, state->ad_nqueries,
1734*e8c27ec8Sbaban 	    &qs);
1735*e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
1736c8e26105Sjp151216 		degrade_svc();
1737c5c4113dSnw141292 		idmapdlog(LOG_ERR,
1738*e8c27ec8Sbaban 		    "Failed to create batch for AD lookup");
1739*e8c27ec8Sbaban 		goto out;
1740c5c4113dSnw141292 	}
1741c5c4113dSnw141292 
1742c8e26105Sjp151216 	restore_svc();
1743c8e26105Sjp151216 
1744*e8c27ec8Sbaban 	idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
1745*e8c27ec8Sbaban 	    state->ad_unixgroup_attr);
1746*e8c27ec8Sbaban 
1747*e8c27ec8Sbaban 	for (i = 0, add = 0; i < batch->idmap_mapping_batch_len; i++) {
1748c5c4113dSnw141292 		req = &batch->idmap_mapping_batch_val[i];
1749c5c4113dSnw141292 		res = &result->ids.ids_val[i];
1750*e8c27ec8Sbaban 		retcode = IDMAP_SUCCESS;
1751*e8c27ec8Sbaban 		req->id2.idtype = IDMAP_NONE;
1752c5c4113dSnw141292 
1753*e8c27ec8Sbaban 		/* Skip if not marked for AD lookup */
1754*e8c27ec8Sbaban 		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
1755*e8c27ec8Sbaban 			continue;
1756*e8c27ec8Sbaban 
1757c5c4113dSnw141292 		if (retries == 0)
1758c5c4113dSnw141292 			res->retcode = IDMAP_ERR_RETRIABLE_NET_ERR;
1759c5c4113dSnw141292 		else if (res->retcode != IDMAP_ERR_RETRIABLE_NET_ERR)
1760c5c4113dSnw141292 			continue;
1761*e8c27ec8Sbaban 
1762*e8c27ec8Sbaban 		if (IS_REQUEST_SID(*req, 1)) {
1763*e8c27ec8Sbaban 			/* win to unix */
1764*e8c27ec8Sbaban 
1765*e8c27ec8Sbaban 			assert(req->id1.idmap_id_u.sid.prefix != NULL);
1766*e8c27ec8Sbaban 
1767*e8c27ec8Sbaban 			/* Lookup AD by SID */
1768*e8c27ec8Sbaban 			unixname = NULL;
1769*e8c27ec8Sbaban 			eunixtype = _IDMAP_T_UNDEF;
1770*e8c27ec8Sbaban 			if (req->id2name == NULL) {
1771*e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_UID &&
1772*e8c27ec8Sbaban 				    AD_OR_MIXED(state->nm_siduid)) {
1773*e8c27ec8Sbaban 					eunixtype = _IDMAP_T_USER;
1774*e8c27ec8Sbaban 					unixname = &req->id2name;
1775*e8c27ec8Sbaban 				} else if (res->id.idtype == IDMAP_GID &&
1776*e8c27ec8Sbaban 				    AD_OR_MIXED(state->nm_sidgid)) {
1777*e8c27ec8Sbaban 					eunixtype = _IDMAP_T_GROUP;
1778*e8c27ec8Sbaban 					unixname = &req->id2name;
1779*e8c27ec8Sbaban 				} else if (AD_OR_MIXED(state->nm_siduid) ||
1780*e8c27ec8Sbaban 				    AD_OR_MIXED(state->nm_sidgid)) {
1781*e8c27ec8Sbaban 					unixname = &req->id2name;
1782*e8c27ec8Sbaban 				}
1783*e8c27ec8Sbaban 			}
1784*e8c27ec8Sbaban 			add = 1;
1785c5c4113dSnw141292 			retcode = idmap_sid2name_batch_add1(
1786*e8c27ec8Sbaban 			    qs, req->id1.idmap_id_u.sid.prefix,
1787*e8c27ec8Sbaban 			    &req->id1.idmap_id_u.sid.rid, eunixtype,
1788*e8c27ec8Sbaban 			    (req->id1name == NULL) ? &req->id1name : NULL,
1789*e8c27ec8Sbaban 			    (req->id1domain == NULL) ? &req->id1domain : NULL,
1790*e8c27ec8Sbaban 			    (int *)&req->id2.idtype, unixname, &res->retcode);
1791c5c4113dSnw141292 
1792*e8c27ec8Sbaban 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
1793*e8c27ec8Sbaban 			/* unix to win */
1794*e8c27ec8Sbaban 
1795*e8c27ec8Sbaban 			if (res->id.idmap_id_u.sid.prefix != NULL &&
1796*e8c27ec8Sbaban 			    req->id2name != NULL) {
1797*e8c27ec8Sbaban 				/* Already have SID and winname -- done */
1798*e8c27ec8Sbaban 				res->retcode = IDMAP_SUCCESS;
1799*e8c27ec8Sbaban 				continue;
1800c5c4113dSnw141292 			}
1801c5c4113dSnw141292 
1802*e8c27ec8Sbaban 			if (res->id.idmap_id_u.sid.prefix != NULL) {
1803cd37da74Snw141292 				/*
1804*e8c27ec8Sbaban 				 * SID but no winname -- lookup AD by
1805*e8c27ec8Sbaban 				 * SID to get winname.
1806cd37da74Snw141292 				 */
1807*e8c27ec8Sbaban 				add = 1;
1808*e8c27ec8Sbaban 				retcode = idmap_sid2name_batch_add1(
1809*e8c27ec8Sbaban 				    qs, res->id.idmap_id_u.sid.prefix,
1810*e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.rid,
1811*e8c27ec8Sbaban 				    _IDMAP_T_UNDEF, &req->id2name,
1812*e8c27ec8Sbaban 				    &req->id2domain, (int *)&req->id2.idtype,
1813*e8c27ec8Sbaban 				    NULL, &res->retcode);
1814*e8c27ec8Sbaban 			} else if (req->id2name != NULL) {
1815*e8c27ec8Sbaban 				/*
1816*e8c27ec8Sbaban 				 * winname but no SID -- lookup AD by
1817*e8c27ec8Sbaban 				 * winname to get SID.
1818*e8c27ec8Sbaban 				 */
1819*e8c27ec8Sbaban 				add = 1;
1820*e8c27ec8Sbaban 				retcode = idmap_name2sid_batch_add1(
1821*e8c27ec8Sbaban 				    qs, req->id2name, req->id2domain,
1822*e8c27ec8Sbaban 				    _IDMAP_T_UNDEF, NULL,
1823*e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.prefix,
1824*e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.rid,
1825*e8c27ec8Sbaban 				    (int *)&req->id2.idtype, NULL,
1826*e8c27ec8Sbaban 				    &res->retcode);
1827*e8c27ec8Sbaban 			} else if (req->id1name != NULL) {
1828*e8c27ec8Sbaban 				/*
1829*e8c27ec8Sbaban 				 * No SID and no winname but we've unixname --
1830*e8c27ec8Sbaban 				 * lookup AD by unixname to get SID.
1831*e8c27ec8Sbaban 				 */
1832*e8c27ec8Sbaban 				is_user = (IS_REQUEST_UID(*req)) ? 1 : 0;
1833*e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_USID)
1834*e8c27ec8Sbaban 					is_wuser = 1;
1835*e8c27ec8Sbaban 				else if (res->id.idtype == IDMAP_GSID)
1836*e8c27ec8Sbaban 					is_wuser = 0;
1837*e8c27ec8Sbaban 				else
1838*e8c27ec8Sbaban 					is_wuser = is_user;
1839*e8c27ec8Sbaban 				add = 1;
1840*e8c27ec8Sbaban 				retcode = idmap_unixname2sid_batch_add1(
1841*e8c27ec8Sbaban 				    qs, req->id1name, is_user, is_wuser,
1842*e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.prefix,
1843*e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.rid,
1844*e8c27ec8Sbaban 				    &req->id2name, &req->id2domain,
1845*e8c27ec8Sbaban 				    (int *)&req->id2.idtype, &res->retcode);
1846*e8c27ec8Sbaban 			}
1847*e8c27ec8Sbaban 		}
1848*e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS) {
1849*e8c27ec8Sbaban 			idmap_lookup_release_batch(&qs);
1850*e8c27ec8Sbaban 			break;
1851*e8c27ec8Sbaban 		}
1852cd37da74Snw141292 	}
1853cd37da74Snw141292 
1854*e8c27ec8Sbaban 	if (retcode == IDMAP_SUCCESS && add)
1855*e8c27ec8Sbaban 		retcode = idmap_lookup_batch_end(&qs, NULL);
1856cd37da74Snw141292 
1857c5c4113dSnw141292 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
1858c5c4113dSnw141292 		goto retry;
1859c8e26105Sjp151216 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
1860c8e26105Sjp151216 		degrade_svc();
1861c5c4113dSnw141292 
1862*e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
1863*e8c27ec8Sbaban 		idmapdlog(LOG_NOTICE, "Failed to batch AD lookup requests");
1864c5c4113dSnw141292 
1865c5c4113dSnw141292 out:
1866*e8c27ec8Sbaban 	/*
1867*e8c27ec8Sbaban 	 * This loop does the following:
1868*e8c27ec8Sbaban 	 * 1) If there are errors in creating or submitting the batch then
1869*e8c27ec8Sbaban 	 *    we set the retcode for each request (res->retcode) that's part
1870*e8c27ec8Sbaban 	 *    of the batch to that error. If there were no such errors then
1871*e8c27ec8Sbaban 	 *    res->retcode for each request will reflect the status of AD
1872*e8c27ec8Sbaban 	 *    lookup for that particular request. Initial value of
1873*e8c27ec8Sbaban 	 *    res->retcode is IDMAP_ERR_RETRIABLE_NET_ERR.
1874*e8c27ec8Sbaban 	 * 2) If AD lookup for a given request succeeds then evaluate the
1875*e8c27ec8Sbaban 	 *    type of the AD object (i.e user or group) and update the
1876*e8c27ec8Sbaban 	 *    idtype in res and req.
1877*e8c27ec8Sbaban 	 * 3) Reset req->id2.idtype to IDMAP_NONE.
1878*e8c27ec8Sbaban 	 */
1879*e8c27ec8Sbaban 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
1880*e8c27ec8Sbaban 		req = &batch->idmap_mapping_batch_val[i];
1881*e8c27ec8Sbaban 		type = req->id2.idtype;
1882*e8c27ec8Sbaban 		req->id2.idtype = IDMAP_NONE;
1883*e8c27ec8Sbaban 		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
1884*e8c27ec8Sbaban 			/* Entry that wasn't marked for AD lookup - skip */
1885*e8c27ec8Sbaban 			continue;
1886*e8c27ec8Sbaban 
1887*e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS) {
1888*e8c27ec8Sbaban 			res->retcode = retcode;
1889*e8c27ec8Sbaban 			continue;
1890*e8c27ec8Sbaban 		}
1891*e8c27ec8Sbaban 
1892*e8c27ec8Sbaban 		if (!add)
1893*e8c27ec8Sbaban 			continue;
1894*e8c27ec8Sbaban 
1895*e8c27ec8Sbaban 		res = &result->ids.ids_val[i];
1896*e8c27ec8Sbaban 
1897*e8c27ec8Sbaban 		if (IS_REQUEST_SID(*req, 1)) {
1898*e8c27ec8Sbaban 			if (res->retcode != IDMAP_SUCCESS)
1899*e8c27ec8Sbaban 				continue;
1900*e8c27ec8Sbaban 			switch (type) {
1901*e8c27ec8Sbaban 			case _IDMAP_T_USER:
1902*e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
1903*e8c27ec8Sbaban 					res->id.idtype = IDMAP_UID;
1904*e8c27ec8Sbaban 				req->id1.idtype = IDMAP_USID;
1905*e8c27ec8Sbaban 				break;
1906*e8c27ec8Sbaban 			case _IDMAP_T_GROUP:
1907*e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
1908*e8c27ec8Sbaban 					res->id.idtype = IDMAP_GID;
1909*e8c27ec8Sbaban 				req->id1.idtype = IDMAP_GSID;
1910*e8c27ec8Sbaban 				break;
1911*e8c27ec8Sbaban 			default:
1912*e8c27ec8Sbaban 				res->retcode = IDMAP_ERR_SID;
1913*e8c27ec8Sbaban 				break;
1914*e8c27ec8Sbaban 			}
1915*e8c27ec8Sbaban 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
1916*e8c27ec8Sbaban 			if (res->retcode != IDMAP_SUCCESS) {
1917*e8c27ec8Sbaban 				if ((!(IDMAP_FATAL_ERROR(res->retcode))) &&
1918*e8c27ec8Sbaban 				    res->id.idmap_id_u.sid.prefix == NULL &&
1919*e8c27ec8Sbaban 				    req->id2name == NULL && /* no winname */
1920*e8c27ec8Sbaban 				    req->id1name != NULL) /* unixname */
1921*e8c27ec8Sbaban 					/*
1922*e8c27ec8Sbaban 					 * Here we have a pid2sid request
1923*e8c27ec8Sbaban 					 * that was marked for AD lookup
1924*e8c27ec8Sbaban 					 * with no SID, no winname but with
1925*e8c27ec8Sbaban 					 * unixname. This request was
1926*e8c27ec8Sbaban 					 * added to the batch to do AD lookup
1927*e8c27ec8Sbaban 					 * by unixname but it failed with non
1928*e8c27ec8Sbaban 					 * fatal error. In such case we
1929*e8c27ec8Sbaban 					 * ignore the error (i.e set
1930*e8c27ec8Sbaban 					 * res->retcode to success) so that
1931*e8c27ec8Sbaban 					 * next pass considers it for name
1932*e8c27ec8Sbaban 					 * based mapping rules or ephemeral
1933*e8c27ec8Sbaban 					 * mapping.
1934*e8c27ec8Sbaban 					 */
1935*e8c27ec8Sbaban 					res->retcode = IDMAP_SUCCESS;
1936*e8c27ec8Sbaban 				continue;
1937*e8c27ec8Sbaban 			}
1938*e8c27ec8Sbaban 			switch (type) {
1939*e8c27ec8Sbaban 			case _IDMAP_T_USER:
1940*e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_SID)
1941*e8c27ec8Sbaban 					res->id.idtype = IDMAP_USID;
1942*e8c27ec8Sbaban 				break;
1943*e8c27ec8Sbaban 			case _IDMAP_T_GROUP:
1944*e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_SID)
1945*e8c27ec8Sbaban 					res->id.idtype = IDMAP_GSID;
1946*e8c27ec8Sbaban 				break;
1947*e8c27ec8Sbaban 			default:
1948*e8c27ec8Sbaban 				res->retcode = IDMAP_ERR_SID;
1949*e8c27ec8Sbaban 				break;
1950*e8c27ec8Sbaban 			}
1951*e8c27ec8Sbaban 		}
1952*e8c27ec8Sbaban 	}
1953*e8c27ec8Sbaban 
1954*e8c27ec8Sbaban 	/* AD lookups done. Reset state->ad_nqueries and return */
1955*e8c27ec8Sbaban 	state->ad_nqueries = 0;
1956c5c4113dSnw141292 	return (retcode);
1957c5c4113dSnw141292 }
1958c5c4113dSnw141292 
1959cd37da74Snw141292 /*
1960cd37da74Snw141292  * Convention when processing win2unix requests:
1961cd37da74Snw141292  *
1962cd37da74Snw141292  * Windows identity:
1963cd37da74Snw141292  * req->id1name =
1964cd37da74Snw141292  *              winname if given otherwise winname found will be placed
1965cd37da74Snw141292  *              here.
1966cd37da74Snw141292  * req->id1domain =
1967cd37da74Snw141292  *              windomain if given otherwise windomain found will be
1968cd37da74Snw141292  *              placed here.
1969cd37da74Snw141292  * req->id1.idtype =
1970cd37da74Snw141292  *              Either IDMAP_SID/USID/GSID. If this is IDMAP_SID then it'll
1971cd37da74Snw141292  *              be set to IDMAP_USID/GSID depending upon whether the
1972cd37da74Snw141292  *              given SID is user or group respectively. The user/group-ness
1973cd37da74Snw141292  *              is determined either when looking up well-known SIDs table OR
1974cd37da74Snw141292  *              if the SID is found in namecache OR by ad_lookup() OR by
1975cd37da74Snw141292  *              ad_lookup_batch().
1976cd37da74Snw141292  * req->id1..sid.[prefix, rid] =
1977cd37da74Snw141292  *              SID if given otherwise SID found will be placed here.
1978cd37da74Snw141292  *
1979cd37da74Snw141292  * Unix identity:
1980cd37da74Snw141292  * req->id2name =
1981cd37da74Snw141292  *              unixname found will be placed here.
1982cd37da74Snw141292  * req->id2domain =
1983cd37da74Snw141292  *              NOT USED
1984cd37da74Snw141292  * res->id.idtype =
1985cd37da74Snw141292  *              Target type initialized from req->id2.idtype. If
1986cd37da74Snw141292  *              it is IDMAP_POSIXID then actual type (IDMAP_UID/GID) found
1987cd37da74Snw141292  *              will be placed here.
1988cd37da74Snw141292  * res->id..[uid or gid] =
1989cd37da74Snw141292  *              UID/GID found will be placed here.
1990cd37da74Snw141292  *
1991cd37da74Snw141292  * Others:
1992cd37da74Snw141292  * res->retcode =
1993cd37da74Snw141292  *              Return status for this request will be placed here.
1994cd37da74Snw141292  * res->direction =
1995cd37da74Snw141292  *              Direction found will be placed here. Direction
1996cd37da74Snw141292  *              meaning whether the resultant mapping is valid
1997cd37da74Snw141292  *              only from win2unix or bi-directional.
1998cd37da74Snw141292  * req->direction =
1999cd37da74Snw141292  *              INTERNAL USE. Used by idmapd to set various
2000cd37da74Snw141292  *              flags (_IDMAP_F_xxxx) to aid in processing
2001cd37da74Snw141292  *              of the request.
2002cd37da74Snw141292  * req->id2.idtype =
2003cd37da74Snw141292  *              INTERNAL USE. Initially this is the requested target
2004cd37da74Snw141292  *              type and is used to initialize res->id.idtype.
2005cd37da74Snw141292  *              ad_lookup_batch() uses this field temporarily to store
2006cd37da74Snw141292  *              sid_type obtained by the batched AD lookups and after
2007cd37da74Snw141292  *              use resets it to IDMAP_NONE to prevent xdr from
2008cd37da74Snw141292  *              mis-interpreting the contents of req->id2.
2009cd37da74Snw141292  * req->id2..[uid or gid or sid] =
2010cd37da74Snw141292  *              NOT USED
2011cd37da74Snw141292  */
2012cd37da74Snw141292 
2013cd37da74Snw141292 /*
2014cd37da74Snw141292  * This function does the following:
2015cd37da74Snw141292  * 1. Lookup well-known SIDs table.
2016cd37da74Snw141292  * 2. Check if the given SID is a local-SID and if so extract UID/GID from it.
2017cd37da74Snw141292  * 3. Lookup cache.
2018cd37da74Snw141292  * 4. Check if the client does not want new mapping to be allocated
2019cd37da74Snw141292  *    in which case this pass is the final pass.
2020cd37da74Snw141292  * 5. Set AD lookup flag if it determines that the next stage needs
2021cd37da74Snw141292  *    to do AD lookup.
2022cd37da74Snw141292  */
2023c5c4113dSnw141292 idmap_retcode
2024c5c4113dSnw141292 sid2pid_first_pass(lookup_state_t *state, sqlite *cache, idmap_mapping *req,
2025cd37da74Snw141292 		idmap_id_res *res)
2026cd37da74Snw141292 {
2027c5c4113dSnw141292 	idmap_retcode	retcode;
2028*e8c27ec8Sbaban 	int		wksid;
2029c5c4113dSnw141292 
2030*e8c27ec8Sbaban 	/* Initialize result */
2031*e8c27ec8Sbaban 	res->id.idtype = req->id2.idtype;
2032*e8c27ec8Sbaban 	res->id.idmap_id_u.uid = SENTINEL_PID;
2033*e8c27ec8Sbaban 	res->direction = IDMAP_DIRECTION_UNDEF;
2034*e8c27ec8Sbaban 	wksid = 0;
2035c5c4113dSnw141292 
2036cf5b5989Sdm199847 	if (EMPTY_STRING(req->id1.idmap_id_u.sid.prefix)) {
2037*e8c27ec8Sbaban 		if (req->id1name == NULL) {
2038*e8c27ec8Sbaban 			retcode = IDMAP_ERR_ARG;
2039c5c4113dSnw141292 			goto out;
2040c5c4113dSnw141292 		}
2041*e8c27ec8Sbaban 		/* sanitize sidprefix */
2042*e8c27ec8Sbaban 		free(req->id1.idmap_id_u.sid.prefix);
2043*e8c27ec8Sbaban 		req->id1.idmap_id_u.sid.prefix = NULL;
2044*e8c27ec8Sbaban 	}
2045c5c4113dSnw141292 
2046*e8c27ec8Sbaban 	/* Lookup well-known SIDs table */
2047*e8c27ec8Sbaban 	retcode = lookup_wksids_sid2pid(req, res, &wksid);
2048c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
2049c5c4113dSnw141292 		goto out;
2050c5c4113dSnw141292 
2051*e8c27ec8Sbaban 	/* Check if this is a localsid */
2052*e8c27ec8Sbaban 	if (!wksid) {
2053*e8c27ec8Sbaban 		retcode = lookup_localsid2pid(req, res);
2054*e8c27ec8Sbaban 		if (retcode != IDMAP_ERR_NOTFOUND)
2055*e8c27ec8Sbaban 			goto out;
2056*e8c27ec8Sbaban 	}
2057*e8c27ec8Sbaban 
2058*e8c27ec8Sbaban 	/* Lookup cache */
2059c5c4113dSnw141292 	retcode = lookup_cache_sid2pid(cache, req, res);
2060c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
2061c5c4113dSnw141292 		goto out;
2062c5c4113dSnw141292 
2063c5c4113dSnw141292 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req) || AVOID_NAMESERVICE(req)) {
2064*e8c27ec8Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
2065c5c4113dSnw141292 		goto out;
2066c5c4113dSnw141292 	}
2067c5c4113dSnw141292 
2068c5c4113dSnw141292 	/*
2069*e8c27ec8Sbaban 	 * Failed to find non-expired entry in cache. Next step is
2070*e8c27ec8Sbaban 	 * to determine if this request needs to be batched for AD lookup.
2071*e8c27ec8Sbaban 	 *
2072*e8c27ec8Sbaban 	 * At this point we have either sid or winname or both. If we don't
2073*e8c27ec8Sbaban 	 * have both then lookup name_cache for the sid or winname
2074*e8c27ec8Sbaban 	 * whichever is missing. If not found then this request will be
2075*e8c27ec8Sbaban 	 * batched for AD lookup.
2076*e8c27ec8Sbaban 	 */
2077*e8c27ec8Sbaban 	retcode = lookup_name_cache(cache, req, res);
2078*e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS && retcode != IDMAP_ERR_NOTFOUND)
2079*e8c27ec8Sbaban 		goto out;
2080*e8c27ec8Sbaban 
2081*e8c27ec8Sbaban 	/*
2082*e8c27ec8Sbaban 	 * Set the flag to indicate that we are not done yet so that
2083*e8c27ec8Sbaban 	 * subsequent passes considers this request for name-based
2084*e8c27ec8Sbaban 	 * mapping and ephemeral mapping.
2085c5c4113dSnw141292 	 */
2086c5c4113dSnw141292 	state->sid2pid_done = FALSE;
2087*e8c27ec8Sbaban 	req->direction |= _IDMAP_F_NOTDONE;
2088c5c4113dSnw141292 
2089c5c4113dSnw141292 	/*
2090*e8c27ec8Sbaban 	 * Even if we have both sid and winname, we still may need to batch
2091*e8c27ec8Sbaban 	 * this request for AD lookup if we don't have unixname and
2092*e8c27ec8Sbaban 	 * directory-based name mapping (AD or mixed) is enabled.
2093*e8c27ec8Sbaban 	 * We avoid AD lookup for well-known SIDs because they don't have
2094*e8c27ec8Sbaban 	 * regular AD objects.
2095c5c4113dSnw141292 	 */
2096*e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS ||
2097*e8c27ec8Sbaban 	    (!wksid && req->id2name == NULL &&
2098*e8c27ec8Sbaban 	    AD_OR_MIXED_MODE(res->id.idtype, state))) {
2099c5c4113dSnw141292 		retcode = IDMAP_SUCCESS;
2100*e8c27ec8Sbaban 		req->direction |= _IDMAP_F_LOOKUP_AD;
2101c5c4113dSnw141292 		state->ad_nqueries++;
2102c5c4113dSnw141292 	}
2103c5c4113dSnw141292 
2104c5c4113dSnw141292 
2105c5c4113dSnw141292 out:
2106c5c4113dSnw141292 	res->retcode = idmap_stat4prot(retcode);
2107*e8c27ec8Sbaban 	/*
2108*e8c27ec8Sbaban 	 * If we are done and there was an error then set fallback pid
2109*e8c27ec8Sbaban 	 * in the result.
2110*e8c27ec8Sbaban 	 */
2111*e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
2112*e8c27ec8Sbaban 		res->id.idmap_id_u.uid = UID_NOBODY;
2113c5c4113dSnw141292 	return (retcode);
2114c5c4113dSnw141292 }
2115c5c4113dSnw141292 
2116c5c4113dSnw141292 /*
2117c5c4113dSnw141292  * Generate SID using the following convention
2118c5c4113dSnw141292  * 	<machine-sid-prefix>-<1000 + uid>
2119c5c4113dSnw141292  * 	<machine-sid-prefix>-<2^31 + gid>
2120c5c4113dSnw141292  */
2121cd37da74Snw141292 static
2122cd37da74Snw141292 idmap_retcode
2123cd37da74Snw141292 generate_localsid(idmap_mapping *req, idmap_id_res *res, int is_user)
2124cd37da74Snw141292 {
2125*e8c27ec8Sbaban 	free(res->id.idmap_id_u.sid.prefix);
2126*e8c27ec8Sbaban 	res->id.idmap_id_u.sid.prefix = NULL;
2127*e8c27ec8Sbaban 
2128*e8c27ec8Sbaban 	/*
2129*e8c27ec8Sbaban 	 * Diagonal mapping for localSIDs not supported because of the
2130*e8c27ec8Sbaban 	 * way we generate localSIDs.
2131*e8c27ec8Sbaban 	 */
2132*e8c27ec8Sbaban 	if (is_user && res->id.idtype == IDMAP_GSID)
2133*e8c27ec8Sbaban 		return (IDMAP_ERR_NOMAPPING);
2134*e8c27ec8Sbaban 	if (!is_user && res->id.idtype == IDMAP_USID)
2135*e8c27ec8Sbaban 		return (IDMAP_ERR_NOMAPPING);
2136*e8c27ec8Sbaban 
2137c5c4113dSnw141292 	/* Skip 1000 UIDs */
2138c5c4113dSnw141292 	if (is_user && req->id1.idmap_id_u.uid >
2139c5c4113dSnw141292 	    (INT32_MAX - LOCALRID_MIN))
214062c60062Sbaban 		return (IDMAP_ERR_NOMAPPING);
2141c5c4113dSnw141292 
2142c5c4113dSnw141292 	RDLOCK_CONFIG();
2143*e8c27ec8Sbaban 	/*
2144*e8c27ec8Sbaban 	 * machine_sid is never NULL because if it is we won't be here.
2145*e8c27ec8Sbaban 	 * No need to assert because stdrup(NULL) will core anyways.
2146*e8c27ec8Sbaban 	 */
2147c5c4113dSnw141292 	res->id.idmap_id_u.sid.prefix =
2148c5c4113dSnw141292 	    strdup(_idmapdstate.cfg->pgcfg.machine_sid);
2149c5c4113dSnw141292 	if (res->id.idmap_id_u.sid.prefix == NULL) {
2150c5c4113dSnw141292 		UNLOCK_CONFIG();
2151c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2152c5c4113dSnw141292 		return (IDMAP_ERR_MEMORY);
2153c5c4113dSnw141292 	}
2154c5c4113dSnw141292 	UNLOCK_CONFIG();
2155c5c4113dSnw141292 	res->id.idmap_id_u.sid.rid =
2156c5c4113dSnw141292 	    (is_user) ? req->id1.idmap_id_u.uid + LOCALRID_MIN :
2157c5c4113dSnw141292 	    req->id1.idmap_id_u.gid + INT32_MAX + 1;
2158651c0131Sbaban 	res->direction = IDMAP_DIRECTION_BI;
2159*e8c27ec8Sbaban 	if (res->id.idtype == IDMAP_SID)
2160*e8c27ec8Sbaban 		res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
2161c5c4113dSnw141292 
2162c5c4113dSnw141292 	/*
2163c5c4113dSnw141292 	 * Don't update name_cache because local sids don't have
2164c5c4113dSnw141292 	 * valid windows names.
2165c5c4113dSnw141292 	 */
2166*e8c27ec8Sbaban 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
2167947c7bc0Sbaban 	return (IDMAP_SUCCESS);
2168c5c4113dSnw141292 }
2169c5c4113dSnw141292 
2170cd37da74Snw141292 static
2171cd37da74Snw141292 idmap_retcode
2172cd37da74Snw141292 lookup_localsid2pid(idmap_mapping *req, idmap_id_res *res)
2173cd37da74Snw141292 {
2174c5c4113dSnw141292 	char		*sidprefix;
2175c5c4113dSnw141292 	uint32_t	rid;
2176c5c4113dSnw141292 	int		s;
2177c5c4113dSnw141292 
2178c5c4113dSnw141292 	/*
2179c5c4113dSnw141292 	 * If the sidprefix == localsid then UID = last RID - 1000 or
2180c5c4113dSnw141292 	 * GID = last RID - 2^31.
2181c5c4113dSnw141292 	 */
2182*e8c27ec8Sbaban 	if ((sidprefix = req->id1.idmap_id_u.sid.prefix) == NULL)
2183*e8c27ec8Sbaban 		/* This means we are looking up by winname */
2184*e8c27ec8Sbaban 		return (IDMAP_ERR_NOTFOUND);
2185c5c4113dSnw141292 	rid = req->id1.idmap_id_u.sid.rid;
2186c5c4113dSnw141292 
2187c5c4113dSnw141292 	RDLOCK_CONFIG();
2188c5c4113dSnw141292 	s = (_idmapdstate.cfg->pgcfg.machine_sid) ?
2189cd37da74Snw141292 	    strcasecmp(sidprefix, _idmapdstate.cfg->pgcfg.machine_sid) : 1;
2190c5c4113dSnw141292 	UNLOCK_CONFIG();
2191c5c4113dSnw141292 
2192*e8c27ec8Sbaban 	/*
2193*e8c27ec8Sbaban 	 * If the given sidprefix does not match machine_sid then this is
2194*e8c27ec8Sbaban 	 * not a local SID.
2195*e8c27ec8Sbaban 	 */
2196*e8c27ec8Sbaban 	if (s != 0)
2197*e8c27ec8Sbaban 		return (IDMAP_ERR_NOTFOUND);
2198*e8c27ec8Sbaban 
2199*e8c27ec8Sbaban 	switch (res->id.idtype) {
2200c5c4113dSnw141292 	case IDMAP_UID:
2201*e8c27ec8Sbaban 		if (rid > INT32_MAX || rid < LOCALRID_MIN)
2202*e8c27ec8Sbaban 			return (IDMAP_ERR_ARG);
2203c5c4113dSnw141292 		res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
2204c5c4113dSnw141292 		break;
2205c5c4113dSnw141292 	case IDMAP_GID:
2206*e8c27ec8Sbaban 		if (rid <= INT32_MAX)
2207*e8c27ec8Sbaban 			return (IDMAP_ERR_ARG);
2208c5c4113dSnw141292 		res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
2209c5c4113dSnw141292 		break;
2210c5c4113dSnw141292 	case IDMAP_POSIXID:
2211c5c4113dSnw141292 		if (rid > INT32_MAX) {
2212cd37da74Snw141292 			res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
2213c5c4113dSnw141292 			res->id.idtype = IDMAP_GID;
2214c5c4113dSnw141292 		} else if (rid < LOCALRID_MIN) {
2215*e8c27ec8Sbaban 			return (IDMAP_ERR_ARG);
2216c5c4113dSnw141292 		} else {
2217c5c4113dSnw141292 			res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
2218c5c4113dSnw141292 			res->id.idtype = IDMAP_UID;
2219c5c4113dSnw141292 		}
2220c5c4113dSnw141292 		break;
2221c5c4113dSnw141292 	default:
2222c5c4113dSnw141292 		return (IDMAP_ERR_NOTSUPPORTED);
2223c5c4113dSnw141292 	}
2224c5c4113dSnw141292 	return (IDMAP_SUCCESS);
2225c5c4113dSnw141292 }
2226c5c4113dSnw141292 
2227*e8c27ec8Sbaban /*
2228*e8c27ec8Sbaban  * Name service lookup by unixname to get pid
2229*e8c27ec8Sbaban  */
2230cd37da74Snw141292 static
2231cd37da74Snw141292 idmap_retcode
2232*e8c27ec8Sbaban ns_lookup_byname(const char *name, const char *lower_name, idmap_id *id)
2233cd37da74Snw141292 {
2234cd37da74Snw141292 	struct passwd	pwd, *pwdp;
2235cd37da74Snw141292 	struct group	grp, *grpp;
2236c5c4113dSnw141292 	char		buf[1024];
2237c5c4113dSnw141292 	int		errnum;
2238c5c4113dSnw141292 	const char	*me = "ns_lookup_byname";
2239c5c4113dSnw141292 
2240*e8c27ec8Sbaban 	switch (id->idtype) {
2241*e8c27ec8Sbaban 	case IDMAP_UID:
2242cd37da74Snw141292 		pwdp = getpwnam_r(name, &pwd, buf, sizeof (buf));
2243*e8c27ec8Sbaban 		if (pwdp == NULL && errno == 0 && lower_name != NULL &&
2244cd37da74Snw141292 		    name != lower_name && strcmp(name, lower_name) != 0)
2245cd37da74Snw141292 			pwdp = getpwnam_r(lower_name, &pwd, buf, sizeof (buf));
2246cd37da74Snw141292 		if (pwdp == NULL) {
2247c5c4113dSnw141292 			errnum = errno;
2248c5c4113dSnw141292 			idmapdlog(LOG_WARNING,
2249c5c4113dSnw141292 			    "%s: getpwnam_r(%s) failed (%s).",
2250cd37da74Snw141292 			    me, name, errnum ? strerror(errnum) : "not found");
2251c5c4113dSnw141292 			if (errnum == 0)
2252c5c4113dSnw141292 				return (IDMAP_ERR_NOTFOUND);
2253c5c4113dSnw141292 			else
2254c5c4113dSnw141292 				return (IDMAP_ERR_INTERNAL);
2255c5c4113dSnw141292 		}
2256*e8c27ec8Sbaban 		id->idmap_id_u.uid = pwd.pw_uid;
2257*e8c27ec8Sbaban 		break;
2258*e8c27ec8Sbaban 	case IDMAP_GID:
2259cd37da74Snw141292 		grpp = getgrnam_r(name, &grp, buf, sizeof (buf));
2260*e8c27ec8Sbaban 		if (grpp == NULL && errno == 0 && lower_name != NULL &&
2261cd37da74Snw141292 		    name != lower_name && strcmp(name, lower_name) != 0)
2262cd37da74Snw141292 			grpp = getgrnam_r(lower_name, &grp, buf, sizeof (buf));
2263cd37da74Snw141292 		if (grpp == NULL) {
2264c5c4113dSnw141292 			errnum = errno;
2265c5c4113dSnw141292 			idmapdlog(LOG_WARNING,
2266c5c4113dSnw141292 			    "%s: getgrnam_r(%s) failed (%s).",
2267cd37da74Snw141292 			    me, name, errnum ? strerror(errnum) : "not found");
2268c5c4113dSnw141292 			if (errnum == 0)
2269c5c4113dSnw141292 				return (IDMAP_ERR_NOTFOUND);
2270c5c4113dSnw141292 			else
2271c5c4113dSnw141292 				return (IDMAP_ERR_INTERNAL);
2272c5c4113dSnw141292 		}
2273*e8c27ec8Sbaban 		id->idmap_id_u.gid = grp.gr_gid;
2274*e8c27ec8Sbaban 		break;
2275*e8c27ec8Sbaban 	default:
2276*e8c27ec8Sbaban 		return (IDMAP_ERR_ARG);
2277c5c4113dSnw141292 	}
2278c5c4113dSnw141292 	return (IDMAP_SUCCESS);
2279c5c4113dSnw141292 }
2280c5c4113dSnw141292 
2281*e8c27ec8Sbaban 
2282*e8c27ec8Sbaban /*
2283*e8c27ec8Sbaban  * Name service lookup by pid to get unixname
2284*e8c27ec8Sbaban  */
2285*e8c27ec8Sbaban static
2286*e8c27ec8Sbaban idmap_retcode
2287*e8c27ec8Sbaban ns_lookup_bypid(uid_t pid, int is_user, char **unixname)
2288*e8c27ec8Sbaban {
2289*e8c27ec8Sbaban 	struct passwd	pwd;
2290*e8c27ec8Sbaban 	struct group	grp;
2291*e8c27ec8Sbaban 	char		buf[1024];
2292*e8c27ec8Sbaban 	int		errnum;
2293*e8c27ec8Sbaban 	const char	*me = "ns_lookup_bypid";
2294*e8c27ec8Sbaban 
2295*e8c27ec8Sbaban 	if (is_user) {
2296*e8c27ec8Sbaban 		errno = 0;
2297*e8c27ec8Sbaban 		if (getpwuid_r(pid, &pwd, buf, sizeof (buf)) == NULL) {
2298*e8c27ec8Sbaban 			errnum = errno;
2299*e8c27ec8Sbaban 			idmapdlog(LOG_WARNING,
2300*e8c27ec8Sbaban 			    "%s: getpwuid_r(%u) failed (%s).",
2301*e8c27ec8Sbaban 			    me, pid, errnum ? strerror(errnum) : "not found");
2302*e8c27ec8Sbaban 			if (errnum == 0)
2303*e8c27ec8Sbaban 				return (IDMAP_ERR_NOTFOUND);
2304*e8c27ec8Sbaban 			else
2305*e8c27ec8Sbaban 				return (IDMAP_ERR_INTERNAL);
2306*e8c27ec8Sbaban 		}
2307*e8c27ec8Sbaban 		*unixname = strdup(pwd.pw_name);
2308*e8c27ec8Sbaban 	} else {
2309*e8c27ec8Sbaban 		errno = 0;
2310*e8c27ec8Sbaban 		if (getgrgid_r(pid, &grp, buf, sizeof (buf)) == NULL) {
2311*e8c27ec8Sbaban 			errnum = errno;
2312*e8c27ec8Sbaban 			idmapdlog(LOG_WARNING,
2313*e8c27ec8Sbaban 			    "%s: getgrgid_r(%u) failed (%s).",
2314*e8c27ec8Sbaban 			    me, pid, errnum ? strerror(errnum) : "not found");
2315*e8c27ec8Sbaban 			if (errnum == 0)
2316*e8c27ec8Sbaban 				return (IDMAP_ERR_NOTFOUND);
2317*e8c27ec8Sbaban 			else
2318*e8c27ec8Sbaban 				return (IDMAP_ERR_INTERNAL);
2319*e8c27ec8Sbaban 		}
2320*e8c27ec8Sbaban 		*unixname = strdup(grp.gr_name);
2321*e8c27ec8Sbaban 	}
2322*e8c27ec8Sbaban 	if (*unixname == NULL)
2323*e8c27ec8Sbaban 		return (IDMAP_ERR_MEMORY);
2324*e8c27ec8Sbaban 	return (IDMAP_SUCCESS);
2325*e8c27ec8Sbaban }
2326*e8c27ec8Sbaban 
2327c5c4113dSnw141292 /*
2328c5c4113dSnw141292  * Name-based mapping
2329c5c4113dSnw141292  *
2330c5c4113dSnw141292  * Case 1: If no rule matches do ephemeral
2331c5c4113dSnw141292  *
2332c5c4113dSnw141292  * Case 2: If rule matches and unixname is "" then return no mapping.
2333c5c4113dSnw141292  *
2334c5c4113dSnw141292  * Case 3: If rule matches and unixname is specified then lookup name
2335c5c4113dSnw141292  *  service using the unixname. If unixname not found then return no mapping.
2336c5c4113dSnw141292  *
2337c5c4113dSnw141292  * Case 4: If rule matches and unixname is * then lookup name service
2338c5c4113dSnw141292  *  using winname as the unixname. If unixname not found then process
2339c5c4113dSnw141292  *  other rules using the lookup order. If no other rule matches then do
2340c5c4113dSnw141292  *  ephemeral. Otherwise, based on the matched rule do Case 2 or 3 or 4.
2341c5c4113dSnw141292  *  This allows us to specify a fallback unixname per _domain_ or no mapping
2342c5c4113dSnw141292  *  instead of the default behaviour of doing ephemeral mapping.
2343c5c4113dSnw141292  *
2344c5c4113dSnw141292  * Example 1:
2345c5c4113dSnw141292  * *@sfbay == *
2346c5c4113dSnw141292  * If looking up windows users foo@sfbay and foo does not exists in
2347c5c4113dSnw141292  * the name service then foo@sfbay will be mapped to an ephemeral id.
2348c5c4113dSnw141292  *
2349c5c4113dSnw141292  * Example 2:
2350c5c4113dSnw141292  * *@sfbay == *
2351c5c4113dSnw141292  * *@sfbay => guest
2352c5c4113dSnw141292  * If looking up windows users foo@sfbay and foo does not exists in
2353c5c4113dSnw141292  * the name service then foo@sfbay will be mapped to guest.
2354c5c4113dSnw141292  *
2355c5c4113dSnw141292  * Example 3:
2356c5c4113dSnw141292  * *@sfbay == *
2357c5c4113dSnw141292  * *@sfbay => ""
2358c5c4113dSnw141292  * If looking up windows users foo@sfbay and foo does not exists in
2359c5c4113dSnw141292  * the name service then we will return no mapping for foo@sfbay.
2360c5c4113dSnw141292  *
2361c5c4113dSnw141292  */
2362cd37da74Snw141292 static
2363cd37da74Snw141292 idmap_retcode
2364cd37da74Snw141292 name_based_mapping_sid2pid(sqlite *db, idmap_mapping *req, idmap_id_res *res)
2365cd37da74Snw141292 {
2366cd37da74Snw141292 	const char	*unixname, *windomain;
2367cd37da74Snw141292 	char		*sql = NULL, *errmsg = NULL, *lower_winname = NULL;
2368c5c4113dSnw141292 	idmap_retcode	retcode;
2369cd37da74Snw141292 	char		*end, *lower_unixname, *winname;
2370c5c4113dSnw141292 	const char	**values;
2371c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
2372cd37da74Snw141292 	int		ncol, r, i, is_user, is_wuser;
2373c5c4113dSnw141292 	const char	*me = "name_based_mapping_sid2pid";
2374c5c4113dSnw141292 
2375*e8c27ec8Sbaban 	assert(req->id1name != NULL); /* We have winname */
2376*e8c27ec8Sbaban 	assert(req->id2name == NULL); /* We don't have unixname */
2377*e8c27ec8Sbaban 
23788e228215Sdm199847 	winname = req->id1name;
23798e228215Sdm199847 	windomain = req->id1domain;
2380cd37da74Snw141292 
2381cd37da74Snw141292 	switch (req->id1.idtype) {
2382cd37da74Snw141292 	case IDMAP_USID:
2383cd37da74Snw141292 		is_wuser = 1;
2384cd37da74Snw141292 		break;
2385cd37da74Snw141292 	case IDMAP_GSID:
2386cd37da74Snw141292 		is_wuser = 0;
2387cd37da74Snw141292 		break;
2388cd37da74Snw141292 	default:
2389*e8c27ec8Sbaban 		idmapdlog(LOG_ERR, "%s: Unable to determine if the "
2390*e8c27ec8Sbaban 		    "given Windows id is user or group.", me);
2391cd37da74Snw141292 		return (IDMAP_ERR_INTERNAL);
2392cd37da74Snw141292 	}
2393cd37da74Snw141292 
2394*e8c27ec8Sbaban 	switch (res->id.idtype) {
2395cd37da74Snw141292 	case IDMAP_UID:
2396cd37da74Snw141292 		is_user = 1;
2397cd37da74Snw141292 		break;
2398cd37da74Snw141292 	case IDMAP_GID:
2399cd37da74Snw141292 		is_user = 0;
2400cd37da74Snw141292 		break;
2401cd37da74Snw141292 	case IDMAP_POSIXID:
2402cd37da74Snw141292 		is_user = is_wuser;
2403cd37da74Snw141292 		res->id.idtype = is_user ? IDMAP_UID : IDMAP_GID;
2404cd37da74Snw141292 		break;
2405cd37da74Snw141292 	}
2406c5c4113dSnw141292 
2407c5c4113dSnw141292 	i = 0;
240862c60062Sbaban 	if (windomain == NULL) {
240962c60062Sbaban 		windomain = "";
241062c60062Sbaban 	} else {
241162c60062Sbaban 		RDLOCK_CONFIG();
2412c8e26105Sjp151216 		if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
2413c8e26105Sjp151216 			if (strcasecmp(_idmapdstate.cfg->pgcfg.default_domain,
2414c5c4113dSnw141292 			    windomain) == 0)
2415c5c4113dSnw141292 				i = 1;
2416c5c4113dSnw141292 		}
2417c5c4113dSnw141292 		UNLOCK_CONFIG();
241862c60062Sbaban 	}
2419c5c4113dSnw141292 
2420cd37da74Snw141292 	if ((lower_winname = tolower_u8(winname)) == NULL)
2421cd37da74Snw141292 		lower_winname = winname;    /* hope for the best */
2422c5c4113dSnw141292 	sql = sqlite_mprintf(
2423c5c4113dSnw141292 	    "SELECT unixname, u2w_order FROM namerules WHERE "
2424cd37da74Snw141292 	    "w2u_order > 0 AND is_user = %d AND is_wuser = %d AND "
2425c5c4113dSnw141292 	    "(winname = %Q OR winname = '*') AND "
2426c5c4113dSnw141292 	    "(windomain = %Q OR windomain = '*' %s) "
2427c5c4113dSnw141292 	    "ORDER BY w2u_order ASC;",
2428cd37da74Snw141292 	    is_user, is_wuser, lower_winname, windomain,
242962c60062Sbaban 	    i ? "OR windomain ISNULL OR windomain = ''" : "");
2430c5c4113dSnw141292 	if (sql == NULL) {
2431c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2432c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
2433c5c4113dSnw141292 		goto out;
2434c5c4113dSnw141292 	}
2435c5c4113dSnw141292 
2436c5c4113dSnw141292 	if (sqlite_compile(db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
2437c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
2438cd37da74Snw141292 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
2439cd37da74Snw141292 		    CHECK_NULL(errmsg));
2440c5c4113dSnw141292 		sqlite_freemem(errmsg);
2441c5c4113dSnw141292 		goto out;
2442c5c4113dSnw141292 	}
2443c5c4113dSnw141292 
244484decf41Sjp151216 	for (; ; ) {
2445c5c4113dSnw141292 		r = sqlite_step(vm, &ncol, &values, NULL);
244684decf41Sjp151216 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
2447c5c4113dSnw141292 
244884decf41Sjp151216 		if (r == SQLITE_ROW) {
2449c5c4113dSnw141292 			if (ncol < 2) {
2450c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
2451c5c4113dSnw141292 				goto out;
2452c5c4113dSnw141292 			}
2453c5c4113dSnw141292 			if (values[0] == NULL) {
2454c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
2455c5c4113dSnw141292 				goto out;
2456c5c4113dSnw141292 			}
2457c5c4113dSnw141292 
2458c5c4113dSnw141292 			if (EMPTY_NAME(values[0])) {
2459c5c4113dSnw141292 				retcode = IDMAP_ERR_NOMAPPING;
2460c5c4113dSnw141292 				goto out;
2461c5c4113dSnw141292 			}
2462c5c4113dSnw141292 			unixname = (values[0][0] == '*') ? winname : values[0];
2463cd37da74Snw141292 			lower_unixname = (values[0][0] == '*') ?
2464cd37da74Snw141292 			    lower_winname : NULL;
2465*e8c27ec8Sbaban 			retcode = ns_lookup_byname(unixname, lower_unixname,
2466*e8c27ec8Sbaban 			    &res->id);
2467c5c4113dSnw141292 			if (retcode == IDMAP_ERR_NOTFOUND) {
2468c5c4113dSnw141292 				if (unixname == winname)
2469c5c4113dSnw141292 					/* Case 4 */
2470c5c4113dSnw141292 					continue;
2471c5c4113dSnw141292 				else
2472c5c4113dSnw141292 					/* Case 3 */
2473c5c4113dSnw141292 					retcode = IDMAP_ERR_NOMAPPING;
2474c5c4113dSnw141292 			}
2475c5c4113dSnw141292 			goto out;
2476c5c4113dSnw141292 		} else if (r == SQLITE_DONE) {
2477c5c4113dSnw141292 			retcode = IDMAP_ERR_NOTFOUND;
2478c5c4113dSnw141292 			goto out;
2479c5c4113dSnw141292 		} else {
2480c5c4113dSnw141292 			(void) sqlite_finalize(vm, &errmsg);
2481c5c4113dSnw141292 			vm = NULL;
2482cd37da74Snw141292 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
2483cd37da74Snw141292 			    CHECK_NULL(errmsg));
2484c5c4113dSnw141292 			sqlite_freemem(errmsg);
2485c5c4113dSnw141292 			retcode = IDMAP_ERR_INTERNAL;
2486c5c4113dSnw141292 			goto out;
2487c5c4113dSnw141292 		}
2488c5c4113dSnw141292 	}
2489c5c4113dSnw141292 
2490c5c4113dSnw141292 out:
2491c5c4113dSnw141292 	sqlite_freemem(sql);
2492c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
249362c60062Sbaban 		if (values[1] != NULL)
2494c5c4113dSnw141292 			res->direction =
2495651c0131Sbaban 			    (strtol(values[1], &end, 10) == 0)?
2496651c0131Sbaban 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
2497c5c4113dSnw141292 		else
2498651c0131Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
24998e228215Sdm199847 		req->id2name = strdup(unixname);
2500c5c4113dSnw141292 	}
2501cd37da74Snw141292 	if (lower_winname != NULL && lower_winname != winname)
2502cd37da74Snw141292 		free(lower_winname);
250362c60062Sbaban 	if (vm != NULL)
2504c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
2505c5c4113dSnw141292 	return (retcode);
2506c5c4113dSnw141292 }
2507c5c4113dSnw141292 
2508c5c4113dSnw141292 static
2509c5c4113dSnw141292 int
2510c5c4113dSnw141292 get_next_eph_uid(uid_t *next_uid)
2511c5c4113dSnw141292 {
2512c5c4113dSnw141292 	uid_t uid;
2513c5c4113dSnw141292 	gid_t gid;
2514c5c4113dSnw141292 	int err;
2515c5c4113dSnw141292 
2516c5c4113dSnw141292 	*next_uid = (uid_t)-1;
2517c5c4113dSnw141292 	uid = _idmapdstate.next_uid++;
2518c5c4113dSnw141292 	if (uid >= _idmapdstate.limit_uid) {
2519c5c4113dSnw141292 		if ((err = allocids(0, 8192, &uid, 0, &gid)) != 0)
2520c5c4113dSnw141292 			return (err);
2521c5c4113dSnw141292 
2522c5c4113dSnw141292 		_idmapdstate.limit_uid = uid + 8192;
2523c5c4113dSnw141292 		_idmapdstate.next_uid = uid;
2524c5c4113dSnw141292 	}
2525c5c4113dSnw141292 	*next_uid = uid;
2526c5c4113dSnw141292 
2527c5c4113dSnw141292 	return (0);
2528c5c4113dSnw141292 }
2529c5c4113dSnw141292 
2530c5c4113dSnw141292 static
2531c5c4113dSnw141292 int
2532c5c4113dSnw141292 get_next_eph_gid(gid_t *next_gid)
2533c5c4113dSnw141292 {
2534c5c4113dSnw141292 	uid_t uid;
2535c5c4113dSnw141292 	gid_t gid;
2536c5c4113dSnw141292 	int err;
2537c5c4113dSnw141292 
2538c5c4113dSnw141292 	*next_gid = (uid_t)-1;
2539c5c4113dSnw141292 	gid = _idmapdstate.next_gid++;
2540c5c4113dSnw141292 	if (gid >= _idmapdstate.limit_gid) {
2541c5c4113dSnw141292 		if ((err = allocids(0, 0, &uid, 8192, &gid)) != 0)
2542c5c4113dSnw141292 			return (err);
2543c5c4113dSnw141292 
2544c5c4113dSnw141292 		_idmapdstate.limit_gid = gid + 8192;
2545c5c4113dSnw141292 		_idmapdstate.next_gid = gid;
2546c5c4113dSnw141292 	}
2547c5c4113dSnw141292 	*next_gid = gid;
2548c5c4113dSnw141292 
2549c5c4113dSnw141292 	return (0);
2550c5c4113dSnw141292 }
2551c5c4113dSnw141292 
255262c60062Sbaban static
255362c60062Sbaban int
2554cd37da74Snw141292 gethash(const char *str, uint32_t num, uint_t htsize)
2555cd37da74Snw141292 {
255662c60062Sbaban 	uint_t  hval, i, len;
255762c60062Sbaban 
255862c60062Sbaban 	if (str == NULL)
255962c60062Sbaban 		return (0);
256062c60062Sbaban 	for (len = strlen(str), hval = 0, i = 0; i < len; i++) {
256162c60062Sbaban 		hval += str[i];
256262c60062Sbaban 		hval += (hval << 10);
256362c60062Sbaban 		hval ^= (hval >> 6);
256462c60062Sbaban 	}
256562c60062Sbaban 	for (str = (const char *)&num, i = 0; i < sizeof (num); i++) {
256662c60062Sbaban 		hval += str[i];
256762c60062Sbaban 		hval += (hval << 10);
256862c60062Sbaban 		hval ^= (hval >> 6);
256962c60062Sbaban 	}
257062c60062Sbaban 	hval += (hval << 3);
257162c60062Sbaban 	hval ^= (hval >> 11);
257262c60062Sbaban 	hval += (hval << 15);
257362c60062Sbaban 	return (hval % htsize);
257462c60062Sbaban }
257562c60062Sbaban 
257662c60062Sbaban static
257762c60062Sbaban int
257862c60062Sbaban get_from_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid,
2579cd37da74Snw141292 		uid_t *pid)
2580cd37da74Snw141292 {
258162c60062Sbaban 	uint_t		next, key;
258262c60062Sbaban 	uint_t		htsize = state->sid_history_size;
258362c60062Sbaban 	idmap_sid	*sid;
258462c60062Sbaban 
258562c60062Sbaban 	next = gethash(prefix, rid, htsize);
258662c60062Sbaban 	while (next != htsize) {
258762c60062Sbaban 		key = state->sid_history[next].key;
258862c60062Sbaban 		if (key == htsize)
258962c60062Sbaban 			return (0);
259062c60062Sbaban 		sid = &state->batch->idmap_mapping_batch_val[key].id1.
259162c60062Sbaban 		    idmap_id_u.sid;
259262c60062Sbaban 		if (sid->rid == rid && strcmp(sid->prefix, prefix) == 0) {
259362c60062Sbaban 			*pid = state->result->ids.ids_val[key].id.
259462c60062Sbaban 			    idmap_id_u.uid;
259562c60062Sbaban 			return (1);
259662c60062Sbaban 		}
259762c60062Sbaban 		next = state->sid_history[next].next;
259862c60062Sbaban 	}
259962c60062Sbaban 	return (0);
260062c60062Sbaban }
260162c60062Sbaban 
260262c60062Sbaban static
260362c60062Sbaban void
2604cd37da74Snw141292 add_to_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid)
2605cd37da74Snw141292 {
260662c60062Sbaban 	uint_t		hash, next;
260762c60062Sbaban 	uint_t		htsize = state->sid_history_size;
260862c60062Sbaban 
260962c60062Sbaban 	hash = next = gethash(prefix, rid, htsize);
261062c60062Sbaban 	while (state->sid_history[next].key != htsize) {
261162c60062Sbaban 		next++;
261262c60062Sbaban 		next %= htsize;
261362c60062Sbaban 	}
261462c60062Sbaban 	state->sid_history[next].key = state->curpos;
261562c60062Sbaban 	if (hash == next)
261662c60062Sbaban 		return;
261762c60062Sbaban 	state->sid_history[next].next = state->sid_history[hash].next;
261862c60062Sbaban 	state->sid_history[hash].next = next;
261962c60062Sbaban }
2620c5c4113dSnw141292 
2621*e8c27ec8Sbaban void
2622*e8c27ec8Sbaban cleanup_lookup_state(lookup_state_t *state)
2623*e8c27ec8Sbaban {
2624*e8c27ec8Sbaban 	free(state->sid_history);
2625*e8c27ec8Sbaban 	free(state->ad_unixuser_attr);
2626*e8c27ec8Sbaban 	free(state->ad_unixgroup_attr);
2627*e8c27ec8Sbaban }
2628*e8c27ec8Sbaban 
2629c5c4113dSnw141292 /* ARGSUSED */
2630c5c4113dSnw141292 static
2631c5c4113dSnw141292 idmap_retcode
263262c60062Sbaban dynamic_ephemeral_mapping(lookup_state_t *state, sqlite *cache,
2633cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
2634cd37da74Snw141292 {
2635c5c4113dSnw141292 
2636c5c4113dSnw141292 	uid_t		next_pid;
2637c5c4113dSnw141292 
2638651c0131Sbaban 	res->direction = IDMAP_DIRECTION_BI;
263962c60062Sbaban 
264062c60062Sbaban 	if (IS_EPHEMERAL(res->id.idmap_id_u.uid))
264162c60062Sbaban 		return (IDMAP_SUCCESS);
264262c60062Sbaban 
264362c60062Sbaban 	if (state->sid_history != NULL &&
264462c60062Sbaban 	    get_from_sid_history(state, req->id1.idmap_id_u.sid.prefix,
264562c60062Sbaban 	    req->id1.idmap_id_u.sid.rid, &next_pid)) {
264662c60062Sbaban 		res->id.idmap_id_u.uid = next_pid;
264762c60062Sbaban 		return (IDMAP_SUCCESS);
264862c60062Sbaban 	}
264962c60062Sbaban 
265062c60062Sbaban 	if (res->id.idtype == IDMAP_UID) {
2651c5c4113dSnw141292 		if (get_next_eph_uid(&next_pid) != 0)
2652c5c4113dSnw141292 			return (IDMAP_ERR_INTERNAL);
2653c5c4113dSnw141292 		res->id.idmap_id_u.uid = next_pid;
2654c5c4113dSnw141292 	} else {
2655c5c4113dSnw141292 		if (get_next_eph_gid(&next_pid) != 0)
2656c5c4113dSnw141292 			return (IDMAP_ERR_INTERNAL);
2657c5c4113dSnw141292 		res->id.idmap_id_u.gid = next_pid;
2658c5c4113dSnw141292 	}
2659c5c4113dSnw141292 
266062c60062Sbaban 	if (state->sid_history != NULL)
266162c60062Sbaban 		add_to_sid_history(state, req->id1.idmap_id_u.sid.prefix,
266262c60062Sbaban 		    req->id1.idmap_id_u.sid.rid);
266362c60062Sbaban 
2664c5c4113dSnw141292 	return (IDMAP_SUCCESS);
2665c5c4113dSnw141292 }
2666c5c4113dSnw141292 
2667c5c4113dSnw141292 idmap_retcode
2668c5c4113dSnw141292 sid2pid_second_pass(lookup_state_t *state, sqlite *cache, sqlite *db,
2669cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
2670cd37da74Snw141292 {
2671c5c4113dSnw141292 	idmap_retcode	retcode;
2672c5c4113dSnw141292 
2673c5c4113dSnw141292 	/* Check if second pass is needed */
2674*e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
2675c5c4113dSnw141292 		return (res->retcode);
2676c5c4113dSnw141292 
2677c5c4113dSnw141292 	/* Get status from previous pass */
2678*e8c27ec8Sbaban 	retcode = res->retcode;
2679*e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
2680*e8c27ec8Sbaban 		goto out;
2681c5c4113dSnw141292 
2682*e8c27ec8Sbaban 	/*
2683*e8c27ec8Sbaban 	 * If directory-based name mapping is enabled then the unixname
2684*e8c27ec8Sbaban 	 * may already have been retrieved from the AD object (AD-mode or
2685*e8c27ec8Sbaban 	 * mixed-mode) or from native LDAP object (nldap-mode) -- done.
2686*e8c27ec8Sbaban 	 */
2687*e8c27ec8Sbaban 	if (req->id2name != NULL) {
2688*e8c27ec8Sbaban 		assert(res->id.idtype != IDMAP_POSIXID);
2689*e8c27ec8Sbaban 		if (AD_MODE(res->id.idtype, state))
2690*e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
2691*e8c27ec8Sbaban 		else if (NLDAP_MODE(res->id.idtype, state))
2692*e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
2693*e8c27ec8Sbaban 		else if (MIXED_MODE(res->id.idtype, state))
2694*e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
2695c5c4113dSnw141292 
2696*e8c27ec8Sbaban 		/*
2697*e8c27ec8Sbaban 		 * Special case: (1) If the ad_unixuser_attr and
2698*e8c27ec8Sbaban 		 * ad_unixgroup_attr uses the same attribute
2699*e8c27ec8Sbaban 		 * name and (2) if this is a diagonal mapping
2700*e8c27ec8Sbaban 		 * request and (3) the unixname has been retrieved
2701*e8c27ec8Sbaban 		 * from the AD object -- then we ignore it and fallback
2702*e8c27ec8Sbaban 		 * to name-based mapping rules and ephemeral mapping
2703*e8c27ec8Sbaban 		 *
2704*e8c27ec8Sbaban 		 * Example:
2705*e8c27ec8Sbaban 		 *  Properties:
2706*e8c27ec8Sbaban 		 *    config/ad_unixuser_attr = "unixname"
2707*e8c27ec8Sbaban 		 *    config/ad_unixgroup_attr = "unixname"
2708*e8c27ec8Sbaban 		 *  AD user object:
2709*e8c27ec8Sbaban 		 *    dn: cn=bob ...
2710*e8c27ec8Sbaban 		 *    objectclass: user
2711*e8c27ec8Sbaban 		 *    sam: bob
2712*e8c27ec8Sbaban 		 *    unixname: bob1234
2713*e8c27ec8Sbaban 		 *  AD group object:
2714*e8c27ec8Sbaban 		 *    dn: cn=winadmins ...
2715*e8c27ec8Sbaban 		 *    objectclass: group
2716*e8c27ec8Sbaban 		 *    sam: winadmins
2717*e8c27ec8Sbaban 		 *    unixname: unixadmins
2718*e8c27ec8Sbaban 		 *
2719*e8c27ec8Sbaban 		 *  In this example whether "unixname" refers to a unixuser
2720*e8c27ec8Sbaban 		 *  or unixgroup depends upon the AD object.
2721*e8c27ec8Sbaban 		 *
2722*e8c27ec8Sbaban 		 * $idmap show -c winname:bob gid
2723*e8c27ec8Sbaban 		 *    AD lookup by "samAccountName=bob" for
2724*e8c27ec8Sbaban 		 *    "ad_unixgroup_attr (i.e unixname)" for directory-based
2725*e8c27ec8Sbaban 		 *    mapping would get "bob1234" which is not what we want.
2726*e8c27ec8Sbaban 		 *    Now why not getgrnam_r("bob1234") and use it if it
2727*e8c27ec8Sbaban 		 *    is indeed a unixgroup? That's because Unix can have
2728*e8c27ec8Sbaban 		 *    users and groups with the same name and we clearly
2729*e8c27ec8Sbaban 		 *    don't know the intention of the admin here.
2730*e8c27ec8Sbaban 		 *    Therefore we ignore this and fallback to name-based
2731*e8c27ec8Sbaban 		 *    mapping rules or ephemeral mapping.
2732*e8c27ec8Sbaban 		 */
2733*e8c27ec8Sbaban 		if ((AD_MODE(res->id.idtype, state) ||
2734*e8c27ec8Sbaban 		    MIXED_MODE(res->id.idtype, state)) &&
2735*e8c27ec8Sbaban 		    state->ad_unixuser_attr != NULL &&
2736*e8c27ec8Sbaban 		    state->ad_unixgroup_attr != NULL &&
2737*e8c27ec8Sbaban 		    strcasecmp(state->ad_unixuser_attr,
2738*e8c27ec8Sbaban 		    state->ad_unixgroup_attr) == 0 &&
2739*e8c27ec8Sbaban 		    ((req->id1.idtype == IDMAP_USID &&
2740*e8c27ec8Sbaban 		    res->id.idtype == IDMAP_GID) ||
2741*e8c27ec8Sbaban 		    (req->id1.idtype == IDMAP_GSID &&
2742*e8c27ec8Sbaban 		    res->id.idtype == IDMAP_UID))) {
2743*e8c27ec8Sbaban 			free(req->id2name);
2744*e8c27ec8Sbaban 			req->id2name = NULL;
2745*e8c27ec8Sbaban 			res->id.idmap_id_u.uid = SENTINEL_PID;
2746*e8c27ec8Sbaban 			/* fallback */
2747*e8c27ec8Sbaban 		} else {
2748*e8c27ec8Sbaban 			if (res->id.idmap_id_u.uid == SENTINEL_PID)
2749*e8c27ec8Sbaban 				retcode = ns_lookup_byname(req->id2name,
2750*e8c27ec8Sbaban 				    NULL, &res->id);
2751*e8c27ec8Sbaban 			/*
2752*e8c27ec8Sbaban 			 * We don't fallback to name-based mapping rules
2753*e8c27ec8Sbaban 			 * or ephemeral mapping.
2754*e8c27ec8Sbaban 			 */
2755c5c4113dSnw141292 			goto out;
2756c5c4113dSnw141292 		}
2757*e8c27ec8Sbaban 	}
2758c5c4113dSnw141292 
2759*e8c27ec8Sbaban 	/*
2760*e8c27ec8Sbaban 	 * If we don't have unixname then evaluate local name-based
2761*e8c27ec8Sbaban 	 * mapping rules.
2762*e8c27ec8Sbaban 	 */
2763c5c4113dSnw141292 	retcode = name_based_mapping_sid2pid(db, req, res);
2764*e8c27ec8Sbaban 	if (retcode != IDMAP_ERR_NOTFOUND)
2765*e8c27ec8Sbaban 		goto out;
2766*e8c27ec8Sbaban 
2767c5c4113dSnw141292 	/* If not found, do ephemeral mapping */
276862c60062Sbaban 	retcode = dynamic_ephemeral_mapping(state, cache, req, res);
2769c5c4113dSnw141292 
2770c5c4113dSnw141292 out:
2771c5c4113dSnw141292 	res->retcode = idmap_stat4prot(retcode);
2772*e8c27ec8Sbaban 	if (res->retcode != IDMAP_SUCCESS) {
2773*e8c27ec8Sbaban 		req->direction = _IDMAP_F_DONE;
2774*e8c27ec8Sbaban 		res->id.idmap_id_u.uid = UID_NOBODY;
2775*e8c27ec8Sbaban 	}
2776*e8c27ec8Sbaban 	if (!ARE_WE_DONE(req->direction))
2777*e8c27ec8Sbaban 		state->sid2pid_done = FALSE;
2778c5c4113dSnw141292 	return (retcode);
2779c5c4113dSnw141292 }
2780c5c4113dSnw141292 
2781c5c4113dSnw141292 idmap_retcode
2782c5c4113dSnw141292 update_cache_pid2sid(lookup_state_t *state, sqlite *cache,
2783cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
2784cd37da74Snw141292 {
2785c5c4113dSnw141292 	char		*sql = NULL;
2786c5c4113dSnw141292 	idmap_retcode	retcode;
2787c5c4113dSnw141292 
2788c5c4113dSnw141292 	/* Check if we need to cache anything */
2789*e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
2790c5c4113dSnw141292 		return (IDMAP_SUCCESS);
2791c5c4113dSnw141292 
2792c5c4113dSnw141292 	/* We don't cache negative entries */
2793c5c4113dSnw141292 	if (res->retcode != IDMAP_SUCCESS)
2794c5c4113dSnw141292 		return (IDMAP_SUCCESS);
2795c5c4113dSnw141292 
2796*e8c27ec8Sbaban 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
2797*e8c27ec8Sbaban 
2798c5c4113dSnw141292 	/*
2799c5c4113dSnw141292 	 * Using NULL for u2w instead of 0 so that our trigger allows
2800c5c4113dSnw141292 	 * the same pid to be the destination in multiple entries
2801c5c4113dSnw141292 	 */
2802c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
2803cd37da74Snw141292 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
2804cd37da74Snw141292 	    "is_user, is_wuser, expiration, w2u, u2w) "
2805cd37da74Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
2806c5c4113dSnw141292 	    "strftime('%%s','now') + 600, %q, 1); ",
2807cd37da74Snw141292 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
2808cd37da74Snw141292 	    req->id2domain, req->id2name, req->id1.idmap_id_u.uid,
2809cd37da74Snw141292 	    req->id1name, (req->id1.idtype == IDMAP_UID) ? 1 : 0,
2810*e8c27ec8Sbaban 	    (res->id.idtype == IDMAP_USID) ? 1 : 0,
2811c5c4113dSnw141292 	    (res->direction == 0) ? "1" : NULL);
2812c5c4113dSnw141292 
2813c5c4113dSnw141292 	if (sql == NULL) {
2814c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
2815c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2816c5c4113dSnw141292 		goto out;
2817c5c4113dSnw141292 	}
2818c5c4113dSnw141292 
2819c5c4113dSnw141292 	retcode = sql_exec_no_cb(cache, sql);
2820c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
2821c5c4113dSnw141292 		goto out;
2822c5c4113dSnw141292 
2823c5c4113dSnw141292 	state->pid2sid_done = FALSE;
2824c5c4113dSnw141292 	sqlite_freemem(sql);
2825c5c4113dSnw141292 	sql = NULL;
2826c5c4113dSnw141292 
2827*e8c27ec8Sbaban 	/* Check if we need to update namecache */
2828*e8c27ec8Sbaban 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
2829c5c4113dSnw141292 		goto out;
2830c5c4113dSnw141292 
28318e228215Sdm199847 	if (req->id2name == NULL)
2832c5c4113dSnw141292 		goto out;
2833c5c4113dSnw141292 
2834c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
2835cd37da74Snw141292 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
2836c5c4113dSnw141292 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
2837cd37da74Snw141292 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
2838cd37da74Snw141292 	    req->id2name, req->id2domain,
2839*e8c27ec8Sbaban 	    (res->id.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
2840c5c4113dSnw141292 
2841c5c4113dSnw141292 	if (sql == NULL) {
2842c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
2843c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2844c5c4113dSnw141292 		goto out;
2845c5c4113dSnw141292 	}
2846c5c4113dSnw141292 
2847c5c4113dSnw141292 	retcode = sql_exec_no_cb(cache, sql);
2848c5c4113dSnw141292 
2849c5c4113dSnw141292 out:
285062c60062Sbaban 	if (sql != NULL)
2851c5c4113dSnw141292 		sqlite_freemem(sql);
2852c5c4113dSnw141292 	return (retcode);
2853c5c4113dSnw141292 }
2854c5c4113dSnw141292 
2855c5c4113dSnw141292 idmap_retcode
2856c5c4113dSnw141292 update_cache_sid2pid(lookup_state_t *state, sqlite *cache,
2857cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
2858cd37da74Snw141292 {
2859c5c4113dSnw141292 	char		*sql = NULL;
2860c5c4113dSnw141292 	idmap_retcode	retcode;
2861c5c4113dSnw141292 	int		is_eph_user;
2862c5c4113dSnw141292 
2863c5c4113dSnw141292 	/* Check if we need to cache anything */
2864*e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
2865c5c4113dSnw141292 		return (IDMAP_SUCCESS);
2866c5c4113dSnw141292 
2867c5c4113dSnw141292 	/* We don't cache negative entries */
2868c5c4113dSnw141292 	if (res->retcode != IDMAP_SUCCESS)
2869c5c4113dSnw141292 		return (IDMAP_SUCCESS);
2870c5c4113dSnw141292 
2871c5c4113dSnw141292 	if (req->direction & _IDMAP_F_EXP_EPH_UID)
2872c5c4113dSnw141292 		is_eph_user = 1;
2873c5c4113dSnw141292 	else if (req->direction & _IDMAP_F_EXP_EPH_GID)
2874c5c4113dSnw141292 		is_eph_user = 0;
2875c5c4113dSnw141292 	else
2876c5c4113dSnw141292 		is_eph_user = -1;
2877c5c4113dSnw141292 
2878c5c4113dSnw141292 	if (is_eph_user >= 0 && !IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
2879c5c4113dSnw141292 		sql = sqlite_mprintf("UPDATE idmap_cache "
2880c5c4113dSnw141292 		    "SET w2u = 0 WHERE "
2881c5c4113dSnw141292 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
2882c5c4113dSnw141292 		    "pid >= 2147483648 AND is_user = %d;",
2883c5c4113dSnw141292 		    req->id1.idmap_id_u.sid.prefix,
2884c5c4113dSnw141292 		    req->id1.idmap_id_u.sid.rid,
2885c5c4113dSnw141292 		    is_eph_user);
2886c5c4113dSnw141292 		if (sql == NULL) {
2887c5c4113dSnw141292 			retcode = IDMAP_ERR_INTERNAL;
2888c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
2889c5c4113dSnw141292 			goto out;
2890c5c4113dSnw141292 		}
2891c5c4113dSnw141292 
2892c5c4113dSnw141292 		retcode = sql_exec_no_cb(cache, sql);
2893c5c4113dSnw141292 		if (retcode != IDMAP_SUCCESS)
2894c5c4113dSnw141292 			goto out;
2895c5c4113dSnw141292 
2896c5c4113dSnw141292 		sqlite_freemem(sql);
2897c5c4113dSnw141292 		sql = NULL;
2898c5c4113dSnw141292 	}
2899c5c4113dSnw141292 
2900*e8c27ec8Sbaban 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
2901cd37da74Snw141292 
2902c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
2903cd37da74Snw141292 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
2904cd37da74Snw141292 	    "is_user, is_wuser, expiration, w2u, u2w) "
2905cd37da74Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
2906c5c4113dSnw141292 	    "strftime('%%s','now') + 600, 1, %q); ",
2907cd37da74Snw141292 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
2908*e8c27ec8Sbaban 	    (req->id1domain != NULL) ? req->id1domain : "", req->id1name,
2909*e8c27ec8Sbaban 	    res->id.idmap_id_u.uid, req->id2name,
2910*e8c27ec8Sbaban 	    (res->id.idtype == IDMAP_UID) ? 1 : 0,
2911cd37da74Snw141292 	    (req->id1.idtype == IDMAP_USID) ? 1 : 0,
2912c5c4113dSnw141292 	    (res->direction == 0) ? "1" : NULL);
2913c5c4113dSnw141292 
2914c5c4113dSnw141292 	if (sql == NULL) {
2915c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
2916c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2917c5c4113dSnw141292 		goto out;
2918c5c4113dSnw141292 	}
2919c5c4113dSnw141292 
2920c5c4113dSnw141292 	retcode = sql_exec_no_cb(cache, sql);
2921c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
2922c5c4113dSnw141292 		goto out;
2923c5c4113dSnw141292 
2924c5c4113dSnw141292 	state->sid2pid_done = FALSE;
2925c5c4113dSnw141292 	sqlite_freemem(sql);
2926c5c4113dSnw141292 	sql = NULL;
2927c5c4113dSnw141292 
2928*e8c27ec8Sbaban 	/* Check if we need to update namecache */
2929*e8c27ec8Sbaban 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
2930c5c4113dSnw141292 		goto out;
2931c5c4113dSnw141292 
2932cf5b5989Sdm199847 	if (EMPTY_STRING(req->id1name))
2933c5c4113dSnw141292 		goto out;
2934c5c4113dSnw141292 
2935c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
2936cd37da74Snw141292 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
2937c5c4113dSnw141292 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
2938cd37da74Snw141292 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
2939cd37da74Snw141292 	    req->id1name, req->id1domain,
2940cd37da74Snw141292 	    (req->id1.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
2941c5c4113dSnw141292 
2942c5c4113dSnw141292 	if (sql == NULL) {
2943c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
2944c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2945c5c4113dSnw141292 		goto out;
2946c5c4113dSnw141292 	}
2947c5c4113dSnw141292 
2948c5c4113dSnw141292 	retcode = sql_exec_no_cb(cache, sql);
2949c5c4113dSnw141292 
2950c5c4113dSnw141292 out:
295162c60062Sbaban 	if (sql != NULL)
2952c5c4113dSnw141292 		sqlite_freemem(sql);
2953c5c4113dSnw141292 	return (retcode);
2954c5c4113dSnw141292 }
2955c5c4113dSnw141292 
2956cd37da74Snw141292 static
2957cd37da74Snw141292 idmap_retcode
2958c5c4113dSnw141292 lookup_cache_pid2sid(sqlite *cache, idmap_mapping *req, idmap_id_res *res,
2959cd37da74Snw141292 		int is_user, int getname)
2960cd37da74Snw141292 {
2961c5c4113dSnw141292 	char		*end;
2962c5c4113dSnw141292 	char		*sql = NULL;
2963c5c4113dSnw141292 	const char	**values;
2964c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
2965c5c4113dSnw141292 	int		ncol;
2966c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
2967c5c4113dSnw141292 	time_t		curtime;
2968*e8c27ec8Sbaban 	idmap_id_type	idtype;
2969c5c4113dSnw141292 
2970c5c4113dSnw141292 	/* Current time */
2971c5c4113dSnw141292 	errno = 0;
2972c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
2973cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
2974c5c4113dSnw141292 		    strerror(errno));
2975c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
2976c5c4113dSnw141292 		goto out;
2977c5c4113dSnw141292 	}
2978c5c4113dSnw141292 
2979*e8c27ec8Sbaban 	/* SQL to lookup the cache by pid or by unixname */
2980*e8c27ec8Sbaban 	if (req->id1.idmap_id_u.uid != SENTINEL_PID) {
2981*e8c27ec8Sbaban 		sql = sqlite_mprintf("SELECT sidprefix, rid, canon_winname, "
2982*e8c27ec8Sbaban 		    "windomain, w2u, is_wuser "
2983c5c4113dSnw141292 		    "FROM idmap_cache WHERE "
2984c5c4113dSnw141292 		    "pid = %u AND u2w = 1 AND is_user = %d AND "
2985c5c4113dSnw141292 		    "(pid >= 2147483648 OR "
2986c5c4113dSnw141292 		    "(expiration = 0 OR expiration ISNULL OR "
2987c5c4113dSnw141292 		    "expiration > %d));",
2988c5c4113dSnw141292 		    req->id1.idmap_id_u.uid, is_user, curtime);
2989*e8c27ec8Sbaban 	} else if (req->id1name != NULL) {
2990*e8c27ec8Sbaban 		sql = sqlite_mprintf("SELECT sidprefix, rid, canon_winname, "
2991*e8c27ec8Sbaban 		    "windomain, w2u, is_wuser "
2992*e8c27ec8Sbaban 		    "FROM idmap_cache WHERE "
2993*e8c27ec8Sbaban 		    "unixname = %Q AND u2w = 1 AND is_user = %d AND "
2994*e8c27ec8Sbaban 		    "(pid >= 2147483648 OR "
2995*e8c27ec8Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
2996*e8c27ec8Sbaban 		    "expiration > %d));",
2997*e8c27ec8Sbaban 		    req->id1name, is_user, curtime);
2998*e8c27ec8Sbaban 	}
2999*e8c27ec8Sbaban 
3000c5c4113dSnw141292 	if (sql == NULL) {
3001c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3002c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
3003c5c4113dSnw141292 		goto out;
3004c5c4113dSnw141292 	}
3005c5c4113dSnw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 5, &values);
3006c5c4113dSnw141292 	sqlite_freemem(sql);
3007c5c4113dSnw141292 
3008c5c4113dSnw141292 	if (retcode == IDMAP_ERR_NOTFOUND)
3009c5c4113dSnw141292 		goto out;
3010c5c4113dSnw141292 	else if (retcode == IDMAP_SUCCESS) {
3011c5c4113dSnw141292 		/* sanity checks */
3012c5c4113dSnw141292 		if (values[0] == NULL || values[1] == NULL) {
3013c5c4113dSnw141292 			retcode = IDMAP_ERR_CACHE;
3014c5c4113dSnw141292 			goto out;
3015c5c4113dSnw141292 		}
3016c5c4113dSnw141292 
3017*e8c27ec8Sbaban 		switch (res->id.idtype) {
3018c5c4113dSnw141292 		case IDMAP_SID:
3019cd37da74Snw141292 		case IDMAP_USID:
3020cd37da74Snw141292 		case IDMAP_GSID:
3021*e8c27ec8Sbaban 			idtype = strtol(values[5], &end, 10) == 1
3022cd37da74Snw141292 			    ? IDMAP_USID : IDMAP_GSID;
3023cd37da74Snw141292 
3024*e8c27ec8Sbaban 			if (res->id.idtype == IDMAP_USID &&
3025*e8c27ec8Sbaban 			    idtype != IDMAP_USID) {
3026cd37da74Snw141292 				retcode = IDMAP_ERR_NOTUSER;
3027cd37da74Snw141292 				goto out;
3028*e8c27ec8Sbaban 			} else if (res->id.idtype == IDMAP_GSID &&
3029*e8c27ec8Sbaban 			    idtype != IDMAP_GSID) {
3030cd37da74Snw141292 				retcode = IDMAP_ERR_NOTGROUP;
3031cd37da74Snw141292 				goto out;
3032cd37da74Snw141292 			}
3033*e8c27ec8Sbaban 			res->id.idtype = idtype;
3034cd37da74Snw141292 
3035c5c4113dSnw141292 			res->id.idmap_id_u.sid.rid =
3036c5c4113dSnw141292 			    strtoul(values[1], &end, 10);
3037c5c4113dSnw141292 			res->id.idmap_id_u.sid.prefix = strdup(values[0]);
3038c5c4113dSnw141292 			if (res->id.idmap_id_u.sid.prefix == NULL) {
3039c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
3040c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
3041c5c4113dSnw141292 				goto out;
3042c5c4113dSnw141292 			}
3043c5c4113dSnw141292 
304462c60062Sbaban 			if (values[4] != NULL)
3045c5c4113dSnw141292 				res->direction =
3046651c0131Sbaban 				    (strtol(values[4], &end, 10) == 0)?
3047651c0131Sbaban 				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
3048c5c4113dSnw141292 			else
3049651c0131Sbaban 				res->direction = IDMAP_DIRECTION_U2W;
3050c5c4113dSnw141292 
3051c5c4113dSnw141292 			if (getname == 0 || values[2] == NULL)
3052c5c4113dSnw141292 				break;
30538e228215Sdm199847 			req->id2name = strdup(values[2]);
30548e228215Sdm199847 			if (req->id2name == NULL) {
3055c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
3056c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
3057c5c4113dSnw141292 				goto out;
3058c5c4113dSnw141292 			}
3059c5c4113dSnw141292 
3060c5c4113dSnw141292 			if (values[3] == NULL)
3061c5c4113dSnw141292 				break;
30628e228215Sdm199847 			req->id2domain = strdup(values[3]);
30638e228215Sdm199847 			if (req->id2domain == NULL) {
3064c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
3065c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
3066c5c4113dSnw141292 				goto out;
3067c5c4113dSnw141292 			}
3068cd37da74Snw141292 
3069c5c4113dSnw141292 			break;
3070c5c4113dSnw141292 		default:
3071c5c4113dSnw141292 			retcode = IDMAP_ERR_NOTSUPPORTED;
3072c5c4113dSnw141292 			break;
3073c5c4113dSnw141292 		}
3074c5c4113dSnw141292 	}
3075c5c4113dSnw141292 
3076c5c4113dSnw141292 out:
307762c60062Sbaban 	if (vm != NULL)
3078c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
3079c5c4113dSnw141292 	return (retcode);
3080c5c4113dSnw141292 }
3081c5c4113dSnw141292 
3082cd37da74Snw141292 static
3083cd37da74Snw141292 idmap_retcode
3084c5c4113dSnw141292 lookup_cache_name2sid(sqlite *cache, const char *name, const char *domain,
3085cd37da74Snw141292 	char **canonname, char **sidprefix, idmap_rid_t *rid, int *type)
3086cd37da74Snw141292 {
3087cd37da74Snw141292 	char		*end, *lower_name;
3088c5c4113dSnw141292 	char		*sql = NULL;
3089c5c4113dSnw141292 	const char	**values;
3090c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
3091c5c4113dSnw141292 	int		ncol;
3092c5c4113dSnw141292 	time_t		curtime;
3093c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
3094c5c4113dSnw141292 
3095c5c4113dSnw141292 	/* Get current time */
3096c5c4113dSnw141292 	errno = 0;
3097c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
3098cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
3099c5c4113dSnw141292 		    strerror(errno));
3100c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3101c5c4113dSnw141292 		goto out;
3102c5c4113dSnw141292 	}
3103c5c4113dSnw141292 
3104c5c4113dSnw141292 	/* SQL to lookup the cache */
3105cd37da74Snw141292 	if ((lower_name = tolower_u8(name)) == NULL)
3106cd37da74Snw141292 		lower_name = (char *)name;
3107cd37da74Snw141292 	sql = sqlite_mprintf("SELECT sidprefix, rid, type, canon_name "
3108cd37da74Snw141292 	    "FROM name_cache WHERE name = %Q AND domain = %Q AND "
3109c5c4113dSnw141292 	    "(expiration = 0 OR expiration ISNULL OR "
3110cd37da74Snw141292 	    "expiration > %d);", lower_name, domain, curtime);
3111cd37da74Snw141292 	if (lower_name != name)
3112cd37da74Snw141292 		free(lower_name);
3113c5c4113dSnw141292 	if (sql == NULL) {
3114c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3115c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
3116c5c4113dSnw141292 		goto out;
3117c5c4113dSnw141292 	}
3118cd37da74Snw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 4, &values);
3119c5c4113dSnw141292 	sqlite_freemem(sql);
3120c5c4113dSnw141292 
3121c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
312262c60062Sbaban 		if (type != NULL) {
3123c5c4113dSnw141292 			if (values[2] == NULL) {
3124c5c4113dSnw141292 				retcode = IDMAP_ERR_CACHE;
3125c5c4113dSnw141292 				goto out;
3126c5c4113dSnw141292 			}
3127c5c4113dSnw141292 			*type = strtol(values[2], &end, 10);
3128c5c4113dSnw141292 		}
3129c5c4113dSnw141292 
3130*e8c27ec8Sbaban 		if (values[0] == NULL || values[1] == NULL) {
3131*e8c27ec8Sbaban 			retcode = IDMAP_ERR_CACHE;
3132*e8c27ec8Sbaban 			goto out;
3133*e8c27ec8Sbaban 		}
3134*e8c27ec8Sbaban 
3135cd37da74Snw141292 		if (canonname != NULL) {
3136cd37da74Snw141292 			assert(values[3] != NULL);
3137cd37da74Snw141292 			if ((*canonname = strdup(values[3])) == NULL) {
3138cd37da74Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
3139cd37da74Snw141292 				retcode = IDMAP_ERR_MEMORY;
3140cd37da74Snw141292 				goto out;
3141cd37da74Snw141292 			}
3142cd37da74Snw141292 		}
3143cd37da74Snw141292 
3144c5c4113dSnw141292 		if ((*sidprefix = strdup(values[0])) == NULL) {
3145c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
3146c5c4113dSnw141292 			retcode = IDMAP_ERR_MEMORY;
3147*e8c27ec8Sbaban 			if (canonname != NULL) {
3148*e8c27ec8Sbaban 				free(*canonname);
3149*e8c27ec8Sbaban 				*canonname = NULL;
3150*e8c27ec8Sbaban 			}
3151c5c4113dSnw141292 			goto out;
3152c5c4113dSnw141292 		}
3153c5c4113dSnw141292 		*rid = strtoul(values[1], &end, 10);
3154c5c4113dSnw141292 	}
3155c5c4113dSnw141292 
3156c5c4113dSnw141292 out:
315762c60062Sbaban 	if (vm != NULL)
3158c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
3159c5c4113dSnw141292 	return (retcode);
3160c5c4113dSnw141292 }
3161c5c4113dSnw141292 
3162cd37da74Snw141292 static
3163cd37da74Snw141292 idmap_retcode
3164*e8c27ec8Sbaban ad_lookup_by_winname(lookup_state_t *state,
3165*e8c27ec8Sbaban 		const char *name, const char *domain, int eunixtype,
3166*e8c27ec8Sbaban 		char **canonname, char **sidprefix,
3167*e8c27ec8Sbaban 		idmap_rid_t *rid, int *wintype, char **unixname)
3168cd37da74Snw141292 {
3169c5c4113dSnw141292 	int			retries = 0;
3170c5c4113dSnw141292 	idmap_query_state_t	*qs = NULL;
3171c5c4113dSnw141292 	idmap_retcode		rc, retcode;
3172c5c4113dSnw141292 
3173c5c4113dSnw141292 retry:
3174*e8c27ec8Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, 1, &qs);
3175*e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
3176c8e26105Sjp151216 		degrade_svc();
3177c5c4113dSnw141292 		idmapdlog(LOG_ERR,
3178*e8c27ec8Sbaban 		    "Failed to create request for AD lookup by winname");
3179*e8c27ec8Sbaban 		return (retcode);
3180c5c4113dSnw141292 	}
3181c5c4113dSnw141292 
3182c8e26105Sjp151216 	restore_svc();
3183c8e26105Sjp151216 
3184*e8c27ec8Sbaban 	if (state != NULL)
3185*e8c27ec8Sbaban 		idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
3186*e8c27ec8Sbaban 		    state->ad_unixgroup_attr);
3187c5c4113dSnw141292 
3188*e8c27ec8Sbaban 	retcode = idmap_name2sid_batch_add1(qs, name, domain, eunixtype,
3189*e8c27ec8Sbaban 	    canonname, sidprefix, rid, wintype, unixname, &rc);
3190c5c4113dSnw141292 
3191*e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
319284decf41Sjp151216 		idmap_lookup_release_batch(&qs);
3193c5c4113dSnw141292 	else
3194c5c4113dSnw141292 		retcode = idmap_lookup_batch_end(&qs, NULL);
3195c5c4113dSnw141292 
3196c5c4113dSnw141292 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
3197c5c4113dSnw141292 		goto retry;
3198c8e26105Sjp151216 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
3199c8e26105Sjp151216 		degrade_svc();
3200c5c4113dSnw141292 
3201c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS) {
3202*e8c27ec8Sbaban 		idmapdlog(LOG_NOTICE, "AD lookup by winname failed");
3203c5c4113dSnw141292 		return (retcode);
3204*e8c27ec8Sbaban 	}
3205c5c4113dSnw141292 	return (rc);
3206c5c4113dSnw141292 }
3207c5c4113dSnw141292 
3208cd37da74Snw141292 static
3209cd37da74Snw141292 idmap_retcode
3210c5c4113dSnw141292 lookup_name2sid(sqlite *cache, const char *name, const char *domain,
3211cd37da74Snw141292 		int *is_wuser, char **canonname, char **sidprefix,
3212cd37da74Snw141292 		idmap_rid_t *rid, idmap_mapping *req)
3213cd37da74Snw141292 {
3214c5c4113dSnw141292 	int		type;
3215c5c4113dSnw141292 	idmap_retcode	retcode;
3216c5c4113dSnw141292 
3217cd37da74Snw141292 	*sidprefix = NULL;
3218*e8c27ec8Sbaban 	if (canonname != NULL)
3219cd37da74Snw141292 		*canonname = NULL;
3220cd37da74Snw141292 
3221*e8c27ec8Sbaban 	/* Lookup well-known SIDs table */
3222cd37da74Snw141292 	retcode = lookup_wksids_name2sid(name, canonname, sidprefix, rid,
3223cd37da74Snw141292 	    &type);
322462c60062Sbaban 	if (retcode == IDMAP_SUCCESS) {
3225*e8c27ec8Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
322662c60062Sbaban 		goto out;
322762c60062Sbaban 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
322862c60062Sbaban 		return (retcode);
322962c60062Sbaban 	}
323062c60062Sbaban 
3231*e8c27ec8Sbaban 	/* Lookup cache */
3232cd37da74Snw141292 	retcode = lookup_cache_name2sid(cache, name, domain, canonname,
3233cd37da74Snw141292 	    sidprefix, rid, &type);
3234*e8c27ec8Sbaban 	if (retcode == IDMAP_SUCCESS) {
3235*e8c27ec8Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
3236*e8c27ec8Sbaban 		goto out;
3237*e8c27ec8Sbaban 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
3238*e8c27ec8Sbaban 		return (retcode);
3239*e8c27ec8Sbaban 	}
3240*e8c27ec8Sbaban 
3241*e8c27ec8Sbaban 	/* Lookup AD */
3242*e8c27ec8Sbaban 	retcode = ad_lookup_by_winname(NULL, name, domain, _IDMAP_T_UNDEF,
3243*e8c27ec8Sbaban 	    canonname, sidprefix, rid, &type, NULL);
3244c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
3245c5c4113dSnw141292 		return (retcode);
3246*e8c27ec8Sbaban 	/* Don't need to set req->direction |= _IDMAP_F_LOOKUP_AD; */
3247c5c4113dSnw141292 
324862c60062Sbaban out:
3249c5c4113dSnw141292 	/*
3250c5c4113dSnw141292 	 * Entry found (cache or Windows lookup)
3251cd37da74Snw141292 	 * is_wuser is both input as well as output parameter
3252c5c4113dSnw141292 	 */
3253*e8c27ec8Sbaban 	if (*is_wuser == 1 && type != _IDMAP_T_USER)
3254*e8c27ec8Sbaban 		retcode = IDMAP_ERR_NOTUSER;
3255*e8c27ec8Sbaban 	else if (*is_wuser == 0 && type != _IDMAP_T_GROUP)
3256*e8c27ec8Sbaban 		retcode = IDMAP_ERR_NOTGROUP;
3257*e8c27ec8Sbaban 	else if (*is_wuser == -1) {
3258c5c4113dSnw141292 		/* Caller wants to know if its user or group */
3259c5c4113dSnw141292 		if (type == _IDMAP_T_USER)
3260cd37da74Snw141292 			*is_wuser = 1;
3261c5c4113dSnw141292 		else if (type == _IDMAP_T_GROUP)
3262cd37da74Snw141292 			*is_wuser = 0;
3263*e8c27ec8Sbaban 		else
3264*e8c27ec8Sbaban 			retcode = IDMAP_ERR_SID;
3265*e8c27ec8Sbaban 	}
3266*e8c27ec8Sbaban 
3267*e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
3268cd37da74Snw141292 		free(*sidprefix);
3269cd37da74Snw141292 		*sidprefix = NULL;
3270*e8c27ec8Sbaban 		if (canonname != NULL) {
3271cd37da74Snw141292 			free(*canonname);
3272cd37da74Snw141292 			*canonname = NULL;
3273cd37da74Snw141292 		}
3274c5c4113dSnw141292 	}
3275c5c4113dSnw141292 	return (retcode);
3276c5c4113dSnw141292 }
3277c5c4113dSnw141292 
3278cd37da74Snw141292 static
3279cd37da74Snw141292 idmap_retcode
3280c5c4113dSnw141292 name_based_mapping_pid2sid(sqlite *db, sqlite *cache, const char *unixname,
3281cd37da74Snw141292 		int is_user, idmap_mapping *req, idmap_id_res *res)
3282cd37da74Snw141292 {
3283c5c4113dSnw141292 	const char	*winname, *windomain;
3284cd37da74Snw141292 	char		*canonname;
3285c8e26105Sjp151216 	char		*default_domain = NULL;
3286c5c4113dSnw141292 	char		*sql = NULL, *errmsg = NULL;
3287c5c4113dSnw141292 	idmap_retcode	retcode;
3288c5c4113dSnw141292 	char		*end;
3289c5c4113dSnw141292 	const char	**values;
3290c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
3291cd37da74Snw141292 	int		ncol, r, nrow;
3292cd37da74Snw141292 	int		is_wuser;
3293*e8c27ec8Sbaban 	const char	*me = "name_based_mapping_pid2sid";
3294*e8c27ec8Sbaban 
3295*e8c27ec8Sbaban 	assert(unixname != NULL); /* We have unixname */
3296*e8c27ec8Sbaban 	assert(req->id2name == NULL); /* We don't have winname */
3297*e8c27ec8Sbaban 	assert(res->id.idmap_id_u.sid.prefix == NULL); /* No SID either */
3298c5c4113dSnw141292 
3299c5c4113dSnw141292 	RDLOCK_CONFIG();
3300c8e26105Sjp151216 	if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
3301c8e26105Sjp151216 		default_domain =
3302c8e26105Sjp151216 		    strdup(_idmapdstate.cfg->pgcfg.default_domain);
3303c8e26105Sjp151216 		if (default_domain == NULL) {
3304c5c4113dSnw141292 			UNLOCK_CONFIG();
3305c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
3306c5c4113dSnw141292 			retcode = IDMAP_ERR_MEMORY;
3307c5c4113dSnw141292 			goto out;
3308c5c4113dSnw141292 		}
3309c5c4113dSnw141292 	}
3310c5c4113dSnw141292 	UNLOCK_CONFIG();
3311c5c4113dSnw141292 
3312c5c4113dSnw141292 	sql = sqlite_mprintf(
3313cd37da74Snw141292 	    "SELECT winname_display, windomain, w2u_order FROM namerules WHERE "
3314c5c4113dSnw141292 	    "u2w_order > 0 AND is_user = %d AND "
3315c5c4113dSnw141292 	    "(unixname = %Q OR unixname = '*') "
3316cd37da74Snw141292 	    "ORDER BY u2w_order ASC;", is_user, unixname);
3317c5c4113dSnw141292 	if (sql == NULL) {
3318c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3319c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
3320c5c4113dSnw141292 		goto out;
3321c5c4113dSnw141292 	}
3322c5c4113dSnw141292 
3323c5c4113dSnw141292 	if (sqlite_compile(db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
3324c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3325cd37da74Snw141292 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
3326cd37da74Snw141292 		    CHECK_NULL(errmsg));
3327c5c4113dSnw141292 		sqlite_freemem(errmsg);
3328c5c4113dSnw141292 		goto out;
3329c5c4113dSnw141292 	}
3330c5c4113dSnw141292 
3331cd37da74Snw141292 	for (nrow = 0; ; ) {
3332c5c4113dSnw141292 		r = sqlite_step(vm, &ncol, &values, NULL);
333384decf41Sjp151216 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
333484decf41Sjp151216 		if (r == SQLITE_ROW) {
3335cd37da74Snw141292 			nrow++;
3336c5c4113dSnw141292 			if (ncol < 3) {
3337c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
3338c5c4113dSnw141292 				goto out;
3339c5c4113dSnw141292 			}
3340c5c4113dSnw141292 			if (values[0] == NULL) {
3341c5c4113dSnw141292 				/* values [1] and [2] can be null */
3342c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
3343c5c4113dSnw141292 				goto out;
3344c5c4113dSnw141292 			}
3345c5c4113dSnw141292 			if (EMPTY_NAME(values[0])) {
3346c5c4113dSnw141292 				retcode = IDMAP_ERR_NOMAPPING;
3347c5c4113dSnw141292 				goto out;
3348c5c4113dSnw141292 			}
3349cd37da74Snw141292 
3350cd37da74Snw141292 			if (values[0][0] == '*') {
3351cd37da74Snw141292 				if (nrow > 1) {
3352cd37da74Snw141292 					/*
3353cd37da74Snw141292 					 * There were non-wildcard rules where
3354cd37da74Snw141292 					 * windows identity doesn't exist
3355cd37da74Snw141292 					 */
3356cd37da74Snw141292 					retcode = IDMAP_ERR_NOMAPPING;
3357cd37da74Snw141292 					goto out;
3358cd37da74Snw141292 				}
3359cd37da74Snw141292 				winname = unixname;
3360cd37da74Snw141292 			} else {
3361cd37da74Snw141292 				winname = values[0];
3362cd37da74Snw141292 			}
3363cd37da74Snw141292 
336462c60062Sbaban 			if (values[1] != NULL)
3365c5c4113dSnw141292 				windomain = values[1];
3366c8e26105Sjp151216 			else if (default_domain != NULL)
3367c8e26105Sjp151216 				windomain = default_domain;
3368c5c4113dSnw141292 			else {
3369cd37da74Snw141292 				idmapdlog(LOG_ERR, "%s: no domain", me);
3370c5c4113dSnw141292 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
3371c5c4113dSnw141292 				goto out;
3372c5c4113dSnw141292 			}
3373c5c4113dSnw141292 			/* Lookup winname@domain to sid */
3374cd37da74Snw141292 
3375cd37da74Snw141292 			is_wuser = res->id.idtype == IDMAP_USID ? 1
3376cd37da74Snw141292 			    : res->id.idtype == IDMAP_GSID ? 0
3377cd37da74Snw141292 			    : -1;
3378cd37da74Snw141292 
3379c5c4113dSnw141292 			retcode = lookup_name2sid(cache, winname, windomain,
3380cd37da74Snw141292 			    &is_wuser, &canonname,
3381cd37da74Snw141292 			    &res->id.idmap_id_u.sid.prefix,
3382c5c4113dSnw141292 			    &res->id.idmap_id_u.sid.rid, req);
3383*e8c27ec8Sbaban 
3384c5c4113dSnw141292 			if (retcode == IDMAP_ERR_NOTFOUND) {
3385c5c4113dSnw141292 				continue;
3386c5c4113dSnw141292 			}
3387cd37da74Snw141292 
3388c5c4113dSnw141292 			goto out;
3389c5c4113dSnw141292 		} else if (r == SQLITE_DONE) {
3390c5c4113dSnw141292 			retcode = IDMAP_ERR_NOTFOUND;
3391c5c4113dSnw141292 			goto out;
3392c5c4113dSnw141292 		} else {
3393c5c4113dSnw141292 			(void) sqlite_finalize(vm, &errmsg);
3394c5c4113dSnw141292 			vm = NULL;
3395cd37da74Snw141292 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
3396cd37da74Snw141292 			    CHECK_NULL(errmsg));
3397c5c4113dSnw141292 			sqlite_freemem(errmsg);
3398c5c4113dSnw141292 			retcode = IDMAP_ERR_INTERNAL;
3399c5c4113dSnw141292 			goto out;
3400c5c4113dSnw141292 		}
3401c5c4113dSnw141292 	}
3402c5c4113dSnw141292 
3403c5c4113dSnw141292 out:
340462c60062Sbaban 	if (sql != NULL)
3405c5c4113dSnw141292 		sqlite_freemem(sql);
3406c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
3407cd37da74Snw141292 		res->id.idtype = is_wuser ? IDMAP_USID : IDMAP_GSID;
3408cd37da74Snw141292 
340962c60062Sbaban 		if (values[2] != NULL)
3410c5c4113dSnw141292 			res->direction =
3411651c0131Sbaban 			    (strtol(values[2], &end, 10) == 0)?
3412651c0131Sbaban 			    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
3413c5c4113dSnw141292 		else
3414651c0131Sbaban 			res->direction = IDMAP_DIRECTION_U2W;
34158e228215Sdm199847 
3416cd37da74Snw141292 		req->id2name = canonname;
34178e228215Sdm199847 		if (req->id2name != NULL) {
3418c8e26105Sjp151216 			if (windomain == default_domain) {
34198e228215Sdm199847 				req->id2domain = (char *)windomain;
3420c8e26105Sjp151216 				default_domain = NULL;
34218e228215Sdm199847 			} else {
34228e228215Sdm199847 				req->id2domain = strdup(windomain);
34238e228215Sdm199847 			}
3424c5c4113dSnw141292 		}
3425c5c4113dSnw141292 	}
342662c60062Sbaban 	if (vm != NULL)
3427c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
3428c8e26105Sjp151216 	if (default_domain != NULL)
3429c8e26105Sjp151216 		free(default_domain);
3430c5c4113dSnw141292 	return (retcode);
3431c5c4113dSnw141292 }
3432c5c4113dSnw141292 
3433cd37da74Snw141292 /*
3434cd37da74Snw141292  * Convention when processing unix2win requests:
3435cd37da74Snw141292  *
3436cd37da74Snw141292  * Unix identity:
3437cd37da74Snw141292  * req->id1name =
3438cd37da74Snw141292  *              unixname if given otherwise unixname found will be placed
3439cd37da74Snw141292  *              here.
3440cd37da74Snw141292  * req->id1domain =
3441cd37da74Snw141292  *              NOT USED
3442cd37da74Snw141292  * req->id1.idtype =
3443cd37da74Snw141292  *              Given type (IDMAP_UID or IDMAP_GID)
3444cd37da74Snw141292  * req->id1..[uid or gid] =
3445cd37da74Snw141292  *              UID/GID if given otherwise UID/GID found will be placed here.
3446cd37da74Snw141292  *
3447cd37da74Snw141292  * Windows identity:
3448cd37da74Snw141292  * req->id2name =
3449cd37da74Snw141292  *              winname found will be placed here.
3450cd37da74Snw141292  * req->id2domain =
3451cd37da74Snw141292  *              windomain found will be placed here.
3452cd37da74Snw141292  * res->id.idtype =
3453cd37da74Snw141292  *              Target type initialized from req->id2.idtype. If
3454cd37da74Snw141292  *              it is IDMAP_SID then actual type (IDMAP_USID/GSID) found
3455cd37da74Snw141292  *              will be placed here.
3456cd37da74Snw141292  * req->id..sid.[prefix, rid] =
3457cd37da74Snw141292  *              SID found will be placed here.
3458cd37da74Snw141292  *
3459cd37da74Snw141292  * Others:
3460cd37da74Snw141292  * res->retcode =
3461cd37da74Snw141292  *              Return status for this request will be placed here.
3462cd37da74Snw141292  * res->direction =
3463cd37da74Snw141292  *              Direction found will be placed here. Direction
3464cd37da74Snw141292  *              meaning whether the resultant mapping is valid
3465cd37da74Snw141292  *              only from unix2win or bi-directional.
3466cd37da74Snw141292  * req->direction =
3467cd37da74Snw141292  *              INTERNAL USE. Used by idmapd to set various
3468cd37da74Snw141292  *              flags (_IDMAP_F_xxxx) to aid in processing
3469cd37da74Snw141292  *              of the request.
3470cd37da74Snw141292  * req->id2.idtype =
3471cd37da74Snw141292  *              INTERNAL USE. Initially this is the requested target
3472cd37da74Snw141292  *              type and is used to initialize res->id.idtype.
3473cd37da74Snw141292  *              ad_lookup_batch() uses this field temporarily to store
3474cd37da74Snw141292  *              sid_type obtained by the batched AD lookups and after
3475cd37da74Snw141292  *              use resets it to IDMAP_NONE to prevent xdr from
3476cd37da74Snw141292  *              mis-interpreting the contents of req->id2.
3477cd37da74Snw141292  * req->id2..[uid or gid or sid] =
3478cd37da74Snw141292  *              NOT USED
3479cd37da74Snw141292  */
3480cd37da74Snw141292 
3481cd37da74Snw141292 /*
3482cd37da74Snw141292  * This function does the following:
3483cd37da74Snw141292  * 1. Lookup well-known SIDs table.
3484cd37da74Snw141292  * 2. Lookup cache.
3485cd37da74Snw141292  * 3. Check if the client does not want new mapping to be allocated
3486cd37da74Snw141292  *    in which case this pass is the final pass.
3487*e8c27ec8Sbaban  * 4. Set AD/NLDAP lookup flags if it determines that the next stage needs
3488*e8c27ec8Sbaban  *    to do AD/NLDAP lookup.
3489cd37da74Snw141292  */
3490c5c4113dSnw141292 idmap_retcode
3491*e8c27ec8Sbaban pid2sid_first_pass(lookup_state_t *state, sqlite *cache,
3492c5c4113dSnw141292 		idmap_mapping *req, idmap_id_res *res, int is_user,
3493cd37da74Snw141292 		int getname)
3494cd37da74Snw141292 {
3495*e8c27ec8Sbaban 	idmap_retcode	retcode;
3496*e8c27ec8Sbaban 	bool_t		gen_localsid_on_err = FALSE;
3497c5c4113dSnw141292 
3498*e8c27ec8Sbaban 	/* Initialize result */
3499c5c4113dSnw141292 	res->id.idtype = req->id2.idtype;
3500*e8c27ec8Sbaban 	res->direction = IDMAP_DIRECTION_UNDEF;
3501c5c4113dSnw141292 
3502*e8c27ec8Sbaban 	if (req->id2.idmap_id_u.sid.prefix != NULL) {
3503*e8c27ec8Sbaban 		/* sanitize sidprefix */
3504*e8c27ec8Sbaban 		free(req->id2.idmap_id_u.sid.prefix);
3505*e8c27ec8Sbaban 		req->id2.idmap_id_u.sid.prefix = NULL;
3506*e8c27ec8Sbaban 	}
3507*e8c27ec8Sbaban 
3508*e8c27ec8Sbaban 	/* Lookup well-known SIDs table */
3509c5c4113dSnw141292 	retcode = lookup_wksids_pid2sid(req, res, is_user);
3510c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
3511c5c4113dSnw141292 		goto out;
3512c5c4113dSnw141292 
3513*e8c27ec8Sbaban 	/* Lookup cache */
3514c5c4113dSnw141292 	retcode = lookup_cache_pid2sid(cache, req, res, is_user, getname);
3515c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
3516c5c4113dSnw141292 		goto out;
3517c5c4113dSnw141292 
3518c5c4113dSnw141292 	/* Ephemeral ids cannot be allocated during pid2sid */
3519c5c4113dSnw141292 	if (IS_EPHEMERAL(req->id1.idmap_id_u.uid)) {
352062c60062Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
3521c5c4113dSnw141292 		goto out;
3522c5c4113dSnw141292 	}
3523c5c4113dSnw141292 
3524c5c4113dSnw141292 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req) || AVOID_NAMESERVICE(req)) {
3525*e8c27ec8Sbaban 		gen_localsid_on_err = TRUE;
352662c60062Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
3527c5c4113dSnw141292 		goto out;
3528c5c4113dSnw141292 	}
3529c5c4113dSnw141292 
3530*e8c27ec8Sbaban 	/* Set flags for the next stage */
3531*e8c27ec8Sbaban 	if (AD_MODE(req->id1.idtype, state)) {
3532*e8c27ec8Sbaban 		/*
3533*e8c27ec8Sbaban 		 * If AD-based name mapping is enabled then the next stage
3534*e8c27ec8Sbaban 		 * will need to lookup AD using unixname to get the
3535*e8c27ec8Sbaban 		 * corresponding winname.
3536*e8c27ec8Sbaban 		 */
3537*e8c27ec8Sbaban 		if (req->id1name == NULL) {
3538*e8c27ec8Sbaban 			/* Get unixname if only pid is given. */
3539*e8c27ec8Sbaban 			retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid,
3540*e8c27ec8Sbaban 			    is_user, &req->id1name);
3541*e8c27ec8Sbaban 			if (retcode != IDMAP_SUCCESS)
3542*e8c27ec8Sbaban 				goto out;
3543c5c4113dSnw141292 		}
3544*e8c27ec8Sbaban 		req->direction |= _IDMAP_F_LOOKUP_AD;
3545*e8c27ec8Sbaban 		state->ad_nqueries++;
3546*e8c27ec8Sbaban 	} else if (NLDAP_OR_MIXED_MODE(req->id1.idtype, state)) {
3547*e8c27ec8Sbaban 		/*
3548*e8c27ec8Sbaban 		 * If native LDAP or mixed mode is enabled for name mapping
3549*e8c27ec8Sbaban 		 * then the next stage will need to lookup native LDAP using
3550*e8c27ec8Sbaban 		 * unixname/pid to get the corresponding winname.
3551*e8c27ec8Sbaban 		 */
3552*e8c27ec8Sbaban 		req->direction |= _IDMAP_F_LOOKUP_NLDAP;
3553*e8c27ec8Sbaban 		state->nldap_nqueries++;
3554c5c4113dSnw141292 	}
3555c5c4113dSnw141292 
3556*e8c27ec8Sbaban 	/*
3557*e8c27ec8Sbaban 	 * Failed to find non-expired entry in cache. Set the flag to
3558*e8c27ec8Sbaban 	 * indicate that we are not done yet.
3559*e8c27ec8Sbaban 	 */
3560*e8c27ec8Sbaban 	state->pid2sid_done = FALSE;
3561*e8c27ec8Sbaban 	req->direction |= _IDMAP_F_NOTDONE;
3562*e8c27ec8Sbaban 	retcode = IDMAP_SUCCESS;
3563*e8c27ec8Sbaban 
3564*e8c27ec8Sbaban out:
3565*e8c27ec8Sbaban 	res->retcode = idmap_stat4prot(retcode);
3566*e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
3567*e8c27ec8Sbaban 		if (gen_localsid_on_err == TRUE)
3568*e8c27ec8Sbaban 			(void) generate_localsid(req, res, is_user);
3569*e8c27ec8Sbaban 	return (retcode);
3570*e8c27ec8Sbaban }
3571*e8c27ec8Sbaban 
3572*e8c27ec8Sbaban idmap_retcode
3573*e8c27ec8Sbaban pid2sid_second_pass(lookup_state_t *state, sqlite *cache, sqlite *db,
3574*e8c27ec8Sbaban 		idmap_mapping *req, idmap_id_res *res, int is_user)
3575*e8c27ec8Sbaban {
3576*e8c27ec8Sbaban 	bool_t		gen_localsid_on_err = TRUE;
3577*e8c27ec8Sbaban 	idmap_retcode	retcode = IDMAP_SUCCESS;
3578*e8c27ec8Sbaban 
3579*e8c27ec8Sbaban 	/* Check if second pass is needed */
3580*e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
3581*e8c27ec8Sbaban 		return (res->retcode);
3582*e8c27ec8Sbaban 
3583*e8c27ec8Sbaban 	/* Get status from previous pass */
3584*e8c27ec8Sbaban 	retcode = res->retcode;
3585*e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
3586*e8c27ec8Sbaban 		goto out;
3587*e8c27ec8Sbaban 
3588*e8c27ec8Sbaban 	/*
3589*e8c27ec8Sbaban 	 * If directory-based name mapping is enabled then the winname
3590*e8c27ec8Sbaban 	 * may already have been retrieved from the AD object (AD-mode)
3591*e8c27ec8Sbaban 	 * or from native LDAP object (nldap-mode or mixed-mode) -- done.
3592*e8c27ec8Sbaban 	 */
3593*e8c27ec8Sbaban 	if (res->id.idmap_id_u.sid.prefix != NULL || req->id2name != NULL) {
3594*e8c27ec8Sbaban 		if (AD_MODE(req->id1.idtype, state))
3595*e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
3596*e8c27ec8Sbaban 		else if (NLDAP_MODE(req->id1.idtype, state))
3597*e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
3598*e8c27ec8Sbaban 		else if (MIXED_MODE(req->id1.idtype, state))
3599*e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
3600*e8c27ec8Sbaban 		goto out;
3601*e8c27ec8Sbaban 	}
3602*e8c27ec8Sbaban 
3603*e8c27ec8Sbaban 	if (req->id1name == NULL) {
3604*e8c27ec8Sbaban 		/* Get unixname from name service */
3605*e8c27ec8Sbaban 		retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid, is_user,
3606*e8c27ec8Sbaban 		    &req->id1name);
3607*e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS)
3608*e8c27ec8Sbaban 			goto out;
3609*e8c27ec8Sbaban 	} else if (req->id1.idmap_id_u.uid == SENTINEL_PID) {
3610*e8c27ec8Sbaban 		/* Get pid from name service */
3611*e8c27ec8Sbaban 		retcode = ns_lookup_byname(req->id1name, NULL, &req->id1);
3612*e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS) {
3613*e8c27ec8Sbaban 			gen_localsid_on_err = FALSE;
3614*e8c27ec8Sbaban 			goto out;
3615*e8c27ec8Sbaban 		}
3616*e8c27ec8Sbaban 	}
3617*e8c27ec8Sbaban 
3618*e8c27ec8Sbaban 	/* Use unixname to evaluate local name-based mapping rules */
3619*e8c27ec8Sbaban 	retcode = name_based_mapping_pid2sid(db, cache, req->id1name, is_user,
3620c5c4113dSnw141292 	    req, res);
3621c5c4113dSnw141292 	if (retcode == IDMAP_ERR_NOTFOUND) {
3622c5c4113dSnw141292 		retcode = generate_localsid(req, res, is_user);
3623*e8c27ec8Sbaban 		gen_localsid_on_err = FALSE;
3624*e8c27ec8Sbaban 	}
3625c5c4113dSnw141292 
3626c5c4113dSnw141292 out:
3627c5c4113dSnw141292 	res->retcode = idmap_stat4prot(retcode);
3628*e8c27ec8Sbaban 	if (res->retcode != IDMAP_SUCCESS) {
3629*e8c27ec8Sbaban 		req->direction = _IDMAP_F_DONE;
3630*e8c27ec8Sbaban 		if (gen_localsid_on_err == TRUE)
3631*e8c27ec8Sbaban 			(void) generate_localsid(req, res, is_user);
3632*e8c27ec8Sbaban 	}
3633*e8c27ec8Sbaban 	if (!ARE_WE_DONE(req->direction))
3634*e8c27ec8Sbaban 		state->pid2sid_done = FALSE;
3635c5c4113dSnw141292 	return (retcode);
3636c5c4113dSnw141292 }
3637c5c4113dSnw141292 
3638cd37da74Snw141292 static
3639cd37da74Snw141292 idmap_retcode
3640*e8c27ec8Sbaban ad_lookup_by_sid(lookup_state_t *state,
3641*e8c27ec8Sbaban 		const char *sidprefix, idmap_rid_t rid, int eunixtype,
3642*e8c27ec8Sbaban 		char **name, char **domain, int *type, char **unixname)
3643cd37da74Snw141292 {
3644*e8c27ec8Sbaban 	int			retries = 0;
3645c5c4113dSnw141292 	idmap_query_state_t	*qs = NULL;
3646c5c4113dSnw141292 	idmap_retcode		rc, retcode;
3647c5c4113dSnw141292 
3648*e8c27ec8Sbaban retry:
3649*e8c27ec8Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, 1, &qs);
3650*e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
3651c8e26105Sjp151216 		degrade_svc();
3652c5c4113dSnw141292 		idmapdlog(LOG_ERR,
3653*e8c27ec8Sbaban 		    "Failed to create request for AD lookup by SID");
3654*e8c27ec8Sbaban 		return (retcode);
3655c5c4113dSnw141292 	}
3656c5c4113dSnw141292 
3657c8e26105Sjp151216 	restore_svc();
3658c8e26105Sjp151216 
3659*e8c27ec8Sbaban 	if (state != NULL)
3660*e8c27ec8Sbaban 		idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
3661*e8c27ec8Sbaban 		    state->ad_unixgroup_attr);
3662c5c4113dSnw141292 
3663*e8c27ec8Sbaban 	retcode = idmap_sid2name_batch_add1(qs, sidprefix, &rid, eunixtype,
3664*e8c27ec8Sbaban 	    name, domain, type, unixname, &rc);
3665*e8c27ec8Sbaban 
3666*e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
3667*e8c27ec8Sbaban 		idmap_lookup_release_batch(&qs);
3668*e8c27ec8Sbaban 	else
3669*e8c27ec8Sbaban 		retcode = idmap_lookup_batch_end(&qs, NULL);
3670*e8c27ec8Sbaban 
3671*e8c27ec8Sbaban 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
3672*e8c27ec8Sbaban 		goto retry;
3673*e8c27ec8Sbaban 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
3674c8e26105Sjp151216 		degrade_svc();
3675c5c4113dSnw141292 
3676*e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
3677*e8c27ec8Sbaban 		idmapdlog(LOG_NOTICE, "AD lookup by SID failed");
3678c5c4113dSnw141292 		return (retcode);
3679c5c4113dSnw141292 	}
3680*e8c27ec8Sbaban 	return (rc);
3681*e8c27ec8Sbaban }
3682c5c4113dSnw141292 
3683cd37da74Snw141292 static
3684cd37da74Snw141292 int
3685651c0131Sbaban copy_mapping_request(idmap_mapping *mapping, idmap_mapping *request)
3686c5c4113dSnw141292 {
3687651c0131Sbaban 	(void) memset(mapping, 0, sizeof (*mapping));
3688651c0131Sbaban 
3689c5c4113dSnw141292 	mapping->flag = request->flag;
3690*e8c27ec8Sbaban 	mapping->direction = _IDMAP_F_DONE;
3691651c0131Sbaban 	mapping->id2.idtype = request->id2.idtype;
3692c5c4113dSnw141292 
3693c5c4113dSnw141292 	mapping->id1.idtype = request->id1.idtype;
3694cd37da74Snw141292 	if (IS_REQUEST_SID(*request, 1)) {
3695c5c4113dSnw141292 		mapping->id1.idmap_id_u.sid.rid =
3696c5c4113dSnw141292 		    request->id1.idmap_id_u.sid.rid;
3697651c0131Sbaban 		if (!EMPTY_STRING(request->id1.idmap_id_u.sid.prefix)) {
3698c5c4113dSnw141292 			mapping->id1.idmap_id_u.sid.prefix =
3699c5c4113dSnw141292 			    strdup(request->id1.idmap_id_u.sid.prefix);
3700651c0131Sbaban 			if (mapping->id1.idmap_id_u.sid.prefix == NULL)
37018e228215Sdm199847 				goto errout;
3702651c0131Sbaban 		}
3703c5c4113dSnw141292 	} else {
3704c5c4113dSnw141292 		mapping->id1.idmap_id_u.uid = request->id1.idmap_id_u.uid;
3705c5c4113dSnw141292 	}
3706c5c4113dSnw141292 
3707*e8c27ec8Sbaban 	if (!EMPTY_STRING(request->id1domain)) {
37088e228215Sdm199847 		mapping->id1domain = strdup(request->id1domain);
37098e228215Sdm199847 		if (mapping->id1domain == NULL)
37108e228215Sdm199847 			goto errout;
3711*e8c27ec8Sbaban 	}
3712c5c4113dSnw141292 
3713*e8c27ec8Sbaban 	if (!EMPTY_STRING(request->id1name)) {
37148e228215Sdm199847 		mapping->id1name = strdup(request->id1name);
37158e228215Sdm199847 		if (mapping->id1name == NULL)
37168e228215Sdm199847 			goto errout;
3717*e8c27ec8Sbaban 	}
3718c5c4113dSnw141292 
3719651c0131Sbaban 	/* We don't need the rest of the request i.e request->id2 */
3720651c0131Sbaban 	return (0);
3721c5c4113dSnw141292 
3722651c0131Sbaban errout:
37238e228215Sdm199847 	if (mapping->id1.idmap_id_u.sid.prefix != NULL)
3724651c0131Sbaban 		free(mapping->id1.idmap_id_u.sid.prefix);
37258e228215Sdm199847 	if (mapping->id1domain != NULL)
37268e228215Sdm199847 		free(mapping->id1domain);
37278e228215Sdm199847 	if (mapping->id1name != NULL)
37288e228215Sdm199847 		free(mapping->id1name);
3729651c0131Sbaban 
3730651c0131Sbaban 	(void) memset(mapping, 0, sizeof (*mapping));
3731651c0131Sbaban 	return (-1);
3732c5c4113dSnw141292 }
3733c5c4113dSnw141292 
3734c5c4113dSnw141292 
3735c5c4113dSnw141292 idmap_retcode
3736c5c4113dSnw141292 get_w2u_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
3737cd37da74Snw141292 		idmap_mapping *mapping)
3738cd37da74Snw141292 {
3739c5c4113dSnw141292 	idmap_id_res	idres;
3740c5c4113dSnw141292 	lookup_state_t	state;
3741dd5829d1Sbaban 	char		*cp;
3742c5c4113dSnw141292 	idmap_retcode	retcode;
3743c5c4113dSnw141292 	const char	*winname, *windomain;
3744c5c4113dSnw141292 
3745c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
3746c5c4113dSnw141292 	(void) memset(&state, 0, sizeof (state));
3747c5c4113dSnw141292 
3748*e8c27ec8Sbaban 	/* Get directory-based name mapping info */
3749*e8c27ec8Sbaban 	retcode = get_ds_namemap_type(&state);
3750*e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
3751c5c4113dSnw141292 		goto out;
3752c5c4113dSnw141292 
3753*e8c27ec8Sbaban 	/*
3754*e8c27ec8Sbaban 	 * Copy data from "request" to "mapping". Note that
3755*e8c27ec8Sbaban 	 * empty strings are not copied from "request" to
3756*e8c27ec8Sbaban 	 * "mapping" and therefore the coresponding strings in
3757*e8c27ec8Sbaban 	 * "mapping" will be NULL. This eliminates having to
3758*e8c27ec8Sbaban 	 * check for empty strings henceforth.
3759*e8c27ec8Sbaban 	 */
3760651c0131Sbaban 	if (copy_mapping_request(mapping, request) < 0) {
3761651c0131Sbaban 		retcode = IDMAP_ERR_MEMORY;
3762651c0131Sbaban 		goto out;
3763651c0131Sbaban 	}
3764c5c4113dSnw141292 
37658e228215Sdm199847 	winname = mapping->id1name;
37668e228215Sdm199847 	windomain = mapping->id1domain;
3767c5c4113dSnw141292 
3768*e8c27ec8Sbaban 	if (winname == NULL && windomain != NULL) {
3769c5c4113dSnw141292 		retcode = IDMAP_ERR_ARG;
3770c5c4113dSnw141292 		goto out;
3771c5c4113dSnw141292 	}
3772c5c4113dSnw141292 
3773*e8c27ec8Sbaban 	/* Need atleast winname or sid to proceed */
3774*e8c27ec8Sbaban 	if (winname == NULL && mapping->id1.idmap_id_u.sid.prefix == NULL) {
3775*e8c27ec8Sbaban 		retcode = IDMAP_ERR_ARG;
3776*e8c27ec8Sbaban 		goto out;
3777*e8c27ec8Sbaban 	}
3778*e8c27ec8Sbaban 
3779*e8c27ec8Sbaban 	/*
3780*e8c27ec8Sbaban 	 * If domainname is not given but we have a fully qualified
3781*e8c27ec8Sbaban 	 * winname then extract the domainname from the winname,
3782*e8c27ec8Sbaban 	 * otherwise use the default_domain from the config
3783*e8c27ec8Sbaban 	 */
3784*e8c27ec8Sbaban 	if (winname != NULL && windomain == NULL) {
37858e228215Sdm199847 		retcode = IDMAP_SUCCESS;
3786dd5829d1Sbaban 		if ((cp = strchr(winname, '@')) != NULL) {
3787dd5829d1Sbaban 			*cp = '\0';
37888e228215Sdm199847 			mapping->id1domain = strdup(cp + 1);
37898e228215Sdm199847 			if (mapping->id1domain == NULL)
37908e228215Sdm199847 				retcode = IDMAP_ERR_MEMORY;
3791*e8c27ec8Sbaban 		} else if (lookup_wksids_name2sid(winname, NULL, NULL, NULL,
3792*e8c27ec8Sbaban 		    NULL) != IDMAP_SUCCESS) {
3793*e8c27ec8Sbaban 			/* well-known SIDs don't need domain */
37948e228215Sdm199847 			RDLOCK_CONFIG();
3795c8e26105Sjp151216 			if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
37968e228215Sdm199847 				mapping->id1domain =
37978e228215Sdm199847 				    strdup(_idmapdstate.cfg->
3798c8e26105Sjp151216 				    pgcfg.default_domain);
37998e228215Sdm199847 				if (mapping->id1domain == NULL)
38008e228215Sdm199847 					retcode = IDMAP_ERR_MEMORY;
3801*e8c27ec8Sbaban 			} else {
3802*e8c27ec8Sbaban 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
38038e228215Sdm199847 			}
3804c5c4113dSnw141292 			UNLOCK_CONFIG();
38058e228215Sdm199847 		}
3806c5c4113dSnw141292 		if (retcode != IDMAP_SUCCESS)
3807c5c4113dSnw141292 			goto out;
3808c5c4113dSnw141292 	}
3809c5c4113dSnw141292 
3810*e8c27ec8Sbaban 	/*
3811*e8c27ec8Sbaban 	 * First pass looks up the well-known SIDs table and cache
3812*e8c27ec8Sbaban 	 * and handles localSIDs
3813*e8c27ec8Sbaban 	 */
3814c5c4113dSnw141292 	state.sid2pid_done = TRUE;
3815c5c4113dSnw141292 	retcode = sid2pid_first_pass(&state, cache, mapping, &idres);
3816c5c4113dSnw141292 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
3817c5c4113dSnw141292 		goto out;
3818c5c4113dSnw141292 
3819*e8c27ec8Sbaban 	/* AD lookup by winname or by sid */
3820*e8c27ec8Sbaban 	if (state.ad_nqueries > 0) {
3821*e8c27ec8Sbaban 		retcode = ad_lookup(&state, mapping, &idres, 1, 1, 0);
3822*e8c27ec8Sbaban 		if (IDMAP_ERROR(retcode))
3823*e8c27ec8Sbaban 			goto out;
3824c5c4113dSnw141292 	}
3825c5c4113dSnw141292 
3826*e8c27ec8Sbaban 	/*
3827*e8c27ec8Sbaban 	 * If nldap-based name mapping is enabled then lookup native LDAP
3828*e8c27ec8Sbaban 	 * directory service by winname to get pid and unixname. Ignore
3829*e8c27ec8Sbaban 	 * non-fatal errors in which case we simply fallback to evaluating
3830*e8c27ec8Sbaban 	 * local name-based mapping rules.
3831*e8c27ec8Sbaban 	 */
3832*e8c27ec8Sbaban 	if (mapping->id1name != NULL && NLDAP_MODE(idres.id.idtype, (&state))) {
3833*e8c27ec8Sbaban 		retcode = nldap_lookup(mapping, &idres, 1, 1);
3834*e8c27ec8Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
3835*e8c27ec8Sbaban 			goto out;
3836*e8c27ec8Sbaban 		idres.retcode = IDMAP_SUCCESS;
3837*e8c27ec8Sbaban 	}
3838*e8c27ec8Sbaban 
3839*e8c27ec8Sbaban 	/* Next pass performs name-based mapping and ephemeral mapping. */
3840c5c4113dSnw141292 	state.sid2pid_done = TRUE;
3841c5c4113dSnw141292 	retcode = sid2pid_second_pass(&state, cache, db, mapping, &idres);
3842c5c4113dSnw141292 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
3843c5c4113dSnw141292 		goto out;
3844c5c4113dSnw141292 
3845c5c4113dSnw141292 	/* Update cache */
3846c5c4113dSnw141292 	(void) update_cache_sid2pid(&state, cache, mapping, &idres);
3847c5c4113dSnw141292 
3848c5c4113dSnw141292 out:
3849*e8c27ec8Sbaban 	/*
3850*e8c27ec8Sbaban 	 * Note that "mapping" is returned to the client. Therefore
3851*e8c27ec8Sbaban 	 * copy whatever we have in "idres" to mapping->id2 and
3852*e8c27ec8Sbaban 	 * free idres.
3853*e8c27ec8Sbaban 	 */
3854c5c4113dSnw141292 	mapping->direction = idres.direction;
3855c5c4113dSnw141292 	mapping->id2 = idres.id;
3856c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
3857*e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
385862c60062Sbaban 		mapping->id2.idmap_id_u.uid = UID_NOBODY;
3859c5c4113dSnw141292 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
3860*e8c27ec8Sbaban 	cleanup_lookup_state(&state);
3861c5c4113dSnw141292 	return (retcode);
3862c5c4113dSnw141292 }
3863c5c4113dSnw141292 
3864c5c4113dSnw141292 idmap_retcode
3865c5c4113dSnw141292 get_u2w_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
3866cd37da74Snw141292 		idmap_mapping *mapping, int is_user)
3867cd37da74Snw141292 {
3868c5c4113dSnw141292 	idmap_id_res	idres;
3869c5c4113dSnw141292 	lookup_state_t	state;
3870c5c4113dSnw141292 	idmap_retcode	retcode;
3871*e8c27ec8Sbaban 	char		*canonname;
3872*e8c27ec8Sbaban 	int		is_wuser;
3873c5c4113dSnw141292 
3874c5c4113dSnw141292 	/*
3875c5c4113dSnw141292 	 * In order to re-use the pid2sid code, we convert
3876c5c4113dSnw141292 	 * our input data into structs that are expected by
3877c5c4113dSnw141292 	 * pid2sid_first_pass.
3878c5c4113dSnw141292 	 */
3879c5c4113dSnw141292 
3880c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
3881c5c4113dSnw141292 	(void) memset(&state, 0, sizeof (state));
3882c5c4113dSnw141292 
3883*e8c27ec8Sbaban 	/* Get directory-based name mapping info */
3884*e8c27ec8Sbaban 	retcode = get_ds_namemap_type(&state);
3885*e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
3886*e8c27ec8Sbaban 		goto out;
3887*e8c27ec8Sbaban 
3888*e8c27ec8Sbaban 	/*
3889*e8c27ec8Sbaban 	 * Copy data from "request" to "mapping". Note that
3890*e8c27ec8Sbaban 	 * empty strings are not copied from "request" to
3891*e8c27ec8Sbaban 	 * "mapping" and therefore the coresponding strings in
3892*e8c27ec8Sbaban 	 * "mapping" will be NULL. This eliminates having to
3893*e8c27ec8Sbaban 	 * check for empty strings henceforth.
3894*e8c27ec8Sbaban 	 */
3895651c0131Sbaban 	if (copy_mapping_request(mapping, request) < 0) {
3896651c0131Sbaban 		retcode = IDMAP_ERR_MEMORY;
3897651c0131Sbaban 		goto out;
3898651c0131Sbaban 	}
3899c5c4113dSnw141292 
3900*e8c27ec8Sbaban 	/*
3901*e8c27ec8Sbaban 	 * For unix to windows mapping request, we need atleast a
3902*e8c27ec8Sbaban 	 * unixname or uid/gid to proceed
3903*e8c27ec8Sbaban 	 */
3904*e8c27ec8Sbaban 	if (mapping->id1name == NULL &&
3905cf5b5989Sdm199847 	    mapping->id1.idmap_id_u.uid == SENTINEL_PID) {
3906c5c4113dSnw141292 		retcode = IDMAP_ERR_ARG;
3907c5c4113dSnw141292 		goto out;
3908c5c4113dSnw141292 	}
3909c5c4113dSnw141292 
3910*e8c27ec8Sbaban 	/* First pass looks up cache and well-known SIDs */
3911*e8c27ec8Sbaban 	state.pid2sid_done = TRUE;
3912*e8c27ec8Sbaban 	retcode = pid2sid_first_pass(&state, cache, mapping, &idres,
3913*e8c27ec8Sbaban 	    is_user, 1);
3914*e8c27ec8Sbaban 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
3915c5c4113dSnw141292 		goto out;
3916*e8c27ec8Sbaban 
3917*e8c27ec8Sbaban 	if (state.nldap_nqueries > 0) {
3918*e8c27ec8Sbaban 		/*
3919*e8c27ec8Sbaban 		 * This means directory-based name mapping (nldap or mixed
3920*e8c27ec8Sbaban 		 * mode) is enabled. Lookup native LDAP directory service
3921*e8c27ec8Sbaban 		 * by unixname or pid to get the winname. Ignore non-fatal
3922*e8c27ec8Sbaban 		 * errors in which case we simply fallback to local name
3923*e8c27ec8Sbaban 		 * based mapping rules.
3924*e8c27ec8Sbaban 		 */
3925*e8c27ec8Sbaban 		retcode = nldap_lookup(mapping, &idres, 0, 0);
3926*e8c27ec8Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
3927c5c4113dSnw141292 			goto out;
3928*e8c27ec8Sbaban 		idres.retcode = IDMAP_SUCCESS;
3929*e8c27ec8Sbaban 
3930*e8c27ec8Sbaban 		/*
3931*e8c27ec8Sbaban 		 * If we've winname then get SID. We use lookup_name2sid()
3932*e8c27ec8Sbaban 		 * instead of ad_lookup() in order to first resolve name2sid
3933*e8c27ec8Sbaban 		 * using well-known SIDs table and name_cache before trying
3934*e8c27ec8Sbaban 		 * AD.
3935*e8c27ec8Sbaban 		 */
3936*e8c27ec8Sbaban 		if (mapping->id2name != NULL) {
3937*e8c27ec8Sbaban 			canonname = NULL;
3938*e8c27ec8Sbaban 			is_wuser = -1;
3939*e8c27ec8Sbaban 			retcode = lookup_name2sid(cache, mapping->id2name,
3940*e8c27ec8Sbaban 			    mapping->id2domain, &is_wuser, &canonname,
3941*e8c27ec8Sbaban 			    &idres.id.idmap_id_u.sid.prefix,
3942*e8c27ec8Sbaban 			    &idres.id.idmap_id_u.sid.rid, mapping);
3943*e8c27ec8Sbaban 			if (canonname != NULL) {
3944*e8c27ec8Sbaban 				free(mapping->id2name);
3945*e8c27ec8Sbaban 				mapping->id2name = canonname;
3946c5c4113dSnw141292 			}
3947*e8c27ec8Sbaban 			if (retcode == IDMAP_SUCCESS)
3948*e8c27ec8Sbaban 				idres.id.idtype = is_wuser ? IDMAP_USID :
3949*e8c27ec8Sbaban 				    IDMAP_GSID;
3950*e8c27ec8Sbaban 			idres.retcode = retcode;
3951c5c4113dSnw141292 		}
3952*e8c27ec8Sbaban 	} else if (state.ad_nqueries > 0) {
3953*e8c27ec8Sbaban 		/*
3954*e8c27ec8Sbaban 		 * This means AD-based name mapping is enabled.
3955*e8c27ec8Sbaban 		 * Lookup AD by unixname to get winname and sid.
3956*e8c27ec8Sbaban 		 * Ignore non-fatal errors in which case we simply fallback
3957*e8c27ec8Sbaban 		 * to local name based mapping rules.
3958*e8c27ec8Sbaban 		 */
3959*e8c27ec8Sbaban 		retcode = ad_lookup(&state, mapping, &idres, 0, 0, 1);
3960*e8c27ec8Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
3961*e8c27ec8Sbaban 			goto out;
3962*e8c27ec8Sbaban 		idres.retcode = IDMAP_SUCCESS;
3963c5c4113dSnw141292 	}
3964c5c4113dSnw141292 
3965*e8c27ec8Sbaban 	/*
3966*e8c27ec8Sbaban 	 * Next pass processes the result of the preceding passes/lookups.
3967*e8c27ec8Sbaban 	 * It returns if there's nothing more to be done otherwise it
3968*e8c27ec8Sbaban 	 * evaluates local name-based mapping rules
3969*e8c27ec8Sbaban 	 */
3970c5c4113dSnw141292 	state.pid2sid_done = TRUE;
3971*e8c27ec8Sbaban 	retcode = pid2sid_second_pass(&state, cache, db, mapping, &idres,
3972*e8c27ec8Sbaban 	    is_user);
3973c5c4113dSnw141292 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
3974c5c4113dSnw141292 		goto out;
3975c5c4113dSnw141292 
3976c5c4113dSnw141292 	/* Update cache */
3977c5c4113dSnw141292 	(void) update_cache_pid2sid(&state, cache, mapping, &idres);
3978c5c4113dSnw141292 
3979c5c4113dSnw141292 out:
3980*e8c27ec8Sbaban 	/*
3981*e8c27ec8Sbaban 	 * Note that "mapping" is returned to the client. Therefore
3982*e8c27ec8Sbaban 	 * copy whatever we have in "idres" to mapping->id2 and
3983*e8c27ec8Sbaban 	 * free idres.
3984*e8c27ec8Sbaban 	 */
3985c5c4113dSnw141292 	mapping->direction = idres.direction;
3986c5c4113dSnw141292 	mapping->id2 = idres.id;
3987c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
3988c5c4113dSnw141292 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
3989*e8c27ec8Sbaban 	cleanup_lookup_state(&state);
3990*e8c27ec8Sbaban 	return (retcode);
3991*e8c27ec8Sbaban }
3992*e8c27ec8Sbaban 
3993*e8c27ec8Sbaban static
3994*e8c27ec8Sbaban idmap_retcode
3995*e8c27ec8Sbaban ad_lookup_by_unixname(lookup_state_t *state,
3996*e8c27ec8Sbaban 		const char *unixname, int is_user, int is_wuser,
3997*e8c27ec8Sbaban 		char **sidprefix, idmap_rid_t *rid, char **winname,
3998*e8c27ec8Sbaban 		char **domain, int *type)
3999*e8c27ec8Sbaban {
4000*e8c27ec8Sbaban 	/* Lookup AD by unixname */
4001*e8c27ec8Sbaban 	int			retries = 0;
4002*e8c27ec8Sbaban 	idmap_query_state_t	*qs = NULL;
4003*e8c27ec8Sbaban 	idmap_retcode		rc, retcode;
4004*e8c27ec8Sbaban 
4005*e8c27ec8Sbaban retry:
4006*e8c27ec8Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, 1, &qs);
4007*e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
4008*e8c27ec8Sbaban 		degrade_svc();
4009*e8c27ec8Sbaban 		idmapdlog(LOG_ERR,
4010*e8c27ec8Sbaban 		    "Failed to create request for AD lookup by unixname");
4011*e8c27ec8Sbaban 		return (IDMAP_ERR_INTERNAL);
4012*e8c27ec8Sbaban 	}
4013*e8c27ec8Sbaban 
4014*e8c27ec8Sbaban 	restore_svc();
4015*e8c27ec8Sbaban 
4016*e8c27ec8Sbaban 	if (state != NULL)
4017*e8c27ec8Sbaban 		idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
4018*e8c27ec8Sbaban 		    state->ad_unixgroup_attr);
4019*e8c27ec8Sbaban 
4020*e8c27ec8Sbaban 	retcode = idmap_unixname2sid_batch_add1(qs, unixname, is_user,
4021*e8c27ec8Sbaban 	    is_wuser, sidprefix, rid, winname, domain, type, &rc);
4022*e8c27ec8Sbaban 
4023*e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
4024*e8c27ec8Sbaban 		idmap_lookup_release_batch(&qs);
4025*e8c27ec8Sbaban 	else
4026*e8c27ec8Sbaban 		retcode = idmap_lookup_batch_end(&qs, NULL);
4027*e8c27ec8Sbaban 
4028*e8c27ec8Sbaban 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
4029*e8c27ec8Sbaban 		goto retry;
4030*e8c27ec8Sbaban 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
4031*e8c27ec8Sbaban 		degrade_svc();
4032*e8c27ec8Sbaban 
4033*e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
4034*e8c27ec8Sbaban 		idmapdlog(LOG_NOTICE, "AD lookup by unixname failed");
4035*e8c27ec8Sbaban 		return (retcode);
4036*e8c27ec8Sbaban 	}
4037*e8c27ec8Sbaban 	return (rc);
4038*e8c27ec8Sbaban }
4039*e8c27ec8Sbaban 
4040*e8c27ec8Sbaban /*
4041*e8c27ec8Sbaban  * This function is called whenever a non-batched AD lookup needs to be
4042*e8c27ec8Sbaban  * done (e.g. get_w2u_mapping() and get_u2w_mapping()). It's already
4043*e8c27ec8Sbaban  * determined by the caller before calling this function that AD lookup is
4044*e8c27ec8Sbaban  * needed and has already searched the well-known SIDs table and name_cache.
4045*e8c27ec8Sbaban  */
4046*e8c27ec8Sbaban static
4047*e8c27ec8Sbaban idmap_retcode
4048*e8c27ec8Sbaban ad_lookup(lookup_state_t *state, idmap_mapping *req, idmap_id_res *res,
4049*e8c27ec8Sbaban 		int w2u, int getunixattr, int byunixattr)
4050*e8c27ec8Sbaban {
4051*e8c27ec8Sbaban 	idmap_retcode	retcode;
4052*e8c27ec8Sbaban 	int		type, eunixtype, is_user, is_wuser;
4053*e8c27ec8Sbaban 	char		*canonname = NULL;
4054*e8c27ec8Sbaban 
4055*e8c27ec8Sbaban 	if (w2u) {
4056*e8c27ec8Sbaban 		/*
4057*e8c27ec8Sbaban 		 * win2unix lookup requests (get_w2u_mapping()) calls this
4058*e8c27ec8Sbaban 		 * function to lookup by sid OR winname and to retrieve
4059*e8c27ec8Sbaban 		 * SID, winname, sidtype (user or group) and unixnames
4060*e8c27ec8Sbaban 		 * from AD.
4061*e8c27ec8Sbaban 		 */
4062*e8c27ec8Sbaban 
4063*e8c27ec8Sbaban 		/* Set the expected unixtype */
4064*e8c27ec8Sbaban 		if (res->id.idtype == IDMAP_UID)
4065*e8c27ec8Sbaban 			eunixtype = _IDMAP_T_USER;
4066*e8c27ec8Sbaban 		else if (res->id.idtype == IDMAP_GID)
4067*e8c27ec8Sbaban 			eunixtype = _IDMAP_T_GROUP;
4068*e8c27ec8Sbaban 		else
4069*e8c27ec8Sbaban 			eunixtype = _IDMAP_T_UNDEF;
4070*e8c27ec8Sbaban 
4071*e8c27ec8Sbaban 		if (req->id1.idmap_id_u.sid.prefix != NULL) {
4072*e8c27ec8Sbaban 			/* AD lookup by sid */
4073*e8c27ec8Sbaban 			retcode = ad_lookup_by_sid(
4074*e8c27ec8Sbaban 			    state, req->id1.idmap_id_u.sid.prefix,
4075*e8c27ec8Sbaban 			    req->id1.idmap_id_u.sid.rid, eunixtype,
4076*e8c27ec8Sbaban 			    (req->id1name == NULL) ? &req->id1name : NULL,
4077*e8c27ec8Sbaban 			    (req->id1domain == NULL) ? &req->id1domain : NULL,
4078*e8c27ec8Sbaban 			    &type, (getunixattr && req->id2name == NULL)
4079*e8c27ec8Sbaban 			    ? &req->id2name : NULL);
4080*e8c27ec8Sbaban 		} else {
4081*e8c27ec8Sbaban 			assert(req->id1name != NULL);
4082*e8c27ec8Sbaban 			/* AD lookup by winname */
4083*e8c27ec8Sbaban 			retcode = ad_lookup_by_winname(
4084*e8c27ec8Sbaban 			    state, req->id1name, req->id1domain, eunixtype,
4085*e8c27ec8Sbaban 			    &canonname, &req->id1.idmap_id_u.sid.prefix,
4086*e8c27ec8Sbaban 			    &req->id1.idmap_id_u.sid.rid, &type,
4087*e8c27ec8Sbaban 			    (getunixattr && req->id2name == NULL)
4088*e8c27ec8Sbaban 			    ? &req->id2name : NULL);
4089*e8c27ec8Sbaban 
4090*e8c27ec8Sbaban 			if (canonname != NULL) {
4091*e8c27ec8Sbaban 				free(req->id1name);
4092*e8c27ec8Sbaban 				req->id1name = canonname;
4093*e8c27ec8Sbaban 			}
4094*e8c27ec8Sbaban 		}
4095*e8c27ec8Sbaban 		if (retcode == IDMAP_SUCCESS) {
4096*e8c27ec8Sbaban 			switch (type) {
4097*e8c27ec8Sbaban 			case _IDMAP_T_USER:
4098*e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
4099*e8c27ec8Sbaban 					res->id.idtype = IDMAP_UID;
4100*e8c27ec8Sbaban 				req->id1.idtype = IDMAP_USID;
4101*e8c27ec8Sbaban 				break;
4102*e8c27ec8Sbaban 			case _IDMAP_T_GROUP:
4103*e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
4104*e8c27ec8Sbaban 					res->id.idtype = IDMAP_GID;
4105*e8c27ec8Sbaban 				req->id1.idtype = IDMAP_GSID;
4106*e8c27ec8Sbaban 				break;
4107*e8c27ec8Sbaban 			default:
4108*e8c27ec8Sbaban 				return (IDMAP_ERR_SID);
4109*e8c27ec8Sbaban 			}
4110*e8c27ec8Sbaban 		}
4111*e8c27ec8Sbaban 		return (retcode);
4112*e8c27ec8Sbaban 	}
4113*e8c27ec8Sbaban 
4114*e8c27ec8Sbaban 	/*
4115*e8c27ec8Sbaban 	 * unix2win lookup requests (get_u2w_mapping()) calls this
4116*e8c27ec8Sbaban 	 * function to lookup AD by unixname and to retrieve
4117*e8c27ec8Sbaban 	 * SID, winname, and sidtype (user or group) from AD.
4118*e8c27ec8Sbaban 	 */
4119*e8c27ec8Sbaban 
4120*e8c27ec8Sbaban 	/* Set the expected unixtype */
4121*e8c27ec8Sbaban 	eunixtype = (req->id1.idtype == IDMAP_UID) ? _IDMAP_T_USER :
4122*e8c27ec8Sbaban 	    _IDMAP_T_GROUP;
4123*e8c27ec8Sbaban 
4124*e8c27ec8Sbaban 	if (byunixattr) {
4125*e8c27ec8Sbaban 		/* AD lookup by unixname */
4126*e8c27ec8Sbaban 		is_user = (IS_REQUEST_UID(*req)) ? 1 : 0;
4127*e8c27ec8Sbaban 		if (res->id.idtype == IDMAP_USID)
4128*e8c27ec8Sbaban 			is_wuser = 1;
4129*e8c27ec8Sbaban 		else if (res->id.idtype == IDMAP_GSID)
4130*e8c27ec8Sbaban 			is_wuser = 0;
4131*e8c27ec8Sbaban 		else
4132*e8c27ec8Sbaban 			is_wuser = is_user;
4133*e8c27ec8Sbaban 		retcode = ad_lookup_by_unixname(
4134*e8c27ec8Sbaban 		    state, req->id1name, is_user, is_wuser,
4135*e8c27ec8Sbaban 		    (res->id.idmap_id_u.sid.prefix == NULL) ?
4136*e8c27ec8Sbaban 		    &res->id.idmap_id_u.sid.prefix : NULL,
4137*e8c27ec8Sbaban 		    (res->id.idmap_id_u.sid.prefix == NULL) ?
4138*e8c27ec8Sbaban 		    &res->id.idmap_id_u.sid.rid : NULL,
4139*e8c27ec8Sbaban 		    (req->id2name == NULL) ? &req->id2name : NULL,
4140*e8c27ec8Sbaban 		    (req->id2domain == NULL) ? &req->id2domain : NULL, NULL);
4141*e8c27ec8Sbaban 	} else if (res->id.idmap_id_u.sid.prefix != NULL) {
4142*e8c27ec8Sbaban 		/* AD lookup by sid */
4143*e8c27ec8Sbaban 		retcode = ad_lookup_by_sid(
4144*e8c27ec8Sbaban 		    state, res->id.idmap_id_u.sid.prefix,
4145*e8c27ec8Sbaban 		    res->id.idmap_id_u.sid.rid, eunixtype,
4146*e8c27ec8Sbaban 		    (req->id2name == NULL) ? &req->id2name : NULL,
4147*e8c27ec8Sbaban 		    (req->id2domain == NULL) ? &req->id2domain : NULL,
4148*e8c27ec8Sbaban 		    NULL, (getunixattr && req->id1name == NULL)
4149*e8c27ec8Sbaban 		    ? &req->id1name : NULL);
4150*e8c27ec8Sbaban 	} else {
4151*e8c27ec8Sbaban 		/* AD lookup by winname */
4152*e8c27ec8Sbaban 		assert(req->id2name != NULL);
4153*e8c27ec8Sbaban 		retcode = ad_lookup_by_winname(
4154*e8c27ec8Sbaban 		    state, req->id2name, req->id2domain, eunixtype,
4155*e8c27ec8Sbaban 		    &canonname, &res->id.idmap_id_u.sid.prefix,
4156*e8c27ec8Sbaban 		    &res->id.idmap_id_u.sid.rid, NULL,
4157*e8c27ec8Sbaban 		    (getunixattr && req->id1name == NULL)
4158*e8c27ec8Sbaban 		    ? &req->id1name : NULL);
4159*e8c27ec8Sbaban 
4160*e8c27ec8Sbaban 		if (canonname != NULL) {
4161*e8c27ec8Sbaban 			free(req->id2name);
4162*e8c27ec8Sbaban 			req->id2name = canonname;
4163*e8c27ec8Sbaban 		}
4164*e8c27ec8Sbaban 	}
4165*e8c27ec8Sbaban 
4166*e8c27ec8Sbaban 	if (retcode == IDMAP_SUCCESS) {
4167*e8c27ec8Sbaban 		switch (type) {
4168*e8c27ec8Sbaban 		case _IDMAP_T_USER:
4169*e8c27ec8Sbaban 			if (res->id.idtype == IDMAP_SID)
4170*e8c27ec8Sbaban 				res->id.idtype = IDMAP_USID;
4171*e8c27ec8Sbaban 			break;
4172*e8c27ec8Sbaban 		case _IDMAP_T_GROUP:
4173*e8c27ec8Sbaban 			if (res->id.idtype == IDMAP_SID)
4174*e8c27ec8Sbaban 				res->id.idtype = IDMAP_GSID;
4175*e8c27ec8Sbaban 			break;
4176*e8c27ec8Sbaban 		default:
4177*e8c27ec8Sbaban 			return (IDMAP_ERR_SID);
4178*e8c27ec8Sbaban 		}
4179*e8c27ec8Sbaban 	}
4180c5c4113dSnw141292 	return (retcode);
4181c5c4113dSnw141292 }
4182