xref: /titanic_50/usr/src/cmd/idmap/idmapd/dbutils.c (revision 0dcc71495bad040a0c83830efc85acf8d897350d)
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 /*
22042addd6Sbaban  * Copyright 2008 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"
53e8c27ec8Sbaban #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 *);
62e8c27ec8Sbaban static idmap_retcode ad_lookup(lookup_state_t *, idmap_mapping *,
63e8c27ec8Sbaban 		idmap_id_res *, int, int, int);
64e8c27ec8Sbaban static idmap_retcode lookup_localsid2pid(idmap_mapping *, idmap_id_res *);
65e8c27ec8Sbaban static idmap_retcode lookup_cache_name2sid(sqlite *, const char *,
66e8c27ec8Sbaban 		const char *, char **, char **, idmap_rid_t *, int *);
67e8c27ec8Sbaban 
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 
77e8c27ec8Sbaban #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 /*
88e8c27ec8Sbaban  * Data structure to store well-known SIDs and
89e8c27ec8Sbaban  * associated mappings (if any)
90e8c27ec8Sbaban  */
91e8c27ec8Sbaban typedef struct wksids_table {
92e8c27ec8Sbaban 	const char	*sidprefix;
93e8c27ec8Sbaban 	uint32_t	rid;
94e8c27ec8Sbaban 	const char	*winname;
95e8c27ec8Sbaban 	int		is_wuser;
96e8c27ec8Sbaban 	uid_t		pid;
97e8c27ec8Sbaban 	int		is_user;
98e8c27ec8Sbaban 	int		direction;
99e8c27ec8Sbaban } wksids_table_t;
100e8c27ec8Sbaban 
101e8c27ec8Sbaban /*
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
214*0dcc7149Snw141292 degrade_svc(const char *reason)
215c8e26105Sjp151216 {
216cd37da74Snw141292 	const char *fmri;
217cd37da74Snw141292 
218*0dcc7149Snw141292 	/*
219*0dcc7149Snw141292 	 * If the config update thread is in a state where auto-discovery could
220*0dcc7149Snw141292 	 * be re-tried, then this will make it try it -- a sort of auto-refresh.
221*0dcc7149Snw141292 	 */
222*0dcc7149Snw141292 	idmap_cfg_poke_updates();
223*0dcc7149Snw141292 
224cd37da74Snw141292 	if ((fmri = get_fmri()) == NULL)
225cd37da74Snw141292 		return;
226cd37da74Snw141292 
227c8e26105Sjp151216 	membar_consumer();
228c8e26105Sjp151216 	if (degraded)
229c8e26105Sjp151216 		return;
230c8e26105Sjp151216 	membar_producer();
231c8e26105Sjp151216 	degraded = 1;
232*0dcc7149Snw141292 	(void) smf_degrade_instance(fmri, 0);
233*0dcc7149Snw141292 	idmapdlog(LOG_ERR, "idmapd: Degraded operation (%s)", reason);
234c8e26105Sjp151216 }
235c8e26105Sjp151216 
236c8e26105Sjp151216 void
237c8e26105Sjp151216 restore_svc(void)
238c8e26105Sjp151216 {
239cd37da74Snw141292 	const char *fmri;
240cd37da74Snw141292 
241cd37da74Snw141292 	if ((fmri = get_fmri()) == NULL)
242cd37da74Snw141292 		return;
243cd37da74Snw141292 
244c8e26105Sjp151216 	membar_consumer();
245c8e26105Sjp151216 	if (!degraded)
246c8e26105Sjp151216 		return;
247cd37da74Snw141292 	(void) smf_restore_instance(fmri);
248c8e26105Sjp151216 	membar_producer();
249c8e26105Sjp151216 	degraded = 0;
250c8e26105Sjp151216 }
25184decf41Sjp151216 
252cd37da74Snw141292 /*
253cd37da74Snw141292  * A simple wrapper around u8_textprep_str() that returns the Unicode
254cd37da74Snw141292  * lower-case version of some string.  The result must be freed.
255cd37da74Snw141292  */
256cd37da74Snw141292 char *
257cd37da74Snw141292 tolower_u8(const char *s)
258cd37da74Snw141292 {
259cd37da74Snw141292 	char *res = NULL;
260cd37da74Snw141292 	char *outs;
261cd37da74Snw141292 	size_t inlen, outlen, inbytesleft, outbytesleft;
262cd37da74Snw141292 	int rc, err;
263cd37da74Snw141292 
264cd37da74Snw141292 	/*
265cd37da74Snw141292 	 * u8_textprep_str() does not allocate memory.  The input and
266cd37da74Snw141292 	 * output buffers may differ in size (though that would be more
267cd37da74Snw141292 	 * likely when normalization is done).  We have to loop over it...
268cd37da74Snw141292 	 *
269cd37da74Snw141292 	 * To improve the chances that we can avoid looping we add 10
270cd37da74Snw141292 	 * bytes of output buffer room the first go around.
271cd37da74Snw141292 	 */
272cd37da74Snw141292 	inlen = inbytesleft = strlen(s);
273cd37da74Snw141292 	outlen = outbytesleft = inlen + 10;
274cd37da74Snw141292 	if ((res = malloc(outlen)) == NULL)
275cd37da74Snw141292 		return (NULL);
276cd37da74Snw141292 	outs = res;
277cd37da74Snw141292 
278cd37da74Snw141292 	while ((rc = u8_textprep_str((char *)s, &inbytesleft, outs,
279cd37da74Snw141292 	    &outbytesleft, U8_TEXTPREP_TOLOWER, U8_UNICODE_LATEST, &err)) < 0 &&
280cd37da74Snw141292 	    err == E2BIG) {
281cd37da74Snw141292 		if ((res = realloc(res, outlen + inbytesleft)) == NULL)
282cd37da74Snw141292 			return (NULL);
283cd37da74Snw141292 		/* adjust input/output buffer pointers */
284cd37da74Snw141292 		s += (inlen - inbytesleft);
285cd37da74Snw141292 		outs = res + outlen - outbytesleft;
286cd37da74Snw141292 		/* adjust outbytesleft and outlen */
287cd37da74Snw141292 		outlen += inbytesleft;
288cd37da74Snw141292 		outbytesleft += inbytesleft;
289cd37da74Snw141292 	}
290cd37da74Snw141292 
291cd37da74Snw141292 	if (rc < 0) {
292cd37da74Snw141292 		free(res);
293cd37da74Snw141292 		res = NULL;
294cd37da74Snw141292 		return (NULL);
295cd37da74Snw141292 	}
296cd37da74Snw141292 
297cd37da74Snw141292 	res[outlen - outbytesleft] = '\0';
298cd37da74Snw141292 
299cd37da74Snw141292 	return (res);
300cd37da74Snw141292 }
301cd37da74Snw141292 
302cd37da74Snw141292 static int sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
303cd37da74Snw141292 	const char *while_doing);
304cd37da74Snw141292 
305c5c4113dSnw141292 
306c5c4113dSnw141292 /*
307c5c4113dSnw141292  * Initialize 'dbname' using 'sql'
308c5c4113dSnw141292  */
309cd37da74Snw141292 static
310cd37da74Snw141292 int
311cd37da74Snw141292 init_db_instance(const char *dbname, int version,
312cd37da74Snw141292 	const char *detect_version_sql, char * const *sql,
313cd37da74Snw141292 	init_db_option_t opt, int *created, int *upgraded)
314c5c4113dSnw141292 {
315cd37da74Snw141292 	int rc, curr_version;
316cd37da74Snw141292 	int tries = 1;
317cd37da74Snw141292 	int prio = LOG_NOTICE;
318c5c4113dSnw141292 	sqlite *db = NULL;
319cd37da74Snw141292 	char *errmsg = NULL;
320c5c4113dSnw141292 
321cd37da74Snw141292 	*created = 0;
322cd37da74Snw141292 	*upgraded = 0;
323c5c4113dSnw141292 
324cd37da74Snw141292 	if (opt == REMOVE_IF_CORRUPT)
325cd37da74Snw141292 		tries = 3;
326cd37da74Snw141292 
327cd37da74Snw141292 rinse_repeat:
328cd37da74Snw141292 	if (tries == 0) {
329cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to initialize db %s", dbname);
330c5c4113dSnw141292 		return (-1);
331cd37da74Snw141292 	}
332cd37da74Snw141292 	if (tries-- == 1)
333cd37da74Snw141292 		/* Last try, log errors */
334cd37da74Snw141292 		prio = LOG_ERR;
335c5c4113dSnw141292 
336cd37da74Snw141292 	db = sqlite_open(dbname, 0600, &errmsg);
337cd37da74Snw141292 	if (db == NULL) {
338cd37da74Snw141292 		idmapdlog(prio, "Error creating database %s (%s)",
339cd37da74Snw141292 		    dbname, CHECK_NULL(errmsg));
340cd37da74Snw141292 		sqlite_freemem(errmsg);
341cd37da74Snw141292 		if (opt == REMOVE_IF_CORRUPT)
342c5c4113dSnw141292 			(void) unlink(dbname);
343cd37da74Snw141292 		goto rinse_repeat;
344c5c4113dSnw141292 	}
345c5c4113dSnw141292 
346c5c4113dSnw141292 	sqlite_busy_timeout(db, 3000);
347cd37da74Snw141292 
348cd37da74Snw141292 	/* Detect current version of schema in the db, if any */
349cd37da74Snw141292 	curr_version = 0;
350cd37da74Snw141292 	if (detect_version_sql != NULL) {
351cd37da74Snw141292 		char *end, **results;
352cd37da74Snw141292 		int nrow;
353cd37da74Snw141292 
354cd37da74Snw141292 #ifdef	IDMAPD_DEBUG
355cd37da74Snw141292 		(void) fprintf(stderr, "Schema version detection SQL: %s\n",
356cd37da74Snw141292 		    detect_version_sql);
357cd37da74Snw141292 #endif	/* IDMAPD_DEBUG */
358cd37da74Snw141292 		rc = sqlite_get_table(db, detect_version_sql, &results,
359cd37da74Snw141292 		    &nrow, NULL, &errmsg);
360cd37da74Snw141292 		if (rc != SQLITE_OK) {
361cd37da74Snw141292 			idmapdlog(prio,
362cd37da74Snw141292 			    "Error detecting schema version of db %s (%s)",
363cd37da74Snw141292 			    dbname, errmsg);
364cd37da74Snw141292 			sqlite_freemem(errmsg);
365cd37da74Snw141292 			sqlite_free_table(results);
366c5c4113dSnw141292 			sqlite_close(db);
367cd37da74Snw141292 			return (-1);
368cd37da74Snw141292 		}
369cd37da74Snw141292 		if (nrow != 1) {
370cd37da74Snw141292 			idmapdlog(prio,
371cd37da74Snw141292 			    "Error detecting schema version of db %s", dbname);
372cd37da74Snw141292 			sqlite_close(db);
373cd37da74Snw141292 			sqlite_free_table(results);
374cd37da74Snw141292 			return (-1);
375cd37da74Snw141292 		}
376cd37da74Snw141292 		curr_version = strtol(results[1], &end, 10);
377cd37da74Snw141292 		sqlite_free_table(results);
378c5c4113dSnw141292 	}
379c5c4113dSnw141292 
380cd37da74Snw141292 	if (curr_version < 0) {
381cd37da74Snw141292 		if (opt == REMOVE_IF_CORRUPT)
382cd37da74Snw141292 			(void) unlink(dbname);
383cd37da74Snw141292 		goto rinse_repeat;
384c5c4113dSnw141292 	}
385c5c4113dSnw141292 
386cd37da74Snw141292 	if (curr_version == version)
387cd37da74Snw141292 		goto done;
388cd37da74Snw141292 
389cd37da74Snw141292 	/* Install or upgrade schema */
390cd37da74Snw141292 #ifdef	IDMAPD_DEBUG
391cd37da74Snw141292 	(void) fprintf(stderr, "Schema init/upgrade SQL: %s\n",
392cd37da74Snw141292 	    sql[curr_version]);
393cd37da74Snw141292 #endif	/* IDMAPD_DEBUG */
394cd37da74Snw141292 	rc = sql_exec_tran_no_cb(db, sql[curr_version], dbname,
395cd37da74Snw141292 	    (curr_version == 0) ? "installing schema" : "upgrading schema");
396cd37da74Snw141292 	if (rc != 0) {
397cd37da74Snw141292 		idmapdlog(prio, "Error %s schema for db %s", dbname,
398cd37da74Snw141292 		    (curr_version == 0) ? "installing schema" :
399cd37da74Snw141292 		    "upgrading schema");
400cd37da74Snw141292 		if (opt == REMOVE_IF_CORRUPT)
401cd37da74Snw141292 			(void) unlink(dbname);
402cd37da74Snw141292 		goto rinse_repeat;
403c5c4113dSnw141292 	}
404c5c4113dSnw141292 
405cd37da74Snw141292 	*upgraded = (curr_version > 0);
406cd37da74Snw141292 	*created = (curr_version == 0);
407cd37da74Snw141292 
408cd37da74Snw141292 done:
409c5c4113dSnw141292 	(void) sqlite_close(db);
410cd37da74Snw141292 	return (0);
411c5c4113dSnw141292 }
412c5c4113dSnw141292 
41384decf41Sjp151216 
41484decf41Sjp151216 /*
41584decf41Sjp151216  * This is the SQLite database busy handler that retries the SQL
41684decf41Sjp151216  * operation until it is successful.
41784decf41Sjp151216  */
41884decf41Sjp151216 int
41984decf41Sjp151216 /* LINTED E_FUNC_ARG_UNUSED */
42084decf41Sjp151216 idmap_sqlite_busy_handler(void *arg, const char *table_name, int count)
42184decf41Sjp151216 {
42284decf41Sjp151216 	struct idmap_busy	*busy = arg;
42384decf41Sjp151216 	int			delay;
42484decf41Sjp151216 	struct timespec		rqtp;
42584decf41Sjp151216 
42684decf41Sjp151216 	if (count == 1)  {
42784decf41Sjp151216 		busy->total = 0;
42884decf41Sjp151216 		busy->sec = 2;
42984decf41Sjp151216 	}
43084decf41Sjp151216 	if (busy->total > 1000 * busy->sec) {
43184decf41Sjp151216 		idmapdlog(LOG_ERR,
43284decf41Sjp151216 		    "Thread %d waited %d sec for the %s database",
43384decf41Sjp151216 		    pthread_self(), busy->sec, busy->name);
43484decf41Sjp151216 		busy->sec++;
43584decf41Sjp151216 	}
43684decf41Sjp151216 
43784decf41Sjp151216 	if (count <= busy->delay_size) {
43884decf41Sjp151216 		delay = busy->delays[count-1];
43984decf41Sjp151216 	} else {
44084decf41Sjp151216 		delay = busy->delays[busy->delay_size - 1];
44184decf41Sjp151216 	}
44284decf41Sjp151216 	busy->total += delay;
44384decf41Sjp151216 	rqtp.tv_sec = 0;
44484decf41Sjp151216 	rqtp.tv_nsec = delay * (NANOSEC / MILLISEC);
44584decf41Sjp151216 	(void) nanosleep(&rqtp, NULL);
44684decf41Sjp151216 	return (1);
44784decf41Sjp151216 }
44884decf41Sjp151216 
44984decf41Sjp151216 
450c5c4113dSnw141292 /*
451c5c4113dSnw141292  * Get the database handle
452c5c4113dSnw141292  */
453c5c4113dSnw141292 idmap_retcode
454cd37da74Snw141292 get_db_handle(sqlite **db)
455cd37da74Snw141292 {
456c5c4113dSnw141292 	char		*errmsg;
45784decf41Sjp151216 	idmap_tsd_t	*tsd;
458c5c4113dSnw141292 
459c5c4113dSnw141292 	/*
46084decf41Sjp151216 	 * Retrieve the db handle from thread-specific storage
461c5c4113dSnw141292 	 * If none exists, open and store in thread-specific storage.
462c5c4113dSnw141292 	 */
46384decf41Sjp151216 	if ((tsd = idmap_get_tsd()) == NULL) {
46484decf41Sjp151216 		idmapdlog(LOG_ERR,
465cd37da74Snw141292 		    "Error getting thread specific data for %s", IDMAP_DBNAME);
46684decf41Sjp151216 		return (IDMAP_ERR_MEMORY);
46784decf41Sjp151216 	}
468c5c4113dSnw141292 
46984decf41Sjp151216 	if (tsd->db_db == NULL) {
47084decf41Sjp151216 		tsd->db_db = sqlite_open(IDMAP_DBNAME, 0, &errmsg);
47184decf41Sjp151216 		if (tsd->db_db == NULL) {
472cd37da74Snw141292 			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
473c5c4113dSnw141292 			    IDMAP_DBNAME, CHECK_NULL(errmsg));
474c5c4113dSnw141292 			sqlite_freemem(errmsg);
475cd37da74Snw141292 			return (IDMAP_ERR_DB);
476c5c4113dSnw141292 		}
477cd37da74Snw141292 
47884decf41Sjp151216 		tsd->db_busy.name = IDMAP_DBNAME;
47984decf41Sjp151216 		tsd->db_busy.delays = db_delay_table;
48084decf41Sjp151216 		tsd->db_busy.delay_size = sizeof (db_delay_table) /
48184decf41Sjp151216 		    sizeof (int);
48284decf41Sjp151216 		sqlite_busy_handler(tsd->db_db, idmap_sqlite_busy_handler,
48384decf41Sjp151216 		    &tsd->db_busy);
48484decf41Sjp151216 	}
48584decf41Sjp151216 	*db = tsd->db_db;
486c5c4113dSnw141292 	return (IDMAP_SUCCESS);
487c5c4113dSnw141292 }
488c5c4113dSnw141292 
489c5c4113dSnw141292 /*
490c5c4113dSnw141292  * Get the cache handle
491c5c4113dSnw141292  */
492c5c4113dSnw141292 idmap_retcode
493cd37da74Snw141292 get_cache_handle(sqlite **cache)
494cd37da74Snw141292 {
495c5c4113dSnw141292 	char		*errmsg;
49684decf41Sjp151216 	idmap_tsd_t	*tsd;
497c5c4113dSnw141292 
498c5c4113dSnw141292 	/*
49984decf41Sjp151216 	 * Retrieve the db handle from thread-specific storage
500c5c4113dSnw141292 	 * If none exists, open and store in thread-specific storage.
501c5c4113dSnw141292 	 */
50284decf41Sjp151216 	if ((tsd = idmap_get_tsd()) == NULL) {
503cd37da74Snw141292 		idmapdlog(LOG_ERR, "Error getting thread specific data for %s",
50484decf41Sjp151216 		    IDMAP_DBNAME);
50584decf41Sjp151216 		return (IDMAP_ERR_MEMORY);
50684decf41Sjp151216 	}
507c5c4113dSnw141292 
50884decf41Sjp151216 	if (tsd->cache_db == NULL) {
50984decf41Sjp151216 		tsd->cache_db = sqlite_open(IDMAP_CACHENAME, 0, &errmsg);
51084decf41Sjp151216 		if (tsd->cache_db == NULL) {
511cd37da74Snw141292 			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
512c5c4113dSnw141292 			    IDMAP_CACHENAME, CHECK_NULL(errmsg));
513c5c4113dSnw141292 			sqlite_freemem(errmsg);
514cd37da74Snw141292 			return (IDMAP_ERR_DB);
515c5c4113dSnw141292 		}
516cd37da74Snw141292 
51784decf41Sjp151216 		tsd->cache_busy.name = IDMAP_CACHENAME;
51884decf41Sjp151216 		tsd->cache_busy.delays = cache_delay_table;
51984decf41Sjp151216 		tsd->cache_busy.delay_size = sizeof (cache_delay_table) /
52084decf41Sjp151216 		    sizeof (int);
52184decf41Sjp151216 		sqlite_busy_handler(tsd->cache_db, idmap_sqlite_busy_handler,
52284decf41Sjp151216 		    &tsd->cache_busy);
52384decf41Sjp151216 	}
52484decf41Sjp151216 	*cache = tsd->cache_db;
525c5c4113dSnw141292 	return (IDMAP_SUCCESS);
526c5c4113dSnw141292 }
527c5c4113dSnw141292 
528c5c4113dSnw141292 /*
529c5c4113dSnw141292  * Initialize cache and db
530c5c4113dSnw141292  */
531c5c4113dSnw141292 int
532cd37da74Snw141292 init_dbs()
533cd37da74Snw141292 {
534cd37da74Snw141292 	char *sql[2];
535cd37da74Snw141292 	int created, upgraded;
536cd37da74Snw141292 
537c5c4113dSnw141292 	/* name-based mappings; probably OK to blow away in a pinch(?) */
538cd37da74Snw141292 	sql[0] = DB_INSTALL_SQL;
539cd37da74Snw141292 	sql[1] = DB_UPGRADE_FROM_v1_SQL;
540cd37da74Snw141292 
541cd37da74Snw141292 	if (init_db_instance(IDMAP_DBNAME, DB_VERSION, DB_VERSION_SQL, sql,
542cd37da74Snw141292 	    FAIL_IF_CORRUPT, &created, &upgraded) < 0)
543c5c4113dSnw141292 		return (-1);
544c5c4113dSnw141292 
545c5c4113dSnw141292 	/* mappings, name/SID lookup cache + ephemeral IDs; OK to blow away */
546cd37da74Snw141292 	sql[0] = CACHE_INSTALL_SQL;
547cd37da74Snw141292 	sql[1] = CACHE_UPGRADE_FROM_v1_SQL;
548cd37da74Snw141292 	if (init_db_instance(IDMAP_CACHENAME, CACHE_VERSION, CACHE_VERSION_SQL,
549cd37da74Snw141292 	    sql, REMOVE_IF_CORRUPT, &created, &upgraded) < 0)
550c5c4113dSnw141292 		return (-1);
551c5c4113dSnw141292 
552cd37da74Snw141292 	_idmapdstate.new_eph_db = (created || upgraded) ? 1 : 0;
553cd37da74Snw141292 
554c5c4113dSnw141292 	return (0);
555c5c4113dSnw141292 }
556c5c4113dSnw141292 
557c5c4113dSnw141292 /*
558c5c4113dSnw141292  * Finalize databases
559c5c4113dSnw141292  */
560c5c4113dSnw141292 void
561cd37da74Snw141292 fini_dbs()
562cd37da74Snw141292 {
563c5c4113dSnw141292 }
564c5c4113dSnw141292 
565c5c4113dSnw141292 /*
566e8c27ec8Sbaban  * This table is a listing of status codes that will be returned to the
567c5c4113dSnw141292  * client when a SQL command fails with the corresponding error message.
568c5c4113dSnw141292  */
569c5c4113dSnw141292 static msg_table_t sqlmsgtable[] = {
57062c60062Sbaban 	{IDMAP_ERR_U2W_NAMERULE_CONFLICT,
571c5c4113dSnw141292 	"columns unixname, is_user, u2w_order are not unique"},
57262c60062Sbaban 	{IDMAP_ERR_W2U_NAMERULE_CONFLICT,
573cd37da74Snw141292 	"columns winname, windomain, is_user, is_wuser, w2u_order are not"
574cd37da74Snw141292 	" unique"},
575cd37da74Snw141292 	{IDMAP_ERR_W2U_NAMERULE_CONFLICT, "Conflicting w2u namerules"},
576c5c4113dSnw141292 	{-1, NULL}
577c5c4113dSnw141292 };
578c5c4113dSnw141292 
579c5c4113dSnw141292 /*
580c5c4113dSnw141292  * idmapd's version of string2stat to map SQLite messages to
581c5c4113dSnw141292  * status codes
582c5c4113dSnw141292  */
583c5c4113dSnw141292 idmap_retcode
584cd37da74Snw141292 idmapd_string2stat(const char *msg)
585cd37da74Snw141292 {
586c5c4113dSnw141292 	int i;
587c5c4113dSnw141292 	for (i = 0; sqlmsgtable[i].msg; i++) {
588c5c4113dSnw141292 		if (strcasecmp(sqlmsgtable[i].msg, msg) == 0)
589c5c4113dSnw141292 			return (sqlmsgtable[i].retcode);
590c5c4113dSnw141292 	}
591c5c4113dSnw141292 	return (IDMAP_ERR_OTHER);
592c5c4113dSnw141292 }
593c5c4113dSnw141292 
594c5c4113dSnw141292 /*
595cd37da74Snw141292  * Executes some SQL in a transaction.
596cd37da74Snw141292  *
597cd37da74Snw141292  * Returns 0 on success, -1 if it failed but the rollback succeeded, -2
598cd37da74Snw141292  * if the rollback failed.
599cd37da74Snw141292  */
600cd37da74Snw141292 static
601cd37da74Snw141292 int
602cd37da74Snw141292 sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
603cd37da74Snw141292 	const char *while_doing)
604cd37da74Snw141292 {
605cd37da74Snw141292 	char		*errmsg = NULL;
606cd37da74Snw141292 	int		rc;
607cd37da74Snw141292 
608cd37da74Snw141292 	rc = sqlite_exec(db, "BEGIN TRANSACTION;", NULL, NULL, &errmsg);
609cd37da74Snw141292 	if (rc != SQLITE_OK) {
610cd37da74Snw141292 		idmapdlog(LOG_ERR, "Begin transaction failed (%s) "
611cd37da74Snw141292 		    "while %s (%s)", errmsg, while_doing, dbname);
612cd37da74Snw141292 		sqlite_freemem(errmsg);
613cd37da74Snw141292 		return (-1);
614cd37da74Snw141292 	}
615cd37da74Snw141292 
616cd37da74Snw141292 	rc = sqlite_exec(db, sql, NULL, NULL, &errmsg);
617cd37da74Snw141292 	if (rc != SQLITE_OK) {
618cd37da74Snw141292 		idmapdlog(LOG_ERR, "Database error (%s) while %s (%s)", errmsg,
619cd37da74Snw141292 		    while_doing, dbname);
620cd37da74Snw141292 		sqlite_freemem(errmsg);
621cd37da74Snw141292 		errmsg = NULL;
622cd37da74Snw141292 		goto rollback;
623cd37da74Snw141292 	}
624cd37da74Snw141292 
625cd37da74Snw141292 	rc = sqlite_exec(db, "COMMIT TRANSACTION", NULL, NULL, &errmsg);
626cd37da74Snw141292 	if (rc == SQLITE_OK) {
627cd37da74Snw141292 		sqlite_freemem(errmsg);
628cd37da74Snw141292 		return (0);
629cd37da74Snw141292 	}
630cd37da74Snw141292 
631cd37da74Snw141292 	idmapdlog(LOG_ERR, "Database commit error (%s) while s (%s)",
632cd37da74Snw141292 	    errmsg, while_doing, dbname);
633cd37da74Snw141292 	sqlite_freemem(errmsg);
634cd37da74Snw141292 	errmsg = NULL;
635cd37da74Snw141292 
636cd37da74Snw141292 rollback:
637cd37da74Snw141292 	rc = sqlite_exec(db, "ROLLBACK TRANSACTION", NULL, NULL, &errmsg);
638cd37da74Snw141292 	if (rc != SQLITE_OK) {
639cd37da74Snw141292 		idmapdlog(LOG_ERR, "Rollback failed (%s) while %s (%s)",
640cd37da74Snw141292 		    errmsg, while_doing, dbname);
641cd37da74Snw141292 		sqlite_freemem(errmsg);
642cd37da74Snw141292 		return (-2);
643cd37da74Snw141292 	}
644cd37da74Snw141292 	sqlite_freemem(errmsg);
645cd37da74Snw141292 
646cd37da74Snw141292 	return (-1);
647cd37da74Snw141292 }
648cd37da74Snw141292 
649cd37da74Snw141292 /*
650c5c4113dSnw141292  * Execute the given SQL statment without using any callbacks
651c5c4113dSnw141292  */
652c5c4113dSnw141292 idmap_retcode
653cd37da74Snw141292 sql_exec_no_cb(sqlite *db, char *sql)
654cd37da74Snw141292 {
655c5c4113dSnw141292 	char		*errmsg = NULL;
65684decf41Sjp151216 	int		r;
657c5c4113dSnw141292 	idmap_retcode	retcode;
658c5c4113dSnw141292 
659c5c4113dSnw141292 	r = sqlite_exec(db, sql, NULL, NULL, &errmsg);
66084decf41Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
661c5c4113dSnw141292 
662c5c4113dSnw141292 	if (r != SQLITE_OK) {
663cd37da74Snw141292 		idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
664cd37da74Snw141292 		    CHECK_NULL(errmsg));
665c5c4113dSnw141292 		retcode = idmapd_string2stat(errmsg);
66662c60062Sbaban 		if (errmsg != NULL)
667c5c4113dSnw141292 			sqlite_freemem(errmsg);
668c5c4113dSnw141292 		return (retcode);
669c5c4113dSnw141292 	}
670c5c4113dSnw141292 
671c5c4113dSnw141292 	return (IDMAP_SUCCESS);
672c5c4113dSnw141292 }
673c5c4113dSnw141292 
674c5c4113dSnw141292 /*
675c5c4113dSnw141292  * Generate expression that can be used in WHERE statements.
676c5c4113dSnw141292  * Examples:
677c5c4113dSnw141292  * <prefix> <col>      <op> <value>   <suffix>
678c5c4113dSnw141292  * ""       "unixuser" "="  "foo" "AND"
679c5c4113dSnw141292  */
680c5c4113dSnw141292 idmap_retcode
681cd37da74Snw141292 gen_sql_expr_from_rule(idmap_namerule *rule, char **out)
682cd37da74Snw141292 {
683cd37da74Snw141292 	char	*s_windomain = NULL, *s_winname = NULL;
684cd37da74Snw141292 	char	*s_unixname = NULL;
685cd37da74Snw141292 	char	*lower_winname;
686cd37da74Snw141292 	int	retcode = IDMAP_SUCCESS;
687cd37da74Snw141292 
688c5c4113dSnw141292 	if (out == NULL)
689c5c4113dSnw141292 		return (IDMAP_ERR_ARG);
690c5c4113dSnw141292 
691c5c4113dSnw141292 
692cd37da74Snw141292 	if (!EMPTY_STRING(rule->windomain)) {
693cd37da74Snw141292 		s_windomain =  sqlite_mprintf("AND windomain = %Q ",
694cd37da74Snw141292 		    rule->windomain);
695cd37da74Snw141292 		if (s_windomain == NULL) {
696cd37da74Snw141292 			retcode = IDMAP_ERR_MEMORY;
697cd37da74Snw141292 			goto out;
698c5c4113dSnw141292 		}
699cd37da74Snw141292 	}
700cd37da74Snw141292 
701cd37da74Snw141292 	if (!EMPTY_STRING(rule->winname)) {
702cd37da74Snw141292 		if ((lower_winname = tolower_u8(rule->winname)) == NULL)
703cd37da74Snw141292 			lower_winname = rule->winname;
704cd37da74Snw141292 		s_winname = sqlite_mprintf(
705cd37da74Snw141292 		    "AND winname = %Q AND is_wuser = %d ",
706cd37da74Snw141292 		    lower_winname, rule->is_wuser ? 1 : 0);
707cd37da74Snw141292 		if (lower_winname != rule->winname)
708cd37da74Snw141292 			free(lower_winname);
709cd37da74Snw141292 		if (s_winname == NULL) {
710cd37da74Snw141292 			retcode = IDMAP_ERR_MEMORY;
711cd37da74Snw141292 			goto out;
712cd37da74Snw141292 		}
713cd37da74Snw141292 	}
714cd37da74Snw141292 
715cd37da74Snw141292 	if (!EMPTY_STRING(rule->unixname)) {
716cd37da74Snw141292 		s_unixname = sqlite_mprintf(
717cd37da74Snw141292 		    "AND unixname = %Q AND is_user = %d ",
718cd37da74Snw141292 		    rule->unixname, rule->is_user ? 1 : 0);
719cd37da74Snw141292 		if (s_unixname == NULL) {
720cd37da74Snw141292 			retcode = IDMAP_ERR_MEMORY;
721cd37da74Snw141292 			goto out;
722cd37da74Snw141292 		}
723cd37da74Snw141292 	}
724cd37da74Snw141292 
725cd37da74Snw141292 	*out = sqlite_mprintf("%s %s %s",
726cd37da74Snw141292 	    s_windomain ? s_windomain : "",
727cd37da74Snw141292 	    s_winname ? s_winname : "",
728cd37da74Snw141292 	    s_unixname ? s_unixname : "");
729cd37da74Snw141292 
730cd37da74Snw141292 	if (*out == NULL) {
731cd37da74Snw141292 		retcode = IDMAP_ERR_MEMORY;
732cd37da74Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
733cd37da74Snw141292 		goto out;
734cd37da74Snw141292 	}
735cd37da74Snw141292 
736cd37da74Snw141292 out:
737cd37da74Snw141292 	if (s_windomain != NULL)
738cd37da74Snw141292 		sqlite_freemem(s_windomain);
739cd37da74Snw141292 	if (s_winname != NULL)
740cd37da74Snw141292 		sqlite_freemem(s_winname);
741cd37da74Snw141292 	if (s_unixname != NULL)
742cd37da74Snw141292 		sqlite_freemem(s_unixname);
743cd37da74Snw141292 
744cd37da74Snw141292 	return (retcode);
745cd37da74Snw141292 }
746cd37da74Snw141292 
747cd37da74Snw141292 
748c5c4113dSnw141292 
749c5c4113dSnw141292 /*
750c5c4113dSnw141292  * Generate and execute SQL statement for LIST RPC calls
751c5c4113dSnw141292  */
752c5c4113dSnw141292 idmap_retcode
753c5c4113dSnw141292 process_list_svc_sql(sqlite *db, char *sql, uint64_t limit,
754cd37da74Snw141292 		list_svc_cb cb, void *result)
755cd37da74Snw141292 {
756c5c4113dSnw141292 	list_cb_data_t	cb_data;
757c5c4113dSnw141292 	char		*errmsg = NULL;
75884decf41Sjp151216 	int		r;
759c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_ERR_INTERNAL;
760c5c4113dSnw141292 
761c5c4113dSnw141292 	(void) memset(&cb_data, 0, sizeof (cb_data));
762c5c4113dSnw141292 	cb_data.result = result;
763c5c4113dSnw141292 	cb_data.limit = limit;
764c5c4113dSnw141292 
76584decf41Sjp151216 
766c5c4113dSnw141292 	r = sqlite_exec(db, sql, cb, &cb_data, &errmsg);
76784decf41Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
768c5c4113dSnw141292 	switch (r) {
769c5c4113dSnw141292 	case SQLITE_OK:
770c5c4113dSnw141292 		retcode = IDMAP_SUCCESS;
77184decf41Sjp151216 		break;
77284decf41Sjp151216 
773c5c4113dSnw141292 	default:
774c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
775cd37da74Snw141292 		idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
776cd37da74Snw141292 		    CHECK_NULL(errmsg));
77784decf41Sjp151216 		break;
778c5c4113dSnw141292 	}
77962c60062Sbaban 	if (errmsg != NULL)
780c5c4113dSnw141292 		sqlite_freemem(errmsg);
781c5c4113dSnw141292 	return (retcode);
782c5c4113dSnw141292 }
783c5c4113dSnw141292 
784c5c4113dSnw141292 /*
785c5c4113dSnw141292  * This routine is called by callbacks that process the results of
786c5c4113dSnw141292  * LIST RPC calls to validate data and to allocate memory for
787c5c4113dSnw141292  * the result array.
788c5c4113dSnw141292  */
789c5c4113dSnw141292 idmap_retcode
790c5c4113dSnw141292 validate_list_cb_data(list_cb_data_t *cb_data, int argc, char **argv,
791cd37da74Snw141292 		int ncol, uchar_t **list, size_t valsize)
792cd37da74Snw141292 {
793c5c4113dSnw141292 	size_t	nsize;
794c5c4113dSnw141292 	void	*tmplist;
795c5c4113dSnw141292 
796c5c4113dSnw141292 	if (cb_data->limit > 0 && cb_data->next == cb_data->limit)
797c5c4113dSnw141292 		return (IDMAP_NEXT);
798c5c4113dSnw141292 
799c5c4113dSnw141292 	if (argc < ncol || argv == NULL) {
800c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Invalid data");
801c5c4113dSnw141292 		return (IDMAP_ERR_INTERNAL);
802c5c4113dSnw141292 	}
803c5c4113dSnw141292 
804c5c4113dSnw141292 	/* alloc in bulk to reduce number of reallocs */
805c5c4113dSnw141292 	if (cb_data->next >= cb_data->len) {
806c5c4113dSnw141292 		nsize = (cb_data->len + SIZE_INCR) * valsize;
807c5c4113dSnw141292 		tmplist = realloc(*list, nsize);
808c5c4113dSnw141292 		if (tmplist == NULL) {
809c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
810c5c4113dSnw141292 			return (IDMAP_ERR_MEMORY);
811c5c4113dSnw141292 		}
812c5c4113dSnw141292 		*list = tmplist;
813c5c4113dSnw141292 		(void) memset(*list + (cb_data->len * valsize), 0,
814c5c4113dSnw141292 		    SIZE_INCR * valsize);
815c5c4113dSnw141292 		cb_data->len += SIZE_INCR;
816c5c4113dSnw141292 	}
817c5c4113dSnw141292 	return (IDMAP_SUCCESS);
818c5c4113dSnw141292 }
819c5c4113dSnw141292 
820cd37da74Snw141292 static
821cd37da74Snw141292 idmap_retcode
822c5c4113dSnw141292 get_namerule_order(char *winname, char *windomain, char *unixname,
823cd37da74Snw141292 	int direction, int is_diagonal, int *w2u_order, int *u2w_order)
824cd37da74Snw141292 {
825c5c4113dSnw141292 	*w2u_order = 0;
826c5c4113dSnw141292 	*u2w_order = 0;
827c5c4113dSnw141292 
828c5c4113dSnw141292 	/*
829c5c4113dSnw141292 	 * Windows to UNIX lookup order:
830c5c4113dSnw141292 	 *  1. winname@domain (or winname) to ""
831c5c4113dSnw141292 	 *  2. winname@domain (or winname) to unixname
832c5c4113dSnw141292 	 *  3. winname@* to ""
833c5c4113dSnw141292 	 *  4. winname@* to unixname
834c5c4113dSnw141292 	 *  5. *@domain (or *) to *
835c5c4113dSnw141292 	 *  6. *@domain (or *) to ""
836c5c4113dSnw141292 	 *  7. *@domain (or *) to unixname
837c5c4113dSnw141292 	 *  8. *@* to *
838c5c4113dSnw141292 	 *  9. *@* to ""
839c5c4113dSnw141292 	 * 10. *@* to unixname
840c5c4113dSnw141292 	 *
841c5c4113dSnw141292 	 * winname is a special case of winname@domain when domain is the
842c5c4113dSnw141292 	 * default domain. Similarly * is a special case of *@domain when
843c5c4113dSnw141292 	 * domain is the default domain.
844c5c4113dSnw141292 	 *
845c5c4113dSnw141292 	 * Note that "" has priority over specific names because "" inhibits
846c5c4113dSnw141292 	 * mappings and traditionally deny rules always had higher priority.
847c5c4113dSnw141292 	 */
848651c0131Sbaban 	if (direction != IDMAP_DIRECTION_U2W) {
849651c0131Sbaban 		/* bi-directional or from windows to unix */
850c5c4113dSnw141292 		if (winname == NULL)
851c5c4113dSnw141292 			return (IDMAP_ERR_W2U_NAMERULE);
852c5c4113dSnw141292 		else if (unixname == NULL)
853c5c4113dSnw141292 			return (IDMAP_ERR_W2U_NAMERULE);
854c5c4113dSnw141292 		else if (EMPTY_NAME(winname))
855c5c4113dSnw141292 			return (IDMAP_ERR_W2U_NAMERULE);
856c5c4113dSnw141292 		else if (*winname == '*' && windomain && *windomain == '*') {
857c5c4113dSnw141292 			if (*unixname == '*')
858c5c4113dSnw141292 				*w2u_order = 8;
859c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
860c5c4113dSnw141292 				*w2u_order = 9;
861c5c4113dSnw141292 			else /* unixname == name */
862c5c4113dSnw141292 				*w2u_order = 10;
863c5c4113dSnw141292 		} else if (*winname == '*') {
864c5c4113dSnw141292 			if (*unixname == '*')
865c5c4113dSnw141292 				*w2u_order = 5;
866c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
867c5c4113dSnw141292 				*w2u_order = 6;
868c5c4113dSnw141292 			else /* name */
869c5c4113dSnw141292 				*w2u_order = 7;
87062c60062Sbaban 		} else if (windomain != NULL && *windomain == '*') {
871c5c4113dSnw141292 			/* winname == name */
872c5c4113dSnw141292 			if (*unixname == '*')
873c5c4113dSnw141292 				return (IDMAP_ERR_W2U_NAMERULE);
874c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
875c5c4113dSnw141292 				*w2u_order = 3;
876c5c4113dSnw141292 			else /* name */
877c5c4113dSnw141292 				*w2u_order = 4;
878c5c4113dSnw141292 		} else  {
879c5c4113dSnw141292 			/* winname == name && windomain == null or name */
880c5c4113dSnw141292 			if (*unixname == '*')
881c5c4113dSnw141292 				return (IDMAP_ERR_W2U_NAMERULE);
882c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
883c5c4113dSnw141292 				*w2u_order = 1;
884c5c4113dSnw141292 			else /* name */
885c5c4113dSnw141292 				*w2u_order = 2;
886c5c4113dSnw141292 		}
887cd37da74Snw141292 
888c5c4113dSnw141292 	}
889c5c4113dSnw141292 
890c5c4113dSnw141292 	/*
891cd37da74Snw141292 	 * 1. unixname to "", non-diagonal
892cd37da74Snw141292 	 * 2. unixname to winname@domain (or winname), non-diagonal
893cd37da74Snw141292 	 * 3. unixname to "", diagonal
894cd37da74Snw141292 	 * 4. unixname to winname@domain (or winname), diagonal
895cd37da74Snw141292 	 * 5. * to *@domain (or *), non-diagonal
896cd37da74Snw141292 	 * 5. * to *@domain (or *), diagonal
897cd37da74Snw141292 	 * 7. * to ""
898cd37da74Snw141292 	 * 8. * to winname@domain (or winname)
899cd37da74Snw141292 	 * 9. * to "", non-diagonal
900cd37da74Snw141292 	 * 10. * to winname@domain (or winname), diagonal
901c5c4113dSnw141292 	 */
902651c0131Sbaban 	if (direction != IDMAP_DIRECTION_W2U) {
903cd37da74Snw141292 		int diagonal = is_diagonal ? 1 : 0;
904cd37da74Snw141292 
905651c0131Sbaban 		/* bi-directional or from unix to windows */
906c5c4113dSnw141292 		if (unixname == NULL || EMPTY_NAME(unixname))
907c5c4113dSnw141292 			return (IDMAP_ERR_U2W_NAMERULE);
908c5c4113dSnw141292 		else if (winname == NULL)
909c5c4113dSnw141292 			return (IDMAP_ERR_U2W_NAMERULE);
91062c60062Sbaban 		else if (windomain != NULL && *windomain == '*')
911651c0131Sbaban 			return (IDMAP_ERR_U2W_NAMERULE);
912c5c4113dSnw141292 		else if (*unixname == '*') {
913c5c4113dSnw141292 			if (*winname == '*')
914cd37da74Snw141292 				*u2w_order = 5 + diagonal;
915c5c4113dSnw141292 			else if (EMPTY_NAME(winname))
916cd37da74Snw141292 				*u2w_order = 7 + 2 * diagonal;
917c5c4113dSnw141292 			else
918cd37da74Snw141292 				*u2w_order = 8 + 2 * diagonal;
919c5c4113dSnw141292 		} else {
920c5c4113dSnw141292 			if (*winname == '*')
921c5c4113dSnw141292 				return (IDMAP_ERR_U2W_NAMERULE);
922c5c4113dSnw141292 			else if (EMPTY_NAME(winname))
923cd37da74Snw141292 				*u2w_order = 1 + 2 * diagonal;
924c5c4113dSnw141292 			else
925cd37da74Snw141292 				*u2w_order = 2 + 2 * diagonal;
926c5c4113dSnw141292 		}
927c5c4113dSnw141292 	}
928c5c4113dSnw141292 	return (IDMAP_SUCCESS);
929c5c4113dSnw141292 }
930c5c4113dSnw141292 
931c5c4113dSnw141292 /*
932c5c4113dSnw141292  * Generate and execute SQL statement to add name-based mapping rule
933c5c4113dSnw141292  */
934c5c4113dSnw141292 idmap_retcode
935cd37da74Snw141292 add_namerule(sqlite *db, idmap_namerule *rule)
936cd37da74Snw141292 {
937c5c4113dSnw141292 	char		*sql = NULL;
938c5c4113dSnw141292 	idmap_stat	retcode;
9398e228215Sdm199847 	char		*dom = NULL;
940c5c4113dSnw141292 	int		w2u_order, u2w_order;
941c5c4113dSnw141292 	char		w2ubuf[11], u2wbuf[11];
942c5c4113dSnw141292 
9438e228215Sdm199847 	retcode = get_namerule_order(rule->winname, rule->windomain,
944cd37da74Snw141292 	    rule->unixname, rule->direction,
945cd37da74Snw141292 	    rule->is_user == rule->is_wuser ? 0 : 1, &w2u_order, &u2w_order);
946c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
947c5c4113dSnw141292 		goto out;
948c5c4113dSnw141292 
949c5c4113dSnw141292 	if (w2u_order)
950c5c4113dSnw141292 		(void) snprintf(w2ubuf, sizeof (w2ubuf), "%d", w2u_order);
951c5c4113dSnw141292 	if (u2w_order)
952c5c4113dSnw141292 		(void) snprintf(u2wbuf, sizeof (u2wbuf), "%d", u2w_order);
953c5c4113dSnw141292 
95462c60062Sbaban 	/*
95562c60062Sbaban 	 * For the triggers on namerules table to work correctly:
95662c60062Sbaban 	 * 1) Use NULL instead of 0 for w2u_order and u2w_order
95762c60062Sbaban 	 * 2) Use "" instead of NULL for "no domain"
95862c60062Sbaban 	 */
95962c60062Sbaban 
960e8c27ec8Sbaban 	if (!EMPTY_STRING(rule->windomain))
9618e228215Sdm199847 		dom = rule->windomain;
962cd37da74Snw141292 	else if (lookup_wksids_name2sid(rule->winname, NULL, NULL, NULL, NULL)
96362c60062Sbaban 	    == IDMAP_SUCCESS) {
96462c60062Sbaban 		/* well-known SIDs don't need domain */
96562c60062Sbaban 		dom = "";
96662c60062Sbaban 	}
967c5c4113dSnw141292 
968c5c4113dSnw141292 	RDLOCK_CONFIG();
96962c60062Sbaban 	if (dom == NULL) {
970c8e26105Sjp151216 		if (_idmapdstate.cfg->pgcfg.default_domain)
971c8e26105Sjp151216 			dom = _idmapdstate.cfg->pgcfg.default_domain;
972c5c4113dSnw141292 		else
973c5c4113dSnw141292 			dom = "";
97462c60062Sbaban 	}
97584decf41Sjp151216 	sql = sqlite_mprintf("INSERT into namerules "
976cd37da74Snw141292 	    "(is_user, is_wuser, windomain, winname_display, is_nt4, "
977c5c4113dSnw141292 	    "unixname, w2u_order, u2w_order) "
978cd37da74Snw141292 	    "VALUES(%d, %d, %Q, %Q, %d, %Q, %q, %q);",
979cd37da74Snw141292 	    rule->is_user ? 1 : 0, rule->is_wuser ? 1 : 0, dom,
980cd37da74Snw141292 	    rule->winname, rule->is_nt4 ? 1 : 0, rule->unixname,
981cd37da74Snw141292 	    w2u_order ? w2ubuf : NULL, u2w_order ? u2wbuf : NULL);
982c5c4113dSnw141292 	UNLOCK_CONFIG();
983c5c4113dSnw141292 
984c5c4113dSnw141292 	if (sql == NULL) {
985c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
986c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
987c5c4113dSnw141292 		goto out;
988c5c4113dSnw141292 	}
989c5c4113dSnw141292 
990c5c4113dSnw141292 	retcode = sql_exec_no_cb(db, sql);
991c5c4113dSnw141292 
992c5c4113dSnw141292 	if (retcode == IDMAP_ERR_OTHER)
993c5c4113dSnw141292 		retcode = IDMAP_ERR_CFG;
994c5c4113dSnw141292 
995c5c4113dSnw141292 out:
99662c60062Sbaban 	if (sql != NULL)
997c5c4113dSnw141292 		sqlite_freemem(sql);
998c5c4113dSnw141292 	return (retcode);
999c5c4113dSnw141292 }
1000c5c4113dSnw141292 
1001c5c4113dSnw141292 /*
1002c5c4113dSnw141292  * Flush name-based mapping rules
1003c5c4113dSnw141292  */
1004c5c4113dSnw141292 idmap_retcode
1005cd37da74Snw141292 flush_namerules(sqlite *db)
1006cd37da74Snw141292 {
1007c5c4113dSnw141292 	idmap_stat	retcode;
1008c5c4113dSnw141292 
1009cd37da74Snw141292 	retcode = sql_exec_no_cb(db, "DELETE FROM namerules;");
1010c5c4113dSnw141292 
1011c5c4113dSnw141292 	return (retcode);
1012c5c4113dSnw141292 }
1013c5c4113dSnw141292 
1014c5c4113dSnw141292 /*
1015c5c4113dSnw141292  * Generate and execute SQL statement to remove a name-based mapping rule
1016c5c4113dSnw141292  */
1017c5c4113dSnw141292 idmap_retcode
1018cd37da74Snw141292 rm_namerule(sqlite *db, idmap_namerule *rule)
1019cd37da74Snw141292 {
1020c5c4113dSnw141292 	char		*sql = NULL;
1021c5c4113dSnw141292 	idmap_stat	retcode;
1022c5c4113dSnw141292 	char		buf[80];
1023cd37da74Snw141292 	char		*expr = NULL;
1024c5c4113dSnw141292 
10258e228215Sdm199847 	if (rule->direction < 0 && EMPTY_STRING(rule->windomain) &&
10268e228215Sdm199847 	    EMPTY_STRING(rule->winname) && EMPTY_STRING(rule->unixname))
1027c5c4113dSnw141292 		return (IDMAP_SUCCESS);
1028c5c4113dSnw141292 
1029c5c4113dSnw141292 	buf[0] = 0;
1030cd37da74Snw141292 
1031cd37da74Snw141292 	if (rule->direction == IDMAP_DIRECTION_BI)
1032c5c4113dSnw141292 		(void) snprintf(buf, sizeof (buf), "AND w2u_order > 0"
1033c5c4113dSnw141292 		    " AND u2w_order > 0");
1034cd37da74Snw141292 	else if (rule->direction == IDMAP_DIRECTION_W2U)
1035c5c4113dSnw141292 		(void) snprintf(buf, sizeof (buf), "AND w2u_order > 0"
1036c5c4113dSnw141292 		    " AND (u2w_order = 0 OR u2w_order ISNULL)");
1037cd37da74Snw141292 	else if (rule->direction == IDMAP_DIRECTION_U2W)
1038c5c4113dSnw141292 		(void) snprintf(buf, sizeof (buf), "AND u2w_order > 0"
1039c5c4113dSnw141292 		    " AND (w2u_order = 0 OR w2u_order ISNULL)");
1040c5c4113dSnw141292 
1041cd37da74Snw141292 	retcode = gen_sql_expr_from_rule(rule, &expr);
1042cd37da74Snw141292 	if (retcode != IDMAP_SUCCESS)
1043c5c4113dSnw141292 		goto out;
1044c5c4113dSnw141292 
1045cd37da74Snw141292 	sql = sqlite_mprintf("DELETE FROM namerules WHERE 1 %s %s;", expr,
1046c5c4113dSnw141292 	    buf);
1047c5c4113dSnw141292 
1048c5c4113dSnw141292 	if (sql == NULL) {
1049c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
1050c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
1051c5c4113dSnw141292 		goto out;
1052c5c4113dSnw141292 	}
1053c5c4113dSnw141292 
1054cd37da74Snw141292 
1055c5c4113dSnw141292 	retcode = sql_exec_no_cb(db, sql);
1056c5c4113dSnw141292 
1057c5c4113dSnw141292 out:
1058cd37da74Snw141292 	if (expr != NULL)
1059cd37da74Snw141292 		sqlite_freemem(expr);
106062c60062Sbaban 	if (sql != NULL)
1061c5c4113dSnw141292 		sqlite_freemem(sql);
1062c5c4113dSnw141292 	return (retcode);
1063c5c4113dSnw141292 }
1064c5c4113dSnw141292 
1065c5c4113dSnw141292 /*
1066c5c4113dSnw141292  * Compile the given SQL query and step just once.
1067c5c4113dSnw141292  *
1068c5c4113dSnw141292  * Input:
1069c5c4113dSnw141292  * db  - db handle
1070c5c4113dSnw141292  * sql - SQL statement
1071c5c4113dSnw141292  *
1072c5c4113dSnw141292  * Output:
1073c5c4113dSnw141292  * vm     -  virtual SQL machine
1074c5c4113dSnw141292  * ncol   - number of columns in the result
1075c5c4113dSnw141292  * values - column values
1076c5c4113dSnw141292  *
1077c5c4113dSnw141292  * Return values:
1078c5c4113dSnw141292  * IDMAP_SUCCESS
1079c5c4113dSnw141292  * IDMAP_ERR_NOTFOUND
1080c5c4113dSnw141292  * IDMAP_ERR_INTERNAL
1081c5c4113dSnw141292  */
1082c5c4113dSnw141292 
1083cd37da74Snw141292 static
1084cd37da74Snw141292 idmap_retcode
1085c5c4113dSnw141292 sql_compile_n_step_once(sqlite *db, char *sql, sqlite_vm **vm, int *ncol,
1086cd37da74Snw141292 		int reqcol, const char ***values)
1087cd37da74Snw141292 {
1088c5c4113dSnw141292 	char		*errmsg = NULL;
108984decf41Sjp151216 	int		r;
1090c5c4113dSnw141292 
109184decf41Sjp151216 	if ((r = sqlite_compile(db, sql, NULL, vm, &errmsg)) != SQLITE_OK) {
1092cd37da74Snw141292 		idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
1093cd37da74Snw141292 		    CHECK_NULL(errmsg));
1094c5c4113dSnw141292 		sqlite_freemem(errmsg);
1095c5c4113dSnw141292 		return (IDMAP_ERR_INTERNAL);
1096c5c4113dSnw141292 	}
1097c5c4113dSnw141292 
1098c5c4113dSnw141292 	r = sqlite_step(*vm, ncol, values, NULL);
109984decf41Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
1100c5c4113dSnw141292 
110184decf41Sjp151216 	if (r == SQLITE_ROW) {
110262c60062Sbaban 		if (ncol != NULL && *ncol < reqcol) {
1103c5c4113dSnw141292 			(void) sqlite_finalize(*vm, NULL);
1104c5c4113dSnw141292 			*vm = NULL;
1105c5c4113dSnw141292 			return (IDMAP_ERR_INTERNAL);
1106c5c4113dSnw141292 		}
1107c5c4113dSnw141292 		/* Caller will call finalize after using the results */
1108c5c4113dSnw141292 		return (IDMAP_SUCCESS);
1109c5c4113dSnw141292 	} else if (r == SQLITE_DONE) {
1110c5c4113dSnw141292 		(void) sqlite_finalize(*vm, NULL);
1111c5c4113dSnw141292 		*vm = NULL;
1112c5c4113dSnw141292 		return (IDMAP_ERR_NOTFOUND);
1113c5c4113dSnw141292 	}
1114c5c4113dSnw141292 
1115c5c4113dSnw141292 	(void) sqlite_finalize(*vm, &errmsg);
1116c5c4113dSnw141292 	*vm = NULL;
1117cd37da74Snw141292 	idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
1118cd37da74Snw141292 	    CHECK_NULL(errmsg));
1119c5c4113dSnw141292 	sqlite_freemem(errmsg);
1120c5c4113dSnw141292 	return (IDMAP_ERR_INTERNAL);
1121c5c4113dSnw141292 }
1122c5c4113dSnw141292 
112362c60062Sbaban /*
1124e8c27ec8Sbaban  * Update nm_siduid and nm_sidgid fields in the lookup state.
1125e8c27ec8Sbaban  *
1126e8c27ec8Sbaban  * state->nm_siduid represents mode used by sid2uid and uid2sid
1127e8c27ec8Sbaban  * requests for directory-based name mappings. Similarly,
1128e8c27ec8Sbaban  * state->nm_sidgid represents mode used by sid2gid and gid2sid
1129e8c27ec8Sbaban  * requests.
1130e8c27ec8Sbaban  *
1131e8c27ec8Sbaban  * sid2uid/uid2sid:
1132e8c27ec8Sbaban  * none       -> ds_name_mapping_enabled != true
1133e8c27ec8Sbaban  * AD-mode    -> !nldap_winname_attr && ad_unixuser_attr
1134e8c27ec8Sbaban  * nldap-mode -> nldap_winname_attr && !ad_unixuser_attr
1135e8c27ec8Sbaban  * mixed-mode -> nldap_winname_attr && ad_unixuser_attr
1136e8c27ec8Sbaban  *
1137e8c27ec8Sbaban  * sid2gid/gid2sid:
1138e8c27ec8Sbaban  * none       -> ds_name_mapping_enabled != true
1139e8c27ec8Sbaban  * AD-mode    -> !nldap_winname_attr && ad_unixgroup_attr
1140e8c27ec8Sbaban  * nldap-mode -> nldap_winname_attr && !ad_unixgroup_attr
1141e8c27ec8Sbaban  * mixed-mode -> nldap_winname_attr && ad_unixgroup_attr
1142e8c27ec8Sbaban  */
1143e8c27ec8Sbaban idmap_retcode
1144e8c27ec8Sbaban get_ds_namemap_type(lookup_state_t *state)
1145e8c27ec8Sbaban {
1146e8c27ec8Sbaban 	state->nm_siduid = IDMAP_NM_NONE;
1147e8c27ec8Sbaban 	state->nm_sidgid = IDMAP_NM_NONE;
1148e8c27ec8Sbaban 	RDLOCK_CONFIG();
1149e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.ds_name_mapping_enabled == FALSE) {
1150e8c27ec8Sbaban 		UNLOCK_CONFIG();
1151e8c27ec8Sbaban 		return (IDMAP_SUCCESS);
1152e8c27ec8Sbaban 	}
1153e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.nldap_winname_attr != NULL) {
1154e8c27ec8Sbaban 		state->nm_siduid =
1155e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
1156e8c27ec8Sbaban 		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
1157e8c27ec8Sbaban 		state->nm_sidgid =
1158e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
1159e8c27ec8Sbaban 		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
1160e8c27ec8Sbaban 	} else {
1161e8c27ec8Sbaban 		state->nm_siduid =
1162e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
1163e8c27ec8Sbaban 		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
1164e8c27ec8Sbaban 		state->nm_sidgid =
1165e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
1166e8c27ec8Sbaban 		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
1167e8c27ec8Sbaban 	}
1168e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL) {
1169e8c27ec8Sbaban 		state->ad_unixuser_attr =
1170e8c27ec8Sbaban 		    strdup(_idmapdstate.cfg->pgcfg.ad_unixuser_attr);
1171e8c27ec8Sbaban 		if (state->ad_unixuser_attr == NULL) {
1172e8c27ec8Sbaban 			UNLOCK_CONFIG();
1173e8c27ec8Sbaban 			return (IDMAP_ERR_MEMORY);
1174e8c27ec8Sbaban 		}
1175e8c27ec8Sbaban 	}
1176e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL) {
1177e8c27ec8Sbaban 		state->ad_unixgroup_attr =
1178e8c27ec8Sbaban 		    strdup(_idmapdstate.cfg->pgcfg.ad_unixgroup_attr);
1179e8c27ec8Sbaban 		if (state->ad_unixgroup_attr == NULL) {
1180e8c27ec8Sbaban 			UNLOCK_CONFIG();
1181e8c27ec8Sbaban 			return (IDMAP_ERR_MEMORY);
1182e8c27ec8Sbaban 		}
1183e8c27ec8Sbaban 	}
1184e8c27ec8Sbaban 	UNLOCK_CONFIG();
1185e8c27ec8Sbaban 	return (IDMAP_SUCCESS);
1186e8c27ec8Sbaban }
1187e8c27ec8Sbaban 
1188e8c27ec8Sbaban /*
118962c60062Sbaban  * Table for well-known SIDs.
119062c60062Sbaban  *
119162c60062Sbaban  * Background:
119262c60062Sbaban  *
119376b27f93Sbaban  * Some of the well-known principals are stored under:
119462c60062Sbaban  * cn=WellKnown Security Principals, cn=Configuration, dc=<forestRootDomain>
119562c60062Sbaban  * They belong to objectClass "foreignSecurityPrincipal". They don't have
119662c60062Sbaban  * "samAccountName" nor "userPrincipalName" attributes. Their names are
119762c60062Sbaban  * available in "cn" and "name" attributes. Some of these principals have a
119862c60062Sbaban  * second entry under CN=ForeignSecurityPrincipals,dc=<forestRootDomain> and
119962c60062Sbaban  * these duplicate entries have the stringified SID in the "name" and "cn"
120062c60062Sbaban  * attributes instead of the actual name.
120162c60062Sbaban  *
120276b27f93Sbaban  * Those of the form S-1-5-32-X are Builtin groups and are stored in the
120376b27f93Sbaban  * cn=builtin container (except, Power Users which is not stored in AD)
120462c60062Sbaban  *
120576b27f93Sbaban  * These principals are and will remain constant. Therefore doing AD lookups
120676b27f93Sbaban  * provides no benefit. Also, using hard-coded table (and thus avoiding AD
120776b27f93Sbaban  * lookup) improves performance and avoids additional complexity in the
120876b27f93Sbaban  * adutils.c code. Moreover these SIDs can be used when no Active Directory
120976b27f93Sbaban  * is available (such as the CIFS server's "workgroup" mode).
121076b27f93Sbaban  *
121176b27f93Sbaban  * Notes:
121276b27f93Sbaban  * 1. Currently we don't support localization of well-known SID names,
121362c60062Sbaban  * unlike Windows.
121462c60062Sbaban  *
121576b27f93Sbaban  * 2. Other well-known SIDs i.e. S-1-5-<domain>-<w-k RID> are not stored
121676b27f93Sbaban  * here. AD does have normal user/group objects for these objects and
121776b27f93Sbaban  * can be looked up using the existing AD lookup code.
1218e8c27ec8Sbaban  *
1219e8c27ec8Sbaban  * 3. See comments above lookup_wksids_sid2pid() for more information
1220e8c27ec8Sbaban  * on how we lookup the wksids table.
122162c60062Sbaban  */
122262c60062Sbaban static wksids_table_t wksids[] = {
1223e8c27ec8Sbaban 	{"S-1-0", 0, "Nobody", 0, SENTINEL_PID, -1, 1},
1224e8c27ec8Sbaban 	{"S-1-1", 0, "Everyone", 0, SENTINEL_PID, -1, -1},
1225e8c27ec8Sbaban 	{"S-1-3", 0, "Creator Owner", 1, IDMAP_WK_CREATOR_OWNER_UID, 1, 0},
1226e8c27ec8Sbaban 	{"S-1-3", 1, "Creator Group", 0, IDMAP_WK_CREATOR_GROUP_GID, 0, 0},
1227e8c27ec8Sbaban 	{"S-1-3", 2, "Creator Owner Server", 1, SENTINEL_PID, -1, -1},
1228e8c27ec8Sbaban 	{"S-1-3", 3, "Creator Group Server", 0, SENTINEL_PID, -1, 1},
1229e8c27ec8Sbaban 	{"S-1-3", 4, "Owner Rights", 0, SENTINEL_PID, -1, -1},
1230e8c27ec8Sbaban 	{"S-1-5", 1, "Dialup", 0, SENTINEL_PID, -1, -1},
1231e8c27ec8Sbaban 	{"S-1-5", 2, "Network", 0, SENTINEL_PID, -1, -1},
1232e8c27ec8Sbaban 	{"S-1-5", 3, "Batch", 0, SENTINEL_PID, -1, -1},
1233e8c27ec8Sbaban 	{"S-1-5", 4, "Interactive", 0, SENTINEL_PID, -1, -1},
1234e8c27ec8Sbaban 	{"S-1-5", 6, "Service", 0, SENTINEL_PID, -1, -1},
1235e8c27ec8Sbaban 	{"S-1-5", 7, "Anonymous Logon", 0, GID_NOBODY, 0, 0},
1236e8c27ec8Sbaban 	{"S-1-5", 7, "Anonymous Logon", 0, UID_NOBODY, 1, 0},
1237e8c27ec8Sbaban 	{"S-1-5", 8, "Proxy", 0, SENTINEL_PID, -1, -1},
1238e8c27ec8Sbaban 	{"S-1-5", 9, "Enterprise Domain Controllers", 0, SENTINEL_PID, -1, -1},
1239e8c27ec8Sbaban 	{"S-1-5", 10, "Self", 0, SENTINEL_PID, -1, -1},
1240e8c27ec8Sbaban 	{"S-1-5", 11, "Authenticated Users", 0, SENTINEL_PID, -1, -1},
1241e8c27ec8Sbaban 	{"S-1-5", 12, "Restricted Code", 0, SENTINEL_PID, -1, -1},
1242e8c27ec8Sbaban 	{"S-1-5", 13, "Terminal Server User", 0, SENTINEL_PID, -1, -1},
1243e8c27ec8Sbaban 	{"S-1-5", 14, "Remote Interactive Logon", 0, SENTINEL_PID, -1, -1},
1244e8c27ec8Sbaban 	{"S-1-5", 15, "This Organization", 0, SENTINEL_PID, -1, -1},
1245e8c27ec8Sbaban 	{"S-1-5", 17, "IUSR", 0, SENTINEL_PID, -1, -1},
1246e8c27ec8Sbaban 	{"S-1-5", 18, "Local System", 0, IDMAP_WK_LOCAL_SYSTEM_GID, 0, 0},
1247e8c27ec8Sbaban 	{"S-1-5", 19, "Local Service", 0, SENTINEL_PID, -1, -1},
1248e8c27ec8Sbaban 	{"S-1-5", 20, "Network Service", 0, SENTINEL_PID, -1, -1},
1249e8c27ec8Sbaban 	{"S-1-5", 1000, "Other Organization", 0, SENTINEL_PID, -1, -1},
1250e8c27ec8Sbaban 	{"S-1-5-32", 544, "Administrators", 0, SENTINEL_PID, -1, -1},
1251e8c27ec8Sbaban 	{"S-1-5-32", 545, "Users", 0, SENTINEL_PID, -1, -1},
1252e8c27ec8Sbaban 	{"S-1-5-32", 546, "Guests", 0, SENTINEL_PID, -1, -1},
1253e8c27ec8Sbaban 	{"S-1-5-32", 547, "Power Users", 0, SENTINEL_PID, -1, -1},
1254e8c27ec8Sbaban 	{"S-1-5-32", 548, "Account Operators", 0, SENTINEL_PID, -1, -1},
1255e8c27ec8Sbaban 	{"S-1-5-32", 549, "Server Operators", 0, SENTINEL_PID, -1, -1},
1256e8c27ec8Sbaban 	{"S-1-5-32", 550, "Print Operators", 0, SENTINEL_PID, -1, -1},
1257e8c27ec8Sbaban 	{"S-1-5-32", 551, "Backup Operators", 0, SENTINEL_PID, -1, -1},
1258e8c27ec8Sbaban 	{"S-1-5-32", 552, "Replicator", 0, SENTINEL_PID, -1, -1},
125976b27f93Sbaban 	{"S-1-5-32", 554, "Pre-Windows 2000 Compatible Access", 0,
1260e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1261e8c27ec8Sbaban 	{"S-1-5-32", 555, "Remote Desktop Users", 0, SENTINEL_PID, -1, -1},
126276b27f93Sbaban 	{"S-1-5-32", 556, "Network Configuration Operators", 0,
1263e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
126476b27f93Sbaban 	{"S-1-5-32", 557, "Incoming Forest Trust Builders", 0,
1265e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1266e8c27ec8Sbaban 	{"S-1-5-32", 558, "Performance Monitor Users", 0, SENTINEL_PID, -1, -1},
1267e8c27ec8Sbaban 	{"S-1-5-32", 559, "Performance Log Users", 0, SENTINEL_PID, -1, -1},
126876b27f93Sbaban 	{"S-1-5-32", 560, "Windows Authorization Access Group", 0,
1269e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
127076b27f93Sbaban 	{"S-1-5-32", 561, "Terminal Server License Servers", 0,
1271e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1272e8c27ec8Sbaban 	{"S-1-5-32", 561, "Distributed COM Users", 0, SENTINEL_PID, -1, -1},
1273e8c27ec8Sbaban 	{"S-1-5-32", 568, "IIS_IUSRS", 0, SENTINEL_PID, -1, -1},
1274e8c27ec8Sbaban 	{"S-1-5-32", 569, "Cryptographic Operators", 0, SENTINEL_PID, -1, -1},
1275e8c27ec8Sbaban 	{"S-1-5-32", 573, "Event Log Readers", 0, SENTINEL_PID, -1, -1},
127676b27f93Sbaban 	{"S-1-5-32", 574, "Certificate Service DCOM Access", 0,
1277e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1278e8c27ec8Sbaban 	{"S-1-5-64", 21, "Digest Authentication", 0, SENTINEL_PID, -1, -1},
1279e8c27ec8Sbaban 	{"S-1-5-64", 10, "NTLM Authentication", 0, SENTINEL_PID, -1, -1},
1280e8c27ec8Sbaban 	{"S-1-5-64", 14, "SChannel Authentication", 0, SENTINEL_PID, -1, -1},
1281e8c27ec8Sbaban 	{NULL, UINT32_MAX, NULL, -1, SENTINEL_PID, -1, -1}
1282c5c4113dSnw141292 };
1283c5c4113dSnw141292 
1284e8c27ec8Sbaban /*
1285e8c27ec8Sbaban  * Lookup well-known SIDs table either by winname or by SID.
1286e8c27ec8Sbaban  * If the given winname or SID is a well-known SID then we set wksid
1287e8c27ec8Sbaban  * variable and then proceed to see if the SID has a hard mapping to
1288e8c27ec8Sbaban  * a particular UID/GID (Ex: Creator Owner/Creator Group mapped to
1289e8c27ec8Sbaban  * fixed ephemeral ids). If we find such mapping then we return
1290e8c27ec8Sbaban  * success otherwise notfound. If a well-known SID is mapped to
1291e8c27ec8Sbaban  * SENTINEL_PID and the direction field is set (bi-directional or
1292e8c27ec8Sbaban  * win2unix) then we treat it as inhibited mapping and return no
1293e8c27ec8Sbaban  * mapping (Ex. S-1-0-0).
1294e8c27ec8Sbaban  */
1295cd37da74Snw141292 static
1296cd37da74Snw141292 idmap_retcode
1297e8c27ec8Sbaban lookup_wksids_sid2pid(idmap_mapping *req, idmap_id_res *res, int *wksid)
1298cd37da74Snw141292 {
1299c5c4113dSnw141292 	int i;
130062c60062Sbaban 
1301e8c27ec8Sbaban 	*wksid = 0;
1302e8c27ec8Sbaban 
1303e8c27ec8Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
1304e8c27ec8Sbaban 		if (req->id1.idmap_id_u.sid.prefix != NULL) {
1305e8c27ec8Sbaban 			if ((strcasecmp(wksids[i].sidprefix,
1306e8c27ec8Sbaban 			    req->id1.idmap_id_u.sid.prefix) != 0) ||
1307e8c27ec8Sbaban 			    wksids[i].rid != req->id1.idmap_id_u.sid.rid)
1308e8c27ec8Sbaban 				/* this is not our SID */
1309e8c27ec8Sbaban 				continue;
1310e8c27ec8Sbaban 			if (req->id1name == NULL) {
1311e8c27ec8Sbaban 				req->id1name = strdup(wksids[i].winname);
1312e8c27ec8Sbaban 				if (req->id1name == NULL)
1313e8c27ec8Sbaban 					return (IDMAP_ERR_MEMORY);
1314e8c27ec8Sbaban 			}
1315e8c27ec8Sbaban 		} else if (req->id1name != NULL) {
1316e8c27ec8Sbaban 			if (strcasecmp(wksids[i].winname, req->id1name) != 0)
1317e8c27ec8Sbaban 				/* this is not our winname */
1318e8c27ec8Sbaban 				continue;
1319e8c27ec8Sbaban 			req->id1.idmap_id_u.sid.prefix =
1320e8c27ec8Sbaban 			    strdup(wksids[i].sidprefix);
1321e8c27ec8Sbaban 			if (req->id1.idmap_id_u.sid.prefix == NULL)
1322e8c27ec8Sbaban 				return (IDMAP_ERR_MEMORY);
1323e8c27ec8Sbaban 			req->id1.idmap_id_u.sid.rid = wksids[i].rid;
1324e8c27ec8Sbaban 		}
1325e8c27ec8Sbaban 
1326e8c27ec8Sbaban 		*wksid = 1;
1327e8c27ec8Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
1328e8c27ec8Sbaban 
1329e8c27ec8Sbaban 		req->id1.idtype = (wksids[i].is_wuser) ?
1330e8c27ec8Sbaban 		    IDMAP_USID : IDMAP_GSID;
1331e8c27ec8Sbaban 
1332e8c27ec8Sbaban 		if (wksids[i].pid == SENTINEL_PID) {
1333e8c27ec8Sbaban 			if (wksids[i].direction == IDMAP_DIRECTION_BI ||
1334e8c27ec8Sbaban 			    wksids[i].direction == IDMAP_DIRECTION_W2U)
1335e8c27ec8Sbaban 				/* Inhibited */
1336e8c27ec8Sbaban 				return (IDMAP_ERR_NOMAPPING);
1337e8c27ec8Sbaban 			/* Not mapped */
1338e8c27ec8Sbaban 			return (IDMAP_ERR_NOTFOUND);
1339e8c27ec8Sbaban 		} else if (wksids[i].direction == IDMAP_DIRECTION_U2W)
134062c60062Sbaban 			continue;
134162c60062Sbaban 
1342e8c27ec8Sbaban 		switch (res->id.idtype) {
1343c5c4113dSnw141292 		case IDMAP_UID:
134462c60062Sbaban 			if (wksids[i].is_user == 0)
134562c60062Sbaban 				continue;
134662c60062Sbaban 			res->id.idmap_id_u.uid = wksids[i].pid;
134762c60062Sbaban 			res->direction = wksids[i].direction;
1348c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1349c5c4113dSnw141292 		case IDMAP_GID:
135062c60062Sbaban 			if (wksids[i].is_user == 1)
135162c60062Sbaban 				continue;
135262c60062Sbaban 			res->id.idmap_id_u.gid = wksids[i].pid;
135362c60062Sbaban 			res->direction = wksids[i].direction;
1354c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1355c5c4113dSnw141292 		case IDMAP_POSIXID:
135662c60062Sbaban 			res->id.idmap_id_u.uid = wksids[i].pid;
135762c60062Sbaban 			res->id.idtype = (!wksids[i].is_user) ?
1358c5c4113dSnw141292 			    IDMAP_GID : IDMAP_UID;
135962c60062Sbaban 			res->direction = wksids[i].direction;
1360c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1361c5c4113dSnw141292 		default:
1362c5c4113dSnw141292 			return (IDMAP_ERR_NOTSUPPORTED);
1363c5c4113dSnw141292 		}
1364c5c4113dSnw141292 	}
1365c5c4113dSnw141292 	return (IDMAP_ERR_NOTFOUND);
1366c5c4113dSnw141292 }
1367c5c4113dSnw141292 
1368cd37da74Snw141292 
1369cd37da74Snw141292 static
1370cd37da74Snw141292 idmap_retcode
1371cd37da74Snw141292 lookup_wksids_pid2sid(idmap_mapping *req, idmap_id_res *res, int is_user)
1372cd37da74Snw141292 {
1373c5c4113dSnw141292 	int i;
1374e8c27ec8Sbaban 	if (req->id1.idmap_id_u.uid == SENTINEL_PID)
1375e8c27ec8Sbaban 		return (IDMAP_ERR_NOTFOUND);
137662c60062Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
137762c60062Sbaban 		if (wksids[i].pid == req->id1.idmap_id_u.uid &&
137862c60062Sbaban 		    wksids[i].is_user == is_user &&
137962c60062Sbaban 		    wksids[i].direction != IDMAP_DIRECTION_W2U) {
1380e8c27ec8Sbaban 			if (res->id.idtype == IDMAP_SID) {
1381e8c27ec8Sbaban 				res->id.idtype = (wksids[i].is_wuser) ?
1382e8c27ec8Sbaban 				    IDMAP_USID : IDMAP_GSID;
1383e8c27ec8Sbaban 			}
138462c60062Sbaban 			res->id.idmap_id_u.sid.rid = wksids[i].rid;
1385c5c4113dSnw141292 			res->id.idmap_id_u.sid.prefix =
138662c60062Sbaban 			    strdup(wksids[i].sidprefix);
1387c5c4113dSnw141292 			if (res->id.idmap_id_u.sid.prefix == NULL) {
1388c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1389c5c4113dSnw141292 				return (IDMAP_ERR_MEMORY);
1390c5c4113dSnw141292 			}
139162c60062Sbaban 			res->direction = wksids[i].direction;
1392c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1393c5c4113dSnw141292 		}
1394c5c4113dSnw141292 	}
139562c60062Sbaban 	return (IDMAP_ERR_NOTFOUND);
139662c60062Sbaban }
139762c60062Sbaban 
1398cd37da74Snw141292 static
1399cd37da74Snw141292 idmap_retcode
1400cd37da74Snw141292 lookup_wksids_name2sid(const char *name, char **canonname, char **sidprefix,
1401cd37da74Snw141292 	idmap_rid_t *rid, int *type)
1402cd37da74Snw141292 {
140362c60062Sbaban 	int i;
140462c60062Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
1405e8c27ec8Sbaban 		if (strcasecmp(wksids[i].winname, name) != 0)
1406e8c27ec8Sbaban 			continue;
1407e8c27ec8Sbaban 		if (sidprefix != NULL &&
1408e8c27ec8Sbaban 		    (*sidprefix = strdup(wksids[i].sidprefix)) == NULL) {
140962c60062Sbaban 			idmapdlog(LOG_ERR, "Out of memory");
141062c60062Sbaban 			return (IDMAP_ERR_MEMORY);
141162c60062Sbaban 		}
1412cd37da74Snw141292 		if (canonname != NULL &&
1413cd37da74Snw141292 		    (*canonname = strdup(wksids[i].winname)) == NULL) {
1414cd37da74Snw141292 			idmapdlog(LOG_ERR, "Out of memory");
1415e8c27ec8Sbaban 			if (sidprefix != NULL) {
1416e8c27ec8Sbaban 				free(*sidprefix);
1417e8c27ec8Sbaban 				*sidprefix = NULL;
1418e8c27ec8Sbaban 			}
1419cd37da74Snw141292 			return (IDMAP_ERR_MEMORY);
1420cd37da74Snw141292 		}
142162c60062Sbaban 		if (type != NULL)
1422e8c27ec8Sbaban 			*type = (wksids[i].is_wuser) ?
142362c60062Sbaban 			    _IDMAP_T_USER : _IDMAP_T_GROUP;
142462c60062Sbaban 		if (rid != NULL)
142562c60062Sbaban 			*rid = wksids[i].rid;
142662c60062Sbaban 		return (IDMAP_SUCCESS);
142762c60062Sbaban 	}
1428c5c4113dSnw141292 	return (IDMAP_ERR_NOTFOUND);
1429c5c4113dSnw141292 }
1430c5c4113dSnw141292 
1431cd37da74Snw141292 static
1432cd37da74Snw141292 idmap_retcode
1433cd37da74Snw141292 lookup_cache_sid2pid(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
1434cd37da74Snw141292 {
1435c5c4113dSnw141292 	char		*end;
1436c5c4113dSnw141292 	char		*sql = NULL;
1437c5c4113dSnw141292 	const char	**values;
1438c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
1439c5c4113dSnw141292 	int		ncol, is_user;
1440c5c4113dSnw141292 	uid_t		pid;
1441c5c4113dSnw141292 	time_t		curtime, exp;
1442c5c4113dSnw141292 	idmap_retcode	retcode;
1443042addd6Sbaban 	char		*is_user_string, *lower_name;
1444c5c4113dSnw141292 
1445c5c4113dSnw141292 	/* Current time */
1446c5c4113dSnw141292 	errno = 0;
1447c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
1448cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
1449c5c4113dSnw141292 		    strerror(errno));
1450c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
1451c5c4113dSnw141292 		goto out;
1452c5c4113dSnw141292 	}
1453c5c4113dSnw141292 
1454e8c27ec8Sbaban 	switch (res->id.idtype) {
1455cd37da74Snw141292 	case IDMAP_UID:
1456cd37da74Snw141292 		is_user_string = "1";
1457cd37da74Snw141292 		break;
1458cd37da74Snw141292 	case IDMAP_GID:
1459cd37da74Snw141292 		is_user_string = "0";
1460cd37da74Snw141292 		break;
1461cd37da74Snw141292 	case IDMAP_POSIXID:
1462cd37da74Snw141292 		/* the non-diagonal mapping */
1463cd37da74Snw141292 		is_user_string = "is_wuser";
1464cd37da74Snw141292 		break;
1465cd37da74Snw141292 	default:
1466cd37da74Snw141292 		retcode = IDMAP_ERR_NOTSUPPORTED;
1467cd37da74Snw141292 		goto out;
1468cd37da74Snw141292 	}
1469cd37da74Snw141292 
1470c5c4113dSnw141292 	/* SQL to lookup the cache */
1471e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
1472e8c27ec8Sbaban 		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
1473e8c27ec8Sbaban 		    "unixname, u2w, is_wuser "
1474cd37da74Snw141292 		    "FROM idmap_cache WHERE is_user = %s AND "
1475c5c4113dSnw141292 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
1476c5c4113dSnw141292 		    "(pid >= 2147483648 OR "
1477c5c4113dSnw141292 		    "(expiration = 0 OR expiration ISNULL OR "
1478c5c4113dSnw141292 		    "expiration > %d));",
1479e8c27ec8Sbaban 		    is_user_string, req->id1.idmap_id_u.sid.prefix,
1480e8c27ec8Sbaban 		    req->id1.idmap_id_u.sid.rid, curtime);
1481e8c27ec8Sbaban 	} else if (req->id1name != NULL) {
1482042addd6Sbaban 		if ((lower_name = tolower_u8(req->id1name)) == NULL)
1483042addd6Sbaban 			lower_name = req->id1name;
1484e8c27ec8Sbaban 		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
1485e8c27ec8Sbaban 		    "unixname, u2w, is_wuser "
1486e8c27ec8Sbaban 		    "FROM idmap_cache WHERE is_user = %s AND "
1487e8c27ec8Sbaban 		    "winname = %Q AND windomain = %Q AND w2u = 1 AND "
1488e8c27ec8Sbaban 		    "(pid >= 2147483648 OR "
1489e8c27ec8Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
1490e8c27ec8Sbaban 		    "expiration > %d));",
1491042addd6Sbaban 		    is_user_string, lower_name, req->id1domain, curtime);
1492042addd6Sbaban 		if (lower_name != req->id1name)
1493042addd6Sbaban 			free(lower_name);
1494e8c27ec8Sbaban 	} else {
1495e8c27ec8Sbaban 		retcode = IDMAP_ERR_ARG;
1496e8c27ec8Sbaban 		goto out;
1497e8c27ec8Sbaban 	}
1498e8c27ec8Sbaban 
1499c5c4113dSnw141292 	if (sql == NULL) {
1500c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
1501c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
1502c5c4113dSnw141292 		goto out;
1503c5c4113dSnw141292 	}
1504e8c27ec8Sbaban 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 6, &values);
1505c5c4113dSnw141292 	sqlite_freemem(sql);
1506c5c4113dSnw141292 
1507c5c4113dSnw141292 	if (retcode == IDMAP_ERR_NOTFOUND) {
1508c5c4113dSnw141292 		goto out;
1509c5c4113dSnw141292 	} else if (retcode == IDMAP_SUCCESS) {
1510c5c4113dSnw141292 		/* sanity checks */
1511c5c4113dSnw141292 		if (values[0] == NULL || values[1] == NULL) {
1512c5c4113dSnw141292 			retcode = IDMAP_ERR_CACHE;
1513c5c4113dSnw141292 			goto out;
1514c5c4113dSnw141292 		}
1515c5c4113dSnw141292 
1516c5c4113dSnw141292 		pid = strtoul(values[0], &end, 10);
1517c5c4113dSnw141292 		is_user = strncmp(values[1], "0", 2) ? 1 : 0;
1518c5c4113dSnw141292 
1519cd37da74Snw141292 		if (is_user) {
1520cd37da74Snw141292 			res->id.idtype = IDMAP_UID;
1521cd37da74Snw141292 			res->id.idmap_id_u.uid = pid;
1522cd37da74Snw141292 		} else {
1523cd37da74Snw141292 			res->id.idtype = IDMAP_GID;
1524cd37da74Snw141292 			res->id.idmap_id_u.gid = pid;
1525cd37da74Snw141292 		}
1526cd37da74Snw141292 
1527c5c4113dSnw141292 		/*
1528c5c4113dSnw141292 		 * We may have an expired ephemeral mapping. Consider
1529c5c4113dSnw141292 		 * the expired entry as valid if we are not going to
1530c5c4113dSnw141292 		 * perform name-based mapping. But do not renew the
1531c5c4113dSnw141292 		 * expiration.
1532c5c4113dSnw141292 		 * If we will be doing name-based mapping then store the
1533c5c4113dSnw141292 		 * ephemeral pid in the result so that we can use it
1534c5c4113dSnw141292 		 * if we end up doing dynamic mapping again.
1535c5c4113dSnw141292 		 */
1536c5c4113dSnw141292 		if (!DO_NOT_ALLOC_NEW_ID_MAPPING(req) &&
1537cd37da74Snw141292 		    !AVOID_NAMESERVICE(req) &&
1538cd37da74Snw141292 		    IS_EPHEMERAL(pid) && values[2] != NULL) {
1539c5c4113dSnw141292 			exp = strtoll(values[2], &end, 10);
1540c5c4113dSnw141292 			if (exp && exp <= curtime) {
1541c5c4113dSnw141292 				/* Store the ephemeral pid */
1542651c0131Sbaban 				res->direction = IDMAP_DIRECTION_BI;
1543cd37da74Snw141292 				req->direction |= is_user
1544cd37da74Snw141292 				    ? _IDMAP_F_EXP_EPH_UID
1545cd37da74Snw141292 				    : _IDMAP_F_EXP_EPH_GID;
1546c5c4113dSnw141292 				retcode = IDMAP_ERR_NOTFOUND;
1547c5c4113dSnw141292 			}
1548c5c4113dSnw141292 		}
1549c5c4113dSnw141292 	}
1550c5c4113dSnw141292 
1551c5c4113dSnw141292 out:
1552c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
155362c60062Sbaban 		if (values[4] != NULL)
1554c5c4113dSnw141292 			res->direction =
1555651c0131Sbaban 			    (strtol(values[4], &end, 10) == 0)?
1556651c0131Sbaban 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
1557c5c4113dSnw141292 		else
1558651c0131Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
1559c5c4113dSnw141292 
156062c60062Sbaban 		if (values[3] != NULL) {
1561e8c27ec8Sbaban 			if (req->id2name != NULL)
1562e8c27ec8Sbaban 				free(req->id2name);
15638e228215Sdm199847 			req->id2name = strdup(values[3]);
15648e228215Sdm199847 			if (req->id2name == NULL) {
1565c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1566c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
1567c5c4113dSnw141292 			}
1568c5c4113dSnw141292 		}
1569e8c27ec8Sbaban 
1570e8c27ec8Sbaban 		req->id1.idtype = strncmp(values[5], "0", 2) ?
1571e8c27ec8Sbaban 		    IDMAP_USID : IDMAP_GSID;
1572c5c4113dSnw141292 	}
157362c60062Sbaban 	if (vm != NULL)
1574c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
1575c5c4113dSnw141292 	return (retcode);
1576c5c4113dSnw141292 }
1577c5c4113dSnw141292 
1578cd37da74Snw141292 static
1579cd37da74Snw141292 idmap_retcode
158062c60062Sbaban lookup_cache_sid2name(sqlite *cache, const char *sidprefix, idmap_rid_t rid,
1581cd37da74Snw141292 		char **name, char **domain, int *type)
1582cd37da74Snw141292 {
1583c5c4113dSnw141292 	char		*end;
1584c5c4113dSnw141292 	char		*sql = NULL;
1585c5c4113dSnw141292 	const char	**values;
1586c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
1587c5c4113dSnw141292 	int		ncol;
1588c5c4113dSnw141292 	time_t		curtime;
1589c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
1590c5c4113dSnw141292 
1591c5c4113dSnw141292 	/* Get current time */
1592c5c4113dSnw141292 	errno = 0;
1593c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
1594cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
1595c5c4113dSnw141292 		    strerror(errno));
1596c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
1597c5c4113dSnw141292 		goto out;
1598c5c4113dSnw141292 	}
1599c5c4113dSnw141292 
1600c5c4113dSnw141292 	/* SQL to lookup the cache */
1601cd37da74Snw141292 	sql = sqlite_mprintf("SELECT canon_name, domain, type "
1602cd37da74Snw141292 	    "FROM name_cache WHERE "
1603c5c4113dSnw141292 	    "sidprefix = %Q AND rid = %u AND "
1604c5c4113dSnw141292 	    "(expiration = 0 OR expiration ISNULL OR "
1605c5c4113dSnw141292 	    "expiration > %d);",
1606c5c4113dSnw141292 	    sidprefix, rid, curtime);
1607c5c4113dSnw141292 	if (sql == NULL) {
1608c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
1609c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
1610c5c4113dSnw141292 		goto out;
1611c5c4113dSnw141292 	}
1612c5c4113dSnw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 3, &values);
1613c5c4113dSnw141292 	sqlite_freemem(sql);
1614c5c4113dSnw141292 
1615c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
161662c60062Sbaban 		if (type != NULL) {
1617c5c4113dSnw141292 			if (values[2] == NULL) {
1618c5c4113dSnw141292 				retcode = IDMAP_ERR_CACHE;
1619c5c4113dSnw141292 				goto out;
1620c5c4113dSnw141292 			}
1621c5c4113dSnw141292 			*type = strtol(values[2], &end, 10);
1622c5c4113dSnw141292 		}
1623c5c4113dSnw141292 
162462c60062Sbaban 		if (name != NULL && values[0] != NULL) {
1625c5c4113dSnw141292 			if ((*name = strdup(values[0])) == NULL) {
1626c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1627c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
1628c5c4113dSnw141292 				goto out;
1629c5c4113dSnw141292 			}
1630c5c4113dSnw141292 		}
1631c5c4113dSnw141292 
163262c60062Sbaban 		if (domain != NULL && values[1] != NULL) {
1633c5c4113dSnw141292 			if ((*domain = strdup(values[1])) == NULL) {
163462c60062Sbaban 				if (name != NULL && *name) {
1635c5c4113dSnw141292 					free(*name);
1636c5c4113dSnw141292 					*name = NULL;
1637c5c4113dSnw141292 				}
1638c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1639c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
1640c5c4113dSnw141292 				goto out;
1641c5c4113dSnw141292 			}
1642c5c4113dSnw141292 		}
1643c5c4113dSnw141292 	}
1644c5c4113dSnw141292 
1645c5c4113dSnw141292 out:
164662c60062Sbaban 	if (vm != NULL)
1647c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
1648c5c4113dSnw141292 	return (retcode);
1649c5c4113dSnw141292 }
1650c5c4113dSnw141292 
1651c5c4113dSnw141292 /*
1652e8c27ec8Sbaban  * Given SID, find winname using name_cache OR
1653e8c27ec8Sbaban  * Given winname, find SID using name_cache.
1654e8c27ec8Sbaban  * Used when mapping win to unix i.e. req->id1 is windows id and
1655e8c27ec8Sbaban  * req->id2 is unix id
1656c5c4113dSnw141292  */
1657cd37da74Snw141292 static
1658cd37da74Snw141292 idmap_retcode
1659e8c27ec8Sbaban lookup_name_cache(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
1660cd37da74Snw141292 {
1661c5c4113dSnw141292 	int		type = -1;
1662c5c4113dSnw141292 	idmap_retcode	retcode;
1663e8c27ec8Sbaban 	char		*sidprefix = NULL;
1664c5c4113dSnw141292 	idmap_rid_t	rid;
1665c5c4113dSnw141292 	char		*name = NULL, *domain = NULL;
1666c5c4113dSnw141292 
1667e8c27ec8Sbaban 	/* Done if we've both sid and winname */
1668e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL && req->id1name != NULL)
1669e8c27ec8Sbaban 		return (IDMAP_SUCCESS);
1670c5c4113dSnw141292 
1671e8c27ec8Sbaban 	/* Lookup sid to winname */
1672e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
1673e8c27ec8Sbaban 		retcode = lookup_cache_sid2name(cache,
1674e8c27ec8Sbaban 		    req->id1.idmap_id_u.sid.prefix,
1675e8c27ec8Sbaban 		    req->id1.idmap_id_u.sid.rid, &name, &domain, &type);
167662c60062Sbaban 		goto out;
1677e8c27ec8Sbaban 	}
167862c60062Sbaban 
1679e8c27ec8Sbaban 	/* Lookup winame to sid */
1680e8c27ec8Sbaban 	retcode = lookup_cache_name2sid(cache, req->id1name, req->id1domain,
1681e8c27ec8Sbaban 	    &name, &sidprefix, &rid, &type);
1682c5c4113dSnw141292 
168362c60062Sbaban out:
1684e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
1685c5c4113dSnw141292 		free(name);
1686c5c4113dSnw141292 		free(domain);
1687e8c27ec8Sbaban 		free(sidprefix);
1688e8c27ec8Sbaban 		return (retcode);
1689e8c27ec8Sbaban 	}
1690e8c27ec8Sbaban 
1691e8c27ec8Sbaban 	if (res->id.idtype == IDMAP_POSIXID) {
1692e8c27ec8Sbaban 		res->id.idtype = (type == _IDMAP_T_USER) ?
1693e8c27ec8Sbaban 		    IDMAP_UID : IDMAP_GID;
1694e8c27ec8Sbaban 	}
1695e8c27ec8Sbaban 	req->id1.idtype = (type == _IDMAP_T_USER) ?
1696e8c27ec8Sbaban 	    IDMAP_USID : IDMAP_GSID;
1697e8c27ec8Sbaban 
1698e8c27ec8Sbaban 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
1699e8c27ec8Sbaban 	if (name != NULL) {
1700e8c27ec8Sbaban 		free(req->id1name);	/* Free existing winname */
1701e8c27ec8Sbaban 		req->id1name = name;	/* and use canonical name instead */
1702e8c27ec8Sbaban 	}
1703e8c27ec8Sbaban 	if (req->id1domain == NULL)
1704e8c27ec8Sbaban 		req->id1domain = domain;
1705e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix == NULL) {
1706e8c27ec8Sbaban 		req->id1.idmap_id_u.sid.prefix = sidprefix;
1707e8c27ec8Sbaban 		req->id1.idmap_id_u.sid.rid = rid;
1708c5c4113dSnw141292 	}
1709c5c4113dSnw141292 	return (retcode);
1710c5c4113dSnw141292 }
1711c5c4113dSnw141292 
1712e8c27ec8Sbaban /*
1713e8c27ec8Sbaban  * Batch AD lookups
1714e8c27ec8Sbaban  */
1715c5c4113dSnw141292 idmap_retcode
1716e8c27ec8Sbaban ad_lookup_batch(lookup_state_t *state, idmap_mapping_batch *batch,
1717cd37da74Snw141292 		idmap_ids_res *result)
1718cd37da74Snw141292 {
1719c5c4113dSnw141292 	idmap_retcode	retcode;
1720e8c27ec8Sbaban 	int		i, add, type, is_wuser, is_user;
1721e8c27ec8Sbaban 	int		retries = 0, eunixtype;
1722e8c27ec8Sbaban 	char		**unixname;
1723c5c4113dSnw141292 	idmap_mapping	*req;
1724c5c4113dSnw141292 	idmap_id_res	*res;
1725e8c27ec8Sbaban 	idmap_query_state_t	*qs = NULL;
1726e8c27ec8Sbaban 
1727e8c27ec8Sbaban 	/*
1728e8c27ec8Sbaban 	 * Since req->id2.idtype is unused, we will use it here
1729e8c27ec8Sbaban 	 * to retrieve the value of sid_type. But it needs to be
1730e8c27ec8Sbaban 	 * reset to IDMAP_NONE before we return to prevent xdr
1731e8c27ec8Sbaban 	 * from mis-interpreting req->id2 when it tries to free
1732e8c27ec8Sbaban 	 * the input argument. Other option is to allocate an
1733e8c27ec8Sbaban 	 * array of integers and use it instead for the batched
1734e8c27ec8Sbaban 	 * call. But why un-necessarily allocate memory. That may
1735e8c27ec8Sbaban 	 * be an option if req->id2.idtype cannot be re-used in
1736e8c27ec8Sbaban 	 * future.
1737e8c27ec8Sbaban 	 */
1738c5c4113dSnw141292 
1739c5c4113dSnw141292 	if (state->ad_nqueries == 0)
1740c5c4113dSnw141292 		return (IDMAP_SUCCESS);
1741c5c4113dSnw141292 
1742c5c4113dSnw141292 retry:
1743e8c27ec8Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, state->ad_nqueries,
1744e8c27ec8Sbaban 	    &qs);
1745e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
1746*0dcc7149Snw141292 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
1747*0dcc7149Snw141292 			goto retry;
1748*0dcc7149Snw141292 		degrade_svc("failed to create batch for AD lookup");
1749e8c27ec8Sbaban 		goto out;
1750c5c4113dSnw141292 	}
1751c5c4113dSnw141292 
1752c8e26105Sjp151216 	restore_svc();
1753c8e26105Sjp151216 
1754e8c27ec8Sbaban 	idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
1755e8c27ec8Sbaban 	    state->ad_unixgroup_attr);
1756e8c27ec8Sbaban 
1757e8c27ec8Sbaban 	for (i = 0, add = 0; i < batch->idmap_mapping_batch_len; i++) {
1758c5c4113dSnw141292 		req = &batch->idmap_mapping_batch_val[i];
1759c5c4113dSnw141292 		res = &result->ids.ids_val[i];
1760e8c27ec8Sbaban 		retcode = IDMAP_SUCCESS;
1761e8c27ec8Sbaban 		req->id2.idtype = IDMAP_NONE;
1762c5c4113dSnw141292 
1763e8c27ec8Sbaban 		/* Skip if not marked for AD lookup */
1764e8c27ec8Sbaban 		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
1765e8c27ec8Sbaban 			continue;
1766e8c27ec8Sbaban 
1767c5c4113dSnw141292 		if (retries == 0)
1768c5c4113dSnw141292 			res->retcode = IDMAP_ERR_RETRIABLE_NET_ERR;
1769c5c4113dSnw141292 		else if (res->retcode != IDMAP_ERR_RETRIABLE_NET_ERR)
1770c5c4113dSnw141292 			continue;
1771e8c27ec8Sbaban 
1772e8c27ec8Sbaban 		if (IS_REQUEST_SID(*req, 1)) {
1773e8c27ec8Sbaban 			/* win to unix */
1774e8c27ec8Sbaban 
1775e8c27ec8Sbaban 			assert(req->id1.idmap_id_u.sid.prefix != NULL);
1776e8c27ec8Sbaban 
1777e8c27ec8Sbaban 			/* Lookup AD by SID */
1778e8c27ec8Sbaban 			unixname = NULL;
1779e8c27ec8Sbaban 			eunixtype = _IDMAP_T_UNDEF;
1780e8c27ec8Sbaban 			if (req->id2name == NULL) {
1781e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_UID &&
1782e8c27ec8Sbaban 				    AD_OR_MIXED(state->nm_siduid)) {
1783e8c27ec8Sbaban 					eunixtype = _IDMAP_T_USER;
1784e8c27ec8Sbaban 					unixname = &req->id2name;
1785e8c27ec8Sbaban 				} else if (res->id.idtype == IDMAP_GID &&
1786e8c27ec8Sbaban 				    AD_OR_MIXED(state->nm_sidgid)) {
1787e8c27ec8Sbaban 					eunixtype = _IDMAP_T_GROUP;
1788e8c27ec8Sbaban 					unixname = &req->id2name;
1789e8c27ec8Sbaban 				} else if (AD_OR_MIXED(state->nm_siduid) ||
1790e8c27ec8Sbaban 				    AD_OR_MIXED(state->nm_sidgid)) {
1791e8c27ec8Sbaban 					unixname = &req->id2name;
1792e8c27ec8Sbaban 				}
1793e8c27ec8Sbaban 			}
1794e8c27ec8Sbaban 			add = 1;
1795c5c4113dSnw141292 			retcode = idmap_sid2name_batch_add1(
1796e8c27ec8Sbaban 			    qs, req->id1.idmap_id_u.sid.prefix,
1797e8c27ec8Sbaban 			    &req->id1.idmap_id_u.sid.rid, eunixtype,
1798e8c27ec8Sbaban 			    (req->id1name == NULL) ? &req->id1name : NULL,
1799e8c27ec8Sbaban 			    (req->id1domain == NULL) ? &req->id1domain : NULL,
1800e8c27ec8Sbaban 			    (int *)&req->id2.idtype, unixname, &res->retcode);
1801c5c4113dSnw141292 
1802e8c27ec8Sbaban 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
1803e8c27ec8Sbaban 			/* unix to win */
1804e8c27ec8Sbaban 
1805e8c27ec8Sbaban 			if (res->id.idmap_id_u.sid.prefix != NULL &&
1806e8c27ec8Sbaban 			    req->id2name != NULL) {
1807e8c27ec8Sbaban 				/* Already have SID and winname -- done */
1808e8c27ec8Sbaban 				res->retcode = IDMAP_SUCCESS;
1809e8c27ec8Sbaban 				continue;
1810c5c4113dSnw141292 			}
1811c5c4113dSnw141292 
1812e8c27ec8Sbaban 			if (res->id.idmap_id_u.sid.prefix != NULL) {
1813cd37da74Snw141292 				/*
1814e8c27ec8Sbaban 				 * SID but no winname -- lookup AD by
1815e8c27ec8Sbaban 				 * SID to get winname.
1816cd37da74Snw141292 				 */
1817e8c27ec8Sbaban 				add = 1;
1818e8c27ec8Sbaban 				retcode = idmap_sid2name_batch_add1(
1819e8c27ec8Sbaban 				    qs, res->id.idmap_id_u.sid.prefix,
1820e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.rid,
1821e8c27ec8Sbaban 				    _IDMAP_T_UNDEF, &req->id2name,
1822e8c27ec8Sbaban 				    &req->id2domain, (int *)&req->id2.idtype,
1823e8c27ec8Sbaban 				    NULL, &res->retcode);
1824e8c27ec8Sbaban 			} else if (req->id2name != NULL) {
1825e8c27ec8Sbaban 				/*
1826e8c27ec8Sbaban 				 * winname but no SID -- lookup AD by
1827e8c27ec8Sbaban 				 * winname to get SID.
1828e8c27ec8Sbaban 				 */
1829e8c27ec8Sbaban 				add = 1;
1830e8c27ec8Sbaban 				retcode = idmap_name2sid_batch_add1(
1831e8c27ec8Sbaban 				    qs, req->id2name, req->id2domain,
1832e8c27ec8Sbaban 				    _IDMAP_T_UNDEF, NULL,
1833e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.prefix,
1834e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.rid,
1835e8c27ec8Sbaban 				    (int *)&req->id2.idtype, NULL,
1836e8c27ec8Sbaban 				    &res->retcode);
1837e8c27ec8Sbaban 			} else if (req->id1name != NULL) {
1838e8c27ec8Sbaban 				/*
1839e8c27ec8Sbaban 				 * No SID and no winname but we've unixname --
1840e8c27ec8Sbaban 				 * lookup AD by unixname to get SID.
1841e8c27ec8Sbaban 				 */
1842e8c27ec8Sbaban 				is_user = (IS_REQUEST_UID(*req)) ? 1 : 0;
1843e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_USID)
1844e8c27ec8Sbaban 					is_wuser = 1;
1845e8c27ec8Sbaban 				else if (res->id.idtype == IDMAP_GSID)
1846e8c27ec8Sbaban 					is_wuser = 0;
1847e8c27ec8Sbaban 				else
1848e8c27ec8Sbaban 					is_wuser = is_user;
1849e8c27ec8Sbaban 				add = 1;
1850e8c27ec8Sbaban 				retcode = idmap_unixname2sid_batch_add1(
1851e8c27ec8Sbaban 				    qs, req->id1name, is_user, is_wuser,
1852e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.prefix,
1853e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.rid,
1854e8c27ec8Sbaban 				    &req->id2name, &req->id2domain,
1855e8c27ec8Sbaban 				    (int *)&req->id2.idtype, &res->retcode);
1856e8c27ec8Sbaban 			}
1857e8c27ec8Sbaban 		}
1858e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS) {
1859e8c27ec8Sbaban 			idmap_lookup_release_batch(&qs);
1860e8c27ec8Sbaban 			break;
1861e8c27ec8Sbaban 		}
1862cd37da74Snw141292 	}
1863cd37da74Snw141292 
1864e8c27ec8Sbaban 	if (retcode == IDMAP_SUCCESS && add)
1865*0dcc7149Snw141292 		retcode = idmap_lookup_batch_end(&qs);
1866cd37da74Snw141292 
1867c5c4113dSnw141292 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
1868c5c4113dSnw141292 		goto retry;
1869c8e26105Sjp151216 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
1870*0dcc7149Snw141292 		degrade_svc("some AD lookups timed out repeatedly");
1871c5c4113dSnw141292 
1872e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
1873e8c27ec8Sbaban 		idmapdlog(LOG_NOTICE, "Failed to batch AD lookup requests");
1874c5c4113dSnw141292 
1875c5c4113dSnw141292 out:
1876e8c27ec8Sbaban 	/*
1877e8c27ec8Sbaban 	 * This loop does the following:
1878e8c27ec8Sbaban 	 * 1) If there are errors in creating or submitting the batch then
1879e8c27ec8Sbaban 	 *    we set the retcode for each request (res->retcode) that's part
1880e8c27ec8Sbaban 	 *    of the batch to that error. If there were no such errors then
1881e8c27ec8Sbaban 	 *    res->retcode for each request will reflect the status of AD
1882e8c27ec8Sbaban 	 *    lookup for that particular request. Initial value of
1883e8c27ec8Sbaban 	 *    res->retcode is IDMAP_ERR_RETRIABLE_NET_ERR.
1884e8c27ec8Sbaban 	 * 2) If AD lookup for a given request succeeds then evaluate the
1885e8c27ec8Sbaban 	 *    type of the AD object (i.e user or group) and update the
1886e8c27ec8Sbaban 	 *    idtype in res and req.
1887e8c27ec8Sbaban 	 * 3) Reset req->id2.idtype to IDMAP_NONE.
1888e8c27ec8Sbaban 	 */
1889e8c27ec8Sbaban 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
1890e8c27ec8Sbaban 		req = &batch->idmap_mapping_batch_val[i];
1891e8c27ec8Sbaban 		type = req->id2.idtype;
1892e8c27ec8Sbaban 		req->id2.idtype = IDMAP_NONE;
18935e0794bcSbaban 		res = &result->ids.ids_val[i];
18945e0794bcSbaban 
1895e8c27ec8Sbaban 		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
1896e8c27ec8Sbaban 			/* Entry that wasn't marked for AD lookup - skip */
1897e8c27ec8Sbaban 			continue;
1898e8c27ec8Sbaban 
1899e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS) {
1900e8c27ec8Sbaban 			res->retcode = retcode;
1901e8c27ec8Sbaban 			continue;
1902e8c27ec8Sbaban 		}
1903e8c27ec8Sbaban 
1904e8c27ec8Sbaban 		if (!add)
1905e8c27ec8Sbaban 			continue;
1906e8c27ec8Sbaban 
1907e8c27ec8Sbaban 
1908e8c27ec8Sbaban 		if (IS_REQUEST_SID(*req, 1)) {
1909e8c27ec8Sbaban 			if (res->retcode != IDMAP_SUCCESS)
1910e8c27ec8Sbaban 				continue;
1911e8c27ec8Sbaban 			switch (type) {
1912e8c27ec8Sbaban 			case _IDMAP_T_USER:
1913e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
1914e8c27ec8Sbaban 					res->id.idtype = IDMAP_UID;
1915e8c27ec8Sbaban 				req->id1.idtype = IDMAP_USID;
1916e8c27ec8Sbaban 				break;
1917e8c27ec8Sbaban 			case _IDMAP_T_GROUP:
1918e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
1919e8c27ec8Sbaban 					res->id.idtype = IDMAP_GID;
1920e8c27ec8Sbaban 				req->id1.idtype = IDMAP_GSID;
1921e8c27ec8Sbaban 				break;
1922e8c27ec8Sbaban 			default:
1923e8c27ec8Sbaban 				res->retcode = IDMAP_ERR_SID;
1924e8c27ec8Sbaban 				break;
1925e8c27ec8Sbaban 			}
1926e8c27ec8Sbaban 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
1927e8c27ec8Sbaban 			if (res->retcode != IDMAP_SUCCESS) {
1928e8c27ec8Sbaban 				if ((!(IDMAP_FATAL_ERROR(res->retcode))) &&
1929e8c27ec8Sbaban 				    res->id.idmap_id_u.sid.prefix == NULL &&
1930e8c27ec8Sbaban 				    req->id2name == NULL && /* no winname */
1931e8c27ec8Sbaban 				    req->id1name != NULL) /* unixname */
1932e8c27ec8Sbaban 					/*
1933e8c27ec8Sbaban 					 * Here we have a pid2sid request
1934e8c27ec8Sbaban 					 * that was marked for AD lookup
1935e8c27ec8Sbaban 					 * with no SID, no winname but with
1936e8c27ec8Sbaban 					 * unixname. This request was
1937e8c27ec8Sbaban 					 * added to the batch to do AD lookup
1938e8c27ec8Sbaban 					 * by unixname but it failed with non
1939e8c27ec8Sbaban 					 * fatal error. In such case we
1940e8c27ec8Sbaban 					 * ignore the error (i.e set
1941e8c27ec8Sbaban 					 * res->retcode to success) so that
1942e8c27ec8Sbaban 					 * next pass considers it for name
1943e8c27ec8Sbaban 					 * based mapping rules or ephemeral
1944e8c27ec8Sbaban 					 * mapping.
1945e8c27ec8Sbaban 					 */
1946e8c27ec8Sbaban 					res->retcode = IDMAP_SUCCESS;
1947e8c27ec8Sbaban 				continue;
1948e8c27ec8Sbaban 			}
1949e8c27ec8Sbaban 			switch (type) {
1950e8c27ec8Sbaban 			case _IDMAP_T_USER:
1951e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_SID)
1952e8c27ec8Sbaban 					res->id.idtype = IDMAP_USID;
1953e8c27ec8Sbaban 				break;
1954e8c27ec8Sbaban 			case _IDMAP_T_GROUP:
1955e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_SID)
1956e8c27ec8Sbaban 					res->id.idtype = IDMAP_GSID;
1957e8c27ec8Sbaban 				break;
1958e8c27ec8Sbaban 			default:
1959e8c27ec8Sbaban 				res->retcode = IDMAP_ERR_SID;
1960e8c27ec8Sbaban 				break;
1961e8c27ec8Sbaban 			}
1962e8c27ec8Sbaban 		}
1963e8c27ec8Sbaban 	}
1964e8c27ec8Sbaban 
1965e8c27ec8Sbaban 	/* AD lookups done. Reset state->ad_nqueries and return */
1966e8c27ec8Sbaban 	state->ad_nqueries = 0;
1967c5c4113dSnw141292 	return (retcode);
1968c5c4113dSnw141292 }
1969c5c4113dSnw141292 
1970cd37da74Snw141292 /*
1971cd37da74Snw141292  * Convention when processing win2unix requests:
1972cd37da74Snw141292  *
1973cd37da74Snw141292  * Windows identity:
1974cd37da74Snw141292  * req->id1name =
1975cd37da74Snw141292  *              winname if given otherwise winname found will be placed
1976cd37da74Snw141292  *              here.
1977cd37da74Snw141292  * req->id1domain =
1978cd37da74Snw141292  *              windomain if given otherwise windomain found will be
1979cd37da74Snw141292  *              placed here.
1980cd37da74Snw141292  * req->id1.idtype =
1981cd37da74Snw141292  *              Either IDMAP_SID/USID/GSID. If this is IDMAP_SID then it'll
1982cd37da74Snw141292  *              be set to IDMAP_USID/GSID depending upon whether the
1983cd37da74Snw141292  *              given SID is user or group respectively. The user/group-ness
1984cd37da74Snw141292  *              is determined either when looking up well-known SIDs table OR
1985cd37da74Snw141292  *              if the SID is found in namecache OR by ad_lookup() OR by
1986cd37da74Snw141292  *              ad_lookup_batch().
1987cd37da74Snw141292  * req->id1..sid.[prefix, rid] =
1988cd37da74Snw141292  *              SID if given otherwise SID found will be placed here.
1989cd37da74Snw141292  *
1990cd37da74Snw141292  * Unix identity:
1991cd37da74Snw141292  * req->id2name =
1992cd37da74Snw141292  *              unixname found will be placed here.
1993cd37da74Snw141292  * req->id2domain =
1994cd37da74Snw141292  *              NOT USED
1995cd37da74Snw141292  * res->id.idtype =
1996cd37da74Snw141292  *              Target type initialized from req->id2.idtype. If
1997cd37da74Snw141292  *              it is IDMAP_POSIXID then actual type (IDMAP_UID/GID) found
1998cd37da74Snw141292  *              will be placed here.
1999cd37da74Snw141292  * res->id..[uid or gid] =
2000cd37da74Snw141292  *              UID/GID found will be placed here.
2001cd37da74Snw141292  *
2002cd37da74Snw141292  * Others:
2003cd37da74Snw141292  * res->retcode =
2004cd37da74Snw141292  *              Return status for this request will be placed here.
2005cd37da74Snw141292  * res->direction =
2006cd37da74Snw141292  *              Direction found will be placed here. Direction
2007cd37da74Snw141292  *              meaning whether the resultant mapping is valid
2008cd37da74Snw141292  *              only from win2unix or bi-directional.
2009cd37da74Snw141292  * req->direction =
2010cd37da74Snw141292  *              INTERNAL USE. Used by idmapd to set various
2011cd37da74Snw141292  *              flags (_IDMAP_F_xxxx) to aid in processing
2012cd37da74Snw141292  *              of the request.
2013cd37da74Snw141292  * req->id2.idtype =
2014cd37da74Snw141292  *              INTERNAL USE. Initially this is the requested target
2015cd37da74Snw141292  *              type and is used to initialize res->id.idtype.
2016cd37da74Snw141292  *              ad_lookup_batch() uses this field temporarily to store
2017cd37da74Snw141292  *              sid_type obtained by the batched AD lookups and after
2018cd37da74Snw141292  *              use resets it to IDMAP_NONE to prevent xdr from
2019cd37da74Snw141292  *              mis-interpreting the contents of req->id2.
2020cd37da74Snw141292  * req->id2..[uid or gid or sid] =
2021cd37da74Snw141292  *              NOT USED
2022cd37da74Snw141292  */
2023cd37da74Snw141292 
2024cd37da74Snw141292 /*
2025cd37da74Snw141292  * This function does the following:
2026cd37da74Snw141292  * 1. Lookup well-known SIDs table.
2027cd37da74Snw141292  * 2. Check if the given SID is a local-SID and if so extract UID/GID from it.
2028cd37da74Snw141292  * 3. Lookup cache.
2029cd37da74Snw141292  * 4. Check if the client does not want new mapping to be allocated
2030cd37da74Snw141292  *    in which case this pass is the final pass.
2031cd37da74Snw141292  * 5. Set AD lookup flag if it determines that the next stage needs
2032cd37da74Snw141292  *    to do AD lookup.
2033cd37da74Snw141292  */
2034c5c4113dSnw141292 idmap_retcode
2035c5c4113dSnw141292 sid2pid_first_pass(lookup_state_t *state, sqlite *cache, idmap_mapping *req,
2036cd37da74Snw141292 		idmap_id_res *res)
2037cd37da74Snw141292 {
2038c5c4113dSnw141292 	idmap_retcode	retcode;
2039e8c27ec8Sbaban 	int		wksid;
2040c5c4113dSnw141292 
2041e8c27ec8Sbaban 	/* Initialize result */
2042e8c27ec8Sbaban 	res->id.idtype = req->id2.idtype;
2043e8c27ec8Sbaban 	res->id.idmap_id_u.uid = SENTINEL_PID;
2044e8c27ec8Sbaban 	res->direction = IDMAP_DIRECTION_UNDEF;
2045e8c27ec8Sbaban 	wksid = 0;
2046c5c4113dSnw141292 
2047cf5b5989Sdm199847 	if (EMPTY_STRING(req->id1.idmap_id_u.sid.prefix)) {
2048e8c27ec8Sbaban 		if (req->id1name == NULL) {
2049e8c27ec8Sbaban 			retcode = IDMAP_ERR_ARG;
2050c5c4113dSnw141292 			goto out;
2051c5c4113dSnw141292 		}
2052e8c27ec8Sbaban 		/* sanitize sidprefix */
2053e8c27ec8Sbaban 		free(req->id1.idmap_id_u.sid.prefix);
2054e8c27ec8Sbaban 		req->id1.idmap_id_u.sid.prefix = NULL;
2055e8c27ec8Sbaban 	}
2056c5c4113dSnw141292 
2057e8c27ec8Sbaban 	/* Lookup well-known SIDs table */
2058e8c27ec8Sbaban 	retcode = lookup_wksids_sid2pid(req, res, &wksid);
2059c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
2060c5c4113dSnw141292 		goto out;
2061c5c4113dSnw141292 
2062e8c27ec8Sbaban 	/* Check if this is a localsid */
2063e8c27ec8Sbaban 	if (!wksid) {
2064e8c27ec8Sbaban 		retcode = lookup_localsid2pid(req, res);
2065e8c27ec8Sbaban 		if (retcode != IDMAP_ERR_NOTFOUND)
2066e8c27ec8Sbaban 			goto out;
2067e8c27ec8Sbaban 	}
2068e8c27ec8Sbaban 
2069e8c27ec8Sbaban 	/* Lookup cache */
2070c5c4113dSnw141292 	retcode = lookup_cache_sid2pid(cache, req, res);
2071c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
2072c5c4113dSnw141292 		goto out;
2073c5c4113dSnw141292 
2074c5c4113dSnw141292 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req) || AVOID_NAMESERVICE(req)) {
2075e8c27ec8Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
2076c5c4113dSnw141292 		goto out;
2077c5c4113dSnw141292 	}
2078c5c4113dSnw141292 
2079c5c4113dSnw141292 	/*
2080e8c27ec8Sbaban 	 * Failed to find non-expired entry in cache. Next step is
2081e8c27ec8Sbaban 	 * to determine if this request needs to be batched for AD lookup.
2082e8c27ec8Sbaban 	 *
2083e8c27ec8Sbaban 	 * At this point we have either sid or winname or both. If we don't
2084e8c27ec8Sbaban 	 * have both then lookup name_cache for the sid or winname
2085e8c27ec8Sbaban 	 * whichever is missing. If not found then this request will be
2086e8c27ec8Sbaban 	 * batched for AD lookup.
2087e8c27ec8Sbaban 	 */
2088e8c27ec8Sbaban 	retcode = lookup_name_cache(cache, req, res);
2089e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS && retcode != IDMAP_ERR_NOTFOUND)
2090e8c27ec8Sbaban 		goto out;
2091e8c27ec8Sbaban 
2092e8c27ec8Sbaban 	/*
2093e8c27ec8Sbaban 	 * Set the flag to indicate that we are not done yet so that
2094e8c27ec8Sbaban 	 * subsequent passes considers this request for name-based
2095e8c27ec8Sbaban 	 * mapping and ephemeral mapping.
2096c5c4113dSnw141292 	 */
2097c5c4113dSnw141292 	state->sid2pid_done = FALSE;
2098e8c27ec8Sbaban 	req->direction |= _IDMAP_F_NOTDONE;
2099c5c4113dSnw141292 
2100c5c4113dSnw141292 	/*
2101e8c27ec8Sbaban 	 * Even if we have both sid and winname, we still may need to batch
2102e8c27ec8Sbaban 	 * this request for AD lookup if we don't have unixname and
2103e8c27ec8Sbaban 	 * directory-based name mapping (AD or mixed) is enabled.
2104e8c27ec8Sbaban 	 * We avoid AD lookup for well-known SIDs because they don't have
2105e8c27ec8Sbaban 	 * regular AD objects.
2106c5c4113dSnw141292 	 */
2107e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS ||
2108e8c27ec8Sbaban 	    (!wksid && req->id2name == NULL &&
2109e8c27ec8Sbaban 	    AD_OR_MIXED_MODE(res->id.idtype, state))) {
2110c5c4113dSnw141292 		retcode = IDMAP_SUCCESS;
2111e8c27ec8Sbaban 		req->direction |= _IDMAP_F_LOOKUP_AD;
2112c5c4113dSnw141292 		state->ad_nqueries++;
2113c5c4113dSnw141292 	}
2114c5c4113dSnw141292 
2115c5c4113dSnw141292 
2116c5c4113dSnw141292 out:
2117c5c4113dSnw141292 	res->retcode = idmap_stat4prot(retcode);
2118e8c27ec8Sbaban 	/*
2119e8c27ec8Sbaban 	 * If we are done and there was an error then set fallback pid
2120e8c27ec8Sbaban 	 * in the result.
2121e8c27ec8Sbaban 	 */
2122e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
2123e8c27ec8Sbaban 		res->id.idmap_id_u.uid = UID_NOBODY;
2124c5c4113dSnw141292 	return (retcode);
2125c5c4113dSnw141292 }
2126c5c4113dSnw141292 
2127c5c4113dSnw141292 /*
2128c5c4113dSnw141292  * Generate SID using the following convention
2129c5c4113dSnw141292  * 	<machine-sid-prefix>-<1000 + uid>
2130c5c4113dSnw141292  * 	<machine-sid-prefix>-<2^31 + gid>
2131c5c4113dSnw141292  */
2132cd37da74Snw141292 static
2133cd37da74Snw141292 idmap_retcode
2134cd37da74Snw141292 generate_localsid(idmap_mapping *req, idmap_id_res *res, int is_user)
2135cd37da74Snw141292 {
2136e8c27ec8Sbaban 	free(res->id.idmap_id_u.sid.prefix);
2137e8c27ec8Sbaban 	res->id.idmap_id_u.sid.prefix = NULL;
2138e8c27ec8Sbaban 
2139e8c27ec8Sbaban 	/*
2140e8c27ec8Sbaban 	 * Diagonal mapping for localSIDs not supported because of the
2141e8c27ec8Sbaban 	 * way we generate localSIDs.
2142e8c27ec8Sbaban 	 */
2143e8c27ec8Sbaban 	if (is_user && res->id.idtype == IDMAP_GSID)
2144e8c27ec8Sbaban 		return (IDMAP_ERR_NOMAPPING);
2145e8c27ec8Sbaban 	if (!is_user && res->id.idtype == IDMAP_USID)
2146e8c27ec8Sbaban 		return (IDMAP_ERR_NOMAPPING);
2147e8c27ec8Sbaban 
2148c5c4113dSnw141292 	/* Skip 1000 UIDs */
2149c5c4113dSnw141292 	if (is_user && req->id1.idmap_id_u.uid >
2150c5c4113dSnw141292 	    (INT32_MAX - LOCALRID_MIN))
215162c60062Sbaban 		return (IDMAP_ERR_NOMAPPING);
2152c5c4113dSnw141292 
2153c5c4113dSnw141292 	RDLOCK_CONFIG();
2154e8c27ec8Sbaban 	/*
2155e8c27ec8Sbaban 	 * machine_sid is never NULL because if it is we won't be here.
2156e8c27ec8Sbaban 	 * No need to assert because stdrup(NULL) will core anyways.
2157e8c27ec8Sbaban 	 */
2158c5c4113dSnw141292 	res->id.idmap_id_u.sid.prefix =
2159c5c4113dSnw141292 	    strdup(_idmapdstate.cfg->pgcfg.machine_sid);
2160c5c4113dSnw141292 	if (res->id.idmap_id_u.sid.prefix == NULL) {
2161c5c4113dSnw141292 		UNLOCK_CONFIG();
2162c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2163c5c4113dSnw141292 		return (IDMAP_ERR_MEMORY);
2164c5c4113dSnw141292 	}
2165c5c4113dSnw141292 	UNLOCK_CONFIG();
2166c5c4113dSnw141292 	res->id.idmap_id_u.sid.rid =
2167c5c4113dSnw141292 	    (is_user) ? req->id1.idmap_id_u.uid + LOCALRID_MIN :
2168c5c4113dSnw141292 	    req->id1.idmap_id_u.gid + INT32_MAX + 1;
2169651c0131Sbaban 	res->direction = IDMAP_DIRECTION_BI;
2170e8c27ec8Sbaban 	if (res->id.idtype == IDMAP_SID)
2171e8c27ec8Sbaban 		res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
2172c5c4113dSnw141292 
2173c5c4113dSnw141292 	/*
2174c5c4113dSnw141292 	 * Don't update name_cache because local sids don't have
2175c5c4113dSnw141292 	 * valid windows names.
2176c5c4113dSnw141292 	 */
2177e8c27ec8Sbaban 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
2178947c7bc0Sbaban 	return (IDMAP_SUCCESS);
2179c5c4113dSnw141292 }
2180c5c4113dSnw141292 
2181cd37da74Snw141292 static
2182cd37da74Snw141292 idmap_retcode
2183cd37da74Snw141292 lookup_localsid2pid(idmap_mapping *req, idmap_id_res *res)
2184cd37da74Snw141292 {
2185c5c4113dSnw141292 	char		*sidprefix;
2186c5c4113dSnw141292 	uint32_t	rid;
2187c5c4113dSnw141292 	int		s;
2188c5c4113dSnw141292 
2189c5c4113dSnw141292 	/*
2190c5c4113dSnw141292 	 * If the sidprefix == localsid then UID = last RID - 1000 or
2191c5c4113dSnw141292 	 * GID = last RID - 2^31.
2192c5c4113dSnw141292 	 */
2193e8c27ec8Sbaban 	if ((sidprefix = req->id1.idmap_id_u.sid.prefix) == NULL)
2194e8c27ec8Sbaban 		/* This means we are looking up by winname */
2195e8c27ec8Sbaban 		return (IDMAP_ERR_NOTFOUND);
2196c5c4113dSnw141292 	rid = req->id1.idmap_id_u.sid.rid;
2197c5c4113dSnw141292 
2198c5c4113dSnw141292 	RDLOCK_CONFIG();
2199c5c4113dSnw141292 	s = (_idmapdstate.cfg->pgcfg.machine_sid) ?
2200cd37da74Snw141292 	    strcasecmp(sidprefix, _idmapdstate.cfg->pgcfg.machine_sid) : 1;
2201c5c4113dSnw141292 	UNLOCK_CONFIG();
2202c5c4113dSnw141292 
2203e8c27ec8Sbaban 	/*
2204e8c27ec8Sbaban 	 * If the given sidprefix does not match machine_sid then this is
2205e8c27ec8Sbaban 	 * not a local SID.
2206e8c27ec8Sbaban 	 */
2207e8c27ec8Sbaban 	if (s != 0)
2208e8c27ec8Sbaban 		return (IDMAP_ERR_NOTFOUND);
2209e8c27ec8Sbaban 
2210e8c27ec8Sbaban 	switch (res->id.idtype) {
2211c5c4113dSnw141292 	case IDMAP_UID:
2212e8c27ec8Sbaban 		if (rid > INT32_MAX || rid < LOCALRID_MIN)
2213e8c27ec8Sbaban 			return (IDMAP_ERR_ARG);
2214c5c4113dSnw141292 		res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
2215c5c4113dSnw141292 		break;
2216c5c4113dSnw141292 	case IDMAP_GID:
2217e8c27ec8Sbaban 		if (rid <= INT32_MAX)
2218e8c27ec8Sbaban 			return (IDMAP_ERR_ARG);
2219c5c4113dSnw141292 		res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
2220c5c4113dSnw141292 		break;
2221c5c4113dSnw141292 	case IDMAP_POSIXID:
2222c5c4113dSnw141292 		if (rid > INT32_MAX) {
2223cd37da74Snw141292 			res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
2224c5c4113dSnw141292 			res->id.idtype = IDMAP_GID;
2225c5c4113dSnw141292 		} else if (rid < LOCALRID_MIN) {
2226e8c27ec8Sbaban 			return (IDMAP_ERR_ARG);
2227c5c4113dSnw141292 		} else {
2228c5c4113dSnw141292 			res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
2229c5c4113dSnw141292 			res->id.idtype = IDMAP_UID;
2230c5c4113dSnw141292 		}
2231c5c4113dSnw141292 		break;
2232c5c4113dSnw141292 	default:
2233c5c4113dSnw141292 		return (IDMAP_ERR_NOTSUPPORTED);
2234c5c4113dSnw141292 	}
2235c5c4113dSnw141292 	return (IDMAP_SUCCESS);
2236c5c4113dSnw141292 }
2237c5c4113dSnw141292 
2238e8c27ec8Sbaban /*
2239e8c27ec8Sbaban  * Name service lookup by unixname to get pid
2240e8c27ec8Sbaban  */
2241cd37da74Snw141292 static
2242cd37da74Snw141292 idmap_retcode
2243e8c27ec8Sbaban ns_lookup_byname(const char *name, const char *lower_name, idmap_id *id)
2244cd37da74Snw141292 {
2245cd37da74Snw141292 	struct passwd	pwd, *pwdp;
2246cd37da74Snw141292 	struct group	grp, *grpp;
2247c5c4113dSnw141292 	char		buf[1024];
2248c5c4113dSnw141292 	int		errnum;
2249c5c4113dSnw141292 	const char	*me = "ns_lookup_byname";
2250c5c4113dSnw141292 
2251e8c27ec8Sbaban 	switch (id->idtype) {
2252e8c27ec8Sbaban 	case IDMAP_UID:
2253cd37da74Snw141292 		pwdp = getpwnam_r(name, &pwd, buf, sizeof (buf));
2254e8c27ec8Sbaban 		if (pwdp == NULL && errno == 0 && lower_name != NULL &&
2255cd37da74Snw141292 		    name != lower_name && strcmp(name, lower_name) != 0)
2256cd37da74Snw141292 			pwdp = getpwnam_r(lower_name, &pwd, buf, sizeof (buf));
2257cd37da74Snw141292 		if (pwdp == NULL) {
2258c5c4113dSnw141292 			errnum = errno;
2259c5c4113dSnw141292 			idmapdlog(LOG_WARNING,
2260c5c4113dSnw141292 			    "%s: getpwnam_r(%s) failed (%s).",
2261cd37da74Snw141292 			    me, name, errnum ? strerror(errnum) : "not found");
2262c5c4113dSnw141292 			if (errnum == 0)
2263c5c4113dSnw141292 				return (IDMAP_ERR_NOTFOUND);
2264c5c4113dSnw141292 			else
2265c5c4113dSnw141292 				return (IDMAP_ERR_INTERNAL);
2266c5c4113dSnw141292 		}
2267e8c27ec8Sbaban 		id->idmap_id_u.uid = pwd.pw_uid;
2268e8c27ec8Sbaban 		break;
2269e8c27ec8Sbaban 	case IDMAP_GID:
2270cd37da74Snw141292 		grpp = getgrnam_r(name, &grp, buf, sizeof (buf));
2271e8c27ec8Sbaban 		if (grpp == NULL && errno == 0 && lower_name != NULL &&
2272cd37da74Snw141292 		    name != lower_name && strcmp(name, lower_name) != 0)
2273cd37da74Snw141292 			grpp = getgrnam_r(lower_name, &grp, buf, sizeof (buf));
2274cd37da74Snw141292 		if (grpp == NULL) {
2275c5c4113dSnw141292 			errnum = errno;
2276c5c4113dSnw141292 			idmapdlog(LOG_WARNING,
2277c5c4113dSnw141292 			    "%s: getgrnam_r(%s) failed (%s).",
2278cd37da74Snw141292 			    me, name, errnum ? strerror(errnum) : "not found");
2279c5c4113dSnw141292 			if (errnum == 0)
2280c5c4113dSnw141292 				return (IDMAP_ERR_NOTFOUND);
2281c5c4113dSnw141292 			else
2282c5c4113dSnw141292 				return (IDMAP_ERR_INTERNAL);
2283c5c4113dSnw141292 		}
2284e8c27ec8Sbaban 		id->idmap_id_u.gid = grp.gr_gid;
2285e8c27ec8Sbaban 		break;
2286e8c27ec8Sbaban 	default:
2287e8c27ec8Sbaban 		return (IDMAP_ERR_ARG);
2288c5c4113dSnw141292 	}
2289c5c4113dSnw141292 	return (IDMAP_SUCCESS);
2290c5c4113dSnw141292 }
2291c5c4113dSnw141292 
2292e8c27ec8Sbaban 
2293e8c27ec8Sbaban /*
2294e8c27ec8Sbaban  * Name service lookup by pid to get unixname
2295e8c27ec8Sbaban  */
2296e8c27ec8Sbaban static
2297e8c27ec8Sbaban idmap_retcode
2298e8c27ec8Sbaban ns_lookup_bypid(uid_t pid, int is_user, char **unixname)
2299e8c27ec8Sbaban {
2300e8c27ec8Sbaban 	struct passwd	pwd;
2301e8c27ec8Sbaban 	struct group	grp;
2302e8c27ec8Sbaban 	char		buf[1024];
2303e8c27ec8Sbaban 	int		errnum;
2304e8c27ec8Sbaban 	const char	*me = "ns_lookup_bypid";
2305e8c27ec8Sbaban 
2306e8c27ec8Sbaban 	if (is_user) {
2307e8c27ec8Sbaban 		errno = 0;
2308e8c27ec8Sbaban 		if (getpwuid_r(pid, &pwd, buf, sizeof (buf)) == NULL) {
2309e8c27ec8Sbaban 			errnum = errno;
2310e8c27ec8Sbaban 			idmapdlog(LOG_WARNING,
2311e8c27ec8Sbaban 			    "%s: getpwuid_r(%u) failed (%s).",
2312e8c27ec8Sbaban 			    me, pid, errnum ? strerror(errnum) : "not found");
2313e8c27ec8Sbaban 			if (errnum == 0)
2314e8c27ec8Sbaban 				return (IDMAP_ERR_NOTFOUND);
2315e8c27ec8Sbaban 			else
2316e8c27ec8Sbaban 				return (IDMAP_ERR_INTERNAL);
2317e8c27ec8Sbaban 		}
2318e8c27ec8Sbaban 		*unixname = strdup(pwd.pw_name);
2319e8c27ec8Sbaban 	} else {
2320e8c27ec8Sbaban 		errno = 0;
2321e8c27ec8Sbaban 		if (getgrgid_r(pid, &grp, buf, sizeof (buf)) == NULL) {
2322e8c27ec8Sbaban 			errnum = errno;
2323e8c27ec8Sbaban 			idmapdlog(LOG_WARNING,
2324e8c27ec8Sbaban 			    "%s: getgrgid_r(%u) failed (%s).",
2325e8c27ec8Sbaban 			    me, pid, errnum ? strerror(errnum) : "not found");
2326e8c27ec8Sbaban 			if (errnum == 0)
2327e8c27ec8Sbaban 				return (IDMAP_ERR_NOTFOUND);
2328e8c27ec8Sbaban 			else
2329e8c27ec8Sbaban 				return (IDMAP_ERR_INTERNAL);
2330e8c27ec8Sbaban 		}
2331e8c27ec8Sbaban 		*unixname = strdup(grp.gr_name);
2332e8c27ec8Sbaban 	}
2333e8c27ec8Sbaban 	if (*unixname == NULL)
2334e8c27ec8Sbaban 		return (IDMAP_ERR_MEMORY);
2335e8c27ec8Sbaban 	return (IDMAP_SUCCESS);
2336e8c27ec8Sbaban }
2337e8c27ec8Sbaban 
2338c5c4113dSnw141292 /*
2339c5c4113dSnw141292  * Name-based mapping
2340c5c4113dSnw141292  *
2341c5c4113dSnw141292  * Case 1: If no rule matches do ephemeral
2342c5c4113dSnw141292  *
2343c5c4113dSnw141292  * Case 2: If rule matches and unixname is "" then return no mapping.
2344c5c4113dSnw141292  *
2345c5c4113dSnw141292  * Case 3: If rule matches and unixname is specified then lookup name
2346c5c4113dSnw141292  *  service using the unixname. If unixname not found then return no mapping.
2347c5c4113dSnw141292  *
2348c5c4113dSnw141292  * Case 4: If rule matches and unixname is * then lookup name service
2349c5c4113dSnw141292  *  using winname as the unixname. If unixname not found then process
2350c5c4113dSnw141292  *  other rules using the lookup order. If no other rule matches then do
2351c5c4113dSnw141292  *  ephemeral. Otherwise, based on the matched rule do Case 2 or 3 or 4.
2352c5c4113dSnw141292  *  This allows us to specify a fallback unixname per _domain_ or no mapping
2353c5c4113dSnw141292  *  instead of the default behaviour of doing ephemeral mapping.
2354c5c4113dSnw141292  *
2355c5c4113dSnw141292  * Example 1:
2356c5c4113dSnw141292  * *@sfbay == *
2357c5c4113dSnw141292  * If looking up windows users foo@sfbay and foo does not exists in
2358c5c4113dSnw141292  * the name service then foo@sfbay will be mapped to an ephemeral id.
2359c5c4113dSnw141292  *
2360c5c4113dSnw141292  * Example 2:
2361c5c4113dSnw141292  * *@sfbay == *
2362c5c4113dSnw141292  * *@sfbay => guest
2363c5c4113dSnw141292  * If looking up windows users foo@sfbay and foo does not exists in
2364c5c4113dSnw141292  * the name service then foo@sfbay will be mapped to guest.
2365c5c4113dSnw141292  *
2366c5c4113dSnw141292  * Example 3:
2367c5c4113dSnw141292  * *@sfbay == *
2368c5c4113dSnw141292  * *@sfbay => ""
2369c5c4113dSnw141292  * If looking up windows users foo@sfbay and foo does not exists in
2370c5c4113dSnw141292  * the name service then we will return no mapping for foo@sfbay.
2371c5c4113dSnw141292  *
2372c5c4113dSnw141292  */
2373cd37da74Snw141292 static
2374cd37da74Snw141292 idmap_retcode
2375cd37da74Snw141292 name_based_mapping_sid2pid(sqlite *db, idmap_mapping *req, idmap_id_res *res)
2376cd37da74Snw141292 {
2377cd37da74Snw141292 	const char	*unixname, *windomain;
2378cd37da74Snw141292 	char		*sql = NULL, *errmsg = NULL, *lower_winname = NULL;
2379c5c4113dSnw141292 	idmap_retcode	retcode;
2380cd37da74Snw141292 	char		*end, *lower_unixname, *winname;
2381c5c4113dSnw141292 	const char	**values;
2382c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
2383cd37da74Snw141292 	int		ncol, r, i, is_user, is_wuser;
2384c5c4113dSnw141292 	const char	*me = "name_based_mapping_sid2pid";
2385c5c4113dSnw141292 
2386e8c27ec8Sbaban 	assert(req->id1name != NULL); /* We have winname */
2387e8c27ec8Sbaban 	assert(req->id2name == NULL); /* We don't have unixname */
2388e8c27ec8Sbaban 
23898e228215Sdm199847 	winname = req->id1name;
23908e228215Sdm199847 	windomain = req->id1domain;
2391cd37da74Snw141292 
2392cd37da74Snw141292 	switch (req->id1.idtype) {
2393cd37da74Snw141292 	case IDMAP_USID:
2394cd37da74Snw141292 		is_wuser = 1;
2395cd37da74Snw141292 		break;
2396cd37da74Snw141292 	case IDMAP_GSID:
2397cd37da74Snw141292 		is_wuser = 0;
2398cd37da74Snw141292 		break;
2399cd37da74Snw141292 	default:
2400e8c27ec8Sbaban 		idmapdlog(LOG_ERR, "%s: Unable to determine if the "
2401e8c27ec8Sbaban 		    "given Windows id is user or group.", me);
2402cd37da74Snw141292 		return (IDMAP_ERR_INTERNAL);
2403cd37da74Snw141292 	}
2404cd37da74Snw141292 
2405e8c27ec8Sbaban 	switch (res->id.idtype) {
2406cd37da74Snw141292 	case IDMAP_UID:
2407cd37da74Snw141292 		is_user = 1;
2408cd37da74Snw141292 		break;
2409cd37da74Snw141292 	case IDMAP_GID:
2410cd37da74Snw141292 		is_user = 0;
2411cd37da74Snw141292 		break;
2412cd37da74Snw141292 	case IDMAP_POSIXID:
2413cd37da74Snw141292 		is_user = is_wuser;
2414cd37da74Snw141292 		res->id.idtype = is_user ? IDMAP_UID : IDMAP_GID;
2415cd37da74Snw141292 		break;
2416cd37da74Snw141292 	}
2417c5c4113dSnw141292 
2418c5c4113dSnw141292 	i = 0;
241962c60062Sbaban 	if (windomain == NULL) {
242062c60062Sbaban 		windomain = "";
242162c60062Sbaban 	} else {
242262c60062Sbaban 		RDLOCK_CONFIG();
2423c8e26105Sjp151216 		if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
2424c8e26105Sjp151216 			if (strcasecmp(_idmapdstate.cfg->pgcfg.default_domain,
2425c5c4113dSnw141292 			    windomain) == 0)
2426c5c4113dSnw141292 				i = 1;
2427c5c4113dSnw141292 		}
2428c5c4113dSnw141292 		UNLOCK_CONFIG();
242962c60062Sbaban 	}
2430c5c4113dSnw141292 
2431cd37da74Snw141292 	if ((lower_winname = tolower_u8(winname)) == NULL)
2432cd37da74Snw141292 		lower_winname = winname;    /* hope for the best */
2433c5c4113dSnw141292 	sql = sqlite_mprintf(
2434c5c4113dSnw141292 	    "SELECT unixname, u2w_order FROM namerules WHERE "
2435cd37da74Snw141292 	    "w2u_order > 0 AND is_user = %d AND is_wuser = %d AND "
2436c5c4113dSnw141292 	    "(winname = %Q OR winname = '*') AND "
2437c5c4113dSnw141292 	    "(windomain = %Q OR windomain = '*' %s) "
2438c5c4113dSnw141292 	    "ORDER BY w2u_order ASC;",
2439cd37da74Snw141292 	    is_user, is_wuser, lower_winname, windomain,
244062c60062Sbaban 	    i ? "OR windomain ISNULL OR windomain = ''" : "");
2441c5c4113dSnw141292 	if (sql == NULL) {
2442c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2443c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
2444c5c4113dSnw141292 		goto out;
2445c5c4113dSnw141292 	}
2446c5c4113dSnw141292 
2447c5c4113dSnw141292 	if (sqlite_compile(db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
2448c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
2449cd37da74Snw141292 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
2450cd37da74Snw141292 		    CHECK_NULL(errmsg));
2451c5c4113dSnw141292 		sqlite_freemem(errmsg);
2452c5c4113dSnw141292 		goto out;
2453c5c4113dSnw141292 	}
2454c5c4113dSnw141292 
245584decf41Sjp151216 	for (; ; ) {
2456c5c4113dSnw141292 		r = sqlite_step(vm, &ncol, &values, NULL);
245784decf41Sjp151216 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
2458c5c4113dSnw141292 
245984decf41Sjp151216 		if (r == SQLITE_ROW) {
2460c5c4113dSnw141292 			if (ncol < 2) {
2461c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
2462c5c4113dSnw141292 				goto out;
2463c5c4113dSnw141292 			}
2464c5c4113dSnw141292 			if (values[0] == NULL) {
2465c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
2466c5c4113dSnw141292 				goto out;
2467c5c4113dSnw141292 			}
2468c5c4113dSnw141292 
2469c5c4113dSnw141292 			if (EMPTY_NAME(values[0])) {
2470c5c4113dSnw141292 				retcode = IDMAP_ERR_NOMAPPING;
2471c5c4113dSnw141292 				goto out;
2472c5c4113dSnw141292 			}
2473c5c4113dSnw141292 			unixname = (values[0][0] == '*') ? winname : values[0];
2474cd37da74Snw141292 			lower_unixname = (values[0][0] == '*') ?
2475cd37da74Snw141292 			    lower_winname : NULL;
2476e8c27ec8Sbaban 			retcode = ns_lookup_byname(unixname, lower_unixname,
2477e8c27ec8Sbaban 			    &res->id);
2478c5c4113dSnw141292 			if (retcode == IDMAP_ERR_NOTFOUND) {
2479c5c4113dSnw141292 				if (unixname == winname)
2480c5c4113dSnw141292 					/* Case 4 */
2481c5c4113dSnw141292 					continue;
2482c5c4113dSnw141292 				else
2483c5c4113dSnw141292 					/* Case 3 */
2484c5c4113dSnw141292 					retcode = IDMAP_ERR_NOMAPPING;
2485c5c4113dSnw141292 			}
2486c5c4113dSnw141292 			goto out;
2487c5c4113dSnw141292 		} else if (r == SQLITE_DONE) {
2488c5c4113dSnw141292 			retcode = IDMAP_ERR_NOTFOUND;
2489c5c4113dSnw141292 			goto out;
2490c5c4113dSnw141292 		} else {
2491c5c4113dSnw141292 			(void) sqlite_finalize(vm, &errmsg);
2492c5c4113dSnw141292 			vm = NULL;
2493cd37da74Snw141292 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
2494cd37da74Snw141292 			    CHECK_NULL(errmsg));
2495c5c4113dSnw141292 			sqlite_freemem(errmsg);
2496c5c4113dSnw141292 			retcode = IDMAP_ERR_INTERNAL;
2497c5c4113dSnw141292 			goto out;
2498c5c4113dSnw141292 		}
2499c5c4113dSnw141292 	}
2500c5c4113dSnw141292 
2501c5c4113dSnw141292 out:
2502c5c4113dSnw141292 	sqlite_freemem(sql);
2503c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
250462c60062Sbaban 		if (values[1] != NULL)
2505c5c4113dSnw141292 			res->direction =
2506651c0131Sbaban 			    (strtol(values[1], &end, 10) == 0)?
2507651c0131Sbaban 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
2508c5c4113dSnw141292 		else
2509651c0131Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
25108e228215Sdm199847 		req->id2name = strdup(unixname);
2511c5c4113dSnw141292 	}
2512cd37da74Snw141292 	if (lower_winname != NULL && lower_winname != winname)
2513cd37da74Snw141292 		free(lower_winname);
251462c60062Sbaban 	if (vm != NULL)
2515c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
2516c5c4113dSnw141292 	return (retcode);
2517c5c4113dSnw141292 }
2518c5c4113dSnw141292 
2519c5c4113dSnw141292 static
2520c5c4113dSnw141292 int
2521c5c4113dSnw141292 get_next_eph_uid(uid_t *next_uid)
2522c5c4113dSnw141292 {
2523c5c4113dSnw141292 	uid_t uid;
2524c5c4113dSnw141292 	gid_t gid;
2525c5c4113dSnw141292 	int err;
2526c5c4113dSnw141292 
2527c5c4113dSnw141292 	*next_uid = (uid_t)-1;
2528c5c4113dSnw141292 	uid = _idmapdstate.next_uid++;
2529c5c4113dSnw141292 	if (uid >= _idmapdstate.limit_uid) {
2530c5c4113dSnw141292 		if ((err = allocids(0, 8192, &uid, 0, &gid)) != 0)
2531c5c4113dSnw141292 			return (err);
2532c5c4113dSnw141292 
2533c5c4113dSnw141292 		_idmapdstate.limit_uid = uid + 8192;
2534c5c4113dSnw141292 		_idmapdstate.next_uid = uid;
2535c5c4113dSnw141292 	}
2536c5c4113dSnw141292 	*next_uid = uid;
2537c5c4113dSnw141292 
2538c5c4113dSnw141292 	return (0);
2539c5c4113dSnw141292 }
2540c5c4113dSnw141292 
2541c5c4113dSnw141292 static
2542c5c4113dSnw141292 int
2543c5c4113dSnw141292 get_next_eph_gid(gid_t *next_gid)
2544c5c4113dSnw141292 {
2545c5c4113dSnw141292 	uid_t uid;
2546c5c4113dSnw141292 	gid_t gid;
2547c5c4113dSnw141292 	int err;
2548c5c4113dSnw141292 
2549c5c4113dSnw141292 	*next_gid = (uid_t)-1;
2550c5c4113dSnw141292 	gid = _idmapdstate.next_gid++;
2551c5c4113dSnw141292 	if (gid >= _idmapdstate.limit_gid) {
2552c5c4113dSnw141292 		if ((err = allocids(0, 0, &uid, 8192, &gid)) != 0)
2553c5c4113dSnw141292 			return (err);
2554c5c4113dSnw141292 
2555c5c4113dSnw141292 		_idmapdstate.limit_gid = gid + 8192;
2556c5c4113dSnw141292 		_idmapdstate.next_gid = gid;
2557c5c4113dSnw141292 	}
2558c5c4113dSnw141292 	*next_gid = gid;
2559c5c4113dSnw141292 
2560c5c4113dSnw141292 	return (0);
2561c5c4113dSnw141292 }
2562c5c4113dSnw141292 
256362c60062Sbaban static
256462c60062Sbaban int
2565cd37da74Snw141292 gethash(const char *str, uint32_t num, uint_t htsize)
2566cd37da74Snw141292 {
256762c60062Sbaban 	uint_t  hval, i, len;
256862c60062Sbaban 
256962c60062Sbaban 	if (str == NULL)
257062c60062Sbaban 		return (0);
257162c60062Sbaban 	for (len = strlen(str), hval = 0, i = 0; i < len; i++) {
257262c60062Sbaban 		hval += str[i];
257362c60062Sbaban 		hval += (hval << 10);
257462c60062Sbaban 		hval ^= (hval >> 6);
257562c60062Sbaban 	}
257662c60062Sbaban 	for (str = (const char *)&num, i = 0; i < sizeof (num); i++) {
257762c60062Sbaban 		hval += str[i];
257862c60062Sbaban 		hval += (hval << 10);
257962c60062Sbaban 		hval ^= (hval >> 6);
258062c60062Sbaban 	}
258162c60062Sbaban 	hval += (hval << 3);
258262c60062Sbaban 	hval ^= (hval >> 11);
258362c60062Sbaban 	hval += (hval << 15);
258462c60062Sbaban 	return (hval % htsize);
258562c60062Sbaban }
258662c60062Sbaban 
258762c60062Sbaban static
258862c60062Sbaban int
258962c60062Sbaban get_from_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid,
2590cd37da74Snw141292 		uid_t *pid)
2591cd37da74Snw141292 {
259262c60062Sbaban 	uint_t		next, key;
259362c60062Sbaban 	uint_t		htsize = state->sid_history_size;
259462c60062Sbaban 	idmap_sid	*sid;
259562c60062Sbaban 
259662c60062Sbaban 	next = gethash(prefix, rid, htsize);
259762c60062Sbaban 	while (next != htsize) {
259862c60062Sbaban 		key = state->sid_history[next].key;
259962c60062Sbaban 		if (key == htsize)
260062c60062Sbaban 			return (0);
260162c60062Sbaban 		sid = &state->batch->idmap_mapping_batch_val[key].id1.
260262c60062Sbaban 		    idmap_id_u.sid;
260362c60062Sbaban 		if (sid->rid == rid && strcmp(sid->prefix, prefix) == 0) {
260462c60062Sbaban 			*pid = state->result->ids.ids_val[key].id.
260562c60062Sbaban 			    idmap_id_u.uid;
260662c60062Sbaban 			return (1);
260762c60062Sbaban 		}
260862c60062Sbaban 		next = state->sid_history[next].next;
260962c60062Sbaban 	}
261062c60062Sbaban 	return (0);
261162c60062Sbaban }
261262c60062Sbaban 
261362c60062Sbaban static
261462c60062Sbaban void
2615cd37da74Snw141292 add_to_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid)
2616cd37da74Snw141292 {
261762c60062Sbaban 	uint_t		hash, next;
261862c60062Sbaban 	uint_t		htsize = state->sid_history_size;
261962c60062Sbaban 
262062c60062Sbaban 	hash = next = gethash(prefix, rid, htsize);
262162c60062Sbaban 	while (state->sid_history[next].key != htsize) {
262262c60062Sbaban 		next++;
262362c60062Sbaban 		next %= htsize;
262462c60062Sbaban 	}
262562c60062Sbaban 	state->sid_history[next].key = state->curpos;
262662c60062Sbaban 	if (hash == next)
262762c60062Sbaban 		return;
262862c60062Sbaban 	state->sid_history[next].next = state->sid_history[hash].next;
262962c60062Sbaban 	state->sid_history[hash].next = next;
263062c60062Sbaban }
2631c5c4113dSnw141292 
2632e8c27ec8Sbaban void
2633e8c27ec8Sbaban cleanup_lookup_state(lookup_state_t *state)
2634e8c27ec8Sbaban {
2635e8c27ec8Sbaban 	free(state->sid_history);
2636e8c27ec8Sbaban 	free(state->ad_unixuser_attr);
2637e8c27ec8Sbaban 	free(state->ad_unixgroup_attr);
2638e8c27ec8Sbaban }
2639e8c27ec8Sbaban 
2640c5c4113dSnw141292 /* ARGSUSED */
2641c5c4113dSnw141292 static
2642c5c4113dSnw141292 idmap_retcode
264362c60062Sbaban dynamic_ephemeral_mapping(lookup_state_t *state, sqlite *cache,
2644cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
2645cd37da74Snw141292 {
2646c5c4113dSnw141292 
2647c5c4113dSnw141292 	uid_t		next_pid;
2648c5c4113dSnw141292 
2649651c0131Sbaban 	res->direction = IDMAP_DIRECTION_BI;
265062c60062Sbaban 
265162c60062Sbaban 	if (IS_EPHEMERAL(res->id.idmap_id_u.uid))
265262c60062Sbaban 		return (IDMAP_SUCCESS);
265362c60062Sbaban 
265462c60062Sbaban 	if (state->sid_history != NULL &&
265562c60062Sbaban 	    get_from_sid_history(state, req->id1.idmap_id_u.sid.prefix,
265662c60062Sbaban 	    req->id1.idmap_id_u.sid.rid, &next_pid)) {
265762c60062Sbaban 		res->id.idmap_id_u.uid = next_pid;
265862c60062Sbaban 		return (IDMAP_SUCCESS);
265962c60062Sbaban 	}
266062c60062Sbaban 
266162c60062Sbaban 	if (res->id.idtype == IDMAP_UID) {
2662c5c4113dSnw141292 		if (get_next_eph_uid(&next_pid) != 0)
2663c5c4113dSnw141292 			return (IDMAP_ERR_INTERNAL);
2664c5c4113dSnw141292 		res->id.idmap_id_u.uid = next_pid;
2665c5c4113dSnw141292 	} else {
2666c5c4113dSnw141292 		if (get_next_eph_gid(&next_pid) != 0)
2667c5c4113dSnw141292 			return (IDMAP_ERR_INTERNAL);
2668c5c4113dSnw141292 		res->id.idmap_id_u.gid = next_pid;
2669c5c4113dSnw141292 	}
2670c5c4113dSnw141292 
267162c60062Sbaban 	if (state->sid_history != NULL)
267262c60062Sbaban 		add_to_sid_history(state, req->id1.idmap_id_u.sid.prefix,
267362c60062Sbaban 		    req->id1.idmap_id_u.sid.rid);
267462c60062Sbaban 
2675c5c4113dSnw141292 	return (IDMAP_SUCCESS);
2676c5c4113dSnw141292 }
2677c5c4113dSnw141292 
2678c5c4113dSnw141292 idmap_retcode
2679c5c4113dSnw141292 sid2pid_second_pass(lookup_state_t *state, sqlite *cache, sqlite *db,
2680cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
2681cd37da74Snw141292 {
2682c5c4113dSnw141292 	idmap_retcode	retcode;
2683c5c4113dSnw141292 
2684c5c4113dSnw141292 	/* Check if second pass is needed */
2685e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
2686c5c4113dSnw141292 		return (res->retcode);
2687c5c4113dSnw141292 
2688c5c4113dSnw141292 	/* Get status from previous pass */
2689e8c27ec8Sbaban 	retcode = res->retcode;
2690e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
2691e8c27ec8Sbaban 		goto out;
2692c5c4113dSnw141292 
2693e8c27ec8Sbaban 	/*
2694e8c27ec8Sbaban 	 * If directory-based name mapping is enabled then the unixname
2695e8c27ec8Sbaban 	 * may already have been retrieved from the AD object (AD-mode or
2696e8c27ec8Sbaban 	 * mixed-mode) or from native LDAP object (nldap-mode) -- done.
2697e8c27ec8Sbaban 	 */
2698e8c27ec8Sbaban 	if (req->id2name != NULL) {
2699e8c27ec8Sbaban 		assert(res->id.idtype != IDMAP_POSIXID);
2700e8c27ec8Sbaban 		if (AD_MODE(res->id.idtype, state))
2701e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
2702e8c27ec8Sbaban 		else if (NLDAP_MODE(res->id.idtype, state))
2703e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
2704e8c27ec8Sbaban 		else if (MIXED_MODE(res->id.idtype, state))
2705e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
2706c5c4113dSnw141292 
2707e8c27ec8Sbaban 		/*
2708e8c27ec8Sbaban 		 * Special case: (1) If the ad_unixuser_attr and
2709e8c27ec8Sbaban 		 * ad_unixgroup_attr uses the same attribute
2710e8c27ec8Sbaban 		 * name and (2) if this is a diagonal mapping
2711e8c27ec8Sbaban 		 * request and (3) the unixname has been retrieved
2712e8c27ec8Sbaban 		 * from the AD object -- then we ignore it and fallback
2713e8c27ec8Sbaban 		 * to name-based mapping rules and ephemeral mapping
2714e8c27ec8Sbaban 		 *
2715e8c27ec8Sbaban 		 * Example:
2716e8c27ec8Sbaban 		 *  Properties:
2717e8c27ec8Sbaban 		 *    config/ad_unixuser_attr = "unixname"
2718e8c27ec8Sbaban 		 *    config/ad_unixgroup_attr = "unixname"
2719e8c27ec8Sbaban 		 *  AD user object:
2720e8c27ec8Sbaban 		 *    dn: cn=bob ...
2721e8c27ec8Sbaban 		 *    objectclass: user
2722e8c27ec8Sbaban 		 *    sam: bob
2723e8c27ec8Sbaban 		 *    unixname: bob1234
2724e8c27ec8Sbaban 		 *  AD group object:
2725e8c27ec8Sbaban 		 *    dn: cn=winadmins ...
2726e8c27ec8Sbaban 		 *    objectclass: group
2727e8c27ec8Sbaban 		 *    sam: winadmins
2728e8c27ec8Sbaban 		 *    unixname: unixadmins
2729e8c27ec8Sbaban 		 *
2730e8c27ec8Sbaban 		 *  In this example whether "unixname" refers to a unixuser
2731e8c27ec8Sbaban 		 *  or unixgroup depends upon the AD object.
2732e8c27ec8Sbaban 		 *
2733e8c27ec8Sbaban 		 * $idmap show -c winname:bob gid
2734e8c27ec8Sbaban 		 *    AD lookup by "samAccountName=bob" for
2735e8c27ec8Sbaban 		 *    "ad_unixgroup_attr (i.e unixname)" for directory-based
2736e8c27ec8Sbaban 		 *    mapping would get "bob1234" which is not what we want.
2737e8c27ec8Sbaban 		 *    Now why not getgrnam_r("bob1234") and use it if it
2738e8c27ec8Sbaban 		 *    is indeed a unixgroup? That's because Unix can have
2739e8c27ec8Sbaban 		 *    users and groups with the same name and we clearly
2740e8c27ec8Sbaban 		 *    don't know the intention of the admin here.
2741e8c27ec8Sbaban 		 *    Therefore we ignore this and fallback to name-based
2742e8c27ec8Sbaban 		 *    mapping rules or ephemeral mapping.
2743e8c27ec8Sbaban 		 */
2744e8c27ec8Sbaban 		if ((AD_MODE(res->id.idtype, state) ||
2745e8c27ec8Sbaban 		    MIXED_MODE(res->id.idtype, state)) &&
2746e8c27ec8Sbaban 		    state->ad_unixuser_attr != NULL &&
2747e8c27ec8Sbaban 		    state->ad_unixgroup_attr != NULL &&
2748e8c27ec8Sbaban 		    strcasecmp(state->ad_unixuser_attr,
2749e8c27ec8Sbaban 		    state->ad_unixgroup_attr) == 0 &&
2750e8c27ec8Sbaban 		    ((req->id1.idtype == IDMAP_USID &&
2751e8c27ec8Sbaban 		    res->id.idtype == IDMAP_GID) ||
2752e8c27ec8Sbaban 		    (req->id1.idtype == IDMAP_GSID &&
2753e8c27ec8Sbaban 		    res->id.idtype == IDMAP_UID))) {
2754e8c27ec8Sbaban 			free(req->id2name);
2755e8c27ec8Sbaban 			req->id2name = NULL;
2756e8c27ec8Sbaban 			res->id.idmap_id_u.uid = SENTINEL_PID;
2757e8c27ec8Sbaban 			/* fallback */
2758e8c27ec8Sbaban 		} else {
2759e8c27ec8Sbaban 			if (res->id.idmap_id_u.uid == SENTINEL_PID)
2760e8c27ec8Sbaban 				retcode = ns_lookup_byname(req->id2name,
2761e8c27ec8Sbaban 				    NULL, &res->id);
2762e8c27ec8Sbaban 			/*
2763e8c27ec8Sbaban 			 * We don't fallback to name-based mapping rules
2764e8c27ec8Sbaban 			 * or ephemeral mapping.
2765e8c27ec8Sbaban 			 */
2766c5c4113dSnw141292 			goto out;
2767c5c4113dSnw141292 		}
2768e8c27ec8Sbaban 	}
2769c5c4113dSnw141292 
2770e8c27ec8Sbaban 	/*
2771e8c27ec8Sbaban 	 * If we don't have unixname then evaluate local name-based
2772e8c27ec8Sbaban 	 * mapping rules.
2773e8c27ec8Sbaban 	 */
2774c5c4113dSnw141292 	retcode = name_based_mapping_sid2pid(db, req, res);
2775e8c27ec8Sbaban 	if (retcode != IDMAP_ERR_NOTFOUND)
2776e8c27ec8Sbaban 		goto out;
2777e8c27ec8Sbaban 
2778c5c4113dSnw141292 	/* If not found, do ephemeral mapping */
277962c60062Sbaban 	retcode = dynamic_ephemeral_mapping(state, cache, req, res);
2780c5c4113dSnw141292 
2781c5c4113dSnw141292 out:
2782c5c4113dSnw141292 	res->retcode = idmap_stat4prot(retcode);
2783e8c27ec8Sbaban 	if (res->retcode != IDMAP_SUCCESS) {
2784e8c27ec8Sbaban 		req->direction = _IDMAP_F_DONE;
2785e8c27ec8Sbaban 		res->id.idmap_id_u.uid = UID_NOBODY;
2786e8c27ec8Sbaban 	}
2787e8c27ec8Sbaban 	if (!ARE_WE_DONE(req->direction))
2788e8c27ec8Sbaban 		state->sid2pid_done = FALSE;
2789c5c4113dSnw141292 	return (retcode);
2790c5c4113dSnw141292 }
2791c5c4113dSnw141292 
2792c5c4113dSnw141292 idmap_retcode
2793c5c4113dSnw141292 update_cache_pid2sid(lookup_state_t *state, sqlite *cache,
2794cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
2795cd37da74Snw141292 {
2796c5c4113dSnw141292 	char		*sql = NULL;
2797c5c4113dSnw141292 	idmap_retcode	retcode;
2798c5c4113dSnw141292 
2799c5c4113dSnw141292 	/* Check if we need to cache anything */
2800e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
2801c5c4113dSnw141292 		return (IDMAP_SUCCESS);
2802c5c4113dSnw141292 
2803c5c4113dSnw141292 	/* We don't cache negative entries */
2804c5c4113dSnw141292 	if (res->retcode != IDMAP_SUCCESS)
2805c5c4113dSnw141292 		return (IDMAP_SUCCESS);
2806c5c4113dSnw141292 
2807e8c27ec8Sbaban 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
2808e8c27ec8Sbaban 
2809c5c4113dSnw141292 	/*
2810c5c4113dSnw141292 	 * Using NULL for u2w instead of 0 so that our trigger allows
2811c5c4113dSnw141292 	 * the same pid to be the destination in multiple entries
2812c5c4113dSnw141292 	 */
2813c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
2814cd37da74Snw141292 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
2815cd37da74Snw141292 	    "is_user, is_wuser, expiration, w2u, u2w) "
2816cd37da74Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
2817c5c4113dSnw141292 	    "strftime('%%s','now') + 600, %q, 1); ",
2818cd37da74Snw141292 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
2819cd37da74Snw141292 	    req->id2domain, req->id2name, req->id1.idmap_id_u.uid,
2820cd37da74Snw141292 	    req->id1name, (req->id1.idtype == IDMAP_UID) ? 1 : 0,
2821e8c27ec8Sbaban 	    (res->id.idtype == IDMAP_USID) ? 1 : 0,
2822c5c4113dSnw141292 	    (res->direction == 0) ? "1" : NULL);
2823c5c4113dSnw141292 
2824c5c4113dSnw141292 	if (sql == NULL) {
2825c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
2826c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2827c5c4113dSnw141292 		goto out;
2828c5c4113dSnw141292 	}
2829c5c4113dSnw141292 
2830c5c4113dSnw141292 	retcode = sql_exec_no_cb(cache, sql);
2831c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
2832c5c4113dSnw141292 		goto out;
2833c5c4113dSnw141292 
2834c5c4113dSnw141292 	state->pid2sid_done = FALSE;
2835c5c4113dSnw141292 	sqlite_freemem(sql);
2836c5c4113dSnw141292 	sql = NULL;
2837c5c4113dSnw141292 
2838e8c27ec8Sbaban 	/* Check if we need to update namecache */
2839e8c27ec8Sbaban 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
2840c5c4113dSnw141292 		goto out;
2841c5c4113dSnw141292 
28428e228215Sdm199847 	if (req->id2name == NULL)
2843c5c4113dSnw141292 		goto out;
2844c5c4113dSnw141292 
2845c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
2846cd37da74Snw141292 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
2847c5c4113dSnw141292 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
2848cd37da74Snw141292 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
2849cd37da74Snw141292 	    req->id2name, req->id2domain,
2850e8c27ec8Sbaban 	    (res->id.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
2851c5c4113dSnw141292 
2852c5c4113dSnw141292 	if (sql == NULL) {
2853c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
2854c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2855c5c4113dSnw141292 		goto out;
2856c5c4113dSnw141292 	}
2857c5c4113dSnw141292 
2858c5c4113dSnw141292 	retcode = sql_exec_no_cb(cache, sql);
2859c5c4113dSnw141292 
2860c5c4113dSnw141292 out:
286162c60062Sbaban 	if (sql != NULL)
2862c5c4113dSnw141292 		sqlite_freemem(sql);
2863c5c4113dSnw141292 	return (retcode);
2864c5c4113dSnw141292 }
2865c5c4113dSnw141292 
2866c5c4113dSnw141292 idmap_retcode
2867c5c4113dSnw141292 update_cache_sid2pid(lookup_state_t *state, sqlite *cache,
2868cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
2869cd37da74Snw141292 {
2870c5c4113dSnw141292 	char		*sql = NULL;
2871c5c4113dSnw141292 	idmap_retcode	retcode;
2872c5c4113dSnw141292 	int		is_eph_user;
2873c5c4113dSnw141292 
2874c5c4113dSnw141292 	/* Check if we need to cache anything */
2875e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
2876c5c4113dSnw141292 		return (IDMAP_SUCCESS);
2877c5c4113dSnw141292 
2878c5c4113dSnw141292 	/* We don't cache negative entries */
2879c5c4113dSnw141292 	if (res->retcode != IDMAP_SUCCESS)
2880c5c4113dSnw141292 		return (IDMAP_SUCCESS);
2881c5c4113dSnw141292 
2882c5c4113dSnw141292 	if (req->direction & _IDMAP_F_EXP_EPH_UID)
2883c5c4113dSnw141292 		is_eph_user = 1;
2884c5c4113dSnw141292 	else if (req->direction & _IDMAP_F_EXP_EPH_GID)
2885c5c4113dSnw141292 		is_eph_user = 0;
2886c5c4113dSnw141292 	else
2887c5c4113dSnw141292 		is_eph_user = -1;
2888c5c4113dSnw141292 
2889c5c4113dSnw141292 	if (is_eph_user >= 0 && !IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
2890c5c4113dSnw141292 		sql = sqlite_mprintf("UPDATE idmap_cache "
2891c5c4113dSnw141292 		    "SET w2u = 0 WHERE "
2892c5c4113dSnw141292 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
2893c5c4113dSnw141292 		    "pid >= 2147483648 AND is_user = %d;",
2894c5c4113dSnw141292 		    req->id1.idmap_id_u.sid.prefix,
2895c5c4113dSnw141292 		    req->id1.idmap_id_u.sid.rid,
2896c5c4113dSnw141292 		    is_eph_user);
2897c5c4113dSnw141292 		if (sql == NULL) {
2898c5c4113dSnw141292 			retcode = IDMAP_ERR_INTERNAL;
2899c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
2900c5c4113dSnw141292 			goto out;
2901c5c4113dSnw141292 		}
2902c5c4113dSnw141292 
2903c5c4113dSnw141292 		retcode = sql_exec_no_cb(cache, sql);
2904c5c4113dSnw141292 		if (retcode != IDMAP_SUCCESS)
2905c5c4113dSnw141292 			goto out;
2906c5c4113dSnw141292 
2907c5c4113dSnw141292 		sqlite_freemem(sql);
2908c5c4113dSnw141292 		sql = NULL;
2909c5c4113dSnw141292 	}
2910c5c4113dSnw141292 
2911e8c27ec8Sbaban 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
2912cd37da74Snw141292 
2913c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
2914cd37da74Snw141292 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
2915cd37da74Snw141292 	    "is_user, is_wuser, expiration, w2u, u2w) "
2916cd37da74Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
2917c5c4113dSnw141292 	    "strftime('%%s','now') + 600, 1, %q); ",
2918cd37da74Snw141292 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
2919e8c27ec8Sbaban 	    (req->id1domain != NULL) ? req->id1domain : "", req->id1name,
2920e8c27ec8Sbaban 	    res->id.idmap_id_u.uid, req->id2name,
2921e8c27ec8Sbaban 	    (res->id.idtype == IDMAP_UID) ? 1 : 0,
2922cd37da74Snw141292 	    (req->id1.idtype == IDMAP_USID) ? 1 : 0,
2923c5c4113dSnw141292 	    (res->direction == 0) ? "1" : NULL);
2924c5c4113dSnw141292 
2925c5c4113dSnw141292 	if (sql == NULL) {
2926c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
2927c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2928c5c4113dSnw141292 		goto out;
2929c5c4113dSnw141292 	}
2930c5c4113dSnw141292 
2931c5c4113dSnw141292 	retcode = sql_exec_no_cb(cache, sql);
2932c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
2933c5c4113dSnw141292 		goto out;
2934c5c4113dSnw141292 
2935c5c4113dSnw141292 	state->sid2pid_done = FALSE;
2936c5c4113dSnw141292 	sqlite_freemem(sql);
2937c5c4113dSnw141292 	sql = NULL;
2938c5c4113dSnw141292 
2939e8c27ec8Sbaban 	/* Check if we need to update namecache */
2940e8c27ec8Sbaban 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
2941c5c4113dSnw141292 		goto out;
2942c5c4113dSnw141292 
2943cf5b5989Sdm199847 	if (EMPTY_STRING(req->id1name))
2944c5c4113dSnw141292 		goto out;
2945c5c4113dSnw141292 
2946c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
2947cd37da74Snw141292 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
2948c5c4113dSnw141292 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
2949cd37da74Snw141292 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
2950cd37da74Snw141292 	    req->id1name, req->id1domain,
2951cd37da74Snw141292 	    (req->id1.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
2952c5c4113dSnw141292 
2953c5c4113dSnw141292 	if (sql == NULL) {
2954c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
2955c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2956c5c4113dSnw141292 		goto out;
2957c5c4113dSnw141292 	}
2958c5c4113dSnw141292 
2959c5c4113dSnw141292 	retcode = sql_exec_no_cb(cache, sql);
2960c5c4113dSnw141292 
2961c5c4113dSnw141292 out:
296262c60062Sbaban 	if (sql != NULL)
2963c5c4113dSnw141292 		sqlite_freemem(sql);
2964c5c4113dSnw141292 	return (retcode);
2965c5c4113dSnw141292 }
2966c5c4113dSnw141292 
2967cd37da74Snw141292 static
2968cd37da74Snw141292 idmap_retcode
2969c5c4113dSnw141292 lookup_cache_pid2sid(sqlite *cache, idmap_mapping *req, idmap_id_res *res,
2970cd37da74Snw141292 		int is_user, int getname)
2971cd37da74Snw141292 {
2972c5c4113dSnw141292 	char		*end;
2973c5c4113dSnw141292 	char		*sql = NULL;
2974c5c4113dSnw141292 	const char	**values;
2975c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
2976c5c4113dSnw141292 	int		ncol;
2977c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
2978c5c4113dSnw141292 	time_t		curtime;
2979e8c27ec8Sbaban 	idmap_id_type	idtype;
2980c5c4113dSnw141292 
2981c5c4113dSnw141292 	/* Current time */
2982c5c4113dSnw141292 	errno = 0;
2983c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
2984cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
2985c5c4113dSnw141292 		    strerror(errno));
2986c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
2987c5c4113dSnw141292 		goto out;
2988c5c4113dSnw141292 	}
2989c5c4113dSnw141292 
2990e8c27ec8Sbaban 	/* SQL to lookup the cache by pid or by unixname */
2991e8c27ec8Sbaban 	if (req->id1.idmap_id_u.uid != SENTINEL_PID) {
2992e8c27ec8Sbaban 		sql = sqlite_mprintf("SELECT sidprefix, rid, canon_winname, "
2993e8c27ec8Sbaban 		    "windomain, w2u, is_wuser "
2994c5c4113dSnw141292 		    "FROM idmap_cache WHERE "
2995c5c4113dSnw141292 		    "pid = %u AND u2w = 1 AND is_user = %d AND "
2996c5c4113dSnw141292 		    "(pid >= 2147483648 OR "
2997c5c4113dSnw141292 		    "(expiration = 0 OR expiration ISNULL OR "
2998c5c4113dSnw141292 		    "expiration > %d));",
2999c5c4113dSnw141292 		    req->id1.idmap_id_u.uid, is_user, curtime);
3000e8c27ec8Sbaban 	} else if (req->id1name != NULL) {
3001e8c27ec8Sbaban 		sql = sqlite_mprintf("SELECT sidprefix, rid, canon_winname, "
3002e8c27ec8Sbaban 		    "windomain, w2u, is_wuser "
3003e8c27ec8Sbaban 		    "FROM idmap_cache WHERE "
3004e8c27ec8Sbaban 		    "unixname = %Q AND u2w = 1 AND is_user = %d AND "
3005e8c27ec8Sbaban 		    "(pid >= 2147483648 OR "
3006e8c27ec8Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
3007e8c27ec8Sbaban 		    "expiration > %d));",
3008e8c27ec8Sbaban 		    req->id1name, is_user, curtime);
3009e8c27ec8Sbaban 	}
3010e8c27ec8Sbaban 
3011c5c4113dSnw141292 	if (sql == NULL) {
3012c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3013c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
3014c5c4113dSnw141292 		goto out;
3015c5c4113dSnw141292 	}
3016c5c4113dSnw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 5, &values);
3017c5c4113dSnw141292 	sqlite_freemem(sql);
3018c5c4113dSnw141292 
3019c5c4113dSnw141292 	if (retcode == IDMAP_ERR_NOTFOUND)
3020c5c4113dSnw141292 		goto out;
3021c5c4113dSnw141292 	else if (retcode == IDMAP_SUCCESS) {
3022c5c4113dSnw141292 		/* sanity checks */
3023c5c4113dSnw141292 		if (values[0] == NULL || values[1] == NULL) {
3024c5c4113dSnw141292 			retcode = IDMAP_ERR_CACHE;
3025c5c4113dSnw141292 			goto out;
3026c5c4113dSnw141292 		}
3027c5c4113dSnw141292 
3028e8c27ec8Sbaban 		switch (res->id.idtype) {
3029c5c4113dSnw141292 		case IDMAP_SID:
3030cd37da74Snw141292 		case IDMAP_USID:
3031cd37da74Snw141292 		case IDMAP_GSID:
3032e8c27ec8Sbaban 			idtype = strtol(values[5], &end, 10) == 1
3033cd37da74Snw141292 			    ? IDMAP_USID : IDMAP_GSID;
3034cd37da74Snw141292 
3035e8c27ec8Sbaban 			if (res->id.idtype == IDMAP_USID &&
3036e8c27ec8Sbaban 			    idtype != IDMAP_USID) {
3037cd37da74Snw141292 				retcode = IDMAP_ERR_NOTUSER;
3038cd37da74Snw141292 				goto out;
3039e8c27ec8Sbaban 			} else if (res->id.idtype == IDMAP_GSID &&
3040e8c27ec8Sbaban 			    idtype != IDMAP_GSID) {
3041cd37da74Snw141292 				retcode = IDMAP_ERR_NOTGROUP;
3042cd37da74Snw141292 				goto out;
3043cd37da74Snw141292 			}
3044e8c27ec8Sbaban 			res->id.idtype = idtype;
3045cd37da74Snw141292 
3046c5c4113dSnw141292 			res->id.idmap_id_u.sid.rid =
3047c5c4113dSnw141292 			    strtoul(values[1], &end, 10);
3048c5c4113dSnw141292 			res->id.idmap_id_u.sid.prefix = strdup(values[0]);
3049c5c4113dSnw141292 			if (res->id.idmap_id_u.sid.prefix == NULL) {
3050c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
3051c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
3052c5c4113dSnw141292 				goto out;
3053c5c4113dSnw141292 			}
3054c5c4113dSnw141292 
305562c60062Sbaban 			if (values[4] != NULL)
3056c5c4113dSnw141292 				res->direction =
3057651c0131Sbaban 				    (strtol(values[4], &end, 10) == 0)?
3058651c0131Sbaban 				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
3059c5c4113dSnw141292 			else
3060651c0131Sbaban 				res->direction = IDMAP_DIRECTION_U2W;
3061c5c4113dSnw141292 
3062c5c4113dSnw141292 			if (getname == 0 || values[2] == NULL)
3063c5c4113dSnw141292 				break;
30648e228215Sdm199847 			req->id2name = strdup(values[2]);
30658e228215Sdm199847 			if (req->id2name == NULL) {
3066c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
3067c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
3068c5c4113dSnw141292 				goto out;
3069c5c4113dSnw141292 			}
3070c5c4113dSnw141292 
3071c5c4113dSnw141292 			if (values[3] == NULL)
3072c5c4113dSnw141292 				break;
30738e228215Sdm199847 			req->id2domain = strdup(values[3]);
30748e228215Sdm199847 			if (req->id2domain == NULL) {
3075c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
3076c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
3077c5c4113dSnw141292 				goto out;
3078c5c4113dSnw141292 			}
3079cd37da74Snw141292 
3080c5c4113dSnw141292 			break;
3081c5c4113dSnw141292 		default:
3082c5c4113dSnw141292 			retcode = IDMAP_ERR_NOTSUPPORTED;
3083c5c4113dSnw141292 			break;
3084c5c4113dSnw141292 		}
3085c5c4113dSnw141292 	}
3086c5c4113dSnw141292 
3087c5c4113dSnw141292 out:
308862c60062Sbaban 	if (vm != NULL)
3089c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
3090c5c4113dSnw141292 	return (retcode);
3091c5c4113dSnw141292 }
3092c5c4113dSnw141292 
3093cd37da74Snw141292 static
3094cd37da74Snw141292 idmap_retcode
3095c5c4113dSnw141292 lookup_cache_name2sid(sqlite *cache, const char *name, const char *domain,
3096cd37da74Snw141292 	char **canonname, char **sidprefix, idmap_rid_t *rid, int *type)
3097cd37da74Snw141292 {
3098cd37da74Snw141292 	char		*end, *lower_name;
3099c5c4113dSnw141292 	char		*sql = NULL;
3100c5c4113dSnw141292 	const char	**values;
3101c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
3102c5c4113dSnw141292 	int		ncol;
3103c5c4113dSnw141292 	time_t		curtime;
3104c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
3105c5c4113dSnw141292 
3106c5c4113dSnw141292 	/* Get current time */
3107c5c4113dSnw141292 	errno = 0;
3108c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
3109cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
3110c5c4113dSnw141292 		    strerror(errno));
3111c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3112c5c4113dSnw141292 		goto out;
3113c5c4113dSnw141292 	}
3114c5c4113dSnw141292 
3115c5c4113dSnw141292 	/* SQL to lookup the cache */
3116cd37da74Snw141292 	if ((lower_name = tolower_u8(name)) == NULL)
3117cd37da74Snw141292 		lower_name = (char *)name;
3118cd37da74Snw141292 	sql = sqlite_mprintf("SELECT sidprefix, rid, type, canon_name "
3119cd37da74Snw141292 	    "FROM name_cache WHERE name = %Q AND domain = %Q AND "
3120c5c4113dSnw141292 	    "(expiration = 0 OR expiration ISNULL OR "
3121cd37da74Snw141292 	    "expiration > %d);", lower_name, domain, curtime);
3122cd37da74Snw141292 	if (lower_name != name)
3123cd37da74Snw141292 		free(lower_name);
3124c5c4113dSnw141292 	if (sql == NULL) {
3125c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3126c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
3127c5c4113dSnw141292 		goto out;
3128c5c4113dSnw141292 	}
3129cd37da74Snw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 4, &values);
3130c5c4113dSnw141292 	sqlite_freemem(sql);
3131c5c4113dSnw141292 
3132c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
313362c60062Sbaban 		if (type != NULL) {
3134c5c4113dSnw141292 			if (values[2] == NULL) {
3135c5c4113dSnw141292 				retcode = IDMAP_ERR_CACHE;
3136c5c4113dSnw141292 				goto out;
3137c5c4113dSnw141292 			}
3138c5c4113dSnw141292 			*type = strtol(values[2], &end, 10);
3139c5c4113dSnw141292 		}
3140c5c4113dSnw141292 
3141e8c27ec8Sbaban 		if (values[0] == NULL || values[1] == NULL) {
3142e8c27ec8Sbaban 			retcode = IDMAP_ERR_CACHE;
3143e8c27ec8Sbaban 			goto out;
3144e8c27ec8Sbaban 		}
3145e8c27ec8Sbaban 
3146cd37da74Snw141292 		if (canonname != NULL) {
3147cd37da74Snw141292 			assert(values[3] != NULL);
3148cd37da74Snw141292 			if ((*canonname = strdup(values[3])) == NULL) {
3149cd37da74Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
3150cd37da74Snw141292 				retcode = IDMAP_ERR_MEMORY;
3151cd37da74Snw141292 				goto out;
3152cd37da74Snw141292 			}
3153cd37da74Snw141292 		}
3154cd37da74Snw141292 
3155c5c4113dSnw141292 		if ((*sidprefix = strdup(values[0])) == NULL) {
3156c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
3157c5c4113dSnw141292 			retcode = IDMAP_ERR_MEMORY;
3158e8c27ec8Sbaban 			if (canonname != NULL) {
3159e8c27ec8Sbaban 				free(*canonname);
3160e8c27ec8Sbaban 				*canonname = NULL;
3161e8c27ec8Sbaban 			}
3162c5c4113dSnw141292 			goto out;
3163c5c4113dSnw141292 		}
3164c5c4113dSnw141292 		*rid = strtoul(values[1], &end, 10);
3165c5c4113dSnw141292 	}
3166c5c4113dSnw141292 
3167c5c4113dSnw141292 out:
316862c60062Sbaban 	if (vm != NULL)
3169c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
3170c5c4113dSnw141292 	return (retcode);
3171c5c4113dSnw141292 }
3172c5c4113dSnw141292 
3173cd37da74Snw141292 static
3174cd37da74Snw141292 idmap_retcode
3175e8c27ec8Sbaban ad_lookup_by_winname(lookup_state_t *state,
3176e8c27ec8Sbaban 		const char *name, const char *domain, int eunixtype,
3177e8c27ec8Sbaban 		char **canonname, char **sidprefix,
3178e8c27ec8Sbaban 		idmap_rid_t *rid, int *wintype, char **unixname)
3179cd37da74Snw141292 {
3180c5c4113dSnw141292 	int			retries = 0;
3181c5c4113dSnw141292 	idmap_query_state_t	*qs = NULL;
3182c5c4113dSnw141292 	idmap_retcode		rc, retcode;
3183c5c4113dSnw141292 
3184c5c4113dSnw141292 retry:
3185e8c27ec8Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, 1, &qs);
3186e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
3187*0dcc7149Snw141292 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
3188*0dcc7149Snw141292 			goto retry;
3189*0dcc7149Snw141292 		degrade_svc("failed to create request for AD lookup "
3190*0dcc7149Snw141292 		    "by winname");
3191e8c27ec8Sbaban 		return (retcode);
3192c5c4113dSnw141292 	}
3193c5c4113dSnw141292 
3194c8e26105Sjp151216 	restore_svc();
3195c8e26105Sjp151216 
3196e8c27ec8Sbaban 	if (state != NULL)
3197e8c27ec8Sbaban 		idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
3198e8c27ec8Sbaban 		    state->ad_unixgroup_attr);
3199c5c4113dSnw141292 
3200e8c27ec8Sbaban 	retcode = idmap_name2sid_batch_add1(qs, name, domain, eunixtype,
3201e8c27ec8Sbaban 	    canonname, sidprefix, rid, wintype, unixname, &rc);
3202c5c4113dSnw141292 
3203e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
320484decf41Sjp151216 		idmap_lookup_release_batch(&qs);
3205c5c4113dSnw141292 	else
3206*0dcc7149Snw141292 		retcode = idmap_lookup_batch_end(&qs);
3207c5c4113dSnw141292 
3208c5c4113dSnw141292 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
3209c5c4113dSnw141292 		goto retry;
3210c8e26105Sjp151216 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
3211*0dcc7149Snw141292 		degrade_svc("some AD lookups timed out repeatedly");
3212c5c4113dSnw141292 
3213c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS) {
3214e8c27ec8Sbaban 		idmapdlog(LOG_NOTICE, "AD lookup by winname failed");
3215c5c4113dSnw141292 		return (retcode);
3216e8c27ec8Sbaban 	}
3217c5c4113dSnw141292 	return (rc);
3218c5c4113dSnw141292 }
3219c5c4113dSnw141292 
3220cd37da74Snw141292 static
3221cd37da74Snw141292 idmap_retcode
3222c5c4113dSnw141292 lookup_name2sid(sqlite *cache, const char *name, const char *domain,
3223cd37da74Snw141292 		int *is_wuser, char **canonname, char **sidprefix,
3224cd37da74Snw141292 		idmap_rid_t *rid, idmap_mapping *req)
3225cd37da74Snw141292 {
3226c5c4113dSnw141292 	int		type;
3227c5c4113dSnw141292 	idmap_retcode	retcode;
3228c5c4113dSnw141292 
3229cd37da74Snw141292 	*sidprefix = NULL;
3230e8c27ec8Sbaban 	if (canonname != NULL)
3231cd37da74Snw141292 		*canonname = NULL;
3232cd37da74Snw141292 
3233e8c27ec8Sbaban 	/* Lookup well-known SIDs table */
3234cd37da74Snw141292 	retcode = lookup_wksids_name2sid(name, canonname, sidprefix, rid,
3235cd37da74Snw141292 	    &type);
323662c60062Sbaban 	if (retcode == IDMAP_SUCCESS) {
3237e8c27ec8Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
323862c60062Sbaban 		goto out;
323962c60062Sbaban 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
324062c60062Sbaban 		return (retcode);
324162c60062Sbaban 	}
324262c60062Sbaban 
3243e8c27ec8Sbaban 	/* Lookup cache */
3244cd37da74Snw141292 	retcode = lookup_cache_name2sid(cache, name, domain, canonname,
3245cd37da74Snw141292 	    sidprefix, rid, &type);
3246e8c27ec8Sbaban 	if (retcode == IDMAP_SUCCESS) {
3247e8c27ec8Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
3248e8c27ec8Sbaban 		goto out;
3249e8c27ec8Sbaban 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
3250e8c27ec8Sbaban 		return (retcode);
3251e8c27ec8Sbaban 	}
3252e8c27ec8Sbaban 
3253e8c27ec8Sbaban 	/* Lookup AD */
3254e8c27ec8Sbaban 	retcode = ad_lookup_by_winname(NULL, name, domain, _IDMAP_T_UNDEF,
3255e8c27ec8Sbaban 	    canonname, sidprefix, rid, &type, NULL);
3256c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
3257c5c4113dSnw141292 		return (retcode);
3258e8c27ec8Sbaban 	/* Don't need to set req->direction |= _IDMAP_F_LOOKUP_AD; */
3259c5c4113dSnw141292 
326062c60062Sbaban out:
3261c5c4113dSnw141292 	/*
3262c5c4113dSnw141292 	 * Entry found (cache or Windows lookup)
3263cd37da74Snw141292 	 * is_wuser is both input as well as output parameter
3264c5c4113dSnw141292 	 */
3265e8c27ec8Sbaban 	if (*is_wuser == 1 && type != _IDMAP_T_USER)
3266e8c27ec8Sbaban 		retcode = IDMAP_ERR_NOTUSER;
3267e8c27ec8Sbaban 	else if (*is_wuser == 0 && type != _IDMAP_T_GROUP)
3268e8c27ec8Sbaban 		retcode = IDMAP_ERR_NOTGROUP;
3269e8c27ec8Sbaban 	else if (*is_wuser == -1) {
3270c5c4113dSnw141292 		/* Caller wants to know if its user or group */
3271c5c4113dSnw141292 		if (type == _IDMAP_T_USER)
3272cd37da74Snw141292 			*is_wuser = 1;
3273c5c4113dSnw141292 		else if (type == _IDMAP_T_GROUP)
3274cd37da74Snw141292 			*is_wuser = 0;
3275e8c27ec8Sbaban 		else
3276e8c27ec8Sbaban 			retcode = IDMAP_ERR_SID;
3277e8c27ec8Sbaban 	}
3278e8c27ec8Sbaban 
3279e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
3280cd37da74Snw141292 		free(*sidprefix);
3281cd37da74Snw141292 		*sidprefix = NULL;
3282e8c27ec8Sbaban 		if (canonname != NULL) {
3283cd37da74Snw141292 			free(*canonname);
3284cd37da74Snw141292 			*canonname = NULL;
3285cd37da74Snw141292 		}
3286c5c4113dSnw141292 	}
3287c5c4113dSnw141292 	return (retcode);
3288c5c4113dSnw141292 }
3289c5c4113dSnw141292 
3290cd37da74Snw141292 static
3291cd37da74Snw141292 idmap_retcode
3292c5c4113dSnw141292 name_based_mapping_pid2sid(sqlite *db, sqlite *cache, const char *unixname,
3293cd37da74Snw141292 		int is_user, idmap_mapping *req, idmap_id_res *res)
3294cd37da74Snw141292 {
3295c5c4113dSnw141292 	const char	*winname, *windomain;
3296cd37da74Snw141292 	char		*canonname;
3297c8e26105Sjp151216 	char		*default_domain = NULL;
3298c5c4113dSnw141292 	char		*sql = NULL, *errmsg = NULL;
3299c5c4113dSnw141292 	idmap_retcode	retcode;
3300c5c4113dSnw141292 	char		*end;
3301c5c4113dSnw141292 	const char	**values;
3302c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
3303cd37da74Snw141292 	int		ncol, r, nrow;
3304cd37da74Snw141292 	int		is_wuser;
3305e8c27ec8Sbaban 	const char	*me = "name_based_mapping_pid2sid";
3306e8c27ec8Sbaban 
3307e8c27ec8Sbaban 	assert(unixname != NULL); /* We have unixname */
3308e8c27ec8Sbaban 	assert(req->id2name == NULL); /* We don't have winname */
3309e8c27ec8Sbaban 	assert(res->id.idmap_id_u.sid.prefix == NULL); /* No SID either */
3310c5c4113dSnw141292 
3311c5c4113dSnw141292 	RDLOCK_CONFIG();
3312c8e26105Sjp151216 	if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
3313c8e26105Sjp151216 		default_domain =
3314c8e26105Sjp151216 		    strdup(_idmapdstate.cfg->pgcfg.default_domain);
3315c8e26105Sjp151216 		if (default_domain == NULL) {
3316c5c4113dSnw141292 			UNLOCK_CONFIG();
3317c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
3318c5c4113dSnw141292 			retcode = IDMAP_ERR_MEMORY;
3319c5c4113dSnw141292 			goto out;
3320c5c4113dSnw141292 		}
3321c5c4113dSnw141292 	}
3322c5c4113dSnw141292 	UNLOCK_CONFIG();
3323c5c4113dSnw141292 
3324c5c4113dSnw141292 	sql = sqlite_mprintf(
3325cd37da74Snw141292 	    "SELECT winname_display, windomain, w2u_order FROM namerules WHERE "
3326c5c4113dSnw141292 	    "u2w_order > 0 AND is_user = %d AND "
3327c5c4113dSnw141292 	    "(unixname = %Q OR unixname = '*') "
3328cd37da74Snw141292 	    "ORDER BY u2w_order ASC;", is_user, unixname);
3329c5c4113dSnw141292 	if (sql == NULL) {
3330c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3331c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
3332c5c4113dSnw141292 		goto out;
3333c5c4113dSnw141292 	}
3334c5c4113dSnw141292 
3335c5c4113dSnw141292 	if (sqlite_compile(db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
3336c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3337cd37da74Snw141292 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
3338cd37da74Snw141292 		    CHECK_NULL(errmsg));
3339c5c4113dSnw141292 		sqlite_freemem(errmsg);
3340c5c4113dSnw141292 		goto out;
3341c5c4113dSnw141292 	}
3342c5c4113dSnw141292 
3343cd37da74Snw141292 	for (nrow = 0; ; ) {
3344c5c4113dSnw141292 		r = sqlite_step(vm, &ncol, &values, NULL);
334584decf41Sjp151216 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
334684decf41Sjp151216 		if (r == SQLITE_ROW) {
3347cd37da74Snw141292 			nrow++;
3348c5c4113dSnw141292 			if (ncol < 3) {
3349c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
3350c5c4113dSnw141292 				goto out;
3351c5c4113dSnw141292 			}
3352c5c4113dSnw141292 			if (values[0] == NULL) {
3353c5c4113dSnw141292 				/* values [1] and [2] can be null */
3354c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
3355c5c4113dSnw141292 				goto out;
3356c5c4113dSnw141292 			}
3357c5c4113dSnw141292 			if (EMPTY_NAME(values[0])) {
3358c5c4113dSnw141292 				retcode = IDMAP_ERR_NOMAPPING;
3359c5c4113dSnw141292 				goto out;
3360c5c4113dSnw141292 			}
3361cd37da74Snw141292 
3362cd37da74Snw141292 			if (values[0][0] == '*') {
3363cd37da74Snw141292 				if (nrow > 1) {
3364cd37da74Snw141292 					/*
3365cd37da74Snw141292 					 * There were non-wildcard rules where
3366cd37da74Snw141292 					 * windows identity doesn't exist
3367cd37da74Snw141292 					 */
3368cd37da74Snw141292 					retcode = IDMAP_ERR_NOMAPPING;
3369cd37da74Snw141292 					goto out;
3370cd37da74Snw141292 				}
3371cd37da74Snw141292 				winname = unixname;
3372cd37da74Snw141292 			} else {
3373cd37da74Snw141292 				winname = values[0];
3374cd37da74Snw141292 			}
3375cd37da74Snw141292 
337662c60062Sbaban 			if (values[1] != NULL)
3377c5c4113dSnw141292 				windomain = values[1];
3378c8e26105Sjp151216 			else if (default_domain != NULL)
3379c8e26105Sjp151216 				windomain = default_domain;
3380c5c4113dSnw141292 			else {
3381cd37da74Snw141292 				idmapdlog(LOG_ERR, "%s: no domain", me);
3382c5c4113dSnw141292 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
3383c5c4113dSnw141292 				goto out;
3384c5c4113dSnw141292 			}
3385c5c4113dSnw141292 			/* Lookup winname@domain to sid */
3386cd37da74Snw141292 
3387cd37da74Snw141292 			is_wuser = res->id.idtype == IDMAP_USID ? 1
3388cd37da74Snw141292 			    : res->id.idtype == IDMAP_GSID ? 0
3389cd37da74Snw141292 			    : -1;
3390cd37da74Snw141292 
3391c5c4113dSnw141292 			retcode = lookup_name2sid(cache, winname, windomain,
3392cd37da74Snw141292 			    &is_wuser, &canonname,
3393cd37da74Snw141292 			    &res->id.idmap_id_u.sid.prefix,
3394c5c4113dSnw141292 			    &res->id.idmap_id_u.sid.rid, req);
3395e8c27ec8Sbaban 
3396c5c4113dSnw141292 			if (retcode == IDMAP_ERR_NOTFOUND) {
3397c5c4113dSnw141292 				continue;
3398c5c4113dSnw141292 			}
3399cd37da74Snw141292 
3400c5c4113dSnw141292 			goto out;
3401c5c4113dSnw141292 		} else if (r == SQLITE_DONE) {
3402c5c4113dSnw141292 			retcode = IDMAP_ERR_NOTFOUND;
3403c5c4113dSnw141292 			goto out;
3404c5c4113dSnw141292 		} else {
3405c5c4113dSnw141292 			(void) sqlite_finalize(vm, &errmsg);
3406c5c4113dSnw141292 			vm = NULL;
3407cd37da74Snw141292 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
3408cd37da74Snw141292 			    CHECK_NULL(errmsg));
3409c5c4113dSnw141292 			sqlite_freemem(errmsg);
3410c5c4113dSnw141292 			retcode = IDMAP_ERR_INTERNAL;
3411c5c4113dSnw141292 			goto out;
3412c5c4113dSnw141292 		}
3413c5c4113dSnw141292 	}
3414c5c4113dSnw141292 
3415c5c4113dSnw141292 out:
341662c60062Sbaban 	if (sql != NULL)
3417c5c4113dSnw141292 		sqlite_freemem(sql);
3418c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
3419cd37da74Snw141292 		res->id.idtype = is_wuser ? IDMAP_USID : IDMAP_GSID;
3420cd37da74Snw141292 
342162c60062Sbaban 		if (values[2] != NULL)
3422c5c4113dSnw141292 			res->direction =
3423651c0131Sbaban 			    (strtol(values[2], &end, 10) == 0)?
3424651c0131Sbaban 			    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
3425c5c4113dSnw141292 		else
3426651c0131Sbaban 			res->direction = IDMAP_DIRECTION_U2W;
34278e228215Sdm199847 
3428cd37da74Snw141292 		req->id2name = canonname;
34298e228215Sdm199847 		if (req->id2name != NULL) {
3430c8e26105Sjp151216 			if (windomain == default_domain) {
34318e228215Sdm199847 				req->id2domain = (char *)windomain;
3432c8e26105Sjp151216 				default_domain = NULL;
34338e228215Sdm199847 			} else {
34348e228215Sdm199847 				req->id2domain = strdup(windomain);
34358e228215Sdm199847 			}
3436c5c4113dSnw141292 		}
3437c5c4113dSnw141292 	}
343862c60062Sbaban 	if (vm != NULL)
3439c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
3440c8e26105Sjp151216 	if (default_domain != NULL)
3441c8e26105Sjp151216 		free(default_domain);
3442c5c4113dSnw141292 	return (retcode);
3443c5c4113dSnw141292 }
3444c5c4113dSnw141292 
3445cd37da74Snw141292 /*
3446cd37da74Snw141292  * Convention when processing unix2win requests:
3447cd37da74Snw141292  *
3448cd37da74Snw141292  * Unix identity:
3449cd37da74Snw141292  * req->id1name =
3450cd37da74Snw141292  *              unixname if given otherwise unixname found will be placed
3451cd37da74Snw141292  *              here.
3452cd37da74Snw141292  * req->id1domain =
3453cd37da74Snw141292  *              NOT USED
3454cd37da74Snw141292  * req->id1.idtype =
3455cd37da74Snw141292  *              Given type (IDMAP_UID or IDMAP_GID)
3456cd37da74Snw141292  * req->id1..[uid or gid] =
3457cd37da74Snw141292  *              UID/GID if given otherwise UID/GID found will be placed here.
3458cd37da74Snw141292  *
3459cd37da74Snw141292  * Windows identity:
3460cd37da74Snw141292  * req->id2name =
3461cd37da74Snw141292  *              winname found will be placed here.
3462cd37da74Snw141292  * req->id2domain =
3463cd37da74Snw141292  *              windomain found will be placed here.
3464cd37da74Snw141292  * res->id.idtype =
3465cd37da74Snw141292  *              Target type initialized from req->id2.idtype. If
3466cd37da74Snw141292  *              it is IDMAP_SID then actual type (IDMAP_USID/GSID) found
3467cd37da74Snw141292  *              will be placed here.
3468cd37da74Snw141292  * req->id..sid.[prefix, rid] =
3469cd37da74Snw141292  *              SID found will be placed here.
3470cd37da74Snw141292  *
3471cd37da74Snw141292  * Others:
3472cd37da74Snw141292  * res->retcode =
3473cd37da74Snw141292  *              Return status for this request will be placed here.
3474cd37da74Snw141292  * res->direction =
3475cd37da74Snw141292  *              Direction found will be placed here. Direction
3476cd37da74Snw141292  *              meaning whether the resultant mapping is valid
3477cd37da74Snw141292  *              only from unix2win or bi-directional.
3478cd37da74Snw141292  * req->direction =
3479cd37da74Snw141292  *              INTERNAL USE. Used by idmapd to set various
3480cd37da74Snw141292  *              flags (_IDMAP_F_xxxx) to aid in processing
3481cd37da74Snw141292  *              of the request.
3482cd37da74Snw141292  * req->id2.idtype =
3483cd37da74Snw141292  *              INTERNAL USE. Initially this is the requested target
3484cd37da74Snw141292  *              type and is used to initialize res->id.idtype.
3485cd37da74Snw141292  *              ad_lookup_batch() uses this field temporarily to store
3486cd37da74Snw141292  *              sid_type obtained by the batched AD lookups and after
3487cd37da74Snw141292  *              use resets it to IDMAP_NONE to prevent xdr from
3488cd37da74Snw141292  *              mis-interpreting the contents of req->id2.
3489cd37da74Snw141292  * req->id2..[uid or gid or sid] =
3490cd37da74Snw141292  *              NOT USED
3491cd37da74Snw141292  */
3492cd37da74Snw141292 
3493cd37da74Snw141292 /*
3494cd37da74Snw141292  * This function does the following:
3495cd37da74Snw141292  * 1. Lookup well-known SIDs table.
3496cd37da74Snw141292  * 2. Lookup cache.
3497cd37da74Snw141292  * 3. Check if the client does not want new mapping to be allocated
3498cd37da74Snw141292  *    in which case this pass is the final pass.
3499e8c27ec8Sbaban  * 4. Set AD/NLDAP lookup flags if it determines that the next stage needs
3500e8c27ec8Sbaban  *    to do AD/NLDAP lookup.
3501cd37da74Snw141292  */
3502c5c4113dSnw141292 idmap_retcode
3503e8c27ec8Sbaban pid2sid_first_pass(lookup_state_t *state, sqlite *cache,
3504c5c4113dSnw141292 		idmap_mapping *req, idmap_id_res *res, int is_user,
3505cd37da74Snw141292 		int getname)
3506cd37da74Snw141292 {
3507e8c27ec8Sbaban 	idmap_retcode	retcode;
3508e8c27ec8Sbaban 	bool_t		gen_localsid_on_err = FALSE;
3509c5c4113dSnw141292 
3510e8c27ec8Sbaban 	/* Initialize result */
3511c5c4113dSnw141292 	res->id.idtype = req->id2.idtype;
3512e8c27ec8Sbaban 	res->direction = IDMAP_DIRECTION_UNDEF;
3513c5c4113dSnw141292 
3514e8c27ec8Sbaban 	if (req->id2.idmap_id_u.sid.prefix != NULL) {
3515e8c27ec8Sbaban 		/* sanitize sidprefix */
3516e8c27ec8Sbaban 		free(req->id2.idmap_id_u.sid.prefix);
3517e8c27ec8Sbaban 		req->id2.idmap_id_u.sid.prefix = NULL;
3518e8c27ec8Sbaban 	}
3519e8c27ec8Sbaban 
3520e8c27ec8Sbaban 	/* Lookup well-known SIDs table */
3521c5c4113dSnw141292 	retcode = lookup_wksids_pid2sid(req, res, is_user);
3522c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
3523c5c4113dSnw141292 		goto out;
3524c5c4113dSnw141292 
3525e8c27ec8Sbaban 	/* Lookup cache */
3526c5c4113dSnw141292 	retcode = lookup_cache_pid2sid(cache, req, res, is_user, getname);
3527c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
3528c5c4113dSnw141292 		goto out;
3529c5c4113dSnw141292 
3530c5c4113dSnw141292 	/* Ephemeral ids cannot be allocated during pid2sid */
3531c5c4113dSnw141292 	if (IS_EPHEMERAL(req->id1.idmap_id_u.uid)) {
353262c60062Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
3533c5c4113dSnw141292 		goto out;
3534c5c4113dSnw141292 	}
3535c5c4113dSnw141292 
3536c5c4113dSnw141292 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req) || AVOID_NAMESERVICE(req)) {
3537e8c27ec8Sbaban 		gen_localsid_on_err = TRUE;
353862c60062Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
3539c5c4113dSnw141292 		goto out;
3540c5c4113dSnw141292 	}
3541c5c4113dSnw141292 
3542e8c27ec8Sbaban 	/* Set flags for the next stage */
3543e8c27ec8Sbaban 	if (AD_MODE(req->id1.idtype, state)) {
3544e8c27ec8Sbaban 		/*
3545e8c27ec8Sbaban 		 * If AD-based name mapping is enabled then the next stage
3546e8c27ec8Sbaban 		 * will need to lookup AD using unixname to get the
3547e8c27ec8Sbaban 		 * corresponding winname.
3548e8c27ec8Sbaban 		 */
3549e8c27ec8Sbaban 		if (req->id1name == NULL) {
3550e8c27ec8Sbaban 			/* Get unixname if only pid is given. */
3551e8c27ec8Sbaban 			retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid,
3552e8c27ec8Sbaban 			    is_user, &req->id1name);
3553e8c27ec8Sbaban 			if (retcode != IDMAP_SUCCESS)
3554e8c27ec8Sbaban 				goto out;
3555c5c4113dSnw141292 		}
3556e8c27ec8Sbaban 		req->direction |= _IDMAP_F_LOOKUP_AD;
3557e8c27ec8Sbaban 		state->ad_nqueries++;
3558e8c27ec8Sbaban 	} else if (NLDAP_OR_MIXED_MODE(req->id1.idtype, state)) {
3559e8c27ec8Sbaban 		/*
3560e8c27ec8Sbaban 		 * If native LDAP or mixed mode is enabled for name mapping
3561e8c27ec8Sbaban 		 * then the next stage will need to lookup native LDAP using
3562e8c27ec8Sbaban 		 * unixname/pid to get the corresponding winname.
3563e8c27ec8Sbaban 		 */
3564e8c27ec8Sbaban 		req->direction |= _IDMAP_F_LOOKUP_NLDAP;
3565e8c27ec8Sbaban 		state->nldap_nqueries++;
3566c5c4113dSnw141292 	}
3567c5c4113dSnw141292 
3568e8c27ec8Sbaban 	/*
3569e8c27ec8Sbaban 	 * Failed to find non-expired entry in cache. Set the flag to
3570e8c27ec8Sbaban 	 * indicate that we are not done yet.
3571e8c27ec8Sbaban 	 */
3572e8c27ec8Sbaban 	state->pid2sid_done = FALSE;
3573e8c27ec8Sbaban 	req->direction |= _IDMAP_F_NOTDONE;
3574e8c27ec8Sbaban 	retcode = IDMAP_SUCCESS;
3575e8c27ec8Sbaban 
3576e8c27ec8Sbaban out:
3577e8c27ec8Sbaban 	res->retcode = idmap_stat4prot(retcode);
3578e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
3579e8c27ec8Sbaban 		if (gen_localsid_on_err == TRUE)
3580e8c27ec8Sbaban 			(void) generate_localsid(req, res, is_user);
3581e8c27ec8Sbaban 	return (retcode);
3582e8c27ec8Sbaban }
3583e8c27ec8Sbaban 
3584e8c27ec8Sbaban idmap_retcode
3585e8c27ec8Sbaban pid2sid_second_pass(lookup_state_t *state, sqlite *cache, sqlite *db,
3586e8c27ec8Sbaban 		idmap_mapping *req, idmap_id_res *res, int is_user)
3587e8c27ec8Sbaban {
3588e8c27ec8Sbaban 	bool_t		gen_localsid_on_err = TRUE;
3589e8c27ec8Sbaban 	idmap_retcode	retcode = IDMAP_SUCCESS;
3590e8c27ec8Sbaban 
3591e8c27ec8Sbaban 	/* Check if second pass is needed */
3592e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
3593e8c27ec8Sbaban 		return (res->retcode);
3594e8c27ec8Sbaban 
3595e8c27ec8Sbaban 	/* Get status from previous pass */
3596e8c27ec8Sbaban 	retcode = res->retcode;
3597e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
3598e8c27ec8Sbaban 		goto out;
3599e8c27ec8Sbaban 
3600e8c27ec8Sbaban 	/*
3601e8c27ec8Sbaban 	 * If directory-based name mapping is enabled then the winname
3602e8c27ec8Sbaban 	 * may already have been retrieved from the AD object (AD-mode)
3603e8c27ec8Sbaban 	 * or from native LDAP object (nldap-mode or mixed-mode) -- done.
3604e8c27ec8Sbaban 	 */
3605e8c27ec8Sbaban 	if (res->id.idmap_id_u.sid.prefix != NULL || req->id2name != NULL) {
3606e8c27ec8Sbaban 		if (AD_MODE(req->id1.idtype, state))
3607e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
3608e8c27ec8Sbaban 		else if (NLDAP_MODE(req->id1.idtype, state))
3609e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
3610e8c27ec8Sbaban 		else if (MIXED_MODE(req->id1.idtype, state))
3611e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
3612e8c27ec8Sbaban 		goto out;
3613e8c27ec8Sbaban 	}
3614e8c27ec8Sbaban 
3615e8c27ec8Sbaban 	if (req->id1name == NULL) {
3616e8c27ec8Sbaban 		/* Get unixname from name service */
3617e8c27ec8Sbaban 		retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid, is_user,
3618e8c27ec8Sbaban 		    &req->id1name);
3619e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS)
3620e8c27ec8Sbaban 			goto out;
3621e8c27ec8Sbaban 	} else if (req->id1.idmap_id_u.uid == SENTINEL_PID) {
3622e8c27ec8Sbaban 		/* Get pid from name service */
3623e8c27ec8Sbaban 		retcode = ns_lookup_byname(req->id1name, NULL, &req->id1);
3624e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS) {
3625e8c27ec8Sbaban 			gen_localsid_on_err = FALSE;
3626e8c27ec8Sbaban 			goto out;
3627e8c27ec8Sbaban 		}
3628e8c27ec8Sbaban 	}
3629e8c27ec8Sbaban 
3630e8c27ec8Sbaban 	/* Use unixname to evaluate local name-based mapping rules */
3631e8c27ec8Sbaban 	retcode = name_based_mapping_pid2sid(db, cache, req->id1name, is_user,
3632c5c4113dSnw141292 	    req, res);
3633c5c4113dSnw141292 	if (retcode == IDMAP_ERR_NOTFOUND) {
3634c5c4113dSnw141292 		retcode = generate_localsid(req, res, is_user);
3635e8c27ec8Sbaban 		gen_localsid_on_err = FALSE;
3636e8c27ec8Sbaban 	}
3637c5c4113dSnw141292 
3638c5c4113dSnw141292 out:
3639c5c4113dSnw141292 	res->retcode = idmap_stat4prot(retcode);
3640e8c27ec8Sbaban 	if (res->retcode != IDMAP_SUCCESS) {
3641e8c27ec8Sbaban 		req->direction = _IDMAP_F_DONE;
3642e8c27ec8Sbaban 		if (gen_localsid_on_err == TRUE)
3643e8c27ec8Sbaban 			(void) generate_localsid(req, res, is_user);
3644e8c27ec8Sbaban 	}
3645e8c27ec8Sbaban 	if (!ARE_WE_DONE(req->direction))
3646e8c27ec8Sbaban 		state->pid2sid_done = FALSE;
3647c5c4113dSnw141292 	return (retcode);
3648c5c4113dSnw141292 }
3649c5c4113dSnw141292 
3650cd37da74Snw141292 static
3651cd37da74Snw141292 idmap_retcode
3652e8c27ec8Sbaban ad_lookup_by_sid(lookup_state_t *state,
3653e8c27ec8Sbaban 		const char *sidprefix, idmap_rid_t rid, int eunixtype,
3654e8c27ec8Sbaban 		char **name, char **domain, int *type, char **unixname)
3655cd37da74Snw141292 {
3656e8c27ec8Sbaban 	int			retries = 0;
3657c5c4113dSnw141292 	idmap_query_state_t	*qs = NULL;
3658c5c4113dSnw141292 	idmap_retcode		rc, retcode;
3659c5c4113dSnw141292 
3660e8c27ec8Sbaban retry:
3661e8c27ec8Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, 1, &qs);
3662e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
3663*0dcc7149Snw141292 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
3664*0dcc7149Snw141292 			goto retry;
3665*0dcc7149Snw141292 		degrade_svc("failed to create request for AD lookup by SID");
3666e8c27ec8Sbaban 		return (retcode);
3667c5c4113dSnw141292 	}
3668c5c4113dSnw141292 
3669c8e26105Sjp151216 	restore_svc();
3670c8e26105Sjp151216 
3671e8c27ec8Sbaban 	if (state != NULL)
3672e8c27ec8Sbaban 		idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
3673e8c27ec8Sbaban 		    state->ad_unixgroup_attr);
3674c5c4113dSnw141292 
3675e8c27ec8Sbaban 	retcode = idmap_sid2name_batch_add1(qs, sidprefix, &rid, eunixtype,
3676e8c27ec8Sbaban 	    name, domain, type, unixname, &rc);
3677e8c27ec8Sbaban 
3678e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
3679e8c27ec8Sbaban 		idmap_lookup_release_batch(&qs);
3680e8c27ec8Sbaban 	else
3681*0dcc7149Snw141292 		retcode = idmap_lookup_batch_end(&qs);
3682e8c27ec8Sbaban 
3683e8c27ec8Sbaban 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
3684e8c27ec8Sbaban 		goto retry;
3685e8c27ec8Sbaban 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
3686*0dcc7149Snw141292 		degrade_svc("some AD lookups timed out repeatedly");
3687c5c4113dSnw141292 
3688e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
3689e8c27ec8Sbaban 		idmapdlog(LOG_NOTICE, "AD lookup by SID failed");
3690c5c4113dSnw141292 		return (retcode);
3691c5c4113dSnw141292 	}
3692e8c27ec8Sbaban 	return (rc);
3693e8c27ec8Sbaban }
3694c5c4113dSnw141292 
3695cd37da74Snw141292 static
3696cd37da74Snw141292 int
3697651c0131Sbaban copy_mapping_request(idmap_mapping *mapping, idmap_mapping *request)
3698c5c4113dSnw141292 {
3699651c0131Sbaban 	(void) memset(mapping, 0, sizeof (*mapping));
3700651c0131Sbaban 
3701c5c4113dSnw141292 	mapping->flag = request->flag;
3702e8c27ec8Sbaban 	mapping->direction = _IDMAP_F_DONE;
3703651c0131Sbaban 	mapping->id2.idtype = request->id2.idtype;
3704c5c4113dSnw141292 
3705c5c4113dSnw141292 	mapping->id1.idtype = request->id1.idtype;
3706cd37da74Snw141292 	if (IS_REQUEST_SID(*request, 1)) {
3707c5c4113dSnw141292 		mapping->id1.idmap_id_u.sid.rid =
3708c5c4113dSnw141292 		    request->id1.idmap_id_u.sid.rid;
3709651c0131Sbaban 		if (!EMPTY_STRING(request->id1.idmap_id_u.sid.prefix)) {
3710c5c4113dSnw141292 			mapping->id1.idmap_id_u.sid.prefix =
3711c5c4113dSnw141292 			    strdup(request->id1.idmap_id_u.sid.prefix);
3712651c0131Sbaban 			if (mapping->id1.idmap_id_u.sid.prefix == NULL)
37138e228215Sdm199847 				goto errout;
3714651c0131Sbaban 		}
3715c5c4113dSnw141292 	} else {
3716c5c4113dSnw141292 		mapping->id1.idmap_id_u.uid = request->id1.idmap_id_u.uid;
3717c5c4113dSnw141292 	}
3718c5c4113dSnw141292 
3719e8c27ec8Sbaban 	if (!EMPTY_STRING(request->id1domain)) {
37208e228215Sdm199847 		mapping->id1domain = strdup(request->id1domain);
37218e228215Sdm199847 		if (mapping->id1domain == NULL)
37228e228215Sdm199847 			goto errout;
3723e8c27ec8Sbaban 	}
3724c5c4113dSnw141292 
3725e8c27ec8Sbaban 	if (!EMPTY_STRING(request->id1name)) {
37268e228215Sdm199847 		mapping->id1name = strdup(request->id1name);
37278e228215Sdm199847 		if (mapping->id1name == NULL)
37288e228215Sdm199847 			goto errout;
3729e8c27ec8Sbaban 	}
3730c5c4113dSnw141292 
3731651c0131Sbaban 	/* We don't need the rest of the request i.e request->id2 */
3732651c0131Sbaban 	return (0);
3733c5c4113dSnw141292 
3734651c0131Sbaban errout:
37358e228215Sdm199847 	if (mapping->id1.idmap_id_u.sid.prefix != NULL)
3736651c0131Sbaban 		free(mapping->id1.idmap_id_u.sid.prefix);
37378e228215Sdm199847 	if (mapping->id1domain != NULL)
37388e228215Sdm199847 		free(mapping->id1domain);
37398e228215Sdm199847 	if (mapping->id1name != NULL)
37408e228215Sdm199847 		free(mapping->id1name);
3741651c0131Sbaban 
3742651c0131Sbaban 	(void) memset(mapping, 0, sizeof (*mapping));
3743651c0131Sbaban 	return (-1);
3744c5c4113dSnw141292 }
3745c5c4113dSnw141292 
3746c5c4113dSnw141292 
3747c5c4113dSnw141292 idmap_retcode
3748c5c4113dSnw141292 get_w2u_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
3749cd37da74Snw141292 		idmap_mapping *mapping)
3750cd37da74Snw141292 {
3751c5c4113dSnw141292 	idmap_id_res	idres;
3752c5c4113dSnw141292 	lookup_state_t	state;
3753dd5829d1Sbaban 	char		*cp;
3754c5c4113dSnw141292 	idmap_retcode	retcode;
3755c5c4113dSnw141292 	const char	*winname, *windomain;
3756c5c4113dSnw141292 
3757c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
3758c5c4113dSnw141292 	(void) memset(&state, 0, sizeof (state));
3759c5c4113dSnw141292 
3760e8c27ec8Sbaban 	/* Get directory-based name mapping info */
3761e8c27ec8Sbaban 	retcode = get_ds_namemap_type(&state);
3762e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
3763c5c4113dSnw141292 		goto out;
3764c5c4113dSnw141292 
3765e8c27ec8Sbaban 	/*
3766e8c27ec8Sbaban 	 * Copy data from "request" to "mapping". Note that
3767e8c27ec8Sbaban 	 * empty strings are not copied from "request" to
3768e8c27ec8Sbaban 	 * "mapping" and therefore the coresponding strings in
3769e8c27ec8Sbaban 	 * "mapping" will be NULL. This eliminates having to
3770e8c27ec8Sbaban 	 * check for empty strings henceforth.
3771e8c27ec8Sbaban 	 */
3772651c0131Sbaban 	if (copy_mapping_request(mapping, request) < 0) {
3773651c0131Sbaban 		retcode = IDMAP_ERR_MEMORY;
3774651c0131Sbaban 		goto out;
3775651c0131Sbaban 	}
3776c5c4113dSnw141292 
37778e228215Sdm199847 	winname = mapping->id1name;
37788e228215Sdm199847 	windomain = mapping->id1domain;
3779c5c4113dSnw141292 
3780e8c27ec8Sbaban 	if (winname == NULL && windomain != NULL) {
3781c5c4113dSnw141292 		retcode = IDMAP_ERR_ARG;
3782c5c4113dSnw141292 		goto out;
3783c5c4113dSnw141292 	}
3784c5c4113dSnw141292 
3785e8c27ec8Sbaban 	/* Need atleast winname or sid to proceed */
3786e8c27ec8Sbaban 	if (winname == NULL && mapping->id1.idmap_id_u.sid.prefix == NULL) {
3787e8c27ec8Sbaban 		retcode = IDMAP_ERR_ARG;
3788e8c27ec8Sbaban 		goto out;
3789e8c27ec8Sbaban 	}
3790e8c27ec8Sbaban 
3791e8c27ec8Sbaban 	/*
3792e8c27ec8Sbaban 	 * If domainname is not given but we have a fully qualified
3793e8c27ec8Sbaban 	 * winname then extract the domainname from the winname,
3794e8c27ec8Sbaban 	 * otherwise use the default_domain from the config
3795e8c27ec8Sbaban 	 */
3796e8c27ec8Sbaban 	if (winname != NULL && windomain == NULL) {
37978e228215Sdm199847 		retcode = IDMAP_SUCCESS;
3798dd5829d1Sbaban 		if ((cp = strchr(winname, '@')) != NULL) {
3799dd5829d1Sbaban 			*cp = '\0';
38008e228215Sdm199847 			mapping->id1domain = strdup(cp + 1);
38018e228215Sdm199847 			if (mapping->id1domain == NULL)
38028e228215Sdm199847 				retcode = IDMAP_ERR_MEMORY;
3803e8c27ec8Sbaban 		} else if (lookup_wksids_name2sid(winname, NULL, NULL, NULL,
3804e8c27ec8Sbaban 		    NULL) != IDMAP_SUCCESS) {
3805e8c27ec8Sbaban 			/* well-known SIDs don't need domain */
38068e228215Sdm199847 			RDLOCK_CONFIG();
3807c8e26105Sjp151216 			if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
38088e228215Sdm199847 				mapping->id1domain =
38098e228215Sdm199847 				    strdup(_idmapdstate.cfg->
3810c8e26105Sjp151216 				    pgcfg.default_domain);
38118e228215Sdm199847 				if (mapping->id1domain == NULL)
38128e228215Sdm199847 					retcode = IDMAP_ERR_MEMORY;
3813e8c27ec8Sbaban 			} else {
3814e8c27ec8Sbaban 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
38158e228215Sdm199847 			}
3816c5c4113dSnw141292 			UNLOCK_CONFIG();
38178e228215Sdm199847 		}
3818c5c4113dSnw141292 		if (retcode != IDMAP_SUCCESS)
3819c5c4113dSnw141292 			goto out;
3820c5c4113dSnw141292 	}
3821c5c4113dSnw141292 
3822e8c27ec8Sbaban 	/*
3823e8c27ec8Sbaban 	 * First pass looks up the well-known SIDs table and cache
3824e8c27ec8Sbaban 	 * and handles localSIDs
3825e8c27ec8Sbaban 	 */
3826c5c4113dSnw141292 	state.sid2pid_done = TRUE;
3827c5c4113dSnw141292 	retcode = sid2pid_first_pass(&state, cache, mapping, &idres);
3828c5c4113dSnw141292 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
3829c5c4113dSnw141292 		goto out;
3830c5c4113dSnw141292 
3831e8c27ec8Sbaban 	/* AD lookup by winname or by sid */
3832e8c27ec8Sbaban 	if (state.ad_nqueries > 0) {
3833e8c27ec8Sbaban 		retcode = ad_lookup(&state, mapping, &idres, 1, 1, 0);
3834e8c27ec8Sbaban 		if (IDMAP_ERROR(retcode))
3835e8c27ec8Sbaban 			goto out;
3836c5c4113dSnw141292 	}
3837c5c4113dSnw141292 
3838e8c27ec8Sbaban 	/*
3839e8c27ec8Sbaban 	 * If nldap-based name mapping is enabled then lookup native LDAP
3840e8c27ec8Sbaban 	 * directory service by winname to get pid and unixname. Ignore
3841e8c27ec8Sbaban 	 * non-fatal errors in which case we simply fallback to evaluating
3842e8c27ec8Sbaban 	 * local name-based mapping rules.
3843e8c27ec8Sbaban 	 */
3844e8c27ec8Sbaban 	if (mapping->id1name != NULL && NLDAP_MODE(idres.id.idtype, (&state))) {
3845e8c27ec8Sbaban 		retcode = nldap_lookup(mapping, &idres, 1, 1);
3846e8c27ec8Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
3847e8c27ec8Sbaban 			goto out;
3848e8c27ec8Sbaban 		idres.retcode = IDMAP_SUCCESS;
3849e8c27ec8Sbaban 	}
3850e8c27ec8Sbaban 
3851e8c27ec8Sbaban 	/* Next pass performs name-based mapping and ephemeral mapping. */
3852c5c4113dSnw141292 	state.sid2pid_done = TRUE;
3853c5c4113dSnw141292 	retcode = sid2pid_second_pass(&state, cache, db, mapping, &idres);
3854c5c4113dSnw141292 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
3855c5c4113dSnw141292 		goto out;
3856c5c4113dSnw141292 
3857c5c4113dSnw141292 	/* Update cache */
3858c5c4113dSnw141292 	(void) update_cache_sid2pid(&state, cache, mapping, &idres);
3859c5c4113dSnw141292 
3860c5c4113dSnw141292 out:
3861e8c27ec8Sbaban 	/*
3862e8c27ec8Sbaban 	 * Note that "mapping" is returned to the client. Therefore
3863e8c27ec8Sbaban 	 * copy whatever we have in "idres" to mapping->id2 and
3864e8c27ec8Sbaban 	 * free idres.
3865e8c27ec8Sbaban 	 */
3866c5c4113dSnw141292 	mapping->direction = idres.direction;
3867c5c4113dSnw141292 	mapping->id2 = idres.id;
3868c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
3869e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
387062c60062Sbaban 		mapping->id2.idmap_id_u.uid = UID_NOBODY;
3871c5c4113dSnw141292 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
3872e8c27ec8Sbaban 	cleanup_lookup_state(&state);
3873c5c4113dSnw141292 	return (retcode);
3874c5c4113dSnw141292 }
3875c5c4113dSnw141292 
3876c5c4113dSnw141292 idmap_retcode
3877c5c4113dSnw141292 get_u2w_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
3878cd37da74Snw141292 		idmap_mapping *mapping, int is_user)
3879cd37da74Snw141292 {
3880c5c4113dSnw141292 	idmap_id_res	idres;
3881c5c4113dSnw141292 	lookup_state_t	state;
3882c5c4113dSnw141292 	idmap_retcode	retcode;
3883e8c27ec8Sbaban 	char		*canonname;
3884e8c27ec8Sbaban 	int		is_wuser;
3885c5c4113dSnw141292 
3886c5c4113dSnw141292 	/*
3887c5c4113dSnw141292 	 * In order to re-use the pid2sid code, we convert
3888c5c4113dSnw141292 	 * our input data into structs that are expected by
3889c5c4113dSnw141292 	 * pid2sid_first_pass.
3890c5c4113dSnw141292 	 */
3891c5c4113dSnw141292 
3892c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
3893c5c4113dSnw141292 	(void) memset(&state, 0, sizeof (state));
3894c5c4113dSnw141292 
3895e8c27ec8Sbaban 	/* Get directory-based name mapping info */
3896e8c27ec8Sbaban 	retcode = get_ds_namemap_type(&state);
3897e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
3898e8c27ec8Sbaban 		goto out;
3899e8c27ec8Sbaban 
3900e8c27ec8Sbaban 	/*
3901e8c27ec8Sbaban 	 * Copy data from "request" to "mapping". Note that
3902e8c27ec8Sbaban 	 * empty strings are not copied from "request" to
3903e8c27ec8Sbaban 	 * "mapping" and therefore the coresponding strings in
3904e8c27ec8Sbaban 	 * "mapping" will be NULL. This eliminates having to
3905e8c27ec8Sbaban 	 * check for empty strings henceforth.
3906e8c27ec8Sbaban 	 */
3907651c0131Sbaban 	if (copy_mapping_request(mapping, request) < 0) {
3908651c0131Sbaban 		retcode = IDMAP_ERR_MEMORY;
3909651c0131Sbaban 		goto out;
3910651c0131Sbaban 	}
3911c5c4113dSnw141292 
3912e8c27ec8Sbaban 	/*
3913e8c27ec8Sbaban 	 * For unix to windows mapping request, we need atleast a
3914e8c27ec8Sbaban 	 * unixname or uid/gid to proceed
3915e8c27ec8Sbaban 	 */
3916e8c27ec8Sbaban 	if (mapping->id1name == NULL &&
3917cf5b5989Sdm199847 	    mapping->id1.idmap_id_u.uid == SENTINEL_PID) {
3918c5c4113dSnw141292 		retcode = IDMAP_ERR_ARG;
3919c5c4113dSnw141292 		goto out;
3920c5c4113dSnw141292 	}
3921c5c4113dSnw141292 
3922e8c27ec8Sbaban 	/* First pass looks up cache and well-known SIDs */
3923e8c27ec8Sbaban 	state.pid2sid_done = TRUE;
3924e8c27ec8Sbaban 	retcode = pid2sid_first_pass(&state, cache, mapping, &idres,
3925e8c27ec8Sbaban 	    is_user, 1);
3926e8c27ec8Sbaban 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
3927c5c4113dSnw141292 		goto out;
3928e8c27ec8Sbaban 
3929e8c27ec8Sbaban 	if (state.nldap_nqueries > 0) {
3930e8c27ec8Sbaban 		/*
3931e8c27ec8Sbaban 		 * This means directory-based name mapping (nldap or mixed
3932e8c27ec8Sbaban 		 * mode) is enabled. Lookup native LDAP directory service
3933e8c27ec8Sbaban 		 * by unixname or pid to get the winname. Ignore non-fatal
3934e8c27ec8Sbaban 		 * errors in which case we simply fallback to local name
3935e8c27ec8Sbaban 		 * based mapping rules.
3936e8c27ec8Sbaban 		 */
3937e8c27ec8Sbaban 		retcode = nldap_lookup(mapping, &idres, 0, 0);
3938e8c27ec8Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
3939c5c4113dSnw141292 			goto out;
3940e8c27ec8Sbaban 		idres.retcode = IDMAP_SUCCESS;
3941e8c27ec8Sbaban 
3942e8c27ec8Sbaban 		/*
3943e8c27ec8Sbaban 		 * If we've winname then get SID. We use lookup_name2sid()
3944e8c27ec8Sbaban 		 * instead of ad_lookup() in order to first resolve name2sid
3945e8c27ec8Sbaban 		 * using well-known SIDs table and name_cache before trying
3946e8c27ec8Sbaban 		 * AD.
3947e8c27ec8Sbaban 		 */
3948e8c27ec8Sbaban 		if (mapping->id2name != NULL) {
3949e8c27ec8Sbaban 			canonname = NULL;
3950e8c27ec8Sbaban 			is_wuser = -1;
3951e8c27ec8Sbaban 			retcode = lookup_name2sid(cache, mapping->id2name,
3952e8c27ec8Sbaban 			    mapping->id2domain, &is_wuser, &canonname,
3953e8c27ec8Sbaban 			    &idres.id.idmap_id_u.sid.prefix,
3954e8c27ec8Sbaban 			    &idres.id.idmap_id_u.sid.rid, mapping);
3955e8c27ec8Sbaban 			if (canonname != NULL) {
3956e8c27ec8Sbaban 				free(mapping->id2name);
3957e8c27ec8Sbaban 				mapping->id2name = canonname;
3958c5c4113dSnw141292 			}
3959e8c27ec8Sbaban 			if (retcode == IDMAP_SUCCESS)
3960e8c27ec8Sbaban 				idres.id.idtype = is_wuser ? IDMAP_USID :
3961e8c27ec8Sbaban 				    IDMAP_GSID;
3962e8c27ec8Sbaban 			idres.retcode = retcode;
3963c5c4113dSnw141292 		}
3964e8c27ec8Sbaban 	} else if (state.ad_nqueries > 0) {
3965e8c27ec8Sbaban 		/*
3966e8c27ec8Sbaban 		 * This means AD-based name mapping is enabled.
3967e8c27ec8Sbaban 		 * Lookup AD by unixname to get winname and sid.
3968e8c27ec8Sbaban 		 * Ignore non-fatal errors in which case we simply fallback
3969e8c27ec8Sbaban 		 * to local name based mapping rules.
3970e8c27ec8Sbaban 		 */
3971e8c27ec8Sbaban 		retcode = ad_lookup(&state, mapping, &idres, 0, 0, 1);
3972e8c27ec8Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
3973e8c27ec8Sbaban 			goto out;
3974e8c27ec8Sbaban 		idres.retcode = IDMAP_SUCCESS;
3975c5c4113dSnw141292 	}
3976c5c4113dSnw141292 
3977e8c27ec8Sbaban 	/*
3978e8c27ec8Sbaban 	 * Next pass processes the result of the preceding passes/lookups.
3979e8c27ec8Sbaban 	 * It returns if there's nothing more to be done otherwise it
3980e8c27ec8Sbaban 	 * evaluates local name-based mapping rules
3981e8c27ec8Sbaban 	 */
3982c5c4113dSnw141292 	state.pid2sid_done = TRUE;
3983e8c27ec8Sbaban 	retcode = pid2sid_second_pass(&state, cache, db, mapping, &idres,
3984e8c27ec8Sbaban 	    is_user);
3985c5c4113dSnw141292 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
3986c5c4113dSnw141292 		goto out;
3987c5c4113dSnw141292 
3988c5c4113dSnw141292 	/* Update cache */
3989c5c4113dSnw141292 	(void) update_cache_pid2sid(&state, cache, mapping, &idres);
3990c5c4113dSnw141292 
3991c5c4113dSnw141292 out:
3992e8c27ec8Sbaban 	/*
3993e8c27ec8Sbaban 	 * Note that "mapping" is returned to the client. Therefore
3994e8c27ec8Sbaban 	 * copy whatever we have in "idres" to mapping->id2 and
3995e8c27ec8Sbaban 	 * free idres.
3996e8c27ec8Sbaban 	 */
3997c5c4113dSnw141292 	mapping->direction = idres.direction;
3998c5c4113dSnw141292 	mapping->id2 = idres.id;
3999c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
4000c5c4113dSnw141292 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
4001e8c27ec8Sbaban 	cleanup_lookup_state(&state);
4002e8c27ec8Sbaban 	return (retcode);
4003e8c27ec8Sbaban }
4004e8c27ec8Sbaban 
4005e8c27ec8Sbaban static
4006e8c27ec8Sbaban idmap_retcode
4007e8c27ec8Sbaban ad_lookup_by_unixname(lookup_state_t *state,
4008e8c27ec8Sbaban 		const char *unixname, int is_user, int is_wuser,
4009e8c27ec8Sbaban 		char **sidprefix, idmap_rid_t *rid, char **winname,
4010e8c27ec8Sbaban 		char **domain, int *type)
4011e8c27ec8Sbaban {
4012e8c27ec8Sbaban 	/* Lookup AD by unixname */
4013e8c27ec8Sbaban 	int			retries = 0;
4014e8c27ec8Sbaban 	idmap_query_state_t	*qs = NULL;
4015e8c27ec8Sbaban 	idmap_retcode		rc, retcode;
4016e8c27ec8Sbaban 
4017e8c27ec8Sbaban retry:
4018e8c27ec8Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, 1, &qs);
4019e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
4020*0dcc7149Snw141292 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
4021*0dcc7149Snw141292 			goto retry;
4022*0dcc7149Snw141292 		degrade_svc("failed to create request for AD lookup "
4023*0dcc7149Snw141292 		    "by unixname");
4024e8c27ec8Sbaban 		return (IDMAP_ERR_INTERNAL);
4025e8c27ec8Sbaban 	}
4026e8c27ec8Sbaban 
4027e8c27ec8Sbaban 	restore_svc();
4028e8c27ec8Sbaban 
4029e8c27ec8Sbaban 	if (state != NULL)
4030e8c27ec8Sbaban 		idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
4031e8c27ec8Sbaban 		    state->ad_unixgroup_attr);
4032e8c27ec8Sbaban 
4033e8c27ec8Sbaban 	retcode = idmap_unixname2sid_batch_add1(qs, unixname, is_user,
4034e8c27ec8Sbaban 	    is_wuser, sidprefix, rid, winname, domain, type, &rc);
4035e8c27ec8Sbaban 
4036e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
4037e8c27ec8Sbaban 		idmap_lookup_release_batch(&qs);
4038e8c27ec8Sbaban 	else
4039*0dcc7149Snw141292 		retcode = idmap_lookup_batch_end(&qs);
4040e8c27ec8Sbaban 
4041e8c27ec8Sbaban 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
4042e8c27ec8Sbaban 		goto retry;
4043e8c27ec8Sbaban 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
4044*0dcc7149Snw141292 		degrade_svc("some AD lookups timed out repeatedly");
4045e8c27ec8Sbaban 
4046e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
4047e8c27ec8Sbaban 		idmapdlog(LOG_NOTICE, "AD lookup by unixname failed");
4048e8c27ec8Sbaban 		return (retcode);
4049e8c27ec8Sbaban 	}
4050e8c27ec8Sbaban 	return (rc);
4051e8c27ec8Sbaban }
4052e8c27ec8Sbaban 
4053e8c27ec8Sbaban /*
4054e8c27ec8Sbaban  * This function is called whenever a non-batched AD lookup needs to be
4055e8c27ec8Sbaban  * done (e.g. get_w2u_mapping() and get_u2w_mapping()). It's already
4056e8c27ec8Sbaban  * determined by the caller before calling this function that AD lookup is
4057e8c27ec8Sbaban  * needed and has already searched the well-known SIDs table and name_cache.
4058e8c27ec8Sbaban  */
4059e8c27ec8Sbaban static
4060e8c27ec8Sbaban idmap_retcode
4061e8c27ec8Sbaban ad_lookup(lookup_state_t *state, idmap_mapping *req, idmap_id_res *res,
4062e8c27ec8Sbaban 		int w2u, int getunixattr, int byunixattr)
4063e8c27ec8Sbaban {
4064e8c27ec8Sbaban 	idmap_retcode	retcode;
4065e8c27ec8Sbaban 	int		type, eunixtype, is_user, is_wuser;
4066e8c27ec8Sbaban 	char		*canonname = NULL;
4067e8c27ec8Sbaban 
4068e8c27ec8Sbaban 	if (w2u) {
4069e8c27ec8Sbaban 		/*
4070e8c27ec8Sbaban 		 * win2unix lookup requests (get_w2u_mapping()) calls this
4071e8c27ec8Sbaban 		 * function to lookup by sid OR winname and to retrieve
4072e8c27ec8Sbaban 		 * SID, winname, sidtype (user or group) and unixnames
4073e8c27ec8Sbaban 		 * from AD.
4074e8c27ec8Sbaban 		 */
4075e8c27ec8Sbaban 
4076e8c27ec8Sbaban 		/* Set the expected unixtype */
4077e8c27ec8Sbaban 		if (res->id.idtype == IDMAP_UID)
4078e8c27ec8Sbaban 			eunixtype = _IDMAP_T_USER;
4079e8c27ec8Sbaban 		else if (res->id.idtype == IDMAP_GID)
4080e8c27ec8Sbaban 			eunixtype = _IDMAP_T_GROUP;
4081e8c27ec8Sbaban 		else
4082e8c27ec8Sbaban 			eunixtype = _IDMAP_T_UNDEF;
4083e8c27ec8Sbaban 
4084e8c27ec8Sbaban 		if (req->id1.idmap_id_u.sid.prefix != NULL) {
4085e8c27ec8Sbaban 			/* AD lookup by sid */
4086e8c27ec8Sbaban 			retcode = ad_lookup_by_sid(
4087e8c27ec8Sbaban 			    state, req->id1.idmap_id_u.sid.prefix,
4088e8c27ec8Sbaban 			    req->id1.idmap_id_u.sid.rid, eunixtype,
4089e8c27ec8Sbaban 			    (req->id1name == NULL) ? &req->id1name : NULL,
4090e8c27ec8Sbaban 			    (req->id1domain == NULL) ? &req->id1domain : NULL,
4091e8c27ec8Sbaban 			    &type, (getunixattr && req->id2name == NULL)
4092e8c27ec8Sbaban 			    ? &req->id2name : NULL);
4093e8c27ec8Sbaban 		} else {
4094e8c27ec8Sbaban 			assert(req->id1name != NULL);
4095e8c27ec8Sbaban 			/* AD lookup by winname */
4096e8c27ec8Sbaban 			retcode = ad_lookup_by_winname(
4097e8c27ec8Sbaban 			    state, req->id1name, req->id1domain, eunixtype,
4098e8c27ec8Sbaban 			    &canonname, &req->id1.idmap_id_u.sid.prefix,
4099e8c27ec8Sbaban 			    &req->id1.idmap_id_u.sid.rid, &type,
4100e8c27ec8Sbaban 			    (getunixattr && req->id2name == NULL)
4101e8c27ec8Sbaban 			    ? &req->id2name : NULL);
4102e8c27ec8Sbaban 
4103e8c27ec8Sbaban 			if (canonname != NULL) {
4104e8c27ec8Sbaban 				free(req->id1name);
4105e8c27ec8Sbaban 				req->id1name = canonname;
4106e8c27ec8Sbaban 			}
4107e8c27ec8Sbaban 		}
4108e8c27ec8Sbaban 		if (retcode == IDMAP_SUCCESS) {
4109e8c27ec8Sbaban 			switch (type) {
4110e8c27ec8Sbaban 			case _IDMAP_T_USER:
4111e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
4112e8c27ec8Sbaban 					res->id.idtype = IDMAP_UID;
4113e8c27ec8Sbaban 				req->id1.idtype = IDMAP_USID;
4114e8c27ec8Sbaban 				break;
4115e8c27ec8Sbaban 			case _IDMAP_T_GROUP:
4116e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
4117e8c27ec8Sbaban 					res->id.idtype = IDMAP_GID;
4118e8c27ec8Sbaban 				req->id1.idtype = IDMAP_GSID;
4119e8c27ec8Sbaban 				break;
4120e8c27ec8Sbaban 			default:
4121e8c27ec8Sbaban 				return (IDMAP_ERR_SID);
4122e8c27ec8Sbaban 			}
4123e8c27ec8Sbaban 		}
4124e8c27ec8Sbaban 		return (retcode);
4125e8c27ec8Sbaban 	}
4126e8c27ec8Sbaban 
4127e8c27ec8Sbaban 	/*
4128e8c27ec8Sbaban 	 * unix2win lookup requests (get_u2w_mapping()) calls this
4129e8c27ec8Sbaban 	 * function to lookup AD by unixname and to retrieve
4130e8c27ec8Sbaban 	 * SID, winname, and sidtype (user or group) from AD.
4131e8c27ec8Sbaban 	 */
4132e8c27ec8Sbaban 
4133e8c27ec8Sbaban 	/* Set the expected unixtype */
4134e8c27ec8Sbaban 	eunixtype = (req->id1.idtype == IDMAP_UID) ? _IDMAP_T_USER :
4135e8c27ec8Sbaban 	    _IDMAP_T_GROUP;
4136e8c27ec8Sbaban 
4137e8c27ec8Sbaban 	if (byunixattr) {
4138e8c27ec8Sbaban 		/* AD lookup by unixname */
4139e8c27ec8Sbaban 		is_user = (IS_REQUEST_UID(*req)) ? 1 : 0;
4140e8c27ec8Sbaban 		if (res->id.idtype == IDMAP_USID)
4141e8c27ec8Sbaban 			is_wuser = 1;
4142e8c27ec8Sbaban 		else if (res->id.idtype == IDMAP_GSID)
4143e8c27ec8Sbaban 			is_wuser = 0;
4144e8c27ec8Sbaban 		else
4145e8c27ec8Sbaban 			is_wuser = is_user;
4146e8c27ec8Sbaban 		retcode = ad_lookup_by_unixname(
4147e8c27ec8Sbaban 		    state, req->id1name, is_user, is_wuser,
4148e8c27ec8Sbaban 		    (res->id.idmap_id_u.sid.prefix == NULL) ?
4149e8c27ec8Sbaban 		    &res->id.idmap_id_u.sid.prefix : NULL,
4150e8c27ec8Sbaban 		    (res->id.idmap_id_u.sid.prefix == NULL) ?
4151e8c27ec8Sbaban 		    &res->id.idmap_id_u.sid.rid : NULL,
4152e8c27ec8Sbaban 		    (req->id2name == NULL) ? &req->id2name : NULL,
4153e8c27ec8Sbaban 		    (req->id2domain == NULL) ? &req->id2domain : NULL, NULL);
4154e8c27ec8Sbaban 	} else if (res->id.idmap_id_u.sid.prefix != NULL) {
4155e8c27ec8Sbaban 		/* AD lookup by sid */
4156e8c27ec8Sbaban 		retcode = ad_lookup_by_sid(
4157e8c27ec8Sbaban 		    state, res->id.idmap_id_u.sid.prefix,
4158e8c27ec8Sbaban 		    res->id.idmap_id_u.sid.rid, eunixtype,
4159e8c27ec8Sbaban 		    (req->id2name == NULL) ? &req->id2name : NULL,
4160e8c27ec8Sbaban 		    (req->id2domain == NULL) ? &req->id2domain : NULL,
4161e8c27ec8Sbaban 		    NULL, (getunixattr && req->id1name == NULL)
4162e8c27ec8Sbaban 		    ? &req->id1name : NULL);
4163e8c27ec8Sbaban 	} else {
4164e8c27ec8Sbaban 		/* AD lookup by winname */
4165e8c27ec8Sbaban 		assert(req->id2name != NULL);
4166e8c27ec8Sbaban 		retcode = ad_lookup_by_winname(
4167e8c27ec8Sbaban 		    state, req->id2name, req->id2domain, eunixtype,
4168e8c27ec8Sbaban 		    &canonname, &res->id.idmap_id_u.sid.prefix,
4169e8c27ec8Sbaban 		    &res->id.idmap_id_u.sid.rid, NULL,
4170e8c27ec8Sbaban 		    (getunixattr && req->id1name == NULL)
4171e8c27ec8Sbaban 		    ? &req->id1name : NULL);
4172e8c27ec8Sbaban 
4173e8c27ec8Sbaban 		if (canonname != NULL) {
4174e8c27ec8Sbaban 			free(req->id2name);
4175e8c27ec8Sbaban 			req->id2name = canonname;
4176e8c27ec8Sbaban 		}
4177e8c27ec8Sbaban 	}
4178e8c27ec8Sbaban 
4179e8c27ec8Sbaban 	if (retcode == IDMAP_SUCCESS) {
4180e8c27ec8Sbaban 		switch (type) {
4181e8c27ec8Sbaban 		case _IDMAP_T_USER:
4182e8c27ec8Sbaban 			if (res->id.idtype == IDMAP_SID)
4183e8c27ec8Sbaban 				res->id.idtype = IDMAP_USID;
4184e8c27ec8Sbaban 			break;
4185e8c27ec8Sbaban 		case _IDMAP_T_GROUP:
4186e8c27ec8Sbaban 			if (res->id.idtype == IDMAP_SID)
4187e8c27ec8Sbaban 				res->id.idtype = IDMAP_GSID;
4188e8c27ec8Sbaban 			break;
4189e8c27ec8Sbaban 		default:
4190e8c27ec8Sbaban 			return (IDMAP_ERR_SID);
4191e8c27ec8Sbaban 		}
4192e8c27ec8Sbaban 	}
4193c5c4113dSnw141292 	return (retcode);
4194c5c4113dSnw141292 }
4195