xref: /titanic_52/usr/src/cmd/idmap/idmapd/dbutils.c (revision 4d61c878ad5fbf36c5338bef5994cc5fe88a589a)
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 /*
27c5c4113dSnw141292  * Database related utility routines
28c5c4113dSnw141292  */
29c5c4113dSnw141292 
30c5c4113dSnw141292 #include <stdio.h>
31c5c4113dSnw141292 #include <stdlib.h>
32c5c4113dSnw141292 #include <string.h>
33c5c4113dSnw141292 #include <errno.h>
34c5c4113dSnw141292 #include <sys/types.h>
35c5c4113dSnw141292 #include <sys/stat.h>
36c5c4113dSnw141292 #include <rpc/rpc.h>
37c5c4113dSnw141292 #include <sys/sid.h>
38c5c4113dSnw141292 #include <time.h>
39c5c4113dSnw141292 #include <pwd.h>
40c5c4113dSnw141292 #include <grp.h>
4184decf41Sjp151216 #include <pthread.h>
4284decf41Sjp151216 #include <assert.h>
43cd37da74Snw141292 #include <sys/u8_textprep.h>
44c5c4113dSnw141292 
45c5c4113dSnw141292 #include "idmapd.h"
46c5c4113dSnw141292 #include "adutils.h"
47c5c4113dSnw141292 #include "string.h"
48c5c4113dSnw141292 #include "idmap_priv.h"
49cd37da74Snw141292 #include "schema.h"
50e8c27ec8Sbaban #include "nldaputils.h"
51c5c4113dSnw141292 
5284decf41Sjp151216 
53c5c4113dSnw141292 static idmap_retcode sql_compile_n_step_once(sqlite *, char *,
54c5c4113dSnw141292 		sqlite_vm **, int *, int, const char ***);
55479ac375Sdm199847 static idmap_retcode ad_lookup_one(lookup_state_t *, idmap_mapping *,
56479ac375Sdm199847 		idmap_id_res *);
57e8c27ec8Sbaban static idmap_retcode lookup_localsid2pid(idmap_mapping *, idmap_id_res *);
58e8c27ec8Sbaban static idmap_retcode lookup_cache_name2sid(sqlite *, const char *,
59e8c27ec8Sbaban 		const char *, char **, char **, idmap_rid_t *, int *);
60e8c27ec8Sbaban 
61c5c4113dSnw141292 
62c5c4113dSnw141292 #define	EMPTY_NAME(name)	(*name == 0 || strcmp(name, "\"\"") == 0)
63c5c4113dSnw141292 
64c5c4113dSnw141292 #define	DO_NOT_ALLOC_NEW_ID_MAPPING(req)\
65c5c4113dSnw141292 		(req->flag & IDMAP_REQ_FLG_NO_NEW_ID_ALLOC)
66c5c4113dSnw141292 
67c5c4113dSnw141292 #define	AVOID_NAMESERVICE(req)\
68c5c4113dSnw141292 		(req->flag & IDMAP_REQ_FLG_NO_NAMESERVICE)
69c5c4113dSnw141292 
702b4a7802SBaban Kenkre #define	ALLOW_WK_OR_LOCAL_SIDS_ONLY(req)\
712b4a7802SBaban Kenkre 		(req->flag & IDMAP_REQ_FLG_WK_OR_LOCAL_SIDS_ONLY)
722b4a7802SBaban Kenkre 
73e8c27ec8Sbaban #define	IS_EPHEMERAL(pid)	(pid > INT32_MAX && pid != SENTINEL_PID)
74c5c4113dSnw141292 
75c5c4113dSnw141292 #define	LOCALRID_MIN	1000
76c5c4113dSnw141292 
77c5c4113dSnw141292 
78c5c4113dSnw141292 typedef enum init_db_option {
79c5c4113dSnw141292 	FAIL_IF_CORRUPT = 0,
80c5c4113dSnw141292 	REMOVE_IF_CORRUPT = 1
81c5c4113dSnw141292 } init_db_option_t;
82c5c4113dSnw141292 
8384decf41Sjp151216 /*
84e8c27ec8Sbaban  * Data structure to store well-known SIDs and
85e8c27ec8Sbaban  * associated mappings (if any)
86e8c27ec8Sbaban  */
87e8c27ec8Sbaban typedef struct wksids_table {
88e8c27ec8Sbaban 	const char	*sidprefix;
89e8c27ec8Sbaban 	uint32_t	rid;
90e8c27ec8Sbaban 	const char	*winname;
91e8c27ec8Sbaban 	int		is_wuser;
92e8c27ec8Sbaban 	uid_t		pid;
93e8c27ec8Sbaban 	int		is_user;
94e8c27ec8Sbaban 	int		direction;
95e8c27ec8Sbaban } wksids_table_t;
96e8c27ec8Sbaban 
97e8c27ec8Sbaban /*
9884decf41Sjp151216  * Thread specfic data to hold the database handles so that the
9984decf41Sjp151216  * databaes are not opened and closed for every request. It also
10084decf41Sjp151216  * contains the sqlite busy handler structure.
10184decf41Sjp151216  */
10284decf41Sjp151216 
10384decf41Sjp151216 struct idmap_busy {
10484decf41Sjp151216 	const char *name;
10584decf41Sjp151216 	const int *delays;
10684decf41Sjp151216 	int delay_size;
10784decf41Sjp151216 	int total;
10884decf41Sjp151216 	int sec;
10984decf41Sjp151216 };
11084decf41Sjp151216 
11184decf41Sjp151216 
11284decf41Sjp151216 typedef struct idmap_tsd {
11384decf41Sjp151216 	sqlite *db_db;
11484decf41Sjp151216 	sqlite *cache_db;
11584decf41Sjp151216 	struct idmap_busy cache_busy;
11684decf41Sjp151216 	struct idmap_busy db_busy;
11784decf41Sjp151216 } idmap_tsd_t;
11884decf41Sjp151216 
11984decf41Sjp151216 
12084decf41Sjp151216 
12184decf41Sjp151216 static const int cache_delay_table[] =
12284decf41Sjp151216 		{ 1, 2, 5, 10, 15, 20, 25, 30,  35,  40,
12384decf41Sjp151216 		50,  50, 60, 70, 80, 90, 100};
12484decf41Sjp151216 
12584decf41Sjp151216 static const int db_delay_table[] =
12684decf41Sjp151216 		{ 5, 10, 15, 20, 30,  40,  55,  70, 100};
12784decf41Sjp151216 
12884decf41Sjp151216 
12984decf41Sjp151216 static pthread_key_t	idmap_tsd_key;
13084decf41Sjp151216 
13184decf41Sjp151216 void
13284decf41Sjp151216 idmap_tsd_destroy(void *key)
13384decf41Sjp151216 {
13484decf41Sjp151216 
13584decf41Sjp151216 	idmap_tsd_t	*tsd = (idmap_tsd_t *)key;
13684decf41Sjp151216 	if (tsd) {
13784decf41Sjp151216 		if (tsd->db_db)
13884decf41Sjp151216 			(void) sqlite_close(tsd->db_db);
13984decf41Sjp151216 		if (tsd->cache_db)
14084decf41Sjp151216 			(void) sqlite_close(tsd->cache_db);
14184decf41Sjp151216 		free(tsd);
14284decf41Sjp151216 	}
14384decf41Sjp151216 }
14484decf41Sjp151216 
14584decf41Sjp151216 int
146cd37da74Snw141292 idmap_init_tsd_key(void)
147cd37da74Snw141292 {
14884decf41Sjp151216 	return (pthread_key_create(&idmap_tsd_key, idmap_tsd_destroy));
14984decf41Sjp151216 }
15084decf41Sjp151216 
15184decf41Sjp151216 
15284decf41Sjp151216 
15384decf41Sjp151216 idmap_tsd_t *
15484decf41Sjp151216 idmap_get_tsd(void)
15584decf41Sjp151216 {
15684decf41Sjp151216 	idmap_tsd_t	*tsd;
15784decf41Sjp151216 
15884decf41Sjp151216 	if ((tsd = pthread_getspecific(idmap_tsd_key)) == NULL) {
15984decf41Sjp151216 		/* No thread specific data so create it */
16084decf41Sjp151216 		if ((tsd = malloc(sizeof (*tsd))) != NULL) {
16184decf41Sjp151216 			/* Initialize thread specific data */
16284decf41Sjp151216 			(void) memset(tsd, 0, sizeof (*tsd));
16384decf41Sjp151216 			/* save the trhread specific data */
16484decf41Sjp151216 			if (pthread_setspecific(idmap_tsd_key, tsd) != 0) {
16584decf41Sjp151216 				/* Can't store key */
16684decf41Sjp151216 				free(tsd);
16784decf41Sjp151216 				tsd = NULL;
16884decf41Sjp151216 			}
16984decf41Sjp151216 		} else {
17084decf41Sjp151216 			tsd = NULL;
17184decf41Sjp151216 		}
17284decf41Sjp151216 	}
17384decf41Sjp151216 
17484decf41Sjp151216 	return (tsd);
17584decf41Sjp151216 }
17684decf41Sjp151216 
177cd37da74Snw141292 /*
178cd37da74Snw141292  * A simple wrapper around u8_textprep_str() that returns the Unicode
179cd37da74Snw141292  * lower-case version of some string.  The result must be freed.
180cd37da74Snw141292  */
181cd37da74Snw141292 char *
182cd37da74Snw141292 tolower_u8(const char *s)
183cd37da74Snw141292 {
184cd37da74Snw141292 	char *res = NULL;
185cd37da74Snw141292 	char *outs;
186cd37da74Snw141292 	size_t inlen, outlen, inbytesleft, outbytesleft;
187cd37da74Snw141292 	int rc, err;
188cd37da74Snw141292 
189cd37da74Snw141292 	/*
190cd37da74Snw141292 	 * u8_textprep_str() does not allocate memory.  The input and
191cd37da74Snw141292 	 * output buffers may differ in size (though that would be more
192cd37da74Snw141292 	 * likely when normalization is done).  We have to loop over it...
193cd37da74Snw141292 	 *
194cd37da74Snw141292 	 * To improve the chances that we can avoid looping we add 10
195cd37da74Snw141292 	 * bytes of output buffer room the first go around.
196cd37da74Snw141292 	 */
197cd37da74Snw141292 	inlen = inbytesleft = strlen(s);
198cd37da74Snw141292 	outlen = outbytesleft = inlen + 10;
199cd37da74Snw141292 	if ((res = malloc(outlen)) == NULL)
200cd37da74Snw141292 		return (NULL);
201cd37da74Snw141292 	outs = res;
202cd37da74Snw141292 
203cd37da74Snw141292 	while ((rc = u8_textprep_str((char *)s, &inbytesleft, outs,
204cd37da74Snw141292 	    &outbytesleft, U8_TEXTPREP_TOLOWER, U8_UNICODE_LATEST, &err)) < 0 &&
205cd37da74Snw141292 	    err == E2BIG) {
206cd37da74Snw141292 		if ((res = realloc(res, outlen + inbytesleft)) == NULL)
207cd37da74Snw141292 			return (NULL);
208cd37da74Snw141292 		/* adjust input/output buffer pointers */
209cd37da74Snw141292 		s += (inlen - inbytesleft);
210cd37da74Snw141292 		outs = res + outlen - outbytesleft;
211cd37da74Snw141292 		/* adjust outbytesleft and outlen */
212cd37da74Snw141292 		outlen += inbytesleft;
213cd37da74Snw141292 		outbytesleft += inbytesleft;
214cd37da74Snw141292 	}
215cd37da74Snw141292 
216cd37da74Snw141292 	if (rc < 0) {
217cd37da74Snw141292 		free(res);
218cd37da74Snw141292 		res = NULL;
219cd37da74Snw141292 		return (NULL);
220cd37da74Snw141292 	}
221cd37da74Snw141292 
222cd37da74Snw141292 	res[outlen - outbytesleft] = '\0';
223cd37da74Snw141292 
224cd37da74Snw141292 	return (res);
225cd37da74Snw141292 }
226cd37da74Snw141292 
227cd37da74Snw141292 static int sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
228cd37da74Snw141292 	const char *while_doing);
229cd37da74Snw141292 
230c5c4113dSnw141292 
231c5c4113dSnw141292 /*
232c5c4113dSnw141292  * Initialize 'dbname' using 'sql'
233c5c4113dSnw141292  */
234cd37da74Snw141292 static
235cd37da74Snw141292 int
236cd37da74Snw141292 init_db_instance(const char *dbname, int version,
237cd37da74Snw141292 	const char *detect_version_sql, char * const *sql,
238cd37da74Snw141292 	init_db_option_t opt, int *created, int *upgraded)
239c5c4113dSnw141292 {
240cd37da74Snw141292 	int rc, curr_version;
241cd37da74Snw141292 	int tries = 1;
242cd37da74Snw141292 	int prio = LOG_NOTICE;
243c5c4113dSnw141292 	sqlite *db = NULL;
244cd37da74Snw141292 	char *errmsg = NULL;
245c5c4113dSnw141292 
246cd37da74Snw141292 	*created = 0;
247cd37da74Snw141292 	*upgraded = 0;
248c5c4113dSnw141292 
249cd37da74Snw141292 	if (opt == REMOVE_IF_CORRUPT)
250cd37da74Snw141292 		tries = 3;
251cd37da74Snw141292 
252cd37da74Snw141292 rinse_repeat:
253cd37da74Snw141292 	if (tries == 0) {
254cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to initialize db %s", dbname);
255c5c4113dSnw141292 		return (-1);
256cd37da74Snw141292 	}
257cd37da74Snw141292 	if (tries-- == 1)
258cd37da74Snw141292 		/* Last try, log errors */
259cd37da74Snw141292 		prio = LOG_ERR;
260c5c4113dSnw141292 
261cd37da74Snw141292 	db = sqlite_open(dbname, 0600, &errmsg);
262cd37da74Snw141292 	if (db == NULL) {
263cd37da74Snw141292 		idmapdlog(prio, "Error creating database %s (%s)",
264cd37da74Snw141292 		    dbname, CHECK_NULL(errmsg));
265cd37da74Snw141292 		sqlite_freemem(errmsg);
266cd37da74Snw141292 		if (opt == REMOVE_IF_CORRUPT)
267c5c4113dSnw141292 			(void) unlink(dbname);
268cd37da74Snw141292 		goto rinse_repeat;
269c5c4113dSnw141292 	}
270c5c4113dSnw141292 
271c5c4113dSnw141292 	sqlite_busy_timeout(db, 3000);
272cd37da74Snw141292 
273cd37da74Snw141292 	/* Detect current version of schema in the db, if any */
274cd37da74Snw141292 	curr_version = 0;
275cd37da74Snw141292 	if (detect_version_sql != NULL) {
276cd37da74Snw141292 		char *end, **results;
277cd37da74Snw141292 		int nrow;
278cd37da74Snw141292 
279cd37da74Snw141292 #ifdef	IDMAPD_DEBUG
280cd37da74Snw141292 		(void) fprintf(stderr, "Schema version detection SQL: %s\n",
281cd37da74Snw141292 		    detect_version_sql);
282cd37da74Snw141292 #endif	/* IDMAPD_DEBUG */
283cd37da74Snw141292 		rc = sqlite_get_table(db, detect_version_sql, &results,
284cd37da74Snw141292 		    &nrow, NULL, &errmsg);
285cd37da74Snw141292 		if (rc != SQLITE_OK) {
286cd37da74Snw141292 			idmapdlog(prio,
287cd37da74Snw141292 			    "Error detecting schema version of db %s (%s)",
288cd37da74Snw141292 			    dbname, errmsg);
289cd37da74Snw141292 			sqlite_freemem(errmsg);
290cd37da74Snw141292 			sqlite_free_table(results);
291c5c4113dSnw141292 			sqlite_close(db);
292cd37da74Snw141292 			return (-1);
293cd37da74Snw141292 		}
294cd37da74Snw141292 		if (nrow != 1) {
295cd37da74Snw141292 			idmapdlog(prio,
296cd37da74Snw141292 			    "Error detecting schema version of db %s", dbname);
297cd37da74Snw141292 			sqlite_close(db);
298cd37da74Snw141292 			sqlite_free_table(results);
299cd37da74Snw141292 			return (-1);
300cd37da74Snw141292 		}
301cd37da74Snw141292 		curr_version = strtol(results[1], &end, 10);
302cd37da74Snw141292 		sqlite_free_table(results);
303c5c4113dSnw141292 	}
304c5c4113dSnw141292 
305cd37da74Snw141292 	if (curr_version < 0) {
306cd37da74Snw141292 		if (opt == REMOVE_IF_CORRUPT)
307cd37da74Snw141292 			(void) unlink(dbname);
308cd37da74Snw141292 		goto rinse_repeat;
309c5c4113dSnw141292 	}
310c5c4113dSnw141292 
311cd37da74Snw141292 	if (curr_version == version)
312cd37da74Snw141292 		goto done;
313cd37da74Snw141292 
314cd37da74Snw141292 	/* Install or upgrade schema */
315cd37da74Snw141292 #ifdef	IDMAPD_DEBUG
316cd37da74Snw141292 	(void) fprintf(stderr, "Schema init/upgrade SQL: %s\n",
317cd37da74Snw141292 	    sql[curr_version]);
318cd37da74Snw141292 #endif	/* IDMAPD_DEBUG */
319cd37da74Snw141292 	rc = sql_exec_tran_no_cb(db, sql[curr_version], dbname,
320cd37da74Snw141292 	    (curr_version == 0) ? "installing schema" : "upgrading schema");
321cd37da74Snw141292 	if (rc != 0) {
322cd37da74Snw141292 		idmapdlog(prio, "Error %s schema for db %s", dbname,
323cd37da74Snw141292 		    (curr_version == 0) ? "installing schema" :
324cd37da74Snw141292 		    "upgrading schema");
325cd37da74Snw141292 		if (opt == REMOVE_IF_CORRUPT)
326cd37da74Snw141292 			(void) unlink(dbname);
327cd37da74Snw141292 		goto rinse_repeat;
328c5c4113dSnw141292 	}
329c5c4113dSnw141292 
330cd37da74Snw141292 	*upgraded = (curr_version > 0);
331cd37da74Snw141292 	*created = (curr_version == 0);
332cd37da74Snw141292 
333cd37da74Snw141292 done:
334c5c4113dSnw141292 	(void) sqlite_close(db);
335cd37da74Snw141292 	return (0);
336c5c4113dSnw141292 }
337c5c4113dSnw141292 
33884decf41Sjp151216 
33984decf41Sjp151216 /*
34084decf41Sjp151216  * This is the SQLite database busy handler that retries the SQL
34184decf41Sjp151216  * operation until it is successful.
34284decf41Sjp151216  */
34384decf41Sjp151216 int
34484decf41Sjp151216 /* LINTED E_FUNC_ARG_UNUSED */
34584decf41Sjp151216 idmap_sqlite_busy_handler(void *arg, const char *table_name, int count)
34684decf41Sjp151216 {
34784decf41Sjp151216 	struct idmap_busy	*busy = arg;
34884decf41Sjp151216 	int			delay;
34984decf41Sjp151216 	struct timespec		rqtp;
35084decf41Sjp151216 
35184decf41Sjp151216 	if (count == 1)  {
35284decf41Sjp151216 		busy->total = 0;
35384decf41Sjp151216 		busy->sec = 2;
35484decf41Sjp151216 	}
35584decf41Sjp151216 	if (busy->total > 1000 * busy->sec) {
3562b3ecdebSjp151216 		idmapdlog(LOG_DEBUG,
35784decf41Sjp151216 		    "Thread %d waited %d sec for the %s database",
35884decf41Sjp151216 		    pthread_self(), busy->sec, busy->name);
35984decf41Sjp151216 		busy->sec++;
36084decf41Sjp151216 	}
36184decf41Sjp151216 
36284decf41Sjp151216 	if (count <= busy->delay_size) {
36384decf41Sjp151216 		delay = busy->delays[count-1];
36484decf41Sjp151216 	} else {
36584decf41Sjp151216 		delay = busy->delays[busy->delay_size - 1];
36684decf41Sjp151216 	}
36784decf41Sjp151216 	busy->total += delay;
36884decf41Sjp151216 	rqtp.tv_sec = 0;
36984decf41Sjp151216 	rqtp.tv_nsec = delay * (NANOSEC / MILLISEC);
37084decf41Sjp151216 	(void) nanosleep(&rqtp, NULL);
37184decf41Sjp151216 	return (1);
37284decf41Sjp151216 }
37384decf41Sjp151216 
37484decf41Sjp151216 
375c5c4113dSnw141292 /*
376c5c4113dSnw141292  * Get the database handle
377c5c4113dSnw141292  */
378c5c4113dSnw141292 idmap_retcode
379cd37da74Snw141292 get_db_handle(sqlite **db)
380cd37da74Snw141292 {
381c5c4113dSnw141292 	char		*errmsg;
38284decf41Sjp151216 	idmap_tsd_t	*tsd;
383c5c4113dSnw141292 
384c5c4113dSnw141292 	/*
38584decf41Sjp151216 	 * Retrieve the db handle from thread-specific storage
386c5c4113dSnw141292 	 * If none exists, open and store in thread-specific storage.
387c5c4113dSnw141292 	 */
38884decf41Sjp151216 	if ((tsd = idmap_get_tsd()) == NULL) {
38984decf41Sjp151216 		idmapdlog(LOG_ERR,
390cd37da74Snw141292 		    "Error getting thread specific data for %s", IDMAP_DBNAME);
39184decf41Sjp151216 		return (IDMAP_ERR_MEMORY);
39284decf41Sjp151216 	}
393c5c4113dSnw141292 
39484decf41Sjp151216 	if (tsd->db_db == NULL) {
39584decf41Sjp151216 		tsd->db_db = sqlite_open(IDMAP_DBNAME, 0, &errmsg);
39684decf41Sjp151216 		if (tsd->db_db == NULL) {
397cd37da74Snw141292 			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
398c5c4113dSnw141292 			    IDMAP_DBNAME, CHECK_NULL(errmsg));
399c5c4113dSnw141292 			sqlite_freemem(errmsg);
400cd37da74Snw141292 			return (IDMAP_ERR_DB);
401c5c4113dSnw141292 		}
402cd37da74Snw141292 
40384decf41Sjp151216 		tsd->db_busy.name = IDMAP_DBNAME;
40484decf41Sjp151216 		tsd->db_busy.delays = db_delay_table;
40584decf41Sjp151216 		tsd->db_busy.delay_size = sizeof (db_delay_table) /
40684decf41Sjp151216 		    sizeof (int);
40784decf41Sjp151216 		sqlite_busy_handler(tsd->db_db, idmap_sqlite_busy_handler,
40884decf41Sjp151216 		    &tsd->db_busy);
40984decf41Sjp151216 	}
41084decf41Sjp151216 	*db = tsd->db_db;
411c5c4113dSnw141292 	return (IDMAP_SUCCESS);
412c5c4113dSnw141292 }
413c5c4113dSnw141292 
414c5c4113dSnw141292 /*
415c5c4113dSnw141292  * Get the cache handle
416c5c4113dSnw141292  */
417c5c4113dSnw141292 idmap_retcode
418cd37da74Snw141292 get_cache_handle(sqlite **cache)
419cd37da74Snw141292 {
420c5c4113dSnw141292 	char		*errmsg;
42184decf41Sjp151216 	idmap_tsd_t	*tsd;
422c5c4113dSnw141292 
423c5c4113dSnw141292 	/*
42484decf41Sjp151216 	 * Retrieve the db handle from thread-specific storage
425c5c4113dSnw141292 	 * If none exists, open and store in thread-specific storage.
426c5c4113dSnw141292 	 */
42784decf41Sjp151216 	if ((tsd = idmap_get_tsd()) == NULL) {
428cd37da74Snw141292 		idmapdlog(LOG_ERR, "Error getting thread specific data for %s",
42984decf41Sjp151216 		    IDMAP_DBNAME);
43084decf41Sjp151216 		return (IDMAP_ERR_MEMORY);
43184decf41Sjp151216 	}
432c5c4113dSnw141292 
43384decf41Sjp151216 	if (tsd->cache_db == NULL) {
43484decf41Sjp151216 		tsd->cache_db = sqlite_open(IDMAP_CACHENAME, 0, &errmsg);
43584decf41Sjp151216 		if (tsd->cache_db == NULL) {
436cd37da74Snw141292 			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
437c5c4113dSnw141292 			    IDMAP_CACHENAME, CHECK_NULL(errmsg));
438c5c4113dSnw141292 			sqlite_freemem(errmsg);
439cd37da74Snw141292 			return (IDMAP_ERR_DB);
440c5c4113dSnw141292 		}
441cd37da74Snw141292 
44284decf41Sjp151216 		tsd->cache_busy.name = IDMAP_CACHENAME;
44384decf41Sjp151216 		tsd->cache_busy.delays = cache_delay_table;
44484decf41Sjp151216 		tsd->cache_busy.delay_size = sizeof (cache_delay_table) /
44584decf41Sjp151216 		    sizeof (int);
44684decf41Sjp151216 		sqlite_busy_handler(tsd->cache_db, idmap_sqlite_busy_handler,
44784decf41Sjp151216 		    &tsd->cache_busy);
44884decf41Sjp151216 	}
44984decf41Sjp151216 	*cache = tsd->cache_db;
450c5c4113dSnw141292 	return (IDMAP_SUCCESS);
451c5c4113dSnw141292 }
452c5c4113dSnw141292 
453c5c4113dSnw141292 /*
454c5c4113dSnw141292  * Initialize cache and db
455c5c4113dSnw141292  */
456c5c4113dSnw141292 int
457cd37da74Snw141292 init_dbs()
458cd37da74Snw141292 {
45948258c6bSjp151216 	char *sql[4];
460cd37da74Snw141292 	int created, upgraded;
461cd37da74Snw141292 
462c5c4113dSnw141292 	/* name-based mappings; probably OK to blow away in a pinch(?) */
463cd37da74Snw141292 	sql[0] = DB_INSTALL_SQL;
464cd37da74Snw141292 	sql[1] = DB_UPGRADE_FROM_v1_SQL;
46548258c6bSjp151216 	sql[2] = NULL;
466cd37da74Snw141292 
467cd37da74Snw141292 	if (init_db_instance(IDMAP_DBNAME, DB_VERSION, DB_VERSION_SQL, sql,
468cd37da74Snw141292 	    FAIL_IF_CORRUPT, &created, &upgraded) < 0)
469c5c4113dSnw141292 		return (-1);
470c5c4113dSnw141292 
471c5c4113dSnw141292 	/* mappings, name/SID lookup cache + ephemeral IDs; OK to blow away */
472cd37da74Snw141292 	sql[0] = CACHE_INSTALL_SQL;
473cd37da74Snw141292 	sql[1] = CACHE_UPGRADE_FROM_v1_SQL;
47448258c6bSjp151216 	sql[2] = CACHE_UPGRADE_FROM_v2_SQL;
47548258c6bSjp151216 	sql[3] = NULL;
47648258c6bSjp151216 
477cd37da74Snw141292 	if (init_db_instance(IDMAP_CACHENAME, CACHE_VERSION, CACHE_VERSION_SQL,
478cd37da74Snw141292 	    sql, REMOVE_IF_CORRUPT, &created, &upgraded) < 0)
479c5c4113dSnw141292 		return (-1);
480c5c4113dSnw141292 
481cd37da74Snw141292 	_idmapdstate.new_eph_db = (created || upgraded) ? 1 : 0;
482cd37da74Snw141292 
483c5c4113dSnw141292 	return (0);
484c5c4113dSnw141292 }
485c5c4113dSnw141292 
486c5c4113dSnw141292 /*
487c5c4113dSnw141292  * Finalize databases
488c5c4113dSnw141292  */
489c5c4113dSnw141292 void
490cd37da74Snw141292 fini_dbs()
491cd37da74Snw141292 {
492c5c4113dSnw141292 }
493c5c4113dSnw141292 
494c5c4113dSnw141292 /*
495e8c27ec8Sbaban  * This table is a listing of status codes that will be returned to the
496c5c4113dSnw141292  * client when a SQL command fails with the corresponding error message.
497c5c4113dSnw141292  */
498c5c4113dSnw141292 static msg_table_t sqlmsgtable[] = {
49962c60062Sbaban 	{IDMAP_ERR_U2W_NAMERULE_CONFLICT,
500c5c4113dSnw141292 	"columns unixname, is_user, u2w_order are not unique"},
50162c60062Sbaban 	{IDMAP_ERR_W2U_NAMERULE_CONFLICT,
502cd37da74Snw141292 	"columns winname, windomain, is_user, is_wuser, w2u_order are not"
503cd37da74Snw141292 	" unique"},
504cd37da74Snw141292 	{IDMAP_ERR_W2U_NAMERULE_CONFLICT, "Conflicting w2u namerules"},
505c5c4113dSnw141292 	{-1, NULL}
506c5c4113dSnw141292 };
507c5c4113dSnw141292 
508c5c4113dSnw141292 /*
509c5c4113dSnw141292  * idmapd's version of string2stat to map SQLite messages to
510c5c4113dSnw141292  * status codes
511c5c4113dSnw141292  */
512c5c4113dSnw141292 idmap_retcode
513cd37da74Snw141292 idmapd_string2stat(const char *msg)
514cd37da74Snw141292 {
515c5c4113dSnw141292 	int i;
516c5c4113dSnw141292 	for (i = 0; sqlmsgtable[i].msg; i++) {
517c5c4113dSnw141292 		if (strcasecmp(sqlmsgtable[i].msg, msg) == 0)
518c5c4113dSnw141292 			return (sqlmsgtable[i].retcode);
519c5c4113dSnw141292 	}
520c5c4113dSnw141292 	return (IDMAP_ERR_OTHER);
521c5c4113dSnw141292 }
522c5c4113dSnw141292 
523c5c4113dSnw141292 /*
524cd37da74Snw141292  * Executes some SQL in a transaction.
525cd37da74Snw141292  *
526cd37da74Snw141292  * Returns 0 on success, -1 if it failed but the rollback succeeded, -2
527cd37da74Snw141292  * if the rollback failed.
528cd37da74Snw141292  */
529cd37da74Snw141292 static
530cd37da74Snw141292 int
531cd37da74Snw141292 sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
532cd37da74Snw141292 	const char *while_doing)
533cd37da74Snw141292 {
534cd37da74Snw141292 	char		*errmsg = NULL;
535cd37da74Snw141292 	int		rc;
536cd37da74Snw141292 
537cd37da74Snw141292 	rc = sqlite_exec(db, "BEGIN TRANSACTION;", NULL, NULL, &errmsg);
538cd37da74Snw141292 	if (rc != SQLITE_OK) {
539cd37da74Snw141292 		idmapdlog(LOG_ERR, "Begin transaction failed (%s) "
540cd37da74Snw141292 		    "while %s (%s)", errmsg, while_doing, dbname);
541cd37da74Snw141292 		sqlite_freemem(errmsg);
542cd37da74Snw141292 		return (-1);
543cd37da74Snw141292 	}
544cd37da74Snw141292 
545cd37da74Snw141292 	rc = sqlite_exec(db, sql, NULL, NULL, &errmsg);
546cd37da74Snw141292 	if (rc != SQLITE_OK) {
547cd37da74Snw141292 		idmapdlog(LOG_ERR, "Database error (%s) while %s (%s)", errmsg,
548cd37da74Snw141292 		    while_doing, dbname);
549cd37da74Snw141292 		sqlite_freemem(errmsg);
550cd37da74Snw141292 		errmsg = NULL;
551cd37da74Snw141292 		goto rollback;
552cd37da74Snw141292 	}
553cd37da74Snw141292 
554cd37da74Snw141292 	rc = sqlite_exec(db, "COMMIT TRANSACTION", NULL, NULL, &errmsg);
555cd37da74Snw141292 	if (rc == SQLITE_OK) {
556cd37da74Snw141292 		sqlite_freemem(errmsg);
557cd37da74Snw141292 		return (0);
558cd37da74Snw141292 	}
559cd37da74Snw141292 
560cd37da74Snw141292 	idmapdlog(LOG_ERR, "Database commit error (%s) while s (%s)",
561cd37da74Snw141292 	    errmsg, while_doing, dbname);
562cd37da74Snw141292 	sqlite_freemem(errmsg);
563cd37da74Snw141292 	errmsg = NULL;
564cd37da74Snw141292 
565cd37da74Snw141292 rollback:
566cd37da74Snw141292 	rc = sqlite_exec(db, "ROLLBACK TRANSACTION", NULL, NULL, &errmsg);
567cd37da74Snw141292 	if (rc != SQLITE_OK) {
568cd37da74Snw141292 		idmapdlog(LOG_ERR, "Rollback failed (%s) while %s (%s)",
569cd37da74Snw141292 		    errmsg, while_doing, dbname);
570cd37da74Snw141292 		sqlite_freemem(errmsg);
571cd37da74Snw141292 		return (-2);
572cd37da74Snw141292 	}
573cd37da74Snw141292 	sqlite_freemem(errmsg);
574cd37da74Snw141292 
575cd37da74Snw141292 	return (-1);
576cd37da74Snw141292 }
577cd37da74Snw141292 
578cd37da74Snw141292 /*
579c5c4113dSnw141292  * Execute the given SQL statment without using any callbacks
580c5c4113dSnw141292  */
581c5c4113dSnw141292 idmap_retcode
58271590c90Snw141292 sql_exec_no_cb(sqlite *db, const char *dbname, char *sql)
583cd37da74Snw141292 {
584c5c4113dSnw141292 	char		*errmsg = NULL;
58584decf41Sjp151216 	int		r;
586c5c4113dSnw141292 	idmap_retcode	retcode;
587c5c4113dSnw141292 
588c5c4113dSnw141292 	r = sqlite_exec(db, sql, NULL, NULL, &errmsg);
58984decf41Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
590c5c4113dSnw141292 
591c5c4113dSnw141292 	if (r != SQLITE_OK) {
59271590c90Snw141292 		idmapdlog(LOG_ERR, "Database error on %s while executing %s "
59371590c90Snw141292 		    "(%s)", dbname, sql, CHECK_NULL(errmsg));
594c5c4113dSnw141292 		retcode = idmapd_string2stat(errmsg);
59562c60062Sbaban 		if (errmsg != NULL)
596c5c4113dSnw141292 			sqlite_freemem(errmsg);
597c5c4113dSnw141292 		return (retcode);
598c5c4113dSnw141292 	}
599c5c4113dSnw141292 
600c5c4113dSnw141292 	return (IDMAP_SUCCESS);
601c5c4113dSnw141292 }
602c5c4113dSnw141292 
603c5c4113dSnw141292 /*
604c5c4113dSnw141292  * Generate expression that can be used in WHERE statements.
605c5c4113dSnw141292  * Examples:
606c5c4113dSnw141292  * <prefix> <col>      <op> <value>   <suffix>
607c5c4113dSnw141292  * ""       "unixuser" "="  "foo" "AND"
608c5c4113dSnw141292  */
609c5c4113dSnw141292 idmap_retcode
610cd37da74Snw141292 gen_sql_expr_from_rule(idmap_namerule *rule, char **out)
611cd37da74Snw141292 {
612cd37da74Snw141292 	char	*s_windomain = NULL, *s_winname = NULL;
613cd37da74Snw141292 	char	*s_unixname = NULL;
614cd37da74Snw141292 	char	*lower_winname;
615cd37da74Snw141292 	int	retcode = IDMAP_SUCCESS;
616cd37da74Snw141292 
617c5c4113dSnw141292 	if (out == NULL)
618c5c4113dSnw141292 		return (IDMAP_ERR_ARG);
619c5c4113dSnw141292 
620c5c4113dSnw141292 
621cd37da74Snw141292 	if (!EMPTY_STRING(rule->windomain)) {
622cd37da74Snw141292 		s_windomain =  sqlite_mprintf("AND windomain = %Q ",
623cd37da74Snw141292 		    rule->windomain);
624cd37da74Snw141292 		if (s_windomain == NULL) {
625cd37da74Snw141292 			retcode = IDMAP_ERR_MEMORY;
626cd37da74Snw141292 			goto out;
627c5c4113dSnw141292 		}
628cd37da74Snw141292 	}
629cd37da74Snw141292 
630cd37da74Snw141292 	if (!EMPTY_STRING(rule->winname)) {
631cd37da74Snw141292 		if ((lower_winname = tolower_u8(rule->winname)) == NULL)
632cd37da74Snw141292 			lower_winname = rule->winname;
633cd37da74Snw141292 		s_winname = sqlite_mprintf(
634cd37da74Snw141292 		    "AND winname = %Q AND is_wuser = %d ",
635cd37da74Snw141292 		    lower_winname, rule->is_wuser ? 1 : 0);
636cd37da74Snw141292 		if (lower_winname != rule->winname)
637cd37da74Snw141292 			free(lower_winname);
638cd37da74Snw141292 		if (s_winname == NULL) {
639cd37da74Snw141292 			retcode = IDMAP_ERR_MEMORY;
640cd37da74Snw141292 			goto out;
641cd37da74Snw141292 		}
642cd37da74Snw141292 	}
643cd37da74Snw141292 
644cd37da74Snw141292 	if (!EMPTY_STRING(rule->unixname)) {
645cd37da74Snw141292 		s_unixname = sqlite_mprintf(
646cd37da74Snw141292 		    "AND unixname = %Q AND is_user = %d ",
647cd37da74Snw141292 		    rule->unixname, rule->is_user ? 1 : 0);
648cd37da74Snw141292 		if (s_unixname == NULL) {
649cd37da74Snw141292 			retcode = IDMAP_ERR_MEMORY;
650cd37da74Snw141292 			goto out;
651cd37da74Snw141292 		}
652cd37da74Snw141292 	}
653cd37da74Snw141292 
654cd37da74Snw141292 	*out = sqlite_mprintf("%s %s %s",
655cd37da74Snw141292 	    s_windomain ? s_windomain : "",
656cd37da74Snw141292 	    s_winname ? s_winname : "",
657cd37da74Snw141292 	    s_unixname ? s_unixname : "");
658cd37da74Snw141292 
659cd37da74Snw141292 	if (*out == NULL) {
660cd37da74Snw141292 		retcode = IDMAP_ERR_MEMORY;
661cd37da74Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
662cd37da74Snw141292 		goto out;
663cd37da74Snw141292 	}
664cd37da74Snw141292 
665cd37da74Snw141292 out:
666cd37da74Snw141292 	if (s_windomain != NULL)
667cd37da74Snw141292 		sqlite_freemem(s_windomain);
668cd37da74Snw141292 	if (s_winname != NULL)
669cd37da74Snw141292 		sqlite_freemem(s_winname);
670cd37da74Snw141292 	if (s_unixname != NULL)
671cd37da74Snw141292 		sqlite_freemem(s_unixname);
672cd37da74Snw141292 
673cd37da74Snw141292 	return (retcode);
674cd37da74Snw141292 }
675cd37da74Snw141292 
676cd37da74Snw141292 
677c5c4113dSnw141292 
678c5c4113dSnw141292 /*
679c5c4113dSnw141292  * Generate and execute SQL statement for LIST RPC calls
680c5c4113dSnw141292  */
681c5c4113dSnw141292 idmap_retcode
68271590c90Snw141292 process_list_svc_sql(sqlite *db, const char *dbname, char *sql, uint64_t limit,
68348258c6bSjp151216 		int flag, list_svc_cb cb, void *result)
684cd37da74Snw141292 {
685c5c4113dSnw141292 	list_cb_data_t	cb_data;
686c5c4113dSnw141292 	char		*errmsg = NULL;
68784decf41Sjp151216 	int		r;
688c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_ERR_INTERNAL;
689c5c4113dSnw141292 
690c5c4113dSnw141292 	(void) memset(&cb_data, 0, sizeof (cb_data));
691c5c4113dSnw141292 	cb_data.result = result;
692c5c4113dSnw141292 	cb_data.limit = limit;
69348258c6bSjp151216 	cb_data.flag = flag;
694c5c4113dSnw141292 
69584decf41Sjp151216 
696c5c4113dSnw141292 	r = sqlite_exec(db, sql, cb, &cb_data, &errmsg);
69784decf41Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
698c5c4113dSnw141292 	switch (r) {
699c5c4113dSnw141292 	case SQLITE_OK:
700c5c4113dSnw141292 		retcode = IDMAP_SUCCESS;
70184decf41Sjp151216 		break;
70284decf41Sjp151216 
703c5c4113dSnw141292 	default:
704c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
70571590c90Snw141292 		idmapdlog(LOG_ERR, "Database error on %s while executing "
70671590c90Snw141292 		    "%s (%s)", dbname, sql, CHECK_NULL(errmsg));
70784decf41Sjp151216 		break;
708c5c4113dSnw141292 	}
70962c60062Sbaban 	if (errmsg != NULL)
710c5c4113dSnw141292 		sqlite_freemem(errmsg);
711c5c4113dSnw141292 	return (retcode);
712c5c4113dSnw141292 }
713c5c4113dSnw141292 
714c5c4113dSnw141292 /*
715c5c4113dSnw141292  * This routine is called by callbacks that process the results of
716c5c4113dSnw141292  * LIST RPC calls to validate data and to allocate memory for
717c5c4113dSnw141292  * the result array.
718c5c4113dSnw141292  */
719c5c4113dSnw141292 idmap_retcode
720c5c4113dSnw141292 validate_list_cb_data(list_cb_data_t *cb_data, int argc, char **argv,
721cd37da74Snw141292 		int ncol, uchar_t **list, size_t valsize)
722cd37da74Snw141292 {
723c5c4113dSnw141292 	size_t	nsize;
724c5c4113dSnw141292 	void	*tmplist;
725c5c4113dSnw141292 
726c5c4113dSnw141292 	if (cb_data->limit > 0 && cb_data->next == cb_data->limit)
727c5c4113dSnw141292 		return (IDMAP_NEXT);
728c5c4113dSnw141292 
729c5c4113dSnw141292 	if (argc < ncol || argv == NULL) {
730c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Invalid data");
731c5c4113dSnw141292 		return (IDMAP_ERR_INTERNAL);
732c5c4113dSnw141292 	}
733c5c4113dSnw141292 
734c5c4113dSnw141292 	/* alloc in bulk to reduce number of reallocs */
735c5c4113dSnw141292 	if (cb_data->next >= cb_data->len) {
736c5c4113dSnw141292 		nsize = (cb_data->len + SIZE_INCR) * valsize;
737c5c4113dSnw141292 		tmplist = realloc(*list, nsize);
738c5c4113dSnw141292 		if (tmplist == NULL) {
739c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
740c5c4113dSnw141292 			return (IDMAP_ERR_MEMORY);
741c5c4113dSnw141292 		}
742c5c4113dSnw141292 		*list = tmplist;
743c5c4113dSnw141292 		(void) memset(*list + (cb_data->len * valsize), 0,
744c5c4113dSnw141292 		    SIZE_INCR * valsize);
745c5c4113dSnw141292 		cb_data->len += SIZE_INCR;
746c5c4113dSnw141292 	}
747c5c4113dSnw141292 	return (IDMAP_SUCCESS);
748c5c4113dSnw141292 }
749c5c4113dSnw141292 
750cd37da74Snw141292 static
751cd37da74Snw141292 idmap_retcode
752c5c4113dSnw141292 get_namerule_order(char *winname, char *windomain, char *unixname,
753cd37da74Snw141292 	int direction, int is_diagonal, int *w2u_order, int *u2w_order)
754cd37da74Snw141292 {
755c5c4113dSnw141292 	*w2u_order = 0;
756c5c4113dSnw141292 	*u2w_order = 0;
757c5c4113dSnw141292 
758c5c4113dSnw141292 	/*
759c5c4113dSnw141292 	 * Windows to UNIX lookup order:
760c5c4113dSnw141292 	 *  1. winname@domain (or winname) to ""
761c5c4113dSnw141292 	 *  2. winname@domain (or winname) to unixname
762c5c4113dSnw141292 	 *  3. winname@* to ""
763c5c4113dSnw141292 	 *  4. winname@* to unixname
764c5c4113dSnw141292 	 *  5. *@domain (or *) to *
765c5c4113dSnw141292 	 *  6. *@domain (or *) to ""
766c5c4113dSnw141292 	 *  7. *@domain (or *) to unixname
767c5c4113dSnw141292 	 *  8. *@* to *
768c5c4113dSnw141292 	 *  9. *@* to ""
769c5c4113dSnw141292 	 * 10. *@* to unixname
770c5c4113dSnw141292 	 *
771c5c4113dSnw141292 	 * winname is a special case of winname@domain when domain is the
772c5c4113dSnw141292 	 * default domain. Similarly * is a special case of *@domain when
773c5c4113dSnw141292 	 * domain is the default domain.
774c5c4113dSnw141292 	 *
775c5c4113dSnw141292 	 * Note that "" has priority over specific names because "" inhibits
776c5c4113dSnw141292 	 * mappings and traditionally deny rules always had higher priority.
777c5c4113dSnw141292 	 */
778651c0131Sbaban 	if (direction != IDMAP_DIRECTION_U2W) {
779651c0131Sbaban 		/* bi-directional or from windows to unix */
780c5c4113dSnw141292 		if (winname == NULL)
781c5c4113dSnw141292 			return (IDMAP_ERR_W2U_NAMERULE);
782c5c4113dSnw141292 		else if (unixname == NULL)
783c5c4113dSnw141292 			return (IDMAP_ERR_W2U_NAMERULE);
784c5c4113dSnw141292 		else if (EMPTY_NAME(winname))
785c5c4113dSnw141292 			return (IDMAP_ERR_W2U_NAMERULE);
786c5c4113dSnw141292 		else if (*winname == '*' && windomain && *windomain == '*') {
787c5c4113dSnw141292 			if (*unixname == '*')
788c5c4113dSnw141292 				*w2u_order = 8;
789c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
790c5c4113dSnw141292 				*w2u_order = 9;
791c5c4113dSnw141292 			else /* unixname == name */
792c5c4113dSnw141292 				*w2u_order = 10;
793c5c4113dSnw141292 		} else if (*winname == '*') {
794c5c4113dSnw141292 			if (*unixname == '*')
795c5c4113dSnw141292 				*w2u_order = 5;
796c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
797c5c4113dSnw141292 				*w2u_order = 6;
798c5c4113dSnw141292 			else /* name */
799c5c4113dSnw141292 				*w2u_order = 7;
80062c60062Sbaban 		} else if (windomain != NULL && *windomain == '*') {
801c5c4113dSnw141292 			/* winname == name */
802c5c4113dSnw141292 			if (*unixname == '*')
803c5c4113dSnw141292 				return (IDMAP_ERR_W2U_NAMERULE);
804c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
805c5c4113dSnw141292 				*w2u_order = 3;
806c5c4113dSnw141292 			else /* name */
807c5c4113dSnw141292 				*w2u_order = 4;
808c5c4113dSnw141292 		} else  {
809c5c4113dSnw141292 			/* winname == name && windomain == null or name */
810c5c4113dSnw141292 			if (*unixname == '*')
811c5c4113dSnw141292 				return (IDMAP_ERR_W2U_NAMERULE);
812c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
813c5c4113dSnw141292 				*w2u_order = 1;
814c5c4113dSnw141292 			else /* name */
815c5c4113dSnw141292 				*w2u_order = 2;
816c5c4113dSnw141292 		}
817cd37da74Snw141292 
818c5c4113dSnw141292 	}
819c5c4113dSnw141292 
820c5c4113dSnw141292 	/*
821cd37da74Snw141292 	 * 1. unixname to "", non-diagonal
822cd37da74Snw141292 	 * 2. unixname to winname@domain (or winname), non-diagonal
823cd37da74Snw141292 	 * 3. unixname to "", diagonal
824cd37da74Snw141292 	 * 4. unixname to winname@domain (or winname), diagonal
825cd37da74Snw141292 	 * 5. * to *@domain (or *), non-diagonal
826cd37da74Snw141292 	 * 5. * to *@domain (or *), diagonal
827cd37da74Snw141292 	 * 7. * to ""
828cd37da74Snw141292 	 * 8. * to winname@domain (or winname)
829cd37da74Snw141292 	 * 9. * to "", non-diagonal
830cd37da74Snw141292 	 * 10. * to winname@domain (or winname), diagonal
831c5c4113dSnw141292 	 */
832651c0131Sbaban 	if (direction != IDMAP_DIRECTION_W2U) {
833cd37da74Snw141292 		int diagonal = is_diagonal ? 1 : 0;
834cd37da74Snw141292 
835651c0131Sbaban 		/* bi-directional or from unix to windows */
836c5c4113dSnw141292 		if (unixname == NULL || EMPTY_NAME(unixname))
837c5c4113dSnw141292 			return (IDMAP_ERR_U2W_NAMERULE);
838c5c4113dSnw141292 		else if (winname == NULL)
839c5c4113dSnw141292 			return (IDMAP_ERR_U2W_NAMERULE);
84062c60062Sbaban 		else if (windomain != NULL && *windomain == '*')
841651c0131Sbaban 			return (IDMAP_ERR_U2W_NAMERULE);
842c5c4113dSnw141292 		else if (*unixname == '*') {
843c5c4113dSnw141292 			if (*winname == '*')
844cd37da74Snw141292 				*u2w_order = 5 + diagonal;
845c5c4113dSnw141292 			else if (EMPTY_NAME(winname))
846cd37da74Snw141292 				*u2w_order = 7 + 2 * diagonal;
847c5c4113dSnw141292 			else
848cd37da74Snw141292 				*u2w_order = 8 + 2 * diagonal;
849c5c4113dSnw141292 		} else {
850c5c4113dSnw141292 			if (*winname == '*')
851c5c4113dSnw141292 				return (IDMAP_ERR_U2W_NAMERULE);
852c5c4113dSnw141292 			else if (EMPTY_NAME(winname))
853cd37da74Snw141292 				*u2w_order = 1 + 2 * diagonal;
854c5c4113dSnw141292 			else
855cd37da74Snw141292 				*u2w_order = 2 + 2 * diagonal;
856c5c4113dSnw141292 		}
857c5c4113dSnw141292 	}
858c5c4113dSnw141292 	return (IDMAP_SUCCESS);
859c5c4113dSnw141292 }
860c5c4113dSnw141292 
861c5c4113dSnw141292 /*
862c5c4113dSnw141292  * Generate and execute SQL statement to add name-based mapping rule
863c5c4113dSnw141292  */
864c5c4113dSnw141292 idmap_retcode
865cd37da74Snw141292 add_namerule(sqlite *db, idmap_namerule *rule)
866cd37da74Snw141292 {
867c5c4113dSnw141292 	char		*sql = NULL;
868c5c4113dSnw141292 	idmap_stat	retcode;
8698e228215Sdm199847 	char		*dom = NULL;
870c5c4113dSnw141292 	int		w2u_order, u2w_order;
871c5c4113dSnw141292 	char		w2ubuf[11], u2wbuf[11];
872c5c4113dSnw141292 
8738e228215Sdm199847 	retcode = get_namerule_order(rule->winname, rule->windomain,
874cd37da74Snw141292 	    rule->unixname, rule->direction,
875cd37da74Snw141292 	    rule->is_user == rule->is_wuser ? 0 : 1, &w2u_order, &u2w_order);
876c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
877c5c4113dSnw141292 		goto out;
878c5c4113dSnw141292 
879c5c4113dSnw141292 	if (w2u_order)
880c5c4113dSnw141292 		(void) snprintf(w2ubuf, sizeof (w2ubuf), "%d", w2u_order);
881c5c4113dSnw141292 	if (u2w_order)
882c5c4113dSnw141292 		(void) snprintf(u2wbuf, sizeof (u2wbuf), "%d", u2w_order);
883c5c4113dSnw141292 
88462c60062Sbaban 	/*
88562c60062Sbaban 	 * For the triggers on namerules table to work correctly:
88662c60062Sbaban 	 * 1) Use NULL instead of 0 for w2u_order and u2w_order
88762c60062Sbaban 	 * 2) Use "" instead of NULL for "no domain"
88862c60062Sbaban 	 */
88962c60062Sbaban 
890e8c27ec8Sbaban 	if (!EMPTY_STRING(rule->windomain))
8918e228215Sdm199847 		dom = rule->windomain;
892cd37da74Snw141292 	else if (lookup_wksids_name2sid(rule->winname, NULL, NULL, NULL, NULL)
89362c60062Sbaban 	    == IDMAP_SUCCESS) {
89462c60062Sbaban 		/* well-known SIDs don't need domain */
89562c60062Sbaban 		dom = "";
89662c60062Sbaban 	}
897c5c4113dSnw141292 
898c5c4113dSnw141292 	RDLOCK_CONFIG();
89962c60062Sbaban 	if (dom == NULL) {
900c8e26105Sjp151216 		if (_idmapdstate.cfg->pgcfg.default_domain)
901c8e26105Sjp151216 			dom = _idmapdstate.cfg->pgcfg.default_domain;
902c5c4113dSnw141292 		else
903c5c4113dSnw141292 			dom = "";
90462c60062Sbaban 	}
90584decf41Sjp151216 	sql = sqlite_mprintf("INSERT into namerules "
906cd37da74Snw141292 	    "(is_user, is_wuser, windomain, winname_display, is_nt4, "
907c5c4113dSnw141292 	    "unixname, w2u_order, u2w_order) "
908cd37da74Snw141292 	    "VALUES(%d, %d, %Q, %Q, %d, %Q, %q, %q);",
909cd37da74Snw141292 	    rule->is_user ? 1 : 0, rule->is_wuser ? 1 : 0, dom,
910cd37da74Snw141292 	    rule->winname, rule->is_nt4 ? 1 : 0, rule->unixname,
911cd37da74Snw141292 	    w2u_order ? w2ubuf : NULL, u2w_order ? u2wbuf : NULL);
912c5c4113dSnw141292 	UNLOCK_CONFIG();
913c5c4113dSnw141292 
914c5c4113dSnw141292 	if (sql == NULL) {
915c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
916c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
917c5c4113dSnw141292 		goto out;
918c5c4113dSnw141292 	}
919c5c4113dSnw141292 
92071590c90Snw141292 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, sql);
921c5c4113dSnw141292 
922c5c4113dSnw141292 	if (retcode == IDMAP_ERR_OTHER)
923c5c4113dSnw141292 		retcode = IDMAP_ERR_CFG;
924c5c4113dSnw141292 
925c5c4113dSnw141292 out:
92662c60062Sbaban 	if (sql != NULL)
927c5c4113dSnw141292 		sqlite_freemem(sql);
928c5c4113dSnw141292 	return (retcode);
929c5c4113dSnw141292 }
930c5c4113dSnw141292 
931c5c4113dSnw141292 /*
932c5c4113dSnw141292  * Flush name-based mapping rules
933c5c4113dSnw141292  */
934c5c4113dSnw141292 idmap_retcode
935cd37da74Snw141292 flush_namerules(sqlite *db)
936cd37da74Snw141292 {
937c5c4113dSnw141292 	idmap_stat	retcode;
938c5c4113dSnw141292 
93971590c90Snw141292 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, "DELETE FROM namerules;");
940c5c4113dSnw141292 
941c5c4113dSnw141292 	return (retcode);
942c5c4113dSnw141292 }
943c5c4113dSnw141292 
944c5c4113dSnw141292 /*
945c5c4113dSnw141292  * Generate and execute SQL statement to remove a name-based mapping rule
946c5c4113dSnw141292  */
947c5c4113dSnw141292 idmap_retcode
948cd37da74Snw141292 rm_namerule(sqlite *db, idmap_namerule *rule)
949cd37da74Snw141292 {
950c5c4113dSnw141292 	char		*sql = NULL;
951c5c4113dSnw141292 	idmap_stat	retcode;
952c5c4113dSnw141292 	char		buf[80];
953cd37da74Snw141292 	char		*expr = NULL;
954c5c4113dSnw141292 
9558e228215Sdm199847 	if (rule->direction < 0 && EMPTY_STRING(rule->windomain) &&
9568e228215Sdm199847 	    EMPTY_STRING(rule->winname) && EMPTY_STRING(rule->unixname))
957c5c4113dSnw141292 		return (IDMAP_SUCCESS);
958c5c4113dSnw141292 
959c5c4113dSnw141292 	buf[0] = 0;
960cd37da74Snw141292 
961cd37da74Snw141292 	if (rule->direction == IDMAP_DIRECTION_BI)
962c5c4113dSnw141292 		(void) snprintf(buf, sizeof (buf), "AND w2u_order > 0"
963c5c4113dSnw141292 		    " AND u2w_order > 0");
964cd37da74Snw141292 	else if (rule->direction == IDMAP_DIRECTION_W2U)
965c5c4113dSnw141292 		(void) snprintf(buf, sizeof (buf), "AND w2u_order > 0"
966c5c4113dSnw141292 		    " AND (u2w_order = 0 OR u2w_order ISNULL)");
967cd37da74Snw141292 	else if (rule->direction == IDMAP_DIRECTION_U2W)
968c5c4113dSnw141292 		(void) snprintf(buf, sizeof (buf), "AND u2w_order > 0"
969c5c4113dSnw141292 		    " AND (w2u_order = 0 OR w2u_order ISNULL)");
970c5c4113dSnw141292 
971cd37da74Snw141292 	retcode = gen_sql_expr_from_rule(rule, &expr);
972cd37da74Snw141292 	if (retcode != IDMAP_SUCCESS)
973c5c4113dSnw141292 		goto out;
974c5c4113dSnw141292 
975cd37da74Snw141292 	sql = sqlite_mprintf("DELETE FROM namerules WHERE 1 %s %s;", expr,
976c5c4113dSnw141292 	    buf);
977c5c4113dSnw141292 
978c5c4113dSnw141292 	if (sql == NULL) {
979c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
980c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
981c5c4113dSnw141292 		goto out;
982c5c4113dSnw141292 	}
983c5c4113dSnw141292 
984cd37da74Snw141292 
98571590c90Snw141292 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, sql);
986c5c4113dSnw141292 
987c5c4113dSnw141292 out:
988cd37da74Snw141292 	if (expr != NULL)
989cd37da74Snw141292 		sqlite_freemem(expr);
99062c60062Sbaban 	if (sql != NULL)
991c5c4113dSnw141292 		sqlite_freemem(sql);
992c5c4113dSnw141292 	return (retcode);
993c5c4113dSnw141292 }
994c5c4113dSnw141292 
995c5c4113dSnw141292 /*
996c5c4113dSnw141292  * Compile the given SQL query and step just once.
997c5c4113dSnw141292  *
998c5c4113dSnw141292  * Input:
999c5c4113dSnw141292  * db  - db handle
1000c5c4113dSnw141292  * sql - SQL statement
1001c5c4113dSnw141292  *
1002c5c4113dSnw141292  * Output:
1003c5c4113dSnw141292  * vm     -  virtual SQL machine
1004c5c4113dSnw141292  * ncol   - number of columns in the result
1005c5c4113dSnw141292  * values - column values
1006c5c4113dSnw141292  *
1007c5c4113dSnw141292  * Return values:
1008c5c4113dSnw141292  * IDMAP_SUCCESS
1009c5c4113dSnw141292  * IDMAP_ERR_NOTFOUND
1010c5c4113dSnw141292  * IDMAP_ERR_INTERNAL
1011c5c4113dSnw141292  */
1012c5c4113dSnw141292 
1013cd37da74Snw141292 static
1014cd37da74Snw141292 idmap_retcode
1015c5c4113dSnw141292 sql_compile_n_step_once(sqlite *db, char *sql, sqlite_vm **vm, int *ncol,
1016cd37da74Snw141292 		int reqcol, const char ***values)
1017cd37da74Snw141292 {
1018c5c4113dSnw141292 	char		*errmsg = NULL;
101984decf41Sjp151216 	int		r;
1020c5c4113dSnw141292 
102184decf41Sjp151216 	if ((r = sqlite_compile(db, sql, NULL, vm, &errmsg)) != SQLITE_OK) {
1022cd37da74Snw141292 		idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
1023cd37da74Snw141292 		    CHECK_NULL(errmsg));
1024c5c4113dSnw141292 		sqlite_freemem(errmsg);
1025c5c4113dSnw141292 		return (IDMAP_ERR_INTERNAL);
1026c5c4113dSnw141292 	}
1027c5c4113dSnw141292 
1028c5c4113dSnw141292 	r = sqlite_step(*vm, ncol, values, NULL);
102984decf41Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
1030c5c4113dSnw141292 
103184decf41Sjp151216 	if (r == SQLITE_ROW) {
103262c60062Sbaban 		if (ncol != NULL && *ncol < reqcol) {
1033c5c4113dSnw141292 			(void) sqlite_finalize(*vm, NULL);
1034c5c4113dSnw141292 			*vm = NULL;
1035c5c4113dSnw141292 			return (IDMAP_ERR_INTERNAL);
1036c5c4113dSnw141292 		}
1037c5c4113dSnw141292 		/* Caller will call finalize after using the results */
1038c5c4113dSnw141292 		return (IDMAP_SUCCESS);
1039c5c4113dSnw141292 	} else if (r == SQLITE_DONE) {
1040c5c4113dSnw141292 		(void) sqlite_finalize(*vm, NULL);
1041c5c4113dSnw141292 		*vm = NULL;
1042c5c4113dSnw141292 		return (IDMAP_ERR_NOTFOUND);
1043c5c4113dSnw141292 	}
1044c5c4113dSnw141292 
1045c5c4113dSnw141292 	(void) sqlite_finalize(*vm, &errmsg);
1046c5c4113dSnw141292 	*vm = NULL;
1047cd37da74Snw141292 	idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
1048cd37da74Snw141292 	    CHECK_NULL(errmsg));
1049c5c4113dSnw141292 	sqlite_freemem(errmsg);
1050c5c4113dSnw141292 	return (IDMAP_ERR_INTERNAL);
1051c5c4113dSnw141292 }
1052c5c4113dSnw141292 
105362c60062Sbaban /*
1054479ac375Sdm199847  * Load config in the state.
1055e8c27ec8Sbaban  *
1056479ac375Sdm199847  * nm_siduid and nm_sidgid fields:
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
1075479ac375Sdm199847 load_cfg_in_state(lookup_state_t *state)
1076e8c27ec8Sbaban {
1077e8c27ec8Sbaban 	state->nm_siduid = IDMAP_NM_NONE;
1078e8c27ec8Sbaban 	state->nm_sidgid = IDMAP_NM_NONE;
1079e8c27ec8Sbaban 	RDLOCK_CONFIG();
1080479ac375Sdm199847 
10814aa0a5e7Snw141292 	state->eph_map_unres_sids = 0;
10824aa0a5e7Snw141292 	if (_idmapdstate.cfg->pgcfg.eph_map_unres_sids)
10834aa0a5e7Snw141292 		state->eph_map_unres_sids = 1;
10844aa0a5e7Snw141292 
1085479ac375Sdm199847 	if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
1086479ac375Sdm199847 		state->defdom =
1087479ac375Sdm199847 		    strdup(_idmapdstate.cfg->pgcfg.default_domain);
1088479ac375Sdm199847 		if (state->defdom == NULL) {
1089479ac375Sdm199847 			UNLOCK_CONFIG();
1090479ac375Sdm199847 			return (IDMAP_ERR_MEMORY);
1091479ac375Sdm199847 		}
1092479ac375Sdm199847 	} else {
1093479ac375Sdm199847 		UNLOCK_CONFIG();
1094dc03a638Sdm199847 		return (IDMAP_SUCCESS);
1095479ac375Sdm199847 	}
1096e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.ds_name_mapping_enabled == FALSE) {
1097e8c27ec8Sbaban 		UNLOCK_CONFIG();
1098e8c27ec8Sbaban 		return (IDMAP_SUCCESS);
1099e8c27ec8Sbaban 	}
1100e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.nldap_winname_attr != NULL) {
1101e8c27ec8Sbaban 		state->nm_siduid =
1102e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
1103e8c27ec8Sbaban 		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
1104e8c27ec8Sbaban 		state->nm_sidgid =
1105e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
1106e8c27ec8Sbaban 		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
1107e8c27ec8Sbaban 	} else {
1108e8c27ec8Sbaban 		state->nm_siduid =
1109e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
1110e8c27ec8Sbaban 		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
1111e8c27ec8Sbaban 		state->nm_sidgid =
1112e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
1113e8c27ec8Sbaban 		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
1114e8c27ec8Sbaban 	}
1115e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL) {
1116e8c27ec8Sbaban 		state->ad_unixuser_attr =
1117e8c27ec8Sbaban 		    strdup(_idmapdstate.cfg->pgcfg.ad_unixuser_attr);
1118e8c27ec8Sbaban 		if (state->ad_unixuser_attr == NULL) {
1119e8c27ec8Sbaban 			UNLOCK_CONFIG();
1120e8c27ec8Sbaban 			return (IDMAP_ERR_MEMORY);
1121e8c27ec8Sbaban 		}
1122e8c27ec8Sbaban 	}
1123e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL) {
1124e8c27ec8Sbaban 		state->ad_unixgroup_attr =
1125e8c27ec8Sbaban 		    strdup(_idmapdstate.cfg->pgcfg.ad_unixgroup_attr);
1126e8c27ec8Sbaban 		if (state->ad_unixgroup_attr == NULL) {
1127e8c27ec8Sbaban 			UNLOCK_CONFIG();
1128e8c27ec8Sbaban 			return (IDMAP_ERR_MEMORY);
1129e8c27ec8Sbaban 		}
1130e8c27ec8Sbaban 	}
1131479ac375Sdm199847 	if (_idmapdstate.cfg->pgcfg.nldap_winname_attr != NULL) {
1132479ac375Sdm199847 		state->nldap_winname_attr =
1133479ac375Sdm199847 		    strdup(_idmapdstate.cfg->pgcfg.nldap_winname_attr);
1134479ac375Sdm199847 		if (state->nldap_winname_attr == NULL) {
1135479ac375Sdm199847 			UNLOCK_CONFIG();
1136479ac375Sdm199847 			return (IDMAP_ERR_MEMORY);
1137479ac375Sdm199847 		}
1138479ac375Sdm199847 	}
1139e8c27ec8Sbaban 	UNLOCK_CONFIG();
1140e8c27ec8Sbaban 	return (IDMAP_SUCCESS);
1141e8c27ec8Sbaban }
1142e8c27ec8Sbaban 
1143e8c27ec8Sbaban /*
114448258c6bSjp151216  * Set the rule with sepecified values.
114548258c6bSjp151216  * All the strings are copied.
114648258c6bSjp151216  */
114748258c6bSjp151216 static void
114848258c6bSjp151216 idmap_namerule_set(idmap_namerule *rule, const char *windomain,
114948258c6bSjp151216 		const char *winname, const char *unixname, boolean_t is_user,
115048258c6bSjp151216 		boolean_t is_wuser, boolean_t is_nt4, int direction)
115148258c6bSjp151216 {
115248258c6bSjp151216 	/*
115348258c6bSjp151216 	 * Only update if they differ because we have to free
115448258c6bSjp151216 	 * and duplicate the strings
115548258c6bSjp151216 	 */
115648258c6bSjp151216 	if (rule->windomain == NULL || windomain == NULL ||
115748258c6bSjp151216 	    strcmp(rule->windomain, windomain) != 0) {
115848258c6bSjp151216 		if (rule->windomain != NULL) {
115948258c6bSjp151216 			free(rule->windomain);
116048258c6bSjp151216 			rule->windomain = NULL;
116148258c6bSjp151216 		}
116248258c6bSjp151216 		if (windomain != NULL)
116348258c6bSjp151216 			rule->windomain = strdup(windomain);
116448258c6bSjp151216 	}
116548258c6bSjp151216 
116648258c6bSjp151216 	if (rule->winname == NULL || winname == NULL ||
116748258c6bSjp151216 	    strcmp(rule->winname, winname) != 0) {
116848258c6bSjp151216 		if (rule->winname != NULL) {
116948258c6bSjp151216 			free(rule->winname);
117048258c6bSjp151216 			rule->winname = NULL;
117148258c6bSjp151216 		}
117248258c6bSjp151216 		if (winname != NULL)
117348258c6bSjp151216 			rule->winname = strdup(winname);
117448258c6bSjp151216 	}
117548258c6bSjp151216 
117648258c6bSjp151216 	if (rule->unixname == NULL || unixname == NULL ||
117748258c6bSjp151216 	    strcmp(rule->unixname, unixname) != 0) {
117848258c6bSjp151216 		if (rule->unixname != NULL) {
117948258c6bSjp151216 			free(rule->unixname);
118048258c6bSjp151216 			rule->unixname = NULL;
118148258c6bSjp151216 		}
118248258c6bSjp151216 		if (unixname != NULL)
118348258c6bSjp151216 			rule->unixname = strdup(unixname);
118448258c6bSjp151216 	}
118548258c6bSjp151216 
118648258c6bSjp151216 	rule->is_user = is_user;
118748258c6bSjp151216 	rule->is_wuser = is_wuser;
118848258c6bSjp151216 	rule->is_nt4 = is_nt4;
118948258c6bSjp151216 	rule->direction = direction;
119048258c6bSjp151216 }
119148258c6bSjp151216 
119248258c6bSjp151216 
119348258c6bSjp151216 /*
119462c60062Sbaban  * Table for well-known SIDs.
119562c60062Sbaban  *
119662c60062Sbaban  * Background:
119762c60062Sbaban  *
119876b27f93Sbaban  * Some of the well-known principals are stored under:
119962c60062Sbaban  * cn=WellKnown Security Principals, cn=Configuration, dc=<forestRootDomain>
120062c60062Sbaban  * They belong to objectClass "foreignSecurityPrincipal". They don't have
120162c60062Sbaban  * "samAccountName" nor "userPrincipalName" attributes. Their names are
120262c60062Sbaban  * available in "cn" and "name" attributes. Some of these principals have a
120362c60062Sbaban  * second entry under CN=ForeignSecurityPrincipals,dc=<forestRootDomain> and
120462c60062Sbaban  * these duplicate entries have the stringified SID in the "name" and "cn"
120562c60062Sbaban  * attributes instead of the actual name.
120662c60062Sbaban  *
120776b27f93Sbaban  * Those of the form S-1-5-32-X are Builtin groups and are stored in the
120876b27f93Sbaban  * cn=builtin container (except, Power Users which is not stored in AD)
120962c60062Sbaban  *
121076b27f93Sbaban  * These principals are and will remain constant. Therefore doing AD lookups
121176b27f93Sbaban  * provides no benefit. Also, using hard-coded table (and thus avoiding AD
121276b27f93Sbaban  * lookup) improves performance and avoids additional complexity in the
121376b27f93Sbaban  * adutils.c code. Moreover these SIDs can be used when no Active Directory
121476b27f93Sbaban  * is available (such as the CIFS server's "workgroup" mode).
121576b27f93Sbaban  *
121676b27f93Sbaban  * Notes:
121776b27f93Sbaban  * 1. Currently we don't support localization of well-known SID names,
121862c60062Sbaban  * unlike Windows.
121962c60062Sbaban  *
122076b27f93Sbaban  * 2. Other well-known SIDs i.e. S-1-5-<domain>-<w-k RID> are not stored
122176b27f93Sbaban  * here. AD does have normal user/group objects for these objects and
122276b27f93Sbaban  * can be looked up using the existing AD lookup code.
1223e8c27ec8Sbaban  *
1224e8c27ec8Sbaban  * 3. See comments above lookup_wksids_sid2pid() for more information
1225e8c27ec8Sbaban  * on how we lookup the wksids table.
122662c60062Sbaban  */
122762c60062Sbaban static wksids_table_t wksids[] = {
1228e8c27ec8Sbaban 	{"S-1-0", 0, "Nobody", 0, SENTINEL_PID, -1, 1},
1229e8c27ec8Sbaban 	{"S-1-1", 0, "Everyone", 0, SENTINEL_PID, -1, -1},
1230e8c27ec8Sbaban 	{"S-1-3", 0, "Creator Owner", 1, IDMAP_WK_CREATOR_OWNER_UID, 1, 0},
1231e8c27ec8Sbaban 	{"S-1-3", 1, "Creator Group", 0, IDMAP_WK_CREATOR_GROUP_GID, 0, 0},
1232e8c27ec8Sbaban 	{"S-1-3", 2, "Creator Owner Server", 1, SENTINEL_PID, -1, -1},
1233e8c27ec8Sbaban 	{"S-1-3", 3, "Creator Group Server", 0, SENTINEL_PID, -1, 1},
1234e8c27ec8Sbaban 	{"S-1-3", 4, "Owner Rights", 0, SENTINEL_PID, -1, -1},
1235e8c27ec8Sbaban 	{"S-1-5", 1, "Dialup", 0, SENTINEL_PID, -1, -1},
1236e8c27ec8Sbaban 	{"S-1-5", 2, "Network", 0, SENTINEL_PID, -1, -1},
1237e8c27ec8Sbaban 	{"S-1-5", 3, "Batch", 0, SENTINEL_PID, -1, -1},
1238e8c27ec8Sbaban 	{"S-1-5", 4, "Interactive", 0, SENTINEL_PID, -1, -1},
1239e8c27ec8Sbaban 	{"S-1-5", 6, "Service", 0, SENTINEL_PID, -1, -1},
1240e8c27ec8Sbaban 	{"S-1-5", 7, "Anonymous Logon", 0, GID_NOBODY, 0, 0},
1241e8c27ec8Sbaban 	{"S-1-5", 7, "Anonymous Logon", 0, UID_NOBODY, 1, 0},
1242e8c27ec8Sbaban 	{"S-1-5", 8, "Proxy", 0, SENTINEL_PID, -1, -1},
1243e8c27ec8Sbaban 	{"S-1-5", 9, "Enterprise Domain Controllers", 0, SENTINEL_PID, -1, -1},
1244e8c27ec8Sbaban 	{"S-1-5", 10, "Self", 0, SENTINEL_PID, -1, -1},
1245e8c27ec8Sbaban 	{"S-1-5", 11, "Authenticated Users", 0, SENTINEL_PID, -1, -1},
1246e8c27ec8Sbaban 	{"S-1-5", 12, "Restricted Code", 0, SENTINEL_PID, -1, -1},
1247e8c27ec8Sbaban 	{"S-1-5", 13, "Terminal Server User", 0, SENTINEL_PID, -1, -1},
1248e8c27ec8Sbaban 	{"S-1-5", 14, "Remote Interactive Logon", 0, SENTINEL_PID, -1, -1},
1249e8c27ec8Sbaban 	{"S-1-5", 15, "This Organization", 0, SENTINEL_PID, -1, -1},
1250e8c27ec8Sbaban 	{"S-1-5", 17, "IUSR", 0, SENTINEL_PID, -1, -1},
1251e8c27ec8Sbaban 	{"S-1-5", 18, "Local System", 0, IDMAP_WK_LOCAL_SYSTEM_GID, 0, 0},
1252e8c27ec8Sbaban 	{"S-1-5", 19, "Local Service", 0, SENTINEL_PID, -1, -1},
1253e8c27ec8Sbaban 	{"S-1-5", 20, "Network Service", 0, SENTINEL_PID, -1, -1},
1254e8c27ec8Sbaban 	{"S-1-5", 1000, "Other Organization", 0, SENTINEL_PID, -1, -1},
1255e8c27ec8Sbaban 	{"S-1-5-32", 544, "Administrators", 0, SENTINEL_PID, -1, -1},
1256e8c27ec8Sbaban 	{"S-1-5-32", 545, "Users", 0, SENTINEL_PID, -1, -1},
1257e8c27ec8Sbaban 	{"S-1-5-32", 546, "Guests", 0, SENTINEL_PID, -1, -1},
1258e8c27ec8Sbaban 	{"S-1-5-32", 547, "Power Users", 0, SENTINEL_PID, -1, -1},
1259e8c27ec8Sbaban 	{"S-1-5-32", 548, "Account Operators", 0, SENTINEL_PID, -1, -1},
1260e8c27ec8Sbaban 	{"S-1-5-32", 549, "Server Operators", 0, SENTINEL_PID, -1, -1},
1261e8c27ec8Sbaban 	{"S-1-5-32", 550, "Print Operators", 0, SENTINEL_PID, -1, -1},
1262e8c27ec8Sbaban 	{"S-1-5-32", 551, "Backup Operators", 0, SENTINEL_PID, -1, -1},
1263e8c27ec8Sbaban 	{"S-1-5-32", 552, "Replicator", 0, SENTINEL_PID, -1, -1},
126476b27f93Sbaban 	{"S-1-5-32", 554, "Pre-Windows 2000 Compatible Access", 0,
1265e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1266e8c27ec8Sbaban 	{"S-1-5-32", 555, "Remote Desktop Users", 0, SENTINEL_PID, -1, -1},
126776b27f93Sbaban 	{"S-1-5-32", 556, "Network Configuration Operators", 0,
1268e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
126976b27f93Sbaban 	{"S-1-5-32", 557, "Incoming Forest Trust Builders", 0,
1270e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1271e8c27ec8Sbaban 	{"S-1-5-32", 558, "Performance Monitor Users", 0, SENTINEL_PID, -1, -1},
1272e8c27ec8Sbaban 	{"S-1-5-32", 559, "Performance Log Users", 0, SENTINEL_PID, -1, -1},
127376b27f93Sbaban 	{"S-1-5-32", 560, "Windows Authorization Access Group", 0,
1274e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
127576b27f93Sbaban 	{"S-1-5-32", 561, "Terminal Server License Servers", 0,
1276e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1277e8c27ec8Sbaban 	{"S-1-5-32", 561, "Distributed COM Users", 0, SENTINEL_PID, -1, -1},
1278e8c27ec8Sbaban 	{"S-1-5-32", 568, "IIS_IUSRS", 0, SENTINEL_PID, -1, -1},
1279e8c27ec8Sbaban 	{"S-1-5-32", 569, "Cryptographic Operators", 0, SENTINEL_PID, -1, -1},
1280e8c27ec8Sbaban 	{"S-1-5-32", 573, "Event Log Readers", 0, SENTINEL_PID, -1, -1},
128176b27f93Sbaban 	{"S-1-5-32", 574, "Certificate Service DCOM Access", 0,
1282e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1283e8c27ec8Sbaban 	{"S-1-5-64", 21, "Digest Authentication", 0, SENTINEL_PID, -1, -1},
1284e8c27ec8Sbaban 	{"S-1-5-64", 10, "NTLM Authentication", 0, SENTINEL_PID, -1, -1},
1285e8c27ec8Sbaban 	{"S-1-5-64", 14, "SChannel Authentication", 0, SENTINEL_PID, -1, -1},
1286e8c27ec8Sbaban 	{NULL, UINT32_MAX, NULL, -1, SENTINEL_PID, -1, -1}
1287c5c4113dSnw141292 };
1288c5c4113dSnw141292 
1289e8c27ec8Sbaban /*
1290e8c27ec8Sbaban  * Lookup well-known SIDs table either by winname or by SID.
1291e8c27ec8Sbaban  * If the given winname or SID is a well-known SID then we set wksid
1292e8c27ec8Sbaban  * variable and then proceed to see if the SID has a hard mapping to
1293e8c27ec8Sbaban  * a particular UID/GID (Ex: Creator Owner/Creator Group mapped to
1294e8c27ec8Sbaban  * fixed ephemeral ids). If we find such mapping then we return
1295e8c27ec8Sbaban  * success otherwise notfound. If a well-known SID is mapped to
1296e8c27ec8Sbaban  * SENTINEL_PID and the direction field is set (bi-directional or
1297e8c27ec8Sbaban  * win2unix) then we treat it as inhibited mapping and return no
1298e8c27ec8Sbaban  * mapping (Ex. S-1-0-0).
1299e8c27ec8Sbaban  */
1300cd37da74Snw141292 static
1301cd37da74Snw141292 idmap_retcode
1302e8c27ec8Sbaban lookup_wksids_sid2pid(idmap_mapping *req, idmap_id_res *res, int *wksid)
1303cd37da74Snw141292 {
1304c5c4113dSnw141292 	int i;
130562c60062Sbaban 
1306e8c27ec8Sbaban 	*wksid = 0;
1307e8c27ec8Sbaban 
1308e8c27ec8Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
1309e8c27ec8Sbaban 		if (req->id1.idmap_id_u.sid.prefix != NULL) {
1310e8c27ec8Sbaban 			if ((strcasecmp(wksids[i].sidprefix,
1311e8c27ec8Sbaban 			    req->id1.idmap_id_u.sid.prefix) != 0) ||
1312e8c27ec8Sbaban 			    wksids[i].rid != req->id1.idmap_id_u.sid.rid)
1313e8c27ec8Sbaban 				/* this is not our SID */
1314e8c27ec8Sbaban 				continue;
1315e8c27ec8Sbaban 			if (req->id1name == NULL) {
1316e8c27ec8Sbaban 				req->id1name = strdup(wksids[i].winname);
1317e8c27ec8Sbaban 				if (req->id1name == NULL)
1318e8c27ec8Sbaban 					return (IDMAP_ERR_MEMORY);
1319e8c27ec8Sbaban 			}
1320e8c27ec8Sbaban 		} else if (req->id1name != NULL) {
1321e8c27ec8Sbaban 			if (strcasecmp(wksids[i].winname, req->id1name) != 0)
1322e8c27ec8Sbaban 				/* this is not our winname */
1323e8c27ec8Sbaban 				continue;
1324e8c27ec8Sbaban 			req->id1.idmap_id_u.sid.prefix =
1325e8c27ec8Sbaban 			    strdup(wksids[i].sidprefix);
1326e8c27ec8Sbaban 			if (req->id1.idmap_id_u.sid.prefix == NULL)
1327e8c27ec8Sbaban 				return (IDMAP_ERR_MEMORY);
1328e8c27ec8Sbaban 			req->id1.idmap_id_u.sid.rid = wksids[i].rid;
1329e8c27ec8Sbaban 		}
1330e8c27ec8Sbaban 
1331e8c27ec8Sbaban 		*wksid = 1;
1332e8c27ec8Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
1333e8c27ec8Sbaban 
1334e8c27ec8Sbaban 		req->id1.idtype = (wksids[i].is_wuser) ?
1335e8c27ec8Sbaban 		    IDMAP_USID : IDMAP_GSID;
1336e8c27ec8Sbaban 
1337e8c27ec8Sbaban 		if (wksids[i].pid == SENTINEL_PID) {
1338e8c27ec8Sbaban 			if (wksids[i].direction == IDMAP_DIRECTION_BI ||
1339e8c27ec8Sbaban 			    wksids[i].direction == IDMAP_DIRECTION_W2U)
1340e8c27ec8Sbaban 				/* Inhibited */
1341e8c27ec8Sbaban 				return (IDMAP_ERR_NOMAPPING);
1342e8c27ec8Sbaban 			/* Not mapped */
1343479ac375Sdm199847 			if (res->id.idtype == IDMAP_POSIXID) {
1344479ac375Sdm199847 				res->id.idtype =
1345479ac375Sdm199847 				    (wksids[i].is_wuser) ?
1346479ac375Sdm199847 				    IDMAP_UID : IDMAP_GID;
1347479ac375Sdm199847 			}
1348e8c27ec8Sbaban 			return (IDMAP_ERR_NOTFOUND);
1349e8c27ec8Sbaban 		} else if (wksids[i].direction == IDMAP_DIRECTION_U2W)
135062c60062Sbaban 			continue;
135162c60062Sbaban 
1352e8c27ec8Sbaban 		switch (res->id.idtype) {
1353c5c4113dSnw141292 		case IDMAP_UID:
135462c60062Sbaban 			if (wksids[i].is_user == 0)
135562c60062Sbaban 				continue;
135662c60062Sbaban 			res->id.idmap_id_u.uid = wksids[i].pid;
135762c60062Sbaban 			res->direction = wksids[i].direction;
135848258c6bSjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
135948258c6bSjp151216 				res->info.how.map_type =
136048258c6bSjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
136148258c6bSjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
136248258c6bSjp151216 			}
1363c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1364c5c4113dSnw141292 		case IDMAP_GID:
136562c60062Sbaban 			if (wksids[i].is_user == 1)
136662c60062Sbaban 				continue;
136762c60062Sbaban 			res->id.idmap_id_u.gid = wksids[i].pid;
136862c60062Sbaban 			res->direction = wksids[i].direction;
136948258c6bSjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
137048258c6bSjp151216 				res->info.how.map_type =
137148258c6bSjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
137248258c6bSjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
137348258c6bSjp151216 			}
1374c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1375c5c4113dSnw141292 		case IDMAP_POSIXID:
137662c60062Sbaban 			res->id.idmap_id_u.uid = wksids[i].pid;
137762c60062Sbaban 			res->id.idtype = (!wksids[i].is_user) ?
1378c5c4113dSnw141292 			    IDMAP_GID : IDMAP_UID;
137962c60062Sbaban 			res->direction = wksids[i].direction;
138048258c6bSjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
138148258c6bSjp151216 				res->info.how.map_type =
138248258c6bSjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
138348258c6bSjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
138448258c6bSjp151216 			}
1385c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1386c5c4113dSnw141292 		default:
1387c5c4113dSnw141292 			return (IDMAP_ERR_NOTSUPPORTED);
1388c5c4113dSnw141292 		}
1389c5c4113dSnw141292 	}
1390c5c4113dSnw141292 	return (IDMAP_ERR_NOTFOUND);
1391c5c4113dSnw141292 }
1392c5c4113dSnw141292 
1393cd37da74Snw141292 
1394cd37da74Snw141292 static
1395cd37da74Snw141292 idmap_retcode
1396cd37da74Snw141292 lookup_wksids_pid2sid(idmap_mapping *req, idmap_id_res *res, int is_user)
1397cd37da74Snw141292 {
1398c5c4113dSnw141292 	int i;
1399e8c27ec8Sbaban 	if (req->id1.idmap_id_u.uid == SENTINEL_PID)
1400e8c27ec8Sbaban 		return (IDMAP_ERR_NOTFOUND);
140162c60062Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
140262c60062Sbaban 		if (wksids[i].pid == req->id1.idmap_id_u.uid &&
140362c60062Sbaban 		    wksids[i].is_user == is_user &&
140462c60062Sbaban 		    wksids[i].direction != IDMAP_DIRECTION_W2U) {
1405e8c27ec8Sbaban 			if (res->id.idtype == IDMAP_SID) {
1406e8c27ec8Sbaban 				res->id.idtype = (wksids[i].is_wuser) ?
1407e8c27ec8Sbaban 				    IDMAP_USID : IDMAP_GSID;
1408e8c27ec8Sbaban 			}
140962c60062Sbaban 			res->id.idmap_id_u.sid.rid = wksids[i].rid;
1410c5c4113dSnw141292 			res->id.idmap_id_u.sid.prefix =
141162c60062Sbaban 			    strdup(wksids[i].sidprefix);
1412c5c4113dSnw141292 			if (res->id.idmap_id_u.sid.prefix == NULL) {
1413c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1414c5c4113dSnw141292 				return (IDMAP_ERR_MEMORY);
1415c5c4113dSnw141292 			}
141662c60062Sbaban 			res->direction = wksids[i].direction;
141748258c6bSjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
141848258c6bSjp151216 				res->info.how.map_type =
141948258c6bSjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
142048258c6bSjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
142148258c6bSjp151216 			}
1422c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1423c5c4113dSnw141292 		}
1424c5c4113dSnw141292 	}
142562c60062Sbaban 	return (IDMAP_ERR_NOTFOUND);
142662c60062Sbaban }
142762c60062Sbaban 
1428cd37da74Snw141292 idmap_retcode
1429cd37da74Snw141292 lookup_wksids_name2sid(const char *name, char **canonname, char **sidprefix,
1430cd37da74Snw141292 	idmap_rid_t *rid, int *type)
1431cd37da74Snw141292 {
143262c60062Sbaban 	int	i;
1433479ac375Sdm199847 
1434479ac375Sdm199847 	if ((strncasecmp(name, "BUILTIN\\", 8) == 0) ||
1435479ac375Sdm199847 	    (strncasecmp(name, "BUILTIN/", 8) == 0))
1436479ac375Sdm199847 		name += 8;
1437479ac375Sdm199847 
143862c60062Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
1439e8c27ec8Sbaban 		if (strcasecmp(wksids[i].winname, name) != 0)
1440e8c27ec8Sbaban 			continue;
1441e8c27ec8Sbaban 		if (sidprefix != NULL &&
1442e8c27ec8Sbaban 		    (*sidprefix = strdup(wksids[i].sidprefix)) == NULL) {
144362c60062Sbaban 			idmapdlog(LOG_ERR, "Out of memory");
144462c60062Sbaban 			return (IDMAP_ERR_MEMORY);
144562c60062Sbaban 		}
1446cd37da74Snw141292 		if (canonname != NULL &&
1447cd37da74Snw141292 		    (*canonname = strdup(wksids[i].winname)) == NULL) {
1448cd37da74Snw141292 			idmapdlog(LOG_ERR, "Out of memory");
1449e8c27ec8Sbaban 			if (sidprefix != NULL) {
1450e8c27ec8Sbaban 				free(*sidprefix);
1451e8c27ec8Sbaban 				*sidprefix = NULL;
1452e8c27ec8Sbaban 			}
1453cd37da74Snw141292 			return (IDMAP_ERR_MEMORY);
1454cd37da74Snw141292 		}
145562c60062Sbaban 		if (type != NULL)
1456e8c27ec8Sbaban 			*type = (wksids[i].is_wuser) ?
145762c60062Sbaban 			    _IDMAP_T_USER : _IDMAP_T_GROUP;
145862c60062Sbaban 		if (rid != NULL)
145962c60062Sbaban 			*rid = wksids[i].rid;
146062c60062Sbaban 		return (IDMAP_SUCCESS);
146162c60062Sbaban 	}
1462c5c4113dSnw141292 	return (IDMAP_ERR_NOTFOUND);
1463c5c4113dSnw141292 }
1464c5c4113dSnw141292 
1465cd37da74Snw141292 static
1466cd37da74Snw141292 idmap_retcode
1467cd37da74Snw141292 lookup_cache_sid2pid(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
1468cd37da74Snw141292 {
1469c5c4113dSnw141292 	char		*end;
1470c5c4113dSnw141292 	char		*sql = NULL;
1471c5c4113dSnw141292 	const char	**values;
1472c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
1473c5c4113dSnw141292 	int		ncol, is_user;
1474c5c4113dSnw141292 	uid_t		pid;
1475c5c4113dSnw141292 	time_t		curtime, exp;
1476c5c4113dSnw141292 	idmap_retcode	retcode;
1477042addd6Sbaban 	char		*is_user_string, *lower_name;
1478c5c4113dSnw141292 
1479c5c4113dSnw141292 	/* Current time */
1480c5c4113dSnw141292 	errno = 0;
1481c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
1482cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
1483c5c4113dSnw141292 		    strerror(errno));
1484c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
1485c5c4113dSnw141292 		goto out;
1486c5c4113dSnw141292 	}
1487c5c4113dSnw141292 
1488e8c27ec8Sbaban 	switch (res->id.idtype) {
1489cd37da74Snw141292 	case IDMAP_UID:
1490cd37da74Snw141292 		is_user_string = "1";
1491cd37da74Snw141292 		break;
1492cd37da74Snw141292 	case IDMAP_GID:
1493cd37da74Snw141292 		is_user_string = "0";
1494cd37da74Snw141292 		break;
1495cd37da74Snw141292 	case IDMAP_POSIXID:
1496cd37da74Snw141292 		/* the non-diagonal mapping */
1497cd37da74Snw141292 		is_user_string = "is_wuser";
1498cd37da74Snw141292 		break;
1499cd37da74Snw141292 	default:
1500cd37da74Snw141292 		retcode = IDMAP_ERR_NOTSUPPORTED;
1501cd37da74Snw141292 		goto out;
1502cd37da74Snw141292 	}
1503cd37da74Snw141292 
1504c5c4113dSnw141292 	/* SQL to lookup the cache */
150548258c6bSjp151216 
1506e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
1507e8c27ec8Sbaban 		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
150848258c6bSjp151216 		    "unixname, u2w, is_wuser, "
150948258c6bSjp151216 		    "map_type, map_dn, map_attr, map_value, "
151048258c6bSjp151216 		    "map_windomain, map_winname, map_unixname, map_is_nt4 "
1511cd37da74Snw141292 		    "FROM idmap_cache WHERE is_user = %s AND "
1512c5c4113dSnw141292 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
1513c5c4113dSnw141292 		    "(pid >= 2147483648 OR "
1514c5c4113dSnw141292 		    "(expiration = 0 OR expiration ISNULL OR "
1515c5c4113dSnw141292 		    "expiration > %d));",
1516e8c27ec8Sbaban 		    is_user_string, req->id1.idmap_id_u.sid.prefix,
1517e8c27ec8Sbaban 		    req->id1.idmap_id_u.sid.rid, curtime);
1518e8c27ec8Sbaban 	} else if (req->id1name != NULL) {
1519042addd6Sbaban 		if ((lower_name = tolower_u8(req->id1name)) == NULL)
1520042addd6Sbaban 			lower_name = req->id1name;
1521e8c27ec8Sbaban 		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
152248258c6bSjp151216 		    "unixname, u2w, is_wuser, "
152348258c6bSjp151216 		    "map_type, map_dn, map_attr, map_value, "
152448258c6bSjp151216 		    "map_windomain, map_winname, map_unixname, map_is_nt4 "
1525e8c27ec8Sbaban 		    "FROM idmap_cache WHERE is_user = %s AND "
1526e8c27ec8Sbaban 		    "winname = %Q AND windomain = %Q AND w2u = 1 AND "
1527e8c27ec8Sbaban 		    "(pid >= 2147483648 OR "
1528e8c27ec8Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
1529e8c27ec8Sbaban 		    "expiration > %d));",
153048258c6bSjp151216 		    is_user_string, lower_name, req->id1domain,
153148258c6bSjp151216 		    curtime);
1532042addd6Sbaban 		if (lower_name != req->id1name)
1533042addd6Sbaban 			free(lower_name);
1534e8c27ec8Sbaban 	} else {
1535e8c27ec8Sbaban 		retcode = IDMAP_ERR_ARG;
1536e8c27ec8Sbaban 		goto out;
1537e8c27ec8Sbaban 	}
1538c5c4113dSnw141292 	if (sql == NULL) {
1539c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
1540c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
1541c5c4113dSnw141292 		goto out;
1542c5c4113dSnw141292 	}
154348258c6bSjp151216 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol,
154448258c6bSjp151216 	    14, &values);
1545c5c4113dSnw141292 	sqlite_freemem(sql);
1546c5c4113dSnw141292 
1547c5c4113dSnw141292 	if (retcode == IDMAP_ERR_NOTFOUND) {
1548c5c4113dSnw141292 		goto out;
1549c5c4113dSnw141292 	} else if (retcode == IDMAP_SUCCESS) {
1550c5c4113dSnw141292 		/* sanity checks */
1551c5c4113dSnw141292 		if (values[0] == NULL || values[1] == NULL) {
1552c5c4113dSnw141292 			retcode = IDMAP_ERR_CACHE;
1553c5c4113dSnw141292 			goto out;
1554c5c4113dSnw141292 		}
1555c5c4113dSnw141292 
1556c5c4113dSnw141292 		pid = strtoul(values[0], &end, 10);
1557c5c4113dSnw141292 		is_user = strncmp(values[1], "0", 2) ? 1 : 0;
1558c5c4113dSnw141292 
1559cd37da74Snw141292 		if (is_user) {
1560cd37da74Snw141292 			res->id.idtype = IDMAP_UID;
1561cd37da74Snw141292 			res->id.idmap_id_u.uid = pid;
1562cd37da74Snw141292 		} else {
1563cd37da74Snw141292 			res->id.idtype = IDMAP_GID;
1564cd37da74Snw141292 			res->id.idmap_id_u.gid = pid;
1565cd37da74Snw141292 		}
1566cd37da74Snw141292 
1567c5c4113dSnw141292 		/*
1568c5c4113dSnw141292 		 * We may have an expired ephemeral mapping. Consider
1569c5c4113dSnw141292 		 * the expired entry as valid if we are not going to
1570c5c4113dSnw141292 		 * perform name-based mapping. But do not renew the
1571c5c4113dSnw141292 		 * expiration.
1572c5c4113dSnw141292 		 * If we will be doing name-based mapping then store the
1573c5c4113dSnw141292 		 * ephemeral pid in the result so that we can use it
1574c5c4113dSnw141292 		 * if we end up doing dynamic mapping again.
1575c5c4113dSnw141292 		 */
1576c5c4113dSnw141292 		if (!DO_NOT_ALLOC_NEW_ID_MAPPING(req) &&
1577cd37da74Snw141292 		    !AVOID_NAMESERVICE(req) &&
1578cd37da74Snw141292 		    IS_EPHEMERAL(pid) && values[2] != NULL) {
1579c5c4113dSnw141292 			exp = strtoll(values[2], &end, 10);
1580c5c4113dSnw141292 			if (exp && exp <= curtime) {
1581c5c4113dSnw141292 				/* Store the ephemeral pid */
1582651c0131Sbaban 				res->direction = IDMAP_DIRECTION_BI;
1583cd37da74Snw141292 				req->direction |= is_user
1584cd37da74Snw141292 				    ? _IDMAP_F_EXP_EPH_UID
1585cd37da74Snw141292 				    : _IDMAP_F_EXP_EPH_GID;
1586c5c4113dSnw141292 				retcode = IDMAP_ERR_NOTFOUND;
1587c5c4113dSnw141292 			}
1588c5c4113dSnw141292 		}
1589c5c4113dSnw141292 	}
1590c5c4113dSnw141292 
1591c5c4113dSnw141292 out:
1592c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
159362c60062Sbaban 		if (values[4] != NULL)
1594c5c4113dSnw141292 			res->direction =
1595651c0131Sbaban 			    (strtol(values[4], &end, 10) == 0)?
1596651c0131Sbaban 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
1597c5c4113dSnw141292 		else
1598651c0131Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
1599c5c4113dSnw141292 
160062c60062Sbaban 		if (values[3] != NULL) {
1601e8c27ec8Sbaban 			if (req->id2name != NULL)
1602e8c27ec8Sbaban 				free(req->id2name);
16038e228215Sdm199847 			req->id2name = strdup(values[3]);
16048e228215Sdm199847 			if (req->id2name == NULL) {
1605c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1606c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
1607c5c4113dSnw141292 			}
1608c5c4113dSnw141292 		}
1609e8c27ec8Sbaban 
1610e8c27ec8Sbaban 		req->id1.idtype = strncmp(values[5], "0", 2) ?
1611e8c27ec8Sbaban 		    IDMAP_USID : IDMAP_GSID;
161248258c6bSjp151216 
161348258c6bSjp151216 		if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
161448258c6bSjp151216 			res->info.src = IDMAP_MAP_SRC_CACHE;
161548258c6bSjp151216 			res->info.how.map_type = strtoul(values[6], &end, 10);
161648258c6bSjp151216 			switch (res->info.how.map_type) {
161748258c6bSjp151216 			case IDMAP_MAP_TYPE_DS_AD:
161848258c6bSjp151216 				res->info.how.idmap_how_u.ad.dn =
161948258c6bSjp151216 				    strdup(values[7]);
162048258c6bSjp151216 				res->info.how.idmap_how_u.ad.attr =
162148258c6bSjp151216 				    strdup(values[8]);
162248258c6bSjp151216 				res->info.how.idmap_how_u.ad.value =
162348258c6bSjp151216 				    strdup(values[9]);
162448258c6bSjp151216 				break;
162548258c6bSjp151216 
162648258c6bSjp151216 			case IDMAP_MAP_TYPE_DS_NLDAP:
162748258c6bSjp151216 				res->info.how.idmap_how_u.nldap.dn =
162848258c6bSjp151216 				    strdup(values[7]);
162948258c6bSjp151216 				res->info.how.idmap_how_u.nldap.attr =
163048258c6bSjp151216 				    strdup(values[8]);
163148258c6bSjp151216 				res->info.how.idmap_how_u.nldap.value =
163248258c6bSjp151216 				    strdup(values[9]);
163348258c6bSjp151216 				break;
163448258c6bSjp151216 
163548258c6bSjp151216 			case IDMAP_MAP_TYPE_RULE_BASED:
163648258c6bSjp151216 				res->info.how.idmap_how_u.rule.windomain =
163748258c6bSjp151216 				    strdup(values[10]);
163848258c6bSjp151216 				res->info.how.idmap_how_u.rule.winname =
163948258c6bSjp151216 				    strdup(values[11]);
164048258c6bSjp151216 				res->info.how.idmap_how_u.rule.unixname =
164148258c6bSjp151216 				    strdup(values[12]);
164248258c6bSjp151216 				res->info.how.idmap_how_u.rule.is_nt4 =
164348258c6bSjp151216 				    strtoul(values[13], &end, 1);
164448258c6bSjp151216 				res->info.how.idmap_how_u.rule.is_user =
164548258c6bSjp151216 				    is_user;
164648258c6bSjp151216 				res->info.how.idmap_how_u.rule.is_wuser =
164748258c6bSjp151216 				    strtoul(values[5], &end, 1);
164848258c6bSjp151216 				break;
164948258c6bSjp151216 
165048258c6bSjp151216 			case IDMAP_MAP_TYPE_EPHEMERAL:
165148258c6bSjp151216 				break;
165248258c6bSjp151216 
165348258c6bSjp151216 			case IDMAP_MAP_TYPE_LOCAL_SID:
165448258c6bSjp151216 				break;
165548258c6bSjp151216 
165648258c6bSjp151216 			case IDMAP_MAP_TYPE_KNOWN_SID:
165748258c6bSjp151216 				break;
165848258c6bSjp151216 
165948258c6bSjp151216 			default:
166048258c6bSjp151216 				/* Unknow mapping type */
166148258c6bSjp151216 				assert(FALSE);
166248258c6bSjp151216 			}
166348258c6bSjp151216 		}
1664c5c4113dSnw141292 	}
166562c60062Sbaban 	if (vm != NULL)
1666c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
1667c5c4113dSnw141292 	return (retcode);
1668c5c4113dSnw141292 }
1669c5c4113dSnw141292 
1670cd37da74Snw141292 static
1671cd37da74Snw141292 idmap_retcode
167262c60062Sbaban lookup_cache_sid2name(sqlite *cache, const char *sidprefix, idmap_rid_t rid,
1673cd37da74Snw141292 		char **name, char **domain, int *type)
1674cd37da74Snw141292 {
1675c5c4113dSnw141292 	char		*end;
1676c5c4113dSnw141292 	char		*sql = NULL;
1677c5c4113dSnw141292 	const char	**values;
1678c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
1679c5c4113dSnw141292 	int		ncol;
1680c5c4113dSnw141292 	time_t		curtime;
1681c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
1682c5c4113dSnw141292 
1683c5c4113dSnw141292 	/* Get current time */
1684c5c4113dSnw141292 	errno = 0;
1685c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
1686cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
1687c5c4113dSnw141292 		    strerror(errno));
1688c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
1689c5c4113dSnw141292 		goto out;
1690c5c4113dSnw141292 	}
1691c5c4113dSnw141292 
1692c5c4113dSnw141292 	/* SQL to lookup the cache */
1693cd37da74Snw141292 	sql = sqlite_mprintf("SELECT canon_name, domain, type "
1694cd37da74Snw141292 	    "FROM name_cache WHERE "
1695c5c4113dSnw141292 	    "sidprefix = %Q AND rid = %u AND "
1696c5c4113dSnw141292 	    "(expiration = 0 OR expiration ISNULL OR "
1697c5c4113dSnw141292 	    "expiration > %d);",
1698c5c4113dSnw141292 	    sidprefix, rid, curtime);
1699c5c4113dSnw141292 	if (sql == NULL) {
1700c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
1701c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
1702c5c4113dSnw141292 		goto out;
1703c5c4113dSnw141292 	}
1704c5c4113dSnw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 3, &values);
1705c5c4113dSnw141292 	sqlite_freemem(sql);
1706c5c4113dSnw141292 
1707c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
170862c60062Sbaban 		if (type != NULL) {
1709c5c4113dSnw141292 			if (values[2] == NULL) {
1710c5c4113dSnw141292 				retcode = IDMAP_ERR_CACHE;
1711c5c4113dSnw141292 				goto out;
1712c5c4113dSnw141292 			}
1713c5c4113dSnw141292 			*type = strtol(values[2], &end, 10);
1714c5c4113dSnw141292 		}
1715c5c4113dSnw141292 
171662c60062Sbaban 		if (name != NULL && values[0] != NULL) {
1717c5c4113dSnw141292 			if ((*name = strdup(values[0])) == NULL) {
1718c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1719c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
1720c5c4113dSnw141292 				goto out;
1721c5c4113dSnw141292 			}
1722c5c4113dSnw141292 		}
1723c5c4113dSnw141292 
172462c60062Sbaban 		if (domain != NULL && values[1] != NULL) {
1725c5c4113dSnw141292 			if ((*domain = strdup(values[1])) == NULL) {
172662c60062Sbaban 				if (name != NULL && *name) {
1727c5c4113dSnw141292 					free(*name);
1728c5c4113dSnw141292 					*name = NULL;
1729c5c4113dSnw141292 				}
1730c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1731c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
1732c5c4113dSnw141292 				goto out;
1733c5c4113dSnw141292 			}
1734c5c4113dSnw141292 		}
1735c5c4113dSnw141292 	}
1736c5c4113dSnw141292 
1737c5c4113dSnw141292 out:
173862c60062Sbaban 	if (vm != NULL)
1739c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
1740c5c4113dSnw141292 	return (retcode);
1741c5c4113dSnw141292 }
1742c5c4113dSnw141292 
1743c5c4113dSnw141292 /*
1744e8c27ec8Sbaban  * Given SID, find winname using name_cache OR
1745e8c27ec8Sbaban  * Given winname, find SID using name_cache.
1746e8c27ec8Sbaban  * Used when mapping win to unix i.e. req->id1 is windows id and
1747e8c27ec8Sbaban  * req->id2 is unix id
1748c5c4113dSnw141292  */
1749cd37da74Snw141292 static
1750cd37da74Snw141292 idmap_retcode
1751e8c27ec8Sbaban lookup_name_cache(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
1752cd37da74Snw141292 {
1753c5c4113dSnw141292 	int		type = -1;
1754c5c4113dSnw141292 	idmap_retcode	retcode;
1755e8c27ec8Sbaban 	char		*sidprefix = NULL;
1756c5c4113dSnw141292 	idmap_rid_t	rid;
1757c5c4113dSnw141292 	char		*name = NULL, *domain = NULL;
1758c5c4113dSnw141292 
1759e8c27ec8Sbaban 	/* Done if we've both sid and winname */
1760e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL && req->id1name != NULL)
1761e8c27ec8Sbaban 		return (IDMAP_SUCCESS);
1762c5c4113dSnw141292 
1763e8c27ec8Sbaban 	/* Lookup sid to winname */
1764e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
1765e8c27ec8Sbaban 		retcode = lookup_cache_sid2name(cache,
1766e8c27ec8Sbaban 		    req->id1.idmap_id_u.sid.prefix,
1767e8c27ec8Sbaban 		    req->id1.idmap_id_u.sid.rid, &name, &domain, &type);
176862c60062Sbaban 		goto out;
1769e8c27ec8Sbaban 	}
177062c60062Sbaban 
1771e8c27ec8Sbaban 	/* Lookup winame to sid */
1772e8c27ec8Sbaban 	retcode = lookup_cache_name2sid(cache, req->id1name, req->id1domain,
1773e8c27ec8Sbaban 	    &name, &sidprefix, &rid, &type);
1774c5c4113dSnw141292 
177562c60062Sbaban out:
1776e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
1777c5c4113dSnw141292 		free(name);
1778c5c4113dSnw141292 		free(domain);
1779e8c27ec8Sbaban 		free(sidprefix);
1780e8c27ec8Sbaban 		return (retcode);
1781e8c27ec8Sbaban 	}
1782e8c27ec8Sbaban 
1783e8c27ec8Sbaban 	if (res->id.idtype == IDMAP_POSIXID) {
1784e8c27ec8Sbaban 		res->id.idtype = (type == _IDMAP_T_USER) ?
1785e8c27ec8Sbaban 		    IDMAP_UID : IDMAP_GID;
1786e8c27ec8Sbaban 	}
1787e8c27ec8Sbaban 	req->id1.idtype = (type == _IDMAP_T_USER) ?
1788e8c27ec8Sbaban 	    IDMAP_USID : IDMAP_GSID;
1789e8c27ec8Sbaban 
1790e8c27ec8Sbaban 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
1791e8c27ec8Sbaban 	if (name != NULL) {
1792e8c27ec8Sbaban 		free(req->id1name);	/* Free existing winname */
1793e8c27ec8Sbaban 		req->id1name = name;	/* and use canonical name instead */
1794e8c27ec8Sbaban 	}
1795e8c27ec8Sbaban 	if (req->id1domain == NULL)
1796e8c27ec8Sbaban 		req->id1domain = domain;
1797e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix == NULL) {
1798e8c27ec8Sbaban 		req->id1.idmap_id_u.sid.prefix = sidprefix;
1799e8c27ec8Sbaban 		req->id1.idmap_id_u.sid.rid = rid;
1800c5c4113dSnw141292 	}
1801c5c4113dSnw141292 	return (retcode);
1802c5c4113dSnw141292 }
1803c5c4113dSnw141292 
1804*4d61c878SJulian Pullen 
1805*4d61c878SJulian Pullen 
1806*4d61c878SJulian Pullen static int
1807*4d61c878SJulian Pullen ad_lookup_batch_int(lookup_state_t *state, idmap_mapping_batch *batch,
1808*4d61c878SJulian Pullen 		idmap_ids_res *result, int index, int *num_processed)
1809cd37da74Snw141292 {
1810c5c4113dSnw141292 	idmap_retcode	retcode;
1811*4d61c878SJulian Pullen 	int		i,  num_queued, type, is_wuser, is_user;
1812*4d61c878SJulian Pullen 	int		next_request;
1813e8c27ec8Sbaban 	int		retries = 0, eunixtype;
1814e8c27ec8Sbaban 	char		**unixname;
1815c5c4113dSnw141292 	idmap_mapping	*req;
1816c5c4113dSnw141292 	idmap_id_res	*res;
1817e8c27ec8Sbaban 	idmap_query_state_t	*qs = NULL;
181848258c6bSjp151216 	idmap_how	*how;
1819479ac375Sdm199847 	char		**dn, **attr, **value;
1820e8c27ec8Sbaban 
1821*4d61c878SJulian Pullen 	*num_processed = 0;
1822*4d61c878SJulian Pullen 
1823e8c27ec8Sbaban 	/*
1824e8c27ec8Sbaban 	 * Since req->id2.idtype is unused, we will use it here
1825e8c27ec8Sbaban 	 * to retrieve the value of sid_type. But it needs to be
1826e8c27ec8Sbaban 	 * reset to IDMAP_NONE before we return to prevent xdr
1827e8c27ec8Sbaban 	 * from mis-interpreting req->id2 when it tries to free
1828e8c27ec8Sbaban 	 * the input argument. Other option is to allocate an
1829e8c27ec8Sbaban 	 * array of integers and use it instead for the batched
1830e8c27ec8Sbaban 	 * call. But why un-necessarily allocate memory. That may
1831e8c27ec8Sbaban 	 * be an option if req->id2.idtype cannot be re-used in
1832e8c27ec8Sbaban 	 * future.
1833e8c27ec8Sbaban 	 */
1834c5c4113dSnw141292 retry:
1835*4d61c878SJulian Pullen 	retcode = idmap_lookup_batch_start(_idmapdstate.ads[index],
1836*4d61c878SJulian Pullen 	    state->ad_nqueries, &qs);
1837e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
18382b4a7802SBaban Kenkre 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
18392b4a7802SBaban Kenkre 		    retries++ < ADUTILS_DEF_NUM_RETRIES)
18400dcc7149Snw141292 			goto retry;
1841349d5d8fSnw141292 		degrade_svc(1, "failed to create batch for AD lookup");
1842e8c27ec8Sbaban 			goto out;
1843c5c4113dSnw141292 	}
1844*4d61c878SJulian Pullen 	num_queued = 0;
1845c5c4113dSnw141292 
1846c8e26105Sjp151216 	restore_svc();
1847c8e26105Sjp151216 
1848*4d61c878SJulian Pullen 	if (index == 0) {
1849*4d61c878SJulian Pullen 		/*
1850*4d61c878SJulian Pullen 		 * Directory based name mapping is only performed within the
1851*4d61c878SJulian Pullen 		 * joined forest (index == 0).  We don't trust other "trusted"
1852*4d61c878SJulian Pullen 		 * forests to provide DS-based name mapping information because
1853*4d61c878SJulian Pullen 		 * AD's definition of "cross-forest trust" does not encompass
1854*4d61c878SJulian Pullen 		 * this sort of behavior.
1855*4d61c878SJulian Pullen 		 */
1856*4d61c878SJulian Pullen 		idmap_lookup_batch_set_unixattr(qs,
1857*4d61c878SJulian Pullen 		    state->ad_unixuser_attr, state->ad_unixgroup_attr);
1858*4d61c878SJulian Pullen 	}
1859e8c27ec8Sbaban 
1860*4d61c878SJulian Pullen 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
1861c5c4113dSnw141292 		req = &batch->idmap_mapping_batch_val[i];
1862c5c4113dSnw141292 		res = &result->ids.ids_val[i];
186348258c6bSjp151216 		how = &res->info.how;
186448258c6bSjp151216 
1865e8c27ec8Sbaban 		retcode = IDMAP_SUCCESS;
1866e8c27ec8Sbaban 		req->id2.idtype = IDMAP_NONE;
1867c5c4113dSnw141292 
1868*4d61c878SJulian Pullen 		/* Skip if not marked for this AD lookup */
1869*4d61c878SJulian Pullen 		if (!(req->direction & _IDMAP_F_LOOKUP_AD) ||
1870*4d61c878SJulian Pullen 		    (req->direction & _IDMAP_F_LOOKUP_OTHER_AD))
1871e8c27ec8Sbaban 			continue;
1872e8c27ec8Sbaban 
187396c3a9a0Sbaban 		if (res->retcode != IDMAP_ERR_RETRIABLE_NET_ERR)
1874c5c4113dSnw141292 			continue;
1875e8c27ec8Sbaban 
1876e8c27ec8Sbaban 		if (IS_REQUEST_SID(*req, 1)) {
1877e8c27ec8Sbaban 
1878479ac375Sdm199847 			/* win2unix request: */
1879e8c27ec8Sbaban 
1880479ac375Sdm199847 			unixname = dn = attr = value = NULL;
1881e8c27ec8Sbaban 			eunixtype = _IDMAP_T_UNDEF;
1882e8c27ec8Sbaban 			if (req->id2name == NULL) {
1883e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_UID &&
1884e8c27ec8Sbaban 				    AD_OR_MIXED(state->nm_siduid)) {
1885e8c27ec8Sbaban 					eunixtype = _IDMAP_T_USER;
1886e8c27ec8Sbaban 					unixname = &req->id2name;
1887e8c27ec8Sbaban 				} else if (res->id.idtype == IDMAP_GID &&
1888e8c27ec8Sbaban 				    AD_OR_MIXED(state->nm_sidgid)) {
1889e8c27ec8Sbaban 					eunixtype = _IDMAP_T_GROUP;
1890e8c27ec8Sbaban 					unixname = &req->id2name;
1891e8c27ec8Sbaban 				} else if (AD_OR_MIXED(state->nm_siduid) ||
1892e8c27ec8Sbaban 				    AD_OR_MIXED(state->nm_sidgid)) {
1893e8c27ec8Sbaban 					unixname = &req->id2name;
1894e8c27ec8Sbaban 				}
1895e8c27ec8Sbaban 			}
1896*4d61c878SJulian Pullen 
1897479ac375Sdm199847 			if (unixname != NULL) {
1898479ac375Sdm199847 				/*
1899479ac375Sdm199847 				 * Get how info for DS-based name
1900479ac375Sdm199847 				 * mapping only if AD or MIXED
1901479ac375Sdm199847 				 * mode is enabled.
1902479ac375Sdm199847 				 */
1903479ac375Sdm199847 				idmap_info_free(&res->info);
190448258c6bSjp151216 				res->info.src = IDMAP_MAP_SRC_NEW;
190548258c6bSjp151216 				how->map_type = IDMAP_MAP_TYPE_DS_AD;
1906479ac375Sdm199847 				dn = &how->idmap_how_u.ad.dn;
1907479ac375Sdm199847 				attr = &how->idmap_how_u.ad.attr;
1908479ac375Sdm199847 				value = &how->idmap_how_u.ad.value;
1909479ac375Sdm199847 			}
1910479ac375Sdm199847 			if (req->id1.idmap_id_u.sid.prefix != NULL) {
1911479ac375Sdm199847 				/* Lookup AD by SID */
1912c5c4113dSnw141292 				retcode = idmap_sid2name_batch_add1(
1913e8c27ec8Sbaban 				    qs, req->id1.idmap_id_u.sid.prefix,
1914e8c27ec8Sbaban 				    &req->id1.idmap_id_u.sid.rid, eunixtype,
1915479ac375Sdm199847 				    dn, attr, value,
1916479ac375Sdm199847 				    (req->id1name == NULL) ?
1917479ac375Sdm199847 				    &req->id1name : NULL,
1918479ac375Sdm199847 				    (req->id1domain == NULL) ?
1919479ac375Sdm199847 				    &req->id1domain : NULL,
1920479ac375Sdm199847 				    (int *)&req->id2.idtype, unixname,
1921479ac375Sdm199847 				    &res->retcode);
1922*4d61c878SJulian Pullen 				if (retcode == IDMAP_SUCCESS)
1923*4d61c878SJulian Pullen 					num_queued++;
1924479ac375Sdm199847 			} else {
1925479ac375Sdm199847 				/* Lookup AD by winname */
1926479ac375Sdm199847 				assert(req->id1name != NULL);
1927479ac375Sdm199847 				retcode = idmap_name2sid_batch_add1(
1928479ac375Sdm199847 				    qs, req->id1name, req->id1domain,
1929479ac375Sdm199847 				    eunixtype,
1930479ac375Sdm199847 				    dn, attr, value,
1931479ac375Sdm199847 				    &req->id1name,
1932479ac375Sdm199847 				    &req->id1.idmap_id_u.sid.prefix,
1933479ac375Sdm199847 				    &req->id1.idmap_id_u.sid.rid,
1934479ac375Sdm199847 				    (int *)&req->id2.idtype, unixname,
1935479ac375Sdm199847 				    &res->retcode);
1936*4d61c878SJulian Pullen 				if (retcode == IDMAP_SUCCESS)
1937*4d61c878SJulian Pullen 					num_queued++;
1938479ac375Sdm199847 			}
1939c5c4113dSnw141292 
1940e8c27ec8Sbaban 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
1941479ac375Sdm199847 
1942479ac375Sdm199847 			/* unix2win request: */
1943e8c27ec8Sbaban 
1944e8c27ec8Sbaban 			if (res->id.idmap_id_u.sid.prefix != NULL &&
1945e8c27ec8Sbaban 			    req->id2name != NULL) {
1946*4d61c878SJulian Pullen 				/* Already have SID and winname. done */
1947e8c27ec8Sbaban 				res->retcode = IDMAP_SUCCESS;
1948e8c27ec8Sbaban 				continue;
1949c5c4113dSnw141292 			}
1950c5c4113dSnw141292 
1951e8c27ec8Sbaban 			if (res->id.idmap_id_u.sid.prefix != NULL) {
1952cd37da74Snw141292 				/*
1953e8c27ec8Sbaban 				 * SID but no winname -- lookup AD by
1954e8c27ec8Sbaban 				 * SID to get winname.
1955479ac375Sdm199847 				 * how info is not needed here because
1956479ac375Sdm199847 				 * we are not retrieving unixname from
1957479ac375Sdm199847 				 * AD.
1958cd37da74Snw141292 				 */
1959*4d61c878SJulian Pullen 
1960e8c27ec8Sbaban 				retcode = idmap_sid2name_batch_add1(
1961e8c27ec8Sbaban 				    qs, res->id.idmap_id_u.sid.prefix,
1962e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.rid,
196348258c6bSjp151216 				    _IDMAP_T_UNDEF,
1964479ac375Sdm199847 				    NULL, NULL, NULL,
196548258c6bSjp151216 				    &req->id2name,
1966e8c27ec8Sbaban 				    &req->id2domain, (int *)&req->id2.idtype,
1967e8c27ec8Sbaban 				    NULL, &res->retcode);
1968*4d61c878SJulian Pullen 				if (retcode == IDMAP_SUCCESS)
1969*4d61c878SJulian Pullen 					num_queued++;
1970e8c27ec8Sbaban 			} else if (req->id2name != NULL) {
1971e8c27ec8Sbaban 				/*
1972e8c27ec8Sbaban 				 * winname but no SID -- lookup AD by
1973e8c27ec8Sbaban 				 * winname to get SID.
1974479ac375Sdm199847 				 * how info is not needed here because
1975479ac375Sdm199847 				 * we are not retrieving unixname from
1976479ac375Sdm199847 				 * AD.
1977e8c27ec8Sbaban 				 */
1978e8c27ec8Sbaban 				retcode = idmap_name2sid_batch_add1(
1979e8c27ec8Sbaban 				    qs, req->id2name, req->id2domain,
198048258c6bSjp151216 				    _IDMAP_T_UNDEF,
1981479ac375Sdm199847 				    NULL, NULL, NULL, NULL,
1982e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.prefix,
1983e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.rid,
1984e8c27ec8Sbaban 				    (int *)&req->id2.idtype, NULL,
1985e8c27ec8Sbaban 				    &res->retcode);
1986*4d61c878SJulian Pullen 				if (retcode == IDMAP_SUCCESS)
1987*4d61c878SJulian Pullen 					num_queued++;
1988e8c27ec8Sbaban 			} else if (req->id1name != NULL) {
1989e8c27ec8Sbaban 				/*
1990*4d61c878SJulian Pullen 				 * No SID and no winname but we've unixname.
1991*4d61c878SJulian Pullen 				 * Lookup AD by unixname to get SID.
1992e8c27ec8Sbaban 				 */
1993e8c27ec8Sbaban 				is_user = (IS_REQUEST_UID(*req)) ? 1 : 0;
1994e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_USID)
1995e8c27ec8Sbaban 					is_wuser = 1;
1996e8c27ec8Sbaban 				else if (res->id.idtype == IDMAP_GSID)
1997e8c27ec8Sbaban 					is_wuser = 0;
1998e8c27ec8Sbaban 				else
1999e8c27ec8Sbaban 					is_wuser = is_user;
2000*4d61c878SJulian Pullen 
2001479ac375Sdm199847 				idmap_info_free(&res->info);
200248258c6bSjp151216 				res->info.src = IDMAP_MAP_SRC_NEW;
200348258c6bSjp151216 				how->map_type = IDMAP_MAP_TYPE_DS_AD;
2004e8c27ec8Sbaban 				retcode = idmap_unixname2sid_batch_add1(
2005e8c27ec8Sbaban 				    qs, req->id1name, is_user, is_wuser,
200648258c6bSjp151216 				    &how->idmap_how_u.ad.dn,
200748258c6bSjp151216 				    &how->idmap_how_u.ad.attr,
200848258c6bSjp151216 				    &how->idmap_how_u.ad.value,
2009e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.prefix,
2010e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.rid,
2011e8c27ec8Sbaban 				    &req->id2name, &req->id2domain,
2012e8c27ec8Sbaban 				    (int *)&req->id2.idtype, &res->retcode);
2013*4d61c878SJulian Pullen 				if (retcode == IDMAP_SUCCESS)
2014*4d61c878SJulian Pullen 					num_queued++;
2015e8c27ec8Sbaban 			}
2016cd37da74Snw141292 		}
2017cd37da74Snw141292 
2018*4d61c878SJulian Pullen 		if (retcode == IDMAP_ERR_DOMAIN_NOTFOUND) {
2019*4d61c878SJulian Pullen 			req->direction |= _IDMAP_F_LOOKUP_OTHER_AD;
2020*4d61c878SJulian Pullen 			retcode = IDMAP_SUCCESS;
2021*4d61c878SJulian Pullen 		} else if (retcode != IDMAP_SUCCESS) {
2022*4d61c878SJulian Pullen 			idmap_lookup_release_batch(&qs);
2023*4d61c878SJulian Pullen 			num_queued = 0;
2024*4d61c878SJulian Pullen 			next_request = i + 1;
2025*4d61c878SJulian Pullen 			break;
2026*4d61c878SJulian Pullen 		}
2027*4d61c878SJulian Pullen 	} /* End of for loop */
2028*4d61c878SJulian Pullen 
202996c3a9a0Sbaban 	if (retcode == IDMAP_SUCCESS) {
203096c3a9a0Sbaban 		/* add keeps track if we added an entry to the batch */
2031*4d61c878SJulian Pullen 		if (num_queued > 0)
20320dcc7149Snw141292 			retcode = idmap_lookup_batch_end(&qs);
203396c3a9a0Sbaban 		else
203496c3a9a0Sbaban 			idmap_lookup_release_batch(&qs);
203596c3a9a0Sbaban 	}
2036cd37da74Snw141292 
20372b4a7802SBaban Kenkre 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
20382b4a7802SBaban Kenkre 	    retries++ < ADUTILS_DEF_NUM_RETRIES)
2039c5c4113dSnw141292 		goto retry;
2040c8e26105Sjp151216 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
2041349d5d8fSnw141292 		degrade_svc(1, "some AD lookups timed out repeatedly");
2042c5c4113dSnw141292 
2043*4d61c878SJulian Pullen 	if (retcode != IDMAP_SUCCESS) {
2044*4d61c878SJulian Pullen 		/* Mark any unproccessed requests for an other AD */
2045*4d61c878SJulian Pullen 		for (i = next_request; i < batch->idmap_mapping_batch_len;
2046*4d61c878SJulian Pullen 		    i++) {
2047*4d61c878SJulian Pullen 			req = &batch->idmap_mapping_batch_val[i];
2048*4d61c878SJulian Pullen 			req->direction |= _IDMAP_F_LOOKUP_OTHER_AD;
2049*4d61c878SJulian Pullen 
2050*4d61c878SJulian Pullen 		}
2051*4d61c878SJulian Pullen 	}
2052*4d61c878SJulian Pullen 
2053e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
2054e8c27ec8Sbaban 		idmapdlog(LOG_NOTICE, "Failed to batch AD lookup requests");
2055c5c4113dSnw141292 
2056c5c4113dSnw141292 out:
2057e8c27ec8Sbaban 	/*
2058e8c27ec8Sbaban 	 * This loop does the following:
2059479ac375Sdm199847 	 * 1. Reset _IDMAP_F_LOOKUP_AD flag from the request.
2060479ac375Sdm199847 	 * 2. Reset req->id2.idtype to IDMAP_NONE
2061479ac375Sdm199847 	 * 3. If batch_start or batch_add failed then set the status
2062479ac375Sdm199847 	 *    of each request marked for AD lookup to that error.
2063*4d61c878SJulian Pullen 	 * 4. Evaluate the type of the AD object (i.e. user or group)
2064*4d61c878SJulian Pullen 	 *    and update the idtype in request.
2065e8c27ec8Sbaban 	 */
2066e8c27ec8Sbaban 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
2067e8c27ec8Sbaban 		req = &batch->idmap_mapping_batch_val[i];
2068e8c27ec8Sbaban 		type = req->id2.idtype;
2069e8c27ec8Sbaban 		req->id2.idtype = IDMAP_NONE;
20705e0794bcSbaban 		res = &result->ids.ids_val[i];
207148258c6bSjp151216 		how = &res->info.how;
2072*4d61c878SJulian Pullen 		if (!(req->direction & _IDMAP_F_LOOKUP_AD) ||
2073*4d61c878SJulian Pullen 		    (req->direction & _IDMAP_F_LOOKUP_OTHER_AD))
2074e8c27ec8Sbaban 			continue;
2075e8c27ec8Sbaban 
2076*4d61c878SJulian Pullen 		/* Count number processed */
2077*4d61c878SJulian Pullen 		(*num_processed)++;
2078*4d61c878SJulian Pullen 
2079479ac375Sdm199847 		/* Reset AD lookup flag */
2080479ac375Sdm199847 		req->direction &= ~(_IDMAP_F_LOOKUP_AD);
2081479ac375Sdm199847 
2082479ac375Sdm199847 		/*
2083*4d61c878SJulian Pullen 		 * If batch_start or batch_add failed then set the
2084*4d61c878SJulian Pullen 		 * status of each request marked for AD lookup to
2085*4d61c878SJulian Pullen 		 * that error.
2086479ac375Sdm199847 		 */
2087e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS) {
2088e8c27ec8Sbaban 			res->retcode = retcode;
2089e8c27ec8Sbaban 			continue;
2090e8c27ec8Sbaban 		}
2091e8c27ec8Sbaban 
209248258c6bSjp151216 		if (res->retcode == IDMAP_ERR_NOTFOUND) {
209348258c6bSjp151216 			/* Nothing found - remove the preset info */
2094479ac375Sdm199847 			idmap_info_free(&res->info);
209548258c6bSjp151216 		}
209648258c6bSjp151216 
2097e8c27ec8Sbaban 		if (IS_REQUEST_SID(*req, 1)) {
2098e8c27ec8Sbaban 			if (res->retcode != IDMAP_SUCCESS)
2099e8c27ec8Sbaban 				continue;
2100479ac375Sdm199847 			/* Evaluate result type */
2101e8c27ec8Sbaban 			switch (type) {
2102e8c27ec8Sbaban 			case _IDMAP_T_USER:
2103e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
2104e8c27ec8Sbaban 					res->id.idtype = IDMAP_UID;
2105e8c27ec8Sbaban 				req->id1.idtype = IDMAP_USID;
2106e8c27ec8Sbaban 				break;
2107*4d61c878SJulian Pullen 
2108e8c27ec8Sbaban 			case _IDMAP_T_GROUP:
2109e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
2110e8c27ec8Sbaban 					res->id.idtype = IDMAP_GID;
2111e8c27ec8Sbaban 				req->id1.idtype = IDMAP_GSID;
2112e8c27ec8Sbaban 				break;
2113*4d61c878SJulian Pullen 
2114e8c27ec8Sbaban 			default:
2115e8c27ec8Sbaban 				res->retcode = IDMAP_ERR_SID;
2116e8c27ec8Sbaban 				break;
2117e8c27ec8Sbaban 			}
2118479ac375Sdm199847 			if (res->retcode == IDMAP_SUCCESS &&
2119479ac375Sdm199847 			    req->id1name != NULL &&
2120479ac375Sdm199847 			    (req->id2name == NULL ||
2121479ac375Sdm199847 			    res->id.idmap_id_u.uid == SENTINEL_PID) &&
2122479ac375Sdm199847 			    NLDAP_MODE(res->id.idtype, state)) {
2123479ac375Sdm199847 				req->direction |= _IDMAP_F_LOOKUP_NLDAP;
2124479ac375Sdm199847 				state->nldap_nqueries++;
2125479ac375Sdm199847 			}
2126e8c27ec8Sbaban 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
2127e8c27ec8Sbaban 			if (res->retcode != IDMAP_SUCCESS) {
2128e8c27ec8Sbaban 				if ((!(IDMAP_FATAL_ERROR(res->retcode))) &&
2129e8c27ec8Sbaban 				    res->id.idmap_id_u.sid.prefix == NULL &&
2130e8c27ec8Sbaban 				    req->id2name == NULL && /* no winname */
2131e8c27ec8Sbaban 				    req->id1name != NULL) /* unixname */
2132e8c27ec8Sbaban 					/*
2133*4d61c878SJulian Pullen 					 * If AD lookup by unixname
2134*4d61c878SJulian Pullen 					 * failed with non fatal error
2135*4d61c878SJulian Pullen 					 * then clear the error (ie set
2136*4d61c878SJulian Pullen 					 * res->retcode to success).
2137*4d61c878SJulian Pullen 					 * This allows the next pass to
2138*4d61c878SJulian Pullen 					 * process other mapping
2139479ac375Sdm199847 					 * mechanisms for this request.
2140e8c27ec8Sbaban 					 */
2141e8c27ec8Sbaban 					res->retcode = IDMAP_SUCCESS;
2142e8c27ec8Sbaban 				continue;
2143e8c27ec8Sbaban 			}
2144479ac375Sdm199847 			/* Evaluate result type */
2145e8c27ec8Sbaban 			switch (type) {
2146e8c27ec8Sbaban 			case _IDMAP_T_USER:
2147e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_SID)
2148e8c27ec8Sbaban 					res->id.idtype = IDMAP_USID;
2149e8c27ec8Sbaban 				break;
2150*4d61c878SJulian Pullen 
2151e8c27ec8Sbaban 			case _IDMAP_T_GROUP:
2152e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_SID)
2153e8c27ec8Sbaban 					res->id.idtype = IDMAP_GSID;
2154e8c27ec8Sbaban 				break;
2155*4d61c878SJulian Pullen 
2156e8c27ec8Sbaban 			default:
2157e8c27ec8Sbaban 				res->retcode = IDMAP_ERR_SID;
2158e8c27ec8Sbaban 				break;
2159e8c27ec8Sbaban 			}
2160e8c27ec8Sbaban 		}
2161e8c27ec8Sbaban 	}
2162e8c27ec8Sbaban 
2163*4d61c878SJulian Pullen 	return (retcode);
2164*4d61c878SJulian Pullen }
2165*4d61c878SJulian Pullen 
2166*4d61c878SJulian Pullen 
2167*4d61c878SJulian Pullen 
2168*4d61c878SJulian Pullen /*
2169*4d61c878SJulian Pullen  * Batch AD lookups
2170*4d61c878SJulian Pullen  */
2171*4d61c878SJulian Pullen idmap_retcode
2172*4d61c878SJulian Pullen ad_lookup_batch(lookup_state_t *state, idmap_mapping_batch *batch,
2173*4d61c878SJulian Pullen 		idmap_ids_res *result)
2174*4d61c878SJulian Pullen {
2175*4d61c878SJulian Pullen 	idmap_retcode	retcode;
2176*4d61c878SJulian Pullen 	int		i, j;
2177*4d61c878SJulian Pullen 	idmap_mapping	*req;
2178*4d61c878SJulian Pullen 	idmap_id_res	*res;
2179*4d61c878SJulian Pullen 	int		num_queries;
2180*4d61c878SJulian Pullen 	int		num_processed;
2181*4d61c878SJulian Pullen 
2182*4d61c878SJulian Pullen 	if (state->ad_nqueries == 0)
2183*4d61c878SJulian Pullen 		return (IDMAP_SUCCESS);
2184*4d61c878SJulian Pullen 
2185*4d61c878SJulian Pullen 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
2186*4d61c878SJulian Pullen 		req = &batch->idmap_mapping_batch_val[i];
2187*4d61c878SJulian Pullen 		res = &result->ids.ids_val[i];
2188*4d61c878SJulian Pullen 
2189*4d61c878SJulian Pullen 		/* Skip if not marked for AD lookup or already in error. */
2190*4d61c878SJulian Pullen 		if (!(req->direction & _IDMAP_F_LOOKUP_AD) ||
2191*4d61c878SJulian Pullen 		    res->retcode != IDMAP_SUCCESS)
2192*4d61c878SJulian Pullen 			continue;
2193*4d61c878SJulian Pullen 
2194*4d61c878SJulian Pullen 		/* Init status */
2195*4d61c878SJulian Pullen 		res->retcode = IDMAP_ERR_RETRIABLE_NET_ERR;
2196*4d61c878SJulian Pullen 	}
2197*4d61c878SJulian Pullen 
2198*4d61c878SJulian Pullen 	RDLOCK_CONFIG();
2199*4d61c878SJulian Pullen 	num_queries = state->ad_nqueries;
2200*4d61c878SJulian Pullen 	if (_idmapdstate.num_ads > 0) {
2201*4d61c878SJulian Pullen 		for (i = 0; i < _idmapdstate.num_ads && num_queries > 0; i++) {
2202*4d61c878SJulian Pullen 
2203*4d61c878SJulian Pullen 			retcode = ad_lookup_batch_int(state, batch, result, i,
2204*4d61c878SJulian Pullen 			    &num_processed);
2205*4d61c878SJulian Pullen 			num_queries -= num_processed;
2206*4d61c878SJulian Pullen 
2207*4d61c878SJulian Pullen 			if (num_queries > 0) {
2208*4d61c878SJulian Pullen 				for (j = 0; j < batch->idmap_mapping_batch_len;
2209*4d61c878SJulian Pullen 				    j++) {
2210*4d61c878SJulian Pullen 					req =
2211*4d61c878SJulian Pullen 					    &batch->idmap_mapping_batch_val[j];
2212*4d61c878SJulian Pullen 					res = &result->ids.ids_val[j];
2213*4d61c878SJulian Pullen 					if (!(req->direction &
2214*4d61c878SJulian Pullen 					    _IDMAP_F_LOOKUP_AD))
2215*4d61c878SJulian Pullen 						continue;
2216*4d61c878SJulian Pullen 					/*
2217*4d61c878SJulian Pullen 					 * Reset the other AD lookup flag so
2218*4d61c878SJulian Pullen 					 * that we can try the next AD
2219*4d61c878SJulian Pullen 					 */
2220*4d61c878SJulian Pullen 					req->direction &=
2221*4d61c878SJulian Pullen 					    ~(_IDMAP_F_LOOKUP_OTHER_AD);
2222*4d61c878SJulian Pullen 
2223*4d61c878SJulian Pullen 					if ((i + 1) >= _idmapdstate.num_ads) {
2224*4d61c878SJulian Pullen 						/*
2225*4d61c878SJulian Pullen 						 * There are no more ADs to try
2226*4d61c878SJulian Pullen 						 */
2227*4d61c878SJulian Pullen 						req->direction &=
2228*4d61c878SJulian Pullen 						    ~(_IDMAP_F_LOOKUP_AD);
2229*4d61c878SJulian Pullen 						res->retcode =
2230*4d61c878SJulian Pullen 						    IDMAP_ERR_DOMAIN_NOTFOUND;
2231*4d61c878SJulian Pullen 					}
2232*4d61c878SJulian Pullen 				}
2233*4d61c878SJulian Pullen 			}
2234*4d61c878SJulian Pullen 		}
2235*4d61c878SJulian Pullen 	} else {
2236*4d61c878SJulian Pullen 		/* Case of no ADs */
2237*4d61c878SJulian Pullen 		retcode = IDMAP_ERR_NO_ACTIVEDIRECTORY;
2238*4d61c878SJulian Pullen 		for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
2239*4d61c878SJulian Pullen 			req = &batch->idmap_mapping_batch_val[i];
2240*4d61c878SJulian Pullen 			res = &result->ids.ids_val[i];
2241*4d61c878SJulian Pullen 			if (!(req->direction & _IDMAP_F_LOOKUP_AD))
2242*4d61c878SJulian Pullen 				continue;
2243*4d61c878SJulian Pullen 			req->direction &= ~(_IDMAP_F_LOOKUP_AD);
2244*4d61c878SJulian Pullen 			res->retcode = IDMAP_ERR_NO_ACTIVEDIRECTORY;
2245*4d61c878SJulian Pullen 		}
2246*4d61c878SJulian Pullen 	}
2247*4d61c878SJulian Pullen 	UNLOCK_CONFIG();
2248*4d61c878SJulian Pullen 
2249e8c27ec8Sbaban 	/* AD lookups done. Reset state->ad_nqueries and return */
2250e8c27ec8Sbaban 	state->ad_nqueries = 0;
2251c5c4113dSnw141292 	return (retcode);
2252c5c4113dSnw141292 }
2253c5c4113dSnw141292 
2254cd37da74Snw141292 /*
2255cd37da74Snw141292  * Convention when processing win2unix requests:
2256cd37da74Snw141292  *
2257cd37da74Snw141292  * Windows identity:
2258cd37da74Snw141292  * req->id1name =
2259cd37da74Snw141292  *              winname if given otherwise winname found will be placed
2260cd37da74Snw141292  *              here.
2261cd37da74Snw141292  * req->id1domain =
2262cd37da74Snw141292  *              windomain if given otherwise windomain found will be
2263cd37da74Snw141292  *              placed here.
2264cd37da74Snw141292  * req->id1.idtype =
2265cd37da74Snw141292  *              Either IDMAP_SID/USID/GSID. If this is IDMAP_SID then it'll
2266cd37da74Snw141292  *              be set to IDMAP_USID/GSID depending upon whether the
2267cd37da74Snw141292  *              given SID is user or group respectively. The user/group-ness
2268cd37da74Snw141292  *              is determined either when looking up well-known SIDs table OR
2269479ac375Sdm199847  *              if the SID is found in namecache OR by ad_lookup_one() OR by
2270cd37da74Snw141292  *              ad_lookup_batch().
2271cd37da74Snw141292  * req->id1..sid.[prefix, rid] =
2272cd37da74Snw141292  *              SID if given otherwise SID found will be placed here.
2273cd37da74Snw141292  *
2274cd37da74Snw141292  * Unix identity:
2275cd37da74Snw141292  * req->id2name =
2276cd37da74Snw141292  *              unixname found will be placed here.
2277cd37da74Snw141292  * req->id2domain =
2278cd37da74Snw141292  *              NOT USED
2279cd37da74Snw141292  * res->id.idtype =
2280cd37da74Snw141292  *              Target type initialized from req->id2.idtype. If
2281cd37da74Snw141292  *              it is IDMAP_POSIXID then actual type (IDMAP_UID/GID) found
2282cd37da74Snw141292  *              will be placed here.
2283cd37da74Snw141292  * res->id..[uid or gid] =
2284cd37da74Snw141292  *              UID/GID found will be placed here.
2285cd37da74Snw141292  *
2286cd37da74Snw141292  * Others:
2287cd37da74Snw141292  * res->retcode =
2288cd37da74Snw141292  *              Return status for this request will be placed here.
2289cd37da74Snw141292  * res->direction =
2290cd37da74Snw141292  *              Direction found will be placed here. Direction
2291cd37da74Snw141292  *              meaning whether the resultant mapping is valid
2292cd37da74Snw141292  *              only from win2unix or bi-directional.
2293cd37da74Snw141292  * req->direction =
2294cd37da74Snw141292  *              INTERNAL USE. Used by idmapd to set various
2295cd37da74Snw141292  *              flags (_IDMAP_F_xxxx) to aid in processing
2296cd37da74Snw141292  *              of the request.
2297cd37da74Snw141292  * req->id2.idtype =
2298cd37da74Snw141292  *              INTERNAL USE. Initially this is the requested target
2299cd37da74Snw141292  *              type and is used to initialize res->id.idtype.
2300cd37da74Snw141292  *              ad_lookup_batch() uses this field temporarily to store
2301cd37da74Snw141292  *              sid_type obtained by the batched AD lookups and after
2302cd37da74Snw141292  *              use resets it to IDMAP_NONE to prevent xdr from
2303cd37da74Snw141292  *              mis-interpreting the contents of req->id2.
2304cd37da74Snw141292  * req->id2..[uid or gid or sid] =
2305cd37da74Snw141292  *              NOT USED
2306cd37da74Snw141292  */
2307cd37da74Snw141292 
2308cd37da74Snw141292 /*
2309cd37da74Snw141292  * This function does the following:
2310cd37da74Snw141292  * 1. Lookup well-known SIDs table.
2311cd37da74Snw141292  * 2. Check if the given SID is a local-SID and if so extract UID/GID from it.
2312cd37da74Snw141292  * 3. Lookup cache.
2313cd37da74Snw141292  * 4. Check if the client does not want new mapping to be allocated
2314cd37da74Snw141292  *    in which case this pass is the final pass.
2315cd37da74Snw141292  * 5. Set AD lookup flag if it determines that the next stage needs
2316cd37da74Snw141292  *    to do AD lookup.
2317cd37da74Snw141292  */
2318c5c4113dSnw141292 idmap_retcode
2319479ac375Sdm199847 sid2pid_first_pass(lookup_state_t *state, idmap_mapping *req,
2320cd37da74Snw141292 		idmap_id_res *res)
2321cd37da74Snw141292 {
2322c5c4113dSnw141292 	idmap_retcode	retcode;
2323e8c27ec8Sbaban 	int		wksid;
2324c5c4113dSnw141292 
2325e8c27ec8Sbaban 	/* Initialize result */
2326e8c27ec8Sbaban 	res->id.idtype = req->id2.idtype;
2327e8c27ec8Sbaban 	res->id.idmap_id_u.uid = SENTINEL_PID;
2328e8c27ec8Sbaban 	res->direction = IDMAP_DIRECTION_UNDEF;
2329e8c27ec8Sbaban 	wksid = 0;
2330c5c4113dSnw141292 
2331cf5b5989Sdm199847 	if (EMPTY_STRING(req->id1.idmap_id_u.sid.prefix)) {
2332e8c27ec8Sbaban 		if (req->id1name == NULL) {
2333e8c27ec8Sbaban 			retcode = IDMAP_ERR_ARG;
2334c5c4113dSnw141292 			goto out;
2335c5c4113dSnw141292 		}
2336e8c27ec8Sbaban 		/* sanitize sidprefix */
2337e8c27ec8Sbaban 		free(req->id1.idmap_id_u.sid.prefix);
2338e8c27ec8Sbaban 		req->id1.idmap_id_u.sid.prefix = NULL;
2339e8c27ec8Sbaban 	}
2340c5c4113dSnw141292 
2341e8c27ec8Sbaban 	/* Lookup well-known SIDs table */
2342e8c27ec8Sbaban 	retcode = lookup_wksids_sid2pid(req, res, &wksid);
2343c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
2344c5c4113dSnw141292 		goto out;
2345c5c4113dSnw141292 
2346e8c27ec8Sbaban 	if (!wksid) {
23472b4a7802SBaban Kenkre 		/* Check if this is a localsid */
2348e8c27ec8Sbaban 		retcode = lookup_localsid2pid(req, res);
2349e8c27ec8Sbaban 		if (retcode != IDMAP_ERR_NOTFOUND)
2350e8c27ec8Sbaban 			goto out;
23512b4a7802SBaban Kenkre 
23522b4a7802SBaban Kenkre 		if (ALLOW_WK_OR_LOCAL_SIDS_ONLY(req)) {
2353*4d61c878SJulian Pullen 			retcode = IDMAP_ERR_NONE_GENERATED;
23542b4a7802SBaban Kenkre 			goto out;
23552b4a7802SBaban Kenkre 		}
2356e8c27ec8Sbaban 	}
2357e8c27ec8Sbaban 
2358e8c27ec8Sbaban 	/* Lookup cache */
2359479ac375Sdm199847 	retcode = lookup_cache_sid2pid(state->cache, req, res);
2360c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
2361c5c4113dSnw141292 		goto out;
2362c5c4113dSnw141292 
2363c5c4113dSnw141292 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req) || AVOID_NAMESERVICE(req)) {
2364*4d61c878SJulian Pullen 		retcode = IDMAP_ERR_NONE_GENERATED;
2365c5c4113dSnw141292 		goto out;
2366c5c4113dSnw141292 	}
2367c5c4113dSnw141292 
2368c5c4113dSnw141292 	/*
2369e8c27ec8Sbaban 	 * Failed to find non-expired entry in cache. Next step is
2370e8c27ec8Sbaban 	 * to determine if this request needs to be batched for AD lookup.
2371e8c27ec8Sbaban 	 *
2372e8c27ec8Sbaban 	 * At this point we have either sid or winname or both. If we don't
2373e8c27ec8Sbaban 	 * have both then lookup name_cache for the sid or winname
2374e8c27ec8Sbaban 	 * whichever is missing. If not found then this request will be
2375e8c27ec8Sbaban 	 * batched for AD lookup.
2376e8c27ec8Sbaban 	 */
2377479ac375Sdm199847 	retcode = lookup_name_cache(state->cache, req, res);
2378e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS && retcode != IDMAP_ERR_NOTFOUND)
2379e8c27ec8Sbaban 		goto out;
2380e8c27ec8Sbaban 
2381e8c27ec8Sbaban 	/*
2382e8c27ec8Sbaban 	 * Set the flag to indicate that we are not done yet so that
2383e8c27ec8Sbaban 	 * subsequent passes considers this request for name-based
2384e8c27ec8Sbaban 	 * mapping and ephemeral mapping.
2385c5c4113dSnw141292 	 */
2386c5c4113dSnw141292 	state->sid2pid_done = FALSE;
2387e8c27ec8Sbaban 	req->direction |= _IDMAP_F_NOTDONE;
2388c5c4113dSnw141292 
2389c5c4113dSnw141292 	/*
2390e8c27ec8Sbaban 	 * Even if we have both sid and winname, we still may need to batch
2391e8c27ec8Sbaban 	 * this request for AD lookup if we don't have unixname and
2392e8c27ec8Sbaban 	 * directory-based name mapping (AD or mixed) is enabled.
2393e8c27ec8Sbaban 	 * We avoid AD lookup for well-known SIDs because they don't have
2394e8c27ec8Sbaban 	 * regular AD objects.
2395c5c4113dSnw141292 	 */
2396e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS ||
2397e8c27ec8Sbaban 	    (!wksid && req->id2name == NULL &&
2398e8c27ec8Sbaban 	    AD_OR_MIXED_MODE(res->id.idtype, state))) {
2399c5c4113dSnw141292 		retcode = IDMAP_SUCCESS;
2400e8c27ec8Sbaban 		req->direction |= _IDMAP_F_LOOKUP_AD;
2401c5c4113dSnw141292 		state->ad_nqueries++;
2402479ac375Sdm199847 	} else if (NLDAP_MODE(res->id.idtype, state)) {
2403479ac375Sdm199847 		req->direction |= _IDMAP_F_LOOKUP_NLDAP;
2404479ac375Sdm199847 		state->nldap_nqueries++;
2405c5c4113dSnw141292 	}
2406c5c4113dSnw141292 
2407c5c4113dSnw141292 
2408c5c4113dSnw141292 out:
2409c5c4113dSnw141292 	res->retcode = idmap_stat4prot(retcode);
2410e8c27ec8Sbaban 	/*
2411e8c27ec8Sbaban 	 * If we are done and there was an error then set fallback pid
2412e8c27ec8Sbaban 	 * in the result.
2413e8c27ec8Sbaban 	 */
2414e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
2415e8c27ec8Sbaban 		res->id.idmap_id_u.uid = UID_NOBODY;
2416c5c4113dSnw141292 	return (retcode);
2417c5c4113dSnw141292 }
2418c5c4113dSnw141292 
2419c5c4113dSnw141292 /*
2420c5c4113dSnw141292  * Generate SID using the following convention
2421c5c4113dSnw141292  * 	<machine-sid-prefix>-<1000 + uid>
2422c5c4113dSnw141292  * 	<machine-sid-prefix>-<2^31 + gid>
2423c5c4113dSnw141292  */
2424cd37da74Snw141292 static
2425cd37da74Snw141292 idmap_retcode
242648258c6bSjp151216 generate_localsid(idmap_mapping *req, idmap_id_res *res, int is_user,
242748258c6bSjp151216 		int fallback)
2428cd37da74Snw141292 {
2429e8c27ec8Sbaban 	free(res->id.idmap_id_u.sid.prefix);
2430e8c27ec8Sbaban 	res->id.idmap_id_u.sid.prefix = NULL;
2431e8c27ec8Sbaban 
2432e8c27ec8Sbaban 	/*
2433e8c27ec8Sbaban 	 * Diagonal mapping for localSIDs not supported because of the
2434e8c27ec8Sbaban 	 * way we generate localSIDs.
2435e8c27ec8Sbaban 	 */
2436e8c27ec8Sbaban 	if (is_user && res->id.idtype == IDMAP_GSID)
2437e8c27ec8Sbaban 		return (IDMAP_ERR_NOMAPPING);
2438e8c27ec8Sbaban 	if (!is_user && res->id.idtype == IDMAP_USID)
2439e8c27ec8Sbaban 		return (IDMAP_ERR_NOMAPPING);
2440e8c27ec8Sbaban 
2441c5c4113dSnw141292 	/* Skip 1000 UIDs */
2442c5c4113dSnw141292 	if (is_user && req->id1.idmap_id_u.uid >
2443c5c4113dSnw141292 	    (INT32_MAX - LOCALRID_MIN))
244462c60062Sbaban 		return (IDMAP_ERR_NOMAPPING);
2445c5c4113dSnw141292 
2446c5c4113dSnw141292 	RDLOCK_CONFIG();
2447e8c27ec8Sbaban 	/*
2448e8c27ec8Sbaban 	 * machine_sid is never NULL because if it is we won't be here.
2449e8c27ec8Sbaban 	 * No need to assert because stdrup(NULL) will core anyways.
2450e8c27ec8Sbaban 	 */
2451c5c4113dSnw141292 	res->id.idmap_id_u.sid.prefix =
2452c5c4113dSnw141292 	    strdup(_idmapdstate.cfg->pgcfg.machine_sid);
2453c5c4113dSnw141292 	if (res->id.idmap_id_u.sid.prefix == NULL) {
2454c5c4113dSnw141292 		UNLOCK_CONFIG();
2455c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2456c5c4113dSnw141292 		return (IDMAP_ERR_MEMORY);
2457c5c4113dSnw141292 	}
2458c5c4113dSnw141292 	UNLOCK_CONFIG();
2459c5c4113dSnw141292 	res->id.idmap_id_u.sid.rid =
2460c5c4113dSnw141292 	    (is_user) ? req->id1.idmap_id_u.uid + LOCALRID_MIN :
2461c5c4113dSnw141292 	    req->id1.idmap_id_u.gid + INT32_MAX + 1;
2462651c0131Sbaban 	res->direction = IDMAP_DIRECTION_BI;
2463e8c27ec8Sbaban 	if (res->id.idtype == IDMAP_SID)
2464e8c27ec8Sbaban 		res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
2465c5c4113dSnw141292 
246648258c6bSjp151216 	if (!fallback && req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
246748258c6bSjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_LOCAL_SID;
246848258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_ALGORITHMIC;
246948258c6bSjp151216 	}
247048258c6bSjp151216 
2471c5c4113dSnw141292 	/*
2472c5c4113dSnw141292 	 * Don't update name_cache because local sids don't have
2473c5c4113dSnw141292 	 * valid windows names.
2474c5c4113dSnw141292 	 */
2475e8c27ec8Sbaban 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
2476947c7bc0Sbaban 	return (IDMAP_SUCCESS);
2477c5c4113dSnw141292 }
2478c5c4113dSnw141292 
2479cd37da74Snw141292 static
2480cd37da74Snw141292 idmap_retcode
2481cd37da74Snw141292 lookup_localsid2pid(idmap_mapping *req, idmap_id_res *res)
2482cd37da74Snw141292 {
2483c5c4113dSnw141292 	char		*sidprefix;
2484c5c4113dSnw141292 	uint32_t	rid;
2485c5c4113dSnw141292 	int		s;
2486c5c4113dSnw141292 
2487c5c4113dSnw141292 	/*
2488c5c4113dSnw141292 	 * If the sidprefix == localsid then UID = last RID - 1000 or
2489c5c4113dSnw141292 	 * GID = last RID - 2^31.
2490c5c4113dSnw141292 	 */
2491e8c27ec8Sbaban 	if ((sidprefix = req->id1.idmap_id_u.sid.prefix) == NULL)
2492e8c27ec8Sbaban 		/* This means we are looking up by winname */
2493e8c27ec8Sbaban 		return (IDMAP_ERR_NOTFOUND);
2494c5c4113dSnw141292 	rid = req->id1.idmap_id_u.sid.rid;
2495c5c4113dSnw141292 
2496c5c4113dSnw141292 	RDLOCK_CONFIG();
2497c5c4113dSnw141292 	s = (_idmapdstate.cfg->pgcfg.machine_sid) ?
2498cd37da74Snw141292 	    strcasecmp(sidprefix, _idmapdstate.cfg->pgcfg.machine_sid) : 1;
2499c5c4113dSnw141292 	UNLOCK_CONFIG();
2500c5c4113dSnw141292 
2501e8c27ec8Sbaban 	/*
2502e8c27ec8Sbaban 	 * If the given sidprefix does not match machine_sid then this is
2503e8c27ec8Sbaban 	 * not a local SID.
2504e8c27ec8Sbaban 	 */
2505e8c27ec8Sbaban 	if (s != 0)
2506e8c27ec8Sbaban 		return (IDMAP_ERR_NOTFOUND);
2507e8c27ec8Sbaban 
2508e8c27ec8Sbaban 	switch (res->id.idtype) {
2509c5c4113dSnw141292 	case IDMAP_UID:
2510e8c27ec8Sbaban 		if (rid > INT32_MAX || rid < LOCALRID_MIN)
2511e8c27ec8Sbaban 			return (IDMAP_ERR_ARG);
2512c5c4113dSnw141292 		res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
2513c5c4113dSnw141292 		break;
2514c5c4113dSnw141292 	case IDMAP_GID:
2515e8c27ec8Sbaban 		if (rid <= INT32_MAX)
2516e8c27ec8Sbaban 			return (IDMAP_ERR_ARG);
2517c5c4113dSnw141292 		res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
2518c5c4113dSnw141292 		break;
2519c5c4113dSnw141292 	case IDMAP_POSIXID:
2520c5c4113dSnw141292 		if (rid > INT32_MAX) {
2521cd37da74Snw141292 			res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
2522c5c4113dSnw141292 			res->id.idtype = IDMAP_GID;
2523c5c4113dSnw141292 		} else if (rid < LOCALRID_MIN) {
2524e8c27ec8Sbaban 			return (IDMAP_ERR_ARG);
2525c5c4113dSnw141292 		} else {
2526c5c4113dSnw141292 			res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
2527c5c4113dSnw141292 			res->id.idtype = IDMAP_UID;
2528c5c4113dSnw141292 		}
2529c5c4113dSnw141292 		break;
2530c5c4113dSnw141292 	default:
2531c5c4113dSnw141292 		return (IDMAP_ERR_NOTSUPPORTED);
2532c5c4113dSnw141292 	}
253348258c6bSjp151216 	if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
253448258c6bSjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_LOCAL_SID;
253548258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_ALGORITHMIC;
253648258c6bSjp151216 	}
2537c5c4113dSnw141292 	return (IDMAP_SUCCESS);
2538c5c4113dSnw141292 }
2539c5c4113dSnw141292 
2540e8c27ec8Sbaban /*
2541e8c27ec8Sbaban  * Name service lookup by unixname to get pid
2542e8c27ec8Sbaban  */
2543cd37da74Snw141292 static
2544cd37da74Snw141292 idmap_retcode
2545e8c27ec8Sbaban ns_lookup_byname(const char *name, const char *lower_name, idmap_id *id)
2546cd37da74Snw141292 {
2547cd37da74Snw141292 	struct passwd	pwd, *pwdp;
2548cd37da74Snw141292 	struct group	grp, *grpp;
2549c5c4113dSnw141292 	char		buf[1024];
2550c5c4113dSnw141292 	int		errnum;
2551c5c4113dSnw141292 	const char	*me = "ns_lookup_byname";
2552c5c4113dSnw141292 
2553e8c27ec8Sbaban 	switch (id->idtype) {
2554e8c27ec8Sbaban 	case IDMAP_UID:
2555cd37da74Snw141292 		pwdp = getpwnam_r(name, &pwd, buf, sizeof (buf));
2556e8c27ec8Sbaban 		if (pwdp == NULL && errno == 0 && lower_name != NULL &&
2557cd37da74Snw141292 		    name != lower_name && strcmp(name, lower_name) != 0)
2558cd37da74Snw141292 			pwdp = getpwnam_r(lower_name, &pwd, buf, sizeof (buf));
2559cd37da74Snw141292 		if (pwdp == NULL) {
2560c5c4113dSnw141292 			errnum = errno;
2561c5c4113dSnw141292 			idmapdlog(LOG_WARNING,
2562c5c4113dSnw141292 			    "%s: getpwnam_r(%s) failed (%s).",
2563cd37da74Snw141292 			    me, name, errnum ? strerror(errnum) : "not found");
2564c5c4113dSnw141292 			if (errnum == 0)
2565c5c4113dSnw141292 				return (IDMAP_ERR_NOTFOUND);
2566c5c4113dSnw141292 			else
2567c5c4113dSnw141292 				return (IDMAP_ERR_INTERNAL);
2568c5c4113dSnw141292 		}
2569e8c27ec8Sbaban 		id->idmap_id_u.uid = pwd.pw_uid;
2570e8c27ec8Sbaban 		break;
2571e8c27ec8Sbaban 	case IDMAP_GID:
2572cd37da74Snw141292 		grpp = getgrnam_r(name, &grp, buf, sizeof (buf));
2573e8c27ec8Sbaban 		if (grpp == NULL && errno == 0 && lower_name != NULL &&
2574cd37da74Snw141292 		    name != lower_name && strcmp(name, lower_name) != 0)
2575cd37da74Snw141292 			grpp = getgrnam_r(lower_name, &grp, buf, sizeof (buf));
2576cd37da74Snw141292 		if (grpp == NULL) {
2577c5c4113dSnw141292 			errnum = errno;
2578c5c4113dSnw141292 			idmapdlog(LOG_WARNING,
2579c5c4113dSnw141292 			    "%s: getgrnam_r(%s) failed (%s).",
2580cd37da74Snw141292 			    me, name, errnum ? strerror(errnum) : "not found");
2581c5c4113dSnw141292 			if (errnum == 0)
2582c5c4113dSnw141292 				return (IDMAP_ERR_NOTFOUND);
2583c5c4113dSnw141292 			else
2584c5c4113dSnw141292 				return (IDMAP_ERR_INTERNAL);
2585c5c4113dSnw141292 		}
2586e8c27ec8Sbaban 		id->idmap_id_u.gid = grp.gr_gid;
2587e8c27ec8Sbaban 		break;
2588e8c27ec8Sbaban 	default:
2589e8c27ec8Sbaban 		return (IDMAP_ERR_ARG);
2590c5c4113dSnw141292 	}
2591c5c4113dSnw141292 	return (IDMAP_SUCCESS);
2592c5c4113dSnw141292 }
2593c5c4113dSnw141292 
2594e8c27ec8Sbaban 
2595e8c27ec8Sbaban /*
2596e8c27ec8Sbaban  * Name service lookup by pid to get unixname
2597e8c27ec8Sbaban  */
2598e8c27ec8Sbaban static
2599e8c27ec8Sbaban idmap_retcode
2600e8c27ec8Sbaban ns_lookup_bypid(uid_t pid, int is_user, char **unixname)
2601e8c27ec8Sbaban {
2602e8c27ec8Sbaban 	struct passwd	pwd;
2603e8c27ec8Sbaban 	struct group	grp;
2604e8c27ec8Sbaban 	char		buf[1024];
2605e8c27ec8Sbaban 	int		errnum;
2606e8c27ec8Sbaban 	const char	*me = "ns_lookup_bypid";
2607e8c27ec8Sbaban 
2608e8c27ec8Sbaban 	if (is_user) {
2609e8c27ec8Sbaban 		errno = 0;
2610e8c27ec8Sbaban 		if (getpwuid_r(pid, &pwd, buf, sizeof (buf)) == NULL) {
2611e8c27ec8Sbaban 			errnum = errno;
2612e8c27ec8Sbaban 			idmapdlog(LOG_WARNING,
2613e8c27ec8Sbaban 			    "%s: getpwuid_r(%u) failed (%s).",
2614e8c27ec8Sbaban 			    me, pid, errnum ? strerror(errnum) : "not found");
2615e8c27ec8Sbaban 			if (errnum == 0)
2616e8c27ec8Sbaban 				return (IDMAP_ERR_NOTFOUND);
2617e8c27ec8Sbaban 			else
2618e8c27ec8Sbaban 				return (IDMAP_ERR_INTERNAL);
2619e8c27ec8Sbaban 		}
2620e8c27ec8Sbaban 		*unixname = strdup(pwd.pw_name);
2621e8c27ec8Sbaban 	} else {
2622e8c27ec8Sbaban 		errno = 0;
2623e8c27ec8Sbaban 		if (getgrgid_r(pid, &grp, buf, sizeof (buf)) == NULL) {
2624e8c27ec8Sbaban 			errnum = errno;
2625e8c27ec8Sbaban 			idmapdlog(LOG_WARNING,
2626e8c27ec8Sbaban 			    "%s: getgrgid_r(%u) failed (%s).",
2627e8c27ec8Sbaban 			    me, pid, errnum ? strerror(errnum) : "not found");
2628e8c27ec8Sbaban 			if (errnum == 0)
2629e8c27ec8Sbaban 				return (IDMAP_ERR_NOTFOUND);
2630e8c27ec8Sbaban 			else
2631e8c27ec8Sbaban 				return (IDMAP_ERR_INTERNAL);
2632e8c27ec8Sbaban 		}
2633e8c27ec8Sbaban 		*unixname = strdup(grp.gr_name);
2634e8c27ec8Sbaban 	}
2635e8c27ec8Sbaban 	if (*unixname == NULL)
2636e8c27ec8Sbaban 		return (IDMAP_ERR_MEMORY);
2637e8c27ec8Sbaban 	return (IDMAP_SUCCESS);
2638e8c27ec8Sbaban }
2639e8c27ec8Sbaban 
2640c5c4113dSnw141292 /*
2641c5c4113dSnw141292  * Name-based mapping
2642c5c4113dSnw141292  *
2643c5c4113dSnw141292  * Case 1: If no rule matches do ephemeral
2644c5c4113dSnw141292  *
2645c5c4113dSnw141292  * Case 2: If rule matches and unixname is "" then return no mapping.
2646c5c4113dSnw141292  *
2647c5c4113dSnw141292  * Case 3: If rule matches and unixname is specified then lookup name
2648c5c4113dSnw141292  *  service using the unixname. If unixname not found then return no mapping.
2649c5c4113dSnw141292  *
2650c5c4113dSnw141292  * Case 4: If rule matches and unixname is * then lookup name service
2651c5c4113dSnw141292  *  using winname as the unixname. If unixname not found then process
2652c5c4113dSnw141292  *  other rules using the lookup order. If no other rule matches then do
2653c5c4113dSnw141292  *  ephemeral. Otherwise, based on the matched rule do Case 2 or 3 or 4.
2654c5c4113dSnw141292  *  This allows us to specify a fallback unixname per _domain_ or no mapping
2655c5c4113dSnw141292  *  instead of the default behaviour of doing ephemeral mapping.
2656c5c4113dSnw141292  *
2657c5c4113dSnw141292  * Example 1:
2658c5c4113dSnw141292  * *@sfbay == *
2659c5c4113dSnw141292  * If looking up windows users foo@sfbay and foo does not exists in
2660c5c4113dSnw141292  * the name service then foo@sfbay will be mapped to an ephemeral id.
2661c5c4113dSnw141292  *
2662c5c4113dSnw141292  * Example 2:
2663c5c4113dSnw141292  * *@sfbay == *
2664c5c4113dSnw141292  * *@sfbay => guest
2665c5c4113dSnw141292  * If looking up windows users foo@sfbay and foo does not exists in
2666c5c4113dSnw141292  * the name service then foo@sfbay will be mapped to guest.
2667c5c4113dSnw141292  *
2668c5c4113dSnw141292  * Example 3:
2669c5c4113dSnw141292  * *@sfbay == *
2670c5c4113dSnw141292  * *@sfbay => ""
2671c5c4113dSnw141292  * If looking up windows users foo@sfbay and foo does not exists in
2672c5c4113dSnw141292  * the name service then we will return no mapping for foo@sfbay.
2673c5c4113dSnw141292  *
2674c5c4113dSnw141292  */
2675cd37da74Snw141292 static
2676cd37da74Snw141292 idmap_retcode
2677479ac375Sdm199847 name_based_mapping_sid2pid(lookup_state_t *state,
2678479ac375Sdm199847 		idmap_mapping *req, idmap_id_res *res)
2679cd37da74Snw141292 {
2680cd37da74Snw141292 	const char	*unixname, *windomain;
2681cd37da74Snw141292 	char		*sql = NULL, *errmsg = NULL, *lower_winname = NULL;
2682c5c4113dSnw141292 	idmap_retcode	retcode;
2683cd37da74Snw141292 	char		*end, *lower_unixname, *winname;
2684c5c4113dSnw141292 	const char	**values;
2685c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
2686cd37da74Snw141292 	int		ncol, r, i, is_user, is_wuser;
268748258c6bSjp151216 	idmap_namerule	*rule = &res->info.how.idmap_how_u.rule;
268848258c6bSjp151216 	int		direction;
2689c5c4113dSnw141292 	const char	*me = "name_based_mapping_sid2pid";
2690c5c4113dSnw141292 
2691e8c27ec8Sbaban 	assert(req->id1name != NULL); /* We have winname */
2692e8c27ec8Sbaban 	assert(req->id2name == NULL); /* We don't have unixname */
2693e8c27ec8Sbaban 
26948e228215Sdm199847 	winname = req->id1name;
26958e228215Sdm199847 	windomain = req->id1domain;
2696cd37da74Snw141292 
2697cd37da74Snw141292 	switch (req->id1.idtype) {
2698cd37da74Snw141292 	case IDMAP_USID:
2699cd37da74Snw141292 		is_wuser = 1;
2700cd37da74Snw141292 		break;
2701cd37da74Snw141292 	case IDMAP_GSID:
2702cd37da74Snw141292 		is_wuser = 0;
2703cd37da74Snw141292 		break;
2704cd37da74Snw141292 	default:
2705e8c27ec8Sbaban 		idmapdlog(LOG_ERR, "%s: Unable to determine if the "
2706e8c27ec8Sbaban 		    "given Windows id is user or group.", me);
2707cd37da74Snw141292 		return (IDMAP_ERR_INTERNAL);
2708cd37da74Snw141292 	}
2709cd37da74Snw141292 
2710e8c27ec8Sbaban 	switch (res->id.idtype) {
2711cd37da74Snw141292 	case IDMAP_UID:
2712cd37da74Snw141292 		is_user = 1;
2713cd37da74Snw141292 		break;
2714cd37da74Snw141292 	case IDMAP_GID:
2715cd37da74Snw141292 		is_user = 0;
2716cd37da74Snw141292 		break;
2717cd37da74Snw141292 	case IDMAP_POSIXID:
2718cd37da74Snw141292 		is_user = is_wuser;
2719cd37da74Snw141292 		res->id.idtype = is_user ? IDMAP_UID : IDMAP_GID;
2720cd37da74Snw141292 		break;
2721cd37da74Snw141292 	}
2722c5c4113dSnw141292 
2723c5c4113dSnw141292 	i = 0;
2724479ac375Sdm199847 	if (windomain == NULL)
272562c60062Sbaban 		windomain = "";
272682da9f60Sbaban 	else if (state->defdom != NULL &&
272782da9f60Sbaban 	    strcasecmp(state->defdom, windomain) == 0)
2728c5c4113dSnw141292 		i = 1;
2729c5c4113dSnw141292 
2730cd37da74Snw141292 	if ((lower_winname = tolower_u8(winname)) == NULL)
2731cd37da74Snw141292 		lower_winname = winname;    /* hope for the best */
2732c5c4113dSnw141292 	sql = sqlite_mprintf(
273348258c6bSjp151216 	    "SELECT unixname, u2w_order, winname_display, windomain, is_nt4 "
273448258c6bSjp151216 	    "FROM namerules WHERE "
2735cd37da74Snw141292 	    "w2u_order > 0 AND is_user = %d AND is_wuser = %d AND "
2736c5c4113dSnw141292 	    "(winname = %Q OR winname = '*') AND "
2737c5c4113dSnw141292 	    "(windomain = %Q OR windomain = '*' %s) "
2738c5c4113dSnw141292 	    "ORDER BY w2u_order ASC;",
2739cd37da74Snw141292 	    is_user, is_wuser, lower_winname, windomain,
274062c60062Sbaban 	    i ? "OR windomain ISNULL OR windomain = ''" : "");
2741c5c4113dSnw141292 	if (sql == NULL) {
2742c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2743c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
2744c5c4113dSnw141292 		goto out;
2745c5c4113dSnw141292 	}
2746c5c4113dSnw141292 
2747479ac375Sdm199847 	if (sqlite_compile(state->db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
2748c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
2749cd37da74Snw141292 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
2750cd37da74Snw141292 		    CHECK_NULL(errmsg));
2751c5c4113dSnw141292 		sqlite_freemem(errmsg);
2752c5c4113dSnw141292 		goto out;
2753c5c4113dSnw141292 	}
2754c5c4113dSnw141292 
275584decf41Sjp151216 	for (;;) {
2756c5c4113dSnw141292 		r = sqlite_step(vm, &ncol, &values, NULL);
275784decf41Sjp151216 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
2758c5c4113dSnw141292 
275984decf41Sjp151216 		if (r == SQLITE_ROW) {
276048258c6bSjp151216 			if (ncol < 5) {
2761c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
2762c5c4113dSnw141292 				goto out;
2763c5c4113dSnw141292 			}
2764c5c4113dSnw141292 			if (values[0] == NULL) {
2765c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
2766c5c4113dSnw141292 				goto out;
2767c5c4113dSnw141292 			}
2768c5c4113dSnw141292 
276948258c6bSjp151216 			if (values[1] != NULL)
277048258c6bSjp151216 				direction =
277148258c6bSjp151216 				    (strtol(values[1], &end, 10) == 0)?
277248258c6bSjp151216 				    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
277348258c6bSjp151216 			else
277448258c6bSjp151216 				direction = IDMAP_DIRECTION_W2U;
277548258c6bSjp151216 
2776c5c4113dSnw141292 			if (EMPTY_NAME(values[0])) {
277748258c6bSjp151216 				idmap_namerule_set(rule, values[3], values[2],
277848258c6bSjp151216 				    values[0], is_wuser, is_user,
277948258c6bSjp151216 				    strtol(values[4], &end, 10),
278048258c6bSjp151216 				    direction);
2781c5c4113dSnw141292 				retcode = IDMAP_ERR_NOMAPPING;
2782c5c4113dSnw141292 				goto out;
2783c5c4113dSnw141292 			}
278448258c6bSjp151216 
278548258c6bSjp151216 			if (values[0][0] == '*') {
278648258c6bSjp151216 				unixname = winname;
278748258c6bSjp151216 				lower_unixname = lower_winname;
278848258c6bSjp151216 			} else {
278948258c6bSjp151216 				unixname = values[0];
279048258c6bSjp151216 				lower_unixname = NULL;
279148258c6bSjp151216 			}
279248258c6bSjp151216 
2793e8c27ec8Sbaban 			retcode = ns_lookup_byname(unixname, lower_unixname,
2794e8c27ec8Sbaban 			    &res->id);
2795c5c4113dSnw141292 			if (retcode == IDMAP_ERR_NOTFOUND) {
279648258c6bSjp151216 				if (values[0][0] == '*')
2797c5c4113dSnw141292 					/* Case 4 */
2798c5c4113dSnw141292 					continue;
279948258c6bSjp151216 				else {
2800c5c4113dSnw141292 					/* Case 3 */
280148258c6bSjp151216 					idmap_namerule_set(rule, values[3],
280248258c6bSjp151216 					    values[2], values[0], is_wuser,
280348258c6bSjp151216 					    is_user,
280448258c6bSjp151216 					    strtol(values[4], &end, 10),
280548258c6bSjp151216 					    direction);
2806c5c4113dSnw141292 					retcode = IDMAP_ERR_NOMAPPING;
2807c5c4113dSnw141292 				}
280848258c6bSjp151216 			}
2809c5c4113dSnw141292 			goto out;
2810c5c4113dSnw141292 		} else if (r == SQLITE_DONE) {
2811c5c4113dSnw141292 			retcode = IDMAP_ERR_NOTFOUND;
2812c5c4113dSnw141292 			goto out;
2813c5c4113dSnw141292 		} else {
2814c5c4113dSnw141292 			(void) sqlite_finalize(vm, &errmsg);
2815c5c4113dSnw141292 			vm = NULL;
2816cd37da74Snw141292 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
2817cd37da74Snw141292 			    CHECK_NULL(errmsg));
2818c5c4113dSnw141292 			sqlite_freemem(errmsg);
2819c5c4113dSnw141292 			retcode = IDMAP_ERR_INTERNAL;
2820c5c4113dSnw141292 			goto out;
2821c5c4113dSnw141292 		}
2822c5c4113dSnw141292 	}
2823c5c4113dSnw141292 
2824c5c4113dSnw141292 out:
282548258c6bSjp151216 	if (sql != NULL)
2826c5c4113dSnw141292 		sqlite_freemem(sql);
282748258c6bSjp151216 	res->info.how.map_type = IDMAP_MAP_TYPE_RULE_BASED;
2828c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
282962c60062Sbaban 		if (values[1] != NULL)
2830c5c4113dSnw141292 			res->direction =
2831651c0131Sbaban 			    (strtol(values[1], &end, 10) == 0)?
2832651c0131Sbaban 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
2833c5c4113dSnw141292 		else
2834651c0131Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
283548258c6bSjp151216 
28368e228215Sdm199847 		req->id2name = strdup(unixname);
2837479ac375Sdm199847 		if (req->id2name == NULL) {
2838479ac375Sdm199847 			retcode = IDMAP_ERR_MEMORY;
2839479ac375Sdm199847 		}
2840479ac375Sdm199847 	}
2841479ac375Sdm199847 
2842479ac375Sdm199847 	if (retcode == IDMAP_SUCCESS) {
284348258c6bSjp151216 		idmap_namerule_set(rule, values[3], values[2],
284448258c6bSjp151216 		    values[0], is_wuser, is_user, strtol(values[4], &end, 10),
284548258c6bSjp151216 		    res->direction);
284648258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
2847c5c4113dSnw141292 	}
2848479ac375Sdm199847 
2849cd37da74Snw141292 	if (lower_winname != NULL && lower_winname != winname)
2850cd37da74Snw141292 		free(lower_winname);
285162c60062Sbaban 	if (vm != NULL)
2852c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
2853c5c4113dSnw141292 	return (retcode);
2854c5c4113dSnw141292 }
2855c5c4113dSnw141292 
2856c5c4113dSnw141292 static
2857c5c4113dSnw141292 int
2858c5c4113dSnw141292 get_next_eph_uid(uid_t *next_uid)
2859c5c4113dSnw141292 {
2860c5c4113dSnw141292 	uid_t uid;
2861c5c4113dSnw141292 	gid_t gid;
2862c5c4113dSnw141292 	int err;
2863c5c4113dSnw141292 
2864c5c4113dSnw141292 	*next_uid = (uid_t)-1;
2865c5c4113dSnw141292 	uid = _idmapdstate.next_uid++;
2866c5c4113dSnw141292 	if (uid >= _idmapdstate.limit_uid) {
2867c5c4113dSnw141292 		if ((err = allocids(0, 8192, &uid, 0, &gid)) != 0)
2868c5c4113dSnw141292 			return (err);
2869c5c4113dSnw141292 
2870c5c4113dSnw141292 		_idmapdstate.limit_uid = uid + 8192;
2871c5c4113dSnw141292 		_idmapdstate.next_uid = uid;
2872c5c4113dSnw141292 	}
2873c5c4113dSnw141292 	*next_uid = uid;
2874c5c4113dSnw141292 
2875c5c4113dSnw141292 	return (0);
2876c5c4113dSnw141292 }
2877c5c4113dSnw141292 
2878c5c4113dSnw141292 static
2879c5c4113dSnw141292 int
2880c5c4113dSnw141292 get_next_eph_gid(gid_t *next_gid)
2881c5c4113dSnw141292 {
2882c5c4113dSnw141292 	uid_t uid;
2883c5c4113dSnw141292 	gid_t gid;
2884c5c4113dSnw141292 	int err;
2885c5c4113dSnw141292 
2886c5c4113dSnw141292 	*next_gid = (uid_t)-1;
2887c5c4113dSnw141292 	gid = _idmapdstate.next_gid++;
2888c5c4113dSnw141292 	if (gid >= _idmapdstate.limit_gid) {
2889c5c4113dSnw141292 		if ((err = allocids(0, 0, &uid, 8192, &gid)) != 0)
2890c5c4113dSnw141292 			return (err);
2891c5c4113dSnw141292 
2892c5c4113dSnw141292 		_idmapdstate.limit_gid = gid + 8192;
2893c5c4113dSnw141292 		_idmapdstate.next_gid = gid;
2894c5c4113dSnw141292 	}
2895c5c4113dSnw141292 	*next_gid = gid;
2896c5c4113dSnw141292 
2897c5c4113dSnw141292 	return (0);
2898c5c4113dSnw141292 }
2899c5c4113dSnw141292 
290062c60062Sbaban static
290162c60062Sbaban int
2902cd37da74Snw141292 gethash(const char *str, uint32_t num, uint_t htsize)
2903cd37da74Snw141292 {
290462c60062Sbaban 	uint_t  hval, i, len;
290562c60062Sbaban 
290662c60062Sbaban 	if (str == NULL)
290762c60062Sbaban 		return (0);
290862c60062Sbaban 	for (len = strlen(str), hval = 0, i = 0; i < len; i++) {
290962c60062Sbaban 		hval += str[i];
291062c60062Sbaban 		hval += (hval << 10);
291162c60062Sbaban 		hval ^= (hval >> 6);
291262c60062Sbaban 	}
291362c60062Sbaban 	for (str = (const char *)&num, i = 0; i < sizeof (num); i++) {
291462c60062Sbaban 		hval += str[i];
291562c60062Sbaban 		hval += (hval << 10);
291662c60062Sbaban 		hval ^= (hval >> 6);
291762c60062Sbaban 	}
291862c60062Sbaban 	hval += (hval << 3);
291962c60062Sbaban 	hval ^= (hval >> 11);
292062c60062Sbaban 	hval += (hval << 15);
292162c60062Sbaban 	return (hval % htsize);
292262c60062Sbaban }
292362c60062Sbaban 
292462c60062Sbaban static
292562c60062Sbaban int
292662c60062Sbaban get_from_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid,
2927cd37da74Snw141292 		uid_t *pid)
2928cd37da74Snw141292 {
292962c60062Sbaban 	uint_t		next, key;
293062c60062Sbaban 	uint_t		htsize = state->sid_history_size;
293162c60062Sbaban 	idmap_sid	*sid;
293262c60062Sbaban 
293362c60062Sbaban 	next = gethash(prefix, rid, htsize);
293462c60062Sbaban 	while (next != htsize) {
293562c60062Sbaban 		key = state->sid_history[next].key;
293662c60062Sbaban 		if (key == htsize)
293762c60062Sbaban 			return (0);
293862c60062Sbaban 		sid = &state->batch->idmap_mapping_batch_val[key].id1.
293962c60062Sbaban 		    idmap_id_u.sid;
294062c60062Sbaban 		if (sid->rid == rid && strcmp(sid->prefix, prefix) == 0) {
294162c60062Sbaban 			*pid = state->result->ids.ids_val[key].id.
294262c60062Sbaban 			    idmap_id_u.uid;
294362c60062Sbaban 			return (1);
294462c60062Sbaban 		}
294562c60062Sbaban 		next = state->sid_history[next].next;
294662c60062Sbaban 	}
294762c60062Sbaban 	return (0);
294862c60062Sbaban }
294962c60062Sbaban 
295062c60062Sbaban static
295162c60062Sbaban void
2952cd37da74Snw141292 add_to_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid)
2953cd37da74Snw141292 {
295462c60062Sbaban 	uint_t		hash, next;
295562c60062Sbaban 	uint_t		htsize = state->sid_history_size;
295662c60062Sbaban 
295762c60062Sbaban 	hash = next = gethash(prefix, rid, htsize);
295862c60062Sbaban 	while (state->sid_history[next].key != htsize) {
295962c60062Sbaban 		next++;
296062c60062Sbaban 		next %= htsize;
296162c60062Sbaban 	}
296262c60062Sbaban 	state->sid_history[next].key = state->curpos;
296362c60062Sbaban 	if (hash == next)
296462c60062Sbaban 		return;
296562c60062Sbaban 	state->sid_history[next].next = state->sid_history[hash].next;
296662c60062Sbaban 	state->sid_history[hash].next = next;
296762c60062Sbaban }
2968c5c4113dSnw141292 
2969e8c27ec8Sbaban void
2970e8c27ec8Sbaban cleanup_lookup_state(lookup_state_t *state)
2971e8c27ec8Sbaban {
2972e8c27ec8Sbaban 	free(state->sid_history);
2973e8c27ec8Sbaban 	free(state->ad_unixuser_attr);
2974e8c27ec8Sbaban 	free(state->ad_unixgroup_attr);
2975479ac375Sdm199847 	free(state->nldap_winname_attr);
2976479ac375Sdm199847 	free(state->defdom);
2977e8c27ec8Sbaban }
2978e8c27ec8Sbaban 
2979c5c4113dSnw141292 /* ARGSUSED */
2980c5c4113dSnw141292 static
2981c5c4113dSnw141292 idmap_retcode
2982479ac375Sdm199847 dynamic_ephemeral_mapping(lookup_state_t *state,
2983cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
2984cd37da74Snw141292 {
2985c5c4113dSnw141292 
2986c5c4113dSnw141292 	uid_t		next_pid;
2987c5c4113dSnw141292 
2988651c0131Sbaban 	res->direction = IDMAP_DIRECTION_BI;
298962c60062Sbaban 
299048258c6bSjp151216 	if (IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
299148258c6bSjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
299248258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_CACHE;
299362c60062Sbaban 		return (IDMAP_SUCCESS);
299448258c6bSjp151216 	}
299562c60062Sbaban 
299662c60062Sbaban 	if (state->sid_history != NULL &&
299762c60062Sbaban 	    get_from_sid_history(state, req->id1.idmap_id_u.sid.prefix,
299862c60062Sbaban 	    req->id1.idmap_id_u.sid.rid, &next_pid)) {
299962c60062Sbaban 		res->id.idmap_id_u.uid = next_pid;
300048258c6bSjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
300148258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
300262c60062Sbaban 		return (IDMAP_SUCCESS);
300362c60062Sbaban 	}
300462c60062Sbaban 
300562c60062Sbaban 	if (res->id.idtype == IDMAP_UID) {
3006c5c4113dSnw141292 		if (get_next_eph_uid(&next_pid) != 0)
3007c5c4113dSnw141292 			return (IDMAP_ERR_INTERNAL);
3008c5c4113dSnw141292 		res->id.idmap_id_u.uid = next_pid;
3009c5c4113dSnw141292 	} else {
3010c5c4113dSnw141292 		if (get_next_eph_gid(&next_pid) != 0)
3011c5c4113dSnw141292 			return (IDMAP_ERR_INTERNAL);
3012c5c4113dSnw141292 		res->id.idmap_id_u.gid = next_pid;
3013c5c4113dSnw141292 	}
3014c5c4113dSnw141292 
301548258c6bSjp151216 	res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
301648258c6bSjp151216 	res->info.src = IDMAP_MAP_SRC_NEW;
301762c60062Sbaban 	if (state->sid_history != NULL)
301862c60062Sbaban 		add_to_sid_history(state, req->id1.idmap_id_u.sid.prefix,
301962c60062Sbaban 		    req->id1.idmap_id_u.sid.rid);
302062c60062Sbaban 
3021c5c4113dSnw141292 	return (IDMAP_SUCCESS);
3022c5c4113dSnw141292 }
3023c5c4113dSnw141292 
3024c5c4113dSnw141292 idmap_retcode
3025479ac375Sdm199847 sid2pid_second_pass(lookup_state_t *state,
3026cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
3027cd37da74Snw141292 {
3028c5c4113dSnw141292 	idmap_retcode	retcode;
3029c5c4113dSnw141292 
3030c5c4113dSnw141292 	/* Check if second pass is needed */
3031e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
3032c5c4113dSnw141292 		return (res->retcode);
3033c5c4113dSnw141292 
3034c5c4113dSnw141292 	/* Get status from previous pass */
3035e8c27ec8Sbaban 	retcode = res->retcode;
30364aa0a5e7Snw141292 	if (retcode != IDMAP_SUCCESS && state->eph_map_unres_sids &&
30374aa0a5e7Snw141292 	    !EMPTY_STRING(req->id1.idmap_id_u.sid.prefix) &&
30384aa0a5e7Snw141292 	    EMPTY_STRING(req->id1name)) {
30394aa0a5e7Snw141292 		/*
30404aa0a5e7Snw141292 		 * We are asked to map an unresolvable SID to a UID or
30414aa0a5e7Snw141292 		 * GID, but, which?  We'll treat all unresolvable SIDs
30424aa0a5e7Snw141292 		 * as users unless the caller specified which of a UID
30434aa0a5e7Snw141292 		 * or GID they want.
30444aa0a5e7Snw141292 		 */
3045a7c8bd9fSNicolas Williams 		if (req->id1.idtype == IDMAP_SID)
3046a7c8bd9fSNicolas Williams 			req->id1.idtype = IDMAP_USID;
30474aa0a5e7Snw141292 		if (res->id.idtype == IDMAP_POSIXID)
30484aa0a5e7Snw141292 			res->id.idtype = IDMAP_UID;
30494aa0a5e7Snw141292 		goto do_eph;
30504aa0a5e7Snw141292 	}
3051e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
3052e8c27ec8Sbaban 		goto out;
3053c5c4113dSnw141292 
3054e8c27ec8Sbaban 	/*
3055e8c27ec8Sbaban 	 * If directory-based name mapping is enabled then the unixname
3056e8c27ec8Sbaban 	 * may already have been retrieved from the AD object (AD-mode or
3057e8c27ec8Sbaban 	 * mixed-mode) or from native LDAP object (nldap-mode) -- done.
3058e8c27ec8Sbaban 	 */
3059e8c27ec8Sbaban 	if (req->id2name != NULL) {
3060e8c27ec8Sbaban 		assert(res->id.idtype != IDMAP_POSIXID);
3061e8c27ec8Sbaban 		if (AD_MODE(res->id.idtype, state))
3062e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
3063e8c27ec8Sbaban 		else if (NLDAP_MODE(res->id.idtype, state))
3064e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
3065e8c27ec8Sbaban 		else if (MIXED_MODE(res->id.idtype, state))
3066e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
3067c5c4113dSnw141292 
3068e8c27ec8Sbaban 		/*
3069e8c27ec8Sbaban 		 * Special case: (1) If the ad_unixuser_attr and
3070e8c27ec8Sbaban 		 * ad_unixgroup_attr uses the same attribute
3071e8c27ec8Sbaban 		 * name and (2) if this is a diagonal mapping
3072e8c27ec8Sbaban 		 * request and (3) the unixname has been retrieved
3073e8c27ec8Sbaban 		 * from the AD object -- then we ignore it and fallback
3074e8c27ec8Sbaban 		 * to name-based mapping rules and ephemeral mapping
3075e8c27ec8Sbaban 		 *
3076e8c27ec8Sbaban 		 * Example:
3077e8c27ec8Sbaban 		 *  Properties:
3078e8c27ec8Sbaban 		 *    config/ad_unixuser_attr = "unixname"
3079e8c27ec8Sbaban 		 *    config/ad_unixgroup_attr = "unixname"
3080e8c27ec8Sbaban 		 *  AD user object:
3081e8c27ec8Sbaban 		 *    dn: cn=bob ...
3082e8c27ec8Sbaban 		 *    objectclass: user
3083e8c27ec8Sbaban 		 *    sam: bob
3084e8c27ec8Sbaban 		 *    unixname: bob1234
3085e8c27ec8Sbaban 		 *  AD group object:
3086e8c27ec8Sbaban 		 *    dn: cn=winadmins ...
3087e8c27ec8Sbaban 		 *    objectclass: group
3088e8c27ec8Sbaban 		 *    sam: winadmins
3089e8c27ec8Sbaban 		 *    unixname: unixadmins
3090e8c27ec8Sbaban 		 *
3091e8c27ec8Sbaban 		 *  In this example whether "unixname" refers to a unixuser
3092e8c27ec8Sbaban 		 *  or unixgroup depends upon the AD object.
3093e8c27ec8Sbaban 		 *
3094e8c27ec8Sbaban 		 * $idmap show -c winname:bob gid
3095e8c27ec8Sbaban 		 *    AD lookup by "samAccountName=bob" for
3096e8c27ec8Sbaban 		 *    "ad_unixgroup_attr (i.e unixname)" for directory-based
3097e8c27ec8Sbaban 		 *    mapping would get "bob1234" which is not what we want.
3098e8c27ec8Sbaban 		 *    Now why not getgrnam_r("bob1234") and use it if it
3099e8c27ec8Sbaban 		 *    is indeed a unixgroup? That's because Unix can have
3100e8c27ec8Sbaban 		 *    users and groups with the same name and we clearly
3101e8c27ec8Sbaban 		 *    don't know the intention of the admin here.
3102e8c27ec8Sbaban 		 *    Therefore we ignore this and fallback to name-based
3103e8c27ec8Sbaban 		 *    mapping rules or ephemeral mapping.
3104e8c27ec8Sbaban 		 */
3105e8c27ec8Sbaban 		if ((AD_MODE(res->id.idtype, state) ||
3106e8c27ec8Sbaban 		    MIXED_MODE(res->id.idtype, state)) &&
3107e8c27ec8Sbaban 		    state->ad_unixuser_attr != NULL &&
3108e8c27ec8Sbaban 		    state->ad_unixgroup_attr != NULL &&
3109e8c27ec8Sbaban 		    strcasecmp(state->ad_unixuser_attr,
3110e8c27ec8Sbaban 		    state->ad_unixgroup_attr) == 0 &&
3111e8c27ec8Sbaban 		    ((req->id1.idtype == IDMAP_USID &&
3112e8c27ec8Sbaban 		    res->id.idtype == IDMAP_GID) ||
3113e8c27ec8Sbaban 		    (req->id1.idtype == IDMAP_GSID &&
3114e8c27ec8Sbaban 		    res->id.idtype == IDMAP_UID))) {
3115e8c27ec8Sbaban 			free(req->id2name);
3116e8c27ec8Sbaban 			req->id2name = NULL;
3117e8c27ec8Sbaban 			res->id.idmap_id_u.uid = SENTINEL_PID;
3118e8c27ec8Sbaban 			/* fallback */
3119e8c27ec8Sbaban 		} else {
3120e8c27ec8Sbaban 			if (res->id.idmap_id_u.uid == SENTINEL_PID)
3121e8c27ec8Sbaban 				retcode = ns_lookup_byname(req->id2name,
3122e8c27ec8Sbaban 				    NULL, &res->id);
3123e8c27ec8Sbaban 			/*
3124479ac375Sdm199847 			 * If ns_lookup_byname() fails that means the
3125479ac375Sdm199847 			 * unixname (req->id2name), which was obtained
3126479ac375Sdm199847 			 * from the AD object by directory-based mapping,
3127479ac375Sdm199847 			 * is not a valid Unix user/group and therefore
3128479ac375Sdm199847 			 * we return the error to the client instead of
3129479ac375Sdm199847 			 * doing rule-based mapping or ephemeral mapping.
3130479ac375Sdm199847 			 * This way the client can detect the issue.
3131e8c27ec8Sbaban 			 */
3132c5c4113dSnw141292 			goto out;
3133c5c4113dSnw141292 		}
3134e8c27ec8Sbaban 	}
3135c5c4113dSnw141292 
313648258c6bSjp151216 	/* Free any mapping info from Directory based mapping */
313748258c6bSjp151216 	if (res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN)
313848258c6bSjp151216 		idmap_info_free(&res->info);
313948258c6bSjp151216 
3140e8c27ec8Sbaban 	/*
3141e8c27ec8Sbaban 	 * If we don't have unixname then evaluate local name-based
3142e8c27ec8Sbaban 	 * mapping rules.
3143e8c27ec8Sbaban 	 */
3144479ac375Sdm199847 	retcode = name_based_mapping_sid2pid(state, req, res);
3145e8c27ec8Sbaban 	if (retcode != IDMAP_ERR_NOTFOUND)
3146e8c27ec8Sbaban 		goto out;
3147e8c27ec8Sbaban 
31484aa0a5e7Snw141292 do_eph:
3149c5c4113dSnw141292 	/* If not found, do ephemeral mapping */
3150479ac375Sdm199847 	retcode = dynamic_ephemeral_mapping(state, req, res);
3151c5c4113dSnw141292 
3152c5c4113dSnw141292 out:
3153c5c4113dSnw141292 	res->retcode = idmap_stat4prot(retcode);
3154e8c27ec8Sbaban 	if (res->retcode != IDMAP_SUCCESS) {
3155e8c27ec8Sbaban 		req->direction = _IDMAP_F_DONE;
3156e8c27ec8Sbaban 		res->id.idmap_id_u.uid = UID_NOBODY;
3157e8c27ec8Sbaban 	}
3158e8c27ec8Sbaban 	if (!ARE_WE_DONE(req->direction))
3159e8c27ec8Sbaban 		state->sid2pid_done = FALSE;
3160c5c4113dSnw141292 	return (retcode);
3161c5c4113dSnw141292 }
3162c5c4113dSnw141292 
3163c5c4113dSnw141292 idmap_retcode
3164479ac375Sdm199847 update_cache_pid2sid(lookup_state_t *state,
3165cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
3166cd37da74Snw141292 {
3167c5c4113dSnw141292 	char		*sql = NULL;
3168c5c4113dSnw141292 	idmap_retcode	retcode;
316948258c6bSjp151216 	char		*map_dn = NULL;
317048258c6bSjp151216 	char		*map_attr = NULL;
317148258c6bSjp151216 	char		*map_value = NULL;
317248258c6bSjp151216 	char 		*map_windomain = NULL;
317348258c6bSjp151216 	char		*map_winname = NULL;
317448258c6bSjp151216 	char		*map_unixname = NULL;
317548258c6bSjp151216 	int		map_is_nt4 = FALSE;
3176c5c4113dSnw141292 
3177c5c4113dSnw141292 	/* Check if we need to cache anything */
3178e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
3179c5c4113dSnw141292 		return (IDMAP_SUCCESS);
3180c5c4113dSnw141292 
3181c5c4113dSnw141292 	/* We don't cache negative entries */
3182c5c4113dSnw141292 	if (res->retcode != IDMAP_SUCCESS)
3183c5c4113dSnw141292 		return (IDMAP_SUCCESS);
3184c5c4113dSnw141292 
3185e8c27ec8Sbaban 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
318648258c6bSjp151216 	assert(req->id1.idmap_id_u.uid != SENTINEL_PID);
318748258c6bSjp151216 	assert(res->id.idtype != IDMAP_SID);
318848258c6bSjp151216 
318948258c6bSjp151216 	assert(res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN);
319048258c6bSjp151216 	switch (res->info.how.map_type) {
319148258c6bSjp151216 	case IDMAP_MAP_TYPE_DS_AD:
319248258c6bSjp151216 		map_dn = res->info.how.idmap_how_u.ad.dn;
319348258c6bSjp151216 		map_attr = res->info.how.idmap_how_u.ad.attr;
319448258c6bSjp151216 		map_value = res->info.how.idmap_how_u.ad.value;
319548258c6bSjp151216 		break;
319648258c6bSjp151216 
319748258c6bSjp151216 	case IDMAP_MAP_TYPE_DS_NLDAP:
319848258c6bSjp151216 		map_dn = res->info.how.idmap_how_u.nldap.dn;
319948258c6bSjp151216 		map_attr = res->info.how.idmap_how_u.nldap.attr;
320048258c6bSjp151216 		map_value = res->info.how.idmap_how_u.nldap.value;
320148258c6bSjp151216 		break;
320248258c6bSjp151216 
320348258c6bSjp151216 	case IDMAP_MAP_TYPE_RULE_BASED:
320448258c6bSjp151216 		map_windomain = res->info.how.idmap_how_u.rule.windomain;
320548258c6bSjp151216 		map_winname = res->info.how.idmap_how_u.rule.winname;
320648258c6bSjp151216 		map_unixname = res->info.how.idmap_how_u.rule.unixname;
320748258c6bSjp151216 		map_is_nt4 = res->info.how.idmap_how_u.rule.is_nt4;
320848258c6bSjp151216 		break;
320948258c6bSjp151216 
321048258c6bSjp151216 	case IDMAP_MAP_TYPE_EPHEMERAL:
321148258c6bSjp151216 		break;
321248258c6bSjp151216 
321348258c6bSjp151216 	case IDMAP_MAP_TYPE_LOCAL_SID:
321448258c6bSjp151216 		break;
321548258c6bSjp151216 
321648258c6bSjp151216 	default:
321748258c6bSjp151216 		/* Dont cache other mapping types */
321848258c6bSjp151216 		assert(FALSE);
321948258c6bSjp151216 	}
3220e8c27ec8Sbaban 
3221c5c4113dSnw141292 	/*
3222c5c4113dSnw141292 	 * Using NULL for u2w instead of 0 so that our trigger allows
3223c5c4113dSnw141292 	 * the same pid to be the destination in multiple entries
3224c5c4113dSnw141292 	 */
3225c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
3226cd37da74Snw141292 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
322748258c6bSjp151216 	    "is_user, is_wuser, expiration, w2u, u2w, "
322848258c6bSjp151216 	    "map_type, map_dn, map_attr, map_value, map_windomain, "
322948258c6bSjp151216 	    "map_winname, map_unixname, map_is_nt4) "
3230cd37da74Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
323148258c6bSjp151216 	    "strftime('%%s','now') + 600, %q, 1, "
323248258c6bSjp151216 	    "%d, %Q, %Q, %Q, %Q, %Q, %Q, %d); ",
3233cd37da74Snw141292 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
3234cd37da74Snw141292 	    req->id2domain, req->id2name, req->id1.idmap_id_u.uid,
3235cd37da74Snw141292 	    req->id1name, (req->id1.idtype == IDMAP_UID) ? 1 : 0,
3236e8c27ec8Sbaban 	    (res->id.idtype == IDMAP_USID) ? 1 : 0,
323748258c6bSjp151216 	    (res->direction == 0) ? "1" : NULL,
323848258c6bSjp151216 	    res->info.how.map_type, map_dn, map_attr, map_value,
323948258c6bSjp151216 	    map_windomain, map_winname, map_unixname, map_is_nt4);
3240c5c4113dSnw141292 
3241c5c4113dSnw141292 	if (sql == NULL) {
3242c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3243c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3244c5c4113dSnw141292 		goto out;
3245c5c4113dSnw141292 	}
3246c5c4113dSnw141292 
3247479ac375Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
3248c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
3249c5c4113dSnw141292 		goto out;
3250c5c4113dSnw141292 
3251c5c4113dSnw141292 	state->pid2sid_done = FALSE;
3252c5c4113dSnw141292 	sqlite_freemem(sql);
3253c5c4113dSnw141292 	sql = NULL;
3254c5c4113dSnw141292 
3255e8c27ec8Sbaban 	/* Check if we need to update namecache */
3256e8c27ec8Sbaban 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
3257c5c4113dSnw141292 		goto out;
3258c5c4113dSnw141292 
32598e228215Sdm199847 	if (req->id2name == NULL)
3260c5c4113dSnw141292 		goto out;
3261c5c4113dSnw141292 
3262c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
3263cd37da74Snw141292 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
3264c5c4113dSnw141292 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
3265cd37da74Snw141292 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
3266cd37da74Snw141292 	    req->id2name, req->id2domain,
3267e8c27ec8Sbaban 	    (res->id.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
3268c5c4113dSnw141292 
3269c5c4113dSnw141292 	if (sql == NULL) {
3270c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3271c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3272c5c4113dSnw141292 		goto out;
3273c5c4113dSnw141292 	}
3274c5c4113dSnw141292 
3275479ac375Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
3276c5c4113dSnw141292 
3277c5c4113dSnw141292 out:
327848258c6bSjp151216 	if (!(req->flag & IDMAP_REQ_FLG_MAPPING_INFO))
327948258c6bSjp151216 		idmap_info_free(&res->info);
328062c60062Sbaban 	if (sql != NULL)
3281c5c4113dSnw141292 		sqlite_freemem(sql);
3282c5c4113dSnw141292 	return (retcode);
3283c5c4113dSnw141292 }
3284c5c4113dSnw141292 
3285c5c4113dSnw141292 idmap_retcode
3286479ac375Sdm199847 update_cache_sid2pid(lookup_state_t *state,
3287cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
3288cd37da74Snw141292 {
3289c5c4113dSnw141292 	char		*sql = NULL;
3290c5c4113dSnw141292 	idmap_retcode	retcode;
3291c5c4113dSnw141292 	int		is_eph_user;
329248258c6bSjp151216 	char		*map_dn = NULL;
329348258c6bSjp151216 	char		*map_attr = NULL;
329448258c6bSjp151216 	char		*map_value = NULL;
329548258c6bSjp151216 	char 		*map_windomain = NULL;
329648258c6bSjp151216 	char		*map_winname = NULL;
329748258c6bSjp151216 	char		*map_unixname = NULL;
329848258c6bSjp151216 	int		map_is_nt4 = FALSE;
3299c5c4113dSnw141292 
3300c5c4113dSnw141292 	/* Check if we need to cache anything */
3301e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
3302c5c4113dSnw141292 		return (IDMAP_SUCCESS);
3303c5c4113dSnw141292 
3304c5c4113dSnw141292 	/* We don't cache negative entries */
3305c5c4113dSnw141292 	if (res->retcode != IDMAP_SUCCESS)
3306c5c4113dSnw141292 		return (IDMAP_SUCCESS);
3307c5c4113dSnw141292 
3308c5c4113dSnw141292 	if (req->direction & _IDMAP_F_EXP_EPH_UID)
3309c5c4113dSnw141292 		is_eph_user = 1;
3310c5c4113dSnw141292 	else if (req->direction & _IDMAP_F_EXP_EPH_GID)
3311c5c4113dSnw141292 		is_eph_user = 0;
3312c5c4113dSnw141292 	else
3313c5c4113dSnw141292 		is_eph_user = -1;
3314c5c4113dSnw141292 
3315c5c4113dSnw141292 	if (is_eph_user >= 0 && !IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
3316c5c4113dSnw141292 		sql = sqlite_mprintf("UPDATE idmap_cache "
3317c5c4113dSnw141292 		    "SET w2u = 0 WHERE "
3318c5c4113dSnw141292 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
3319c5c4113dSnw141292 		    "pid >= 2147483648 AND is_user = %d;",
3320c5c4113dSnw141292 		    req->id1.idmap_id_u.sid.prefix,
3321c5c4113dSnw141292 		    req->id1.idmap_id_u.sid.rid,
3322c5c4113dSnw141292 		    is_eph_user);
3323c5c4113dSnw141292 		if (sql == NULL) {
3324c5c4113dSnw141292 			retcode = IDMAP_ERR_INTERNAL;
3325c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
3326c5c4113dSnw141292 			goto out;
3327c5c4113dSnw141292 		}
3328c5c4113dSnw141292 
3329479ac375Sdm199847 		retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
3330c5c4113dSnw141292 		if (retcode != IDMAP_SUCCESS)
3331c5c4113dSnw141292 			goto out;
3332c5c4113dSnw141292 
3333c5c4113dSnw141292 		sqlite_freemem(sql);
3334c5c4113dSnw141292 		sql = NULL;
3335c5c4113dSnw141292 	}
3336c5c4113dSnw141292 
3337e8c27ec8Sbaban 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
333848258c6bSjp151216 	assert(res->id.idmap_id_u.uid != SENTINEL_PID);
333948258c6bSjp151216 
334048258c6bSjp151216 	switch (res->info.how.map_type) {
334148258c6bSjp151216 	case IDMAP_MAP_TYPE_DS_AD:
334248258c6bSjp151216 		map_dn = res->info.how.idmap_how_u.ad.dn;
334348258c6bSjp151216 		map_attr = res->info.how.idmap_how_u.ad.attr;
334448258c6bSjp151216 		map_value = res->info.how.idmap_how_u.ad.value;
334548258c6bSjp151216 		break;
334648258c6bSjp151216 
334748258c6bSjp151216 	case IDMAP_MAP_TYPE_DS_NLDAP:
334848258c6bSjp151216 		map_dn = res->info.how.idmap_how_u.nldap.dn;
334948258c6bSjp151216 		map_attr = res->info.how.idmap_how_u.ad.attr;
335048258c6bSjp151216 		map_value = res->info.how.idmap_how_u.nldap.value;
335148258c6bSjp151216 		break;
335248258c6bSjp151216 
335348258c6bSjp151216 	case IDMAP_MAP_TYPE_RULE_BASED:
335448258c6bSjp151216 		map_windomain = res->info.how.idmap_how_u.rule.windomain;
335548258c6bSjp151216 		map_winname = res->info.how.idmap_how_u.rule.winname;
335648258c6bSjp151216 		map_unixname = res->info.how.idmap_how_u.rule.unixname;
335748258c6bSjp151216 		map_is_nt4 = res->info.how.idmap_how_u.rule.is_nt4;
335848258c6bSjp151216 		break;
335948258c6bSjp151216 
336048258c6bSjp151216 	case IDMAP_MAP_TYPE_EPHEMERAL:
336148258c6bSjp151216 		break;
336248258c6bSjp151216 
336348258c6bSjp151216 	default:
336448258c6bSjp151216 		/* Dont cache other mapping types */
336548258c6bSjp151216 		assert(FALSE);
336648258c6bSjp151216 	}
3367cd37da74Snw141292 
3368c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
3369cd37da74Snw141292 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
337048258c6bSjp151216 	    "is_user, is_wuser, expiration, w2u, u2w, "
337148258c6bSjp151216 	    "map_type, map_dn, map_attr, map_value, map_windomain, "
337248258c6bSjp151216 	    "map_winname, map_unixname, map_is_nt4) "
3373cd37da74Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
337448258c6bSjp151216 	    "strftime('%%s','now') + 600, 1, %q, "
337548258c6bSjp151216 	    "%d, %Q, %Q, %Q, %Q, %Q, %Q, %d);",
3376cd37da74Snw141292 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
3377e8c27ec8Sbaban 	    (req->id1domain != NULL) ? req->id1domain : "", req->id1name,
3378e8c27ec8Sbaban 	    res->id.idmap_id_u.uid, req->id2name,
3379e8c27ec8Sbaban 	    (res->id.idtype == IDMAP_UID) ? 1 : 0,
3380cd37da74Snw141292 	    (req->id1.idtype == IDMAP_USID) ? 1 : 0,
338148258c6bSjp151216 	    (res->direction == 0) ? "1" : NULL,
338248258c6bSjp151216 	    res->info.how.map_type, map_dn, map_attr, map_value,
338348258c6bSjp151216 	    map_windomain, map_winname, map_unixname, map_is_nt4);
3384c5c4113dSnw141292 
3385c5c4113dSnw141292 	if (sql == NULL) {
3386c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3387c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3388c5c4113dSnw141292 		goto out;
3389c5c4113dSnw141292 	}
3390c5c4113dSnw141292 
3391479ac375Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
3392c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
3393c5c4113dSnw141292 		goto out;
3394c5c4113dSnw141292 
3395c5c4113dSnw141292 	state->sid2pid_done = FALSE;
3396c5c4113dSnw141292 	sqlite_freemem(sql);
3397c5c4113dSnw141292 	sql = NULL;
3398c5c4113dSnw141292 
3399e8c27ec8Sbaban 	/* Check if we need to update namecache */
3400e8c27ec8Sbaban 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
3401c5c4113dSnw141292 		goto out;
3402c5c4113dSnw141292 
3403cf5b5989Sdm199847 	if (EMPTY_STRING(req->id1name))
3404c5c4113dSnw141292 		goto out;
3405c5c4113dSnw141292 
3406c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
3407cd37da74Snw141292 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
3408c5c4113dSnw141292 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
3409cd37da74Snw141292 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
3410cd37da74Snw141292 	    req->id1name, req->id1domain,
3411cd37da74Snw141292 	    (req->id1.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
3412c5c4113dSnw141292 
3413c5c4113dSnw141292 	if (sql == NULL) {
3414c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3415c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3416c5c4113dSnw141292 		goto out;
3417c5c4113dSnw141292 	}
3418c5c4113dSnw141292 
3419479ac375Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
3420c5c4113dSnw141292 
3421c5c4113dSnw141292 out:
342248258c6bSjp151216 	if (!(req->flag & IDMAP_REQ_FLG_MAPPING_INFO))
342348258c6bSjp151216 		idmap_info_free(&res->info);
342448258c6bSjp151216 
342562c60062Sbaban 	if (sql != NULL)
3426c5c4113dSnw141292 		sqlite_freemem(sql);
3427c5c4113dSnw141292 	return (retcode);
3428c5c4113dSnw141292 }
3429c5c4113dSnw141292 
3430cd37da74Snw141292 static
3431cd37da74Snw141292 idmap_retcode
3432c5c4113dSnw141292 lookup_cache_pid2sid(sqlite *cache, idmap_mapping *req, idmap_id_res *res,
3433cd37da74Snw141292 		int is_user, int getname)
3434cd37da74Snw141292 {
3435c5c4113dSnw141292 	char		*end;
3436c5c4113dSnw141292 	char		*sql = NULL;
3437c5c4113dSnw141292 	const char	**values;
3438c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
3439c5c4113dSnw141292 	int		ncol;
3440c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
3441c5c4113dSnw141292 	time_t		curtime;
3442e8c27ec8Sbaban 	idmap_id_type	idtype;
3443c5c4113dSnw141292 
3444c5c4113dSnw141292 	/* Current time */
3445c5c4113dSnw141292 	errno = 0;
3446c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
3447cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
3448c5c4113dSnw141292 		    strerror(errno));
3449c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3450c5c4113dSnw141292 		goto out;
3451c5c4113dSnw141292 	}
3452c5c4113dSnw141292 
3453e8c27ec8Sbaban 	/* SQL to lookup the cache by pid or by unixname */
3454e8c27ec8Sbaban 	if (req->id1.idmap_id_u.uid != SENTINEL_PID) {
345548258c6bSjp151216 		sql = sqlite_mprintf("SELECT sidprefix, rid, "
345648258c6bSjp151216 		    "canon_winname, windomain, w2u, is_wuser, "
345748258c6bSjp151216 		    "map_type, map_dn, map_attr, map_value, map_windomain, "
345848258c6bSjp151216 		    "map_winname, map_unixname, map_is_nt4 "
3459c5c4113dSnw141292 		    "FROM idmap_cache WHERE "
3460c5c4113dSnw141292 		    "pid = %u AND u2w = 1 AND is_user = %d AND "
3461c5c4113dSnw141292 		    "(pid >= 2147483648 OR "
3462c5c4113dSnw141292 		    "(expiration = 0 OR expiration ISNULL OR "
3463c5c4113dSnw141292 		    "expiration > %d));",
3464c5c4113dSnw141292 		    req->id1.idmap_id_u.uid, is_user, curtime);
3465e8c27ec8Sbaban 	} else if (req->id1name != NULL) {
346648258c6bSjp151216 		sql = sqlite_mprintf("SELECT sidprefix, rid, "
346748258c6bSjp151216 		    "canon_winname, windomain, w2u, is_wuser, "
346848258c6bSjp151216 		    "map_type, map_dn, map_attr, map_value, map_windomain, "
346948258c6bSjp151216 		    "map_winname, map_unixname, map_is_nt4 "
3470e8c27ec8Sbaban 		    "FROM idmap_cache WHERE "
3471e8c27ec8Sbaban 		    "unixname = %Q AND u2w = 1 AND is_user = %d AND "
3472e8c27ec8Sbaban 		    "(pid >= 2147483648 OR "
3473e8c27ec8Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
3474e8c27ec8Sbaban 		    "expiration > %d));",
3475e8c27ec8Sbaban 		    req->id1name, is_user, curtime);
347648258c6bSjp151216 	} else {
347748258c6bSjp151216 		retcode = IDMAP_ERR_ARG;
347848258c6bSjp151216 		goto out;
3479e8c27ec8Sbaban 	}
3480e8c27ec8Sbaban 
3481c5c4113dSnw141292 	if (sql == NULL) {
3482c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3483c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
3484c5c4113dSnw141292 		goto out;
3485c5c4113dSnw141292 	}
348648258c6bSjp151216 	retcode = sql_compile_n_step_once(
348748258c6bSjp151216 	    cache, sql, &vm, &ncol, 14, &values);
3488c5c4113dSnw141292 	sqlite_freemem(sql);
3489c5c4113dSnw141292 
3490c5c4113dSnw141292 	if (retcode == IDMAP_ERR_NOTFOUND)
3491c5c4113dSnw141292 		goto out;
3492c5c4113dSnw141292 	else if (retcode == IDMAP_SUCCESS) {
3493c5c4113dSnw141292 		/* sanity checks */
3494c5c4113dSnw141292 		if (values[0] == NULL || values[1] == NULL) {
3495c5c4113dSnw141292 			retcode = IDMAP_ERR_CACHE;
3496c5c4113dSnw141292 			goto out;
3497c5c4113dSnw141292 		}
3498c5c4113dSnw141292 
3499e8c27ec8Sbaban 		switch (res->id.idtype) {
3500c5c4113dSnw141292 		case IDMAP_SID:
3501cd37da74Snw141292 		case IDMAP_USID:
3502cd37da74Snw141292 		case IDMAP_GSID:
3503e8c27ec8Sbaban 			idtype = strtol(values[5], &end, 10) == 1
3504cd37da74Snw141292 			    ? IDMAP_USID : IDMAP_GSID;
3505cd37da74Snw141292 
3506e8c27ec8Sbaban 			if (res->id.idtype == IDMAP_USID &&
3507e8c27ec8Sbaban 			    idtype != IDMAP_USID) {
3508cd37da74Snw141292 				retcode = IDMAP_ERR_NOTUSER;
3509cd37da74Snw141292 				goto out;
3510e8c27ec8Sbaban 			} else if (res->id.idtype == IDMAP_GSID &&
3511e8c27ec8Sbaban 			    idtype != IDMAP_GSID) {
3512cd37da74Snw141292 				retcode = IDMAP_ERR_NOTGROUP;
3513cd37da74Snw141292 				goto out;
3514cd37da74Snw141292 			}
3515e8c27ec8Sbaban 			res->id.idtype = idtype;
3516cd37da74Snw141292 
3517c5c4113dSnw141292 			res->id.idmap_id_u.sid.rid =
3518c5c4113dSnw141292 			    strtoul(values[1], &end, 10);
3519c5c4113dSnw141292 			res->id.idmap_id_u.sid.prefix = strdup(values[0]);
3520c5c4113dSnw141292 			if (res->id.idmap_id_u.sid.prefix == NULL) {
3521c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
3522c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
3523c5c4113dSnw141292 				goto out;
3524c5c4113dSnw141292 			}
3525c5c4113dSnw141292 
352662c60062Sbaban 			if (values[4] != NULL)
3527c5c4113dSnw141292 				res->direction =
3528651c0131Sbaban 				    (strtol(values[4], &end, 10) == 0)?
3529651c0131Sbaban 				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
3530c5c4113dSnw141292 			else
3531651c0131Sbaban 				res->direction = IDMAP_DIRECTION_U2W;
3532c5c4113dSnw141292 
3533c5c4113dSnw141292 			if (getname == 0 || values[2] == NULL)
3534c5c4113dSnw141292 				break;
35358e228215Sdm199847 			req->id2name = strdup(values[2]);
35368e228215Sdm199847 			if (req->id2name == NULL) {
3537c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
3538c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
3539c5c4113dSnw141292 				goto out;
3540c5c4113dSnw141292 			}
3541c5c4113dSnw141292 
3542c5c4113dSnw141292 			if (values[3] == NULL)
3543c5c4113dSnw141292 				break;
35448e228215Sdm199847 			req->id2domain = strdup(values[3]);
35458e228215Sdm199847 			if (req->id2domain == NULL) {
3546c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
3547c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
3548c5c4113dSnw141292 				goto out;
3549c5c4113dSnw141292 			}
3550cd37da74Snw141292 
3551c5c4113dSnw141292 			break;
3552c5c4113dSnw141292 		default:
3553c5c4113dSnw141292 			retcode = IDMAP_ERR_NOTSUPPORTED;
3554c5c4113dSnw141292 			break;
3555c5c4113dSnw141292 		}
355648258c6bSjp151216 		if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
355748258c6bSjp151216 			res->info.src = IDMAP_MAP_SRC_CACHE;
355848258c6bSjp151216 			res->info.how.map_type = strtoul(values[6], &end, 10);
355948258c6bSjp151216 			switch (res->info.how.map_type) {
356048258c6bSjp151216 			case IDMAP_MAP_TYPE_DS_AD:
356148258c6bSjp151216 				res->info.how.idmap_how_u.ad.dn =
356248258c6bSjp151216 				    strdup(values[7]);
356348258c6bSjp151216 				res->info.how.idmap_how_u.ad.attr =
356448258c6bSjp151216 				    strdup(values[8]);
356548258c6bSjp151216 				res->info.how.idmap_how_u.ad.value =
356648258c6bSjp151216 				    strdup(values[9]);
356748258c6bSjp151216 				break;
356848258c6bSjp151216 
356948258c6bSjp151216 			case IDMAP_MAP_TYPE_DS_NLDAP:
357048258c6bSjp151216 				res->info.how.idmap_how_u.nldap.dn =
357148258c6bSjp151216 				    strdup(values[7]);
357248258c6bSjp151216 				res->info.how.idmap_how_u.nldap.attr =
357348258c6bSjp151216 				    strdup(values[8]);
357448258c6bSjp151216 				res->info.how.idmap_how_u.nldap.value =
357548258c6bSjp151216 				    strdup(values[9]);
357648258c6bSjp151216 				break;
357748258c6bSjp151216 
357848258c6bSjp151216 			case IDMAP_MAP_TYPE_RULE_BASED:
357948258c6bSjp151216 				res->info.how.idmap_how_u.rule.windomain =
358048258c6bSjp151216 				    strdup(values[10]);
358148258c6bSjp151216 				res->info.how.idmap_how_u.rule.winname =
358248258c6bSjp151216 				    strdup(values[11]);
358348258c6bSjp151216 				res->info.how.idmap_how_u.rule.unixname =
358448258c6bSjp151216 				    strdup(values[12]);
358548258c6bSjp151216 				res->info.how.idmap_how_u.rule.is_nt4 =
358648258c6bSjp151216 				    strtoul(values[13], &end, 10);
358748258c6bSjp151216 				res->info.how.idmap_how_u.rule.is_user =
358848258c6bSjp151216 				    is_user;
358948258c6bSjp151216 				res->info.how.idmap_how_u.rule.is_wuser =
359048258c6bSjp151216 				    strtol(values[5], &end, 10);
359148258c6bSjp151216 				break;
359248258c6bSjp151216 
359348258c6bSjp151216 			case IDMAP_MAP_TYPE_EPHEMERAL:
359448258c6bSjp151216 				break;
359548258c6bSjp151216 
359648258c6bSjp151216 			case IDMAP_MAP_TYPE_LOCAL_SID:
359748258c6bSjp151216 				break;
359848258c6bSjp151216 
359948258c6bSjp151216 			case IDMAP_MAP_TYPE_KNOWN_SID:
360048258c6bSjp151216 				break;
360148258c6bSjp151216 
360248258c6bSjp151216 			default:
360348258c6bSjp151216 				/* Unknow mapping type */
360448258c6bSjp151216 				assert(FALSE);
360548258c6bSjp151216 			}
360648258c6bSjp151216 		}
3607c5c4113dSnw141292 	}
3608c5c4113dSnw141292 
3609c5c4113dSnw141292 out:
361062c60062Sbaban 	if (vm != NULL)
3611c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
3612c5c4113dSnw141292 	return (retcode);
3613c5c4113dSnw141292 }
3614c5c4113dSnw141292 
3615cd37da74Snw141292 static
3616cd37da74Snw141292 idmap_retcode
3617c5c4113dSnw141292 lookup_cache_name2sid(sqlite *cache, const char *name, const char *domain,
3618cd37da74Snw141292 	char **canonname, char **sidprefix, idmap_rid_t *rid, int *type)
3619cd37da74Snw141292 {
3620cd37da74Snw141292 	char		*end, *lower_name;
3621c5c4113dSnw141292 	char		*sql = NULL;
3622c5c4113dSnw141292 	const char	**values;
3623c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
3624c5c4113dSnw141292 	int		ncol;
3625c5c4113dSnw141292 	time_t		curtime;
3626c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
3627c5c4113dSnw141292 
3628c5c4113dSnw141292 	/* Get current time */
3629c5c4113dSnw141292 	errno = 0;
3630c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
3631cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
3632c5c4113dSnw141292 		    strerror(errno));
3633c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3634c5c4113dSnw141292 		goto out;
3635c5c4113dSnw141292 	}
3636c5c4113dSnw141292 
3637c5c4113dSnw141292 	/* SQL to lookup the cache */
3638cd37da74Snw141292 	if ((lower_name = tolower_u8(name)) == NULL)
3639cd37da74Snw141292 		lower_name = (char *)name;
3640cd37da74Snw141292 	sql = sqlite_mprintf("SELECT sidprefix, rid, type, canon_name "
3641cd37da74Snw141292 	    "FROM name_cache WHERE name = %Q AND domain = %Q AND "
3642c5c4113dSnw141292 	    "(expiration = 0 OR expiration ISNULL OR "
3643cd37da74Snw141292 	    "expiration > %d);", lower_name, domain, curtime);
3644cd37da74Snw141292 	if (lower_name != name)
3645cd37da74Snw141292 		free(lower_name);
3646c5c4113dSnw141292 	if (sql == NULL) {
3647c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3648c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
3649c5c4113dSnw141292 		goto out;
3650c5c4113dSnw141292 	}
3651cd37da74Snw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 4, &values);
3652c5c4113dSnw141292 	sqlite_freemem(sql);
3653c5c4113dSnw141292 
3654c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
365562c60062Sbaban 		if (type != NULL) {
3656c5c4113dSnw141292 			if (values[2] == NULL) {
3657c5c4113dSnw141292 				retcode = IDMAP_ERR_CACHE;
3658c5c4113dSnw141292 				goto out;
3659c5c4113dSnw141292 			}
3660c5c4113dSnw141292 			*type = strtol(values[2], &end, 10);
3661c5c4113dSnw141292 		}
3662c5c4113dSnw141292 
3663e8c27ec8Sbaban 		if (values[0] == NULL || values[1] == NULL) {
3664e8c27ec8Sbaban 			retcode = IDMAP_ERR_CACHE;
3665e8c27ec8Sbaban 			goto out;
3666e8c27ec8Sbaban 		}
3667e8c27ec8Sbaban 
3668cd37da74Snw141292 		if (canonname != NULL) {
3669cd37da74Snw141292 			assert(values[3] != NULL);
3670cd37da74Snw141292 			if ((*canonname = strdup(values[3])) == NULL) {
3671cd37da74Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
3672cd37da74Snw141292 				retcode = IDMAP_ERR_MEMORY;
3673cd37da74Snw141292 				goto out;
3674cd37da74Snw141292 			}
3675cd37da74Snw141292 		}
3676cd37da74Snw141292 
3677c5c4113dSnw141292 		if ((*sidprefix = strdup(values[0])) == NULL) {
3678c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
3679c5c4113dSnw141292 			retcode = IDMAP_ERR_MEMORY;
3680e8c27ec8Sbaban 			if (canonname != NULL) {
3681e8c27ec8Sbaban 				free(*canonname);
3682e8c27ec8Sbaban 				*canonname = NULL;
3683e8c27ec8Sbaban 			}
3684c5c4113dSnw141292 			goto out;
3685c5c4113dSnw141292 		}
3686c5c4113dSnw141292 		*rid = strtoul(values[1], &end, 10);
3687c5c4113dSnw141292 	}
3688c5c4113dSnw141292 
3689c5c4113dSnw141292 out:
369062c60062Sbaban 	if (vm != NULL)
3691c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
3692c5c4113dSnw141292 	return (retcode);
3693c5c4113dSnw141292 }
3694c5c4113dSnw141292 
3695cd37da74Snw141292 static
3696cd37da74Snw141292 idmap_retcode
3697e8c27ec8Sbaban ad_lookup_by_winname(lookup_state_t *state,
3698e8c27ec8Sbaban 		const char *name, const char *domain, int eunixtype,
369948258c6bSjp151216 		char **dn, char **attr, char **value, char **canonname,
370048258c6bSjp151216 		char **sidprefix, idmap_rid_t *rid, int *wintype,
370148258c6bSjp151216 		char **unixname)
3702cd37da74Snw141292 {
3703*4d61c878SJulian Pullen 	int			retries;
3704c5c4113dSnw141292 	idmap_query_state_t	*qs = NULL;
3705c5c4113dSnw141292 	idmap_retcode		rc, retcode;
3706*4d61c878SJulian Pullen 	int			i;
3707*4d61c878SJulian Pullen 	int			found_ad = 0;
3708c5c4113dSnw141292 
37092b4a7802SBaban Kenkre 	RDLOCK_CONFIG();
3710*4d61c878SJulian Pullen 	if (_idmapdstate.num_ads > 0) {
3711*4d61c878SJulian Pullen 		for (i = 0; i < _idmapdstate.num_ads && !found_ad; i++) {
3712*4d61c878SJulian Pullen 			retries = 0;
3713*4d61c878SJulian Pullen retry:
3714*4d61c878SJulian Pullen 			retcode = idmap_lookup_batch_start(_idmapdstate.ads[i],
3715*4d61c878SJulian Pullen 			    1, &qs);
3716e8c27ec8Sbaban 			if (retcode != IDMAP_SUCCESS) {
37172b4a7802SBaban Kenkre 				if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
37182b4a7802SBaban Kenkre 				    retries++ < ADUTILS_DEF_NUM_RETRIES)
37190dcc7149Snw141292 					goto retry;
3720*4d61c878SJulian Pullen 				degrade_svc(1, "failed to create request for "
3721*4d61c878SJulian Pullen 				    "AD lookup by winname");
3722e8c27ec8Sbaban 				return (retcode);
3723c5c4113dSnw141292 			}
3724c5c4113dSnw141292 
3725c8e26105Sjp151216 			restore_svc();
3726c8e26105Sjp151216 
3727*4d61c878SJulian Pullen 			if (state != NULL && i == 0) {
3728*4d61c878SJulian Pullen 				/*
3729*4d61c878SJulian Pullen 				 * Directory based name mapping is only
3730*4d61c878SJulian Pullen 				 * performed within the joined forest (i == 0).
3731*4d61c878SJulian Pullen 				 * We don't trust other "trusted" forests to
3732*4d61c878SJulian Pullen 				 * provide DS-based name mapping information
3733*4d61c878SJulian Pullen 				 * because AD's definition of "cross-forest
3734*4d61c878SJulian Pullen 				 * trust" does not encompass this sort of
3735*4d61c878SJulian Pullen 				 * behavior.
3736*4d61c878SJulian Pullen 				 */
3737*4d61c878SJulian Pullen 				idmap_lookup_batch_set_unixattr(qs,
3738*4d61c878SJulian Pullen 				    state->ad_unixuser_attr,
3739e8c27ec8Sbaban 				    state->ad_unixgroup_attr);
3740*4d61c878SJulian Pullen 			}
3741c5c4113dSnw141292 
3742*4d61c878SJulian Pullen 			retcode = idmap_name2sid_batch_add1(qs, name, domain,
3743*4d61c878SJulian Pullen 			    eunixtype, dn, attr, value, canonname, sidprefix,
3744*4d61c878SJulian Pullen 			    rid, wintype, unixname, &rc);
3745*4d61c878SJulian Pullen 			if (retcode == IDMAP_ERR_DOMAIN_NOTFOUND) {
3746*4d61c878SJulian Pullen 				idmap_lookup_release_batch(&qs);
3747*4d61c878SJulian Pullen 				continue;
3748*4d61c878SJulian Pullen 			}
3749*4d61c878SJulian Pullen 			found_ad = 1;
3750e8c27ec8Sbaban 			if (retcode != IDMAP_SUCCESS)
375184decf41Sjp151216 				idmap_lookup_release_batch(&qs);
3752c5c4113dSnw141292 			else
37530dcc7149Snw141292 				retcode = idmap_lookup_batch_end(&qs);
3754c5c4113dSnw141292 
37552b4a7802SBaban Kenkre 			if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
37562b4a7802SBaban Kenkre 			    retries++ < ADUTILS_DEF_NUM_RETRIES)
3757c5c4113dSnw141292 				goto retry;
3758c8e26105Sjp151216 			else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
3759*4d61c878SJulian Pullen 				degrade_svc(1,
3760*4d61c878SJulian Pullen 				    "some AD lookups timed out repeatedly");
3761*4d61c878SJulian Pullen 		}
3762*4d61c878SJulian Pullen 	} else {
3763*4d61c878SJulian Pullen 		/* No AD case */
3764*4d61c878SJulian Pullen 		retcode = IDMAP_ERR_NO_ACTIVEDIRECTORY;
3765*4d61c878SJulian Pullen 	}
3766*4d61c878SJulian Pullen 	UNLOCK_CONFIG();
3767c5c4113dSnw141292 
3768c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS) {
3769e8c27ec8Sbaban 		idmapdlog(LOG_NOTICE, "AD lookup by winname failed");
3770c5c4113dSnw141292 		return (retcode);
3771e8c27ec8Sbaban 	}
3772c5c4113dSnw141292 	return (rc);
3773c5c4113dSnw141292 }
3774c5c4113dSnw141292 
3775cd37da74Snw141292 idmap_retcode
3776c5c4113dSnw141292 lookup_name2sid(sqlite *cache, const char *name, const char *domain,
3777cd37da74Snw141292 		int *is_wuser, char **canonname, char **sidprefix,
3778479ac375Sdm199847 		idmap_rid_t *rid, idmap_mapping *req, int local_only)
3779cd37da74Snw141292 {
3780c5c4113dSnw141292 	int		type;
3781c5c4113dSnw141292 	idmap_retcode	retcode;
3782c5c4113dSnw141292 
3783cd37da74Snw141292 	*sidprefix = NULL;
3784e8c27ec8Sbaban 	if (canonname != NULL)
3785cd37da74Snw141292 		*canonname = NULL;
3786cd37da74Snw141292 
3787e8c27ec8Sbaban 	/* Lookup well-known SIDs table */
3788cd37da74Snw141292 	retcode = lookup_wksids_name2sid(name, canonname, sidprefix, rid,
3789cd37da74Snw141292 	    &type);
379062c60062Sbaban 	if (retcode == IDMAP_SUCCESS) {
3791e8c27ec8Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
379262c60062Sbaban 		goto out;
379362c60062Sbaban 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
379462c60062Sbaban 		return (retcode);
379562c60062Sbaban 	}
379662c60062Sbaban 
3797e8c27ec8Sbaban 	/* Lookup cache */
3798cd37da74Snw141292 	retcode = lookup_cache_name2sid(cache, name, domain, canonname,
3799cd37da74Snw141292 	    sidprefix, rid, &type);
3800e8c27ec8Sbaban 	if (retcode == IDMAP_SUCCESS) {
3801e8c27ec8Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
3802e8c27ec8Sbaban 		goto out;
3803e8c27ec8Sbaban 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
3804e8c27ec8Sbaban 		return (retcode);
3805e8c27ec8Sbaban 	}
3806e8c27ec8Sbaban 
3807479ac375Sdm199847 	/*
3808479ac375Sdm199847 	 * The caller may be using this function to determine if this
3809479ac375Sdm199847 	 * request needs to be marked for AD lookup or not
3810479ac375Sdm199847 	 * (i.e. _IDMAP_F_LOOKUP_AD) and therefore may not want this
3811479ac375Sdm199847 	 * function to AD lookup now.
3812479ac375Sdm199847 	 */
3813479ac375Sdm199847 	if (local_only)
3814479ac375Sdm199847 		return (retcode);
3815479ac375Sdm199847 
3816e8c27ec8Sbaban 	/* Lookup AD */
3817e8c27ec8Sbaban 	retcode = ad_lookup_by_winname(NULL, name, domain, _IDMAP_T_UNDEF,
381848258c6bSjp151216 	    NULL, NULL, NULL, canonname, sidprefix, rid, &type, NULL);
3819c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
3820c5c4113dSnw141292 		return (retcode);
3821c5c4113dSnw141292 
382262c60062Sbaban out:
3823c5c4113dSnw141292 	/*
3824c5c4113dSnw141292 	 * Entry found (cache or Windows lookup)
3825cd37da74Snw141292 	 * is_wuser is both input as well as output parameter
3826c5c4113dSnw141292 	 */
3827e8c27ec8Sbaban 	if (*is_wuser == 1 && type != _IDMAP_T_USER)
3828e8c27ec8Sbaban 		retcode = IDMAP_ERR_NOTUSER;
3829e8c27ec8Sbaban 	else if (*is_wuser == 0 && type != _IDMAP_T_GROUP)
3830e8c27ec8Sbaban 		retcode = IDMAP_ERR_NOTGROUP;
3831e8c27ec8Sbaban 	else if (*is_wuser == -1) {
3832c5c4113dSnw141292 		/* Caller wants to know if its user or group */
3833c5c4113dSnw141292 		if (type == _IDMAP_T_USER)
3834cd37da74Snw141292 			*is_wuser = 1;
3835c5c4113dSnw141292 		else if (type == _IDMAP_T_GROUP)
3836cd37da74Snw141292 			*is_wuser = 0;
3837e8c27ec8Sbaban 		else
3838e8c27ec8Sbaban 			retcode = IDMAP_ERR_SID;
3839e8c27ec8Sbaban 	}
3840e8c27ec8Sbaban 
3841e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
3842cd37da74Snw141292 		free(*sidprefix);
3843cd37da74Snw141292 		*sidprefix = NULL;
3844e8c27ec8Sbaban 		if (canonname != NULL) {
3845cd37da74Snw141292 			free(*canonname);
3846cd37da74Snw141292 			*canonname = NULL;
3847cd37da74Snw141292 		}
3848c5c4113dSnw141292 	}
3849c5c4113dSnw141292 	return (retcode);
3850c5c4113dSnw141292 }
3851c5c4113dSnw141292 
3852cd37da74Snw141292 static
3853cd37da74Snw141292 idmap_retcode
3854479ac375Sdm199847 name_based_mapping_pid2sid(lookup_state_t *state, const char *unixname,
3855cd37da74Snw141292 		int is_user, idmap_mapping *req, idmap_id_res *res)
3856cd37da74Snw141292 {
3857c5c4113dSnw141292 	const char	*winname, *windomain;
3858cd37da74Snw141292 	char		*canonname;
3859c5c4113dSnw141292 	char		*sql = NULL, *errmsg = NULL;
3860c5c4113dSnw141292 	idmap_retcode	retcode;
3861c5c4113dSnw141292 	char		*end;
3862c5c4113dSnw141292 	const char	**values;
3863c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
386448258c6bSjp151216 	int		ncol, r;
3865cd37da74Snw141292 	int		is_wuser;
3866e8c27ec8Sbaban 	const char	*me = "name_based_mapping_pid2sid";
386748258c6bSjp151216 	int 		non_wild_match = FALSE;
386848258c6bSjp151216 	idmap_namerule	*rule = &res->info.how.idmap_how_u.rule;
386948258c6bSjp151216 	int direction;
3870e8c27ec8Sbaban 
3871e8c27ec8Sbaban 	assert(unixname != NULL); /* We have unixname */
3872e8c27ec8Sbaban 	assert(req->id2name == NULL); /* We don't have winname */
3873e8c27ec8Sbaban 	assert(res->id.idmap_id_u.sid.prefix == NULL); /* No SID either */
3874c5c4113dSnw141292 
3875c5c4113dSnw141292 	sql = sqlite_mprintf(
387648258c6bSjp151216 	    "SELECT winname_display, windomain, w2u_order, "
387748258c6bSjp151216 	    "is_wuser, unixname, is_nt4 "
387848258c6bSjp151216 	    "FROM namerules WHERE "
3879c5c4113dSnw141292 	    "u2w_order > 0 AND is_user = %d AND "
3880c5c4113dSnw141292 	    "(unixname = %Q OR unixname = '*') "
3881cd37da74Snw141292 	    "ORDER BY u2w_order ASC;", is_user, unixname);
3882c5c4113dSnw141292 	if (sql == NULL) {
3883c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3884c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
3885c5c4113dSnw141292 		goto out;
3886c5c4113dSnw141292 	}
3887c5c4113dSnw141292 
3888479ac375Sdm199847 	if (sqlite_compile(state->db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
3889c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3890cd37da74Snw141292 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
3891cd37da74Snw141292 		    CHECK_NULL(errmsg));
3892c5c4113dSnw141292 		sqlite_freemem(errmsg);
3893c5c4113dSnw141292 		goto out;
3894c5c4113dSnw141292 	}
3895c5c4113dSnw141292 
389648258c6bSjp151216 	for (;;) {
3897c5c4113dSnw141292 		r = sqlite_step(vm, &ncol, &values, NULL);
389884decf41Sjp151216 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
389984decf41Sjp151216 		if (r == SQLITE_ROW) {
390048258c6bSjp151216 			if (ncol < 6) {
3901c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
3902c5c4113dSnw141292 				goto out;
3903c5c4113dSnw141292 			}
3904c5c4113dSnw141292 			if (values[0] == NULL) {
3905c5c4113dSnw141292 				/* values [1] and [2] can be null */
3906c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
3907c5c4113dSnw141292 				goto out;
3908c5c4113dSnw141292 			}
390948258c6bSjp151216 
391048258c6bSjp151216 			if (values[2] != NULL)
391148258c6bSjp151216 				direction =
391248258c6bSjp151216 				    (strtol(values[2], &end, 10) == 0)?
391348258c6bSjp151216 				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
391448258c6bSjp151216 			else
391548258c6bSjp151216 				direction = IDMAP_DIRECTION_U2W;
391648258c6bSjp151216 
3917c5c4113dSnw141292 			if (EMPTY_NAME(values[0])) {
391848258c6bSjp151216 				idmap_namerule_set(rule, values[1], values[0],
391948258c6bSjp151216 				    values[4], is_user,
392048258c6bSjp151216 				    strtol(values[3], &end, 10),
392148258c6bSjp151216 				    strtol(values[5], &end, 10),
392248258c6bSjp151216 				    direction);
3923c5c4113dSnw141292 				retcode = IDMAP_ERR_NOMAPPING;
3924c5c4113dSnw141292 				goto out;
3925c5c4113dSnw141292 			}
3926cd37da74Snw141292 
3927cd37da74Snw141292 			if (values[0][0] == '*') {
392848258c6bSjp151216 				winname = unixname;
392948258c6bSjp151216 				if (non_wild_match) {
3930cd37da74Snw141292 					/*
393148258c6bSjp151216 					 * There were non-wildcard rules
393248258c6bSjp151216 					 * where the Windows identity doesn't
393348258c6bSjp151216 					 * exist. Return no mapping.
3934cd37da74Snw141292 					 */
3935cd37da74Snw141292 					retcode = IDMAP_ERR_NOMAPPING;
3936cd37da74Snw141292 					goto out;
3937cd37da74Snw141292 				}
3938cd37da74Snw141292 			} else {
393948258c6bSjp151216 				/* Save first non-wild match rule */
394048258c6bSjp151216 				if (!non_wild_match) {
394148258c6bSjp151216 					idmap_namerule_set(rule, values[1],
394248258c6bSjp151216 					    values[0], values[4],
394348258c6bSjp151216 					    is_user,
394448258c6bSjp151216 					    strtol(values[3], &end, 10),
394548258c6bSjp151216 					    strtol(values[5], &end, 10),
394648258c6bSjp151216 					    direction);
394748258c6bSjp151216 					non_wild_match = TRUE;
394848258c6bSjp151216 				}
3949cd37da74Snw141292 				winname = values[0];
3950cd37da74Snw141292 			}
395148258c6bSjp151216 			is_wuser = res->id.idtype == IDMAP_USID ? 1
395248258c6bSjp151216 			    : res->id.idtype == IDMAP_GSID ? 0
395348258c6bSjp151216 			    : -1;
395462c60062Sbaban 			if (values[1] != NULL)
3955c5c4113dSnw141292 				windomain = values[1];
3956479ac375Sdm199847 			else if (state->defdom != NULL)
3957479ac375Sdm199847 				windomain = state->defdom;
3958c5c4113dSnw141292 			else {
3959cd37da74Snw141292 				idmapdlog(LOG_ERR, "%s: no domain", me);
3960c5c4113dSnw141292 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
3961c5c4113dSnw141292 				goto out;
3962c5c4113dSnw141292 			}
3963cd37da74Snw141292 
3964479ac375Sdm199847 			retcode = lookup_name2sid(state->cache,
3965479ac375Sdm199847 			    winname, windomain,
3966cd37da74Snw141292 			    &is_wuser, &canonname,
3967cd37da74Snw141292 			    &res->id.idmap_id_u.sid.prefix,
3968479ac375Sdm199847 			    &res->id.idmap_id_u.sid.rid, req, 0);
3969e8c27ec8Sbaban 
3970c5c4113dSnw141292 			if (retcode == IDMAP_ERR_NOTFOUND) {
3971c5c4113dSnw141292 				continue;
3972c5c4113dSnw141292 			}
3973c5c4113dSnw141292 			goto out;
397448258c6bSjp151216 
3975c5c4113dSnw141292 		} else if (r == SQLITE_DONE) {
397648258c6bSjp151216 			/*
397748258c6bSjp151216 			 * If there were non-wildcard rules where
397848258c6bSjp151216 			 * Windows identity doesn't exist
397948258c6bSjp151216 			 * return no mapping.
398048258c6bSjp151216 			 */
398148258c6bSjp151216 			if (non_wild_match)
398248258c6bSjp151216 				retcode = IDMAP_ERR_NOMAPPING;
398348258c6bSjp151216 			else
3984c5c4113dSnw141292 				retcode = IDMAP_ERR_NOTFOUND;
3985c5c4113dSnw141292 			goto out;
3986c5c4113dSnw141292 		} else {
3987c5c4113dSnw141292 			(void) sqlite_finalize(vm, &errmsg);
3988c5c4113dSnw141292 			vm = NULL;
3989cd37da74Snw141292 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
3990cd37da74Snw141292 			    CHECK_NULL(errmsg));
3991c5c4113dSnw141292 			sqlite_freemem(errmsg);
3992c5c4113dSnw141292 			retcode = IDMAP_ERR_INTERNAL;
3993c5c4113dSnw141292 			goto out;
3994c5c4113dSnw141292 		}
3995c5c4113dSnw141292 	}
3996c5c4113dSnw141292 
3997c5c4113dSnw141292 out:
399862c60062Sbaban 	if (sql != NULL)
3999c5c4113dSnw141292 		sqlite_freemem(sql);
400048258c6bSjp151216 	res->info.how.map_type = IDMAP_MAP_TYPE_RULE_BASED;
4001c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
4002cd37da74Snw141292 		res->id.idtype = is_wuser ? IDMAP_USID : IDMAP_GSID;
4003cd37da74Snw141292 
400462c60062Sbaban 		if (values[2] != NULL)
4005c5c4113dSnw141292 			res->direction =
4006651c0131Sbaban 			    (strtol(values[2], &end, 10) == 0)?
4007651c0131Sbaban 			    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
4008c5c4113dSnw141292 		else
4009651c0131Sbaban 			res->direction = IDMAP_DIRECTION_U2W;
40108e228215Sdm199847 
4011cd37da74Snw141292 		req->id2name = canonname;
40128e228215Sdm199847 		if (req->id2name != NULL) {
40138e228215Sdm199847 			req->id2domain = strdup(windomain);
4014479ac375Sdm199847 			if (req->id2domain == NULL)
4015479ac375Sdm199847 				retcode = IDMAP_ERR_MEMORY;
40168e228215Sdm199847 		}
4017c5c4113dSnw141292 	}
4018479ac375Sdm199847 
4019479ac375Sdm199847 	if (retcode == IDMAP_SUCCESS) {
402048258c6bSjp151216 		idmap_namerule_set(rule, values[1], values[0], values[4],
402148258c6bSjp151216 		    is_user, strtol(values[3], &end, 10),
402248258c6bSjp151216 		    strtol(values[5], &end, 10),
402348258c6bSjp151216 		    rule->direction);
402448258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
4025c5c4113dSnw141292 	}
402662c60062Sbaban 	if (vm != NULL)
4027c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
4028c5c4113dSnw141292 	return (retcode);
4029c5c4113dSnw141292 }
4030c5c4113dSnw141292 
4031cd37da74Snw141292 /*
4032cd37da74Snw141292  * Convention when processing unix2win requests:
4033cd37da74Snw141292  *
4034cd37da74Snw141292  * Unix identity:
4035cd37da74Snw141292  * req->id1name =
4036cd37da74Snw141292  *              unixname if given otherwise unixname found will be placed
4037cd37da74Snw141292  *              here.
4038cd37da74Snw141292  * req->id1domain =
4039cd37da74Snw141292  *              NOT USED
4040cd37da74Snw141292  * req->id1.idtype =
4041cd37da74Snw141292  *              Given type (IDMAP_UID or IDMAP_GID)
4042cd37da74Snw141292  * req->id1..[uid or gid] =
4043cd37da74Snw141292  *              UID/GID if given otherwise UID/GID found will be placed here.
4044cd37da74Snw141292  *
4045cd37da74Snw141292  * Windows identity:
4046cd37da74Snw141292  * req->id2name =
4047cd37da74Snw141292  *              winname found will be placed here.
4048cd37da74Snw141292  * req->id2domain =
4049cd37da74Snw141292  *              windomain found will be placed here.
4050cd37da74Snw141292  * res->id.idtype =
4051cd37da74Snw141292  *              Target type initialized from req->id2.idtype. If
4052cd37da74Snw141292  *              it is IDMAP_SID then actual type (IDMAP_USID/GSID) found
4053cd37da74Snw141292  *              will be placed here.
4054cd37da74Snw141292  * req->id..sid.[prefix, rid] =
4055cd37da74Snw141292  *              SID found will be placed here.
4056cd37da74Snw141292  *
4057cd37da74Snw141292  * Others:
4058cd37da74Snw141292  * res->retcode =
4059cd37da74Snw141292  *              Return status for this request will be placed here.
4060cd37da74Snw141292  * res->direction =
4061cd37da74Snw141292  *              Direction found will be placed here. Direction
4062cd37da74Snw141292  *              meaning whether the resultant mapping is valid
4063cd37da74Snw141292  *              only from unix2win or bi-directional.
4064cd37da74Snw141292  * req->direction =
4065cd37da74Snw141292  *              INTERNAL USE. Used by idmapd to set various
4066cd37da74Snw141292  *              flags (_IDMAP_F_xxxx) to aid in processing
4067cd37da74Snw141292  *              of the request.
4068cd37da74Snw141292  * req->id2.idtype =
4069cd37da74Snw141292  *              INTERNAL USE. Initially this is the requested target
4070cd37da74Snw141292  *              type and is used to initialize res->id.idtype.
4071cd37da74Snw141292  *              ad_lookup_batch() uses this field temporarily to store
4072cd37da74Snw141292  *              sid_type obtained by the batched AD lookups and after
4073cd37da74Snw141292  *              use resets it to IDMAP_NONE to prevent xdr from
4074cd37da74Snw141292  *              mis-interpreting the contents of req->id2.
4075cd37da74Snw141292  * req->id2..[uid or gid or sid] =
4076cd37da74Snw141292  *              NOT USED
4077cd37da74Snw141292  */
4078cd37da74Snw141292 
4079cd37da74Snw141292 /*
4080cd37da74Snw141292  * This function does the following:
4081cd37da74Snw141292  * 1. Lookup well-known SIDs table.
4082cd37da74Snw141292  * 2. Lookup cache.
4083cd37da74Snw141292  * 3. Check if the client does not want new mapping to be allocated
4084cd37da74Snw141292  *    in which case this pass is the final pass.
4085e8c27ec8Sbaban  * 4. Set AD/NLDAP lookup flags if it determines that the next stage needs
4086e8c27ec8Sbaban  *    to do AD/NLDAP lookup.
4087cd37da74Snw141292  */
4088c5c4113dSnw141292 idmap_retcode
4089479ac375Sdm199847 pid2sid_first_pass(lookup_state_t *state, idmap_mapping *req,
4090479ac375Sdm199847 		idmap_id_res *res, int is_user, int getname)
4091cd37da74Snw141292 {
4092e8c27ec8Sbaban 	idmap_retcode	retcode;
4093e8c27ec8Sbaban 	bool_t		gen_localsid_on_err = FALSE;
4094c5c4113dSnw141292 
4095e8c27ec8Sbaban 	/* Initialize result */
4096c5c4113dSnw141292 	res->id.idtype = req->id2.idtype;
4097e8c27ec8Sbaban 	res->direction = IDMAP_DIRECTION_UNDEF;
4098c5c4113dSnw141292 
4099e8c27ec8Sbaban 	if (req->id2.idmap_id_u.sid.prefix != NULL) {
4100e8c27ec8Sbaban 		/* sanitize sidprefix */
4101e8c27ec8Sbaban 		free(req->id2.idmap_id_u.sid.prefix);
4102e8c27ec8Sbaban 		req->id2.idmap_id_u.sid.prefix = NULL;
4103e8c27ec8Sbaban 	}
4104e8c27ec8Sbaban 
410548258c6bSjp151216 	/* Find pid */
410648258c6bSjp151216 	if (req->id1.idmap_id_u.uid == SENTINEL_PID) {
410748258c6bSjp151216 		if (ns_lookup_byname(req->id1name, NULL, &req->id1)
410848258c6bSjp151216 		    != IDMAP_SUCCESS) {
410948258c6bSjp151216 			retcode = IDMAP_ERR_NOMAPPING;
411048258c6bSjp151216 			goto out;
411148258c6bSjp151216 		}
411248258c6bSjp151216 	}
411348258c6bSjp151216 
4114e8c27ec8Sbaban 	/* Lookup well-known SIDs table */
4115c5c4113dSnw141292 	retcode = lookup_wksids_pid2sid(req, res, is_user);
4116c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
4117c5c4113dSnw141292 		goto out;
4118c5c4113dSnw141292 
4119e8c27ec8Sbaban 	/* Lookup cache */
4120479ac375Sdm199847 	retcode = lookup_cache_pid2sid(state->cache, req, res, is_user,
4121479ac375Sdm199847 	    getname);
4122c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
4123c5c4113dSnw141292 		goto out;
4124c5c4113dSnw141292 
4125c5c4113dSnw141292 	/* Ephemeral ids cannot be allocated during pid2sid */
4126c5c4113dSnw141292 	if (IS_EPHEMERAL(req->id1.idmap_id_u.uid)) {
412762c60062Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
4128c5c4113dSnw141292 		goto out;
4129c5c4113dSnw141292 	}
4130c5c4113dSnw141292 
413148258c6bSjp151216 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req)) {
4132*4d61c878SJulian Pullen 		retcode = IDMAP_ERR_NONE_GENERATED;
413348258c6bSjp151216 		goto out;
413448258c6bSjp151216 	}
413548258c6bSjp151216 
413648258c6bSjp151216 	if (AVOID_NAMESERVICE(req)) {
4137e8c27ec8Sbaban 		gen_localsid_on_err = TRUE;
413862c60062Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
4139c5c4113dSnw141292 		goto out;
4140c5c4113dSnw141292 	}
4141c5c4113dSnw141292 
4142e8c27ec8Sbaban 	/* Set flags for the next stage */
4143e8c27ec8Sbaban 	if (AD_MODE(req->id1.idtype, state)) {
4144e8c27ec8Sbaban 		/*
4145e8c27ec8Sbaban 		 * If AD-based name mapping is enabled then the next stage
4146e8c27ec8Sbaban 		 * will need to lookup AD using unixname to get the
4147e8c27ec8Sbaban 		 * corresponding winname.
4148e8c27ec8Sbaban 		 */
4149e8c27ec8Sbaban 		if (req->id1name == NULL) {
4150e8c27ec8Sbaban 			/* Get unixname if only pid is given. */
4151e8c27ec8Sbaban 			retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid,
4152e8c27ec8Sbaban 			    is_user, &req->id1name);
4153479ac375Sdm199847 			if (retcode != IDMAP_SUCCESS) {
4154479ac375Sdm199847 				gen_localsid_on_err = TRUE;
4155e8c27ec8Sbaban 				goto out;
4156c5c4113dSnw141292 			}
4157479ac375Sdm199847 		}
4158e8c27ec8Sbaban 		req->direction |= _IDMAP_F_LOOKUP_AD;
4159e8c27ec8Sbaban 		state->ad_nqueries++;
4160e8c27ec8Sbaban 	} else if (NLDAP_OR_MIXED_MODE(req->id1.idtype, state)) {
4161e8c27ec8Sbaban 		/*
4162e8c27ec8Sbaban 		 * If native LDAP or mixed mode is enabled for name mapping
4163e8c27ec8Sbaban 		 * then the next stage will need to lookup native LDAP using
4164e8c27ec8Sbaban 		 * unixname/pid to get the corresponding winname.
4165e8c27ec8Sbaban 		 */
4166e8c27ec8Sbaban 		req->direction |= _IDMAP_F_LOOKUP_NLDAP;
4167e8c27ec8Sbaban 		state->nldap_nqueries++;
4168c5c4113dSnw141292 	}
4169c5c4113dSnw141292 
4170e8c27ec8Sbaban 	/*
4171e8c27ec8Sbaban 	 * Failed to find non-expired entry in cache. Set the flag to
4172e8c27ec8Sbaban 	 * indicate that we are not done yet.
4173e8c27ec8Sbaban 	 */
4174e8c27ec8Sbaban 	state->pid2sid_done = FALSE;
4175e8c27ec8Sbaban 	req->direction |= _IDMAP_F_NOTDONE;
4176e8c27ec8Sbaban 	retcode = IDMAP_SUCCESS;
4177e8c27ec8Sbaban 
4178e8c27ec8Sbaban out:
4179e8c27ec8Sbaban 	res->retcode = idmap_stat4prot(retcode);
4180e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
4181e8c27ec8Sbaban 		if (gen_localsid_on_err == TRUE)
418248258c6bSjp151216 			(void) generate_localsid(req, res, is_user, TRUE);
4183e8c27ec8Sbaban 	return (retcode);
4184e8c27ec8Sbaban }
4185e8c27ec8Sbaban 
4186e8c27ec8Sbaban idmap_retcode
4187479ac375Sdm199847 pid2sid_second_pass(lookup_state_t *state, idmap_mapping *req,
4188479ac375Sdm199847 	idmap_id_res *res, int is_user)
4189e8c27ec8Sbaban {
4190e8c27ec8Sbaban 	bool_t		gen_localsid_on_err = TRUE;
4191e8c27ec8Sbaban 	idmap_retcode	retcode = IDMAP_SUCCESS;
4192e8c27ec8Sbaban 
4193e8c27ec8Sbaban 	/* Check if second pass is needed */
4194e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
4195e8c27ec8Sbaban 		return (res->retcode);
4196e8c27ec8Sbaban 
4197e8c27ec8Sbaban 	/* Get status from previous pass */
4198e8c27ec8Sbaban 	retcode = res->retcode;
4199e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
4200e8c27ec8Sbaban 		goto out;
4201e8c27ec8Sbaban 
4202e8c27ec8Sbaban 	/*
4203e8c27ec8Sbaban 	 * If directory-based name mapping is enabled then the winname
4204e8c27ec8Sbaban 	 * may already have been retrieved from the AD object (AD-mode)
4205479ac375Sdm199847 	 * or from native LDAP object (nldap-mode or mixed-mode).
4206479ac375Sdm199847 	 * Note that if we have winname but no SID then it's an error
4207479ac375Sdm199847 	 * because this implies that the Native LDAP entry contains
4208479ac375Sdm199847 	 * winname which does not exist and it's better that we return
4209479ac375Sdm199847 	 * an error instead of doing rule-based mapping so that the user
4210479ac375Sdm199847 	 * can detect the issue and take appropriate action.
4211e8c27ec8Sbaban 	 */
4212479ac375Sdm199847 	if (req->id2name != NULL) {
4213479ac375Sdm199847 		/* Return notfound if we've winname but no SID. */
4214479ac375Sdm199847 		if (res->id.idmap_id_u.sid.prefix == NULL) {
4215479ac375Sdm199847 			retcode = IDMAP_ERR_NOTFOUND;
4216479ac375Sdm199847 			goto out;
4217479ac375Sdm199847 		}
4218e8c27ec8Sbaban 		if (AD_MODE(req->id1.idtype, state))
4219e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
4220e8c27ec8Sbaban 		else if (NLDAP_MODE(req->id1.idtype, state))
4221e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
4222e8c27ec8Sbaban 		else if (MIXED_MODE(req->id1.idtype, state))
4223e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
4224e8c27ec8Sbaban 		goto out;
4225479ac375Sdm199847 	} else if (res->id.idmap_id_u.sid.prefix != NULL) {
4226479ac375Sdm199847 		/*
4227479ac375Sdm199847 		 * We've SID but no winname. This is fine because
4228479ac375Sdm199847 		 * the caller may have only requested SID.
4229479ac375Sdm199847 		 */
4230479ac375Sdm199847 		goto out;
4231e8c27ec8Sbaban 	}
4232e8c27ec8Sbaban 
4233479ac375Sdm199847 	/* Free any mapping info from Directory based mapping */
4234479ac375Sdm199847 	if (res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN)
4235479ac375Sdm199847 		idmap_info_free(&res->info);
4236479ac375Sdm199847 
4237e8c27ec8Sbaban 	if (req->id1name == NULL) {
4238e8c27ec8Sbaban 		/* Get unixname from name service */
4239e8c27ec8Sbaban 		retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid, is_user,
4240e8c27ec8Sbaban 		    &req->id1name);
4241e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS)
4242e8c27ec8Sbaban 			goto out;
4243e8c27ec8Sbaban 	} else if (req->id1.idmap_id_u.uid == SENTINEL_PID) {
4244e8c27ec8Sbaban 		/* Get pid from name service */
4245e8c27ec8Sbaban 		retcode = ns_lookup_byname(req->id1name, NULL, &req->id1);
4246e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS) {
4247e8c27ec8Sbaban 			gen_localsid_on_err = FALSE;
4248e8c27ec8Sbaban 			goto out;
4249e8c27ec8Sbaban 		}
4250e8c27ec8Sbaban 	}
4251e8c27ec8Sbaban 
4252e8c27ec8Sbaban 	/* Use unixname to evaluate local name-based mapping rules */
4253479ac375Sdm199847 	retcode = name_based_mapping_pid2sid(state, req->id1name, is_user,
4254c5c4113dSnw141292 	    req, res);
4255c5c4113dSnw141292 	if (retcode == IDMAP_ERR_NOTFOUND) {
425648258c6bSjp151216 		retcode = generate_localsid(req, res, is_user, FALSE);
4257e8c27ec8Sbaban 		gen_localsid_on_err = FALSE;
4258e8c27ec8Sbaban 	}
4259c5c4113dSnw141292 
4260c5c4113dSnw141292 out:
4261c5c4113dSnw141292 	res->retcode = idmap_stat4prot(retcode);
4262e8c27ec8Sbaban 	if (res->retcode != IDMAP_SUCCESS) {
4263e8c27ec8Sbaban 		req->direction = _IDMAP_F_DONE;
4264479ac375Sdm199847 		free(req->id2name);
4265479ac375Sdm199847 		req->id2name = NULL;
4266479ac375Sdm199847 		free(req->id2domain);
4267479ac375Sdm199847 		req->id2domain = NULL;
4268e8c27ec8Sbaban 		if (gen_localsid_on_err == TRUE)
426948258c6bSjp151216 			(void) generate_localsid(req, res, is_user, TRUE);
4270479ac375Sdm199847 		else
4271479ac375Sdm199847 			res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
4272e8c27ec8Sbaban 	}
4273e8c27ec8Sbaban 	if (!ARE_WE_DONE(req->direction))
4274e8c27ec8Sbaban 		state->pid2sid_done = FALSE;
4275c5c4113dSnw141292 	return (retcode);
4276c5c4113dSnw141292 }
4277c5c4113dSnw141292 
4278cd37da74Snw141292 static
4279cd37da74Snw141292 int
4280651c0131Sbaban copy_mapping_request(idmap_mapping *mapping, idmap_mapping *request)
4281c5c4113dSnw141292 {
4282651c0131Sbaban 	(void) memset(mapping, 0, sizeof (*mapping));
4283651c0131Sbaban 
4284c5c4113dSnw141292 	mapping->flag = request->flag;
4285e8c27ec8Sbaban 	mapping->direction = _IDMAP_F_DONE;
4286651c0131Sbaban 	mapping->id2.idtype = request->id2.idtype;
4287c5c4113dSnw141292 
4288c5c4113dSnw141292 	mapping->id1.idtype = request->id1.idtype;
4289cd37da74Snw141292 	if (IS_REQUEST_SID(*request, 1)) {
4290c5c4113dSnw141292 		mapping->id1.idmap_id_u.sid.rid =
4291c5c4113dSnw141292 		    request->id1.idmap_id_u.sid.rid;
4292651c0131Sbaban 		if (!EMPTY_STRING(request->id1.idmap_id_u.sid.prefix)) {
4293c5c4113dSnw141292 			mapping->id1.idmap_id_u.sid.prefix =
4294c5c4113dSnw141292 			    strdup(request->id1.idmap_id_u.sid.prefix);
4295651c0131Sbaban 			if (mapping->id1.idmap_id_u.sid.prefix == NULL)
42968e228215Sdm199847 				goto errout;
4297651c0131Sbaban 		}
4298c5c4113dSnw141292 	} else {
4299c5c4113dSnw141292 		mapping->id1.idmap_id_u.uid = request->id1.idmap_id_u.uid;
4300c5c4113dSnw141292 	}
4301c5c4113dSnw141292 
4302e8c27ec8Sbaban 	if (!EMPTY_STRING(request->id1domain)) {
43038e228215Sdm199847 		mapping->id1domain = strdup(request->id1domain);
43048e228215Sdm199847 		if (mapping->id1domain == NULL)
43058e228215Sdm199847 			goto errout;
4306e8c27ec8Sbaban 	}
4307c5c4113dSnw141292 
4308e8c27ec8Sbaban 	if (!EMPTY_STRING(request->id1name)) {
43098e228215Sdm199847 		mapping->id1name = strdup(request->id1name);
43108e228215Sdm199847 		if (mapping->id1name == NULL)
43118e228215Sdm199847 			goto errout;
4312e8c27ec8Sbaban 	}
4313c5c4113dSnw141292 
4314651c0131Sbaban 	/* We don't need the rest of the request i.e request->id2 */
4315651c0131Sbaban 	return (0);
4316c5c4113dSnw141292 
4317651c0131Sbaban errout:
43188e228215Sdm199847 	if (mapping->id1.idmap_id_u.sid.prefix != NULL)
4319651c0131Sbaban 		free(mapping->id1.idmap_id_u.sid.prefix);
43208e228215Sdm199847 	if (mapping->id1domain != NULL)
43218e228215Sdm199847 		free(mapping->id1domain);
43228e228215Sdm199847 	if (mapping->id1name != NULL)
43238e228215Sdm199847 		free(mapping->id1name);
4324651c0131Sbaban 
4325651c0131Sbaban 	(void) memset(mapping, 0, sizeof (*mapping));
4326651c0131Sbaban 	return (-1);
4327c5c4113dSnw141292 }
4328c5c4113dSnw141292 
4329c5c4113dSnw141292 
4330c5c4113dSnw141292 idmap_retcode
4331c5c4113dSnw141292 get_w2u_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
4332cd37da74Snw141292 		idmap_mapping *mapping)
4333cd37da74Snw141292 {
4334c5c4113dSnw141292 	idmap_id_res	idres;
4335c5c4113dSnw141292 	lookup_state_t	state;
4336dd5829d1Sbaban 	char		*cp;
4337c5c4113dSnw141292 	idmap_retcode	retcode;
4338c5c4113dSnw141292 	const char	*winname, *windomain;
4339c5c4113dSnw141292 
4340c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
4341c5c4113dSnw141292 	(void) memset(&state, 0, sizeof (state));
4342479ac375Sdm199847 	state.cache = cache;
4343479ac375Sdm199847 	state.db = db;
4344c5c4113dSnw141292 
4345e8c27ec8Sbaban 	/* Get directory-based name mapping info */
4346479ac375Sdm199847 	retcode = load_cfg_in_state(&state);
4347e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
4348c5c4113dSnw141292 		goto out;
4349c5c4113dSnw141292 
4350e8c27ec8Sbaban 	/*
4351e8c27ec8Sbaban 	 * Copy data from "request" to "mapping". Note that
4352e8c27ec8Sbaban 	 * empty strings are not copied from "request" to
4353e8c27ec8Sbaban 	 * "mapping" and therefore the coresponding strings in
4354e8c27ec8Sbaban 	 * "mapping" will be NULL. This eliminates having to
4355e8c27ec8Sbaban 	 * check for empty strings henceforth.
4356e8c27ec8Sbaban 	 */
4357651c0131Sbaban 	if (copy_mapping_request(mapping, request) < 0) {
4358651c0131Sbaban 		retcode = IDMAP_ERR_MEMORY;
4359651c0131Sbaban 		goto out;
4360651c0131Sbaban 	}
4361c5c4113dSnw141292 
43628e228215Sdm199847 	winname = mapping->id1name;
43638e228215Sdm199847 	windomain = mapping->id1domain;
4364c5c4113dSnw141292 
4365e8c27ec8Sbaban 	if (winname == NULL && windomain != NULL) {
4366c5c4113dSnw141292 		retcode = IDMAP_ERR_ARG;
4367c5c4113dSnw141292 		goto out;
4368c5c4113dSnw141292 	}
4369c5c4113dSnw141292 
4370e8c27ec8Sbaban 	/* Need atleast winname or sid to proceed */
4371e8c27ec8Sbaban 	if (winname == NULL && mapping->id1.idmap_id_u.sid.prefix == NULL) {
4372e8c27ec8Sbaban 		retcode = IDMAP_ERR_ARG;
4373e8c27ec8Sbaban 		goto out;
4374e8c27ec8Sbaban 	}
4375e8c27ec8Sbaban 
4376e8c27ec8Sbaban 	/*
4377e8c27ec8Sbaban 	 * If domainname is not given but we have a fully qualified
4378e8c27ec8Sbaban 	 * winname then extract the domainname from the winname,
4379e8c27ec8Sbaban 	 * otherwise use the default_domain from the config
4380e8c27ec8Sbaban 	 */
4381e8c27ec8Sbaban 	if (winname != NULL && windomain == NULL) {
43828e228215Sdm199847 		retcode = IDMAP_SUCCESS;
4383dd5829d1Sbaban 		if ((cp = strchr(winname, '@')) != NULL) {
4384dd5829d1Sbaban 			*cp = '\0';
43858e228215Sdm199847 			mapping->id1domain = strdup(cp + 1);
43868e228215Sdm199847 			if (mapping->id1domain == NULL)
43878e228215Sdm199847 				retcode = IDMAP_ERR_MEMORY;
4388e8c27ec8Sbaban 		} else if (lookup_wksids_name2sid(winname, NULL, NULL, NULL,
4389e8c27ec8Sbaban 		    NULL) != IDMAP_SUCCESS) {
439082da9f60Sbaban 			if (state.defdom == NULL) {
439182da9f60Sbaban 				/*
439282da9f60Sbaban 				 * We have a non-qualified winname which is
439382da9f60Sbaban 				 * neither the name of a well-known SID nor
439482da9f60Sbaban 				 * there is a default domain with which we can
439582da9f60Sbaban 				 * qualify it.
439682da9f60Sbaban 				 */
439782da9f60Sbaban 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
439882da9f60Sbaban 			} else {
4399479ac375Sdm199847 				mapping->id1domain = strdup(state.defdom);
44008e228215Sdm199847 				if (mapping->id1domain == NULL)
44018e228215Sdm199847 					retcode = IDMAP_ERR_MEMORY;
44028e228215Sdm199847 			}
440382da9f60Sbaban 		}
4404c5c4113dSnw141292 		if (retcode != IDMAP_SUCCESS)
4405c5c4113dSnw141292 			goto out;
4406c5c4113dSnw141292 	}
4407c5c4113dSnw141292 
4408e8c27ec8Sbaban 	/*
4409e8c27ec8Sbaban 	 * First pass looks up the well-known SIDs table and cache
4410e8c27ec8Sbaban 	 * and handles localSIDs
4411e8c27ec8Sbaban 	 */
4412c5c4113dSnw141292 	state.sid2pid_done = TRUE;
4413479ac375Sdm199847 	retcode = sid2pid_first_pass(&state, mapping, &idres);
4414c5c4113dSnw141292 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
4415c5c4113dSnw141292 		goto out;
4416c5c4113dSnw141292 
4417479ac375Sdm199847 	/* AD lookup */
4418e8c27ec8Sbaban 	if (state.ad_nqueries > 0) {
4419479ac375Sdm199847 		retcode = ad_lookup_one(&state, mapping, &idres);
4420e8c27ec8Sbaban 		if (IDMAP_ERROR(retcode))
4421e8c27ec8Sbaban 			goto out;
4422c5c4113dSnw141292 	}
4423c5c4113dSnw141292 
4424479ac375Sdm199847 	/* nldap lookup */
4425479ac375Sdm199847 	if (state.nldap_nqueries > 0) {
4426479ac375Sdm199847 		retcode = nldap_lookup_one(&state, mapping, &idres);
4427479ac375Sdm199847 		if (IDMAP_FATAL_ERROR(retcode))
4428e8c27ec8Sbaban 			goto out;
442948258c6bSjp151216 	}
4430e8c27ec8Sbaban 
4431e8c27ec8Sbaban 	/* Next pass performs name-based mapping and ephemeral mapping. */
4432c5c4113dSnw141292 	state.sid2pid_done = TRUE;
4433479ac375Sdm199847 	retcode = sid2pid_second_pass(&state, mapping, &idres);
4434c5c4113dSnw141292 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
4435c5c4113dSnw141292 		goto out;
4436c5c4113dSnw141292 
4437c5c4113dSnw141292 	/* Update cache */
4438479ac375Sdm199847 	(void) update_cache_sid2pid(&state, mapping, &idres);
4439c5c4113dSnw141292 
4440c5c4113dSnw141292 out:
4441e8c27ec8Sbaban 	/*
4442e8c27ec8Sbaban 	 * Note that "mapping" is returned to the client. Therefore
4443e8c27ec8Sbaban 	 * copy whatever we have in "idres" to mapping->id2 and
4444e8c27ec8Sbaban 	 * free idres.
4445e8c27ec8Sbaban 	 */
4446c5c4113dSnw141292 	mapping->direction = idres.direction;
4447c5c4113dSnw141292 	mapping->id2 = idres.id;
444848258c6bSjp151216 	if (mapping->flag & IDMAP_REQ_FLG_MAPPING_INFO ||
444948258c6bSjp151216 	    retcode != IDMAP_SUCCESS)
445048258c6bSjp151216 		(void) idmap_info_mov(&mapping->info, &idres.info);
445148258c6bSjp151216 	else
445248258c6bSjp151216 		idmap_info_free(&idres.info);
4453c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
4454e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
445562c60062Sbaban 		mapping->id2.idmap_id_u.uid = UID_NOBODY;
4456c5c4113dSnw141292 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
4457e8c27ec8Sbaban 	cleanup_lookup_state(&state);
4458c5c4113dSnw141292 	return (retcode);
4459c5c4113dSnw141292 }
4460c5c4113dSnw141292 
4461c5c4113dSnw141292 idmap_retcode
4462c5c4113dSnw141292 get_u2w_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
4463cd37da74Snw141292 		idmap_mapping *mapping, int is_user)
4464cd37da74Snw141292 {
4465c5c4113dSnw141292 	idmap_id_res	idres;
4466c5c4113dSnw141292 	lookup_state_t	state;
4467c5c4113dSnw141292 	idmap_retcode	retcode;
4468c5c4113dSnw141292 
4469c5c4113dSnw141292 	/*
4470c5c4113dSnw141292 	 * In order to re-use the pid2sid code, we convert
4471c5c4113dSnw141292 	 * our input data into structs that are expected by
4472c5c4113dSnw141292 	 * pid2sid_first_pass.
4473c5c4113dSnw141292 	 */
4474c5c4113dSnw141292 
4475c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
4476c5c4113dSnw141292 	(void) memset(&state, 0, sizeof (state));
4477479ac375Sdm199847 	state.cache = cache;
4478479ac375Sdm199847 	state.db = db;
4479c5c4113dSnw141292 
4480e8c27ec8Sbaban 	/* Get directory-based name mapping info */
4481479ac375Sdm199847 	retcode = load_cfg_in_state(&state);
4482e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
4483e8c27ec8Sbaban 		goto out;
4484e8c27ec8Sbaban 
4485e8c27ec8Sbaban 	/*
4486e8c27ec8Sbaban 	 * Copy data from "request" to "mapping". Note that
4487e8c27ec8Sbaban 	 * empty strings are not copied from "request" to
4488e8c27ec8Sbaban 	 * "mapping" and therefore the coresponding strings in
4489e8c27ec8Sbaban 	 * "mapping" will be NULL. This eliminates having to
4490e8c27ec8Sbaban 	 * check for empty strings henceforth.
4491e8c27ec8Sbaban 	 */
4492651c0131Sbaban 	if (copy_mapping_request(mapping, request) < 0) {
4493651c0131Sbaban 		retcode = IDMAP_ERR_MEMORY;
4494651c0131Sbaban 		goto out;
4495651c0131Sbaban 	}
4496c5c4113dSnw141292 
4497e8c27ec8Sbaban 	/*
4498e8c27ec8Sbaban 	 * For unix to windows mapping request, we need atleast a
4499e8c27ec8Sbaban 	 * unixname or uid/gid to proceed
4500e8c27ec8Sbaban 	 */
4501e8c27ec8Sbaban 	if (mapping->id1name == NULL &&
4502cf5b5989Sdm199847 	    mapping->id1.idmap_id_u.uid == SENTINEL_PID) {
4503c5c4113dSnw141292 		retcode = IDMAP_ERR_ARG;
4504c5c4113dSnw141292 		goto out;
4505c5c4113dSnw141292 	}
4506c5c4113dSnw141292 
4507e8c27ec8Sbaban 	/* First pass looks up cache and well-known SIDs */
4508e8c27ec8Sbaban 	state.pid2sid_done = TRUE;
4509479ac375Sdm199847 	retcode = pid2sid_first_pass(&state, mapping, &idres, is_user, 1);
4510e8c27ec8Sbaban 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
4511c5c4113dSnw141292 		goto out;
4512e8c27ec8Sbaban 
4513479ac375Sdm199847 	/* nldap lookup */
4514e8c27ec8Sbaban 	if (state.nldap_nqueries > 0) {
4515479ac375Sdm199847 		retcode = nldap_lookup_one(&state, mapping, &idres);
4516e8c27ec8Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
4517c5c4113dSnw141292 			goto out;
4518479ac375Sdm199847 	}
4519e8c27ec8Sbaban 
4520479ac375Sdm199847 	/* AD lookup */
4521479ac375Sdm199847 	if (state.ad_nqueries > 0) {
4522479ac375Sdm199847 		retcode = ad_lookup_one(&state, mapping, &idres);
4523e8c27ec8Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
4524e8c27ec8Sbaban 			goto out;
4525c5c4113dSnw141292 	}
4526c5c4113dSnw141292 
4527e8c27ec8Sbaban 	/*
4528e8c27ec8Sbaban 	 * Next pass processes the result of the preceding passes/lookups.
4529e8c27ec8Sbaban 	 * It returns if there's nothing more to be done otherwise it
4530e8c27ec8Sbaban 	 * evaluates local name-based mapping rules
4531e8c27ec8Sbaban 	 */
4532c5c4113dSnw141292 	state.pid2sid_done = TRUE;
4533479ac375Sdm199847 	retcode = pid2sid_second_pass(&state, mapping, &idres, is_user);
4534c5c4113dSnw141292 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
4535c5c4113dSnw141292 		goto out;
4536c5c4113dSnw141292 
4537c5c4113dSnw141292 	/* Update cache */
4538479ac375Sdm199847 	(void) update_cache_pid2sid(&state, mapping, &idres);
4539c5c4113dSnw141292 
4540c5c4113dSnw141292 out:
4541e8c27ec8Sbaban 	/*
4542e8c27ec8Sbaban 	 * Note that "mapping" is returned to the client. Therefore
4543e8c27ec8Sbaban 	 * copy whatever we have in "idres" to mapping->id2 and
4544e8c27ec8Sbaban 	 * free idres.
4545e8c27ec8Sbaban 	 */
4546c5c4113dSnw141292 	mapping->direction = idres.direction;
4547c5c4113dSnw141292 	mapping->id2 = idres.id;
454848258c6bSjp151216 	if (mapping->flag & IDMAP_REQ_FLG_MAPPING_INFO ||
454948258c6bSjp151216 	    retcode != IDMAP_SUCCESS)
455048258c6bSjp151216 		(void) idmap_info_mov(&mapping->info, &idres.info);
455148258c6bSjp151216 	else
455248258c6bSjp151216 		idmap_info_free(&idres.info);
4553c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
4554c5c4113dSnw141292 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
4555e8c27ec8Sbaban 	cleanup_lookup_state(&state);
4556e8c27ec8Sbaban 	return (retcode);
4557e8c27ec8Sbaban }
4558e8c27ec8Sbaban 
4559479ac375Sdm199847 /*ARGSUSED*/
4560e8c27ec8Sbaban static
4561e8c27ec8Sbaban idmap_retcode
4562479ac375Sdm199847 ad_lookup_one(lookup_state_t *state, idmap_mapping *req, idmap_id_res *res)
4563e8c27ec8Sbaban {
4564479ac375Sdm199847 	idmap_mapping_batch	batch;
4565479ac375Sdm199847 	idmap_ids_res		result;
4566e8c27ec8Sbaban 
4567479ac375Sdm199847 	batch.idmap_mapping_batch_len = 1;
4568479ac375Sdm199847 	batch.idmap_mapping_batch_val = req;
4569479ac375Sdm199847 	result.ids.ids_len = 1;
4570479ac375Sdm199847 	result.ids.ids_val = res;
4571479ac375Sdm199847 	return (ad_lookup_batch(state, &batch, &result));
4572c5c4113dSnw141292 }
4573