xref: /titanic_44/usr/src/cmd/idmap/idmapd/dbutils.c (revision 2b3ecdeb32aab9a01194518a0459b6515b9da9bb)
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 
32c5c4113dSnw141292 #include <stdio.h>
33c5c4113dSnw141292 #include <stdlib.h>
34c5c4113dSnw141292 #include <string.h>
35c5c4113dSnw141292 #include <errno.h>
36c5c4113dSnw141292 #include <sys/types.h>
37c5c4113dSnw141292 #include <sys/stat.h>
38c5c4113dSnw141292 #include <rpc/rpc.h>
39c5c4113dSnw141292 #include <sys/sid.h>
40c5c4113dSnw141292 #include <time.h>
41c5c4113dSnw141292 #include <pwd.h>
42c5c4113dSnw141292 #include <grp.h>
4384decf41Sjp151216 #include <pthread.h>
4484decf41Sjp151216 #include <assert.h>
45cd37da74Snw141292 #include <sys/u8_textprep.h>
46c5c4113dSnw141292 
47c5c4113dSnw141292 #include "idmapd.h"
48c5c4113dSnw141292 #include "adutils.h"
49c5c4113dSnw141292 #include "string.h"
50c5c4113dSnw141292 #include "idmap_priv.h"
51cd37da74Snw141292 #include "schema.h"
52e8c27ec8Sbaban #include "nldaputils.h"
53c5c4113dSnw141292 
5484decf41Sjp151216 
55c5c4113dSnw141292 static idmap_retcode sql_compile_n_step_once(sqlite *, char *,
56c5c4113dSnw141292 		sqlite_vm **, int *, int, const char ***);
57cd37da74Snw141292 static idmap_retcode lookup_wksids_name2sid(const char *, char **, char **,
5862c60062Sbaban 		idmap_rid_t *, int *);
59e8c27ec8Sbaban static idmap_retcode ad_lookup(lookup_state_t *, idmap_mapping *,
60e8c27ec8Sbaban 		idmap_id_res *, int, int, int);
61e8c27ec8Sbaban static idmap_retcode lookup_localsid2pid(idmap_mapping *, idmap_id_res *);
62e8c27ec8Sbaban static idmap_retcode lookup_cache_name2sid(sqlite *, const char *,
63e8c27ec8Sbaban 		const char *, char **, char **, idmap_rid_t *, int *);
64e8c27ec8Sbaban 
65c5c4113dSnw141292 
66c5c4113dSnw141292 #define	EMPTY_NAME(name)	(*name == 0 || strcmp(name, "\"\"") == 0)
67c5c4113dSnw141292 
68c5c4113dSnw141292 #define	DO_NOT_ALLOC_NEW_ID_MAPPING(req)\
69c5c4113dSnw141292 		(req->flag & IDMAP_REQ_FLG_NO_NEW_ID_ALLOC)
70c5c4113dSnw141292 
71c5c4113dSnw141292 #define	AVOID_NAMESERVICE(req)\
72c5c4113dSnw141292 		(req->flag & IDMAP_REQ_FLG_NO_NAMESERVICE)
73c5c4113dSnw141292 
74e8c27ec8Sbaban #define	IS_EPHEMERAL(pid)	(pid > INT32_MAX && pid != SENTINEL_PID)
75c5c4113dSnw141292 
76c5c4113dSnw141292 #define	LOCALRID_MIN	1000
77c5c4113dSnw141292 
78c5c4113dSnw141292 
79c5c4113dSnw141292 typedef enum init_db_option {
80c5c4113dSnw141292 	FAIL_IF_CORRUPT = 0,
81c5c4113dSnw141292 	REMOVE_IF_CORRUPT = 1
82c5c4113dSnw141292 } init_db_option_t;
83c5c4113dSnw141292 
8484decf41Sjp151216 /*
85e8c27ec8Sbaban  * Data structure to store well-known SIDs and
86e8c27ec8Sbaban  * associated mappings (if any)
87e8c27ec8Sbaban  */
88e8c27ec8Sbaban typedef struct wksids_table {
89e8c27ec8Sbaban 	const char	*sidprefix;
90e8c27ec8Sbaban 	uint32_t	rid;
91e8c27ec8Sbaban 	const char	*winname;
92e8c27ec8Sbaban 	int		is_wuser;
93e8c27ec8Sbaban 	uid_t		pid;
94e8c27ec8Sbaban 	int		is_user;
95e8c27ec8Sbaban 	int		direction;
96e8c27ec8Sbaban } wksids_table_t;
97e8c27ec8Sbaban 
98e8c27ec8Sbaban /*
9984decf41Sjp151216  * Thread specfic data to hold the database handles so that the
10084decf41Sjp151216  * databaes are not opened and closed for every request. It also
10184decf41Sjp151216  * contains the sqlite busy handler structure.
10284decf41Sjp151216  */
10384decf41Sjp151216 
10484decf41Sjp151216 struct idmap_busy {
10584decf41Sjp151216 	const char *name;
10684decf41Sjp151216 	const int *delays;
10784decf41Sjp151216 	int delay_size;
10884decf41Sjp151216 	int total;
10984decf41Sjp151216 	int sec;
11084decf41Sjp151216 };
11184decf41Sjp151216 
11284decf41Sjp151216 
11384decf41Sjp151216 typedef struct idmap_tsd {
11484decf41Sjp151216 	sqlite *db_db;
11584decf41Sjp151216 	sqlite *cache_db;
11684decf41Sjp151216 	struct idmap_busy cache_busy;
11784decf41Sjp151216 	struct idmap_busy db_busy;
11884decf41Sjp151216 } idmap_tsd_t;
11984decf41Sjp151216 
12084decf41Sjp151216 
12184decf41Sjp151216 
12284decf41Sjp151216 static const int cache_delay_table[] =
12384decf41Sjp151216 		{ 1, 2, 5, 10, 15, 20, 25, 30,  35,  40,
12484decf41Sjp151216 		50,  50, 60, 70, 80, 90, 100};
12584decf41Sjp151216 
12684decf41Sjp151216 static const int db_delay_table[] =
12784decf41Sjp151216 		{ 5, 10, 15, 20, 30,  40,  55,  70, 100};
12884decf41Sjp151216 
12984decf41Sjp151216 
13084decf41Sjp151216 static pthread_key_t	idmap_tsd_key;
13184decf41Sjp151216 
13284decf41Sjp151216 void
13384decf41Sjp151216 idmap_tsd_destroy(void *key)
13484decf41Sjp151216 {
13584decf41Sjp151216 
13684decf41Sjp151216 	idmap_tsd_t	*tsd = (idmap_tsd_t *)key;
13784decf41Sjp151216 	if (tsd) {
13884decf41Sjp151216 		if (tsd->db_db)
13984decf41Sjp151216 			(void) sqlite_close(tsd->db_db);
14084decf41Sjp151216 		if (tsd->cache_db)
14184decf41Sjp151216 			(void) sqlite_close(tsd->cache_db);
14284decf41Sjp151216 		free(tsd);
14384decf41Sjp151216 	}
14484decf41Sjp151216 }
14584decf41Sjp151216 
14684decf41Sjp151216 int
147cd37da74Snw141292 idmap_init_tsd_key(void)
148cd37da74Snw141292 {
14984decf41Sjp151216 	return (pthread_key_create(&idmap_tsd_key, idmap_tsd_destroy));
15084decf41Sjp151216 }
15184decf41Sjp151216 
15284decf41Sjp151216 
15384decf41Sjp151216 
15484decf41Sjp151216 idmap_tsd_t *
15584decf41Sjp151216 idmap_get_tsd(void)
15684decf41Sjp151216 {
15784decf41Sjp151216 	idmap_tsd_t	*tsd;
15884decf41Sjp151216 
15984decf41Sjp151216 	if ((tsd = pthread_getspecific(idmap_tsd_key)) == NULL) {
16084decf41Sjp151216 		/* No thread specific data so create it */
16184decf41Sjp151216 		if ((tsd = malloc(sizeof (*tsd))) != NULL) {
16284decf41Sjp151216 			/* Initialize thread specific data */
16384decf41Sjp151216 			(void) memset(tsd, 0, sizeof (*tsd));
16484decf41Sjp151216 			/* save the trhread specific data */
16584decf41Sjp151216 			if (pthread_setspecific(idmap_tsd_key, tsd) != 0) {
16684decf41Sjp151216 				/* Can't store key */
16784decf41Sjp151216 				free(tsd);
16884decf41Sjp151216 				tsd = NULL;
16984decf41Sjp151216 			}
17084decf41Sjp151216 		} else {
17184decf41Sjp151216 			tsd = NULL;
17284decf41Sjp151216 		}
17384decf41Sjp151216 	}
17484decf41Sjp151216 
17584decf41Sjp151216 	return (tsd);
17684decf41Sjp151216 }
17784decf41Sjp151216 
178cd37da74Snw141292 /*
179cd37da74Snw141292  * A simple wrapper around u8_textprep_str() that returns the Unicode
180cd37da74Snw141292  * lower-case version of some string.  The result must be freed.
181cd37da74Snw141292  */
182cd37da74Snw141292 char *
183cd37da74Snw141292 tolower_u8(const char *s)
184cd37da74Snw141292 {
185cd37da74Snw141292 	char *res = NULL;
186cd37da74Snw141292 	char *outs;
187cd37da74Snw141292 	size_t inlen, outlen, inbytesleft, outbytesleft;
188cd37da74Snw141292 	int rc, err;
189cd37da74Snw141292 
190cd37da74Snw141292 	/*
191cd37da74Snw141292 	 * u8_textprep_str() does not allocate memory.  The input and
192cd37da74Snw141292 	 * output buffers may differ in size (though that would be more
193cd37da74Snw141292 	 * likely when normalization is done).  We have to loop over it...
194cd37da74Snw141292 	 *
195cd37da74Snw141292 	 * To improve the chances that we can avoid looping we add 10
196cd37da74Snw141292 	 * bytes of output buffer room the first go around.
197cd37da74Snw141292 	 */
198cd37da74Snw141292 	inlen = inbytesleft = strlen(s);
199cd37da74Snw141292 	outlen = outbytesleft = inlen + 10;
200cd37da74Snw141292 	if ((res = malloc(outlen)) == NULL)
201cd37da74Snw141292 		return (NULL);
202cd37da74Snw141292 	outs = res;
203cd37da74Snw141292 
204cd37da74Snw141292 	while ((rc = u8_textprep_str((char *)s, &inbytesleft, outs,
205cd37da74Snw141292 	    &outbytesleft, U8_TEXTPREP_TOLOWER, U8_UNICODE_LATEST, &err)) < 0 &&
206cd37da74Snw141292 	    err == E2BIG) {
207cd37da74Snw141292 		if ((res = realloc(res, outlen + inbytesleft)) == NULL)
208cd37da74Snw141292 			return (NULL);
209cd37da74Snw141292 		/* adjust input/output buffer pointers */
210cd37da74Snw141292 		s += (inlen - inbytesleft);
211cd37da74Snw141292 		outs = res + outlen - outbytesleft;
212cd37da74Snw141292 		/* adjust outbytesleft and outlen */
213cd37da74Snw141292 		outlen += inbytesleft;
214cd37da74Snw141292 		outbytesleft += inbytesleft;
215cd37da74Snw141292 	}
216cd37da74Snw141292 
217cd37da74Snw141292 	if (rc < 0) {
218cd37da74Snw141292 		free(res);
219cd37da74Snw141292 		res = NULL;
220cd37da74Snw141292 		return (NULL);
221cd37da74Snw141292 	}
222cd37da74Snw141292 
223cd37da74Snw141292 	res[outlen - outbytesleft] = '\0';
224cd37da74Snw141292 
225cd37da74Snw141292 	return (res);
226cd37da74Snw141292 }
227cd37da74Snw141292 
228cd37da74Snw141292 static int sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
229cd37da74Snw141292 	const char *while_doing);
230cd37da74Snw141292 
231c5c4113dSnw141292 
232c5c4113dSnw141292 /*
233c5c4113dSnw141292  * Initialize 'dbname' using 'sql'
234c5c4113dSnw141292  */
235cd37da74Snw141292 static
236cd37da74Snw141292 int
237cd37da74Snw141292 init_db_instance(const char *dbname, int version,
238cd37da74Snw141292 	const char *detect_version_sql, char * const *sql,
239cd37da74Snw141292 	init_db_option_t opt, int *created, int *upgraded)
240c5c4113dSnw141292 {
241cd37da74Snw141292 	int rc, curr_version;
242cd37da74Snw141292 	int tries = 1;
243cd37da74Snw141292 	int prio = LOG_NOTICE;
244c5c4113dSnw141292 	sqlite *db = NULL;
245cd37da74Snw141292 	char *errmsg = NULL;
246c5c4113dSnw141292 
247cd37da74Snw141292 	*created = 0;
248cd37da74Snw141292 	*upgraded = 0;
249c5c4113dSnw141292 
250cd37da74Snw141292 	if (opt == REMOVE_IF_CORRUPT)
251cd37da74Snw141292 		tries = 3;
252cd37da74Snw141292 
253cd37da74Snw141292 rinse_repeat:
254cd37da74Snw141292 	if (tries == 0) {
255cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to initialize db %s", dbname);
256c5c4113dSnw141292 		return (-1);
257cd37da74Snw141292 	}
258cd37da74Snw141292 	if (tries-- == 1)
259cd37da74Snw141292 		/* Last try, log errors */
260cd37da74Snw141292 		prio = LOG_ERR;
261c5c4113dSnw141292 
262cd37da74Snw141292 	db = sqlite_open(dbname, 0600, &errmsg);
263cd37da74Snw141292 	if (db == NULL) {
264cd37da74Snw141292 		idmapdlog(prio, "Error creating database %s (%s)",
265cd37da74Snw141292 		    dbname, CHECK_NULL(errmsg));
266cd37da74Snw141292 		sqlite_freemem(errmsg);
267cd37da74Snw141292 		if (opt == REMOVE_IF_CORRUPT)
268c5c4113dSnw141292 			(void) unlink(dbname);
269cd37da74Snw141292 		goto rinse_repeat;
270c5c4113dSnw141292 	}
271c5c4113dSnw141292 
272c5c4113dSnw141292 	sqlite_busy_timeout(db, 3000);
273cd37da74Snw141292 
274cd37da74Snw141292 	/* Detect current version of schema in the db, if any */
275cd37da74Snw141292 	curr_version = 0;
276cd37da74Snw141292 	if (detect_version_sql != NULL) {
277cd37da74Snw141292 		char *end, **results;
278cd37da74Snw141292 		int nrow;
279cd37da74Snw141292 
280cd37da74Snw141292 #ifdef	IDMAPD_DEBUG
281cd37da74Snw141292 		(void) fprintf(stderr, "Schema version detection SQL: %s\n",
282cd37da74Snw141292 		    detect_version_sql);
283cd37da74Snw141292 #endif	/* IDMAPD_DEBUG */
284cd37da74Snw141292 		rc = sqlite_get_table(db, detect_version_sql, &results,
285cd37da74Snw141292 		    &nrow, NULL, &errmsg);
286cd37da74Snw141292 		if (rc != SQLITE_OK) {
287cd37da74Snw141292 			idmapdlog(prio,
288cd37da74Snw141292 			    "Error detecting schema version of db %s (%s)",
289cd37da74Snw141292 			    dbname, errmsg);
290cd37da74Snw141292 			sqlite_freemem(errmsg);
291cd37da74Snw141292 			sqlite_free_table(results);
292c5c4113dSnw141292 			sqlite_close(db);
293cd37da74Snw141292 			return (-1);
294cd37da74Snw141292 		}
295cd37da74Snw141292 		if (nrow != 1) {
296cd37da74Snw141292 			idmapdlog(prio,
297cd37da74Snw141292 			    "Error detecting schema version of db %s", dbname);
298cd37da74Snw141292 			sqlite_close(db);
299cd37da74Snw141292 			sqlite_free_table(results);
300cd37da74Snw141292 			return (-1);
301cd37da74Snw141292 		}
302cd37da74Snw141292 		curr_version = strtol(results[1], &end, 10);
303cd37da74Snw141292 		sqlite_free_table(results);
304c5c4113dSnw141292 	}
305c5c4113dSnw141292 
306cd37da74Snw141292 	if (curr_version < 0) {
307cd37da74Snw141292 		if (opt == REMOVE_IF_CORRUPT)
308cd37da74Snw141292 			(void) unlink(dbname);
309cd37da74Snw141292 		goto rinse_repeat;
310c5c4113dSnw141292 	}
311c5c4113dSnw141292 
312cd37da74Snw141292 	if (curr_version == version)
313cd37da74Snw141292 		goto done;
314cd37da74Snw141292 
315cd37da74Snw141292 	/* Install or upgrade schema */
316cd37da74Snw141292 #ifdef	IDMAPD_DEBUG
317cd37da74Snw141292 	(void) fprintf(stderr, "Schema init/upgrade SQL: %s\n",
318cd37da74Snw141292 	    sql[curr_version]);
319cd37da74Snw141292 #endif	/* IDMAPD_DEBUG */
320cd37da74Snw141292 	rc = sql_exec_tran_no_cb(db, sql[curr_version], dbname,
321cd37da74Snw141292 	    (curr_version == 0) ? "installing schema" : "upgrading schema");
322cd37da74Snw141292 	if (rc != 0) {
323cd37da74Snw141292 		idmapdlog(prio, "Error %s schema for db %s", dbname,
324cd37da74Snw141292 		    (curr_version == 0) ? "installing schema" :
325cd37da74Snw141292 		    "upgrading schema");
326cd37da74Snw141292 		if (opt == REMOVE_IF_CORRUPT)
327cd37da74Snw141292 			(void) unlink(dbname);
328cd37da74Snw141292 		goto rinse_repeat;
329c5c4113dSnw141292 	}
330c5c4113dSnw141292 
331cd37da74Snw141292 	*upgraded = (curr_version > 0);
332cd37da74Snw141292 	*created = (curr_version == 0);
333cd37da74Snw141292 
334cd37da74Snw141292 done:
335c5c4113dSnw141292 	(void) sqlite_close(db);
336cd37da74Snw141292 	return (0);
337c5c4113dSnw141292 }
338c5c4113dSnw141292 
33984decf41Sjp151216 
34084decf41Sjp151216 /*
34184decf41Sjp151216  * This is the SQLite database busy handler that retries the SQL
34284decf41Sjp151216  * operation until it is successful.
34384decf41Sjp151216  */
34484decf41Sjp151216 int
34584decf41Sjp151216 /* LINTED E_FUNC_ARG_UNUSED */
34684decf41Sjp151216 idmap_sqlite_busy_handler(void *arg, const char *table_name, int count)
34784decf41Sjp151216 {
34884decf41Sjp151216 	struct idmap_busy	*busy = arg;
34984decf41Sjp151216 	int			delay;
35084decf41Sjp151216 	struct timespec		rqtp;
35184decf41Sjp151216 
35284decf41Sjp151216 	if (count == 1)  {
35384decf41Sjp151216 		busy->total = 0;
35484decf41Sjp151216 		busy->sec = 2;
35584decf41Sjp151216 	}
35684decf41Sjp151216 	if (busy->total > 1000 * busy->sec) {
357*2b3ecdebSjp151216 		idmapdlog(LOG_DEBUG,
35884decf41Sjp151216 		    "Thread %d waited %d sec for the %s database",
35984decf41Sjp151216 		    pthread_self(), busy->sec, busy->name);
36084decf41Sjp151216 		busy->sec++;
36184decf41Sjp151216 	}
36284decf41Sjp151216 
36384decf41Sjp151216 	if (count <= busy->delay_size) {
36484decf41Sjp151216 		delay = busy->delays[count-1];
36584decf41Sjp151216 	} else {
36684decf41Sjp151216 		delay = busy->delays[busy->delay_size - 1];
36784decf41Sjp151216 	}
36884decf41Sjp151216 	busy->total += delay;
36984decf41Sjp151216 	rqtp.tv_sec = 0;
37084decf41Sjp151216 	rqtp.tv_nsec = delay * (NANOSEC / MILLISEC);
37184decf41Sjp151216 	(void) nanosleep(&rqtp, NULL);
37284decf41Sjp151216 	return (1);
37384decf41Sjp151216 }
37484decf41Sjp151216 
37584decf41Sjp151216 
376c5c4113dSnw141292 /*
377c5c4113dSnw141292  * Get the database handle
378c5c4113dSnw141292  */
379c5c4113dSnw141292 idmap_retcode
380cd37da74Snw141292 get_db_handle(sqlite **db)
381cd37da74Snw141292 {
382c5c4113dSnw141292 	char		*errmsg;
38384decf41Sjp151216 	idmap_tsd_t	*tsd;
384c5c4113dSnw141292 
385c5c4113dSnw141292 	/*
38684decf41Sjp151216 	 * Retrieve the db handle from thread-specific storage
387c5c4113dSnw141292 	 * If none exists, open and store in thread-specific storage.
388c5c4113dSnw141292 	 */
38984decf41Sjp151216 	if ((tsd = idmap_get_tsd()) == NULL) {
39084decf41Sjp151216 		idmapdlog(LOG_ERR,
391cd37da74Snw141292 		    "Error getting thread specific data for %s", IDMAP_DBNAME);
39284decf41Sjp151216 		return (IDMAP_ERR_MEMORY);
39384decf41Sjp151216 	}
394c5c4113dSnw141292 
39584decf41Sjp151216 	if (tsd->db_db == NULL) {
39684decf41Sjp151216 		tsd->db_db = sqlite_open(IDMAP_DBNAME, 0, &errmsg);
39784decf41Sjp151216 		if (tsd->db_db == NULL) {
398cd37da74Snw141292 			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
399c5c4113dSnw141292 			    IDMAP_DBNAME, CHECK_NULL(errmsg));
400c5c4113dSnw141292 			sqlite_freemem(errmsg);
401cd37da74Snw141292 			return (IDMAP_ERR_DB);
402c5c4113dSnw141292 		}
403cd37da74Snw141292 
40484decf41Sjp151216 		tsd->db_busy.name = IDMAP_DBNAME;
40584decf41Sjp151216 		tsd->db_busy.delays = db_delay_table;
40684decf41Sjp151216 		tsd->db_busy.delay_size = sizeof (db_delay_table) /
40784decf41Sjp151216 		    sizeof (int);
40884decf41Sjp151216 		sqlite_busy_handler(tsd->db_db, idmap_sqlite_busy_handler,
40984decf41Sjp151216 		    &tsd->db_busy);
41084decf41Sjp151216 	}
41184decf41Sjp151216 	*db = tsd->db_db;
412c5c4113dSnw141292 	return (IDMAP_SUCCESS);
413c5c4113dSnw141292 }
414c5c4113dSnw141292 
415c5c4113dSnw141292 /*
416c5c4113dSnw141292  * Get the cache handle
417c5c4113dSnw141292  */
418c5c4113dSnw141292 idmap_retcode
419cd37da74Snw141292 get_cache_handle(sqlite **cache)
420cd37da74Snw141292 {
421c5c4113dSnw141292 	char		*errmsg;
42284decf41Sjp151216 	idmap_tsd_t	*tsd;
423c5c4113dSnw141292 
424c5c4113dSnw141292 	/*
42584decf41Sjp151216 	 * Retrieve the db handle from thread-specific storage
426c5c4113dSnw141292 	 * If none exists, open and store in thread-specific storage.
427c5c4113dSnw141292 	 */
42884decf41Sjp151216 	if ((tsd = idmap_get_tsd()) == NULL) {
429cd37da74Snw141292 		idmapdlog(LOG_ERR, "Error getting thread specific data for %s",
43084decf41Sjp151216 		    IDMAP_DBNAME);
43184decf41Sjp151216 		return (IDMAP_ERR_MEMORY);
43284decf41Sjp151216 	}
433c5c4113dSnw141292 
43484decf41Sjp151216 	if (tsd->cache_db == NULL) {
43584decf41Sjp151216 		tsd->cache_db = sqlite_open(IDMAP_CACHENAME, 0, &errmsg);
43684decf41Sjp151216 		if (tsd->cache_db == NULL) {
437cd37da74Snw141292 			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
438c5c4113dSnw141292 			    IDMAP_CACHENAME, CHECK_NULL(errmsg));
439c5c4113dSnw141292 			sqlite_freemem(errmsg);
440cd37da74Snw141292 			return (IDMAP_ERR_DB);
441c5c4113dSnw141292 		}
442cd37da74Snw141292 
44384decf41Sjp151216 		tsd->cache_busy.name = IDMAP_CACHENAME;
44484decf41Sjp151216 		tsd->cache_busy.delays = cache_delay_table;
44584decf41Sjp151216 		tsd->cache_busy.delay_size = sizeof (cache_delay_table) /
44684decf41Sjp151216 		    sizeof (int);
44784decf41Sjp151216 		sqlite_busy_handler(tsd->cache_db, idmap_sqlite_busy_handler,
44884decf41Sjp151216 		    &tsd->cache_busy);
44984decf41Sjp151216 	}
45084decf41Sjp151216 	*cache = tsd->cache_db;
451c5c4113dSnw141292 	return (IDMAP_SUCCESS);
452c5c4113dSnw141292 }
453c5c4113dSnw141292 
454c5c4113dSnw141292 /*
455c5c4113dSnw141292  * Initialize cache and db
456c5c4113dSnw141292  */
457c5c4113dSnw141292 int
458cd37da74Snw141292 init_dbs()
459cd37da74Snw141292 {
46048258c6bSjp151216 	char *sql[4];
461cd37da74Snw141292 	int created, upgraded;
462cd37da74Snw141292 
463c5c4113dSnw141292 	/* name-based mappings; probably OK to blow away in a pinch(?) */
464cd37da74Snw141292 	sql[0] = DB_INSTALL_SQL;
465cd37da74Snw141292 	sql[1] = DB_UPGRADE_FROM_v1_SQL;
46648258c6bSjp151216 	sql[2] = NULL;
467cd37da74Snw141292 
468cd37da74Snw141292 	if (init_db_instance(IDMAP_DBNAME, DB_VERSION, DB_VERSION_SQL, sql,
469cd37da74Snw141292 	    FAIL_IF_CORRUPT, &created, &upgraded) < 0)
470c5c4113dSnw141292 		return (-1);
471c5c4113dSnw141292 
472c5c4113dSnw141292 	/* mappings, name/SID lookup cache + ephemeral IDs; OK to blow away */
473cd37da74Snw141292 	sql[0] = CACHE_INSTALL_SQL;
474cd37da74Snw141292 	sql[1] = CACHE_UPGRADE_FROM_v1_SQL;
47548258c6bSjp151216 	sql[2] = CACHE_UPGRADE_FROM_v2_SQL;
47648258c6bSjp151216 	sql[3] = NULL;
47748258c6bSjp151216 
478cd37da74Snw141292 	if (init_db_instance(IDMAP_CACHENAME, CACHE_VERSION, CACHE_VERSION_SQL,
479cd37da74Snw141292 	    sql, REMOVE_IF_CORRUPT, &created, &upgraded) < 0)
480c5c4113dSnw141292 		return (-1);
481c5c4113dSnw141292 
482cd37da74Snw141292 	_idmapdstate.new_eph_db = (created || upgraded) ? 1 : 0;
483cd37da74Snw141292 
484c5c4113dSnw141292 	return (0);
485c5c4113dSnw141292 }
486c5c4113dSnw141292 
487c5c4113dSnw141292 /*
488c5c4113dSnw141292  * Finalize databases
489c5c4113dSnw141292  */
490c5c4113dSnw141292 void
491cd37da74Snw141292 fini_dbs()
492cd37da74Snw141292 {
493c5c4113dSnw141292 }
494c5c4113dSnw141292 
495c5c4113dSnw141292 /*
496e8c27ec8Sbaban  * This table is a listing of status codes that will be returned to the
497c5c4113dSnw141292  * client when a SQL command fails with the corresponding error message.
498c5c4113dSnw141292  */
499c5c4113dSnw141292 static msg_table_t sqlmsgtable[] = {
50062c60062Sbaban 	{IDMAP_ERR_U2W_NAMERULE_CONFLICT,
501c5c4113dSnw141292 	"columns unixname, is_user, u2w_order are not unique"},
50262c60062Sbaban 	{IDMAP_ERR_W2U_NAMERULE_CONFLICT,
503cd37da74Snw141292 	"columns winname, windomain, is_user, is_wuser, w2u_order are not"
504cd37da74Snw141292 	" unique"},
505cd37da74Snw141292 	{IDMAP_ERR_W2U_NAMERULE_CONFLICT, "Conflicting w2u namerules"},
506c5c4113dSnw141292 	{-1, NULL}
507c5c4113dSnw141292 };
508c5c4113dSnw141292 
509c5c4113dSnw141292 /*
510c5c4113dSnw141292  * idmapd's version of string2stat to map SQLite messages to
511c5c4113dSnw141292  * status codes
512c5c4113dSnw141292  */
513c5c4113dSnw141292 idmap_retcode
514cd37da74Snw141292 idmapd_string2stat(const char *msg)
515cd37da74Snw141292 {
516c5c4113dSnw141292 	int i;
517c5c4113dSnw141292 	for (i = 0; sqlmsgtable[i].msg; i++) {
518c5c4113dSnw141292 		if (strcasecmp(sqlmsgtable[i].msg, msg) == 0)
519c5c4113dSnw141292 			return (sqlmsgtable[i].retcode);
520c5c4113dSnw141292 	}
521c5c4113dSnw141292 	return (IDMAP_ERR_OTHER);
522c5c4113dSnw141292 }
523c5c4113dSnw141292 
524c5c4113dSnw141292 /*
525cd37da74Snw141292  * Executes some SQL in a transaction.
526cd37da74Snw141292  *
527cd37da74Snw141292  * Returns 0 on success, -1 if it failed but the rollback succeeded, -2
528cd37da74Snw141292  * if the rollback failed.
529cd37da74Snw141292  */
530cd37da74Snw141292 static
531cd37da74Snw141292 int
532cd37da74Snw141292 sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
533cd37da74Snw141292 	const char *while_doing)
534cd37da74Snw141292 {
535cd37da74Snw141292 	char		*errmsg = NULL;
536cd37da74Snw141292 	int		rc;
537cd37da74Snw141292 
538cd37da74Snw141292 	rc = sqlite_exec(db, "BEGIN TRANSACTION;", NULL, NULL, &errmsg);
539cd37da74Snw141292 	if (rc != SQLITE_OK) {
540cd37da74Snw141292 		idmapdlog(LOG_ERR, "Begin transaction failed (%s) "
541cd37da74Snw141292 		    "while %s (%s)", errmsg, while_doing, dbname);
542cd37da74Snw141292 		sqlite_freemem(errmsg);
543cd37da74Snw141292 		return (-1);
544cd37da74Snw141292 	}
545cd37da74Snw141292 
546cd37da74Snw141292 	rc = sqlite_exec(db, sql, NULL, NULL, &errmsg);
547cd37da74Snw141292 	if (rc != SQLITE_OK) {
548cd37da74Snw141292 		idmapdlog(LOG_ERR, "Database error (%s) while %s (%s)", errmsg,
549cd37da74Snw141292 		    while_doing, dbname);
550cd37da74Snw141292 		sqlite_freemem(errmsg);
551cd37da74Snw141292 		errmsg = NULL;
552cd37da74Snw141292 		goto rollback;
553cd37da74Snw141292 	}
554cd37da74Snw141292 
555cd37da74Snw141292 	rc = sqlite_exec(db, "COMMIT TRANSACTION", NULL, NULL, &errmsg);
556cd37da74Snw141292 	if (rc == SQLITE_OK) {
557cd37da74Snw141292 		sqlite_freemem(errmsg);
558cd37da74Snw141292 		return (0);
559cd37da74Snw141292 	}
560cd37da74Snw141292 
561cd37da74Snw141292 	idmapdlog(LOG_ERR, "Database commit error (%s) while s (%s)",
562cd37da74Snw141292 	    errmsg, while_doing, dbname);
563cd37da74Snw141292 	sqlite_freemem(errmsg);
564cd37da74Snw141292 	errmsg = NULL;
565cd37da74Snw141292 
566cd37da74Snw141292 rollback:
567cd37da74Snw141292 	rc = sqlite_exec(db, "ROLLBACK TRANSACTION", NULL, NULL, &errmsg);
568cd37da74Snw141292 	if (rc != SQLITE_OK) {
569cd37da74Snw141292 		idmapdlog(LOG_ERR, "Rollback failed (%s) while %s (%s)",
570cd37da74Snw141292 		    errmsg, while_doing, dbname);
571cd37da74Snw141292 		sqlite_freemem(errmsg);
572cd37da74Snw141292 		return (-2);
573cd37da74Snw141292 	}
574cd37da74Snw141292 	sqlite_freemem(errmsg);
575cd37da74Snw141292 
576cd37da74Snw141292 	return (-1);
577cd37da74Snw141292 }
578cd37da74Snw141292 
579cd37da74Snw141292 /*
580c5c4113dSnw141292  * Execute the given SQL statment without using any callbacks
581c5c4113dSnw141292  */
582c5c4113dSnw141292 idmap_retcode
58371590c90Snw141292 sql_exec_no_cb(sqlite *db, const char *dbname, char *sql)
584cd37da74Snw141292 {
585c5c4113dSnw141292 	char		*errmsg = NULL;
58684decf41Sjp151216 	int		r;
587c5c4113dSnw141292 	idmap_retcode	retcode;
588c5c4113dSnw141292 
589c5c4113dSnw141292 	r = sqlite_exec(db, sql, NULL, NULL, &errmsg);
59084decf41Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
591c5c4113dSnw141292 
592c5c4113dSnw141292 	if (r != SQLITE_OK) {
59371590c90Snw141292 		idmapdlog(LOG_ERR, "Database error on %s while executing %s "
59471590c90Snw141292 		    "(%s)", dbname, sql, CHECK_NULL(errmsg));
595c5c4113dSnw141292 		retcode = idmapd_string2stat(errmsg);
59662c60062Sbaban 		if (errmsg != NULL)
597c5c4113dSnw141292 			sqlite_freemem(errmsg);
598c5c4113dSnw141292 		return (retcode);
599c5c4113dSnw141292 	}
600c5c4113dSnw141292 
601c5c4113dSnw141292 	return (IDMAP_SUCCESS);
602c5c4113dSnw141292 }
603c5c4113dSnw141292 
604c5c4113dSnw141292 /*
605c5c4113dSnw141292  * Generate expression that can be used in WHERE statements.
606c5c4113dSnw141292  * Examples:
607c5c4113dSnw141292  * <prefix> <col>      <op> <value>   <suffix>
608c5c4113dSnw141292  * ""       "unixuser" "="  "foo" "AND"
609c5c4113dSnw141292  */
610c5c4113dSnw141292 idmap_retcode
611cd37da74Snw141292 gen_sql_expr_from_rule(idmap_namerule *rule, char **out)
612cd37da74Snw141292 {
613cd37da74Snw141292 	char	*s_windomain = NULL, *s_winname = NULL;
614cd37da74Snw141292 	char	*s_unixname = NULL;
615cd37da74Snw141292 	char	*lower_winname;
616cd37da74Snw141292 	int	retcode = IDMAP_SUCCESS;
617cd37da74Snw141292 
618c5c4113dSnw141292 	if (out == NULL)
619c5c4113dSnw141292 		return (IDMAP_ERR_ARG);
620c5c4113dSnw141292 
621c5c4113dSnw141292 
622cd37da74Snw141292 	if (!EMPTY_STRING(rule->windomain)) {
623cd37da74Snw141292 		s_windomain =  sqlite_mprintf("AND windomain = %Q ",
624cd37da74Snw141292 		    rule->windomain);
625cd37da74Snw141292 		if (s_windomain == NULL) {
626cd37da74Snw141292 			retcode = IDMAP_ERR_MEMORY;
627cd37da74Snw141292 			goto out;
628c5c4113dSnw141292 		}
629cd37da74Snw141292 	}
630cd37da74Snw141292 
631cd37da74Snw141292 	if (!EMPTY_STRING(rule->winname)) {
632cd37da74Snw141292 		if ((lower_winname = tolower_u8(rule->winname)) == NULL)
633cd37da74Snw141292 			lower_winname = rule->winname;
634cd37da74Snw141292 		s_winname = sqlite_mprintf(
635cd37da74Snw141292 		    "AND winname = %Q AND is_wuser = %d ",
636cd37da74Snw141292 		    lower_winname, rule->is_wuser ? 1 : 0);
637cd37da74Snw141292 		if (lower_winname != rule->winname)
638cd37da74Snw141292 			free(lower_winname);
639cd37da74Snw141292 		if (s_winname == NULL) {
640cd37da74Snw141292 			retcode = IDMAP_ERR_MEMORY;
641cd37da74Snw141292 			goto out;
642cd37da74Snw141292 		}
643cd37da74Snw141292 	}
644cd37da74Snw141292 
645cd37da74Snw141292 	if (!EMPTY_STRING(rule->unixname)) {
646cd37da74Snw141292 		s_unixname = sqlite_mprintf(
647cd37da74Snw141292 		    "AND unixname = %Q AND is_user = %d ",
648cd37da74Snw141292 		    rule->unixname, rule->is_user ? 1 : 0);
649cd37da74Snw141292 		if (s_unixname == NULL) {
650cd37da74Snw141292 			retcode = IDMAP_ERR_MEMORY;
651cd37da74Snw141292 			goto out;
652cd37da74Snw141292 		}
653cd37da74Snw141292 	}
654cd37da74Snw141292 
655cd37da74Snw141292 	*out = sqlite_mprintf("%s %s %s",
656cd37da74Snw141292 	    s_windomain ? s_windomain : "",
657cd37da74Snw141292 	    s_winname ? s_winname : "",
658cd37da74Snw141292 	    s_unixname ? s_unixname : "");
659cd37da74Snw141292 
660cd37da74Snw141292 	if (*out == NULL) {
661cd37da74Snw141292 		retcode = IDMAP_ERR_MEMORY;
662cd37da74Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
663cd37da74Snw141292 		goto out;
664cd37da74Snw141292 	}
665cd37da74Snw141292 
666cd37da74Snw141292 out:
667cd37da74Snw141292 	if (s_windomain != NULL)
668cd37da74Snw141292 		sqlite_freemem(s_windomain);
669cd37da74Snw141292 	if (s_winname != NULL)
670cd37da74Snw141292 		sqlite_freemem(s_winname);
671cd37da74Snw141292 	if (s_unixname != NULL)
672cd37da74Snw141292 		sqlite_freemem(s_unixname);
673cd37da74Snw141292 
674cd37da74Snw141292 	return (retcode);
675cd37da74Snw141292 }
676cd37da74Snw141292 
677cd37da74Snw141292 
678c5c4113dSnw141292 
679c5c4113dSnw141292 /*
680c5c4113dSnw141292  * Generate and execute SQL statement for LIST RPC calls
681c5c4113dSnw141292  */
682c5c4113dSnw141292 idmap_retcode
68371590c90Snw141292 process_list_svc_sql(sqlite *db, const char *dbname, char *sql, uint64_t limit,
68448258c6bSjp151216 		int flag, list_svc_cb cb, void *result)
685cd37da74Snw141292 {
686c5c4113dSnw141292 	list_cb_data_t	cb_data;
687c5c4113dSnw141292 	char		*errmsg = NULL;
68884decf41Sjp151216 	int		r;
689c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_ERR_INTERNAL;
690c5c4113dSnw141292 
691c5c4113dSnw141292 	(void) memset(&cb_data, 0, sizeof (cb_data));
692c5c4113dSnw141292 	cb_data.result = result;
693c5c4113dSnw141292 	cb_data.limit = limit;
69448258c6bSjp151216 	cb_data.flag = flag;
695c5c4113dSnw141292 
69684decf41Sjp151216 
697c5c4113dSnw141292 	r = sqlite_exec(db, sql, cb, &cb_data, &errmsg);
69884decf41Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
699c5c4113dSnw141292 	switch (r) {
700c5c4113dSnw141292 	case SQLITE_OK:
701c5c4113dSnw141292 		retcode = IDMAP_SUCCESS;
70284decf41Sjp151216 		break;
70384decf41Sjp151216 
704c5c4113dSnw141292 	default:
705c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
70671590c90Snw141292 		idmapdlog(LOG_ERR, "Database error on %s while executing "
70771590c90Snw141292 		    "%s (%s)", dbname, sql, CHECK_NULL(errmsg));
70884decf41Sjp151216 		break;
709c5c4113dSnw141292 	}
71062c60062Sbaban 	if (errmsg != NULL)
711c5c4113dSnw141292 		sqlite_freemem(errmsg);
712c5c4113dSnw141292 	return (retcode);
713c5c4113dSnw141292 }
714c5c4113dSnw141292 
715c5c4113dSnw141292 /*
716c5c4113dSnw141292  * This routine is called by callbacks that process the results of
717c5c4113dSnw141292  * LIST RPC calls to validate data and to allocate memory for
718c5c4113dSnw141292  * the result array.
719c5c4113dSnw141292  */
720c5c4113dSnw141292 idmap_retcode
721c5c4113dSnw141292 validate_list_cb_data(list_cb_data_t *cb_data, int argc, char **argv,
722cd37da74Snw141292 		int ncol, uchar_t **list, size_t valsize)
723cd37da74Snw141292 {
724c5c4113dSnw141292 	size_t	nsize;
725c5c4113dSnw141292 	void	*tmplist;
726c5c4113dSnw141292 
727c5c4113dSnw141292 	if (cb_data->limit > 0 && cb_data->next == cb_data->limit)
728c5c4113dSnw141292 		return (IDMAP_NEXT);
729c5c4113dSnw141292 
730c5c4113dSnw141292 	if (argc < ncol || argv == NULL) {
731c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Invalid data");
732c5c4113dSnw141292 		return (IDMAP_ERR_INTERNAL);
733c5c4113dSnw141292 	}
734c5c4113dSnw141292 
735c5c4113dSnw141292 	/* alloc in bulk to reduce number of reallocs */
736c5c4113dSnw141292 	if (cb_data->next >= cb_data->len) {
737c5c4113dSnw141292 		nsize = (cb_data->len + SIZE_INCR) * valsize;
738c5c4113dSnw141292 		tmplist = realloc(*list, nsize);
739c5c4113dSnw141292 		if (tmplist == NULL) {
740c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
741c5c4113dSnw141292 			return (IDMAP_ERR_MEMORY);
742c5c4113dSnw141292 		}
743c5c4113dSnw141292 		*list = tmplist;
744c5c4113dSnw141292 		(void) memset(*list + (cb_data->len * valsize), 0,
745c5c4113dSnw141292 		    SIZE_INCR * valsize);
746c5c4113dSnw141292 		cb_data->len += SIZE_INCR;
747c5c4113dSnw141292 	}
748c5c4113dSnw141292 	return (IDMAP_SUCCESS);
749c5c4113dSnw141292 }
750c5c4113dSnw141292 
751cd37da74Snw141292 static
752cd37da74Snw141292 idmap_retcode
753c5c4113dSnw141292 get_namerule_order(char *winname, char *windomain, char *unixname,
754cd37da74Snw141292 	int direction, int is_diagonal, int *w2u_order, int *u2w_order)
755cd37da74Snw141292 {
756c5c4113dSnw141292 	*w2u_order = 0;
757c5c4113dSnw141292 	*u2w_order = 0;
758c5c4113dSnw141292 
759c5c4113dSnw141292 	/*
760c5c4113dSnw141292 	 * Windows to UNIX lookup order:
761c5c4113dSnw141292 	 *  1. winname@domain (or winname) to ""
762c5c4113dSnw141292 	 *  2. winname@domain (or winname) to unixname
763c5c4113dSnw141292 	 *  3. winname@* to ""
764c5c4113dSnw141292 	 *  4. winname@* to unixname
765c5c4113dSnw141292 	 *  5. *@domain (or *) to *
766c5c4113dSnw141292 	 *  6. *@domain (or *) to ""
767c5c4113dSnw141292 	 *  7. *@domain (or *) to unixname
768c5c4113dSnw141292 	 *  8. *@* to *
769c5c4113dSnw141292 	 *  9. *@* to ""
770c5c4113dSnw141292 	 * 10. *@* to unixname
771c5c4113dSnw141292 	 *
772c5c4113dSnw141292 	 * winname is a special case of winname@domain when domain is the
773c5c4113dSnw141292 	 * default domain. Similarly * is a special case of *@domain when
774c5c4113dSnw141292 	 * domain is the default domain.
775c5c4113dSnw141292 	 *
776c5c4113dSnw141292 	 * Note that "" has priority over specific names because "" inhibits
777c5c4113dSnw141292 	 * mappings and traditionally deny rules always had higher priority.
778c5c4113dSnw141292 	 */
779651c0131Sbaban 	if (direction != IDMAP_DIRECTION_U2W) {
780651c0131Sbaban 		/* bi-directional or from windows to unix */
781c5c4113dSnw141292 		if (winname == NULL)
782c5c4113dSnw141292 			return (IDMAP_ERR_W2U_NAMERULE);
783c5c4113dSnw141292 		else if (unixname == NULL)
784c5c4113dSnw141292 			return (IDMAP_ERR_W2U_NAMERULE);
785c5c4113dSnw141292 		else if (EMPTY_NAME(winname))
786c5c4113dSnw141292 			return (IDMAP_ERR_W2U_NAMERULE);
787c5c4113dSnw141292 		else if (*winname == '*' && windomain && *windomain == '*') {
788c5c4113dSnw141292 			if (*unixname == '*')
789c5c4113dSnw141292 				*w2u_order = 8;
790c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
791c5c4113dSnw141292 				*w2u_order = 9;
792c5c4113dSnw141292 			else /* unixname == name */
793c5c4113dSnw141292 				*w2u_order = 10;
794c5c4113dSnw141292 		} else if (*winname == '*') {
795c5c4113dSnw141292 			if (*unixname == '*')
796c5c4113dSnw141292 				*w2u_order = 5;
797c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
798c5c4113dSnw141292 				*w2u_order = 6;
799c5c4113dSnw141292 			else /* name */
800c5c4113dSnw141292 				*w2u_order = 7;
80162c60062Sbaban 		} else if (windomain != NULL && *windomain == '*') {
802c5c4113dSnw141292 			/* winname == name */
803c5c4113dSnw141292 			if (*unixname == '*')
804c5c4113dSnw141292 				return (IDMAP_ERR_W2U_NAMERULE);
805c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
806c5c4113dSnw141292 				*w2u_order = 3;
807c5c4113dSnw141292 			else /* name */
808c5c4113dSnw141292 				*w2u_order = 4;
809c5c4113dSnw141292 		} else  {
810c5c4113dSnw141292 			/* winname == name && windomain == null or name */
811c5c4113dSnw141292 			if (*unixname == '*')
812c5c4113dSnw141292 				return (IDMAP_ERR_W2U_NAMERULE);
813c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
814c5c4113dSnw141292 				*w2u_order = 1;
815c5c4113dSnw141292 			else /* name */
816c5c4113dSnw141292 				*w2u_order = 2;
817c5c4113dSnw141292 		}
818cd37da74Snw141292 
819c5c4113dSnw141292 	}
820c5c4113dSnw141292 
821c5c4113dSnw141292 	/*
822cd37da74Snw141292 	 * 1. unixname to "", non-diagonal
823cd37da74Snw141292 	 * 2. unixname to winname@domain (or winname), non-diagonal
824cd37da74Snw141292 	 * 3. unixname to "", diagonal
825cd37da74Snw141292 	 * 4. unixname to winname@domain (or winname), diagonal
826cd37da74Snw141292 	 * 5. * to *@domain (or *), non-diagonal
827cd37da74Snw141292 	 * 5. * to *@domain (or *), diagonal
828cd37da74Snw141292 	 * 7. * to ""
829cd37da74Snw141292 	 * 8. * to winname@domain (or winname)
830cd37da74Snw141292 	 * 9. * to "", non-diagonal
831cd37da74Snw141292 	 * 10. * to winname@domain (or winname), diagonal
832c5c4113dSnw141292 	 */
833651c0131Sbaban 	if (direction != IDMAP_DIRECTION_W2U) {
834cd37da74Snw141292 		int diagonal = is_diagonal ? 1 : 0;
835cd37da74Snw141292 
836651c0131Sbaban 		/* bi-directional or from unix to windows */
837c5c4113dSnw141292 		if (unixname == NULL || EMPTY_NAME(unixname))
838c5c4113dSnw141292 			return (IDMAP_ERR_U2W_NAMERULE);
839c5c4113dSnw141292 		else if (winname == NULL)
840c5c4113dSnw141292 			return (IDMAP_ERR_U2W_NAMERULE);
84162c60062Sbaban 		else if (windomain != NULL && *windomain == '*')
842651c0131Sbaban 			return (IDMAP_ERR_U2W_NAMERULE);
843c5c4113dSnw141292 		else if (*unixname == '*') {
844c5c4113dSnw141292 			if (*winname == '*')
845cd37da74Snw141292 				*u2w_order = 5 + diagonal;
846c5c4113dSnw141292 			else if (EMPTY_NAME(winname))
847cd37da74Snw141292 				*u2w_order = 7 + 2 * diagonal;
848c5c4113dSnw141292 			else
849cd37da74Snw141292 				*u2w_order = 8 + 2 * diagonal;
850c5c4113dSnw141292 		} else {
851c5c4113dSnw141292 			if (*winname == '*')
852c5c4113dSnw141292 				return (IDMAP_ERR_U2W_NAMERULE);
853c5c4113dSnw141292 			else if (EMPTY_NAME(winname))
854cd37da74Snw141292 				*u2w_order = 1 + 2 * diagonal;
855c5c4113dSnw141292 			else
856cd37da74Snw141292 				*u2w_order = 2 + 2 * diagonal;
857c5c4113dSnw141292 		}
858c5c4113dSnw141292 	}
859c5c4113dSnw141292 	return (IDMAP_SUCCESS);
860c5c4113dSnw141292 }
861c5c4113dSnw141292 
862c5c4113dSnw141292 /*
863c5c4113dSnw141292  * Generate and execute SQL statement to add name-based mapping rule
864c5c4113dSnw141292  */
865c5c4113dSnw141292 idmap_retcode
866cd37da74Snw141292 add_namerule(sqlite *db, idmap_namerule *rule)
867cd37da74Snw141292 {
868c5c4113dSnw141292 	char		*sql = NULL;
869c5c4113dSnw141292 	idmap_stat	retcode;
8708e228215Sdm199847 	char		*dom = NULL;
871c5c4113dSnw141292 	int		w2u_order, u2w_order;
872c5c4113dSnw141292 	char		w2ubuf[11], u2wbuf[11];
873c5c4113dSnw141292 
8748e228215Sdm199847 	retcode = get_namerule_order(rule->winname, rule->windomain,
875cd37da74Snw141292 	    rule->unixname, rule->direction,
876cd37da74Snw141292 	    rule->is_user == rule->is_wuser ? 0 : 1, &w2u_order, &u2w_order);
877c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
878c5c4113dSnw141292 		goto out;
879c5c4113dSnw141292 
880c5c4113dSnw141292 	if (w2u_order)
881c5c4113dSnw141292 		(void) snprintf(w2ubuf, sizeof (w2ubuf), "%d", w2u_order);
882c5c4113dSnw141292 	if (u2w_order)
883c5c4113dSnw141292 		(void) snprintf(u2wbuf, sizeof (u2wbuf), "%d", u2w_order);
884c5c4113dSnw141292 
88562c60062Sbaban 	/*
88662c60062Sbaban 	 * For the triggers on namerules table to work correctly:
88762c60062Sbaban 	 * 1) Use NULL instead of 0 for w2u_order and u2w_order
88862c60062Sbaban 	 * 2) Use "" instead of NULL for "no domain"
88962c60062Sbaban 	 */
89062c60062Sbaban 
891e8c27ec8Sbaban 	if (!EMPTY_STRING(rule->windomain))
8928e228215Sdm199847 		dom = rule->windomain;
893cd37da74Snw141292 	else if (lookup_wksids_name2sid(rule->winname, NULL, NULL, NULL, NULL)
89462c60062Sbaban 	    == IDMAP_SUCCESS) {
89562c60062Sbaban 		/* well-known SIDs don't need domain */
89662c60062Sbaban 		dom = "";
89762c60062Sbaban 	}
898c5c4113dSnw141292 
899c5c4113dSnw141292 	RDLOCK_CONFIG();
90062c60062Sbaban 	if (dom == NULL) {
901c8e26105Sjp151216 		if (_idmapdstate.cfg->pgcfg.default_domain)
902c8e26105Sjp151216 			dom = _idmapdstate.cfg->pgcfg.default_domain;
903c5c4113dSnw141292 		else
904c5c4113dSnw141292 			dom = "";
90562c60062Sbaban 	}
90684decf41Sjp151216 	sql = sqlite_mprintf("INSERT into namerules "
907cd37da74Snw141292 	    "(is_user, is_wuser, windomain, winname_display, is_nt4, "
908c5c4113dSnw141292 	    "unixname, w2u_order, u2w_order) "
909cd37da74Snw141292 	    "VALUES(%d, %d, %Q, %Q, %d, %Q, %q, %q);",
910cd37da74Snw141292 	    rule->is_user ? 1 : 0, rule->is_wuser ? 1 : 0, dom,
911cd37da74Snw141292 	    rule->winname, rule->is_nt4 ? 1 : 0, rule->unixname,
912cd37da74Snw141292 	    w2u_order ? w2ubuf : NULL, u2w_order ? u2wbuf : NULL);
913c5c4113dSnw141292 	UNLOCK_CONFIG();
914c5c4113dSnw141292 
915c5c4113dSnw141292 	if (sql == NULL) {
916c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
917c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
918c5c4113dSnw141292 		goto out;
919c5c4113dSnw141292 	}
920c5c4113dSnw141292 
92171590c90Snw141292 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, sql);
922c5c4113dSnw141292 
923c5c4113dSnw141292 	if (retcode == IDMAP_ERR_OTHER)
924c5c4113dSnw141292 		retcode = IDMAP_ERR_CFG;
925c5c4113dSnw141292 
926c5c4113dSnw141292 out:
92762c60062Sbaban 	if (sql != NULL)
928c5c4113dSnw141292 		sqlite_freemem(sql);
929c5c4113dSnw141292 	return (retcode);
930c5c4113dSnw141292 }
931c5c4113dSnw141292 
932c5c4113dSnw141292 /*
933c5c4113dSnw141292  * Flush name-based mapping rules
934c5c4113dSnw141292  */
935c5c4113dSnw141292 idmap_retcode
936cd37da74Snw141292 flush_namerules(sqlite *db)
937cd37da74Snw141292 {
938c5c4113dSnw141292 	idmap_stat	retcode;
939c5c4113dSnw141292 
94071590c90Snw141292 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, "DELETE FROM namerules;");
941c5c4113dSnw141292 
942c5c4113dSnw141292 	return (retcode);
943c5c4113dSnw141292 }
944c5c4113dSnw141292 
945c5c4113dSnw141292 /*
946c5c4113dSnw141292  * Generate and execute SQL statement to remove a name-based mapping rule
947c5c4113dSnw141292  */
948c5c4113dSnw141292 idmap_retcode
949cd37da74Snw141292 rm_namerule(sqlite *db, idmap_namerule *rule)
950cd37da74Snw141292 {
951c5c4113dSnw141292 	char		*sql = NULL;
952c5c4113dSnw141292 	idmap_stat	retcode;
953c5c4113dSnw141292 	char		buf[80];
954cd37da74Snw141292 	char		*expr = NULL;
955c5c4113dSnw141292 
9568e228215Sdm199847 	if (rule->direction < 0 && EMPTY_STRING(rule->windomain) &&
9578e228215Sdm199847 	    EMPTY_STRING(rule->winname) && EMPTY_STRING(rule->unixname))
958c5c4113dSnw141292 		return (IDMAP_SUCCESS);
959c5c4113dSnw141292 
960c5c4113dSnw141292 	buf[0] = 0;
961cd37da74Snw141292 
962cd37da74Snw141292 	if (rule->direction == IDMAP_DIRECTION_BI)
963c5c4113dSnw141292 		(void) snprintf(buf, sizeof (buf), "AND w2u_order > 0"
964c5c4113dSnw141292 		    " AND u2w_order > 0");
965cd37da74Snw141292 	else if (rule->direction == IDMAP_DIRECTION_W2U)
966c5c4113dSnw141292 		(void) snprintf(buf, sizeof (buf), "AND w2u_order > 0"
967c5c4113dSnw141292 		    " AND (u2w_order = 0 OR u2w_order ISNULL)");
968cd37da74Snw141292 	else if (rule->direction == IDMAP_DIRECTION_U2W)
969c5c4113dSnw141292 		(void) snprintf(buf, sizeof (buf), "AND u2w_order > 0"
970c5c4113dSnw141292 		    " AND (w2u_order = 0 OR w2u_order ISNULL)");
971c5c4113dSnw141292 
972cd37da74Snw141292 	retcode = gen_sql_expr_from_rule(rule, &expr);
973cd37da74Snw141292 	if (retcode != IDMAP_SUCCESS)
974c5c4113dSnw141292 		goto out;
975c5c4113dSnw141292 
976cd37da74Snw141292 	sql = sqlite_mprintf("DELETE FROM namerules WHERE 1 %s %s;", expr,
977c5c4113dSnw141292 	    buf);
978c5c4113dSnw141292 
979c5c4113dSnw141292 	if (sql == NULL) {
980c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
981c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
982c5c4113dSnw141292 		goto out;
983c5c4113dSnw141292 	}
984c5c4113dSnw141292 
985cd37da74Snw141292 
98671590c90Snw141292 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, sql);
987c5c4113dSnw141292 
988c5c4113dSnw141292 out:
989cd37da74Snw141292 	if (expr != NULL)
990cd37da74Snw141292 		sqlite_freemem(expr);
99162c60062Sbaban 	if (sql != NULL)
992c5c4113dSnw141292 		sqlite_freemem(sql);
993c5c4113dSnw141292 	return (retcode);
994c5c4113dSnw141292 }
995c5c4113dSnw141292 
996c5c4113dSnw141292 /*
997c5c4113dSnw141292  * Compile the given SQL query and step just once.
998c5c4113dSnw141292  *
999c5c4113dSnw141292  * Input:
1000c5c4113dSnw141292  * db  - db handle
1001c5c4113dSnw141292  * sql - SQL statement
1002c5c4113dSnw141292  *
1003c5c4113dSnw141292  * Output:
1004c5c4113dSnw141292  * vm     -  virtual SQL machine
1005c5c4113dSnw141292  * ncol   - number of columns in the result
1006c5c4113dSnw141292  * values - column values
1007c5c4113dSnw141292  *
1008c5c4113dSnw141292  * Return values:
1009c5c4113dSnw141292  * IDMAP_SUCCESS
1010c5c4113dSnw141292  * IDMAP_ERR_NOTFOUND
1011c5c4113dSnw141292  * IDMAP_ERR_INTERNAL
1012c5c4113dSnw141292  */
1013c5c4113dSnw141292 
1014cd37da74Snw141292 static
1015cd37da74Snw141292 idmap_retcode
1016c5c4113dSnw141292 sql_compile_n_step_once(sqlite *db, char *sql, sqlite_vm **vm, int *ncol,
1017cd37da74Snw141292 		int reqcol, const char ***values)
1018cd37da74Snw141292 {
1019c5c4113dSnw141292 	char		*errmsg = NULL;
102084decf41Sjp151216 	int		r;
1021c5c4113dSnw141292 
102284decf41Sjp151216 	if ((r = sqlite_compile(db, sql, NULL, vm, &errmsg)) != SQLITE_OK) {
1023cd37da74Snw141292 		idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
1024cd37da74Snw141292 		    CHECK_NULL(errmsg));
1025c5c4113dSnw141292 		sqlite_freemem(errmsg);
1026c5c4113dSnw141292 		return (IDMAP_ERR_INTERNAL);
1027c5c4113dSnw141292 	}
1028c5c4113dSnw141292 
1029c5c4113dSnw141292 	r = sqlite_step(*vm, ncol, values, NULL);
103084decf41Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
1031c5c4113dSnw141292 
103284decf41Sjp151216 	if (r == SQLITE_ROW) {
103362c60062Sbaban 		if (ncol != NULL && *ncol < reqcol) {
1034c5c4113dSnw141292 			(void) sqlite_finalize(*vm, NULL);
1035c5c4113dSnw141292 			*vm = NULL;
1036c5c4113dSnw141292 			return (IDMAP_ERR_INTERNAL);
1037c5c4113dSnw141292 		}
1038c5c4113dSnw141292 		/* Caller will call finalize after using the results */
1039c5c4113dSnw141292 		return (IDMAP_SUCCESS);
1040c5c4113dSnw141292 	} else if (r == SQLITE_DONE) {
1041c5c4113dSnw141292 		(void) sqlite_finalize(*vm, NULL);
1042c5c4113dSnw141292 		*vm = NULL;
1043c5c4113dSnw141292 		return (IDMAP_ERR_NOTFOUND);
1044c5c4113dSnw141292 	}
1045c5c4113dSnw141292 
1046c5c4113dSnw141292 	(void) sqlite_finalize(*vm, &errmsg);
1047c5c4113dSnw141292 	*vm = NULL;
1048cd37da74Snw141292 	idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
1049cd37da74Snw141292 	    CHECK_NULL(errmsg));
1050c5c4113dSnw141292 	sqlite_freemem(errmsg);
1051c5c4113dSnw141292 	return (IDMAP_ERR_INTERNAL);
1052c5c4113dSnw141292 }
1053c5c4113dSnw141292 
105462c60062Sbaban /*
1055e8c27ec8Sbaban  * Update nm_siduid and nm_sidgid fields in the lookup state.
1056e8c27ec8Sbaban  *
1057e8c27ec8Sbaban  * state->nm_siduid represents mode used by sid2uid and uid2sid
1058e8c27ec8Sbaban  * requests for directory-based name mappings. Similarly,
1059e8c27ec8Sbaban  * state->nm_sidgid represents mode used by sid2gid and gid2sid
1060e8c27ec8Sbaban  * requests.
1061e8c27ec8Sbaban  *
1062e8c27ec8Sbaban  * sid2uid/uid2sid:
1063e8c27ec8Sbaban  * none       -> ds_name_mapping_enabled != true
1064e8c27ec8Sbaban  * AD-mode    -> !nldap_winname_attr && ad_unixuser_attr
1065e8c27ec8Sbaban  * nldap-mode -> nldap_winname_attr && !ad_unixuser_attr
1066e8c27ec8Sbaban  * mixed-mode -> nldap_winname_attr && ad_unixuser_attr
1067e8c27ec8Sbaban  *
1068e8c27ec8Sbaban  * sid2gid/gid2sid:
1069e8c27ec8Sbaban  * none       -> ds_name_mapping_enabled != true
1070e8c27ec8Sbaban  * AD-mode    -> !nldap_winname_attr && ad_unixgroup_attr
1071e8c27ec8Sbaban  * nldap-mode -> nldap_winname_attr && !ad_unixgroup_attr
1072e8c27ec8Sbaban  * mixed-mode -> nldap_winname_attr && ad_unixgroup_attr
1073e8c27ec8Sbaban  */
1074e8c27ec8Sbaban idmap_retcode
1075e8c27ec8Sbaban get_ds_namemap_type(lookup_state_t *state)
1076e8c27ec8Sbaban {
1077e8c27ec8Sbaban 	state->nm_siduid = IDMAP_NM_NONE;
1078e8c27ec8Sbaban 	state->nm_sidgid = IDMAP_NM_NONE;
1079e8c27ec8Sbaban 	RDLOCK_CONFIG();
1080e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.ds_name_mapping_enabled == FALSE) {
1081e8c27ec8Sbaban 		UNLOCK_CONFIG();
1082e8c27ec8Sbaban 		return (IDMAP_SUCCESS);
1083e8c27ec8Sbaban 	}
1084e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.nldap_winname_attr != NULL) {
1085e8c27ec8Sbaban 		state->nm_siduid =
1086e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
1087e8c27ec8Sbaban 		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
1088e8c27ec8Sbaban 		state->nm_sidgid =
1089e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
1090e8c27ec8Sbaban 		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
1091e8c27ec8Sbaban 	} else {
1092e8c27ec8Sbaban 		state->nm_siduid =
1093e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
1094e8c27ec8Sbaban 		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
1095e8c27ec8Sbaban 		state->nm_sidgid =
1096e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
1097e8c27ec8Sbaban 		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
1098e8c27ec8Sbaban 	}
1099e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL) {
1100e8c27ec8Sbaban 		state->ad_unixuser_attr =
1101e8c27ec8Sbaban 		    strdup(_idmapdstate.cfg->pgcfg.ad_unixuser_attr);
1102e8c27ec8Sbaban 		if (state->ad_unixuser_attr == NULL) {
1103e8c27ec8Sbaban 			UNLOCK_CONFIG();
1104e8c27ec8Sbaban 			return (IDMAP_ERR_MEMORY);
1105e8c27ec8Sbaban 		}
1106e8c27ec8Sbaban 	}
1107e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL) {
1108e8c27ec8Sbaban 		state->ad_unixgroup_attr =
1109e8c27ec8Sbaban 		    strdup(_idmapdstate.cfg->pgcfg.ad_unixgroup_attr);
1110e8c27ec8Sbaban 		if (state->ad_unixgroup_attr == NULL) {
1111e8c27ec8Sbaban 			UNLOCK_CONFIG();
1112e8c27ec8Sbaban 			return (IDMAP_ERR_MEMORY);
1113e8c27ec8Sbaban 		}
1114e8c27ec8Sbaban 	}
1115e8c27ec8Sbaban 	UNLOCK_CONFIG();
1116e8c27ec8Sbaban 	return (IDMAP_SUCCESS);
1117e8c27ec8Sbaban }
1118e8c27ec8Sbaban 
1119e8c27ec8Sbaban /*
112048258c6bSjp151216  * Set the rule with sepecified values.
112148258c6bSjp151216  * All the strings are copied.
112248258c6bSjp151216  */
112348258c6bSjp151216 static void
112448258c6bSjp151216 idmap_namerule_set(idmap_namerule *rule, const char *windomain,
112548258c6bSjp151216 		const char *winname, const char *unixname, boolean_t is_user,
112648258c6bSjp151216 		boolean_t is_wuser, boolean_t is_nt4, int direction)
112748258c6bSjp151216 {
112848258c6bSjp151216 	/*
112948258c6bSjp151216 	 * Only update if they differ because we have to free
113048258c6bSjp151216 	 * and duplicate the strings
113148258c6bSjp151216 	 */
113248258c6bSjp151216 	if (rule->windomain == NULL || windomain == NULL ||
113348258c6bSjp151216 	    strcmp(rule->windomain, windomain) != 0) {
113448258c6bSjp151216 		if (rule->windomain != NULL) {
113548258c6bSjp151216 			free(rule->windomain);
113648258c6bSjp151216 			rule->windomain = NULL;
113748258c6bSjp151216 		}
113848258c6bSjp151216 		if (windomain != NULL)
113948258c6bSjp151216 			rule->windomain = strdup(windomain);
114048258c6bSjp151216 	}
114148258c6bSjp151216 
114248258c6bSjp151216 	if (rule->winname == NULL || winname == NULL ||
114348258c6bSjp151216 	    strcmp(rule->winname, winname) != 0) {
114448258c6bSjp151216 		if (rule->winname != NULL) {
114548258c6bSjp151216 			free(rule->winname);
114648258c6bSjp151216 			rule->winname = NULL;
114748258c6bSjp151216 		}
114848258c6bSjp151216 		if (winname != NULL)
114948258c6bSjp151216 			rule->winname = strdup(winname);
115048258c6bSjp151216 	}
115148258c6bSjp151216 
115248258c6bSjp151216 	if (rule->unixname == NULL || unixname == NULL ||
115348258c6bSjp151216 	    strcmp(rule->unixname, unixname) != 0) {
115448258c6bSjp151216 		if (rule->unixname != NULL) {
115548258c6bSjp151216 			free(rule->unixname);
115648258c6bSjp151216 			rule->unixname = NULL;
115748258c6bSjp151216 		}
115848258c6bSjp151216 		if (unixname != NULL)
115948258c6bSjp151216 			rule->unixname = strdup(unixname);
116048258c6bSjp151216 	}
116148258c6bSjp151216 
116248258c6bSjp151216 	rule->is_user = is_user;
116348258c6bSjp151216 	rule->is_wuser = is_wuser;
116448258c6bSjp151216 	rule->is_nt4 = is_nt4;
116548258c6bSjp151216 	rule->direction = direction;
116648258c6bSjp151216 }
116748258c6bSjp151216 
116848258c6bSjp151216 
116948258c6bSjp151216 /*
117062c60062Sbaban  * Table for well-known SIDs.
117162c60062Sbaban  *
117262c60062Sbaban  * Background:
117362c60062Sbaban  *
117476b27f93Sbaban  * Some of the well-known principals are stored under:
117562c60062Sbaban  * cn=WellKnown Security Principals, cn=Configuration, dc=<forestRootDomain>
117662c60062Sbaban  * They belong to objectClass "foreignSecurityPrincipal". They don't have
117762c60062Sbaban  * "samAccountName" nor "userPrincipalName" attributes. Their names are
117862c60062Sbaban  * available in "cn" and "name" attributes. Some of these principals have a
117962c60062Sbaban  * second entry under CN=ForeignSecurityPrincipals,dc=<forestRootDomain> and
118062c60062Sbaban  * these duplicate entries have the stringified SID in the "name" and "cn"
118162c60062Sbaban  * attributes instead of the actual name.
118262c60062Sbaban  *
118376b27f93Sbaban  * Those of the form S-1-5-32-X are Builtin groups and are stored in the
118476b27f93Sbaban  * cn=builtin container (except, Power Users which is not stored in AD)
118562c60062Sbaban  *
118676b27f93Sbaban  * These principals are and will remain constant. Therefore doing AD lookups
118776b27f93Sbaban  * provides no benefit. Also, using hard-coded table (and thus avoiding AD
118876b27f93Sbaban  * lookup) improves performance and avoids additional complexity in the
118976b27f93Sbaban  * adutils.c code. Moreover these SIDs can be used when no Active Directory
119076b27f93Sbaban  * is available (such as the CIFS server's "workgroup" mode).
119176b27f93Sbaban  *
119276b27f93Sbaban  * Notes:
119376b27f93Sbaban  * 1. Currently we don't support localization of well-known SID names,
119462c60062Sbaban  * unlike Windows.
119562c60062Sbaban  *
119676b27f93Sbaban  * 2. Other well-known SIDs i.e. S-1-5-<domain>-<w-k RID> are not stored
119776b27f93Sbaban  * here. AD does have normal user/group objects for these objects and
119876b27f93Sbaban  * can be looked up using the existing AD lookup code.
1199e8c27ec8Sbaban  *
1200e8c27ec8Sbaban  * 3. See comments above lookup_wksids_sid2pid() for more information
1201e8c27ec8Sbaban  * on how we lookup the wksids table.
120262c60062Sbaban  */
120362c60062Sbaban static wksids_table_t wksids[] = {
1204e8c27ec8Sbaban 	{"S-1-0", 0, "Nobody", 0, SENTINEL_PID, -1, 1},
1205e8c27ec8Sbaban 	{"S-1-1", 0, "Everyone", 0, SENTINEL_PID, -1, -1},
1206e8c27ec8Sbaban 	{"S-1-3", 0, "Creator Owner", 1, IDMAP_WK_CREATOR_OWNER_UID, 1, 0},
1207e8c27ec8Sbaban 	{"S-1-3", 1, "Creator Group", 0, IDMAP_WK_CREATOR_GROUP_GID, 0, 0},
1208e8c27ec8Sbaban 	{"S-1-3", 2, "Creator Owner Server", 1, SENTINEL_PID, -1, -1},
1209e8c27ec8Sbaban 	{"S-1-3", 3, "Creator Group Server", 0, SENTINEL_PID, -1, 1},
1210e8c27ec8Sbaban 	{"S-1-3", 4, "Owner Rights", 0, SENTINEL_PID, -1, -1},
1211e8c27ec8Sbaban 	{"S-1-5", 1, "Dialup", 0, SENTINEL_PID, -1, -1},
1212e8c27ec8Sbaban 	{"S-1-5", 2, "Network", 0, SENTINEL_PID, -1, -1},
1213e8c27ec8Sbaban 	{"S-1-5", 3, "Batch", 0, SENTINEL_PID, -1, -1},
1214e8c27ec8Sbaban 	{"S-1-5", 4, "Interactive", 0, SENTINEL_PID, -1, -1},
1215e8c27ec8Sbaban 	{"S-1-5", 6, "Service", 0, SENTINEL_PID, -1, -1},
1216e8c27ec8Sbaban 	{"S-1-5", 7, "Anonymous Logon", 0, GID_NOBODY, 0, 0},
1217e8c27ec8Sbaban 	{"S-1-5", 7, "Anonymous Logon", 0, UID_NOBODY, 1, 0},
1218e8c27ec8Sbaban 	{"S-1-5", 8, "Proxy", 0, SENTINEL_PID, -1, -1},
1219e8c27ec8Sbaban 	{"S-1-5", 9, "Enterprise Domain Controllers", 0, SENTINEL_PID, -1, -1},
1220e8c27ec8Sbaban 	{"S-1-5", 10, "Self", 0, SENTINEL_PID, -1, -1},
1221e8c27ec8Sbaban 	{"S-1-5", 11, "Authenticated Users", 0, SENTINEL_PID, -1, -1},
1222e8c27ec8Sbaban 	{"S-1-5", 12, "Restricted Code", 0, SENTINEL_PID, -1, -1},
1223e8c27ec8Sbaban 	{"S-1-5", 13, "Terminal Server User", 0, SENTINEL_PID, -1, -1},
1224e8c27ec8Sbaban 	{"S-1-5", 14, "Remote Interactive Logon", 0, SENTINEL_PID, -1, -1},
1225e8c27ec8Sbaban 	{"S-1-5", 15, "This Organization", 0, SENTINEL_PID, -1, -1},
1226e8c27ec8Sbaban 	{"S-1-5", 17, "IUSR", 0, SENTINEL_PID, -1, -1},
1227e8c27ec8Sbaban 	{"S-1-5", 18, "Local System", 0, IDMAP_WK_LOCAL_SYSTEM_GID, 0, 0},
1228e8c27ec8Sbaban 	{"S-1-5", 19, "Local Service", 0, SENTINEL_PID, -1, -1},
1229e8c27ec8Sbaban 	{"S-1-5", 20, "Network Service", 0, SENTINEL_PID, -1, -1},
1230e8c27ec8Sbaban 	{"S-1-5", 1000, "Other Organization", 0, SENTINEL_PID, -1, -1},
1231e8c27ec8Sbaban 	{"S-1-5-32", 544, "Administrators", 0, SENTINEL_PID, -1, -1},
1232e8c27ec8Sbaban 	{"S-1-5-32", 545, "Users", 0, SENTINEL_PID, -1, -1},
1233e8c27ec8Sbaban 	{"S-1-5-32", 546, "Guests", 0, SENTINEL_PID, -1, -1},
1234e8c27ec8Sbaban 	{"S-1-5-32", 547, "Power Users", 0, SENTINEL_PID, -1, -1},
1235e8c27ec8Sbaban 	{"S-1-5-32", 548, "Account Operators", 0, SENTINEL_PID, -1, -1},
1236e8c27ec8Sbaban 	{"S-1-5-32", 549, "Server Operators", 0, SENTINEL_PID, -1, -1},
1237e8c27ec8Sbaban 	{"S-1-5-32", 550, "Print Operators", 0, SENTINEL_PID, -1, -1},
1238e8c27ec8Sbaban 	{"S-1-5-32", 551, "Backup Operators", 0, SENTINEL_PID, -1, -1},
1239e8c27ec8Sbaban 	{"S-1-5-32", 552, "Replicator", 0, SENTINEL_PID, -1, -1},
124076b27f93Sbaban 	{"S-1-5-32", 554, "Pre-Windows 2000 Compatible Access", 0,
1241e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1242e8c27ec8Sbaban 	{"S-1-5-32", 555, "Remote Desktop Users", 0, SENTINEL_PID, -1, -1},
124376b27f93Sbaban 	{"S-1-5-32", 556, "Network Configuration Operators", 0,
1244e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
124576b27f93Sbaban 	{"S-1-5-32", 557, "Incoming Forest Trust Builders", 0,
1246e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1247e8c27ec8Sbaban 	{"S-1-5-32", 558, "Performance Monitor Users", 0, SENTINEL_PID, -1, -1},
1248e8c27ec8Sbaban 	{"S-1-5-32", 559, "Performance Log Users", 0, SENTINEL_PID, -1, -1},
124976b27f93Sbaban 	{"S-1-5-32", 560, "Windows Authorization Access Group", 0,
1250e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
125176b27f93Sbaban 	{"S-1-5-32", 561, "Terminal Server License Servers", 0,
1252e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1253e8c27ec8Sbaban 	{"S-1-5-32", 561, "Distributed COM Users", 0, SENTINEL_PID, -1, -1},
1254e8c27ec8Sbaban 	{"S-1-5-32", 568, "IIS_IUSRS", 0, SENTINEL_PID, -1, -1},
1255e8c27ec8Sbaban 	{"S-1-5-32", 569, "Cryptographic Operators", 0, SENTINEL_PID, -1, -1},
1256e8c27ec8Sbaban 	{"S-1-5-32", 573, "Event Log Readers", 0, SENTINEL_PID, -1, -1},
125776b27f93Sbaban 	{"S-1-5-32", 574, "Certificate Service DCOM Access", 0,
1258e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1259e8c27ec8Sbaban 	{"S-1-5-64", 21, "Digest Authentication", 0, SENTINEL_PID, -1, -1},
1260e8c27ec8Sbaban 	{"S-1-5-64", 10, "NTLM Authentication", 0, SENTINEL_PID, -1, -1},
1261e8c27ec8Sbaban 	{"S-1-5-64", 14, "SChannel Authentication", 0, SENTINEL_PID, -1, -1},
1262e8c27ec8Sbaban 	{NULL, UINT32_MAX, NULL, -1, SENTINEL_PID, -1, -1}
1263c5c4113dSnw141292 };
1264c5c4113dSnw141292 
1265e8c27ec8Sbaban /*
1266e8c27ec8Sbaban  * Lookup well-known SIDs table either by winname or by SID.
1267e8c27ec8Sbaban  * If the given winname or SID is a well-known SID then we set wksid
1268e8c27ec8Sbaban  * variable and then proceed to see if the SID has a hard mapping to
1269e8c27ec8Sbaban  * a particular UID/GID (Ex: Creator Owner/Creator Group mapped to
1270e8c27ec8Sbaban  * fixed ephemeral ids). If we find such mapping then we return
1271e8c27ec8Sbaban  * success otherwise notfound. If a well-known SID is mapped to
1272e8c27ec8Sbaban  * SENTINEL_PID and the direction field is set (bi-directional or
1273e8c27ec8Sbaban  * win2unix) then we treat it as inhibited mapping and return no
1274e8c27ec8Sbaban  * mapping (Ex. S-1-0-0).
1275e8c27ec8Sbaban  */
1276cd37da74Snw141292 static
1277cd37da74Snw141292 idmap_retcode
1278e8c27ec8Sbaban lookup_wksids_sid2pid(idmap_mapping *req, idmap_id_res *res, int *wksid)
1279cd37da74Snw141292 {
1280c5c4113dSnw141292 	int i;
128162c60062Sbaban 
1282e8c27ec8Sbaban 	*wksid = 0;
1283e8c27ec8Sbaban 
1284e8c27ec8Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
1285e8c27ec8Sbaban 		if (req->id1.idmap_id_u.sid.prefix != NULL) {
1286e8c27ec8Sbaban 			if ((strcasecmp(wksids[i].sidprefix,
1287e8c27ec8Sbaban 			    req->id1.idmap_id_u.sid.prefix) != 0) ||
1288e8c27ec8Sbaban 			    wksids[i].rid != req->id1.idmap_id_u.sid.rid)
1289e8c27ec8Sbaban 				/* this is not our SID */
1290e8c27ec8Sbaban 				continue;
1291e8c27ec8Sbaban 			if (req->id1name == NULL) {
1292e8c27ec8Sbaban 				req->id1name = strdup(wksids[i].winname);
1293e8c27ec8Sbaban 				if (req->id1name == NULL)
1294e8c27ec8Sbaban 					return (IDMAP_ERR_MEMORY);
1295e8c27ec8Sbaban 			}
1296e8c27ec8Sbaban 		} else if (req->id1name != NULL) {
1297e8c27ec8Sbaban 			if (strcasecmp(wksids[i].winname, req->id1name) != 0)
1298e8c27ec8Sbaban 				/* this is not our winname */
1299e8c27ec8Sbaban 				continue;
1300e8c27ec8Sbaban 			req->id1.idmap_id_u.sid.prefix =
1301e8c27ec8Sbaban 			    strdup(wksids[i].sidprefix);
1302e8c27ec8Sbaban 			if (req->id1.idmap_id_u.sid.prefix == NULL)
1303e8c27ec8Sbaban 				return (IDMAP_ERR_MEMORY);
1304e8c27ec8Sbaban 			req->id1.idmap_id_u.sid.rid = wksids[i].rid;
1305e8c27ec8Sbaban 		}
1306e8c27ec8Sbaban 
1307e8c27ec8Sbaban 		*wksid = 1;
1308e8c27ec8Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
1309e8c27ec8Sbaban 
1310e8c27ec8Sbaban 		req->id1.idtype = (wksids[i].is_wuser) ?
1311e8c27ec8Sbaban 		    IDMAP_USID : IDMAP_GSID;
1312e8c27ec8Sbaban 
1313e8c27ec8Sbaban 		if (wksids[i].pid == SENTINEL_PID) {
1314e8c27ec8Sbaban 			if (wksids[i].direction == IDMAP_DIRECTION_BI ||
1315e8c27ec8Sbaban 			    wksids[i].direction == IDMAP_DIRECTION_W2U)
1316e8c27ec8Sbaban 				/* Inhibited */
1317e8c27ec8Sbaban 				return (IDMAP_ERR_NOMAPPING);
1318e8c27ec8Sbaban 			/* Not mapped */
1319e8c27ec8Sbaban 			return (IDMAP_ERR_NOTFOUND);
1320e8c27ec8Sbaban 		} else if (wksids[i].direction == IDMAP_DIRECTION_U2W)
132162c60062Sbaban 			continue;
132262c60062Sbaban 
1323e8c27ec8Sbaban 		switch (res->id.idtype) {
1324c5c4113dSnw141292 		case IDMAP_UID:
132562c60062Sbaban 			if (wksids[i].is_user == 0)
132662c60062Sbaban 				continue;
132762c60062Sbaban 			res->id.idmap_id_u.uid = wksids[i].pid;
132862c60062Sbaban 			res->direction = wksids[i].direction;
132948258c6bSjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
133048258c6bSjp151216 				res->info.how.map_type =
133148258c6bSjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
133248258c6bSjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
133348258c6bSjp151216 			}
1334c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1335c5c4113dSnw141292 		case IDMAP_GID:
133662c60062Sbaban 			if (wksids[i].is_user == 1)
133762c60062Sbaban 				continue;
133862c60062Sbaban 			res->id.idmap_id_u.gid = wksids[i].pid;
133962c60062Sbaban 			res->direction = wksids[i].direction;
134048258c6bSjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
134148258c6bSjp151216 				res->info.how.map_type =
134248258c6bSjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
134348258c6bSjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
134448258c6bSjp151216 			}
1345c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1346c5c4113dSnw141292 		case IDMAP_POSIXID:
134762c60062Sbaban 			res->id.idmap_id_u.uid = wksids[i].pid;
134862c60062Sbaban 			res->id.idtype = (!wksids[i].is_user) ?
1349c5c4113dSnw141292 			    IDMAP_GID : IDMAP_UID;
135062c60062Sbaban 			res->direction = wksids[i].direction;
135148258c6bSjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
135248258c6bSjp151216 				res->info.how.map_type =
135348258c6bSjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
135448258c6bSjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
135548258c6bSjp151216 			}
1356c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1357c5c4113dSnw141292 		default:
1358c5c4113dSnw141292 			return (IDMAP_ERR_NOTSUPPORTED);
1359c5c4113dSnw141292 		}
1360c5c4113dSnw141292 	}
1361c5c4113dSnw141292 	return (IDMAP_ERR_NOTFOUND);
1362c5c4113dSnw141292 }
1363c5c4113dSnw141292 
1364cd37da74Snw141292 
1365cd37da74Snw141292 static
1366cd37da74Snw141292 idmap_retcode
1367cd37da74Snw141292 lookup_wksids_pid2sid(idmap_mapping *req, idmap_id_res *res, int is_user)
1368cd37da74Snw141292 {
1369c5c4113dSnw141292 	int i;
1370e8c27ec8Sbaban 	if (req->id1.idmap_id_u.uid == SENTINEL_PID)
1371e8c27ec8Sbaban 		return (IDMAP_ERR_NOTFOUND);
137262c60062Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
137362c60062Sbaban 		if (wksids[i].pid == req->id1.idmap_id_u.uid &&
137462c60062Sbaban 		    wksids[i].is_user == is_user &&
137562c60062Sbaban 		    wksids[i].direction != IDMAP_DIRECTION_W2U) {
1376e8c27ec8Sbaban 			if (res->id.idtype == IDMAP_SID) {
1377e8c27ec8Sbaban 				res->id.idtype = (wksids[i].is_wuser) ?
1378e8c27ec8Sbaban 				    IDMAP_USID : IDMAP_GSID;
1379e8c27ec8Sbaban 			}
138062c60062Sbaban 			res->id.idmap_id_u.sid.rid = wksids[i].rid;
1381c5c4113dSnw141292 			res->id.idmap_id_u.sid.prefix =
138262c60062Sbaban 			    strdup(wksids[i].sidprefix);
1383c5c4113dSnw141292 			if (res->id.idmap_id_u.sid.prefix == NULL) {
1384c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1385c5c4113dSnw141292 				return (IDMAP_ERR_MEMORY);
1386c5c4113dSnw141292 			}
138762c60062Sbaban 			res->direction = wksids[i].direction;
138848258c6bSjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
138948258c6bSjp151216 				res->info.how.map_type =
139048258c6bSjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
139148258c6bSjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
139248258c6bSjp151216 			}
1393c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1394c5c4113dSnw141292 		}
1395c5c4113dSnw141292 	}
139662c60062Sbaban 	return (IDMAP_ERR_NOTFOUND);
139762c60062Sbaban }
139862c60062Sbaban 
1399cd37da74Snw141292 static
1400cd37da74Snw141292 idmap_retcode
1401cd37da74Snw141292 lookup_wksids_name2sid(const char *name, char **canonname, char **sidprefix,
1402cd37da74Snw141292 	idmap_rid_t *rid, int *type)
1403cd37da74Snw141292 {
140462c60062Sbaban 	int i;
140562c60062Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
1406e8c27ec8Sbaban 		if (strcasecmp(wksids[i].winname, name) != 0)
1407e8c27ec8Sbaban 			continue;
1408e8c27ec8Sbaban 		if (sidprefix != NULL &&
1409e8c27ec8Sbaban 		    (*sidprefix = strdup(wksids[i].sidprefix)) == NULL) {
141062c60062Sbaban 			idmapdlog(LOG_ERR, "Out of memory");
141162c60062Sbaban 			return (IDMAP_ERR_MEMORY);
141262c60062Sbaban 		}
1413cd37da74Snw141292 		if (canonname != NULL &&
1414cd37da74Snw141292 		    (*canonname = strdup(wksids[i].winname)) == NULL) {
1415cd37da74Snw141292 			idmapdlog(LOG_ERR, "Out of memory");
1416e8c27ec8Sbaban 			if (sidprefix != NULL) {
1417e8c27ec8Sbaban 				free(*sidprefix);
1418e8c27ec8Sbaban 				*sidprefix = NULL;
1419e8c27ec8Sbaban 			}
1420cd37da74Snw141292 			return (IDMAP_ERR_MEMORY);
1421cd37da74Snw141292 		}
142262c60062Sbaban 		if (type != NULL)
1423e8c27ec8Sbaban 			*type = (wksids[i].is_wuser) ?
142462c60062Sbaban 			    _IDMAP_T_USER : _IDMAP_T_GROUP;
142562c60062Sbaban 		if (rid != NULL)
142662c60062Sbaban 			*rid = wksids[i].rid;
142762c60062Sbaban 		return (IDMAP_SUCCESS);
142862c60062Sbaban 	}
1429c5c4113dSnw141292 	return (IDMAP_ERR_NOTFOUND);
1430c5c4113dSnw141292 }
1431c5c4113dSnw141292 
1432cd37da74Snw141292 static
1433cd37da74Snw141292 idmap_retcode
1434cd37da74Snw141292 lookup_cache_sid2pid(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
1435cd37da74Snw141292 {
1436c5c4113dSnw141292 	char		*end;
1437c5c4113dSnw141292 	char		*sql = NULL;
1438c5c4113dSnw141292 	const char	**values;
1439c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
1440c5c4113dSnw141292 	int		ncol, is_user;
1441c5c4113dSnw141292 	uid_t		pid;
1442c5c4113dSnw141292 	time_t		curtime, exp;
1443c5c4113dSnw141292 	idmap_retcode	retcode;
1444042addd6Sbaban 	char		*is_user_string, *lower_name;
1445c5c4113dSnw141292 
1446c5c4113dSnw141292 	/* Current time */
1447c5c4113dSnw141292 	errno = 0;
1448c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
1449cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
1450c5c4113dSnw141292 		    strerror(errno));
1451c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
1452c5c4113dSnw141292 		goto out;
1453c5c4113dSnw141292 	}
1454c5c4113dSnw141292 
1455e8c27ec8Sbaban 	switch (res->id.idtype) {
1456cd37da74Snw141292 	case IDMAP_UID:
1457cd37da74Snw141292 		is_user_string = "1";
1458cd37da74Snw141292 		break;
1459cd37da74Snw141292 	case IDMAP_GID:
1460cd37da74Snw141292 		is_user_string = "0";
1461cd37da74Snw141292 		break;
1462cd37da74Snw141292 	case IDMAP_POSIXID:
1463cd37da74Snw141292 		/* the non-diagonal mapping */
1464cd37da74Snw141292 		is_user_string = "is_wuser";
1465cd37da74Snw141292 		break;
1466cd37da74Snw141292 	default:
1467cd37da74Snw141292 		retcode = IDMAP_ERR_NOTSUPPORTED;
1468cd37da74Snw141292 		goto out;
1469cd37da74Snw141292 	}
1470cd37da74Snw141292 
1471c5c4113dSnw141292 	/* SQL to lookup the cache */
147248258c6bSjp151216 
1473e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
1474e8c27ec8Sbaban 		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
147548258c6bSjp151216 		    "unixname, u2w, is_wuser, "
147648258c6bSjp151216 		    "map_type, map_dn, map_attr, map_value, "
147748258c6bSjp151216 		    "map_windomain, map_winname, map_unixname, map_is_nt4 "
1478cd37da74Snw141292 		    "FROM idmap_cache WHERE is_user = %s AND "
1479c5c4113dSnw141292 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
1480c5c4113dSnw141292 		    "(pid >= 2147483648 OR "
1481c5c4113dSnw141292 		    "(expiration = 0 OR expiration ISNULL OR "
1482c5c4113dSnw141292 		    "expiration > %d));",
1483e8c27ec8Sbaban 		    is_user_string, req->id1.idmap_id_u.sid.prefix,
1484e8c27ec8Sbaban 		    req->id1.idmap_id_u.sid.rid, curtime);
1485e8c27ec8Sbaban 	} else if (req->id1name != NULL) {
1486042addd6Sbaban 		if ((lower_name = tolower_u8(req->id1name)) == NULL)
1487042addd6Sbaban 			lower_name = req->id1name;
1488e8c27ec8Sbaban 		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
148948258c6bSjp151216 		    "unixname, u2w, is_wuser, "
149048258c6bSjp151216 		    "map_type, map_dn, map_attr, map_value, "
149148258c6bSjp151216 		    "map_windomain, map_winname, map_unixname, map_is_nt4 "
1492e8c27ec8Sbaban 		    "FROM idmap_cache WHERE is_user = %s AND "
1493e8c27ec8Sbaban 		    "winname = %Q AND windomain = %Q AND w2u = 1 AND "
1494e8c27ec8Sbaban 		    "(pid >= 2147483648 OR "
1495e8c27ec8Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
1496e8c27ec8Sbaban 		    "expiration > %d));",
149748258c6bSjp151216 		    is_user_string, lower_name, req->id1domain,
149848258c6bSjp151216 		    curtime);
1499042addd6Sbaban 		if (lower_name != req->id1name)
1500042addd6Sbaban 			free(lower_name);
1501e8c27ec8Sbaban 	} else {
1502e8c27ec8Sbaban 		retcode = IDMAP_ERR_ARG;
1503e8c27ec8Sbaban 		goto out;
1504e8c27ec8Sbaban 	}
1505c5c4113dSnw141292 	if (sql == NULL) {
1506c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
1507c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
1508c5c4113dSnw141292 		goto out;
1509c5c4113dSnw141292 	}
151048258c6bSjp151216 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol,
151148258c6bSjp151216 	    14, &values);
1512c5c4113dSnw141292 	sqlite_freemem(sql);
1513c5c4113dSnw141292 
1514c5c4113dSnw141292 	if (retcode == IDMAP_ERR_NOTFOUND) {
1515c5c4113dSnw141292 		goto out;
1516c5c4113dSnw141292 	} else if (retcode == IDMAP_SUCCESS) {
1517c5c4113dSnw141292 		/* sanity checks */
1518c5c4113dSnw141292 		if (values[0] == NULL || values[1] == NULL) {
1519c5c4113dSnw141292 			retcode = IDMAP_ERR_CACHE;
1520c5c4113dSnw141292 			goto out;
1521c5c4113dSnw141292 		}
1522c5c4113dSnw141292 
1523c5c4113dSnw141292 		pid = strtoul(values[0], &end, 10);
1524c5c4113dSnw141292 		is_user = strncmp(values[1], "0", 2) ? 1 : 0;
1525c5c4113dSnw141292 
1526cd37da74Snw141292 		if (is_user) {
1527cd37da74Snw141292 			res->id.idtype = IDMAP_UID;
1528cd37da74Snw141292 			res->id.idmap_id_u.uid = pid;
1529cd37da74Snw141292 		} else {
1530cd37da74Snw141292 			res->id.idtype = IDMAP_GID;
1531cd37da74Snw141292 			res->id.idmap_id_u.gid = pid;
1532cd37da74Snw141292 		}
1533cd37da74Snw141292 
1534c5c4113dSnw141292 		/*
1535c5c4113dSnw141292 		 * We may have an expired ephemeral mapping. Consider
1536c5c4113dSnw141292 		 * the expired entry as valid if we are not going to
1537c5c4113dSnw141292 		 * perform name-based mapping. But do not renew the
1538c5c4113dSnw141292 		 * expiration.
1539c5c4113dSnw141292 		 * If we will be doing name-based mapping then store the
1540c5c4113dSnw141292 		 * ephemeral pid in the result so that we can use it
1541c5c4113dSnw141292 		 * if we end up doing dynamic mapping again.
1542c5c4113dSnw141292 		 */
1543c5c4113dSnw141292 		if (!DO_NOT_ALLOC_NEW_ID_MAPPING(req) &&
1544cd37da74Snw141292 		    !AVOID_NAMESERVICE(req) &&
1545cd37da74Snw141292 		    IS_EPHEMERAL(pid) && values[2] != NULL) {
1546c5c4113dSnw141292 			exp = strtoll(values[2], &end, 10);
1547c5c4113dSnw141292 			if (exp && exp <= curtime) {
1548c5c4113dSnw141292 				/* Store the ephemeral pid */
1549651c0131Sbaban 				res->direction = IDMAP_DIRECTION_BI;
1550cd37da74Snw141292 				req->direction |= is_user
1551cd37da74Snw141292 				    ? _IDMAP_F_EXP_EPH_UID
1552cd37da74Snw141292 				    : _IDMAP_F_EXP_EPH_GID;
1553c5c4113dSnw141292 				retcode = IDMAP_ERR_NOTFOUND;
1554c5c4113dSnw141292 			}
1555c5c4113dSnw141292 		}
1556c5c4113dSnw141292 	}
1557c5c4113dSnw141292 
1558c5c4113dSnw141292 out:
1559c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
156062c60062Sbaban 		if (values[4] != NULL)
1561c5c4113dSnw141292 			res->direction =
1562651c0131Sbaban 			    (strtol(values[4], &end, 10) == 0)?
1563651c0131Sbaban 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
1564c5c4113dSnw141292 		else
1565651c0131Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
1566c5c4113dSnw141292 
156762c60062Sbaban 		if (values[3] != NULL) {
1568e8c27ec8Sbaban 			if (req->id2name != NULL)
1569e8c27ec8Sbaban 				free(req->id2name);
15708e228215Sdm199847 			req->id2name = strdup(values[3]);
15718e228215Sdm199847 			if (req->id2name == NULL) {
1572c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1573c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
1574c5c4113dSnw141292 			}
1575c5c4113dSnw141292 		}
1576e8c27ec8Sbaban 
1577e8c27ec8Sbaban 		req->id1.idtype = strncmp(values[5], "0", 2) ?
1578e8c27ec8Sbaban 		    IDMAP_USID : IDMAP_GSID;
157948258c6bSjp151216 
158048258c6bSjp151216 		if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
158148258c6bSjp151216 			res->info.src = IDMAP_MAP_SRC_CACHE;
158248258c6bSjp151216 			res->info.how.map_type = strtoul(values[6], &end, 10);
158348258c6bSjp151216 			switch (res->info.how.map_type) {
158448258c6bSjp151216 			case IDMAP_MAP_TYPE_DS_AD:
158548258c6bSjp151216 				res->info.how.idmap_how_u.ad.dn =
158648258c6bSjp151216 				    strdup(values[7]);
158748258c6bSjp151216 				res->info.how.idmap_how_u.ad.attr =
158848258c6bSjp151216 				    strdup(values[8]);
158948258c6bSjp151216 				res->info.how.idmap_how_u.ad.value =
159048258c6bSjp151216 				    strdup(values[9]);
159148258c6bSjp151216 				break;
159248258c6bSjp151216 
159348258c6bSjp151216 			case IDMAP_MAP_TYPE_DS_NLDAP:
159448258c6bSjp151216 				res->info.how.idmap_how_u.nldap.dn =
159548258c6bSjp151216 				    strdup(values[7]);
159648258c6bSjp151216 				res->info.how.idmap_how_u.nldap.attr =
159748258c6bSjp151216 				    strdup(values[8]);
159848258c6bSjp151216 				res->info.how.idmap_how_u.nldap.value =
159948258c6bSjp151216 				    strdup(values[9]);
160048258c6bSjp151216 				break;
160148258c6bSjp151216 
160248258c6bSjp151216 			case IDMAP_MAP_TYPE_RULE_BASED:
160348258c6bSjp151216 				res->info.how.idmap_how_u.rule.windomain =
160448258c6bSjp151216 				    strdup(values[10]);
160548258c6bSjp151216 				res->info.how.idmap_how_u.rule.winname =
160648258c6bSjp151216 				    strdup(values[11]);
160748258c6bSjp151216 				res->info.how.idmap_how_u.rule.unixname =
160848258c6bSjp151216 				    strdup(values[12]);
160948258c6bSjp151216 				res->info.how.idmap_how_u.rule.is_nt4 =
161048258c6bSjp151216 				    strtoul(values[13], &end, 1);
161148258c6bSjp151216 				res->info.how.idmap_how_u.rule.is_user =
161248258c6bSjp151216 				    is_user;
161348258c6bSjp151216 				res->info.how.idmap_how_u.rule.is_wuser =
161448258c6bSjp151216 				    strtoul(values[5], &end, 1);
161548258c6bSjp151216 				break;
161648258c6bSjp151216 
161748258c6bSjp151216 			case IDMAP_MAP_TYPE_EPHEMERAL:
161848258c6bSjp151216 				break;
161948258c6bSjp151216 
162048258c6bSjp151216 			case IDMAP_MAP_TYPE_LOCAL_SID:
162148258c6bSjp151216 				break;
162248258c6bSjp151216 
162348258c6bSjp151216 			case IDMAP_MAP_TYPE_KNOWN_SID:
162448258c6bSjp151216 				break;
162548258c6bSjp151216 
162648258c6bSjp151216 			default:
162748258c6bSjp151216 				/* Unknow mapping type */
162848258c6bSjp151216 				assert(FALSE);
162948258c6bSjp151216 			}
163048258c6bSjp151216 		}
1631c5c4113dSnw141292 	}
163262c60062Sbaban 	if (vm != NULL)
1633c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
1634c5c4113dSnw141292 	return (retcode);
1635c5c4113dSnw141292 }
1636c5c4113dSnw141292 
1637cd37da74Snw141292 static
1638cd37da74Snw141292 idmap_retcode
163962c60062Sbaban lookup_cache_sid2name(sqlite *cache, const char *sidprefix, idmap_rid_t rid,
1640cd37da74Snw141292 		char **name, char **domain, int *type)
1641cd37da74Snw141292 {
1642c5c4113dSnw141292 	char		*end;
1643c5c4113dSnw141292 	char		*sql = NULL;
1644c5c4113dSnw141292 	const char	**values;
1645c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
1646c5c4113dSnw141292 	int		ncol;
1647c5c4113dSnw141292 	time_t		curtime;
1648c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
1649c5c4113dSnw141292 
1650c5c4113dSnw141292 	/* Get current time */
1651c5c4113dSnw141292 	errno = 0;
1652c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
1653cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
1654c5c4113dSnw141292 		    strerror(errno));
1655c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
1656c5c4113dSnw141292 		goto out;
1657c5c4113dSnw141292 	}
1658c5c4113dSnw141292 
1659c5c4113dSnw141292 	/* SQL to lookup the cache */
1660cd37da74Snw141292 	sql = sqlite_mprintf("SELECT canon_name, domain, type "
1661cd37da74Snw141292 	    "FROM name_cache WHERE "
1662c5c4113dSnw141292 	    "sidprefix = %Q AND rid = %u AND "
1663c5c4113dSnw141292 	    "(expiration = 0 OR expiration ISNULL OR "
1664c5c4113dSnw141292 	    "expiration > %d);",
1665c5c4113dSnw141292 	    sidprefix, rid, curtime);
1666c5c4113dSnw141292 	if (sql == NULL) {
1667c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
1668c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
1669c5c4113dSnw141292 		goto out;
1670c5c4113dSnw141292 	}
1671c5c4113dSnw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 3, &values);
1672c5c4113dSnw141292 	sqlite_freemem(sql);
1673c5c4113dSnw141292 
1674c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
167562c60062Sbaban 		if (type != NULL) {
1676c5c4113dSnw141292 			if (values[2] == NULL) {
1677c5c4113dSnw141292 				retcode = IDMAP_ERR_CACHE;
1678c5c4113dSnw141292 				goto out;
1679c5c4113dSnw141292 			}
1680c5c4113dSnw141292 			*type = strtol(values[2], &end, 10);
1681c5c4113dSnw141292 		}
1682c5c4113dSnw141292 
168362c60062Sbaban 		if (name != NULL && values[0] != NULL) {
1684c5c4113dSnw141292 			if ((*name = strdup(values[0])) == NULL) {
1685c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1686c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
1687c5c4113dSnw141292 				goto out;
1688c5c4113dSnw141292 			}
1689c5c4113dSnw141292 		}
1690c5c4113dSnw141292 
169162c60062Sbaban 		if (domain != NULL && values[1] != NULL) {
1692c5c4113dSnw141292 			if ((*domain = strdup(values[1])) == NULL) {
169362c60062Sbaban 				if (name != NULL && *name) {
1694c5c4113dSnw141292 					free(*name);
1695c5c4113dSnw141292 					*name = NULL;
1696c5c4113dSnw141292 				}
1697c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1698c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
1699c5c4113dSnw141292 				goto out;
1700c5c4113dSnw141292 			}
1701c5c4113dSnw141292 		}
1702c5c4113dSnw141292 	}
1703c5c4113dSnw141292 
1704c5c4113dSnw141292 out:
170562c60062Sbaban 	if (vm != NULL)
1706c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
1707c5c4113dSnw141292 	return (retcode);
1708c5c4113dSnw141292 }
1709c5c4113dSnw141292 
1710c5c4113dSnw141292 /*
1711e8c27ec8Sbaban  * Given SID, find winname using name_cache OR
1712e8c27ec8Sbaban  * Given winname, find SID using name_cache.
1713e8c27ec8Sbaban  * Used when mapping win to unix i.e. req->id1 is windows id and
1714e8c27ec8Sbaban  * req->id2 is unix id
1715c5c4113dSnw141292  */
1716cd37da74Snw141292 static
1717cd37da74Snw141292 idmap_retcode
1718e8c27ec8Sbaban lookup_name_cache(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
1719cd37da74Snw141292 {
1720c5c4113dSnw141292 	int		type = -1;
1721c5c4113dSnw141292 	idmap_retcode	retcode;
1722e8c27ec8Sbaban 	char		*sidprefix = NULL;
1723c5c4113dSnw141292 	idmap_rid_t	rid;
1724c5c4113dSnw141292 	char		*name = NULL, *domain = NULL;
1725c5c4113dSnw141292 
1726e8c27ec8Sbaban 	/* Done if we've both sid and winname */
1727e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL && req->id1name != NULL)
1728e8c27ec8Sbaban 		return (IDMAP_SUCCESS);
1729c5c4113dSnw141292 
1730e8c27ec8Sbaban 	/* Lookup sid to winname */
1731e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
1732e8c27ec8Sbaban 		retcode = lookup_cache_sid2name(cache,
1733e8c27ec8Sbaban 		    req->id1.idmap_id_u.sid.prefix,
1734e8c27ec8Sbaban 		    req->id1.idmap_id_u.sid.rid, &name, &domain, &type);
173562c60062Sbaban 		goto out;
1736e8c27ec8Sbaban 	}
173762c60062Sbaban 
1738e8c27ec8Sbaban 	/* Lookup winame to sid */
1739e8c27ec8Sbaban 	retcode = lookup_cache_name2sid(cache, req->id1name, req->id1domain,
1740e8c27ec8Sbaban 	    &name, &sidprefix, &rid, &type);
1741c5c4113dSnw141292 
174262c60062Sbaban out:
1743e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
1744c5c4113dSnw141292 		free(name);
1745c5c4113dSnw141292 		free(domain);
1746e8c27ec8Sbaban 		free(sidprefix);
1747e8c27ec8Sbaban 		return (retcode);
1748e8c27ec8Sbaban 	}
1749e8c27ec8Sbaban 
1750e8c27ec8Sbaban 	if (res->id.idtype == IDMAP_POSIXID) {
1751e8c27ec8Sbaban 		res->id.idtype = (type == _IDMAP_T_USER) ?
1752e8c27ec8Sbaban 		    IDMAP_UID : IDMAP_GID;
1753e8c27ec8Sbaban 	}
1754e8c27ec8Sbaban 	req->id1.idtype = (type == _IDMAP_T_USER) ?
1755e8c27ec8Sbaban 	    IDMAP_USID : IDMAP_GSID;
1756e8c27ec8Sbaban 
1757e8c27ec8Sbaban 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
1758e8c27ec8Sbaban 	if (name != NULL) {
1759e8c27ec8Sbaban 		free(req->id1name);	/* Free existing winname */
1760e8c27ec8Sbaban 		req->id1name = name;	/* and use canonical name instead */
1761e8c27ec8Sbaban 	}
1762e8c27ec8Sbaban 	if (req->id1domain == NULL)
1763e8c27ec8Sbaban 		req->id1domain = domain;
1764e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix == NULL) {
1765e8c27ec8Sbaban 		req->id1.idmap_id_u.sid.prefix = sidprefix;
1766e8c27ec8Sbaban 		req->id1.idmap_id_u.sid.rid = rid;
1767c5c4113dSnw141292 	}
1768c5c4113dSnw141292 	return (retcode);
1769c5c4113dSnw141292 }
1770c5c4113dSnw141292 
1771e8c27ec8Sbaban /*
1772e8c27ec8Sbaban  * Batch AD lookups
1773e8c27ec8Sbaban  */
1774c5c4113dSnw141292 idmap_retcode
1775e8c27ec8Sbaban ad_lookup_batch(lookup_state_t *state, idmap_mapping_batch *batch,
1776cd37da74Snw141292 		idmap_ids_res *result)
1777cd37da74Snw141292 {
1778c5c4113dSnw141292 	idmap_retcode	retcode;
1779e8c27ec8Sbaban 	int		i, add, type, is_wuser, is_user;
1780e8c27ec8Sbaban 	int		retries = 0, eunixtype;
1781e8c27ec8Sbaban 	char		**unixname;
1782c5c4113dSnw141292 	idmap_mapping	*req;
1783c5c4113dSnw141292 	idmap_id_res	*res;
1784e8c27ec8Sbaban 	idmap_query_state_t	*qs = NULL;
178548258c6bSjp151216 	idmap_how	*how;
1786e8c27ec8Sbaban 
1787e8c27ec8Sbaban 	/*
1788e8c27ec8Sbaban 	 * Since req->id2.idtype is unused, we will use it here
1789e8c27ec8Sbaban 	 * to retrieve the value of sid_type. But it needs to be
1790e8c27ec8Sbaban 	 * reset to IDMAP_NONE before we return to prevent xdr
1791e8c27ec8Sbaban 	 * from mis-interpreting req->id2 when it tries to free
1792e8c27ec8Sbaban 	 * the input argument. Other option is to allocate an
1793e8c27ec8Sbaban 	 * array of integers and use it instead for the batched
1794e8c27ec8Sbaban 	 * call. But why un-necessarily allocate memory. That may
1795e8c27ec8Sbaban 	 * be an option if req->id2.idtype cannot be re-used in
1796e8c27ec8Sbaban 	 * future.
1797e8c27ec8Sbaban 	 */
1798c5c4113dSnw141292 
1799c5c4113dSnw141292 	if (state->ad_nqueries == 0)
1800c5c4113dSnw141292 		return (IDMAP_SUCCESS);
1801c5c4113dSnw141292 
1802c5c4113dSnw141292 retry:
1803e8c27ec8Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, state->ad_nqueries,
1804e8c27ec8Sbaban 	    &qs);
1805e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
18060dcc7149Snw141292 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
18070dcc7149Snw141292 			goto retry;
1808349d5d8fSnw141292 		degrade_svc(1, "failed to create batch for AD lookup");
1809e8c27ec8Sbaban 		goto out;
1810c5c4113dSnw141292 	}
1811c5c4113dSnw141292 
1812c8e26105Sjp151216 	restore_svc();
1813c8e26105Sjp151216 
1814e8c27ec8Sbaban 	idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
1815e8c27ec8Sbaban 	    state->ad_unixgroup_attr);
1816e8c27ec8Sbaban 
1817e8c27ec8Sbaban 	for (i = 0, add = 0; i < batch->idmap_mapping_batch_len; i++) {
1818c5c4113dSnw141292 		req = &batch->idmap_mapping_batch_val[i];
1819c5c4113dSnw141292 		res = &result->ids.ids_val[i];
182048258c6bSjp151216 		how = &res->info.how;
182148258c6bSjp151216 
1822e8c27ec8Sbaban 		retcode = IDMAP_SUCCESS;
1823e8c27ec8Sbaban 		req->id2.idtype = IDMAP_NONE;
1824c5c4113dSnw141292 
1825e8c27ec8Sbaban 		/* Skip if not marked for AD lookup */
1826e8c27ec8Sbaban 		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
1827e8c27ec8Sbaban 			continue;
1828e8c27ec8Sbaban 
1829c5c4113dSnw141292 		if (retries == 0)
1830c5c4113dSnw141292 			res->retcode = IDMAP_ERR_RETRIABLE_NET_ERR;
1831c5c4113dSnw141292 		else if (res->retcode != IDMAP_ERR_RETRIABLE_NET_ERR)
1832c5c4113dSnw141292 			continue;
183348258c6bSjp151216 		/*
183448258c6bSjp151216 		 * Make sure that info is not set as we may be performing
183548258c6bSjp151216 		 * a retry.
183648258c6bSjp151216 		 */
183748258c6bSjp151216 		idmap_info_free(&res->info);
1838e8c27ec8Sbaban 
1839e8c27ec8Sbaban 		if (IS_REQUEST_SID(*req, 1)) {
1840e8c27ec8Sbaban 			/* win to unix */
1841e8c27ec8Sbaban 
1842e8c27ec8Sbaban 			assert(req->id1.idmap_id_u.sid.prefix != NULL);
1843e8c27ec8Sbaban 
1844e8c27ec8Sbaban 			/* Lookup AD by SID */
1845e8c27ec8Sbaban 			unixname = NULL;
1846e8c27ec8Sbaban 			eunixtype = _IDMAP_T_UNDEF;
1847e8c27ec8Sbaban 			if (req->id2name == NULL) {
1848e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_UID &&
1849e8c27ec8Sbaban 				    AD_OR_MIXED(state->nm_siduid)) {
1850e8c27ec8Sbaban 					eunixtype = _IDMAP_T_USER;
1851e8c27ec8Sbaban 					unixname = &req->id2name;
1852e8c27ec8Sbaban 				} else if (res->id.idtype == IDMAP_GID &&
1853e8c27ec8Sbaban 				    AD_OR_MIXED(state->nm_sidgid)) {
1854e8c27ec8Sbaban 					eunixtype = _IDMAP_T_GROUP;
1855e8c27ec8Sbaban 					unixname = &req->id2name;
1856e8c27ec8Sbaban 				} else if (AD_OR_MIXED(state->nm_siduid) ||
1857e8c27ec8Sbaban 				    AD_OR_MIXED(state->nm_sidgid)) {
1858e8c27ec8Sbaban 					unixname = &req->id2name;
1859e8c27ec8Sbaban 				}
1860e8c27ec8Sbaban 			}
1861e8c27ec8Sbaban 			add = 1;
186248258c6bSjp151216 			res->info.src = IDMAP_MAP_SRC_NEW;
186348258c6bSjp151216 			how->map_type = IDMAP_MAP_TYPE_DS_AD;
1864c5c4113dSnw141292 			retcode = idmap_sid2name_batch_add1(
1865e8c27ec8Sbaban 			    qs, req->id1.idmap_id_u.sid.prefix,
1866e8c27ec8Sbaban 			    &req->id1.idmap_id_u.sid.rid, eunixtype,
186748258c6bSjp151216 			    &how->idmap_how_u.ad.dn,
186848258c6bSjp151216 			    &how->idmap_how_u.ad.attr,
186948258c6bSjp151216 			    &how->idmap_how_u.ad.value,
1870e8c27ec8Sbaban 			    (req->id1name == NULL) ? &req->id1name : NULL,
1871e8c27ec8Sbaban 			    (req->id1domain == NULL) ? &req->id1domain : NULL,
1872e8c27ec8Sbaban 			    (int *)&req->id2.idtype, unixname, &res->retcode);
1873c5c4113dSnw141292 
1874e8c27ec8Sbaban 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
1875e8c27ec8Sbaban 			/* unix to win */
1876e8c27ec8Sbaban 
1877e8c27ec8Sbaban 			if (res->id.idmap_id_u.sid.prefix != NULL &&
1878e8c27ec8Sbaban 			    req->id2name != NULL) {
1879e8c27ec8Sbaban 				/* Already have SID and winname -- done */
1880e8c27ec8Sbaban 				res->retcode = IDMAP_SUCCESS;
1881e8c27ec8Sbaban 				continue;
1882c5c4113dSnw141292 			}
1883c5c4113dSnw141292 
1884e8c27ec8Sbaban 			if (res->id.idmap_id_u.sid.prefix != NULL) {
1885cd37da74Snw141292 				/*
1886e8c27ec8Sbaban 				 * SID but no winname -- lookup AD by
1887e8c27ec8Sbaban 				 * SID to get winname.
1888cd37da74Snw141292 				 */
1889e8c27ec8Sbaban 				add = 1;
189048258c6bSjp151216 				res->info.src = IDMAP_MAP_SRC_NEW;
189148258c6bSjp151216 				how->map_type = IDMAP_MAP_TYPE_DS_AD;
1892e8c27ec8Sbaban 				retcode = idmap_sid2name_batch_add1(
1893e8c27ec8Sbaban 				    qs, res->id.idmap_id_u.sid.prefix,
1894e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.rid,
189548258c6bSjp151216 				    _IDMAP_T_UNDEF,
189648258c6bSjp151216 				    &how->idmap_how_u.ad.dn,
189748258c6bSjp151216 				    &how->idmap_how_u.ad.attr,
189848258c6bSjp151216 				    &how->idmap_how_u.ad.value,
189948258c6bSjp151216 				    &req->id2name,
1900e8c27ec8Sbaban 				    &req->id2domain, (int *)&req->id2.idtype,
1901e8c27ec8Sbaban 				    NULL, &res->retcode);
1902e8c27ec8Sbaban 			} else if (req->id2name != NULL) {
1903e8c27ec8Sbaban 				/*
1904e8c27ec8Sbaban 				 * winname but no SID -- lookup AD by
1905e8c27ec8Sbaban 				 * winname to get SID.
1906e8c27ec8Sbaban 				 */
1907e8c27ec8Sbaban 				add = 1;
190848258c6bSjp151216 				res->info.src = IDMAP_MAP_SRC_NEW;
190948258c6bSjp151216 				how->map_type = IDMAP_MAP_TYPE_DS_AD;
1910e8c27ec8Sbaban 				retcode = idmap_name2sid_batch_add1(
1911e8c27ec8Sbaban 				    qs, req->id2name, req->id2domain,
191248258c6bSjp151216 				    _IDMAP_T_UNDEF,
191348258c6bSjp151216 				    &how->idmap_how_u.ad.dn,
191448258c6bSjp151216 				    &how->idmap_how_u.ad.attr,
191548258c6bSjp151216 				    &how->idmap_how_u.ad.value,
191648258c6bSjp151216 				    NULL,
1917e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.prefix,
1918e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.rid,
1919e8c27ec8Sbaban 				    (int *)&req->id2.idtype, NULL,
1920e8c27ec8Sbaban 				    &res->retcode);
1921e8c27ec8Sbaban 			} else if (req->id1name != NULL) {
1922e8c27ec8Sbaban 				/*
1923e8c27ec8Sbaban 				 * No SID and no winname but we've unixname --
1924e8c27ec8Sbaban 				 * lookup AD by unixname to get SID.
1925e8c27ec8Sbaban 				 */
1926e8c27ec8Sbaban 				is_user = (IS_REQUEST_UID(*req)) ? 1 : 0;
1927e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_USID)
1928e8c27ec8Sbaban 					is_wuser = 1;
1929e8c27ec8Sbaban 				else if (res->id.idtype == IDMAP_GSID)
1930e8c27ec8Sbaban 					is_wuser = 0;
1931e8c27ec8Sbaban 				else
1932e8c27ec8Sbaban 					is_wuser = is_user;
1933e8c27ec8Sbaban 				add = 1;
193448258c6bSjp151216 				res->info.src = IDMAP_MAP_SRC_NEW;
193548258c6bSjp151216 				how->map_type = IDMAP_MAP_TYPE_DS_AD;
1936e8c27ec8Sbaban 				retcode = idmap_unixname2sid_batch_add1(
1937e8c27ec8Sbaban 				    qs, req->id1name, is_user, is_wuser,
193848258c6bSjp151216 				    &how->idmap_how_u.ad.dn,
193948258c6bSjp151216 				    &how->idmap_how_u.ad.attr,
194048258c6bSjp151216 				    &how->idmap_how_u.ad.value,
1941e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.prefix,
1942e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.rid,
1943e8c27ec8Sbaban 				    &req->id2name, &req->id2domain,
1944e8c27ec8Sbaban 				    (int *)&req->id2.idtype, &res->retcode);
1945e8c27ec8Sbaban 			}
1946e8c27ec8Sbaban 		}
1947e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS) {
1948e8c27ec8Sbaban 			idmap_lookup_release_batch(&qs);
1949e8c27ec8Sbaban 			break;
1950e8c27ec8Sbaban 		}
1951cd37da74Snw141292 	}
1952cd37da74Snw141292 
1953e8c27ec8Sbaban 	if (retcode == IDMAP_SUCCESS && add)
19540dcc7149Snw141292 		retcode = idmap_lookup_batch_end(&qs);
1955cd37da74Snw141292 
1956c5c4113dSnw141292 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
1957c5c4113dSnw141292 		goto retry;
1958c8e26105Sjp151216 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
1959349d5d8fSnw141292 		degrade_svc(1, "some AD lookups timed out repeatedly");
1960c5c4113dSnw141292 
1961e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
1962e8c27ec8Sbaban 		idmapdlog(LOG_NOTICE, "Failed to batch AD lookup requests");
1963c5c4113dSnw141292 
1964c5c4113dSnw141292 out:
1965e8c27ec8Sbaban 	/*
1966e8c27ec8Sbaban 	 * This loop does the following:
1967e8c27ec8Sbaban 	 * 1) If there are errors in creating or submitting the batch then
1968e8c27ec8Sbaban 	 *    we set the retcode for each request (res->retcode) that's part
1969e8c27ec8Sbaban 	 *    of the batch to that error. If there were no such errors then
1970e8c27ec8Sbaban 	 *    res->retcode for each request will reflect the status of AD
1971e8c27ec8Sbaban 	 *    lookup for that particular request. Initial value of
1972e8c27ec8Sbaban 	 *    res->retcode is IDMAP_ERR_RETRIABLE_NET_ERR.
1973e8c27ec8Sbaban 	 * 2) If AD lookup for a given request succeeds then evaluate the
1974e8c27ec8Sbaban 	 *    type of the AD object (i.e user or group) and update the
1975e8c27ec8Sbaban 	 *    idtype in res and req.
1976e8c27ec8Sbaban 	 * 3) Reset req->id2.idtype to IDMAP_NONE.
1977e8c27ec8Sbaban 	 */
1978e8c27ec8Sbaban 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
1979e8c27ec8Sbaban 		req = &batch->idmap_mapping_batch_val[i];
1980e8c27ec8Sbaban 		type = req->id2.idtype;
1981e8c27ec8Sbaban 		req->id2.idtype = IDMAP_NONE;
19825e0794bcSbaban 		res = &result->ids.ids_val[i];
198348258c6bSjp151216 		how = &res->info.how;
19845e0794bcSbaban 
1985e8c27ec8Sbaban 		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
1986e8c27ec8Sbaban 			/* Entry that wasn't marked for AD lookup - skip */
1987e8c27ec8Sbaban 			continue;
1988e8c27ec8Sbaban 
1989e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS) {
1990e8c27ec8Sbaban 			res->retcode = retcode;
1991e8c27ec8Sbaban 			continue;
1992e8c27ec8Sbaban 		}
1993e8c27ec8Sbaban 
1994e8c27ec8Sbaban 		if (!add)
1995e8c27ec8Sbaban 			continue;
1996e8c27ec8Sbaban 
1997e8c27ec8Sbaban 
199848258c6bSjp151216 		if (res->retcode == IDMAP_ERR_NOTFOUND) {
199948258c6bSjp151216 			/* Nothing found - remove the preset info */
200048258c6bSjp151216 			res->info.src = IDMAP_MAP_SRC_UNKNOWN;
200148258c6bSjp151216 			how->map_type = IDMAP_MAP_TYPE_UNKNOWN;
200248258c6bSjp151216 		}
200348258c6bSjp151216 
2004e8c27ec8Sbaban 		if (IS_REQUEST_SID(*req, 1)) {
2005e8c27ec8Sbaban 			if (res->retcode != IDMAP_SUCCESS)
2006e8c27ec8Sbaban 				continue;
2007e8c27ec8Sbaban 			switch (type) {
2008e8c27ec8Sbaban 			case _IDMAP_T_USER:
2009e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
2010e8c27ec8Sbaban 					res->id.idtype = IDMAP_UID;
2011e8c27ec8Sbaban 				req->id1.idtype = IDMAP_USID;
2012e8c27ec8Sbaban 				break;
2013e8c27ec8Sbaban 			case _IDMAP_T_GROUP:
2014e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
2015e8c27ec8Sbaban 					res->id.idtype = IDMAP_GID;
2016e8c27ec8Sbaban 				req->id1.idtype = IDMAP_GSID;
2017e8c27ec8Sbaban 				break;
2018e8c27ec8Sbaban 			default:
2019e8c27ec8Sbaban 				res->retcode = IDMAP_ERR_SID;
2020e8c27ec8Sbaban 				break;
2021e8c27ec8Sbaban 			}
2022e8c27ec8Sbaban 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
2023e8c27ec8Sbaban 			if (res->retcode != IDMAP_SUCCESS) {
2024e8c27ec8Sbaban 				if ((!(IDMAP_FATAL_ERROR(res->retcode))) &&
2025e8c27ec8Sbaban 				    res->id.idmap_id_u.sid.prefix == NULL &&
2026e8c27ec8Sbaban 				    req->id2name == NULL && /* no winname */
2027e8c27ec8Sbaban 				    req->id1name != NULL) /* unixname */
2028e8c27ec8Sbaban 					/*
2029e8c27ec8Sbaban 					 * Here we have a pid2sid request
2030e8c27ec8Sbaban 					 * that was marked for AD lookup
2031e8c27ec8Sbaban 					 * with no SID, no winname but with
2032e8c27ec8Sbaban 					 * unixname. This request was
2033e8c27ec8Sbaban 					 * added to the batch to do AD lookup
2034e8c27ec8Sbaban 					 * by unixname but it failed with non
2035e8c27ec8Sbaban 					 * fatal error. In such case we
2036e8c27ec8Sbaban 					 * ignore the error (i.e set
2037e8c27ec8Sbaban 					 * res->retcode to success) so that
2038e8c27ec8Sbaban 					 * next pass considers it for name
2039e8c27ec8Sbaban 					 * based mapping rules or ephemeral
2040e8c27ec8Sbaban 					 * mapping.
2041e8c27ec8Sbaban 					 */
2042e8c27ec8Sbaban 					res->retcode = IDMAP_SUCCESS;
2043e8c27ec8Sbaban 				continue;
2044e8c27ec8Sbaban 			}
2045e8c27ec8Sbaban 			switch (type) {
2046e8c27ec8Sbaban 			case _IDMAP_T_USER:
2047e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_SID)
2048e8c27ec8Sbaban 					res->id.idtype = IDMAP_USID;
2049e8c27ec8Sbaban 				break;
2050e8c27ec8Sbaban 			case _IDMAP_T_GROUP:
2051e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_SID)
2052e8c27ec8Sbaban 					res->id.idtype = IDMAP_GSID;
2053e8c27ec8Sbaban 				break;
2054e8c27ec8Sbaban 			default:
2055e8c27ec8Sbaban 				res->retcode = IDMAP_ERR_SID;
2056e8c27ec8Sbaban 				break;
2057e8c27ec8Sbaban 			}
2058e8c27ec8Sbaban 		}
2059e8c27ec8Sbaban 	}
2060e8c27ec8Sbaban 
2061e8c27ec8Sbaban 	/* AD lookups done. Reset state->ad_nqueries and return */
2062e8c27ec8Sbaban 	state->ad_nqueries = 0;
2063c5c4113dSnw141292 	return (retcode);
2064c5c4113dSnw141292 }
2065c5c4113dSnw141292 
2066cd37da74Snw141292 /*
2067cd37da74Snw141292  * Convention when processing win2unix requests:
2068cd37da74Snw141292  *
2069cd37da74Snw141292  * Windows identity:
2070cd37da74Snw141292  * req->id1name =
2071cd37da74Snw141292  *              winname if given otherwise winname found will be placed
2072cd37da74Snw141292  *              here.
2073cd37da74Snw141292  * req->id1domain =
2074cd37da74Snw141292  *              windomain if given otherwise windomain found will be
2075cd37da74Snw141292  *              placed here.
2076cd37da74Snw141292  * req->id1.idtype =
2077cd37da74Snw141292  *              Either IDMAP_SID/USID/GSID. If this is IDMAP_SID then it'll
2078cd37da74Snw141292  *              be set to IDMAP_USID/GSID depending upon whether the
2079cd37da74Snw141292  *              given SID is user or group respectively. The user/group-ness
2080cd37da74Snw141292  *              is determined either when looking up well-known SIDs table OR
2081cd37da74Snw141292  *              if the SID is found in namecache OR by ad_lookup() OR by
2082cd37da74Snw141292  *              ad_lookup_batch().
2083cd37da74Snw141292  * req->id1..sid.[prefix, rid] =
2084cd37da74Snw141292  *              SID if given otherwise SID found will be placed here.
2085cd37da74Snw141292  *
2086cd37da74Snw141292  * Unix identity:
2087cd37da74Snw141292  * req->id2name =
2088cd37da74Snw141292  *              unixname found will be placed here.
2089cd37da74Snw141292  * req->id2domain =
2090cd37da74Snw141292  *              NOT USED
2091cd37da74Snw141292  * res->id.idtype =
2092cd37da74Snw141292  *              Target type initialized from req->id2.idtype. If
2093cd37da74Snw141292  *              it is IDMAP_POSIXID then actual type (IDMAP_UID/GID) found
2094cd37da74Snw141292  *              will be placed here.
2095cd37da74Snw141292  * res->id..[uid or gid] =
2096cd37da74Snw141292  *              UID/GID found will be placed here.
2097cd37da74Snw141292  *
2098cd37da74Snw141292  * Others:
2099cd37da74Snw141292  * res->retcode =
2100cd37da74Snw141292  *              Return status for this request will be placed here.
2101cd37da74Snw141292  * res->direction =
2102cd37da74Snw141292  *              Direction found will be placed here. Direction
2103cd37da74Snw141292  *              meaning whether the resultant mapping is valid
2104cd37da74Snw141292  *              only from win2unix or bi-directional.
2105cd37da74Snw141292  * req->direction =
2106cd37da74Snw141292  *              INTERNAL USE. Used by idmapd to set various
2107cd37da74Snw141292  *              flags (_IDMAP_F_xxxx) to aid in processing
2108cd37da74Snw141292  *              of the request.
2109cd37da74Snw141292  * req->id2.idtype =
2110cd37da74Snw141292  *              INTERNAL USE. Initially this is the requested target
2111cd37da74Snw141292  *              type and is used to initialize res->id.idtype.
2112cd37da74Snw141292  *              ad_lookup_batch() uses this field temporarily to store
2113cd37da74Snw141292  *              sid_type obtained by the batched AD lookups and after
2114cd37da74Snw141292  *              use resets it to IDMAP_NONE to prevent xdr from
2115cd37da74Snw141292  *              mis-interpreting the contents of req->id2.
2116cd37da74Snw141292  * req->id2..[uid or gid or sid] =
2117cd37da74Snw141292  *              NOT USED
2118cd37da74Snw141292  */
2119cd37da74Snw141292 
2120cd37da74Snw141292 /*
2121cd37da74Snw141292  * This function does the following:
2122cd37da74Snw141292  * 1. Lookup well-known SIDs table.
2123cd37da74Snw141292  * 2. Check if the given SID is a local-SID and if so extract UID/GID from it.
2124cd37da74Snw141292  * 3. Lookup cache.
2125cd37da74Snw141292  * 4. Check if the client does not want new mapping to be allocated
2126cd37da74Snw141292  *    in which case this pass is the final pass.
2127cd37da74Snw141292  * 5. Set AD lookup flag if it determines that the next stage needs
2128cd37da74Snw141292  *    to do AD lookup.
2129cd37da74Snw141292  */
2130c5c4113dSnw141292 idmap_retcode
2131c5c4113dSnw141292 sid2pid_first_pass(lookup_state_t *state, sqlite *cache, idmap_mapping *req,
2132cd37da74Snw141292 		idmap_id_res *res)
2133cd37da74Snw141292 {
2134c5c4113dSnw141292 	idmap_retcode	retcode;
2135e8c27ec8Sbaban 	int		wksid;
2136c5c4113dSnw141292 
2137e8c27ec8Sbaban 	/* Initialize result */
2138e8c27ec8Sbaban 	res->id.idtype = req->id2.idtype;
2139e8c27ec8Sbaban 	res->id.idmap_id_u.uid = SENTINEL_PID;
2140e8c27ec8Sbaban 	res->direction = IDMAP_DIRECTION_UNDEF;
2141e8c27ec8Sbaban 	wksid = 0;
2142c5c4113dSnw141292 
2143cf5b5989Sdm199847 	if (EMPTY_STRING(req->id1.idmap_id_u.sid.prefix)) {
2144e8c27ec8Sbaban 		if (req->id1name == NULL) {
2145e8c27ec8Sbaban 			retcode = IDMAP_ERR_ARG;
2146c5c4113dSnw141292 			goto out;
2147c5c4113dSnw141292 		}
2148e8c27ec8Sbaban 		/* sanitize sidprefix */
2149e8c27ec8Sbaban 		free(req->id1.idmap_id_u.sid.prefix);
2150e8c27ec8Sbaban 		req->id1.idmap_id_u.sid.prefix = NULL;
2151e8c27ec8Sbaban 	}
2152c5c4113dSnw141292 
2153e8c27ec8Sbaban 	/* Lookup well-known SIDs table */
2154e8c27ec8Sbaban 	retcode = lookup_wksids_sid2pid(req, res, &wksid);
2155c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
2156c5c4113dSnw141292 		goto out;
2157c5c4113dSnw141292 
2158e8c27ec8Sbaban 	/* Check if this is a localsid */
2159e8c27ec8Sbaban 	if (!wksid) {
2160e8c27ec8Sbaban 		retcode = lookup_localsid2pid(req, res);
2161e8c27ec8Sbaban 		if (retcode != IDMAP_ERR_NOTFOUND)
2162e8c27ec8Sbaban 			goto out;
2163e8c27ec8Sbaban 	}
2164e8c27ec8Sbaban 
2165e8c27ec8Sbaban 	/* Lookup cache */
2166c5c4113dSnw141292 	retcode = lookup_cache_sid2pid(cache, req, res);
2167c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
2168c5c4113dSnw141292 		goto out;
2169c5c4113dSnw141292 
2170c5c4113dSnw141292 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req) || AVOID_NAMESERVICE(req)) {
217148258c6bSjp151216 		retcode = IDMAP_ERR_NONEGENERATED;
2172c5c4113dSnw141292 		goto out;
2173c5c4113dSnw141292 	}
2174c5c4113dSnw141292 
2175c5c4113dSnw141292 	/*
2176e8c27ec8Sbaban 	 * Failed to find non-expired entry in cache. Next step is
2177e8c27ec8Sbaban 	 * to determine if this request needs to be batched for AD lookup.
2178e8c27ec8Sbaban 	 *
2179e8c27ec8Sbaban 	 * At this point we have either sid or winname or both. If we don't
2180e8c27ec8Sbaban 	 * have both then lookup name_cache for the sid or winname
2181e8c27ec8Sbaban 	 * whichever is missing. If not found then this request will be
2182e8c27ec8Sbaban 	 * batched for AD lookup.
2183e8c27ec8Sbaban 	 */
2184e8c27ec8Sbaban 	retcode = lookup_name_cache(cache, req, res);
2185e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS && retcode != IDMAP_ERR_NOTFOUND)
2186e8c27ec8Sbaban 		goto out;
2187e8c27ec8Sbaban 
2188e8c27ec8Sbaban 	/*
2189e8c27ec8Sbaban 	 * Set the flag to indicate that we are not done yet so that
2190e8c27ec8Sbaban 	 * subsequent passes considers this request for name-based
2191e8c27ec8Sbaban 	 * mapping and ephemeral mapping.
2192c5c4113dSnw141292 	 */
2193c5c4113dSnw141292 	state->sid2pid_done = FALSE;
2194e8c27ec8Sbaban 	req->direction |= _IDMAP_F_NOTDONE;
2195c5c4113dSnw141292 
2196c5c4113dSnw141292 	/*
2197e8c27ec8Sbaban 	 * Even if we have both sid and winname, we still may need to batch
2198e8c27ec8Sbaban 	 * this request for AD lookup if we don't have unixname and
2199e8c27ec8Sbaban 	 * directory-based name mapping (AD or mixed) is enabled.
2200e8c27ec8Sbaban 	 * We avoid AD lookup for well-known SIDs because they don't have
2201e8c27ec8Sbaban 	 * regular AD objects.
2202c5c4113dSnw141292 	 */
2203e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS ||
2204e8c27ec8Sbaban 	    (!wksid && req->id2name == NULL &&
2205e8c27ec8Sbaban 	    AD_OR_MIXED_MODE(res->id.idtype, state))) {
2206c5c4113dSnw141292 		retcode = IDMAP_SUCCESS;
2207e8c27ec8Sbaban 		req->direction |= _IDMAP_F_LOOKUP_AD;
2208c5c4113dSnw141292 		state->ad_nqueries++;
2209c5c4113dSnw141292 	}
2210c5c4113dSnw141292 
2211c5c4113dSnw141292 
2212c5c4113dSnw141292 out:
2213c5c4113dSnw141292 	res->retcode = idmap_stat4prot(retcode);
2214e8c27ec8Sbaban 	/*
2215e8c27ec8Sbaban 	 * If we are done and there was an error then set fallback pid
2216e8c27ec8Sbaban 	 * in the result.
2217e8c27ec8Sbaban 	 */
2218e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
2219e8c27ec8Sbaban 		res->id.idmap_id_u.uid = UID_NOBODY;
2220c5c4113dSnw141292 	return (retcode);
2221c5c4113dSnw141292 }
2222c5c4113dSnw141292 
2223c5c4113dSnw141292 /*
2224c5c4113dSnw141292  * Generate SID using the following convention
2225c5c4113dSnw141292  * 	<machine-sid-prefix>-<1000 + uid>
2226c5c4113dSnw141292  * 	<machine-sid-prefix>-<2^31 + gid>
2227c5c4113dSnw141292  */
2228cd37da74Snw141292 static
2229cd37da74Snw141292 idmap_retcode
223048258c6bSjp151216 generate_localsid(idmap_mapping *req, idmap_id_res *res, int is_user,
223148258c6bSjp151216 		int fallback)
2232cd37da74Snw141292 {
2233e8c27ec8Sbaban 	free(res->id.idmap_id_u.sid.prefix);
2234e8c27ec8Sbaban 	res->id.idmap_id_u.sid.prefix = NULL;
2235e8c27ec8Sbaban 
2236e8c27ec8Sbaban 	/*
2237e8c27ec8Sbaban 	 * Diagonal mapping for localSIDs not supported because of the
2238e8c27ec8Sbaban 	 * way we generate localSIDs.
2239e8c27ec8Sbaban 	 */
2240e8c27ec8Sbaban 	if (is_user && res->id.idtype == IDMAP_GSID)
2241e8c27ec8Sbaban 		return (IDMAP_ERR_NOMAPPING);
2242e8c27ec8Sbaban 	if (!is_user && res->id.idtype == IDMAP_USID)
2243e8c27ec8Sbaban 		return (IDMAP_ERR_NOMAPPING);
2244e8c27ec8Sbaban 
2245c5c4113dSnw141292 	/* Skip 1000 UIDs */
2246c5c4113dSnw141292 	if (is_user && req->id1.idmap_id_u.uid >
2247c5c4113dSnw141292 	    (INT32_MAX - LOCALRID_MIN))
224862c60062Sbaban 		return (IDMAP_ERR_NOMAPPING);
2249c5c4113dSnw141292 
2250c5c4113dSnw141292 	RDLOCK_CONFIG();
2251e8c27ec8Sbaban 	/*
2252e8c27ec8Sbaban 	 * machine_sid is never NULL because if it is we won't be here.
2253e8c27ec8Sbaban 	 * No need to assert because stdrup(NULL) will core anyways.
2254e8c27ec8Sbaban 	 */
2255c5c4113dSnw141292 	res->id.idmap_id_u.sid.prefix =
2256c5c4113dSnw141292 	    strdup(_idmapdstate.cfg->pgcfg.machine_sid);
2257c5c4113dSnw141292 	if (res->id.idmap_id_u.sid.prefix == NULL) {
2258c5c4113dSnw141292 		UNLOCK_CONFIG();
2259c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2260c5c4113dSnw141292 		return (IDMAP_ERR_MEMORY);
2261c5c4113dSnw141292 	}
2262c5c4113dSnw141292 	UNLOCK_CONFIG();
2263c5c4113dSnw141292 	res->id.idmap_id_u.sid.rid =
2264c5c4113dSnw141292 	    (is_user) ? req->id1.idmap_id_u.uid + LOCALRID_MIN :
2265c5c4113dSnw141292 	    req->id1.idmap_id_u.gid + INT32_MAX + 1;
2266651c0131Sbaban 	res->direction = IDMAP_DIRECTION_BI;
2267e8c27ec8Sbaban 	if (res->id.idtype == IDMAP_SID)
2268e8c27ec8Sbaban 		res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
2269c5c4113dSnw141292 
227048258c6bSjp151216 	if (!fallback && req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
227148258c6bSjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_LOCAL_SID;
227248258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_ALGORITHMIC;
227348258c6bSjp151216 	}
227448258c6bSjp151216 
2275c5c4113dSnw141292 	/*
2276c5c4113dSnw141292 	 * Don't update name_cache because local sids don't have
2277c5c4113dSnw141292 	 * valid windows names.
2278c5c4113dSnw141292 	 */
2279e8c27ec8Sbaban 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
2280947c7bc0Sbaban 	return (IDMAP_SUCCESS);
2281c5c4113dSnw141292 }
2282c5c4113dSnw141292 
2283cd37da74Snw141292 static
2284cd37da74Snw141292 idmap_retcode
2285cd37da74Snw141292 lookup_localsid2pid(idmap_mapping *req, idmap_id_res *res)
2286cd37da74Snw141292 {
2287c5c4113dSnw141292 	char		*sidprefix;
2288c5c4113dSnw141292 	uint32_t	rid;
2289c5c4113dSnw141292 	int		s;
2290c5c4113dSnw141292 
2291c5c4113dSnw141292 	/*
2292c5c4113dSnw141292 	 * If the sidprefix == localsid then UID = last RID - 1000 or
2293c5c4113dSnw141292 	 * GID = last RID - 2^31.
2294c5c4113dSnw141292 	 */
2295e8c27ec8Sbaban 	if ((sidprefix = req->id1.idmap_id_u.sid.prefix) == NULL)
2296e8c27ec8Sbaban 		/* This means we are looking up by winname */
2297e8c27ec8Sbaban 		return (IDMAP_ERR_NOTFOUND);
2298c5c4113dSnw141292 	rid = req->id1.idmap_id_u.sid.rid;
2299c5c4113dSnw141292 
2300c5c4113dSnw141292 	RDLOCK_CONFIG();
2301c5c4113dSnw141292 	s = (_idmapdstate.cfg->pgcfg.machine_sid) ?
2302cd37da74Snw141292 	    strcasecmp(sidprefix, _idmapdstate.cfg->pgcfg.machine_sid) : 1;
2303c5c4113dSnw141292 	UNLOCK_CONFIG();
2304c5c4113dSnw141292 
2305e8c27ec8Sbaban 	/*
2306e8c27ec8Sbaban 	 * If the given sidprefix does not match machine_sid then this is
2307e8c27ec8Sbaban 	 * not a local SID.
2308e8c27ec8Sbaban 	 */
2309e8c27ec8Sbaban 	if (s != 0)
2310e8c27ec8Sbaban 		return (IDMAP_ERR_NOTFOUND);
2311e8c27ec8Sbaban 
2312e8c27ec8Sbaban 	switch (res->id.idtype) {
2313c5c4113dSnw141292 	case IDMAP_UID:
2314e8c27ec8Sbaban 		if (rid > INT32_MAX || rid < LOCALRID_MIN)
2315e8c27ec8Sbaban 			return (IDMAP_ERR_ARG);
2316c5c4113dSnw141292 		res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
2317c5c4113dSnw141292 		break;
2318c5c4113dSnw141292 	case IDMAP_GID:
2319e8c27ec8Sbaban 		if (rid <= INT32_MAX)
2320e8c27ec8Sbaban 			return (IDMAP_ERR_ARG);
2321c5c4113dSnw141292 		res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
2322c5c4113dSnw141292 		break;
2323c5c4113dSnw141292 	case IDMAP_POSIXID:
2324c5c4113dSnw141292 		if (rid > INT32_MAX) {
2325cd37da74Snw141292 			res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
2326c5c4113dSnw141292 			res->id.idtype = IDMAP_GID;
2327c5c4113dSnw141292 		} else if (rid < LOCALRID_MIN) {
2328e8c27ec8Sbaban 			return (IDMAP_ERR_ARG);
2329c5c4113dSnw141292 		} else {
2330c5c4113dSnw141292 			res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
2331c5c4113dSnw141292 			res->id.idtype = IDMAP_UID;
2332c5c4113dSnw141292 		}
2333c5c4113dSnw141292 		break;
2334c5c4113dSnw141292 	default:
2335c5c4113dSnw141292 		return (IDMAP_ERR_NOTSUPPORTED);
2336c5c4113dSnw141292 	}
233748258c6bSjp151216 	if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
233848258c6bSjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_LOCAL_SID;
233948258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_ALGORITHMIC;
234048258c6bSjp151216 	}
2341c5c4113dSnw141292 	return (IDMAP_SUCCESS);
2342c5c4113dSnw141292 }
2343c5c4113dSnw141292 
2344e8c27ec8Sbaban /*
2345e8c27ec8Sbaban  * Name service lookup by unixname to get pid
2346e8c27ec8Sbaban  */
2347cd37da74Snw141292 static
2348cd37da74Snw141292 idmap_retcode
2349e8c27ec8Sbaban ns_lookup_byname(const char *name, const char *lower_name, idmap_id *id)
2350cd37da74Snw141292 {
2351cd37da74Snw141292 	struct passwd	pwd, *pwdp;
2352cd37da74Snw141292 	struct group	grp, *grpp;
2353c5c4113dSnw141292 	char		buf[1024];
2354c5c4113dSnw141292 	int		errnum;
2355c5c4113dSnw141292 	const char	*me = "ns_lookup_byname";
2356c5c4113dSnw141292 
2357e8c27ec8Sbaban 	switch (id->idtype) {
2358e8c27ec8Sbaban 	case IDMAP_UID:
2359cd37da74Snw141292 		pwdp = getpwnam_r(name, &pwd, buf, sizeof (buf));
2360e8c27ec8Sbaban 		if (pwdp == NULL && errno == 0 && lower_name != NULL &&
2361cd37da74Snw141292 		    name != lower_name && strcmp(name, lower_name) != 0)
2362cd37da74Snw141292 			pwdp = getpwnam_r(lower_name, &pwd, buf, sizeof (buf));
2363cd37da74Snw141292 		if (pwdp == NULL) {
2364c5c4113dSnw141292 			errnum = errno;
2365c5c4113dSnw141292 			idmapdlog(LOG_WARNING,
2366c5c4113dSnw141292 			    "%s: getpwnam_r(%s) failed (%s).",
2367cd37da74Snw141292 			    me, name, errnum ? strerror(errnum) : "not found");
2368c5c4113dSnw141292 			if (errnum == 0)
2369c5c4113dSnw141292 				return (IDMAP_ERR_NOTFOUND);
2370c5c4113dSnw141292 			else
2371c5c4113dSnw141292 				return (IDMAP_ERR_INTERNAL);
2372c5c4113dSnw141292 		}
2373e8c27ec8Sbaban 		id->idmap_id_u.uid = pwd.pw_uid;
2374e8c27ec8Sbaban 		break;
2375e8c27ec8Sbaban 	case IDMAP_GID:
2376cd37da74Snw141292 		grpp = getgrnam_r(name, &grp, buf, sizeof (buf));
2377e8c27ec8Sbaban 		if (grpp == NULL && errno == 0 && lower_name != NULL &&
2378cd37da74Snw141292 		    name != lower_name && strcmp(name, lower_name) != 0)
2379cd37da74Snw141292 			grpp = getgrnam_r(lower_name, &grp, buf, sizeof (buf));
2380cd37da74Snw141292 		if (grpp == NULL) {
2381c5c4113dSnw141292 			errnum = errno;
2382c5c4113dSnw141292 			idmapdlog(LOG_WARNING,
2383c5c4113dSnw141292 			    "%s: getgrnam_r(%s) failed (%s).",
2384cd37da74Snw141292 			    me, name, errnum ? strerror(errnum) : "not found");
2385c5c4113dSnw141292 			if (errnum == 0)
2386c5c4113dSnw141292 				return (IDMAP_ERR_NOTFOUND);
2387c5c4113dSnw141292 			else
2388c5c4113dSnw141292 				return (IDMAP_ERR_INTERNAL);
2389c5c4113dSnw141292 		}
2390e8c27ec8Sbaban 		id->idmap_id_u.gid = grp.gr_gid;
2391e8c27ec8Sbaban 		break;
2392e8c27ec8Sbaban 	default:
2393e8c27ec8Sbaban 		return (IDMAP_ERR_ARG);
2394c5c4113dSnw141292 	}
2395c5c4113dSnw141292 	return (IDMAP_SUCCESS);
2396c5c4113dSnw141292 }
2397c5c4113dSnw141292 
2398e8c27ec8Sbaban 
2399e8c27ec8Sbaban /*
2400e8c27ec8Sbaban  * Name service lookup by pid to get unixname
2401e8c27ec8Sbaban  */
2402e8c27ec8Sbaban static
2403e8c27ec8Sbaban idmap_retcode
2404e8c27ec8Sbaban ns_lookup_bypid(uid_t pid, int is_user, char **unixname)
2405e8c27ec8Sbaban {
2406e8c27ec8Sbaban 	struct passwd	pwd;
2407e8c27ec8Sbaban 	struct group	grp;
2408e8c27ec8Sbaban 	char		buf[1024];
2409e8c27ec8Sbaban 	int		errnum;
2410e8c27ec8Sbaban 	const char	*me = "ns_lookup_bypid";
2411e8c27ec8Sbaban 
2412e8c27ec8Sbaban 	if (is_user) {
2413e8c27ec8Sbaban 		errno = 0;
2414e8c27ec8Sbaban 		if (getpwuid_r(pid, &pwd, buf, sizeof (buf)) == NULL) {
2415e8c27ec8Sbaban 			errnum = errno;
2416e8c27ec8Sbaban 			idmapdlog(LOG_WARNING,
2417e8c27ec8Sbaban 			    "%s: getpwuid_r(%u) failed (%s).",
2418e8c27ec8Sbaban 			    me, pid, errnum ? strerror(errnum) : "not found");
2419e8c27ec8Sbaban 			if (errnum == 0)
2420e8c27ec8Sbaban 				return (IDMAP_ERR_NOTFOUND);
2421e8c27ec8Sbaban 			else
2422e8c27ec8Sbaban 				return (IDMAP_ERR_INTERNAL);
2423e8c27ec8Sbaban 		}
2424e8c27ec8Sbaban 		*unixname = strdup(pwd.pw_name);
2425e8c27ec8Sbaban 	} else {
2426e8c27ec8Sbaban 		errno = 0;
2427e8c27ec8Sbaban 		if (getgrgid_r(pid, &grp, buf, sizeof (buf)) == NULL) {
2428e8c27ec8Sbaban 			errnum = errno;
2429e8c27ec8Sbaban 			idmapdlog(LOG_WARNING,
2430e8c27ec8Sbaban 			    "%s: getgrgid_r(%u) failed (%s).",
2431e8c27ec8Sbaban 			    me, pid, errnum ? strerror(errnum) : "not found");
2432e8c27ec8Sbaban 			if (errnum == 0)
2433e8c27ec8Sbaban 				return (IDMAP_ERR_NOTFOUND);
2434e8c27ec8Sbaban 			else
2435e8c27ec8Sbaban 				return (IDMAP_ERR_INTERNAL);
2436e8c27ec8Sbaban 		}
2437e8c27ec8Sbaban 		*unixname = strdup(grp.gr_name);
2438e8c27ec8Sbaban 	}
2439e8c27ec8Sbaban 	if (*unixname == NULL)
2440e8c27ec8Sbaban 		return (IDMAP_ERR_MEMORY);
2441e8c27ec8Sbaban 	return (IDMAP_SUCCESS);
2442e8c27ec8Sbaban }
2443e8c27ec8Sbaban 
2444c5c4113dSnw141292 /*
2445c5c4113dSnw141292  * Name-based mapping
2446c5c4113dSnw141292  *
2447c5c4113dSnw141292  * Case 1: If no rule matches do ephemeral
2448c5c4113dSnw141292  *
2449c5c4113dSnw141292  * Case 2: If rule matches and unixname is "" then return no mapping.
2450c5c4113dSnw141292  *
2451c5c4113dSnw141292  * Case 3: If rule matches and unixname is specified then lookup name
2452c5c4113dSnw141292  *  service using the unixname. If unixname not found then return no mapping.
2453c5c4113dSnw141292  *
2454c5c4113dSnw141292  * Case 4: If rule matches and unixname is * then lookup name service
2455c5c4113dSnw141292  *  using winname as the unixname. If unixname not found then process
2456c5c4113dSnw141292  *  other rules using the lookup order. If no other rule matches then do
2457c5c4113dSnw141292  *  ephemeral. Otherwise, based on the matched rule do Case 2 or 3 or 4.
2458c5c4113dSnw141292  *  This allows us to specify a fallback unixname per _domain_ or no mapping
2459c5c4113dSnw141292  *  instead of the default behaviour of doing ephemeral mapping.
2460c5c4113dSnw141292  *
2461c5c4113dSnw141292  * Example 1:
2462c5c4113dSnw141292  * *@sfbay == *
2463c5c4113dSnw141292  * If looking up windows users foo@sfbay and foo does not exists in
2464c5c4113dSnw141292  * the name service then foo@sfbay will be mapped to an ephemeral id.
2465c5c4113dSnw141292  *
2466c5c4113dSnw141292  * Example 2:
2467c5c4113dSnw141292  * *@sfbay == *
2468c5c4113dSnw141292  * *@sfbay => guest
2469c5c4113dSnw141292  * If looking up windows users foo@sfbay and foo does not exists in
2470c5c4113dSnw141292  * the name service then foo@sfbay will be mapped to guest.
2471c5c4113dSnw141292  *
2472c5c4113dSnw141292  * Example 3:
2473c5c4113dSnw141292  * *@sfbay == *
2474c5c4113dSnw141292  * *@sfbay => ""
2475c5c4113dSnw141292  * If looking up windows users foo@sfbay and foo does not exists in
2476c5c4113dSnw141292  * the name service then we will return no mapping for foo@sfbay.
2477c5c4113dSnw141292  *
2478c5c4113dSnw141292  */
2479cd37da74Snw141292 static
2480cd37da74Snw141292 idmap_retcode
2481cd37da74Snw141292 name_based_mapping_sid2pid(sqlite *db, idmap_mapping *req, idmap_id_res *res)
2482cd37da74Snw141292 {
2483cd37da74Snw141292 	const char	*unixname, *windomain;
2484cd37da74Snw141292 	char		*sql = NULL, *errmsg = NULL, *lower_winname = NULL;
2485c5c4113dSnw141292 	idmap_retcode	retcode;
2486cd37da74Snw141292 	char		*end, *lower_unixname, *winname;
2487c5c4113dSnw141292 	const char	**values;
2488c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
2489cd37da74Snw141292 	int		ncol, r, i, is_user, is_wuser;
249048258c6bSjp151216 	idmap_namerule	*rule = &res->info.how.idmap_how_u.rule;
249148258c6bSjp151216 	int		direction;
2492c5c4113dSnw141292 	const char	*me = "name_based_mapping_sid2pid";
2493c5c4113dSnw141292 
2494e8c27ec8Sbaban 	assert(req->id1name != NULL); /* We have winname */
2495e8c27ec8Sbaban 	assert(req->id2name == NULL); /* We don't have unixname */
2496e8c27ec8Sbaban 
24978e228215Sdm199847 	winname = req->id1name;
24988e228215Sdm199847 	windomain = req->id1domain;
2499cd37da74Snw141292 
2500cd37da74Snw141292 	switch (req->id1.idtype) {
2501cd37da74Snw141292 	case IDMAP_USID:
2502cd37da74Snw141292 		is_wuser = 1;
2503cd37da74Snw141292 		break;
2504cd37da74Snw141292 	case IDMAP_GSID:
2505cd37da74Snw141292 		is_wuser = 0;
2506cd37da74Snw141292 		break;
2507cd37da74Snw141292 	default:
2508e8c27ec8Sbaban 		idmapdlog(LOG_ERR, "%s: Unable to determine if the "
2509e8c27ec8Sbaban 		    "given Windows id is user or group.", me);
2510cd37da74Snw141292 		return (IDMAP_ERR_INTERNAL);
2511cd37da74Snw141292 	}
2512cd37da74Snw141292 
2513e8c27ec8Sbaban 	switch (res->id.idtype) {
2514cd37da74Snw141292 	case IDMAP_UID:
2515cd37da74Snw141292 		is_user = 1;
2516cd37da74Snw141292 		break;
2517cd37da74Snw141292 	case IDMAP_GID:
2518cd37da74Snw141292 		is_user = 0;
2519cd37da74Snw141292 		break;
2520cd37da74Snw141292 	case IDMAP_POSIXID:
2521cd37da74Snw141292 		is_user = is_wuser;
2522cd37da74Snw141292 		res->id.idtype = is_user ? IDMAP_UID : IDMAP_GID;
2523cd37da74Snw141292 		break;
2524cd37da74Snw141292 	}
2525c5c4113dSnw141292 
2526c5c4113dSnw141292 	i = 0;
252762c60062Sbaban 	if (windomain == NULL) {
252862c60062Sbaban 		windomain = "";
252962c60062Sbaban 	} else {
253062c60062Sbaban 		RDLOCK_CONFIG();
2531c8e26105Sjp151216 		if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
2532c8e26105Sjp151216 			if (strcasecmp(_idmapdstate.cfg->pgcfg.default_domain,
2533c5c4113dSnw141292 			    windomain) == 0)
2534c5c4113dSnw141292 				i = 1;
2535c5c4113dSnw141292 		}
2536c5c4113dSnw141292 		UNLOCK_CONFIG();
253762c60062Sbaban 	}
2538c5c4113dSnw141292 
2539cd37da74Snw141292 	if ((lower_winname = tolower_u8(winname)) == NULL)
2540cd37da74Snw141292 		lower_winname = winname;    /* hope for the best */
2541c5c4113dSnw141292 	sql = sqlite_mprintf(
254248258c6bSjp151216 	    "SELECT unixname, u2w_order, winname_display, windomain, is_nt4 "
254348258c6bSjp151216 	    "FROM namerules WHERE "
2544cd37da74Snw141292 	    "w2u_order > 0 AND is_user = %d AND is_wuser = %d AND "
2545c5c4113dSnw141292 	    "(winname = %Q OR winname = '*') AND "
2546c5c4113dSnw141292 	    "(windomain = %Q OR windomain = '*' %s) "
2547c5c4113dSnw141292 	    "ORDER BY w2u_order ASC;",
2548cd37da74Snw141292 	    is_user, is_wuser, lower_winname, windomain,
254962c60062Sbaban 	    i ? "OR windomain ISNULL OR windomain = ''" : "");
2550c5c4113dSnw141292 	if (sql == NULL) {
2551c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2552c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
2553c5c4113dSnw141292 		goto out;
2554c5c4113dSnw141292 	}
2555c5c4113dSnw141292 
2556c5c4113dSnw141292 	if (sqlite_compile(db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
2557c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
2558cd37da74Snw141292 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
2559cd37da74Snw141292 		    CHECK_NULL(errmsg));
2560c5c4113dSnw141292 		sqlite_freemem(errmsg);
2561c5c4113dSnw141292 		goto out;
2562c5c4113dSnw141292 	}
2563c5c4113dSnw141292 
256484decf41Sjp151216 	for (;;) {
2565c5c4113dSnw141292 		r = sqlite_step(vm, &ncol, &values, NULL);
256684decf41Sjp151216 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
2567c5c4113dSnw141292 
256884decf41Sjp151216 		if (r == SQLITE_ROW) {
256948258c6bSjp151216 			if (ncol < 5) {
2570c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
2571c5c4113dSnw141292 				goto out;
2572c5c4113dSnw141292 			}
2573c5c4113dSnw141292 			if (values[0] == NULL) {
2574c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
2575c5c4113dSnw141292 				goto out;
2576c5c4113dSnw141292 			}
2577c5c4113dSnw141292 
257848258c6bSjp151216 			if (values[1] != NULL)
257948258c6bSjp151216 				direction =
258048258c6bSjp151216 				    (strtol(values[1], &end, 10) == 0)?
258148258c6bSjp151216 				    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
258248258c6bSjp151216 			else
258348258c6bSjp151216 				direction = IDMAP_DIRECTION_W2U;
258448258c6bSjp151216 
2585c5c4113dSnw141292 			if (EMPTY_NAME(values[0])) {
258648258c6bSjp151216 				idmap_namerule_set(rule, values[3], values[2],
258748258c6bSjp151216 				    values[0], is_wuser, is_user,
258848258c6bSjp151216 				    strtol(values[4], &end, 10),
258948258c6bSjp151216 				    direction);
2590c5c4113dSnw141292 				retcode = IDMAP_ERR_NOMAPPING;
2591c5c4113dSnw141292 				goto out;
2592c5c4113dSnw141292 			}
259348258c6bSjp151216 
259448258c6bSjp151216 			if (values[0][0] == '*') {
259548258c6bSjp151216 				unixname = winname;
259648258c6bSjp151216 				lower_unixname = lower_winname;
259748258c6bSjp151216 			} else {
259848258c6bSjp151216 				unixname = values[0];
259948258c6bSjp151216 				lower_unixname = NULL;
260048258c6bSjp151216 			}
260148258c6bSjp151216 
2602e8c27ec8Sbaban 			retcode = ns_lookup_byname(unixname, lower_unixname,
2603e8c27ec8Sbaban 			    &res->id);
2604c5c4113dSnw141292 			if (retcode == IDMAP_ERR_NOTFOUND) {
260548258c6bSjp151216 				if (values[0][0] == '*')
2606c5c4113dSnw141292 					/* Case 4 */
2607c5c4113dSnw141292 					continue;
260848258c6bSjp151216 				else {
2609c5c4113dSnw141292 					/* Case 3 */
261048258c6bSjp151216 					idmap_namerule_set(rule, values[3],
261148258c6bSjp151216 					    values[2], values[0], is_wuser,
261248258c6bSjp151216 					    is_user,
261348258c6bSjp151216 					    strtol(values[4], &end, 10),
261448258c6bSjp151216 					    direction);
2615c5c4113dSnw141292 					retcode = IDMAP_ERR_NOMAPPING;
2616c5c4113dSnw141292 				}
261748258c6bSjp151216 			}
2618c5c4113dSnw141292 			goto out;
2619c5c4113dSnw141292 		} else if (r == SQLITE_DONE) {
2620c5c4113dSnw141292 			retcode = IDMAP_ERR_NOTFOUND;
2621c5c4113dSnw141292 			goto out;
2622c5c4113dSnw141292 		} else {
2623c5c4113dSnw141292 			(void) sqlite_finalize(vm, &errmsg);
2624c5c4113dSnw141292 			vm = NULL;
2625cd37da74Snw141292 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
2626cd37da74Snw141292 			    CHECK_NULL(errmsg));
2627c5c4113dSnw141292 			sqlite_freemem(errmsg);
2628c5c4113dSnw141292 			retcode = IDMAP_ERR_INTERNAL;
2629c5c4113dSnw141292 			goto out;
2630c5c4113dSnw141292 		}
2631c5c4113dSnw141292 	}
2632c5c4113dSnw141292 
2633c5c4113dSnw141292 out:
263448258c6bSjp151216 	if (sql != NULL)
2635c5c4113dSnw141292 		sqlite_freemem(sql);
263648258c6bSjp151216 	res->info.how.map_type = IDMAP_MAP_TYPE_RULE_BASED;
2637c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
263862c60062Sbaban 		if (values[1] != NULL)
2639c5c4113dSnw141292 			res->direction =
2640651c0131Sbaban 			    (strtol(values[1], &end, 10) == 0)?
2641651c0131Sbaban 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
2642c5c4113dSnw141292 		else
2643651c0131Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
264448258c6bSjp151216 
26458e228215Sdm199847 		req->id2name = strdup(unixname);
264648258c6bSjp151216 		idmap_namerule_set(rule, values[3], values[2],
264748258c6bSjp151216 		    values[0], is_wuser, is_user, strtol(values[4], &end, 10),
264848258c6bSjp151216 		    res->direction);
264948258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
2650c5c4113dSnw141292 	}
2651cd37da74Snw141292 	if (lower_winname != NULL && lower_winname != winname)
2652cd37da74Snw141292 		free(lower_winname);
265362c60062Sbaban 	if (vm != NULL)
2654c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
2655c5c4113dSnw141292 	return (retcode);
2656c5c4113dSnw141292 }
2657c5c4113dSnw141292 
2658c5c4113dSnw141292 static
2659c5c4113dSnw141292 int
2660c5c4113dSnw141292 get_next_eph_uid(uid_t *next_uid)
2661c5c4113dSnw141292 {
2662c5c4113dSnw141292 	uid_t uid;
2663c5c4113dSnw141292 	gid_t gid;
2664c5c4113dSnw141292 	int err;
2665c5c4113dSnw141292 
2666c5c4113dSnw141292 	*next_uid = (uid_t)-1;
2667c5c4113dSnw141292 	uid = _idmapdstate.next_uid++;
2668c5c4113dSnw141292 	if (uid >= _idmapdstate.limit_uid) {
2669c5c4113dSnw141292 		if ((err = allocids(0, 8192, &uid, 0, &gid)) != 0)
2670c5c4113dSnw141292 			return (err);
2671c5c4113dSnw141292 
2672c5c4113dSnw141292 		_idmapdstate.limit_uid = uid + 8192;
2673c5c4113dSnw141292 		_idmapdstate.next_uid = uid;
2674c5c4113dSnw141292 	}
2675c5c4113dSnw141292 	*next_uid = uid;
2676c5c4113dSnw141292 
2677c5c4113dSnw141292 	return (0);
2678c5c4113dSnw141292 }
2679c5c4113dSnw141292 
2680c5c4113dSnw141292 static
2681c5c4113dSnw141292 int
2682c5c4113dSnw141292 get_next_eph_gid(gid_t *next_gid)
2683c5c4113dSnw141292 {
2684c5c4113dSnw141292 	uid_t uid;
2685c5c4113dSnw141292 	gid_t gid;
2686c5c4113dSnw141292 	int err;
2687c5c4113dSnw141292 
2688c5c4113dSnw141292 	*next_gid = (uid_t)-1;
2689c5c4113dSnw141292 	gid = _idmapdstate.next_gid++;
2690c5c4113dSnw141292 	if (gid >= _idmapdstate.limit_gid) {
2691c5c4113dSnw141292 		if ((err = allocids(0, 0, &uid, 8192, &gid)) != 0)
2692c5c4113dSnw141292 			return (err);
2693c5c4113dSnw141292 
2694c5c4113dSnw141292 		_idmapdstate.limit_gid = gid + 8192;
2695c5c4113dSnw141292 		_idmapdstate.next_gid = gid;
2696c5c4113dSnw141292 	}
2697c5c4113dSnw141292 	*next_gid = gid;
2698c5c4113dSnw141292 
2699c5c4113dSnw141292 	return (0);
2700c5c4113dSnw141292 }
2701c5c4113dSnw141292 
270262c60062Sbaban static
270362c60062Sbaban int
2704cd37da74Snw141292 gethash(const char *str, uint32_t num, uint_t htsize)
2705cd37da74Snw141292 {
270662c60062Sbaban 	uint_t  hval, i, len;
270762c60062Sbaban 
270862c60062Sbaban 	if (str == NULL)
270962c60062Sbaban 		return (0);
271062c60062Sbaban 	for (len = strlen(str), hval = 0, i = 0; i < len; i++) {
271162c60062Sbaban 		hval += str[i];
271262c60062Sbaban 		hval += (hval << 10);
271362c60062Sbaban 		hval ^= (hval >> 6);
271462c60062Sbaban 	}
271562c60062Sbaban 	for (str = (const char *)&num, i = 0; i < sizeof (num); i++) {
271662c60062Sbaban 		hval += str[i];
271762c60062Sbaban 		hval += (hval << 10);
271862c60062Sbaban 		hval ^= (hval >> 6);
271962c60062Sbaban 	}
272062c60062Sbaban 	hval += (hval << 3);
272162c60062Sbaban 	hval ^= (hval >> 11);
272262c60062Sbaban 	hval += (hval << 15);
272362c60062Sbaban 	return (hval % htsize);
272462c60062Sbaban }
272562c60062Sbaban 
272662c60062Sbaban static
272762c60062Sbaban int
272862c60062Sbaban get_from_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid,
2729cd37da74Snw141292 		uid_t *pid)
2730cd37da74Snw141292 {
273162c60062Sbaban 	uint_t		next, key;
273262c60062Sbaban 	uint_t		htsize = state->sid_history_size;
273362c60062Sbaban 	idmap_sid	*sid;
273462c60062Sbaban 
273562c60062Sbaban 	next = gethash(prefix, rid, htsize);
273662c60062Sbaban 	while (next != htsize) {
273762c60062Sbaban 		key = state->sid_history[next].key;
273862c60062Sbaban 		if (key == htsize)
273962c60062Sbaban 			return (0);
274062c60062Sbaban 		sid = &state->batch->idmap_mapping_batch_val[key].id1.
274162c60062Sbaban 		    idmap_id_u.sid;
274262c60062Sbaban 		if (sid->rid == rid && strcmp(sid->prefix, prefix) == 0) {
274362c60062Sbaban 			*pid = state->result->ids.ids_val[key].id.
274462c60062Sbaban 			    idmap_id_u.uid;
274562c60062Sbaban 			return (1);
274662c60062Sbaban 		}
274762c60062Sbaban 		next = state->sid_history[next].next;
274862c60062Sbaban 	}
274962c60062Sbaban 	return (0);
275062c60062Sbaban }
275162c60062Sbaban 
275262c60062Sbaban static
275362c60062Sbaban void
2754cd37da74Snw141292 add_to_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid)
2755cd37da74Snw141292 {
275662c60062Sbaban 	uint_t		hash, next;
275762c60062Sbaban 	uint_t		htsize = state->sid_history_size;
275862c60062Sbaban 
275962c60062Sbaban 	hash = next = gethash(prefix, rid, htsize);
276062c60062Sbaban 	while (state->sid_history[next].key != htsize) {
276162c60062Sbaban 		next++;
276262c60062Sbaban 		next %= htsize;
276362c60062Sbaban 	}
276462c60062Sbaban 	state->sid_history[next].key = state->curpos;
276562c60062Sbaban 	if (hash == next)
276662c60062Sbaban 		return;
276762c60062Sbaban 	state->sid_history[next].next = state->sid_history[hash].next;
276862c60062Sbaban 	state->sid_history[hash].next = next;
276962c60062Sbaban }
2770c5c4113dSnw141292 
2771e8c27ec8Sbaban void
2772e8c27ec8Sbaban cleanup_lookup_state(lookup_state_t *state)
2773e8c27ec8Sbaban {
2774e8c27ec8Sbaban 	free(state->sid_history);
2775e8c27ec8Sbaban 	free(state->ad_unixuser_attr);
2776e8c27ec8Sbaban 	free(state->ad_unixgroup_attr);
2777e8c27ec8Sbaban }
2778e8c27ec8Sbaban 
2779c5c4113dSnw141292 /* ARGSUSED */
2780c5c4113dSnw141292 static
2781c5c4113dSnw141292 idmap_retcode
278262c60062Sbaban dynamic_ephemeral_mapping(lookup_state_t *state, sqlite *cache,
2783cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
2784cd37da74Snw141292 {
2785c5c4113dSnw141292 
2786c5c4113dSnw141292 	uid_t		next_pid;
2787c5c4113dSnw141292 
2788651c0131Sbaban 	res->direction = IDMAP_DIRECTION_BI;
278962c60062Sbaban 
279048258c6bSjp151216 	if (IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
279148258c6bSjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
279248258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_CACHE;
279362c60062Sbaban 		return (IDMAP_SUCCESS);
279448258c6bSjp151216 	}
279562c60062Sbaban 
279662c60062Sbaban 	if (state->sid_history != NULL &&
279762c60062Sbaban 	    get_from_sid_history(state, req->id1.idmap_id_u.sid.prefix,
279862c60062Sbaban 	    req->id1.idmap_id_u.sid.rid, &next_pid)) {
279962c60062Sbaban 		res->id.idmap_id_u.uid = next_pid;
280048258c6bSjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
280148258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
280262c60062Sbaban 		return (IDMAP_SUCCESS);
280362c60062Sbaban 	}
280462c60062Sbaban 
280562c60062Sbaban 	if (res->id.idtype == IDMAP_UID) {
2806c5c4113dSnw141292 		if (get_next_eph_uid(&next_pid) != 0)
2807c5c4113dSnw141292 			return (IDMAP_ERR_INTERNAL);
2808c5c4113dSnw141292 		res->id.idmap_id_u.uid = next_pid;
2809c5c4113dSnw141292 	} else {
2810c5c4113dSnw141292 		if (get_next_eph_gid(&next_pid) != 0)
2811c5c4113dSnw141292 			return (IDMAP_ERR_INTERNAL);
2812c5c4113dSnw141292 		res->id.idmap_id_u.gid = next_pid;
2813c5c4113dSnw141292 	}
2814c5c4113dSnw141292 
281548258c6bSjp151216 	res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
281648258c6bSjp151216 	res->info.src = IDMAP_MAP_SRC_NEW;
281762c60062Sbaban 	if (state->sid_history != NULL)
281862c60062Sbaban 		add_to_sid_history(state, req->id1.idmap_id_u.sid.prefix,
281962c60062Sbaban 		    req->id1.idmap_id_u.sid.rid);
282062c60062Sbaban 
2821c5c4113dSnw141292 	return (IDMAP_SUCCESS);
2822c5c4113dSnw141292 }
2823c5c4113dSnw141292 
2824c5c4113dSnw141292 idmap_retcode
2825c5c4113dSnw141292 sid2pid_second_pass(lookup_state_t *state, sqlite *cache, sqlite *db,
2826cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
2827cd37da74Snw141292 {
2828c5c4113dSnw141292 	idmap_retcode	retcode;
2829c5c4113dSnw141292 
2830c5c4113dSnw141292 	/* Check if second pass is needed */
2831e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
2832c5c4113dSnw141292 		return (res->retcode);
2833c5c4113dSnw141292 
2834c5c4113dSnw141292 	/* Get status from previous pass */
2835e8c27ec8Sbaban 	retcode = res->retcode;
2836e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
2837e8c27ec8Sbaban 		goto out;
2838c5c4113dSnw141292 
2839e8c27ec8Sbaban 	/*
2840e8c27ec8Sbaban 	 * If directory-based name mapping is enabled then the unixname
2841e8c27ec8Sbaban 	 * may already have been retrieved from the AD object (AD-mode or
2842e8c27ec8Sbaban 	 * mixed-mode) or from native LDAP object (nldap-mode) -- done.
2843e8c27ec8Sbaban 	 */
2844e8c27ec8Sbaban 	if (req->id2name != NULL) {
2845e8c27ec8Sbaban 		assert(res->id.idtype != IDMAP_POSIXID);
2846e8c27ec8Sbaban 		if (AD_MODE(res->id.idtype, state))
2847e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
2848e8c27ec8Sbaban 		else if (NLDAP_MODE(res->id.idtype, state))
2849e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
2850e8c27ec8Sbaban 		else if (MIXED_MODE(res->id.idtype, state))
2851e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
2852c5c4113dSnw141292 
2853e8c27ec8Sbaban 		/*
2854e8c27ec8Sbaban 		 * Special case: (1) If the ad_unixuser_attr and
2855e8c27ec8Sbaban 		 * ad_unixgroup_attr uses the same attribute
2856e8c27ec8Sbaban 		 * name and (2) if this is a diagonal mapping
2857e8c27ec8Sbaban 		 * request and (3) the unixname has been retrieved
2858e8c27ec8Sbaban 		 * from the AD object -- then we ignore it and fallback
2859e8c27ec8Sbaban 		 * to name-based mapping rules and ephemeral mapping
2860e8c27ec8Sbaban 		 *
2861e8c27ec8Sbaban 		 * Example:
2862e8c27ec8Sbaban 		 *  Properties:
2863e8c27ec8Sbaban 		 *    config/ad_unixuser_attr = "unixname"
2864e8c27ec8Sbaban 		 *    config/ad_unixgroup_attr = "unixname"
2865e8c27ec8Sbaban 		 *  AD user object:
2866e8c27ec8Sbaban 		 *    dn: cn=bob ...
2867e8c27ec8Sbaban 		 *    objectclass: user
2868e8c27ec8Sbaban 		 *    sam: bob
2869e8c27ec8Sbaban 		 *    unixname: bob1234
2870e8c27ec8Sbaban 		 *  AD group object:
2871e8c27ec8Sbaban 		 *    dn: cn=winadmins ...
2872e8c27ec8Sbaban 		 *    objectclass: group
2873e8c27ec8Sbaban 		 *    sam: winadmins
2874e8c27ec8Sbaban 		 *    unixname: unixadmins
2875e8c27ec8Sbaban 		 *
2876e8c27ec8Sbaban 		 *  In this example whether "unixname" refers to a unixuser
2877e8c27ec8Sbaban 		 *  or unixgroup depends upon the AD object.
2878e8c27ec8Sbaban 		 *
2879e8c27ec8Sbaban 		 * $idmap show -c winname:bob gid
2880e8c27ec8Sbaban 		 *    AD lookup by "samAccountName=bob" for
2881e8c27ec8Sbaban 		 *    "ad_unixgroup_attr (i.e unixname)" for directory-based
2882e8c27ec8Sbaban 		 *    mapping would get "bob1234" which is not what we want.
2883e8c27ec8Sbaban 		 *    Now why not getgrnam_r("bob1234") and use it if it
2884e8c27ec8Sbaban 		 *    is indeed a unixgroup? That's because Unix can have
2885e8c27ec8Sbaban 		 *    users and groups with the same name and we clearly
2886e8c27ec8Sbaban 		 *    don't know the intention of the admin here.
2887e8c27ec8Sbaban 		 *    Therefore we ignore this and fallback to name-based
2888e8c27ec8Sbaban 		 *    mapping rules or ephemeral mapping.
2889e8c27ec8Sbaban 		 */
2890e8c27ec8Sbaban 		if ((AD_MODE(res->id.idtype, state) ||
2891e8c27ec8Sbaban 		    MIXED_MODE(res->id.idtype, state)) &&
2892e8c27ec8Sbaban 		    state->ad_unixuser_attr != NULL &&
2893e8c27ec8Sbaban 		    state->ad_unixgroup_attr != NULL &&
2894e8c27ec8Sbaban 		    strcasecmp(state->ad_unixuser_attr,
2895e8c27ec8Sbaban 		    state->ad_unixgroup_attr) == 0 &&
2896e8c27ec8Sbaban 		    ((req->id1.idtype == IDMAP_USID &&
2897e8c27ec8Sbaban 		    res->id.idtype == IDMAP_GID) ||
2898e8c27ec8Sbaban 		    (req->id1.idtype == IDMAP_GSID &&
2899e8c27ec8Sbaban 		    res->id.idtype == IDMAP_UID))) {
2900e8c27ec8Sbaban 			free(req->id2name);
2901e8c27ec8Sbaban 			req->id2name = NULL;
2902e8c27ec8Sbaban 			res->id.idmap_id_u.uid = SENTINEL_PID;
2903e8c27ec8Sbaban 			/* fallback */
2904e8c27ec8Sbaban 		} else {
2905e8c27ec8Sbaban 			if (res->id.idmap_id_u.uid == SENTINEL_PID)
2906e8c27ec8Sbaban 				retcode = ns_lookup_byname(req->id2name,
2907e8c27ec8Sbaban 				    NULL, &res->id);
2908e8c27ec8Sbaban 			/*
2909e8c27ec8Sbaban 			 * We don't fallback to name-based mapping rules
2910e8c27ec8Sbaban 			 * or ephemeral mapping.
2911e8c27ec8Sbaban 			 */
2912c5c4113dSnw141292 			goto out;
2913c5c4113dSnw141292 		}
2914e8c27ec8Sbaban 	}
2915c5c4113dSnw141292 
291648258c6bSjp151216 	/* Free any mapping info from Directory based mapping */
291748258c6bSjp151216 	if (res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN)
291848258c6bSjp151216 		idmap_info_free(&res->info);
291948258c6bSjp151216 
2920e8c27ec8Sbaban 	/*
2921e8c27ec8Sbaban 	 * If we don't have unixname then evaluate local name-based
2922e8c27ec8Sbaban 	 * mapping rules.
2923e8c27ec8Sbaban 	 */
2924c5c4113dSnw141292 	retcode = name_based_mapping_sid2pid(db, req, res);
2925e8c27ec8Sbaban 	if (retcode != IDMAP_ERR_NOTFOUND)
2926e8c27ec8Sbaban 		goto out;
2927e8c27ec8Sbaban 
2928c5c4113dSnw141292 	/* If not found, do ephemeral mapping */
292962c60062Sbaban 	retcode = dynamic_ephemeral_mapping(state, cache, req, res);
2930c5c4113dSnw141292 
2931c5c4113dSnw141292 out:
2932c5c4113dSnw141292 	res->retcode = idmap_stat4prot(retcode);
2933e8c27ec8Sbaban 	if (res->retcode != IDMAP_SUCCESS) {
2934e8c27ec8Sbaban 		req->direction = _IDMAP_F_DONE;
2935e8c27ec8Sbaban 		res->id.idmap_id_u.uid = UID_NOBODY;
2936e8c27ec8Sbaban 	}
2937e8c27ec8Sbaban 	if (!ARE_WE_DONE(req->direction))
2938e8c27ec8Sbaban 		state->sid2pid_done = FALSE;
2939c5c4113dSnw141292 	return (retcode);
2940c5c4113dSnw141292 }
2941c5c4113dSnw141292 
2942c5c4113dSnw141292 idmap_retcode
2943c5c4113dSnw141292 update_cache_pid2sid(lookup_state_t *state, sqlite *cache,
2944cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
2945cd37da74Snw141292 {
2946c5c4113dSnw141292 	char		*sql = NULL;
2947c5c4113dSnw141292 	idmap_retcode	retcode;
294848258c6bSjp151216 	char		*map_dn = NULL;
294948258c6bSjp151216 	char		*map_attr = NULL;
295048258c6bSjp151216 	char		*map_value = NULL;
295148258c6bSjp151216 	char 		*map_windomain = NULL;
295248258c6bSjp151216 	char		*map_winname = NULL;
295348258c6bSjp151216 	char		*map_unixname = NULL;
295448258c6bSjp151216 	int		map_is_nt4 = FALSE;
2955c5c4113dSnw141292 
2956c5c4113dSnw141292 	/* Check if we need to cache anything */
2957e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
2958c5c4113dSnw141292 		return (IDMAP_SUCCESS);
2959c5c4113dSnw141292 
2960c5c4113dSnw141292 	/* We don't cache negative entries */
2961c5c4113dSnw141292 	if (res->retcode != IDMAP_SUCCESS)
2962c5c4113dSnw141292 		return (IDMAP_SUCCESS);
2963c5c4113dSnw141292 
2964e8c27ec8Sbaban 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
296548258c6bSjp151216 	assert(req->id1.idmap_id_u.uid != SENTINEL_PID);
296648258c6bSjp151216 	assert(res->id.idtype != IDMAP_SID);
296748258c6bSjp151216 
296848258c6bSjp151216 	assert(res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN);
296948258c6bSjp151216 	switch (res->info.how.map_type) {
297048258c6bSjp151216 	case IDMAP_MAP_TYPE_DS_AD:
297148258c6bSjp151216 		map_dn = res->info.how.idmap_how_u.ad.dn;
297248258c6bSjp151216 		map_attr = res->info.how.idmap_how_u.ad.attr;
297348258c6bSjp151216 		map_value = res->info.how.idmap_how_u.ad.value;
297448258c6bSjp151216 		break;
297548258c6bSjp151216 
297648258c6bSjp151216 	case IDMAP_MAP_TYPE_DS_NLDAP:
297748258c6bSjp151216 		map_dn = res->info.how.idmap_how_u.nldap.dn;
297848258c6bSjp151216 		map_attr = res->info.how.idmap_how_u.nldap.attr;
297948258c6bSjp151216 		map_value = res->info.how.idmap_how_u.nldap.value;
298048258c6bSjp151216 		break;
298148258c6bSjp151216 
298248258c6bSjp151216 	case IDMAP_MAP_TYPE_RULE_BASED:
298348258c6bSjp151216 		map_windomain = res->info.how.idmap_how_u.rule.windomain;
298448258c6bSjp151216 		map_winname = res->info.how.idmap_how_u.rule.winname;
298548258c6bSjp151216 		map_unixname = res->info.how.idmap_how_u.rule.unixname;
298648258c6bSjp151216 		map_is_nt4 = res->info.how.idmap_how_u.rule.is_nt4;
298748258c6bSjp151216 		break;
298848258c6bSjp151216 
298948258c6bSjp151216 	case IDMAP_MAP_TYPE_EPHEMERAL:
299048258c6bSjp151216 		break;
299148258c6bSjp151216 
299248258c6bSjp151216 	case IDMAP_MAP_TYPE_LOCAL_SID:
299348258c6bSjp151216 		break;
299448258c6bSjp151216 
299548258c6bSjp151216 	default:
299648258c6bSjp151216 		/* Dont cache other mapping types */
299748258c6bSjp151216 		assert(FALSE);
299848258c6bSjp151216 	}
2999e8c27ec8Sbaban 
3000c5c4113dSnw141292 	/*
3001c5c4113dSnw141292 	 * Using NULL for u2w instead of 0 so that our trigger allows
3002c5c4113dSnw141292 	 * the same pid to be the destination in multiple entries
3003c5c4113dSnw141292 	 */
3004c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
3005cd37da74Snw141292 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
300648258c6bSjp151216 	    "is_user, is_wuser, expiration, w2u, u2w, "
300748258c6bSjp151216 	    "map_type, map_dn, map_attr, map_value, map_windomain, "
300848258c6bSjp151216 	    "map_winname, map_unixname, map_is_nt4) "
3009cd37da74Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
301048258c6bSjp151216 	    "strftime('%%s','now') + 600, %q, 1, "
301148258c6bSjp151216 	    "%d, %Q, %Q, %Q, %Q, %Q, %Q, %d); ",
3012cd37da74Snw141292 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
3013cd37da74Snw141292 	    req->id2domain, req->id2name, req->id1.idmap_id_u.uid,
3014cd37da74Snw141292 	    req->id1name, (req->id1.idtype == IDMAP_UID) ? 1 : 0,
3015e8c27ec8Sbaban 	    (res->id.idtype == IDMAP_USID) ? 1 : 0,
301648258c6bSjp151216 	    (res->direction == 0) ? "1" : NULL,
301748258c6bSjp151216 	    res->info.how.map_type, map_dn, map_attr, map_value,
301848258c6bSjp151216 	    map_windomain, map_winname, map_unixname, map_is_nt4);
3019c5c4113dSnw141292 
3020c5c4113dSnw141292 	if (sql == NULL) {
3021c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3022c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3023c5c4113dSnw141292 		goto out;
3024c5c4113dSnw141292 	}
3025c5c4113dSnw141292 
302671590c90Snw141292 	retcode = sql_exec_no_cb(cache, IDMAP_CACHENAME, sql);
3027c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
3028c5c4113dSnw141292 		goto out;
3029c5c4113dSnw141292 
3030c5c4113dSnw141292 	state->pid2sid_done = FALSE;
3031c5c4113dSnw141292 	sqlite_freemem(sql);
3032c5c4113dSnw141292 	sql = NULL;
3033c5c4113dSnw141292 
3034e8c27ec8Sbaban 	/* Check if we need to update namecache */
3035e8c27ec8Sbaban 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
3036c5c4113dSnw141292 		goto out;
3037c5c4113dSnw141292 
30388e228215Sdm199847 	if (req->id2name == NULL)
3039c5c4113dSnw141292 		goto out;
3040c5c4113dSnw141292 
3041c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
3042cd37da74Snw141292 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
3043c5c4113dSnw141292 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
3044cd37da74Snw141292 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
3045cd37da74Snw141292 	    req->id2name, req->id2domain,
3046e8c27ec8Sbaban 	    (res->id.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
3047c5c4113dSnw141292 
3048c5c4113dSnw141292 	if (sql == NULL) {
3049c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3050c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3051c5c4113dSnw141292 		goto out;
3052c5c4113dSnw141292 	}
3053c5c4113dSnw141292 
305471590c90Snw141292 	retcode = sql_exec_no_cb(cache, IDMAP_CACHENAME, sql);
3055c5c4113dSnw141292 
3056c5c4113dSnw141292 out:
305748258c6bSjp151216 	if (!(req->flag & IDMAP_REQ_FLG_MAPPING_INFO))
305848258c6bSjp151216 		idmap_info_free(&res->info);
305962c60062Sbaban 	if (sql != NULL)
3060c5c4113dSnw141292 		sqlite_freemem(sql);
3061c5c4113dSnw141292 	return (retcode);
3062c5c4113dSnw141292 }
3063c5c4113dSnw141292 
3064c5c4113dSnw141292 idmap_retcode
3065c5c4113dSnw141292 update_cache_sid2pid(lookup_state_t *state, sqlite *cache,
3066cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
3067cd37da74Snw141292 {
3068c5c4113dSnw141292 	char		*sql = NULL;
3069c5c4113dSnw141292 	idmap_retcode	retcode;
3070c5c4113dSnw141292 	int		is_eph_user;
307148258c6bSjp151216 	char		*map_dn = NULL;
307248258c6bSjp151216 	char		*map_attr = NULL;
307348258c6bSjp151216 	char		*map_value = NULL;
307448258c6bSjp151216 	char 		*map_windomain = NULL;
307548258c6bSjp151216 	char		*map_winname = NULL;
307648258c6bSjp151216 	char		*map_unixname = NULL;
307748258c6bSjp151216 	int		map_is_nt4 = FALSE;
3078c5c4113dSnw141292 
3079c5c4113dSnw141292 	/* Check if we need to cache anything */
3080e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
3081c5c4113dSnw141292 		return (IDMAP_SUCCESS);
3082c5c4113dSnw141292 
3083c5c4113dSnw141292 	/* We don't cache negative entries */
3084c5c4113dSnw141292 	if (res->retcode != IDMAP_SUCCESS)
3085c5c4113dSnw141292 		return (IDMAP_SUCCESS);
3086c5c4113dSnw141292 
3087c5c4113dSnw141292 	if (req->direction & _IDMAP_F_EXP_EPH_UID)
3088c5c4113dSnw141292 		is_eph_user = 1;
3089c5c4113dSnw141292 	else if (req->direction & _IDMAP_F_EXP_EPH_GID)
3090c5c4113dSnw141292 		is_eph_user = 0;
3091c5c4113dSnw141292 	else
3092c5c4113dSnw141292 		is_eph_user = -1;
3093c5c4113dSnw141292 
3094c5c4113dSnw141292 	if (is_eph_user >= 0 && !IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
3095c5c4113dSnw141292 		sql = sqlite_mprintf("UPDATE idmap_cache "
3096c5c4113dSnw141292 		    "SET w2u = 0 WHERE "
3097c5c4113dSnw141292 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
3098c5c4113dSnw141292 		    "pid >= 2147483648 AND is_user = %d;",
3099c5c4113dSnw141292 		    req->id1.idmap_id_u.sid.prefix,
3100c5c4113dSnw141292 		    req->id1.idmap_id_u.sid.rid,
3101c5c4113dSnw141292 		    is_eph_user);
3102c5c4113dSnw141292 		if (sql == NULL) {
3103c5c4113dSnw141292 			retcode = IDMAP_ERR_INTERNAL;
3104c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
3105c5c4113dSnw141292 			goto out;
3106c5c4113dSnw141292 		}
3107c5c4113dSnw141292 
310871590c90Snw141292 		retcode = sql_exec_no_cb(cache, IDMAP_CACHENAME, sql);
3109c5c4113dSnw141292 		if (retcode != IDMAP_SUCCESS)
3110c5c4113dSnw141292 			goto out;
3111c5c4113dSnw141292 
3112c5c4113dSnw141292 		sqlite_freemem(sql);
3113c5c4113dSnw141292 		sql = NULL;
3114c5c4113dSnw141292 	}
3115c5c4113dSnw141292 
3116e8c27ec8Sbaban 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
311748258c6bSjp151216 	assert(res->id.idmap_id_u.uid != SENTINEL_PID);
311848258c6bSjp151216 
311948258c6bSjp151216 	switch (res->info.how.map_type) {
312048258c6bSjp151216 	case IDMAP_MAP_TYPE_DS_AD:
312148258c6bSjp151216 		map_dn = res->info.how.idmap_how_u.ad.dn;
312248258c6bSjp151216 		map_attr = res->info.how.idmap_how_u.ad.attr;
312348258c6bSjp151216 		map_value = res->info.how.idmap_how_u.ad.value;
312448258c6bSjp151216 		break;
312548258c6bSjp151216 
312648258c6bSjp151216 	case IDMAP_MAP_TYPE_DS_NLDAP:
312748258c6bSjp151216 		map_dn = res->info.how.idmap_how_u.nldap.dn;
312848258c6bSjp151216 		map_attr = res->info.how.idmap_how_u.ad.attr;
312948258c6bSjp151216 		map_value = res->info.how.idmap_how_u.nldap.value;
313048258c6bSjp151216 		break;
313148258c6bSjp151216 
313248258c6bSjp151216 	case IDMAP_MAP_TYPE_RULE_BASED:
313348258c6bSjp151216 		map_windomain = res->info.how.idmap_how_u.rule.windomain;
313448258c6bSjp151216 		map_winname = res->info.how.idmap_how_u.rule.winname;
313548258c6bSjp151216 		map_unixname = res->info.how.idmap_how_u.rule.unixname;
313648258c6bSjp151216 		map_is_nt4 = res->info.how.idmap_how_u.rule.is_nt4;
313748258c6bSjp151216 		break;
313848258c6bSjp151216 
313948258c6bSjp151216 	case IDMAP_MAP_TYPE_EPHEMERAL:
314048258c6bSjp151216 		break;
314148258c6bSjp151216 
314248258c6bSjp151216 	default:
314348258c6bSjp151216 		/* Dont cache other mapping types */
314448258c6bSjp151216 		assert(FALSE);
314548258c6bSjp151216 	}
3146cd37da74Snw141292 
3147c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
3148cd37da74Snw141292 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
314948258c6bSjp151216 	    "is_user, is_wuser, expiration, w2u, u2w, "
315048258c6bSjp151216 	    "map_type, map_dn, map_attr, map_value, map_windomain, "
315148258c6bSjp151216 	    "map_winname, map_unixname, map_is_nt4) "
3152cd37da74Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
315348258c6bSjp151216 	    "strftime('%%s','now') + 600, 1, %q, "
315448258c6bSjp151216 	    "%d, %Q, %Q, %Q, %Q, %Q, %Q, %d);",
3155cd37da74Snw141292 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
3156e8c27ec8Sbaban 	    (req->id1domain != NULL) ? req->id1domain : "", req->id1name,
3157e8c27ec8Sbaban 	    res->id.idmap_id_u.uid, req->id2name,
3158e8c27ec8Sbaban 	    (res->id.idtype == IDMAP_UID) ? 1 : 0,
3159cd37da74Snw141292 	    (req->id1.idtype == IDMAP_USID) ? 1 : 0,
316048258c6bSjp151216 	    (res->direction == 0) ? "1" : NULL,
316148258c6bSjp151216 	    res->info.how.map_type, map_dn, map_attr, map_value,
316248258c6bSjp151216 	    map_windomain, map_winname, map_unixname, map_is_nt4);
3163c5c4113dSnw141292 
3164c5c4113dSnw141292 	if (sql == NULL) {
3165c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3166c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3167c5c4113dSnw141292 		goto out;
3168c5c4113dSnw141292 	}
3169c5c4113dSnw141292 
317071590c90Snw141292 	retcode = sql_exec_no_cb(cache, IDMAP_CACHENAME, sql);
3171c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
3172c5c4113dSnw141292 		goto out;
3173c5c4113dSnw141292 
3174c5c4113dSnw141292 	state->sid2pid_done = FALSE;
3175c5c4113dSnw141292 	sqlite_freemem(sql);
3176c5c4113dSnw141292 	sql = NULL;
3177c5c4113dSnw141292 
3178e8c27ec8Sbaban 	/* Check if we need to update namecache */
3179e8c27ec8Sbaban 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
3180c5c4113dSnw141292 		goto out;
3181c5c4113dSnw141292 
3182cf5b5989Sdm199847 	if (EMPTY_STRING(req->id1name))
3183c5c4113dSnw141292 		goto out;
3184c5c4113dSnw141292 
3185c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
3186cd37da74Snw141292 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
3187c5c4113dSnw141292 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
3188cd37da74Snw141292 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
3189cd37da74Snw141292 	    req->id1name, req->id1domain,
3190cd37da74Snw141292 	    (req->id1.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
3191c5c4113dSnw141292 
3192c5c4113dSnw141292 	if (sql == NULL) {
3193c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3194c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3195c5c4113dSnw141292 		goto out;
3196c5c4113dSnw141292 	}
3197c5c4113dSnw141292 
319871590c90Snw141292 	retcode = sql_exec_no_cb(cache, IDMAP_CACHENAME, sql);
3199c5c4113dSnw141292 
3200c5c4113dSnw141292 out:
320148258c6bSjp151216 	if (!(req->flag & IDMAP_REQ_FLG_MAPPING_INFO))
320248258c6bSjp151216 		idmap_info_free(&res->info);
320348258c6bSjp151216 
320462c60062Sbaban 	if (sql != NULL)
3205c5c4113dSnw141292 		sqlite_freemem(sql);
3206c5c4113dSnw141292 	return (retcode);
3207c5c4113dSnw141292 }
3208c5c4113dSnw141292 
3209cd37da74Snw141292 static
3210cd37da74Snw141292 idmap_retcode
3211c5c4113dSnw141292 lookup_cache_pid2sid(sqlite *cache, idmap_mapping *req, idmap_id_res *res,
3212cd37da74Snw141292 		int is_user, int getname)
3213cd37da74Snw141292 {
3214c5c4113dSnw141292 	char		*end;
3215c5c4113dSnw141292 	char		*sql = NULL;
3216c5c4113dSnw141292 	const char	**values;
3217c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
3218c5c4113dSnw141292 	int		ncol;
3219c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
3220c5c4113dSnw141292 	time_t		curtime;
3221e8c27ec8Sbaban 	idmap_id_type	idtype;
3222c5c4113dSnw141292 
3223c5c4113dSnw141292 	/* Current time */
3224c5c4113dSnw141292 	errno = 0;
3225c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
3226cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
3227c5c4113dSnw141292 		    strerror(errno));
3228c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3229c5c4113dSnw141292 		goto out;
3230c5c4113dSnw141292 	}
3231c5c4113dSnw141292 
3232e8c27ec8Sbaban 	/* SQL to lookup the cache by pid or by unixname */
3233e8c27ec8Sbaban 	if (req->id1.idmap_id_u.uid != SENTINEL_PID) {
323448258c6bSjp151216 		sql = sqlite_mprintf("SELECT sidprefix, rid, "
323548258c6bSjp151216 		    "canon_winname, windomain, w2u, is_wuser, "
323648258c6bSjp151216 		    "map_type, map_dn, map_attr, map_value, map_windomain, "
323748258c6bSjp151216 		    "map_winname, map_unixname, map_is_nt4 "
3238c5c4113dSnw141292 		    "FROM idmap_cache WHERE "
3239c5c4113dSnw141292 		    "pid = %u AND u2w = 1 AND is_user = %d AND "
3240c5c4113dSnw141292 		    "(pid >= 2147483648 OR "
3241c5c4113dSnw141292 		    "(expiration = 0 OR expiration ISNULL OR "
3242c5c4113dSnw141292 		    "expiration > %d));",
3243c5c4113dSnw141292 		    req->id1.idmap_id_u.uid, is_user, curtime);
3244e8c27ec8Sbaban 	} else if (req->id1name != NULL) {
324548258c6bSjp151216 		sql = sqlite_mprintf("SELECT sidprefix, rid, "
324648258c6bSjp151216 		    "canon_winname, windomain, w2u, is_wuser, "
324748258c6bSjp151216 		    "map_type, map_dn, map_attr, map_value, map_windomain, "
324848258c6bSjp151216 		    "map_winname, map_unixname, map_is_nt4 "
3249e8c27ec8Sbaban 		    "FROM idmap_cache WHERE "
3250e8c27ec8Sbaban 		    "unixname = %Q AND u2w = 1 AND is_user = %d AND "
3251e8c27ec8Sbaban 		    "(pid >= 2147483648 OR "
3252e8c27ec8Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
3253e8c27ec8Sbaban 		    "expiration > %d));",
3254e8c27ec8Sbaban 		    req->id1name, is_user, curtime);
325548258c6bSjp151216 	} else {
325648258c6bSjp151216 		retcode = IDMAP_ERR_ARG;
325748258c6bSjp151216 		goto out;
3258e8c27ec8Sbaban 	}
3259e8c27ec8Sbaban 
3260c5c4113dSnw141292 	if (sql == NULL) {
3261c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3262c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
3263c5c4113dSnw141292 		goto out;
3264c5c4113dSnw141292 	}
326548258c6bSjp151216 	retcode = sql_compile_n_step_once(
326648258c6bSjp151216 	    cache, sql, &vm, &ncol, 14, &values);
3267c5c4113dSnw141292 	sqlite_freemem(sql);
3268c5c4113dSnw141292 
3269c5c4113dSnw141292 	if (retcode == IDMAP_ERR_NOTFOUND)
3270c5c4113dSnw141292 		goto out;
3271c5c4113dSnw141292 	else if (retcode == IDMAP_SUCCESS) {
3272c5c4113dSnw141292 		/* sanity checks */
3273c5c4113dSnw141292 		if (values[0] == NULL || values[1] == NULL) {
3274c5c4113dSnw141292 			retcode = IDMAP_ERR_CACHE;
3275c5c4113dSnw141292 			goto out;
3276c5c4113dSnw141292 		}
3277c5c4113dSnw141292 
3278e8c27ec8Sbaban 		switch (res->id.idtype) {
3279c5c4113dSnw141292 		case IDMAP_SID:
3280cd37da74Snw141292 		case IDMAP_USID:
3281cd37da74Snw141292 		case IDMAP_GSID:
3282e8c27ec8Sbaban 			idtype = strtol(values[5], &end, 10) == 1
3283cd37da74Snw141292 			    ? IDMAP_USID : IDMAP_GSID;
3284cd37da74Snw141292 
3285e8c27ec8Sbaban 			if (res->id.idtype == IDMAP_USID &&
3286e8c27ec8Sbaban 			    idtype != IDMAP_USID) {
3287cd37da74Snw141292 				retcode = IDMAP_ERR_NOTUSER;
3288cd37da74Snw141292 				goto out;
3289e8c27ec8Sbaban 			} else if (res->id.idtype == IDMAP_GSID &&
3290e8c27ec8Sbaban 			    idtype != IDMAP_GSID) {
3291cd37da74Snw141292 				retcode = IDMAP_ERR_NOTGROUP;
3292cd37da74Snw141292 				goto out;
3293cd37da74Snw141292 			}
3294e8c27ec8Sbaban 			res->id.idtype = idtype;
3295cd37da74Snw141292 
3296c5c4113dSnw141292 			res->id.idmap_id_u.sid.rid =
3297c5c4113dSnw141292 			    strtoul(values[1], &end, 10);
3298c5c4113dSnw141292 			res->id.idmap_id_u.sid.prefix = strdup(values[0]);
3299c5c4113dSnw141292 			if (res->id.idmap_id_u.sid.prefix == NULL) {
3300c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
3301c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
3302c5c4113dSnw141292 				goto out;
3303c5c4113dSnw141292 			}
3304c5c4113dSnw141292 
330562c60062Sbaban 			if (values[4] != NULL)
3306c5c4113dSnw141292 				res->direction =
3307651c0131Sbaban 				    (strtol(values[4], &end, 10) == 0)?
3308651c0131Sbaban 				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
3309c5c4113dSnw141292 			else
3310651c0131Sbaban 				res->direction = IDMAP_DIRECTION_U2W;
3311c5c4113dSnw141292 
3312c5c4113dSnw141292 			if (getname == 0 || values[2] == NULL)
3313c5c4113dSnw141292 				break;
33148e228215Sdm199847 			req->id2name = strdup(values[2]);
33158e228215Sdm199847 			if (req->id2name == NULL) {
3316c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
3317c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
3318c5c4113dSnw141292 				goto out;
3319c5c4113dSnw141292 			}
3320c5c4113dSnw141292 
3321c5c4113dSnw141292 			if (values[3] == NULL)
3322c5c4113dSnw141292 				break;
33238e228215Sdm199847 			req->id2domain = strdup(values[3]);
33248e228215Sdm199847 			if (req->id2domain == NULL) {
3325c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
3326c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
3327c5c4113dSnw141292 				goto out;
3328c5c4113dSnw141292 			}
3329cd37da74Snw141292 
3330c5c4113dSnw141292 			break;
3331c5c4113dSnw141292 		default:
3332c5c4113dSnw141292 			retcode = IDMAP_ERR_NOTSUPPORTED;
3333c5c4113dSnw141292 			break;
3334c5c4113dSnw141292 		}
333548258c6bSjp151216 		if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
333648258c6bSjp151216 			res->info.src = IDMAP_MAP_SRC_CACHE;
333748258c6bSjp151216 			res->info.how.map_type = strtoul(values[6], &end, 10);
333848258c6bSjp151216 			switch (res->info.how.map_type) {
333948258c6bSjp151216 			case IDMAP_MAP_TYPE_DS_AD:
334048258c6bSjp151216 				res->info.how.idmap_how_u.ad.dn =
334148258c6bSjp151216 				    strdup(values[7]);
334248258c6bSjp151216 				res->info.how.idmap_how_u.ad.attr =
334348258c6bSjp151216 				    strdup(values[8]);
334448258c6bSjp151216 				res->info.how.idmap_how_u.ad.value =
334548258c6bSjp151216 				    strdup(values[9]);
334648258c6bSjp151216 				break;
334748258c6bSjp151216 
334848258c6bSjp151216 			case IDMAP_MAP_TYPE_DS_NLDAP:
334948258c6bSjp151216 				res->info.how.idmap_how_u.nldap.dn =
335048258c6bSjp151216 				    strdup(values[7]);
335148258c6bSjp151216 				res->info.how.idmap_how_u.nldap.attr =
335248258c6bSjp151216 				    strdup(values[8]);
335348258c6bSjp151216 				res->info.how.idmap_how_u.nldap.value =
335448258c6bSjp151216 				    strdup(values[9]);
335548258c6bSjp151216 				break;
335648258c6bSjp151216 
335748258c6bSjp151216 			case IDMAP_MAP_TYPE_RULE_BASED:
335848258c6bSjp151216 				res->info.how.idmap_how_u.rule.windomain =
335948258c6bSjp151216 				    strdup(values[10]);
336048258c6bSjp151216 				res->info.how.idmap_how_u.rule.winname =
336148258c6bSjp151216 				    strdup(values[11]);
336248258c6bSjp151216 				res->info.how.idmap_how_u.rule.unixname =
336348258c6bSjp151216 				    strdup(values[12]);
336448258c6bSjp151216 				res->info.how.idmap_how_u.rule.is_nt4 =
336548258c6bSjp151216 				    strtoul(values[13], &end, 10);
336648258c6bSjp151216 				res->info.how.idmap_how_u.rule.is_user =
336748258c6bSjp151216 				    is_user;
336848258c6bSjp151216 				res->info.how.idmap_how_u.rule.is_wuser =
336948258c6bSjp151216 				    strtol(values[5], &end, 10);
337048258c6bSjp151216 				break;
337148258c6bSjp151216 
337248258c6bSjp151216 			case IDMAP_MAP_TYPE_EPHEMERAL:
337348258c6bSjp151216 				break;
337448258c6bSjp151216 
337548258c6bSjp151216 			case IDMAP_MAP_TYPE_LOCAL_SID:
337648258c6bSjp151216 				break;
337748258c6bSjp151216 
337848258c6bSjp151216 			case IDMAP_MAP_TYPE_KNOWN_SID:
337948258c6bSjp151216 				break;
338048258c6bSjp151216 
338148258c6bSjp151216 			default:
338248258c6bSjp151216 				/* Unknow mapping type */
338348258c6bSjp151216 				assert(FALSE);
338448258c6bSjp151216 			}
338548258c6bSjp151216 		}
3386c5c4113dSnw141292 	}
3387c5c4113dSnw141292 
3388c5c4113dSnw141292 out:
338962c60062Sbaban 	if (vm != NULL)
3390c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
3391c5c4113dSnw141292 	return (retcode);
3392c5c4113dSnw141292 }
3393c5c4113dSnw141292 
3394cd37da74Snw141292 static
3395cd37da74Snw141292 idmap_retcode
3396c5c4113dSnw141292 lookup_cache_name2sid(sqlite *cache, const char *name, const char *domain,
3397cd37da74Snw141292 	char **canonname, char **sidprefix, idmap_rid_t *rid, int *type)
3398cd37da74Snw141292 {
3399cd37da74Snw141292 	char		*end, *lower_name;
3400c5c4113dSnw141292 	char		*sql = NULL;
3401c5c4113dSnw141292 	const char	**values;
3402c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
3403c5c4113dSnw141292 	int		ncol;
3404c5c4113dSnw141292 	time_t		curtime;
3405c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
3406c5c4113dSnw141292 
3407c5c4113dSnw141292 	/* Get current time */
3408c5c4113dSnw141292 	errno = 0;
3409c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
3410cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
3411c5c4113dSnw141292 		    strerror(errno));
3412c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3413c5c4113dSnw141292 		goto out;
3414c5c4113dSnw141292 	}
3415c5c4113dSnw141292 
3416c5c4113dSnw141292 	/* SQL to lookup the cache */
3417cd37da74Snw141292 	if ((lower_name = tolower_u8(name)) == NULL)
3418cd37da74Snw141292 		lower_name = (char *)name;
3419cd37da74Snw141292 	sql = sqlite_mprintf("SELECT sidprefix, rid, type, canon_name "
3420cd37da74Snw141292 	    "FROM name_cache WHERE name = %Q AND domain = %Q AND "
3421c5c4113dSnw141292 	    "(expiration = 0 OR expiration ISNULL OR "
3422cd37da74Snw141292 	    "expiration > %d);", lower_name, domain, curtime);
3423cd37da74Snw141292 	if (lower_name != name)
3424cd37da74Snw141292 		free(lower_name);
3425c5c4113dSnw141292 	if (sql == NULL) {
3426c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3427c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
3428c5c4113dSnw141292 		goto out;
3429c5c4113dSnw141292 	}
3430cd37da74Snw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 4, &values);
3431c5c4113dSnw141292 	sqlite_freemem(sql);
3432c5c4113dSnw141292 
3433c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
343462c60062Sbaban 		if (type != NULL) {
3435c5c4113dSnw141292 			if (values[2] == NULL) {
3436c5c4113dSnw141292 				retcode = IDMAP_ERR_CACHE;
3437c5c4113dSnw141292 				goto out;
3438c5c4113dSnw141292 			}
3439c5c4113dSnw141292 			*type = strtol(values[2], &end, 10);
3440c5c4113dSnw141292 		}
3441c5c4113dSnw141292 
3442e8c27ec8Sbaban 		if (values[0] == NULL || values[1] == NULL) {
3443e8c27ec8Sbaban 			retcode = IDMAP_ERR_CACHE;
3444e8c27ec8Sbaban 			goto out;
3445e8c27ec8Sbaban 		}
3446e8c27ec8Sbaban 
3447cd37da74Snw141292 		if (canonname != NULL) {
3448cd37da74Snw141292 			assert(values[3] != NULL);
3449cd37da74Snw141292 			if ((*canonname = strdup(values[3])) == NULL) {
3450cd37da74Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
3451cd37da74Snw141292 				retcode = IDMAP_ERR_MEMORY;
3452cd37da74Snw141292 				goto out;
3453cd37da74Snw141292 			}
3454cd37da74Snw141292 		}
3455cd37da74Snw141292 
3456c5c4113dSnw141292 		if ((*sidprefix = strdup(values[0])) == NULL) {
3457c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
3458c5c4113dSnw141292 			retcode = IDMAP_ERR_MEMORY;
3459e8c27ec8Sbaban 			if (canonname != NULL) {
3460e8c27ec8Sbaban 				free(*canonname);
3461e8c27ec8Sbaban 				*canonname = NULL;
3462e8c27ec8Sbaban 			}
3463c5c4113dSnw141292 			goto out;
3464c5c4113dSnw141292 		}
3465c5c4113dSnw141292 		*rid = strtoul(values[1], &end, 10);
3466c5c4113dSnw141292 	}
3467c5c4113dSnw141292 
3468c5c4113dSnw141292 out:
346962c60062Sbaban 	if (vm != NULL)
3470c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
3471c5c4113dSnw141292 	return (retcode);
3472c5c4113dSnw141292 }
3473c5c4113dSnw141292 
3474cd37da74Snw141292 static
3475cd37da74Snw141292 idmap_retcode
3476e8c27ec8Sbaban ad_lookup_by_winname(lookup_state_t *state,
3477e8c27ec8Sbaban 		const char *name, const char *domain, int eunixtype,
347848258c6bSjp151216 		char **dn, char **attr, char **value, char **canonname,
347948258c6bSjp151216 		char **sidprefix, idmap_rid_t *rid, int *wintype,
348048258c6bSjp151216 		char **unixname)
3481cd37da74Snw141292 {
3482c5c4113dSnw141292 	int			retries = 0;
3483c5c4113dSnw141292 	idmap_query_state_t	*qs = NULL;
3484c5c4113dSnw141292 	idmap_retcode		rc, retcode;
3485c5c4113dSnw141292 
3486c5c4113dSnw141292 retry:
3487e8c27ec8Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, 1, &qs);
3488e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
34890dcc7149Snw141292 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
34900dcc7149Snw141292 			goto retry;
3491349d5d8fSnw141292 		degrade_svc(1, "failed to create request for AD lookup "
34920dcc7149Snw141292 		    "by winname");
3493e8c27ec8Sbaban 		return (retcode);
3494c5c4113dSnw141292 	}
3495c5c4113dSnw141292 
3496c8e26105Sjp151216 	restore_svc();
3497c8e26105Sjp151216 
3498e8c27ec8Sbaban 	if (state != NULL)
3499e8c27ec8Sbaban 		idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
3500e8c27ec8Sbaban 		    state->ad_unixgroup_attr);
3501c5c4113dSnw141292 
3502e8c27ec8Sbaban 	retcode = idmap_name2sid_batch_add1(qs, name, domain, eunixtype,
350348258c6bSjp151216 	    dn, attr, value, canonname, sidprefix, rid, wintype, unixname, &rc);
3504c5c4113dSnw141292 
3505e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
350684decf41Sjp151216 		idmap_lookup_release_batch(&qs);
3507c5c4113dSnw141292 	else
35080dcc7149Snw141292 		retcode = idmap_lookup_batch_end(&qs);
3509c5c4113dSnw141292 
3510c5c4113dSnw141292 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
3511c5c4113dSnw141292 		goto retry;
3512c8e26105Sjp151216 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
3513349d5d8fSnw141292 		degrade_svc(1, "some AD lookups timed out repeatedly");
3514c5c4113dSnw141292 
3515c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS) {
3516e8c27ec8Sbaban 		idmapdlog(LOG_NOTICE, "AD lookup by winname failed");
3517c5c4113dSnw141292 		return (retcode);
3518e8c27ec8Sbaban 	}
3519c5c4113dSnw141292 	return (rc);
3520c5c4113dSnw141292 }
3521c5c4113dSnw141292 
3522cd37da74Snw141292 static
3523cd37da74Snw141292 idmap_retcode
3524c5c4113dSnw141292 lookup_name2sid(sqlite *cache, const char *name, const char *domain,
3525cd37da74Snw141292 		int *is_wuser, char **canonname, char **sidprefix,
3526cd37da74Snw141292 		idmap_rid_t *rid, idmap_mapping *req)
3527cd37da74Snw141292 {
3528c5c4113dSnw141292 	int		type;
3529c5c4113dSnw141292 	idmap_retcode	retcode;
3530c5c4113dSnw141292 
3531cd37da74Snw141292 	*sidprefix = NULL;
3532e8c27ec8Sbaban 	if (canonname != NULL)
3533cd37da74Snw141292 		*canonname = NULL;
3534cd37da74Snw141292 
3535e8c27ec8Sbaban 	/* Lookup well-known SIDs table */
3536cd37da74Snw141292 	retcode = lookup_wksids_name2sid(name, canonname, sidprefix, rid,
3537cd37da74Snw141292 	    &type);
353862c60062Sbaban 	if (retcode == IDMAP_SUCCESS) {
3539e8c27ec8Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
354062c60062Sbaban 		goto out;
354162c60062Sbaban 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
354262c60062Sbaban 		return (retcode);
354362c60062Sbaban 	}
354462c60062Sbaban 
3545e8c27ec8Sbaban 	/* Lookup cache */
3546cd37da74Snw141292 	retcode = lookup_cache_name2sid(cache, name, domain, canonname,
3547cd37da74Snw141292 	    sidprefix, rid, &type);
3548e8c27ec8Sbaban 	if (retcode == IDMAP_SUCCESS) {
3549e8c27ec8Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
3550e8c27ec8Sbaban 		goto out;
3551e8c27ec8Sbaban 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
3552e8c27ec8Sbaban 		return (retcode);
3553e8c27ec8Sbaban 	}
3554e8c27ec8Sbaban 
3555e8c27ec8Sbaban 	/* Lookup AD */
3556e8c27ec8Sbaban 	retcode = ad_lookup_by_winname(NULL, name, domain, _IDMAP_T_UNDEF,
355748258c6bSjp151216 	    NULL, NULL, NULL, canonname, sidprefix, rid, &type, NULL);
3558c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
3559c5c4113dSnw141292 		return (retcode);
3560e8c27ec8Sbaban 	/* Don't need to set req->direction |= _IDMAP_F_LOOKUP_AD; */
3561c5c4113dSnw141292 
356262c60062Sbaban out:
3563c5c4113dSnw141292 	/*
3564c5c4113dSnw141292 	 * Entry found (cache or Windows lookup)
3565cd37da74Snw141292 	 * is_wuser is both input as well as output parameter
3566c5c4113dSnw141292 	 */
3567e8c27ec8Sbaban 	if (*is_wuser == 1 && type != _IDMAP_T_USER)
3568e8c27ec8Sbaban 		retcode = IDMAP_ERR_NOTUSER;
3569e8c27ec8Sbaban 	else if (*is_wuser == 0 && type != _IDMAP_T_GROUP)
3570e8c27ec8Sbaban 		retcode = IDMAP_ERR_NOTGROUP;
3571e8c27ec8Sbaban 	else if (*is_wuser == -1) {
3572c5c4113dSnw141292 		/* Caller wants to know if its user or group */
3573c5c4113dSnw141292 		if (type == _IDMAP_T_USER)
3574cd37da74Snw141292 			*is_wuser = 1;
3575c5c4113dSnw141292 		else if (type == _IDMAP_T_GROUP)
3576cd37da74Snw141292 			*is_wuser = 0;
3577e8c27ec8Sbaban 		else
3578e8c27ec8Sbaban 			retcode = IDMAP_ERR_SID;
3579e8c27ec8Sbaban 	}
3580e8c27ec8Sbaban 
3581e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
3582cd37da74Snw141292 		free(*sidprefix);
3583cd37da74Snw141292 		*sidprefix = NULL;
3584e8c27ec8Sbaban 		if (canonname != NULL) {
3585cd37da74Snw141292 			free(*canonname);
3586cd37da74Snw141292 			*canonname = NULL;
3587cd37da74Snw141292 		}
3588c5c4113dSnw141292 	}
3589c5c4113dSnw141292 	return (retcode);
3590c5c4113dSnw141292 }
3591c5c4113dSnw141292 
3592cd37da74Snw141292 static
3593cd37da74Snw141292 idmap_retcode
3594c5c4113dSnw141292 name_based_mapping_pid2sid(sqlite *db, sqlite *cache, const char *unixname,
3595cd37da74Snw141292 		int is_user, idmap_mapping *req, idmap_id_res *res)
3596cd37da74Snw141292 {
3597c5c4113dSnw141292 	const char	*winname, *windomain;
3598cd37da74Snw141292 	char		*canonname;
3599c8e26105Sjp151216 	char		*default_domain = NULL;
3600c5c4113dSnw141292 	char		*sql = NULL, *errmsg = NULL;
3601c5c4113dSnw141292 	idmap_retcode	retcode;
3602c5c4113dSnw141292 	char		*end;
3603c5c4113dSnw141292 	const char	**values;
3604c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
360548258c6bSjp151216 	int		ncol, r;
3606cd37da74Snw141292 	int		is_wuser;
3607e8c27ec8Sbaban 	const char	*me = "name_based_mapping_pid2sid";
360848258c6bSjp151216 	int 		non_wild_match = FALSE;
360948258c6bSjp151216 	idmap_namerule	*rule = &res->info.how.idmap_how_u.rule;
361048258c6bSjp151216 	int direction;
3611e8c27ec8Sbaban 
3612e8c27ec8Sbaban 	assert(unixname != NULL); /* We have unixname */
3613e8c27ec8Sbaban 	assert(req->id2name == NULL); /* We don't have winname */
3614e8c27ec8Sbaban 	assert(res->id.idmap_id_u.sid.prefix == NULL); /* No SID either */
3615c5c4113dSnw141292 
3616c5c4113dSnw141292 	RDLOCK_CONFIG();
3617c8e26105Sjp151216 	if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
3618c8e26105Sjp151216 		default_domain =
3619c8e26105Sjp151216 		    strdup(_idmapdstate.cfg->pgcfg.default_domain);
3620c8e26105Sjp151216 		if (default_domain == NULL) {
3621c5c4113dSnw141292 			UNLOCK_CONFIG();
3622c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
3623c5c4113dSnw141292 			retcode = IDMAP_ERR_MEMORY;
3624c5c4113dSnw141292 			goto out;
3625c5c4113dSnw141292 		}
3626c5c4113dSnw141292 	}
3627c5c4113dSnw141292 	UNLOCK_CONFIG();
3628c5c4113dSnw141292 
3629c5c4113dSnw141292 	sql = sqlite_mprintf(
363048258c6bSjp151216 	    "SELECT winname_display, windomain, w2u_order, "
363148258c6bSjp151216 	    "is_wuser, unixname, is_nt4 "
363248258c6bSjp151216 	    "FROM namerules WHERE "
3633c5c4113dSnw141292 	    "u2w_order > 0 AND is_user = %d AND "
3634c5c4113dSnw141292 	    "(unixname = %Q OR unixname = '*') "
3635cd37da74Snw141292 	    "ORDER BY u2w_order ASC;", is_user, unixname);
3636c5c4113dSnw141292 	if (sql == NULL) {
3637c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3638c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
3639c5c4113dSnw141292 		goto out;
3640c5c4113dSnw141292 	}
3641c5c4113dSnw141292 
3642c5c4113dSnw141292 	if (sqlite_compile(db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
3643c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3644cd37da74Snw141292 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
3645cd37da74Snw141292 		    CHECK_NULL(errmsg));
3646c5c4113dSnw141292 		sqlite_freemem(errmsg);
3647c5c4113dSnw141292 		goto out;
3648c5c4113dSnw141292 	}
3649c5c4113dSnw141292 
365048258c6bSjp151216 	for (;;) {
3651c5c4113dSnw141292 		r = sqlite_step(vm, &ncol, &values, NULL);
365284decf41Sjp151216 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
365384decf41Sjp151216 		if (r == SQLITE_ROW) {
365448258c6bSjp151216 			if (ncol < 6) {
3655c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
3656c5c4113dSnw141292 				goto out;
3657c5c4113dSnw141292 			}
3658c5c4113dSnw141292 			if (values[0] == NULL) {
3659c5c4113dSnw141292 				/* values [1] and [2] can be null */
3660c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
3661c5c4113dSnw141292 				goto out;
3662c5c4113dSnw141292 			}
366348258c6bSjp151216 
366448258c6bSjp151216 			if (values[2] != NULL)
366548258c6bSjp151216 				direction =
366648258c6bSjp151216 				    (strtol(values[2], &end, 10) == 0)?
366748258c6bSjp151216 				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
366848258c6bSjp151216 			else
366948258c6bSjp151216 				direction = IDMAP_DIRECTION_U2W;
367048258c6bSjp151216 
3671c5c4113dSnw141292 			if (EMPTY_NAME(values[0])) {
367248258c6bSjp151216 				idmap_namerule_set(rule, values[1], values[0],
367348258c6bSjp151216 				    values[4], is_user,
367448258c6bSjp151216 				    strtol(values[3], &end, 10),
367548258c6bSjp151216 				    strtol(values[5], &end, 10),
367648258c6bSjp151216 				    direction);
3677c5c4113dSnw141292 				retcode = IDMAP_ERR_NOMAPPING;
3678c5c4113dSnw141292 				goto out;
3679c5c4113dSnw141292 			}
3680cd37da74Snw141292 
3681cd37da74Snw141292 			if (values[0][0] == '*') {
368248258c6bSjp151216 				winname = unixname;
368348258c6bSjp151216 				if (non_wild_match) {
3684cd37da74Snw141292 					/*
368548258c6bSjp151216 					 * There were non-wildcard rules
368648258c6bSjp151216 					 * where the Windows identity doesn't
368748258c6bSjp151216 					 * exist. Return no mapping.
3688cd37da74Snw141292 					 */
3689cd37da74Snw141292 					retcode = IDMAP_ERR_NOMAPPING;
3690cd37da74Snw141292 					goto out;
3691cd37da74Snw141292 				}
3692cd37da74Snw141292 			} else {
369348258c6bSjp151216 				/* Save first non-wild match rule */
369448258c6bSjp151216 				if (!non_wild_match) {
369548258c6bSjp151216 					idmap_namerule_set(rule, values[1],
369648258c6bSjp151216 					    values[0], values[4],
369748258c6bSjp151216 					    is_user,
369848258c6bSjp151216 					    strtol(values[3], &end, 10),
369948258c6bSjp151216 					    strtol(values[5], &end, 10),
370048258c6bSjp151216 					    direction);
370148258c6bSjp151216 					non_wild_match = TRUE;
370248258c6bSjp151216 				}
3703cd37da74Snw141292 				winname = values[0];
3704cd37da74Snw141292 			}
370548258c6bSjp151216 			is_wuser = res->id.idtype == IDMAP_USID ? 1
370648258c6bSjp151216 			    : res->id.idtype == IDMAP_GSID ? 0
370748258c6bSjp151216 			    : -1;
370862c60062Sbaban 			if (values[1] != NULL)
3709c5c4113dSnw141292 				windomain = values[1];
3710c8e26105Sjp151216 			else if (default_domain != NULL)
3711c8e26105Sjp151216 				windomain = default_domain;
3712c5c4113dSnw141292 			else {
3713cd37da74Snw141292 				idmapdlog(LOG_ERR, "%s: no domain", me);
3714c5c4113dSnw141292 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
3715c5c4113dSnw141292 				goto out;
3716c5c4113dSnw141292 			}
3717cd37da74Snw141292 
3718c5c4113dSnw141292 			retcode = lookup_name2sid(cache, winname, windomain,
3719cd37da74Snw141292 			    &is_wuser, &canonname,
3720cd37da74Snw141292 			    &res->id.idmap_id_u.sid.prefix,
3721c5c4113dSnw141292 			    &res->id.idmap_id_u.sid.rid, req);
3722e8c27ec8Sbaban 
3723c5c4113dSnw141292 			if (retcode == IDMAP_ERR_NOTFOUND) {
3724c5c4113dSnw141292 				continue;
3725c5c4113dSnw141292 			}
3726c5c4113dSnw141292 			goto out;
372748258c6bSjp151216 
3728c5c4113dSnw141292 		} else if (r == SQLITE_DONE) {
372948258c6bSjp151216 			/*
373048258c6bSjp151216 			 * If there were non-wildcard rules where
373148258c6bSjp151216 			 * Windows identity doesn't exist
373248258c6bSjp151216 			 * return no mapping.
373348258c6bSjp151216 			 */
373448258c6bSjp151216 			if (non_wild_match)
373548258c6bSjp151216 				retcode = IDMAP_ERR_NOMAPPING;
373648258c6bSjp151216 			else
3737c5c4113dSnw141292 				retcode = IDMAP_ERR_NOTFOUND;
3738c5c4113dSnw141292 			goto out;
3739c5c4113dSnw141292 		} else {
3740c5c4113dSnw141292 			(void) sqlite_finalize(vm, &errmsg);
3741c5c4113dSnw141292 			vm = NULL;
3742cd37da74Snw141292 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
3743cd37da74Snw141292 			    CHECK_NULL(errmsg));
3744c5c4113dSnw141292 			sqlite_freemem(errmsg);
3745c5c4113dSnw141292 			retcode = IDMAP_ERR_INTERNAL;
3746c5c4113dSnw141292 			goto out;
3747c5c4113dSnw141292 		}
3748c5c4113dSnw141292 	}
3749c5c4113dSnw141292 
3750c5c4113dSnw141292 out:
375162c60062Sbaban 	if (sql != NULL)
3752c5c4113dSnw141292 		sqlite_freemem(sql);
375348258c6bSjp151216 	res->info.how.map_type = IDMAP_MAP_TYPE_RULE_BASED;
3754c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
3755cd37da74Snw141292 		res->id.idtype = is_wuser ? IDMAP_USID : IDMAP_GSID;
3756cd37da74Snw141292 
375762c60062Sbaban 		if (values[2] != NULL)
3758c5c4113dSnw141292 			res->direction =
3759651c0131Sbaban 			    (strtol(values[2], &end, 10) == 0)?
3760651c0131Sbaban 			    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
3761c5c4113dSnw141292 		else
3762651c0131Sbaban 			res->direction = IDMAP_DIRECTION_U2W;
37638e228215Sdm199847 
3764cd37da74Snw141292 		req->id2name = canonname;
37658e228215Sdm199847 		if (req->id2name != NULL) {
3766c8e26105Sjp151216 			if (windomain == default_domain) {
37678e228215Sdm199847 				req->id2domain = (char *)windomain;
3768c8e26105Sjp151216 				default_domain = NULL;
37698e228215Sdm199847 			} else {
37708e228215Sdm199847 				req->id2domain = strdup(windomain);
37718e228215Sdm199847 			}
3772c5c4113dSnw141292 		}
377348258c6bSjp151216 		idmap_namerule_set(rule, values[1], values[0], values[4],
377448258c6bSjp151216 		    is_user, strtol(values[3], &end, 10),
377548258c6bSjp151216 		    strtol(values[5], &end, 10),
377648258c6bSjp151216 		    rule->direction);
377748258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
3778c5c4113dSnw141292 	}
377962c60062Sbaban 	if (vm != NULL)
3780c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
3781c8e26105Sjp151216 	if (default_domain != NULL)
3782c8e26105Sjp151216 		free(default_domain);
3783c5c4113dSnw141292 	return (retcode);
3784c5c4113dSnw141292 }
3785c5c4113dSnw141292 
3786cd37da74Snw141292 /*
3787cd37da74Snw141292  * Convention when processing unix2win requests:
3788cd37da74Snw141292  *
3789cd37da74Snw141292  * Unix identity:
3790cd37da74Snw141292  * req->id1name =
3791cd37da74Snw141292  *              unixname if given otherwise unixname found will be placed
3792cd37da74Snw141292  *              here.
3793cd37da74Snw141292  * req->id1domain =
3794cd37da74Snw141292  *              NOT USED
3795cd37da74Snw141292  * req->id1.idtype =
3796cd37da74Snw141292  *              Given type (IDMAP_UID or IDMAP_GID)
3797cd37da74Snw141292  * req->id1..[uid or gid] =
3798cd37da74Snw141292  *              UID/GID if given otherwise UID/GID found will be placed here.
3799cd37da74Snw141292  *
3800cd37da74Snw141292  * Windows identity:
3801cd37da74Snw141292  * req->id2name =
3802cd37da74Snw141292  *              winname found will be placed here.
3803cd37da74Snw141292  * req->id2domain =
3804cd37da74Snw141292  *              windomain found will be placed here.
3805cd37da74Snw141292  * res->id.idtype =
3806cd37da74Snw141292  *              Target type initialized from req->id2.idtype. If
3807cd37da74Snw141292  *              it is IDMAP_SID then actual type (IDMAP_USID/GSID) found
3808cd37da74Snw141292  *              will be placed here.
3809cd37da74Snw141292  * req->id..sid.[prefix, rid] =
3810cd37da74Snw141292  *              SID found will be placed here.
3811cd37da74Snw141292  *
3812cd37da74Snw141292  * Others:
3813cd37da74Snw141292  * res->retcode =
3814cd37da74Snw141292  *              Return status for this request will be placed here.
3815cd37da74Snw141292  * res->direction =
3816cd37da74Snw141292  *              Direction found will be placed here. Direction
3817cd37da74Snw141292  *              meaning whether the resultant mapping is valid
3818cd37da74Snw141292  *              only from unix2win or bi-directional.
3819cd37da74Snw141292  * req->direction =
3820cd37da74Snw141292  *              INTERNAL USE. Used by idmapd to set various
3821cd37da74Snw141292  *              flags (_IDMAP_F_xxxx) to aid in processing
3822cd37da74Snw141292  *              of the request.
3823cd37da74Snw141292  * req->id2.idtype =
3824cd37da74Snw141292  *              INTERNAL USE. Initially this is the requested target
3825cd37da74Snw141292  *              type and is used to initialize res->id.idtype.
3826cd37da74Snw141292  *              ad_lookup_batch() uses this field temporarily to store
3827cd37da74Snw141292  *              sid_type obtained by the batched AD lookups and after
3828cd37da74Snw141292  *              use resets it to IDMAP_NONE to prevent xdr from
3829cd37da74Snw141292  *              mis-interpreting the contents of req->id2.
3830cd37da74Snw141292  * req->id2..[uid or gid or sid] =
3831cd37da74Snw141292  *              NOT USED
3832cd37da74Snw141292  */
3833cd37da74Snw141292 
3834cd37da74Snw141292 /*
3835cd37da74Snw141292  * This function does the following:
3836cd37da74Snw141292  * 1. Lookup well-known SIDs table.
3837cd37da74Snw141292  * 2. Lookup cache.
3838cd37da74Snw141292  * 3. Check if the client does not want new mapping to be allocated
3839cd37da74Snw141292  *    in which case this pass is the final pass.
3840e8c27ec8Sbaban  * 4. Set AD/NLDAP lookup flags if it determines that the next stage needs
3841e8c27ec8Sbaban  *    to do AD/NLDAP lookup.
3842cd37da74Snw141292  */
3843c5c4113dSnw141292 idmap_retcode
3844e8c27ec8Sbaban pid2sid_first_pass(lookup_state_t *state, sqlite *cache,
3845c5c4113dSnw141292 		idmap_mapping *req, idmap_id_res *res, int is_user,
3846cd37da74Snw141292 		int getname)
3847cd37da74Snw141292 {
3848e8c27ec8Sbaban 	idmap_retcode	retcode;
3849e8c27ec8Sbaban 	bool_t		gen_localsid_on_err = FALSE;
3850c5c4113dSnw141292 
3851e8c27ec8Sbaban 	/* Initialize result */
3852c5c4113dSnw141292 	res->id.idtype = req->id2.idtype;
3853e8c27ec8Sbaban 	res->direction = IDMAP_DIRECTION_UNDEF;
3854c5c4113dSnw141292 
3855e8c27ec8Sbaban 	if (req->id2.idmap_id_u.sid.prefix != NULL) {
3856e8c27ec8Sbaban 		/* sanitize sidprefix */
3857e8c27ec8Sbaban 		free(req->id2.idmap_id_u.sid.prefix);
3858e8c27ec8Sbaban 		req->id2.idmap_id_u.sid.prefix = NULL;
3859e8c27ec8Sbaban 	}
3860e8c27ec8Sbaban 
386148258c6bSjp151216 	/* Find pid */
386248258c6bSjp151216 	if (req->id1.idmap_id_u.uid == SENTINEL_PID) {
386348258c6bSjp151216 		if (ns_lookup_byname(req->id1name, NULL, &req->id1)
386448258c6bSjp151216 		    != IDMAP_SUCCESS) {
386548258c6bSjp151216 			retcode = IDMAP_ERR_NOMAPPING;
386648258c6bSjp151216 			goto out;
386748258c6bSjp151216 		}
386848258c6bSjp151216 	}
386948258c6bSjp151216 
3870e8c27ec8Sbaban 	/* Lookup well-known SIDs table */
3871c5c4113dSnw141292 	retcode = lookup_wksids_pid2sid(req, res, is_user);
3872c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
3873c5c4113dSnw141292 		goto out;
3874c5c4113dSnw141292 
3875e8c27ec8Sbaban 	/* Lookup cache */
3876c5c4113dSnw141292 	retcode = lookup_cache_pid2sid(cache, req, res, is_user, getname);
3877c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
3878c5c4113dSnw141292 		goto out;
3879c5c4113dSnw141292 
3880c5c4113dSnw141292 	/* Ephemeral ids cannot be allocated during pid2sid */
3881c5c4113dSnw141292 	if (IS_EPHEMERAL(req->id1.idmap_id_u.uid)) {
388262c60062Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
3883c5c4113dSnw141292 		goto out;
3884c5c4113dSnw141292 	}
3885c5c4113dSnw141292 
388648258c6bSjp151216 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req)) {
388748258c6bSjp151216 		retcode = IDMAP_ERR_NONEGENERATED;
388848258c6bSjp151216 		goto out;
388948258c6bSjp151216 	}
389048258c6bSjp151216 
389148258c6bSjp151216 	if (AVOID_NAMESERVICE(req)) {
3892e8c27ec8Sbaban 		gen_localsid_on_err = TRUE;
389362c60062Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
3894c5c4113dSnw141292 		goto out;
3895c5c4113dSnw141292 	}
3896c5c4113dSnw141292 
3897e8c27ec8Sbaban 	/* Set flags for the next stage */
3898e8c27ec8Sbaban 	if (AD_MODE(req->id1.idtype, state)) {
3899e8c27ec8Sbaban 		/*
3900e8c27ec8Sbaban 		 * If AD-based name mapping is enabled then the next stage
3901e8c27ec8Sbaban 		 * will need to lookup AD using unixname to get the
3902e8c27ec8Sbaban 		 * corresponding winname.
3903e8c27ec8Sbaban 		 */
3904e8c27ec8Sbaban 		if (req->id1name == NULL) {
3905e8c27ec8Sbaban 			/* Get unixname if only pid is given. */
3906e8c27ec8Sbaban 			retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid,
3907e8c27ec8Sbaban 			    is_user, &req->id1name);
3908e8c27ec8Sbaban 			if (retcode != IDMAP_SUCCESS)
3909e8c27ec8Sbaban 				goto out;
3910c5c4113dSnw141292 		}
3911e8c27ec8Sbaban 		req->direction |= _IDMAP_F_LOOKUP_AD;
3912e8c27ec8Sbaban 		state->ad_nqueries++;
3913e8c27ec8Sbaban 	} else if (NLDAP_OR_MIXED_MODE(req->id1.idtype, state)) {
3914e8c27ec8Sbaban 		/*
3915e8c27ec8Sbaban 		 * If native LDAP or mixed mode is enabled for name mapping
3916e8c27ec8Sbaban 		 * then the next stage will need to lookup native LDAP using
3917e8c27ec8Sbaban 		 * unixname/pid to get the corresponding winname.
3918e8c27ec8Sbaban 		 */
3919e8c27ec8Sbaban 		req->direction |= _IDMAP_F_LOOKUP_NLDAP;
3920e8c27ec8Sbaban 		state->nldap_nqueries++;
3921c5c4113dSnw141292 	}
3922c5c4113dSnw141292 
3923e8c27ec8Sbaban 	/*
3924e8c27ec8Sbaban 	 * Failed to find non-expired entry in cache. Set the flag to
3925e8c27ec8Sbaban 	 * indicate that we are not done yet.
3926e8c27ec8Sbaban 	 */
3927e8c27ec8Sbaban 	state->pid2sid_done = FALSE;
3928e8c27ec8Sbaban 	req->direction |= _IDMAP_F_NOTDONE;
3929e8c27ec8Sbaban 	retcode = IDMAP_SUCCESS;
3930e8c27ec8Sbaban 
3931e8c27ec8Sbaban out:
3932e8c27ec8Sbaban 	res->retcode = idmap_stat4prot(retcode);
3933e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
3934e8c27ec8Sbaban 		if (gen_localsid_on_err == TRUE)
393548258c6bSjp151216 			(void) generate_localsid(req, res, is_user, TRUE);
3936e8c27ec8Sbaban 	return (retcode);
3937e8c27ec8Sbaban }
3938e8c27ec8Sbaban 
3939e8c27ec8Sbaban idmap_retcode
3940e8c27ec8Sbaban pid2sid_second_pass(lookup_state_t *state, sqlite *cache, sqlite *db,
3941e8c27ec8Sbaban 		idmap_mapping *req, idmap_id_res *res, int is_user)
3942e8c27ec8Sbaban {
3943e8c27ec8Sbaban 	bool_t		gen_localsid_on_err = TRUE;
3944e8c27ec8Sbaban 	idmap_retcode	retcode = IDMAP_SUCCESS;
3945e8c27ec8Sbaban 
3946e8c27ec8Sbaban 	/* Check if second pass is needed */
3947e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
3948e8c27ec8Sbaban 		return (res->retcode);
3949e8c27ec8Sbaban 
3950e8c27ec8Sbaban 	/* Get status from previous pass */
3951e8c27ec8Sbaban 	retcode = res->retcode;
3952e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
3953e8c27ec8Sbaban 		goto out;
3954e8c27ec8Sbaban 
3955e8c27ec8Sbaban 	/*
3956e8c27ec8Sbaban 	 * If directory-based name mapping is enabled then the winname
3957e8c27ec8Sbaban 	 * may already have been retrieved from the AD object (AD-mode)
3958e8c27ec8Sbaban 	 * or from native LDAP object (nldap-mode or mixed-mode) -- done.
3959e8c27ec8Sbaban 	 */
3960e8c27ec8Sbaban 	if (res->id.idmap_id_u.sid.prefix != NULL || req->id2name != NULL) {
3961e8c27ec8Sbaban 		if (AD_MODE(req->id1.idtype, state))
3962e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
3963e8c27ec8Sbaban 		else if (NLDAP_MODE(req->id1.idtype, state))
3964e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
3965e8c27ec8Sbaban 		else if (MIXED_MODE(req->id1.idtype, state))
3966e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
3967e8c27ec8Sbaban 		goto out;
3968e8c27ec8Sbaban 	}
3969e8c27ec8Sbaban 
3970e8c27ec8Sbaban 	if (req->id1name == NULL) {
3971e8c27ec8Sbaban 		/* Get unixname from name service */
3972e8c27ec8Sbaban 		retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid, is_user,
3973e8c27ec8Sbaban 		    &req->id1name);
3974e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS)
3975e8c27ec8Sbaban 			goto out;
3976e8c27ec8Sbaban 	} else if (req->id1.idmap_id_u.uid == SENTINEL_PID) {
3977e8c27ec8Sbaban 		/* Get pid from name service */
3978e8c27ec8Sbaban 		retcode = ns_lookup_byname(req->id1name, NULL, &req->id1);
3979e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS) {
3980e8c27ec8Sbaban 			gen_localsid_on_err = FALSE;
3981e8c27ec8Sbaban 			goto out;
3982e8c27ec8Sbaban 		}
3983e8c27ec8Sbaban 	}
3984e8c27ec8Sbaban 
398548258c6bSjp151216 	/* Free any mapping info from Directory based mapping */
398648258c6bSjp151216 	if (res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN)
398748258c6bSjp151216 		idmap_info_free(&res->info);
398848258c6bSjp151216 
3989e8c27ec8Sbaban 	/* Use unixname to evaluate local name-based mapping rules */
3990e8c27ec8Sbaban 	retcode = name_based_mapping_pid2sid(db, cache, req->id1name, is_user,
3991c5c4113dSnw141292 	    req, res);
3992c5c4113dSnw141292 	if (retcode == IDMAP_ERR_NOTFOUND) {
399348258c6bSjp151216 		retcode = generate_localsid(req, res, is_user, FALSE);
3994e8c27ec8Sbaban 		gen_localsid_on_err = FALSE;
3995e8c27ec8Sbaban 	}
3996c5c4113dSnw141292 
3997c5c4113dSnw141292 out:
3998c5c4113dSnw141292 	res->retcode = idmap_stat4prot(retcode);
3999e8c27ec8Sbaban 	if (res->retcode != IDMAP_SUCCESS) {
4000e8c27ec8Sbaban 		req->direction = _IDMAP_F_DONE;
4001e8c27ec8Sbaban 		if (gen_localsid_on_err == TRUE)
400248258c6bSjp151216 			(void) generate_localsid(req, res, is_user, TRUE);
4003e8c27ec8Sbaban 	}
4004e8c27ec8Sbaban 	if (!ARE_WE_DONE(req->direction))
4005e8c27ec8Sbaban 		state->pid2sid_done = FALSE;
4006c5c4113dSnw141292 	return (retcode);
4007c5c4113dSnw141292 }
4008c5c4113dSnw141292 
4009cd37da74Snw141292 static
4010cd37da74Snw141292 idmap_retcode
4011e8c27ec8Sbaban ad_lookup_by_sid(lookup_state_t *state,
4012e8c27ec8Sbaban 		const char *sidprefix, idmap_rid_t rid, int eunixtype,
401348258c6bSjp151216 		char **dn, char **attr, char **value, char **name,
401448258c6bSjp151216 		char **domain, int *type, char **unixname)
4015cd37da74Snw141292 {
4016e8c27ec8Sbaban 	int			retries = 0;
4017c5c4113dSnw141292 	idmap_query_state_t	*qs = NULL;
4018c5c4113dSnw141292 	idmap_retcode		rc, retcode;
4019c5c4113dSnw141292 
4020e8c27ec8Sbaban retry:
4021e8c27ec8Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, 1, &qs);
4022e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
40230dcc7149Snw141292 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
40240dcc7149Snw141292 			goto retry;
4025349d5d8fSnw141292 		degrade_svc(1, "failed to create request for AD lookup by SID");
4026e8c27ec8Sbaban 		return (retcode);
4027c5c4113dSnw141292 	}
4028c5c4113dSnw141292 
4029c8e26105Sjp151216 	restore_svc();
4030c8e26105Sjp151216 
4031e8c27ec8Sbaban 	if (state != NULL)
4032e8c27ec8Sbaban 		idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
4033e8c27ec8Sbaban 		    state->ad_unixgroup_attr);
4034c5c4113dSnw141292 
4035e8c27ec8Sbaban 	retcode = idmap_sid2name_batch_add1(qs, sidprefix, &rid, eunixtype,
403648258c6bSjp151216 	    dn, attr, value, name, domain, type, unixname, &rc);
4037e8c27ec8Sbaban 
4038e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
4039e8c27ec8Sbaban 		idmap_lookup_release_batch(&qs);
4040e8c27ec8Sbaban 	else
40410dcc7149Snw141292 		retcode = idmap_lookup_batch_end(&qs);
4042e8c27ec8Sbaban 
4043e8c27ec8Sbaban 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
4044e8c27ec8Sbaban 		goto retry;
4045e8c27ec8Sbaban 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
4046349d5d8fSnw141292 		degrade_svc(1, "some AD lookups timed out repeatedly");
4047c5c4113dSnw141292 
4048e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
4049e8c27ec8Sbaban 		idmapdlog(LOG_NOTICE, "AD lookup by SID failed");
4050c5c4113dSnw141292 		return (retcode);
4051c5c4113dSnw141292 	}
4052e8c27ec8Sbaban 	return (rc);
4053e8c27ec8Sbaban }
4054c5c4113dSnw141292 
4055cd37da74Snw141292 static
4056cd37da74Snw141292 int
4057651c0131Sbaban copy_mapping_request(idmap_mapping *mapping, idmap_mapping *request)
4058c5c4113dSnw141292 {
4059651c0131Sbaban 	(void) memset(mapping, 0, sizeof (*mapping));
4060651c0131Sbaban 
4061c5c4113dSnw141292 	mapping->flag = request->flag;
4062e8c27ec8Sbaban 	mapping->direction = _IDMAP_F_DONE;
4063651c0131Sbaban 	mapping->id2.idtype = request->id2.idtype;
4064c5c4113dSnw141292 
4065c5c4113dSnw141292 	mapping->id1.idtype = request->id1.idtype;
4066cd37da74Snw141292 	if (IS_REQUEST_SID(*request, 1)) {
4067c5c4113dSnw141292 		mapping->id1.idmap_id_u.sid.rid =
4068c5c4113dSnw141292 		    request->id1.idmap_id_u.sid.rid;
4069651c0131Sbaban 		if (!EMPTY_STRING(request->id1.idmap_id_u.sid.prefix)) {
4070c5c4113dSnw141292 			mapping->id1.idmap_id_u.sid.prefix =
4071c5c4113dSnw141292 			    strdup(request->id1.idmap_id_u.sid.prefix);
4072651c0131Sbaban 			if (mapping->id1.idmap_id_u.sid.prefix == NULL)
40738e228215Sdm199847 				goto errout;
4074651c0131Sbaban 		}
4075c5c4113dSnw141292 	} else {
4076c5c4113dSnw141292 		mapping->id1.idmap_id_u.uid = request->id1.idmap_id_u.uid;
4077c5c4113dSnw141292 	}
4078c5c4113dSnw141292 
4079e8c27ec8Sbaban 	if (!EMPTY_STRING(request->id1domain)) {
40808e228215Sdm199847 		mapping->id1domain = strdup(request->id1domain);
40818e228215Sdm199847 		if (mapping->id1domain == NULL)
40828e228215Sdm199847 			goto errout;
4083e8c27ec8Sbaban 	}
4084c5c4113dSnw141292 
4085e8c27ec8Sbaban 	if (!EMPTY_STRING(request->id1name)) {
40868e228215Sdm199847 		mapping->id1name = strdup(request->id1name);
40878e228215Sdm199847 		if (mapping->id1name == NULL)
40888e228215Sdm199847 			goto errout;
4089e8c27ec8Sbaban 	}
4090c5c4113dSnw141292 
4091651c0131Sbaban 	/* We don't need the rest of the request i.e request->id2 */
4092651c0131Sbaban 	return (0);
4093c5c4113dSnw141292 
4094651c0131Sbaban errout:
40958e228215Sdm199847 	if (mapping->id1.idmap_id_u.sid.prefix != NULL)
4096651c0131Sbaban 		free(mapping->id1.idmap_id_u.sid.prefix);
40978e228215Sdm199847 	if (mapping->id1domain != NULL)
40988e228215Sdm199847 		free(mapping->id1domain);
40998e228215Sdm199847 	if (mapping->id1name != NULL)
41008e228215Sdm199847 		free(mapping->id1name);
4101651c0131Sbaban 
4102651c0131Sbaban 	(void) memset(mapping, 0, sizeof (*mapping));
4103651c0131Sbaban 	return (-1);
4104c5c4113dSnw141292 }
4105c5c4113dSnw141292 
4106c5c4113dSnw141292 
4107c5c4113dSnw141292 idmap_retcode
4108c5c4113dSnw141292 get_w2u_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
4109cd37da74Snw141292 		idmap_mapping *mapping)
4110cd37da74Snw141292 {
4111c5c4113dSnw141292 	idmap_id_res	idres;
4112c5c4113dSnw141292 	lookup_state_t	state;
4113dd5829d1Sbaban 	char		*cp;
4114c5c4113dSnw141292 	idmap_retcode	retcode;
4115c5c4113dSnw141292 	const char	*winname, *windomain;
4116c5c4113dSnw141292 
4117c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
4118c5c4113dSnw141292 	(void) memset(&state, 0, sizeof (state));
4119c5c4113dSnw141292 
4120e8c27ec8Sbaban 	/* Get directory-based name mapping info */
4121e8c27ec8Sbaban 	retcode = get_ds_namemap_type(&state);
4122e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
4123c5c4113dSnw141292 		goto out;
4124c5c4113dSnw141292 
4125e8c27ec8Sbaban 	/*
4126e8c27ec8Sbaban 	 * Copy data from "request" to "mapping". Note that
4127e8c27ec8Sbaban 	 * empty strings are not copied from "request" to
4128e8c27ec8Sbaban 	 * "mapping" and therefore the coresponding strings in
4129e8c27ec8Sbaban 	 * "mapping" will be NULL. This eliminates having to
4130e8c27ec8Sbaban 	 * check for empty strings henceforth.
4131e8c27ec8Sbaban 	 */
4132651c0131Sbaban 	if (copy_mapping_request(mapping, request) < 0) {
4133651c0131Sbaban 		retcode = IDMAP_ERR_MEMORY;
4134651c0131Sbaban 		goto out;
4135651c0131Sbaban 	}
4136c5c4113dSnw141292 
41378e228215Sdm199847 	winname = mapping->id1name;
41388e228215Sdm199847 	windomain = mapping->id1domain;
4139c5c4113dSnw141292 
4140e8c27ec8Sbaban 	if (winname == NULL && windomain != NULL) {
4141c5c4113dSnw141292 		retcode = IDMAP_ERR_ARG;
4142c5c4113dSnw141292 		goto out;
4143c5c4113dSnw141292 	}
4144c5c4113dSnw141292 
4145e8c27ec8Sbaban 	/* Need atleast winname or sid to proceed */
4146e8c27ec8Sbaban 	if (winname == NULL && mapping->id1.idmap_id_u.sid.prefix == NULL) {
4147e8c27ec8Sbaban 		retcode = IDMAP_ERR_ARG;
4148e8c27ec8Sbaban 		goto out;
4149e8c27ec8Sbaban 	}
4150e8c27ec8Sbaban 
4151e8c27ec8Sbaban 	/*
4152e8c27ec8Sbaban 	 * If domainname is not given but we have a fully qualified
4153e8c27ec8Sbaban 	 * winname then extract the domainname from the winname,
4154e8c27ec8Sbaban 	 * otherwise use the default_domain from the config
4155e8c27ec8Sbaban 	 */
4156e8c27ec8Sbaban 	if (winname != NULL && windomain == NULL) {
41578e228215Sdm199847 		retcode = IDMAP_SUCCESS;
4158dd5829d1Sbaban 		if ((cp = strchr(winname, '@')) != NULL) {
4159dd5829d1Sbaban 			*cp = '\0';
41608e228215Sdm199847 			mapping->id1domain = strdup(cp + 1);
41618e228215Sdm199847 			if (mapping->id1domain == NULL)
41628e228215Sdm199847 				retcode = IDMAP_ERR_MEMORY;
4163e8c27ec8Sbaban 		} else if (lookup_wksids_name2sid(winname, NULL, NULL, NULL,
4164e8c27ec8Sbaban 		    NULL) != IDMAP_SUCCESS) {
4165e8c27ec8Sbaban 			/* well-known SIDs don't need domain */
41668e228215Sdm199847 			RDLOCK_CONFIG();
4167c8e26105Sjp151216 			if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
41688e228215Sdm199847 				mapping->id1domain =
41698e228215Sdm199847 				    strdup(_idmapdstate.cfg->
4170c8e26105Sjp151216 				    pgcfg.default_domain);
41718e228215Sdm199847 				if (mapping->id1domain == NULL)
41728e228215Sdm199847 					retcode = IDMAP_ERR_MEMORY;
4173e8c27ec8Sbaban 			} else {
4174e8c27ec8Sbaban 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
41758e228215Sdm199847 			}
4176c5c4113dSnw141292 			UNLOCK_CONFIG();
41778e228215Sdm199847 		}
4178c5c4113dSnw141292 		if (retcode != IDMAP_SUCCESS)
4179c5c4113dSnw141292 			goto out;
4180c5c4113dSnw141292 	}
4181c5c4113dSnw141292 
4182e8c27ec8Sbaban 	/*
4183e8c27ec8Sbaban 	 * First pass looks up the well-known SIDs table and cache
4184e8c27ec8Sbaban 	 * and handles localSIDs
4185e8c27ec8Sbaban 	 */
4186c5c4113dSnw141292 	state.sid2pid_done = TRUE;
4187c5c4113dSnw141292 	retcode = sid2pid_first_pass(&state, cache, mapping, &idres);
4188c5c4113dSnw141292 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
4189c5c4113dSnw141292 		goto out;
4190c5c4113dSnw141292 
4191e8c27ec8Sbaban 	/* AD lookup by winname or by sid */
4192e8c27ec8Sbaban 	if (state.ad_nqueries > 0) {
4193e8c27ec8Sbaban 		retcode = ad_lookup(&state, mapping, &idres, 1, 1, 0);
4194e8c27ec8Sbaban 		if (IDMAP_ERROR(retcode))
4195e8c27ec8Sbaban 			goto out;
4196c5c4113dSnw141292 	}
4197c5c4113dSnw141292 
4198e8c27ec8Sbaban 	/*
4199e8c27ec8Sbaban 	 * If nldap-based name mapping is enabled then lookup native LDAP
4200e8c27ec8Sbaban 	 * directory service by winname to get pid and unixname. Ignore
4201e8c27ec8Sbaban 	 * non-fatal errors in which case we simply fallback to evaluating
4202e8c27ec8Sbaban 	 * local name-based mapping rules.
4203e8c27ec8Sbaban 	 */
4204e8c27ec8Sbaban 	if (mapping->id1name != NULL && NLDAP_MODE(idres.id.idtype, (&state))) {
4205e8c27ec8Sbaban 		retcode = nldap_lookup(mapping, &idres, 1, 1);
420648258c6bSjp151216 		if (IDMAP_FATAL_ERROR(retcode)) {
4207e8c27ec8Sbaban 			goto out;
420848258c6bSjp151216 		}
4209e8c27ec8Sbaban 		idres.retcode = IDMAP_SUCCESS;
4210e8c27ec8Sbaban 	}
4211e8c27ec8Sbaban 
4212e8c27ec8Sbaban 	/* Next pass performs name-based mapping and ephemeral mapping. */
4213c5c4113dSnw141292 	state.sid2pid_done = TRUE;
4214c5c4113dSnw141292 	retcode = sid2pid_second_pass(&state, cache, db, mapping, &idres);
4215c5c4113dSnw141292 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
4216c5c4113dSnw141292 		goto out;
4217c5c4113dSnw141292 
4218c5c4113dSnw141292 	/* Update cache */
4219c5c4113dSnw141292 	(void) update_cache_sid2pid(&state, cache, mapping, &idres);
4220c5c4113dSnw141292 
4221c5c4113dSnw141292 out:
4222e8c27ec8Sbaban 	/*
4223e8c27ec8Sbaban 	 * Note that "mapping" is returned to the client. Therefore
4224e8c27ec8Sbaban 	 * copy whatever we have in "idres" to mapping->id2 and
4225e8c27ec8Sbaban 	 * free idres.
4226e8c27ec8Sbaban 	 */
4227c5c4113dSnw141292 	mapping->direction = idres.direction;
4228c5c4113dSnw141292 	mapping->id2 = idres.id;
422948258c6bSjp151216 	if (mapping->flag & IDMAP_REQ_FLG_MAPPING_INFO ||
423048258c6bSjp151216 	    retcode != IDMAP_SUCCESS)
423148258c6bSjp151216 		(void) idmap_info_mov(&mapping->info, &idres.info);
423248258c6bSjp151216 	else
423348258c6bSjp151216 		idmap_info_free(&idres.info);
4234c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
4235e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
423662c60062Sbaban 		mapping->id2.idmap_id_u.uid = UID_NOBODY;
4237c5c4113dSnw141292 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
4238e8c27ec8Sbaban 	cleanup_lookup_state(&state);
4239c5c4113dSnw141292 	return (retcode);
4240c5c4113dSnw141292 }
4241c5c4113dSnw141292 
4242c5c4113dSnw141292 idmap_retcode
4243c5c4113dSnw141292 get_u2w_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
4244cd37da74Snw141292 		idmap_mapping *mapping, int is_user)
4245cd37da74Snw141292 {
4246c5c4113dSnw141292 	idmap_id_res	idres;
4247c5c4113dSnw141292 	lookup_state_t	state;
4248c5c4113dSnw141292 	idmap_retcode	retcode;
4249e8c27ec8Sbaban 	char		*canonname;
4250e8c27ec8Sbaban 	int		is_wuser;
4251c5c4113dSnw141292 
4252c5c4113dSnw141292 	/*
4253c5c4113dSnw141292 	 * In order to re-use the pid2sid code, we convert
4254c5c4113dSnw141292 	 * our input data into structs that are expected by
4255c5c4113dSnw141292 	 * pid2sid_first_pass.
4256c5c4113dSnw141292 	 */
4257c5c4113dSnw141292 
4258c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
4259c5c4113dSnw141292 	(void) memset(&state, 0, sizeof (state));
4260c5c4113dSnw141292 
4261e8c27ec8Sbaban 	/* Get directory-based name mapping info */
4262e8c27ec8Sbaban 	retcode = get_ds_namemap_type(&state);
4263e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
4264e8c27ec8Sbaban 		goto out;
4265e8c27ec8Sbaban 
4266e8c27ec8Sbaban 	/*
4267e8c27ec8Sbaban 	 * Copy data from "request" to "mapping". Note that
4268e8c27ec8Sbaban 	 * empty strings are not copied from "request" to
4269e8c27ec8Sbaban 	 * "mapping" and therefore the coresponding strings in
4270e8c27ec8Sbaban 	 * "mapping" will be NULL. This eliminates having to
4271e8c27ec8Sbaban 	 * check for empty strings henceforth.
4272e8c27ec8Sbaban 	 */
4273651c0131Sbaban 	if (copy_mapping_request(mapping, request) < 0) {
4274651c0131Sbaban 		retcode = IDMAP_ERR_MEMORY;
4275651c0131Sbaban 		goto out;
4276651c0131Sbaban 	}
4277c5c4113dSnw141292 
4278e8c27ec8Sbaban 	/*
4279e8c27ec8Sbaban 	 * For unix to windows mapping request, we need atleast a
4280e8c27ec8Sbaban 	 * unixname or uid/gid to proceed
4281e8c27ec8Sbaban 	 */
4282e8c27ec8Sbaban 	if (mapping->id1name == NULL &&
4283cf5b5989Sdm199847 	    mapping->id1.idmap_id_u.uid == SENTINEL_PID) {
4284c5c4113dSnw141292 		retcode = IDMAP_ERR_ARG;
4285c5c4113dSnw141292 		goto out;
4286c5c4113dSnw141292 	}
4287c5c4113dSnw141292 
4288e8c27ec8Sbaban 	/* First pass looks up cache and well-known SIDs */
4289e8c27ec8Sbaban 	state.pid2sid_done = TRUE;
4290e8c27ec8Sbaban 	retcode = pid2sid_first_pass(&state, cache, mapping, &idres,
4291e8c27ec8Sbaban 	    is_user, 1);
4292e8c27ec8Sbaban 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
4293c5c4113dSnw141292 		goto out;
4294e8c27ec8Sbaban 
4295e8c27ec8Sbaban 	if (state.nldap_nqueries > 0) {
4296e8c27ec8Sbaban 		/*
4297e8c27ec8Sbaban 		 * This means directory-based name mapping (nldap or mixed
4298e8c27ec8Sbaban 		 * mode) is enabled. Lookup native LDAP directory service
4299e8c27ec8Sbaban 		 * by unixname or pid to get the winname. Ignore non-fatal
4300e8c27ec8Sbaban 		 * errors in which case we simply fallback to local name
4301e8c27ec8Sbaban 		 * based mapping rules.
4302e8c27ec8Sbaban 		 */
4303e8c27ec8Sbaban 		retcode = nldap_lookup(mapping, &idres, 0, 0);
4304e8c27ec8Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
4305c5c4113dSnw141292 			goto out;
4306e8c27ec8Sbaban 		idres.retcode = IDMAP_SUCCESS;
4307e8c27ec8Sbaban 
4308e8c27ec8Sbaban 		/*
4309e8c27ec8Sbaban 		 * If we've winname then get SID. We use lookup_name2sid()
4310e8c27ec8Sbaban 		 * instead of ad_lookup() in order to first resolve name2sid
4311e8c27ec8Sbaban 		 * using well-known SIDs table and name_cache before trying
4312e8c27ec8Sbaban 		 * AD.
4313e8c27ec8Sbaban 		 */
4314e8c27ec8Sbaban 		if (mapping->id2name != NULL) {
4315e8c27ec8Sbaban 			canonname = NULL;
4316e8c27ec8Sbaban 			is_wuser = -1;
4317e8c27ec8Sbaban 			retcode = lookup_name2sid(cache, mapping->id2name,
4318e8c27ec8Sbaban 			    mapping->id2domain, &is_wuser, &canonname,
4319e8c27ec8Sbaban 			    &idres.id.idmap_id_u.sid.prefix,
4320e8c27ec8Sbaban 			    &idres.id.idmap_id_u.sid.rid, mapping);
4321e8c27ec8Sbaban 			if (canonname != NULL) {
4322e8c27ec8Sbaban 				free(mapping->id2name);
4323e8c27ec8Sbaban 				mapping->id2name = canonname;
4324c5c4113dSnw141292 			}
4325e8c27ec8Sbaban 			if (retcode == IDMAP_SUCCESS)
4326e8c27ec8Sbaban 				idres.id.idtype = is_wuser ? IDMAP_USID :
4327e8c27ec8Sbaban 				    IDMAP_GSID;
4328e8c27ec8Sbaban 			idres.retcode = retcode;
4329c5c4113dSnw141292 		}
4330e8c27ec8Sbaban 	} else if (state.ad_nqueries > 0) {
4331e8c27ec8Sbaban 		/*
4332e8c27ec8Sbaban 		 * This means AD-based name mapping is enabled.
4333e8c27ec8Sbaban 		 * Lookup AD by unixname to get winname and sid.
4334e8c27ec8Sbaban 		 * Ignore non-fatal errors in which case we simply fallback
4335e8c27ec8Sbaban 		 * to local name based mapping rules.
4336e8c27ec8Sbaban 		 */
4337e8c27ec8Sbaban 		retcode = ad_lookup(&state, mapping, &idres, 0, 0, 1);
4338e8c27ec8Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
4339e8c27ec8Sbaban 			goto out;
4340e8c27ec8Sbaban 		idres.retcode = IDMAP_SUCCESS;
4341c5c4113dSnw141292 	}
4342c5c4113dSnw141292 
4343e8c27ec8Sbaban 	/*
4344e8c27ec8Sbaban 	 * Next pass processes the result of the preceding passes/lookups.
4345e8c27ec8Sbaban 	 * It returns if there's nothing more to be done otherwise it
4346e8c27ec8Sbaban 	 * evaluates local name-based mapping rules
4347e8c27ec8Sbaban 	 */
4348c5c4113dSnw141292 	state.pid2sid_done = TRUE;
4349e8c27ec8Sbaban 	retcode = pid2sid_second_pass(&state, cache, db, mapping, &idres,
4350e8c27ec8Sbaban 	    is_user);
4351c5c4113dSnw141292 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
4352c5c4113dSnw141292 		goto out;
4353c5c4113dSnw141292 
4354c5c4113dSnw141292 	/* Update cache */
4355c5c4113dSnw141292 	(void) update_cache_pid2sid(&state, cache, mapping, &idres);
4356c5c4113dSnw141292 
4357c5c4113dSnw141292 out:
4358e8c27ec8Sbaban 	/*
4359e8c27ec8Sbaban 	 * Note that "mapping" is returned to the client. Therefore
4360e8c27ec8Sbaban 	 * copy whatever we have in "idres" to mapping->id2 and
4361e8c27ec8Sbaban 	 * free idres.
4362e8c27ec8Sbaban 	 */
4363c5c4113dSnw141292 	mapping->direction = idres.direction;
4364c5c4113dSnw141292 	mapping->id2 = idres.id;
436548258c6bSjp151216 	if (mapping->flag & IDMAP_REQ_FLG_MAPPING_INFO ||
436648258c6bSjp151216 	    retcode != IDMAP_SUCCESS)
436748258c6bSjp151216 		(void) idmap_info_mov(&mapping->info, &idres.info);
436848258c6bSjp151216 	else
436948258c6bSjp151216 		idmap_info_free(&idres.info);
4370c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
4371c5c4113dSnw141292 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
4372e8c27ec8Sbaban 	cleanup_lookup_state(&state);
4373e8c27ec8Sbaban 	return (retcode);
4374e8c27ec8Sbaban }
4375e8c27ec8Sbaban 
4376e8c27ec8Sbaban static
4377e8c27ec8Sbaban idmap_retcode
4378e8c27ec8Sbaban ad_lookup_by_unixname(lookup_state_t *state,
4379e8c27ec8Sbaban 		const char *unixname, int is_user, int is_wuser,
438048258c6bSjp151216 		char **dn, char **attr, char **value, char **sidprefix,
438148258c6bSjp151216 		idmap_rid_t *rid, char **winname, char **domain, int *type)
4382e8c27ec8Sbaban {
4383e8c27ec8Sbaban 	/* Lookup AD by unixname */
4384e8c27ec8Sbaban 	int			retries = 0;
4385e8c27ec8Sbaban 	idmap_query_state_t	*qs = NULL;
4386e8c27ec8Sbaban 	idmap_retcode		rc, retcode;
4387e8c27ec8Sbaban 
4388e8c27ec8Sbaban retry:
4389e8c27ec8Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, 1, &qs);
4390e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
43910dcc7149Snw141292 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
43920dcc7149Snw141292 			goto retry;
4393349d5d8fSnw141292 		degrade_svc(1, "failed to create request for AD lookup "
43940dcc7149Snw141292 		    "by unixname");
4395e8c27ec8Sbaban 		return (IDMAP_ERR_INTERNAL);
4396e8c27ec8Sbaban 	}
4397e8c27ec8Sbaban 
4398e8c27ec8Sbaban 	restore_svc();
4399e8c27ec8Sbaban 
4400e8c27ec8Sbaban 	if (state != NULL)
4401e8c27ec8Sbaban 		idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
4402e8c27ec8Sbaban 		    state->ad_unixgroup_attr);
4403e8c27ec8Sbaban 
4404e8c27ec8Sbaban 	retcode = idmap_unixname2sid_batch_add1(qs, unixname, is_user,
440548258c6bSjp151216 	    is_wuser, dn, attr, value, sidprefix, rid, winname, domain,
440648258c6bSjp151216 	    type, &rc);
4407e8c27ec8Sbaban 
4408e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
4409e8c27ec8Sbaban 		idmap_lookup_release_batch(&qs);
4410e8c27ec8Sbaban 	else
44110dcc7149Snw141292 		retcode = idmap_lookup_batch_end(&qs);
4412e8c27ec8Sbaban 
4413e8c27ec8Sbaban 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
4414e8c27ec8Sbaban 		goto retry;
4415e8c27ec8Sbaban 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
4416349d5d8fSnw141292 		degrade_svc(1, "some AD lookups timed out repeatedly");
4417e8c27ec8Sbaban 
4418e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
4419e8c27ec8Sbaban 		idmapdlog(LOG_NOTICE, "AD lookup by unixname failed");
4420e8c27ec8Sbaban 		return (retcode);
4421e8c27ec8Sbaban 	}
4422e8c27ec8Sbaban 	return (rc);
4423e8c27ec8Sbaban }
4424e8c27ec8Sbaban 
4425e8c27ec8Sbaban /*
4426e8c27ec8Sbaban  * This function is called whenever a non-batched AD lookup needs to be
4427e8c27ec8Sbaban  * done (e.g. get_w2u_mapping() and get_u2w_mapping()). It's already
4428e8c27ec8Sbaban  * determined by the caller before calling this function that AD lookup is
4429e8c27ec8Sbaban  * needed and has already searched the well-known SIDs table and name_cache.
4430e8c27ec8Sbaban  */
4431e8c27ec8Sbaban static
4432e8c27ec8Sbaban idmap_retcode
4433e8c27ec8Sbaban ad_lookup(lookup_state_t *state, idmap_mapping *req, idmap_id_res *res,
4434e8c27ec8Sbaban 		int w2u, int getunixattr, int byunixattr)
4435e8c27ec8Sbaban {
4436e8c27ec8Sbaban 	idmap_retcode	retcode;
4437e8c27ec8Sbaban 	int		type, eunixtype, is_user, is_wuser;
4438e8c27ec8Sbaban 	char		*canonname = NULL;
443948258c6bSjp151216 	idmap_how	*how = &res->info.how;
4440e8c27ec8Sbaban 
4441e8c27ec8Sbaban 	if (w2u) {
4442e8c27ec8Sbaban 		/*
4443e8c27ec8Sbaban 		 * win2unix lookup requests (get_w2u_mapping()) calls this
4444e8c27ec8Sbaban 		 * function to lookup by sid OR winname and to retrieve
4445e8c27ec8Sbaban 		 * SID, winname, sidtype (user or group) and unixnames
4446e8c27ec8Sbaban 		 * from AD.
4447e8c27ec8Sbaban 		 */
4448e8c27ec8Sbaban 
4449e8c27ec8Sbaban 		/* Set the expected unixtype */
4450e8c27ec8Sbaban 		if (res->id.idtype == IDMAP_UID)
4451e8c27ec8Sbaban 			eunixtype = _IDMAP_T_USER;
4452e8c27ec8Sbaban 		else if (res->id.idtype == IDMAP_GID)
4453e8c27ec8Sbaban 			eunixtype = _IDMAP_T_GROUP;
4454e8c27ec8Sbaban 		else
4455e8c27ec8Sbaban 			eunixtype = _IDMAP_T_UNDEF;
4456e8c27ec8Sbaban 
4457e8c27ec8Sbaban 		if (req->id1.idmap_id_u.sid.prefix != NULL) {
4458e8c27ec8Sbaban 			/* AD lookup by sid */
445948258c6bSjp151216 			res->info.src = IDMAP_MAP_SRC_NEW;
446048258c6bSjp151216 			how->map_type = IDMAP_MAP_TYPE_DS_AD;
4461e8c27ec8Sbaban 			retcode = ad_lookup_by_sid(
4462e8c27ec8Sbaban 			    state, req->id1.idmap_id_u.sid.prefix,
4463e8c27ec8Sbaban 			    req->id1.idmap_id_u.sid.rid, eunixtype,
446448258c6bSjp151216 			    &how->idmap_how_u.ad.dn,
446548258c6bSjp151216 			    &how->idmap_how_u.ad.attr,
446648258c6bSjp151216 			    &how->idmap_how_u.ad.value,
4467e8c27ec8Sbaban 			    (req->id1name == NULL) ? &req->id1name : NULL,
4468e8c27ec8Sbaban 			    (req->id1domain == NULL) ? &req->id1domain : NULL,
4469e8c27ec8Sbaban 			    &type, (getunixattr && req->id2name == NULL)
4470e8c27ec8Sbaban 			    ? &req->id2name : NULL);
4471e8c27ec8Sbaban 		} else {
4472e8c27ec8Sbaban 			assert(req->id1name != NULL);
4473e8c27ec8Sbaban 			/* AD lookup by winname */
447448258c6bSjp151216 			res->info.src = IDMAP_MAP_SRC_NEW;
447548258c6bSjp151216 			how->map_type = IDMAP_MAP_TYPE_DS_AD;
4476e8c27ec8Sbaban 			retcode = ad_lookup_by_winname(
4477e8c27ec8Sbaban 			    state, req->id1name, req->id1domain, eunixtype,
447848258c6bSjp151216 			    &how->idmap_how_u.ad.dn,
447948258c6bSjp151216 			    &how->idmap_how_u.ad.attr,
448048258c6bSjp151216 			    &how->idmap_how_u.ad.value,
448148258c6bSjp151216 			    &canonname,
448248258c6bSjp151216 			    &req->id1.idmap_id_u.sid.prefix,
4483e8c27ec8Sbaban 			    &req->id1.idmap_id_u.sid.rid, &type,
4484e8c27ec8Sbaban 			    (getunixattr && req->id2name == NULL)
4485e8c27ec8Sbaban 			    ? &req->id2name : NULL);
4486e8c27ec8Sbaban 
4487e8c27ec8Sbaban 			if (canonname != NULL) {
4488e8c27ec8Sbaban 				free(req->id1name);
4489e8c27ec8Sbaban 				req->id1name = canonname;
4490e8c27ec8Sbaban 			}
4491e8c27ec8Sbaban 		}
4492e8c27ec8Sbaban 		if (retcode == IDMAP_SUCCESS) {
4493e8c27ec8Sbaban 			switch (type) {
4494e8c27ec8Sbaban 			case _IDMAP_T_USER:
4495e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
4496e8c27ec8Sbaban 					res->id.idtype = IDMAP_UID;
4497e8c27ec8Sbaban 				req->id1.idtype = IDMAP_USID;
4498e8c27ec8Sbaban 				break;
4499e8c27ec8Sbaban 			case _IDMAP_T_GROUP:
4500e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
4501e8c27ec8Sbaban 					res->id.idtype = IDMAP_GID;
4502e8c27ec8Sbaban 				req->id1.idtype = IDMAP_GSID;
4503e8c27ec8Sbaban 				break;
4504e8c27ec8Sbaban 			default:
4505e8c27ec8Sbaban 				return (IDMAP_ERR_SID);
4506e8c27ec8Sbaban 			}
450748258c6bSjp151216 		} else if (retcode == IDMAP_ERR_NOTFOUND) {
450848258c6bSjp151216 			/* Nothing found - remove the preset info */
450948258c6bSjp151216 			res->info.src = IDMAP_MAP_SRC_UNKNOWN;
451048258c6bSjp151216 			how->map_type = IDMAP_MAP_TYPE_UNKNOWN;
4511e8c27ec8Sbaban 		}
4512e8c27ec8Sbaban 		return (retcode);
4513e8c27ec8Sbaban 	}
4514e8c27ec8Sbaban 
4515e8c27ec8Sbaban 	/*
4516e8c27ec8Sbaban 	 * unix2win lookup requests (get_u2w_mapping()) calls this
4517e8c27ec8Sbaban 	 * function to lookup AD by unixname and to retrieve
4518e8c27ec8Sbaban 	 * SID, winname, and sidtype (user or group) from AD.
4519e8c27ec8Sbaban 	 */
4520e8c27ec8Sbaban 
4521e8c27ec8Sbaban 	/* Set the expected unixtype */
4522e8c27ec8Sbaban 	eunixtype = (req->id1.idtype == IDMAP_UID) ? _IDMAP_T_USER :
4523e8c27ec8Sbaban 	    _IDMAP_T_GROUP;
4524e8c27ec8Sbaban 
4525e8c27ec8Sbaban 	if (byunixattr) {
4526e8c27ec8Sbaban 		/* AD lookup by unixname */
4527e8c27ec8Sbaban 		is_user = (IS_REQUEST_UID(*req)) ? 1 : 0;
4528e8c27ec8Sbaban 		if (res->id.idtype == IDMAP_USID)
4529e8c27ec8Sbaban 			is_wuser = 1;
4530e8c27ec8Sbaban 		else if (res->id.idtype == IDMAP_GSID)
4531e8c27ec8Sbaban 			is_wuser = 0;
4532e8c27ec8Sbaban 		else
4533e8c27ec8Sbaban 			is_wuser = is_user;
453448258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
453548258c6bSjp151216 		how->map_type = IDMAP_MAP_TYPE_DS_AD;
4536e8c27ec8Sbaban 		retcode = ad_lookup_by_unixname(
4537e8c27ec8Sbaban 		    state, req->id1name, is_user, is_wuser,
453848258c6bSjp151216 		    &how->idmap_how_u.ad.dn,
453948258c6bSjp151216 		    &how->idmap_how_u.ad.attr,
454048258c6bSjp151216 		    &how->idmap_how_u.ad.value,
4541e8c27ec8Sbaban 		    (res->id.idmap_id_u.sid.prefix == NULL) ?
4542e8c27ec8Sbaban 		    &res->id.idmap_id_u.sid.prefix : NULL,
4543e8c27ec8Sbaban 		    (res->id.idmap_id_u.sid.prefix == NULL) ?
4544e8c27ec8Sbaban 		    &res->id.idmap_id_u.sid.rid : NULL,
4545e8c27ec8Sbaban 		    (req->id2name == NULL) ? &req->id2name : NULL,
454648258c6bSjp151216 		    (req->id2domain == NULL) ? &req->id2domain : NULL, &type);
4547e8c27ec8Sbaban 	} else if (res->id.idmap_id_u.sid.prefix != NULL) {
4548e8c27ec8Sbaban 		/* AD lookup by sid */
454948258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
455048258c6bSjp151216 		how->map_type = IDMAP_MAP_TYPE_DS_AD;
4551e8c27ec8Sbaban 		retcode = ad_lookup_by_sid(
4552e8c27ec8Sbaban 		    state, res->id.idmap_id_u.sid.prefix,
4553e8c27ec8Sbaban 		    res->id.idmap_id_u.sid.rid, eunixtype,
455448258c6bSjp151216 		    &how->idmap_how_u.ad.dn,
455548258c6bSjp151216 		    &how->idmap_how_u.ad.attr,
455648258c6bSjp151216 		    &how->idmap_how_u.ad.value,
4557e8c27ec8Sbaban 		    (req->id2name == NULL) ? &req->id2name : NULL,
4558e8c27ec8Sbaban 		    (req->id2domain == NULL) ? &req->id2domain : NULL,
455948258c6bSjp151216 		    &type, (getunixattr && req->id1name == NULL)
4560e8c27ec8Sbaban 		    ? &req->id1name : NULL);
4561e8c27ec8Sbaban 	} else {
4562e8c27ec8Sbaban 		/* AD lookup by winname */
4563e8c27ec8Sbaban 		assert(req->id2name != NULL);
456448258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
456548258c6bSjp151216 		how->map_type = IDMAP_MAP_TYPE_DS_AD;
4566e8c27ec8Sbaban 		retcode = ad_lookup_by_winname(
4567e8c27ec8Sbaban 		    state, req->id2name, req->id2domain, eunixtype,
456848258c6bSjp151216 		    &how->idmap_how_u.ad.dn,
456948258c6bSjp151216 		    &how->idmap_how_u.ad.attr,
457048258c6bSjp151216 		    &how->idmap_how_u.ad.value,
4571e8c27ec8Sbaban 		    &canonname, &res->id.idmap_id_u.sid.prefix,
457248258c6bSjp151216 		    &res->id.idmap_id_u.sid.rid, &type,
4573e8c27ec8Sbaban 		    (getunixattr && req->id1name == NULL)
4574e8c27ec8Sbaban 		    ? &req->id1name : NULL);
4575e8c27ec8Sbaban 
4576e8c27ec8Sbaban 		if (canonname != NULL) {
4577e8c27ec8Sbaban 			free(req->id2name);
4578e8c27ec8Sbaban 			req->id2name = canonname;
4579e8c27ec8Sbaban 		}
4580e8c27ec8Sbaban 	}
4581e8c27ec8Sbaban 
4582e8c27ec8Sbaban 	if (retcode == IDMAP_SUCCESS) {
4583e8c27ec8Sbaban 		switch (type) {
4584e8c27ec8Sbaban 		case _IDMAP_T_USER:
4585e8c27ec8Sbaban 			if (res->id.idtype == IDMAP_SID)
4586e8c27ec8Sbaban 				res->id.idtype = IDMAP_USID;
4587e8c27ec8Sbaban 			break;
4588e8c27ec8Sbaban 		case _IDMAP_T_GROUP:
4589e8c27ec8Sbaban 			if (res->id.idtype == IDMAP_SID)
4590e8c27ec8Sbaban 				res->id.idtype = IDMAP_GSID;
4591e8c27ec8Sbaban 			break;
4592e8c27ec8Sbaban 		default:
4593e8c27ec8Sbaban 			return (IDMAP_ERR_SID);
4594e8c27ec8Sbaban 		}
459548258c6bSjp151216 	} else if (retcode == IDMAP_ERR_NOTFOUND) {
459648258c6bSjp151216 		/* Nothing found - remove the preset info */
459748258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_UNKNOWN;
459848258c6bSjp151216 		how->map_type = IDMAP_MAP_TYPE_UNKNOWN;
4599e8c27ec8Sbaban 	}
4600c5c4113dSnw141292 	return (retcode);
4601c5c4113dSnw141292 }
4602