xref: /titanic_44/usr/src/cmd/idmap/idmapd/dbutils.c (revision 96c3a9a05f98a6ec3f12762582828fe2fcbbccd0)
1c5c4113dSnw141292 /*
2c5c4113dSnw141292  * CDDL HEADER START
3c5c4113dSnw141292  *
4c5c4113dSnw141292  * The contents of this file are subject to the terms of the
5c5c4113dSnw141292  * Common Development and Distribution License (the "License").
6c5c4113dSnw141292  * You may not use this file except in compliance with the License.
7c5c4113dSnw141292  *
8c5c4113dSnw141292  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9c5c4113dSnw141292  * or http://www.opensolaris.org/os/licensing.
10c5c4113dSnw141292  * See the License for the specific language governing permissions
11c5c4113dSnw141292  * and limitations under the License.
12c5c4113dSnw141292  *
13c5c4113dSnw141292  * When distributing Covered Code, include this CDDL HEADER in each
14c5c4113dSnw141292  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15c5c4113dSnw141292  * If applicable, add the following below this CDDL HEADER, with the
16c5c4113dSnw141292  * fields enclosed by brackets "[]" replaced with your own identifying
17c5c4113dSnw141292  * information: Portions Copyright [yyyy] [name of copyright owner]
18c5c4113dSnw141292  *
19c5c4113dSnw141292  * CDDL HEADER END
20c5c4113dSnw141292  */
21c5c4113dSnw141292 /*
22042addd6Sbaban  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23c5c4113dSnw141292  * Use is subject to license terms.
24c5c4113dSnw141292  */
25c5c4113dSnw141292 
26c5c4113dSnw141292 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27c5c4113dSnw141292 
28c5c4113dSnw141292 /*
29c5c4113dSnw141292  * Database related utility routines
30c5c4113dSnw141292  */
31c5c4113dSnw141292 
32c5c4113dSnw141292 #include <stdio.h>
33c5c4113dSnw141292 #include <stdlib.h>
34c5c4113dSnw141292 #include <string.h>
35c5c4113dSnw141292 #include <errno.h>
36c5c4113dSnw141292 #include <sys/types.h>
37c5c4113dSnw141292 #include <sys/stat.h>
38c5c4113dSnw141292 #include <rpc/rpc.h>
39c5c4113dSnw141292 #include <sys/sid.h>
40c5c4113dSnw141292 #include <time.h>
41c5c4113dSnw141292 #include <pwd.h>
42c5c4113dSnw141292 #include <grp.h>
4384decf41Sjp151216 #include <pthread.h>
4484decf41Sjp151216 #include <assert.h>
45cd37da74Snw141292 #include <sys/u8_textprep.h>
46c5c4113dSnw141292 
47c5c4113dSnw141292 #include "idmapd.h"
48c5c4113dSnw141292 #include "adutils.h"
49c5c4113dSnw141292 #include "string.h"
50c5c4113dSnw141292 #include "idmap_priv.h"
51cd37da74Snw141292 #include "schema.h"
52e8c27ec8Sbaban #include "nldaputils.h"
53c5c4113dSnw141292 
5484decf41Sjp151216 
55c5c4113dSnw141292 static idmap_retcode sql_compile_n_step_once(sqlite *, char *,
56c5c4113dSnw141292 		sqlite_vm **, int *, int, const char ***);
57479ac375Sdm199847 static idmap_retcode ad_lookup_one(lookup_state_t *, idmap_mapping *,
58479ac375Sdm199847 		idmap_id_res *);
59e8c27ec8Sbaban static idmap_retcode lookup_localsid2pid(idmap_mapping *, idmap_id_res *);
60e8c27ec8Sbaban static idmap_retcode lookup_cache_name2sid(sqlite *, const char *,
61e8c27ec8Sbaban 		const char *, char **, char **, idmap_rid_t *, int *);
62e8c27ec8Sbaban 
63c5c4113dSnw141292 
64c5c4113dSnw141292 #define	EMPTY_NAME(name)	(*name == 0 || strcmp(name, "\"\"") == 0)
65c5c4113dSnw141292 
66c5c4113dSnw141292 #define	DO_NOT_ALLOC_NEW_ID_MAPPING(req)\
67c5c4113dSnw141292 		(req->flag & IDMAP_REQ_FLG_NO_NEW_ID_ALLOC)
68c5c4113dSnw141292 
69c5c4113dSnw141292 #define	AVOID_NAMESERVICE(req)\
70c5c4113dSnw141292 		(req->flag & IDMAP_REQ_FLG_NO_NAMESERVICE)
71c5c4113dSnw141292 
72e8c27ec8Sbaban #define	IS_EPHEMERAL(pid)	(pid > INT32_MAX && pid != SENTINEL_PID)
73c5c4113dSnw141292 
74c5c4113dSnw141292 #define	LOCALRID_MIN	1000
75c5c4113dSnw141292 
76c5c4113dSnw141292 
77c5c4113dSnw141292 typedef enum init_db_option {
78c5c4113dSnw141292 	FAIL_IF_CORRUPT = 0,
79c5c4113dSnw141292 	REMOVE_IF_CORRUPT = 1
80c5c4113dSnw141292 } init_db_option_t;
81c5c4113dSnw141292 
8284decf41Sjp151216 /*
83e8c27ec8Sbaban  * Data structure to store well-known SIDs and
84e8c27ec8Sbaban  * associated mappings (if any)
85e8c27ec8Sbaban  */
86e8c27ec8Sbaban typedef struct wksids_table {
87e8c27ec8Sbaban 	const char	*sidprefix;
88e8c27ec8Sbaban 	uint32_t	rid;
89e8c27ec8Sbaban 	const char	*winname;
90e8c27ec8Sbaban 	int		is_wuser;
91e8c27ec8Sbaban 	uid_t		pid;
92e8c27ec8Sbaban 	int		is_user;
93e8c27ec8Sbaban 	int		direction;
94e8c27ec8Sbaban } wksids_table_t;
95e8c27ec8Sbaban 
96e8c27ec8Sbaban /*
9784decf41Sjp151216  * Thread specfic data to hold the database handles so that the
9884decf41Sjp151216  * databaes are not opened and closed for every request. It also
9984decf41Sjp151216  * contains the sqlite busy handler structure.
10084decf41Sjp151216  */
10184decf41Sjp151216 
10284decf41Sjp151216 struct idmap_busy {
10384decf41Sjp151216 	const char *name;
10484decf41Sjp151216 	const int *delays;
10584decf41Sjp151216 	int delay_size;
10684decf41Sjp151216 	int total;
10784decf41Sjp151216 	int sec;
10884decf41Sjp151216 };
10984decf41Sjp151216 
11084decf41Sjp151216 
11184decf41Sjp151216 typedef struct idmap_tsd {
11284decf41Sjp151216 	sqlite *db_db;
11384decf41Sjp151216 	sqlite *cache_db;
11484decf41Sjp151216 	struct idmap_busy cache_busy;
11584decf41Sjp151216 	struct idmap_busy db_busy;
11684decf41Sjp151216 } idmap_tsd_t;
11784decf41Sjp151216 
11884decf41Sjp151216 
11984decf41Sjp151216 
12084decf41Sjp151216 static const int cache_delay_table[] =
12184decf41Sjp151216 		{ 1, 2, 5, 10, 15, 20, 25, 30,  35,  40,
12284decf41Sjp151216 		50,  50, 60, 70, 80, 90, 100};
12384decf41Sjp151216 
12484decf41Sjp151216 static const int db_delay_table[] =
12584decf41Sjp151216 		{ 5, 10, 15, 20, 30,  40,  55,  70, 100};
12684decf41Sjp151216 
12784decf41Sjp151216 
12884decf41Sjp151216 static pthread_key_t	idmap_tsd_key;
12984decf41Sjp151216 
13084decf41Sjp151216 void
13184decf41Sjp151216 idmap_tsd_destroy(void *key)
13284decf41Sjp151216 {
13384decf41Sjp151216 
13484decf41Sjp151216 	idmap_tsd_t	*tsd = (idmap_tsd_t *)key;
13584decf41Sjp151216 	if (tsd) {
13684decf41Sjp151216 		if (tsd->db_db)
13784decf41Sjp151216 			(void) sqlite_close(tsd->db_db);
13884decf41Sjp151216 		if (tsd->cache_db)
13984decf41Sjp151216 			(void) sqlite_close(tsd->cache_db);
14084decf41Sjp151216 		free(tsd);
14184decf41Sjp151216 	}
14284decf41Sjp151216 }
14384decf41Sjp151216 
14484decf41Sjp151216 int
145cd37da74Snw141292 idmap_init_tsd_key(void)
146cd37da74Snw141292 {
14784decf41Sjp151216 	return (pthread_key_create(&idmap_tsd_key, idmap_tsd_destroy));
14884decf41Sjp151216 }
14984decf41Sjp151216 
15084decf41Sjp151216 
15184decf41Sjp151216 
15284decf41Sjp151216 idmap_tsd_t *
15384decf41Sjp151216 idmap_get_tsd(void)
15484decf41Sjp151216 {
15584decf41Sjp151216 	idmap_tsd_t	*tsd;
15684decf41Sjp151216 
15784decf41Sjp151216 	if ((tsd = pthread_getspecific(idmap_tsd_key)) == NULL) {
15884decf41Sjp151216 		/* No thread specific data so create it */
15984decf41Sjp151216 		if ((tsd = malloc(sizeof (*tsd))) != NULL) {
16084decf41Sjp151216 			/* Initialize thread specific data */
16184decf41Sjp151216 			(void) memset(tsd, 0, sizeof (*tsd));
16284decf41Sjp151216 			/* save the trhread specific data */
16384decf41Sjp151216 			if (pthread_setspecific(idmap_tsd_key, tsd) != 0) {
16484decf41Sjp151216 				/* Can't store key */
16584decf41Sjp151216 				free(tsd);
16684decf41Sjp151216 				tsd = NULL;
16784decf41Sjp151216 			}
16884decf41Sjp151216 		} else {
16984decf41Sjp151216 			tsd = NULL;
17084decf41Sjp151216 		}
17184decf41Sjp151216 	}
17284decf41Sjp151216 
17384decf41Sjp151216 	return (tsd);
17484decf41Sjp151216 }
17584decf41Sjp151216 
176cd37da74Snw141292 /*
177cd37da74Snw141292  * A simple wrapper around u8_textprep_str() that returns the Unicode
178cd37da74Snw141292  * lower-case version of some string.  The result must be freed.
179cd37da74Snw141292  */
180cd37da74Snw141292 char *
181cd37da74Snw141292 tolower_u8(const char *s)
182cd37da74Snw141292 {
183cd37da74Snw141292 	char *res = NULL;
184cd37da74Snw141292 	char *outs;
185cd37da74Snw141292 	size_t inlen, outlen, inbytesleft, outbytesleft;
186cd37da74Snw141292 	int rc, err;
187cd37da74Snw141292 
188cd37da74Snw141292 	/*
189cd37da74Snw141292 	 * u8_textprep_str() does not allocate memory.  The input and
190cd37da74Snw141292 	 * output buffers may differ in size (though that would be more
191cd37da74Snw141292 	 * likely when normalization is done).  We have to loop over it...
192cd37da74Snw141292 	 *
193cd37da74Snw141292 	 * To improve the chances that we can avoid looping we add 10
194cd37da74Snw141292 	 * bytes of output buffer room the first go around.
195cd37da74Snw141292 	 */
196cd37da74Snw141292 	inlen = inbytesleft = strlen(s);
197cd37da74Snw141292 	outlen = outbytesleft = inlen + 10;
198cd37da74Snw141292 	if ((res = malloc(outlen)) == NULL)
199cd37da74Snw141292 		return (NULL);
200cd37da74Snw141292 	outs = res;
201cd37da74Snw141292 
202cd37da74Snw141292 	while ((rc = u8_textprep_str((char *)s, &inbytesleft, outs,
203cd37da74Snw141292 	    &outbytesleft, U8_TEXTPREP_TOLOWER, U8_UNICODE_LATEST, &err)) < 0 &&
204cd37da74Snw141292 	    err == E2BIG) {
205cd37da74Snw141292 		if ((res = realloc(res, outlen + inbytesleft)) == NULL)
206cd37da74Snw141292 			return (NULL);
207cd37da74Snw141292 		/* adjust input/output buffer pointers */
208cd37da74Snw141292 		s += (inlen - inbytesleft);
209cd37da74Snw141292 		outs = res + outlen - outbytesleft;
210cd37da74Snw141292 		/* adjust outbytesleft and outlen */
211cd37da74Snw141292 		outlen += inbytesleft;
212cd37da74Snw141292 		outbytesleft += inbytesleft;
213cd37da74Snw141292 	}
214cd37da74Snw141292 
215cd37da74Snw141292 	if (rc < 0) {
216cd37da74Snw141292 		free(res);
217cd37da74Snw141292 		res = NULL;
218cd37da74Snw141292 		return (NULL);
219cd37da74Snw141292 	}
220cd37da74Snw141292 
221cd37da74Snw141292 	res[outlen - outbytesleft] = '\0';
222cd37da74Snw141292 
223cd37da74Snw141292 	return (res);
224cd37da74Snw141292 }
225cd37da74Snw141292 
226cd37da74Snw141292 static int sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
227cd37da74Snw141292 	const char *while_doing);
228cd37da74Snw141292 
229c5c4113dSnw141292 
230c5c4113dSnw141292 /*
231c5c4113dSnw141292  * Initialize 'dbname' using 'sql'
232c5c4113dSnw141292  */
233cd37da74Snw141292 static
234cd37da74Snw141292 int
235cd37da74Snw141292 init_db_instance(const char *dbname, int version,
236cd37da74Snw141292 	const char *detect_version_sql, char * const *sql,
237cd37da74Snw141292 	init_db_option_t opt, int *created, int *upgraded)
238c5c4113dSnw141292 {
239cd37da74Snw141292 	int rc, curr_version;
240cd37da74Snw141292 	int tries = 1;
241cd37da74Snw141292 	int prio = LOG_NOTICE;
242c5c4113dSnw141292 	sqlite *db = NULL;
243cd37da74Snw141292 	char *errmsg = NULL;
244c5c4113dSnw141292 
245cd37da74Snw141292 	*created = 0;
246cd37da74Snw141292 	*upgraded = 0;
247c5c4113dSnw141292 
248cd37da74Snw141292 	if (opt == REMOVE_IF_CORRUPT)
249cd37da74Snw141292 		tries = 3;
250cd37da74Snw141292 
251cd37da74Snw141292 rinse_repeat:
252cd37da74Snw141292 	if (tries == 0) {
253cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to initialize db %s", dbname);
254c5c4113dSnw141292 		return (-1);
255cd37da74Snw141292 	}
256cd37da74Snw141292 	if (tries-- == 1)
257cd37da74Snw141292 		/* Last try, log errors */
258cd37da74Snw141292 		prio = LOG_ERR;
259c5c4113dSnw141292 
260cd37da74Snw141292 	db = sqlite_open(dbname, 0600, &errmsg);
261cd37da74Snw141292 	if (db == NULL) {
262cd37da74Snw141292 		idmapdlog(prio, "Error creating database %s (%s)",
263cd37da74Snw141292 		    dbname, CHECK_NULL(errmsg));
264cd37da74Snw141292 		sqlite_freemem(errmsg);
265cd37da74Snw141292 		if (opt == REMOVE_IF_CORRUPT)
266c5c4113dSnw141292 			(void) unlink(dbname);
267cd37da74Snw141292 		goto rinse_repeat;
268c5c4113dSnw141292 	}
269c5c4113dSnw141292 
270c5c4113dSnw141292 	sqlite_busy_timeout(db, 3000);
271cd37da74Snw141292 
272cd37da74Snw141292 	/* Detect current version of schema in the db, if any */
273cd37da74Snw141292 	curr_version = 0;
274cd37da74Snw141292 	if (detect_version_sql != NULL) {
275cd37da74Snw141292 		char *end, **results;
276cd37da74Snw141292 		int nrow;
277cd37da74Snw141292 
278cd37da74Snw141292 #ifdef	IDMAPD_DEBUG
279cd37da74Snw141292 		(void) fprintf(stderr, "Schema version detection SQL: %s\n",
280cd37da74Snw141292 		    detect_version_sql);
281cd37da74Snw141292 #endif	/* IDMAPD_DEBUG */
282cd37da74Snw141292 		rc = sqlite_get_table(db, detect_version_sql, &results,
283cd37da74Snw141292 		    &nrow, NULL, &errmsg);
284cd37da74Snw141292 		if (rc != SQLITE_OK) {
285cd37da74Snw141292 			idmapdlog(prio,
286cd37da74Snw141292 			    "Error detecting schema version of db %s (%s)",
287cd37da74Snw141292 			    dbname, errmsg);
288cd37da74Snw141292 			sqlite_freemem(errmsg);
289cd37da74Snw141292 			sqlite_free_table(results);
290c5c4113dSnw141292 			sqlite_close(db);
291cd37da74Snw141292 			return (-1);
292cd37da74Snw141292 		}
293cd37da74Snw141292 		if (nrow != 1) {
294cd37da74Snw141292 			idmapdlog(prio,
295cd37da74Snw141292 			    "Error detecting schema version of db %s", dbname);
296cd37da74Snw141292 			sqlite_close(db);
297cd37da74Snw141292 			sqlite_free_table(results);
298cd37da74Snw141292 			return (-1);
299cd37da74Snw141292 		}
300cd37da74Snw141292 		curr_version = strtol(results[1], &end, 10);
301cd37da74Snw141292 		sqlite_free_table(results);
302c5c4113dSnw141292 	}
303c5c4113dSnw141292 
304cd37da74Snw141292 	if (curr_version < 0) {
305cd37da74Snw141292 		if (opt == REMOVE_IF_CORRUPT)
306cd37da74Snw141292 			(void) unlink(dbname);
307cd37da74Snw141292 		goto rinse_repeat;
308c5c4113dSnw141292 	}
309c5c4113dSnw141292 
310cd37da74Snw141292 	if (curr_version == version)
311cd37da74Snw141292 		goto done;
312cd37da74Snw141292 
313cd37da74Snw141292 	/* Install or upgrade schema */
314cd37da74Snw141292 #ifdef	IDMAPD_DEBUG
315cd37da74Snw141292 	(void) fprintf(stderr, "Schema init/upgrade SQL: %s\n",
316cd37da74Snw141292 	    sql[curr_version]);
317cd37da74Snw141292 #endif	/* IDMAPD_DEBUG */
318cd37da74Snw141292 	rc = sql_exec_tran_no_cb(db, sql[curr_version], dbname,
319cd37da74Snw141292 	    (curr_version == 0) ? "installing schema" : "upgrading schema");
320cd37da74Snw141292 	if (rc != 0) {
321cd37da74Snw141292 		idmapdlog(prio, "Error %s schema for db %s", dbname,
322cd37da74Snw141292 		    (curr_version == 0) ? "installing schema" :
323cd37da74Snw141292 		    "upgrading schema");
324cd37da74Snw141292 		if (opt == REMOVE_IF_CORRUPT)
325cd37da74Snw141292 			(void) unlink(dbname);
326cd37da74Snw141292 		goto rinse_repeat;
327c5c4113dSnw141292 	}
328c5c4113dSnw141292 
329cd37da74Snw141292 	*upgraded = (curr_version > 0);
330cd37da74Snw141292 	*created = (curr_version == 0);
331cd37da74Snw141292 
332cd37da74Snw141292 done:
333c5c4113dSnw141292 	(void) sqlite_close(db);
334cd37da74Snw141292 	return (0);
335c5c4113dSnw141292 }
336c5c4113dSnw141292 
33784decf41Sjp151216 
33884decf41Sjp151216 /*
33984decf41Sjp151216  * This is the SQLite database busy handler that retries the SQL
34084decf41Sjp151216  * operation until it is successful.
34184decf41Sjp151216  */
34284decf41Sjp151216 int
34384decf41Sjp151216 /* LINTED E_FUNC_ARG_UNUSED */
34484decf41Sjp151216 idmap_sqlite_busy_handler(void *arg, const char *table_name, int count)
34584decf41Sjp151216 {
34684decf41Sjp151216 	struct idmap_busy	*busy = arg;
34784decf41Sjp151216 	int			delay;
34884decf41Sjp151216 	struct timespec		rqtp;
34984decf41Sjp151216 
35084decf41Sjp151216 	if (count == 1)  {
35184decf41Sjp151216 		busy->total = 0;
35284decf41Sjp151216 		busy->sec = 2;
35384decf41Sjp151216 	}
35484decf41Sjp151216 	if (busy->total > 1000 * busy->sec) {
3552b3ecdebSjp151216 		idmapdlog(LOG_DEBUG,
35684decf41Sjp151216 		    "Thread %d waited %d sec for the %s database",
35784decf41Sjp151216 		    pthread_self(), busy->sec, busy->name);
35884decf41Sjp151216 		busy->sec++;
35984decf41Sjp151216 	}
36084decf41Sjp151216 
36184decf41Sjp151216 	if (count <= busy->delay_size) {
36284decf41Sjp151216 		delay = busy->delays[count-1];
36384decf41Sjp151216 	} else {
36484decf41Sjp151216 		delay = busy->delays[busy->delay_size - 1];
36584decf41Sjp151216 	}
36684decf41Sjp151216 	busy->total += delay;
36784decf41Sjp151216 	rqtp.tv_sec = 0;
36884decf41Sjp151216 	rqtp.tv_nsec = delay * (NANOSEC / MILLISEC);
36984decf41Sjp151216 	(void) nanosleep(&rqtp, NULL);
37084decf41Sjp151216 	return (1);
37184decf41Sjp151216 }
37284decf41Sjp151216 
37384decf41Sjp151216 
374c5c4113dSnw141292 /*
375c5c4113dSnw141292  * Get the database handle
376c5c4113dSnw141292  */
377c5c4113dSnw141292 idmap_retcode
378cd37da74Snw141292 get_db_handle(sqlite **db)
379cd37da74Snw141292 {
380c5c4113dSnw141292 	char		*errmsg;
38184decf41Sjp151216 	idmap_tsd_t	*tsd;
382c5c4113dSnw141292 
383c5c4113dSnw141292 	/*
38484decf41Sjp151216 	 * Retrieve the db handle from thread-specific storage
385c5c4113dSnw141292 	 * If none exists, open and store in thread-specific storage.
386c5c4113dSnw141292 	 */
38784decf41Sjp151216 	if ((tsd = idmap_get_tsd()) == NULL) {
38884decf41Sjp151216 		idmapdlog(LOG_ERR,
389cd37da74Snw141292 		    "Error getting thread specific data for %s", IDMAP_DBNAME);
39084decf41Sjp151216 		return (IDMAP_ERR_MEMORY);
39184decf41Sjp151216 	}
392c5c4113dSnw141292 
39384decf41Sjp151216 	if (tsd->db_db == NULL) {
39484decf41Sjp151216 		tsd->db_db = sqlite_open(IDMAP_DBNAME, 0, &errmsg);
39584decf41Sjp151216 		if (tsd->db_db == NULL) {
396cd37da74Snw141292 			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
397c5c4113dSnw141292 			    IDMAP_DBNAME, CHECK_NULL(errmsg));
398c5c4113dSnw141292 			sqlite_freemem(errmsg);
399cd37da74Snw141292 			return (IDMAP_ERR_DB);
400c5c4113dSnw141292 		}
401cd37da74Snw141292 
40284decf41Sjp151216 		tsd->db_busy.name = IDMAP_DBNAME;
40384decf41Sjp151216 		tsd->db_busy.delays = db_delay_table;
40484decf41Sjp151216 		tsd->db_busy.delay_size = sizeof (db_delay_table) /
40584decf41Sjp151216 		    sizeof (int);
40684decf41Sjp151216 		sqlite_busy_handler(tsd->db_db, idmap_sqlite_busy_handler,
40784decf41Sjp151216 		    &tsd->db_busy);
40884decf41Sjp151216 	}
40984decf41Sjp151216 	*db = tsd->db_db;
410c5c4113dSnw141292 	return (IDMAP_SUCCESS);
411c5c4113dSnw141292 }
412c5c4113dSnw141292 
413c5c4113dSnw141292 /*
414c5c4113dSnw141292  * Get the cache handle
415c5c4113dSnw141292  */
416c5c4113dSnw141292 idmap_retcode
417cd37da74Snw141292 get_cache_handle(sqlite **cache)
418cd37da74Snw141292 {
419c5c4113dSnw141292 	char		*errmsg;
42084decf41Sjp151216 	idmap_tsd_t	*tsd;
421c5c4113dSnw141292 
422c5c4113dSnw141292 	/*
42384decf41Sjp151216 	 * Retrieve the db handle from thread-specific storage
424c5c4113dSnw141292 	 * If none exists, open and store in thread-specific storage.
425c5c4113dSnw141292 	 */
42684decf41Sjp151216 	if ((tsd = idmap_get_tsd()) == NULL) {
427cd37da74Snw141292 		idmapdlog(LOG_ERR, "Error getting thread specific data for %s",
42884decf41Sjp151216 		    IDMAP_DBNAME);
42984decf41Sjp151216 		return (IDMAP_ERR_MEMORY);
43084decf41Sjp151216 	}
431c5c4113dSnw141292 
43284decf41Sjp151216 	if (tsd->cache_db == NULL) {
43384decf41Sjp151216 		tsd->cache_db = sqlite_open(IDMAP_CACHENAME, 0, &errmsg);
43484decf41Sjp151216 		if (tsd->cache_db == NULL) {
435cd37da74Snw141292 			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
436c5c4113dSnw141292 			    IDMAP_CACHENAME, CHECK_NULL(errmsg));
437c5c4113dSnw141292 			sqlite_freemem(errmsg);
438cd37da74Snw141292 			return (IDMAP_ERR_DB);
439c5c4113dSnw141292 		}
440cd37da74Snw141292 
44184decf41Sjp151216 		tsd->cache_busy.name = IDMAP_CACHENAME;
44284decf41Sjp151216 		tsd->cache_busy.delays = cache_delay_table;
44384decf41Sjp151216 		tsd->cache_busy.delay_size = sizeof (cache_delay_table) /
44484decf41Sjp151216 		    sizeof (int);
44584decf41Sjp151216 		sqlite_busy_handler(tsd->cache_db, idmap_sqlite_busy_handler,
44684decf41Sjp151216 		    &tsd->cache_busy);
44784decf41Sjp151216 	}
44884decf41Sjp151216 	*cache = tsd->cache_db;
449c5c4113dSnw141292 	return (IDMAP_SUCCESS);
450c5c4113dSnw141292 }
451c5c4113dSnw141292 
452c5c4113dSnw141292 /*
453c5c4113dSnw141292  * Initialize cache and db
454c5c4113dSnw141292  */
455c5c4113dSnw141292 int
456cd37da74Snw141292 init_dbs()
457cd37da74Snw141292 {
45848258c6bSjp151216 	char *sql[4];
459cd37da74Snw141292 	int created, upgraded;
460cd37da74Snw141292 
461c5c4113dSnw141292 	/* name-based mappings; probably OK to blow away in a pinch(?) */
462cd37da74Snw141292 	sql[0] = DB_INSTALL_SQL;
463cd37da74Snw141292 	sql[1] = DB_UPGRADE_FROM_v1_SQL;
46448258c6bSjp151216 	sql[2] = NULL;
465cd37da74Snw141292 
466cd37da74Snw141292 	if (init_db_instance(IDMAP_DBNAME, DB_VERSION, DB_VERSION_SQL, sql,
467cd37da74Snw141292 	    FAIL_IF_CORRUPT, &created, &upgraded) < 0)
468c5c4113dSnw141292 		return (-1);
469c5c4113dSnw141292 
470c5c4113dSnw141292 	/* mappings, name/SID lookup cache + ephemeral IDs; OK to blow away */
471cd37da74Snw141292 	sql[0] = CACHE_INSTALL_SQL;
472cd37da74Snw141292 	sql[1] = CACHE_UPGRADE_FROM_v1_SQL;
47348258c6bSjp151216 	sql[2] = CACHE_UPGRADE_FROM_v2_SQL;
47448258c6bSjp151216 	sql[3] = NULL;
47548258c6bSjp151216 
476cd37da74Snw141292 	if (init_db_instance(IDMAP_CACHENAME, CACHE_VERSION, CACHE_VERSION_SQL,
477cd37da74Snw141292 	    sql, REMOVE_IF_CORRUPT, &created, &upgraded) < 0)
478c5c4113dSnw141292 		return (-1);
479c5c4113dSnw141292 
480cd37da74Snw141292 	_idmapdstate.new_eph_db = (created || upgraded) ? 1 : 0;
481cd37da74Snw141292 
482c5c4113dSnw141292 	return (0);
483c5c4113dSnw141292 }
484c5c4113dSnw141292 
485c5c4113dSnw141292 /*
486c5c4113dSnw141292  * Finalize databases
487c5c4113dSnw141292  */
488c5c4113dSnw141292 void
489cd37da74Snw141292 fini_dbs()
490cd37da74Snw141292 {
491c5c4113dSnw141292 }
492c5c4113dSnw141292 
493c5c4113dSnw141292 /*
494e8c27ec8Sbaban  * This table is a listing of status codes that will be returned to the
495c5c4113dSnw141292  * client when a SQL command fails with the corresponding error message.
496c5c4113dSnw141292  */
497c5c4113dSnw141292 static msg_table_t sqlmsgtable[] = {
49862c60062Sbaban 	{IDMAP_ERR_U2W_NAMERULE_CONFLICT,
499c5c4113dSnw141292 	"columns unixname, is_user, u2w_order are not unique"},
50062c60062Sbaban 	{IDMAP_ERR_W2U_NAMERULE_CONFLICT,
501cd37da74Snw141292 	"columns winname, windomain, is_user, is_wuser, w2u_order are not"
502cd37da74Snw141292 	" unique"},
503cd37da74Snw141292 	{IDMAP_ERR_W2U_NAMERULE_CONFLICT, "Conflicting w2u namerules"},
504c5c4113dSnw141292 	{-1, NULL}
505c5c4113dSnw141292 };
506c5c4113dSnw141292 
507c5c4113dSnw141292 /*
508c5c4113dSnw141292  * idmapd's version of string2stat to map SQLite messages to
509c5c4113dSnw141292  * status codes
510c5c4113dSnw141292  */
511c5c4113dSnw141292 idmap_retcode
512cd37da74Snw141292 idmapd_string2stat(const char *msg)
513cd37da74Snw141292 {
514c5c4113dSnw141292 	int i;
515c5c4113dSnw141292 	for (i = 0; sqlmsgtable[i].msg; i++) {
516c5c4113dSnw141292 		if (strcasecmp(sqlmsgtable[i].msg, msg) == 0)
517c5c4113dSnw141292 			return (sqlmsgtable[i].retcode);
518c5c4113dSnw141292 	}
519c5c4113dSnw141292 	return (IDMAP_ERR_OTHER);
520c5c4113dSnw141292 }
521c5c4113dSnw141292 
522c5c4113dSnw141292 /*
523cd37da74Snw141292  * Executes some SQL in a transaction.
524cd37da74Snw141292  *
525cd37da74Snw141292  * Returns 0 on success, -1 if it failed but the rollback succeeded, -2
526cd37da74Snw141292  * if the rollback failed.
527cd37da74Snw141292  */
528cd37da74Snw141292 static
529cd37da74Snw141292 int
530cd37da74Snw141292 sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
531cd37da74Snw141292 	const char *while_doing)
532cd37da74Snw141292 {
533cd37da74Snw141292 	char		*errmsg = NULL;
534cd37da74Snw141292 	int		rc;
535cd37da74Snw141292 
536cd37da74Snw141292 	rc = sqlite_exec(db, "BEGIN TRANSACTION;", NULL, NULL, &errmsg);
537cd37da74Snw141292 	if (rc != SQLITE_OK) {
538cd37da74Snw141292 		idmapdlog(LOG_ERR, "Begin transaction failed (%s) "
539cd37da74Snw141292 		    "while %s (%s)", errmsg, while_doing, dbname);
540cd37da74Snw141292 		sqlite_freemem(errmsg);
541cd37da74Snw141292 		return (-1);
542cd37da74Snw141292 	}
543cd37da74Snw141292 
544cd37da74Snw141292 	rc = sqlite_exec(db, sql, NULL, NULL, &errmsg);
545cd37da74Snw141292 	if (rc != SQLITE_OK) {
546cd37da74Snw141292 		idmapdlog(LOG_ERR, "Database error (%s) while %s (%s)", errmsg,
547cd37da74Snw141292 		    while_doing, dbname);
548cd37da74Snw141292 		sqlite_freemem(errmsg);
549cd37da74Snw141292 		errmsg = NULL;
550cd37da74Snw141292 		goto rollback;
551cd37da74Snw141292 	}
552cd37da74Snw141292 
553cd37da74Snw141292 	rc = sqlite_exec(db, "COMMIT TRANSACTION", NULL, NULL, &errmsg);
554cd37da74Snw141292 	if (rc == SQLITE_OK) {
555cd37da74Snw141292 		sqlite_freemem(errmsg);
556cd37da74Snw141292 		return (0);
557cd37da74Snw141292 	}
558cd37da74Snw141292 
559cd37da74Snw141292 	idmapdlog(LOG_ERR, "Database commit error (%s) while s (%s)",
560cd37da74Snw141292 	    errmsg, while_doing, dbname);
561cd37da74Snw141292 	sqlite_freemem(errmsg);
562cd37da74Snw141292 	errmsg = NULL;
563cd37da74Snw141292 
564cd37da74Snw141292 rollback:
565cd37da74Snw141292 	rc = sqlite_exec(db, "ROLLBACK TRANSACTION", NULL, NULL, &errmsg);
566cd37da74Snw141292 	if (rc != SQLITE_OK) {
567cd37da74Snw141292 		idmapdlog(LOG_ERR, "Rollback failed (%s) while %s (%s)",
568cd37da74Snw141292 		    errmsg, while_doing, dbname);
569cd37da74Snw141292 		sqlite_freemem(errmsg);
570cd37da74Snw141292 		return (-2);
571cd37da74Snw141292 	}
572cd37da74Snw141292 	sqlite_freemem(errmsg);
573cd37da74Snw141292 
574cd37da74Snw141292 	return (-1);
575cd37da74Snw141292 }
576cd37da74Snw141292 
577cd37da74Snw141292 /*
578c5c4113dSnw141292  * Execute the given SQL statment without using any callbacks
579c5c4113dSnw141292  */
580c5c4113dSnw141292 idmap_retcode
58171590c90Snw141292 sql_exec_no_cb(sqlite *db, const char *dbname, char *sql)
582cd37da74Snw141292 {
583c5c4113dSnw141292 	char		*errmsg = NULL;
58484decf41Sjp151216 	int		r;
585c5c4113dSnw141292 	idmap_retcode	retcode;
586c5c4113dSnw141292 
587c5c4113dSnw141292 	r = sqlite_exec(db, sql, NULL, NULL, &errmsg);
58884decf41Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
589c5c4113dSnw141292 
590c5c4113dSnw141292 	if (r != SQLITE_OK) {
59171590c90Snw141292 		idmapdlog(LOG_ERR, "Database error on %s while executing %s "
59271590c90Snw141292 		    "(%s)", dbname, sql, CHECK_NULL(errmsg));
593c5c4113dSnw141292 		retcode = idmapd_string2stat(errmsg);
59462c60062Sbaban 		if (errmsg != NULL)
595c5c4113dSnw141292 			sqlite_freemem(errmsg);
596c5c4113dSnw141292 		return (retcode);
597c5c4113dSnw141292 	}
598c5c4113dSnw141292 
599c5c4113dSnw141292 	return (IDMAP_SUCCESS);
600c5c4113dSnw141292 }
601c5c4113dSnw141292 
602c5c4113dSnw141292 /*
603c5c4113dSnw141292  * Generate expression that can be used in WHERE statements.
604c5c4113dSnw141292  * Examples:
605c5c4113dSnw141292  * <prefix> <col>      <op> <value>   <suffix>
606c5c4113dSnw141292  * ""       "unixuser" "="  "foo" "AND"
607c5c4113dSnw141292  */
608c5c4113dSnw141292 idmap_retcode
609cd37da74Snw141292 gen_sql_expr_from_rule(idmap_namerule *rule, char **out)
610cd37da74Snw141292 {
611cd37da74Snw141292 	char	*s_windomain = NULL, *s_winname = NULL;
612cd37da74Snw141292 	char	*s_unixname = NULL;
613cd37da74Snw141292 	char	*lower_winname;
614cd37da74Snw141292 	int	retcode = IDMAP_SUCCESS;
615cd37da74Snw141292 
616c5c4113dSnw141292 	if (out == NULL)
617c5c4113dSnw141292 		return (IDMAP_ERR_ARG);
618c5c4113dSnw141292 
619c5c4113dSnw141292 
620cd37da74Snw141292 	if (!EMPTY_STRING(rule->windomain)) {
621cd37da74Snw141292 		s_windomain =  sqlite_mprintf("AND windomain = %Q ",
622cd37da74Snw141292 		    rule->windomain);
623cd37da74Snw141292 		if (s_windomain == NULL) {
624cd37da74Snw141292 			retcode = IDMAP_ERR_MEMORY;
625cd37da74Snw141292 			goto out;
626c5c4113dSnw141292 		}
627cd37da74Snw141292 	}
628cd37da74Snw141292 
629cd37da74Snw141292 	if (!EMPTY_STRING(rule->winname)) {
630cd37da74Snw141292 		if ((lower_winname = tolower_u8(rule->winname)) == NULL)
631cd37da74Snw141292 			lower_winname = rule->winname;
632cd37da74Snw141292 		s_winname = sqlite_mprintf(
633cd37da74Snw141292 		    "AND winname = %Q AND is_wuser = %d ",
634cd37da74Snw141292 		    lower_winname, rule->is_wuser ? 1 : 0);
635cd37da74Snw141292 		if (lower_winname != rule->winname)
636cd37da74Snw141292 			free(lower_winname);
637cd37da74Snw141292 		if (s_winname == NULL) {
638cd37da74Snw141292 			retcode = IDMAP_ERR_MEMORY;
639cd37da74Snw141292 			goto out;
640cd37da74Snw141292 		}
641cd37da74Snw141292 	}
642cd37da74Snw141292 
643cd37da74Snw141292 	if (!EMPTY_STRING(rule->unixname)) {
644cd37da74Snw141292 		s_unixname = sqlite_mprintf(
645cd37da74Snw141292 		    "AND unixname = %Q AND is_user = %d ",
646cd37da74Snw141292 		    rule->unixname, rule->is_user ? 1 : 0);
647cd37da74Snw141292 		if (s_unixname == NULL) {
648cd37da74Snw141292 			retcode = IDMAP_ERR_MEMORY;
649cd37da74Snw141292 			goto out;
650cd37da74Snw141292 		}
651cd37da74Snw141292 	}
652cd37da74Snw141292 
653cd37da74Snw141292 	*out = sqlite_mprintf("%s %s %s",
654cd37da74Snw141292 	    s_windomain ? s_windomain : "",
655cd37da74Snw141292 	    s_winname ? s_winname : "",
656cd37da74Snw141292 	    s_unixname ? s_unixname : "");
657cd37da74Snw141292 
658cd37da74Snw141292 	if (*out == NULL) {
659cd37da74Snw141292 		retcode = IDMAP_ERR_MEMORY;
660cd37da74Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
661cd37da74Snw141292 		goto out;
662cd37da74Snw141292 	}
663cd37da74Snw141292 
664cd37da74Snw141292 out:
665cd37da74Snw141292 	if (s_windomain != NULL)
666cd37da74Snw141292 		sqlite_freemem(s_windomain);
667cd37da74Snw141292 	if (s_winname != NULL)
668cd37da74Snw141292 		sqlite_freemem(s_winname);
669cd37da74Snw141292 	if (s_unixname != NULL)
670cd37da74Snw141292 		sqlite_freemem(s_unixname);
671cd37da74Snw141292 
672cd37da74Snw141292 	return (retcode);
673cd37da74Snw141292 }
674cd37da74Snw141292 
675cd37da74Snw141292 
676c5c4113dSnw141292 
677c5c4113dSnw141292 /*
678c5c4113dSnw141292  * Generate and execute SQL statement for LIST RPC calls
679c5c4113dSnw141292  */
680c5c4113dSnw141292 idmap_retcode
68171590c90Snw141292 process_list_svc_sql(sqlite *db, const char *dbname, char *sql, uint64_t limit,
68248258c6bSjp151216 		int flag, list_svc_cb cb, void *result)
683cd37da74Snw141292 {
684c5c4113dSnw141292 	list_cb_data_t	cb_data;
685c5c4113dSnw141292 	char		*errmsg = NULL;
68684decf41Sjp151216 	int		r;
687c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_ERR_INTERNAL;
688c5c4113dSnw141292 
689c5c4113dSnw141292 	(void) memset(&cb_data, 0, sizeof (cb_data));
690c5c4113dSnw141292 	cb_data.result = result;
691c5c4113dSnw141292 	cb_data.limit = limit;
69248258c6bSjp151216 	cb_data.flag = flag;
693c5c4113dSnw141292 
69484decf41Sjp151216 
695c5c4113dSnw141292 	r = sqlite_exec(db, sql, cb, &cb_data, &errmsg);
69684decf41Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
697c5c4113dSnw141292 	switch (r) {
698c5c4113dSnw141292 	case SQLITE_OK:
699c5c4113dSnw141292 		retcode = IDMAP_SUCCESS;
70084decf41Sjp151216 		break;
70184decf41Sjp151216 
702c5c4113dSnw141292 	default:
703c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
70471590c90Snw141292 		idmapdlog(LOG_ERR, "Database error on %s while executing "
70571590c90Snw141292 		    "%s (%s)", dbname, sql, CHECK_NULL(errmsg));
70684decf41Sjp151216 		break;
707c5c4113dSnw141292 	}
70862c60062Sbaban 	if (errmsg != NULL)
709c5c4113dSnw141292 		sqlite_freemem(errmsg);
710c5c4113dSnw141292 	return (retcode);
711c5c4113dSnw141292 }
712c5c4113dSnw141292 
713c5c4113dSnw141292 /*
714c5c4113dSnw141292  * This routine is called by callbacks that process the results of
715c5c4113dSnw141292  * LIST RPC calls to validate data and to allocate memory for
716c5c4113dSnw141292  * the result array.
717c5c4113dSnw141292  */
718c5c4113dSnw141292 idmap_retcode
719c5c4113dSnw141292 validate_list_cb_data(list_cb_data_t *cb_data, int argc, char **argv,
720cd37da74Snw141292 		int ncol, uchar_t **list, size_t valsize)
721cd37da74Snw141292 {
722c5c4113dSnw141292 	size_t	nsize;
723c5c4113dSnw141292 	void	*tmplist;
724c5c4113dSnw141292 
725c5c4113dSnw141292 	if (cb_data->limit > 0 && cb_data->next == cb_data->limit)
726c5c4113dSnw141292 		return (IDMAP_NEXT);
727c5c4113dSnw141292 
728c5c4113dSnw141292 	if (argc < ncol || argv == NULL) {
729c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Invalid data");
730c5c4113dSnw141292 		return (IDMAP_ERR_INTERNAL);
731c5c4113dSnw141292 	}
732c5c4113dSnw141292 
733c5c4113dSnw141292 	/* alloc in bulk to reduce number of reallocs */
734c5c4113dSnw141292 	if (cb_data->next >= cb_data->len) {
735c5c4113dSnw141292 		nsize = (cb_data->len + SIZE_INCR) * valsize;
736c5c4113dSnw141292 		tmplist = realloc(*list, nsize);
737c5c4113dSnw141292 		if (tmplist == NULL) {
738c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
739c5c4113dSnw141292 			return (IDMAP_ERR_MEMORY);
740c5c4113dSnw141292 		}
741c5c4113dSnw141292 		*list = tmplist;
742c5c4113dSnw141292 		(void) memset(*list + (cb_data->len * valsize), 0,
743c5c4113dSnw141292 		    SIZE_INCR * valsize);
744c5c4113dSnw141292 		cb_data->len += SIZE_INCR;
745c5c4113dSnw141292 	}
746c5c4113dSnw141292 	return (IDMAP_SUCCESS);
747c5c4113dSnw141292 }
748c5c4113dSnw141292 
749cd37da74Snw141292 static
750cd37da74Snw141292 idmap_retcode
751c5c4113dSnw141292 get_namerule_order(char *winname, char *windomain, char *unixname,
752cd37da74Snw141292 	int direction, int is_diagonal, int *w2u_order, int *u2w_order)
753cd37da74Snw141292 {
754c5c4113dSnw141292 	*w2u_order = 0;
755c5c4113dSnw141292 	*u2w_order = 0;
756c5c4113dSnw141292 
757c5c4113dSnw141292 	/*
758c5c4113dSnw141292 	 * Windows to UNIX lookup order:
759c5c4113dSnw141292 	 *  1. winname@domain (or winname) to ""
760c5c4113dSnw141292 	 *  2. winname@domain (or winname) to unixname
761c5c4113dSnw141292 	 *  3. winname@* to ""
762c5c4113dSnw141292 	 *  4. winname@* to unixname
763c5c4113dSnw141292 	 *  5. *@domain (or *) to *
764c5c4113dSnw141292 	 *  6. *@domain (or *) to ""
765c5c4113dSnw141292 	 *  7. *@domain (or *) to unixname
766c5c4113dSnw141292 	 *  8. *@* to *
767c5c4113dSnw141292 	 *  9. *@* to ""
768c5c4113dSnw141292 	 * 10. *@* to unixname
769c5c4113dSnw141292 	 *
770c5c4113dSnw141292 	 * winname is a special case of winname@domain when domain is the
771c5c4113dSnw141292 	 * default domain. Similarly * is a special case of *@domain when
772c5c4113dSnw141292 	 * domain is the default domain.
773c5c4113dSnw141292 	 *
774c5c4113dSnw141292 	 * Note that "" has priority over specific names because "" inhibits
775c5c4113dSnw141292 	 * mappings and traditionally deny rules always had higher priority.
776c5c4113dSnw141292 	 */
777651c0131Sbaban 	if (direction != IDMAP_DIRECTION_U2W) {
778651c0131Sbaban 		/* bi-directional or from windows to unix */
779c5c4113dSnw141292 		if (winname == NULL)
780c5c4113dSnw141292 			return (IDMAP_ERR_W2U_NAMERULE);
781c5c4113dSnw141292 		else if (unixname == NULL)
782c5c4113dSnw141292 			return (IDMAP_ERR_W2U_NAMERULE);
783c5c4113dSnw141292 		else if (EMPTY_NAME(winname))
784c5c4113dSnw141292 			return (IDMAP_ERR_W2U_NAMERULE);
785c5c4113dSnw141292 		else if (*winname == '*' && windomain && *windomain == '*') {
786c5c4113dSnw141292 			if (*unixname == '*')
787c5c4113dSnw141292 				*w2u_order = 8;
788c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
789c5c4113dSnw141292 				*w2u_order = 9;
790c5c4113dSnw141292 			else /* unixname == name */
791c5c4113dSnw141292 				*w2u_order = 10;
792c5c4113dSnw141292 		} else if (*winname == '*') {
793c5c4113dSnw141292 			if (*unixname == '*')
794c5c4113dSnw141292 				*w2u_order = 5;
795c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
796c5c4113dSnw141292 				*w2u_order = 6;
797c5c4113dSnw141292 			else /* name */
798c5c4113dSnw141292 				*w2u_order = 7;
79962c60062Sbaban 		} else if (windomain != NULL && *windomain == '*') {
800c5c4113dSnw141292 			/* winname == name */
801c5c4113dSnw141292 			if (*unixname == '*')
802c5c4113dSnw141292 				return (IDMAP_ERR_W2U_NAMERULE);
803c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
804c5c4113dSnw141292 				*w2u_order = 3;
805c5c4113dSnw141292 			else /* name */
806c5c4113dSnw141292 				*w2u_order = 4;
807c5c4113dSnw141292 		} else  {
808c5c4113dSnw141292 			/* winname == name && windomain == null or name */
809c5c4113dSnw141292 			if (*unixname == '*')
810c5c4113dSnw141292 				return (IDMAP_ERR_W2U_NAMERULE);
811c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
812c5c4113dSnw141292 				*w2u_order = 1;
813c5c4113dSnw141292 			else /* name */
814c5c4113dSnw141292 				*w2u_order = 2;
815c5c4113dSnw141292 		}
816cd37da74Snw141292 
817c5c4113dSnw141292 	}
818c5c4113dSnw141292 
819c5c4113dSnw141292 	/*
820cd37da74Snw141292 	 * 1. unixname to "", non-diagonal
821cd37da74Snw141292 	 * 2. unixname to winname@domain (or winname), non-diagonal
822cd37da74Snw141292 	 * 3. unixname to "", diagonal
823cd37da74Snw141292 	 * 4. unixname to winname@domain (or winname), diagonal
824cd37da74Snw141292 	 * 5. * to *@domain (or *), non-diagonal
825cd37da74Snw141292 	 * 5. * to *@domain (or *), diagonal
826cd37da74Snw141292 	 * 7. * to ""
827cd37da74Snw141292 	 * 8. * to winname@domain (or winname)
828cd37da74Snw141292 	 * 9. * to "", non-diagonal
829cd37da74Snw141292 	 * 10. * to winname@domain (or winname), diagonal
830c5c4113dSnw141292 	 */
831651c0131Sbaban 	if (direction != IDMAP_DIRECTION_W2U) {
832cd37da74Snw141292 		int diagonal = is_diagonal ? 1 : 0;
833cd37da74Snw141292 
834651c0131Sbaban 		/* bi-directional or from unix to windows */
835c5c4113dSnw141292 		if (unixname == NULL || EMPTY_NAME(unixname))
836c5c4113dSnw141292 			return (IDMAP_ERR_U2W_NAMERULE);
837c5c4113dSnw141292 		else if (winname == NULL)
838c5c4113dSnw141292 			return (IDMAP_ERR_U2W_NAMERULE);
83962c60062Sbaban 		else if (windomain != NULL && *windomain == '*')
840651c0131Sbaban 			return (IDMAP_ERR_U2W_NAMERULE);
841c5c4113dSnw141292 		else if (*unixname == '*') {
842c5c4113dSnw141292 			if (*winname == '*')
843cd37da74Snw141292 				*u2w_order = 5 + diagonal;
844c5c4113dSnw141292 			else if (EMPTY_NAME(winname))
845cd37da74Snw141292 				*u2w_order = 7 + 2 * diagonal;
846c5c4113dSnw141292 			else
847cd37da74Snw141292 				*u2w_order = 8 + 2 * diagonal;
848c5c4113dSnw141292 		} else {
849c5c4113dSnw141292 			if (*winname == '*')
850c5c4113dSnw141292 				return (IDMAP_ERR_U2W_NAMERULE);
851c5c4113dSnw141292 			else if (EMPTY_NAME(winname))
852cd37da74Snw141292 				*u2w_order = 1 + 2 * diagonal;
853c5c4113dSnw141292 			else
854cd37da74Snw141292 				*u2w_order = 2 + 2 * diagonal;
855c5c4113dSnw141292 		}
856c5c4113dSnw141292 	}
857c5c4113dSnw141292 	return (IDMAP_SUCCESS);
858c5c4113dSnw141292 }
859c5c4113dSnw141292 
860c5c4113dSnw141292 /*
861c5c4113dSnw141292  * Generate and execute SQL statement to add name-based mapping rule
862c5c4113dSnw141292  */
863c5c4113dSnw141292 idmap_retcode
864cd37da74Snw141292 add_namerule(sqlite *db, idmap_namerule *rule)
865cd37da74Snw141292 {
866c5c4113dSnw141292 	char		*sql = NULL;
867c5c4113dSnw141292 	idmap_stat	retcode;
8688e228215Sdm199847 	char		*dom = NULL;
869c5c4113dSnw141292 	int		w2u_order, u2w_order;
870c5c4113dSnw141292 	char		w2ubuf[11], u2wbuf[11];
871c5c4113dSnw141292 
8728e228215Sdm199847 	retcode = get_namerule_order(rule->winname, rule->windomain,
873cd37da74Snw141292 	    rule->unixname, rule->direction,
874cd37da74Snw141292 	    rule->is_user == rule->is_wuser ? 0 : 1, &w2u_order, &u2w_order);
875c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
876c5c4113dSnw141292 		goto out;
877c5c4113dSnw141292 
878c5c4113dSnw141292 	if (w2u_order)
879c5c4113dSnw141292 		(void) snprintf(w2ubuf, sizeof (w2ubuf), "%d", w2u_order);
880c5c4113dSnw141292 	if (u2w_order)
881c5c4113dSnw141292 		(void) snprintf(u2wbuf, sizeof (u2wbuf), "%d", u2w_order);
882c5c4113dSnw141292 
88362c60062Sbaban 	/*
88462c60062Sbaban 	 * For the triggers on namerules table to work correctly:
88562c60062Sbaban 	 * 1) Use NULL instead of 0 for w2u_order and u2w_order
88662c60062Sbaban 	 * 2) Use "" instead of NULL for "no domain"
88762c60062Sbaban 	 */
88862c60062Sbaban 
889e8c27ec8Sbaban 	if (!EMPTY_STRING(rule->windomain))
8908e228215Sdm199847 		dom = rule->windomain;
891cd37da74Snw141292 	else if (lookup_wksids_name2sid(rule->winname, NULL, NULL, NULL, NULL)
89262c60062Sbaban 	    == IDMAP_SUCCESS) {
89362c60062Sbaban 		/* well-known SIDs don't need domain */
89462c60062Sbaban 		dom = "";
89562c60062Sbaban 	}
896c5c4113dSnw141292 
897c5c4113dSnw141292 	RDLOCK_CONFIG();
89862c60062Sbaban 	if (dom == NULL) {
899c8e26105Sjp151216 		if (_idmapdstate.cfg->pgcfg.default_domain)
900c8e26105Sjp151216 			dom = _idmapdstate.cfg->pgcfg.default_domain;
901c5c4113dSnw141292 		else
902c5c4113dSnw141292 			dom = "";
90362c60062Sbaban 	}
90484decf41Sjp151216 	sql = sqlite_mprintf("INSERT into namerules "
905cd37da74Snw141292 	    "(is_user, is_wuser, windomain, winname_display, is_nt4, "
906c5c4113dSnw141292 	    "unixname, w2u_order, u2w_order) "
907cd37da74Snw141292 	    "VALUES(%d, %d, %Q, %Q, %d, %Q, %q, %q);",
908cd37da74Snw141292 	    rule->is_user ? 1 : 0, rule->is_wuser ? 1 : 0, dom,
909cd37da74Snw141292 	    rule->winname, rule->is_nt4 ? 1 : 0, rule->unixname,
910cd37da74Snw141292 	    w2u_order ? w2ubuf : NULL, u2w_order ? u2wbuf : NULL);
911c5c4113dSnw141292 	UNLOCK_CONFIG();
912c5c4113dSnw141292 
913c5c4113dSnw141292 	if (sql == NULL) {
914c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
915c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
916c5c4113dSnw141292 		goto out;
917c5c4113dSnw141292 	}
918c5c4113dSnw141292 
91971590c90Snw141292 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, sql);
920c5c4113dSnw141292 
921c5c4113dSnw141292 	if (retcode == IDMAP_ERR_OTHER)
922c5c4113dSnw141292 		retcode = IDMAP_ERR_CFG;
923c5c4113dSnw141292 
924c5c4113dSnw141292 out:
92562c60062Sbaban 	if (sql != NULL)
926c5c4113dSnw141292 		sqlite_freemem(sql);
927c5c4113dSnw141292 	return (retcode);
928c5c4113dSnw141292 }
929c5c4113dSnw141292 
930c5c4113dSnw141292 /*
931c5c4113dSnw141292  * Flush name-based mapping rules
932c5c4113dSnw141292  */
933c5c4113dSnw141292 idmap_retcode
934cd37da74Snw141292 flush_namerules(sqlite *db)
935cd37da74Snw141292 {
936c5c4113dSnw141292 	idmap_stat	retcode;
937c5c4113dSnw141292 
93871590c90Snw141292 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, "DELETE FROM namerules;");
939c5c4113dSnw141292 
940c5c4113dSnw141292 	return (retcode);
941c5c4113dSnw141292 }
942c5c4113dSnw141292 
943c5c4113dSnw141292 /*
944c5c4113dSnw141292  * Generate and execute SQL statement to remove a name-based mapping rule
945c5c4113dSnw141292  */
946c5c4113dSnw141292 idmap_retcode
947cd37da74Snw141292 rm_namerule(sqlite *db, idmap_namerule *rule)
948cd37da74Snw141292 {
949c5c4113dSnw141292 	char		*sql = NULL;
950c5c4113dSnw141292 	idmap_stat	retcode;
951c5c4113dSnw141292 	char		buf[80];
952cd37da74Snw141292 	char		*expr = NULL;
953c5c4113dSnw141292 
9548e228215Sdm199847 	if (rule->direction < 0 && EMPTY_STRING(rule->windomain) &&
9558e228215Sdm199847 	    EMPTY_STRING(rule->winname) && EMPTY_STRING(rule->unixname))
956c5c4113dSnw141292 		return (IDMAP_SUCCESS);
957c5c4113dSnw141292 
958c5c4113dSnw141292 	buf[0] = 0;
959cd37da74Snw141292 
960cd37da74Snw141292 	if (rule->direction == IDMAP_DIRECTION_BI)
961c5c4113dSnw141292 		(void) snprintf(buf, sizeof (buf), "AND w2u_order > 0"
962c5c4113dSnw141292 		    " AND u2w_order > 0");
963cd37da74Snw141292 	else if (rule->direction == IDMAP_DIRECTION_W2U)
964c5c4113dSnw141292 		(void) snprintf(buf, sizeof (buf), "AND w2u_order > 0"
965c5c4113dSnw141292 		    " AND (u2w_order = 0 OR u2w_order ISNULL)");
966cd37da74Snw141292 	else if (rule->direction == IDMAP_DIRECTION_U2W)
967c5c4113dSnw141292 		(void) snprintf(buf, sizeof (buf), "AND u2w_order > 0"
968c5c4113dSnw141292 		    " AND (w2u_order = 0 OR w2u_order ISNULL)");
969c5c4113dSnw141292 
970cd37da74Snw141292 	retcode = gen_sql_expr_from_rule(rule, &expr);
971cd37da74Snw141292 	if (retcode != IDMAP_SUCCESS)
972c5c4113dSnw141292 		goto out;
973c5c4113dSnw141292 
974cd37da74Snw141292 	sql = sqlite_mprintf("DELETE FROM namerules WHERE 1 %s %s;", expr,
975c5c4113dSnw141292 	    buf);
976c5c4113dSnw141292 
977c5c4113dSnw141292 	if (sql == NULL) {
978c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
979c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
980c5c4113dSnw141292 		goto out;
981c5c4113dSnw141292 	}
982c5c4113dSnw141292 
983cd37da74Snw141292 
98471590c90Snw141292 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, sql);
985c5c4113dSnw141292 
986c5c4113dSnw141292 out:
987cd37da74Snw141292 	if (expr != NULL)
988cd37da74Snw141292 		sqlite_freemem(expr);
98962c60062Sbaban 	if (sql != NULL)
990c5c4113dSnw141292 		sqlite_freemem(sql);
991c5c4113dSnw141292 	return (retcode);
992c5c4113dSnw141292 }
993c5c4113dSnw141292 
994c5c4113dSnw141292 /*
995c5c4113dSnw141292  * Compile the given SQL query and step just once.
996c5c4113dSnw141292  *
997c5c4113dSnw141292  * Input:
998c5c4113dSnw141292  * db  - db handle
999c5c4113dSnw141292  * sql - SQL statement
1000c5c4113dSnw141292  *
1001c5c4113dSnw141292  * Output:
1002c5c4113dSnw141292  * vm     -  virtual SQL machine
1003c5c4113dSnw141292  * ncol   - number of columns in the result
1004c5c4113dSnw141292  * values - column values
1005c5c4113dSnw141292  *
1006c5c4113dSnw141292  * Return values:
1007c5c4113dSnw141292  * IDMAP_SUCCESS
1008c5c4113dSnw141292  * IDMAP_ERR_NOTFOUND
1009c5c4113dSnw141292  * IDMAP_ERR_INTERNAL
1010c5c4113dSnw141292  */
1011c5c4113dSnw141292 
1012cd37da74Snw141292 static
1013cd37da74Snw141292 idmap_retcode
1014c5c4113dSnw141292 sql_compile_n_step_once(sqlite *db, char *sql, sqlite_vm **vm, int *ncol,
1015cd37da74Snw141292 		int reqcol, const char ***values)
1016cd37da74Snw141292 {
1017c5c4113dSnw141292 	char		*errmsg = NULL;
101884decf41Sjp151216 	int		r;
1019c5c4113dSnw141292 
102084decf41Sjp151216 	if ((r = sqlite_compile(db, sql, NULL, vm, &errmsg)) != SQLITE_OK) {
1021cd37da74Snw141292 		idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
1022cd37da74Snw141292 		    CHECK_NULL(errmsg));
1023c5c4113dSnw141292 		sqlite_freemem(errmsg);
1024c5c4113dSnw141292 		return (IDMAP_ERR_INTERNAL);
1025c5c4113dSnw141292 	}
1026c5c4113dSnw141292 
1027c5c4113dSnw141292 	r = sqlite_step(*vm, ncol, values, NULL);
102884decf41Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
1029c5c4113dSnw141292 
103084decf41Sjp151216 	if (r == SQLITE_ROW) {
103162c60062Sbaban 		if (ncol != NULL && *ncol < reqcol) {
1032c5c4113dSnw141292 			(void) sqlite_finalize(*vm, NULL);
1033c5c4113dSnw141292 			*vm = NULL;
1034c5c4113dSnw141292 			return (IDMAP_ERR_INTERNAL);
1035c5c4113dSnw141292 		}
1036c5c4113dSnw141292 		/* Caller will call finalize after using the results */
1037c5c4113dSnw141292 		return (IDMAP_SUCCESS);
1038c5c4113dSnw141292 	} else if (r == SQLITE_DONE) {
1039c5c4113dSnw141292 		(void) sqlite_finalize(*vm, NULL);
1040c5c4113dSnw141292 		*vm = NULL;
1041c5c4113dSnw141292 		return (IDMAP_ERR_NOTFOUND);
1042c5c4113dSnw141292 	}
1043c5c4113dSnw141292 
1044c5c4113dSnw141292 	(void) sqlite_finalize(*vm, &errmsg);
1045c5c4113dSnw141292 	*vm = NULL;
1046cd37da74Snw141292 	idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
1047cd37da74Snw141292 	    CHECK_NULL(errmsg));
1048c5c4113dSnw141292 	sqlite_freemem(errmsg);
1049c5c4113dSnw141292 	return (IDMAP_ERR_INTERNAL);
1050c5c4113dSnw141292 }
1051c5c4113dSnw141292 
105262c60062Sbaban /*
1053479ac375Sdm199847  * Load config in the state.
1054e8c27ec8Sbaban  *
1055479ac375Sdm199847  * nm_siduid and nm_sidgid fields:
1056e8c27ec8Sbaban  * state->nm_siduid represents mode used by sid2uid and uid2sid
1057e8c27ec8Sbaban  * requests for directory-based name mappings. Similarly,
1058e8c27ec8Sbaban  * state->nm_sidgid represents mode used by sid2gid and gid2sid
1059e8c27ec8Sbaban  * requests.
1060e8c27ec8Sbaban  *
1061e8c27ec8Sbaban  * sid2uid/uid2sid:
1062e8c27ec8Sbaban  * none       -> ds_name_mapping_enabled != true
1063e8c27ec8Sbaban  * AD-mode    -> !nldap_winname_attr && ad_unixuser_attr
1064e8c27ec8Sbaban  * nldap-mode -> nldap_winname_attr && !ad_unixuser_attr
1065e8c27ec8Sbaban  * mixed-mode -> nldap_winname_attr && ad_unixuser_attr
1066e8c27ec8Sbaban  *
1067e8c27ec8Sbaban  * sid2gid/gid2sid:
1068e8c27ec8Sbaban  * none       -> ds_name_mapping_enabled != true
1069e8c27ec8Sbaban  * AD-mode    -> !nldap_winname_attr && ad_unixgroup_attr
1070e8c27ec8Sbaban  * nldap-mode -> nldap_winname_attr && !ad_unixgroup_attr
1071e8c27ec8Sbaban  * mixed-mode -> nldap_winname_attr && ad_unixgroup_attr
1072e8c27ec8Sbaban  */
1073e8c27ec8Sbaban idmap_retcode
1074479ac375Sdm199847 load_cfg_in_state(lookup_state_t *state)
1075e8c27ec8Sbaban {
1076e8c27ec8Sbaban 	state->nm_siduid = IDMAP_NM_NONE;
1077e8c27ec8Sbaban 	state->nm_sidgid = IDMAP_NM_NONE;
1078e8c27ec8Sbaban 	RDLOCK_CONFIG();
1079479ac375Sdm199847 
1080479ac375Sdm199847 	if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
1081479ac375Sdm199847 		state->defdom =
1082479ac375Sdm199847 		    strdup(_idmapdstate.cfg->pgcfg.default_domain);
1083479ac375Sdm199847 		if (state->defdom == NULL) {
1084479ac375Sdm199847 			UNLOCK_CONFIG();
1085479ac375Sdm199847 			return (IDMAP_ERR_MEMORY);
1086479ac375Sdm199847 		}
1087479ac375Sdm199847 	} else {
1088479ac375Sdm199847 		UNLOCK_CONFIG();
1089dc03a638Sdm199847 		return (IDMAP_SUCCESS);
1090479ac375Sdm199847 	}
1091e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.ds_name_mapping_enabled == FALSE) {
1092e8c27ec8Sbaban 		UNLOCK_CONFIG();
1093e8c27ec8Sbaban 		return (IDMAP_SUCCESS);
1094e8c27ec8Sbaban 	}
1095e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.nldap_winname_attr != NULL) {
1096e8c27ec8Sbaban 		state->nm_siduid =
1097e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
1098e8c27ec8Sbaban 		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
1099e8c27ec8Sbaban 		state->nm_sidgid =
1100e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
1101e8c27ec8Sbaban 		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
1102e8c27ec8Sbaban 	} else {
1103e8c27ec8Sbaban 		state->nm_siduid =
1104e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
1105e8c27ec8Sbaban 		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
1106e8c27ec8Sbaban 		state->nm_sidgid =
1107e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
1108e8c27ec8Sbaban 		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
1109e8c27ec8Sbaban 	}
1110e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL) {
1111e8c27ec8Sbaban 		state->ad_unixuser_attr =
1112e8c27ec8Sbaban 		    strdup(_idmapdstate.cfg->pgcfg.ad_unixuser_attr);
1113e8c27ec8Sbaban 		if (state->ad_unixuser_attr == NULL) {
1114e8c27ec8Sbaban 			UNLOCK_CONFIG();
1115e8c27ec8Sbaban 			return (IDMAP_ERR_MEMORY);
1116e8c27ec8Sbaban 		}
1117e8c27ec8Sbaban 	}
1118e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL) {
1119e8c27ec8Sbaban 		state->ad_unixgroup_attr =
1120e8c27ec8Sbaban 		    strdup(_idmapdstate.cfg->pgcfg.ad_unixgroup_attr);
1121e8c27ec8Sbaban 		if (state->ad_unixgroup_attr == NULL) {
1122e8c27ec8Sbaban 			UNLOCK_CONFIG();
1123e8c27ec8Sbaban 			return (IDMAP_ERR_MEMORY);
1124e8c27ec8Sbaban 		}
1125e8c27ec8Sbaban 	}
1126479ac375Sdm199847 	if (_idmapdstate.cfg->pgcfg.nldap_winname_attr != NULL) {
1127479ac375Sdm199847 		state->nldap_winname_attr =
1128479ac375Sdm199847 		    strdup(_idmapdstate.cfg->pgcfg.nldap_winname_attr);
1129479ac375Sdm199847 		if (state->nldap_winname_attr == NULL) {
1130479ac375Sdm199847 			UNLOCK_CONFIG();
1131479ac375Sdm199847 			return (IDMAP_ERR_MEMORY);
1132479ac375Sdm199847 		}
1133479ac375Sdm199847 	}
1134e8c27ec8Sbaban 	UNLOCK_CONFIG();
1135e8c27ec8Sbaban 	return (IDMAP_SUCCESS);
1136e8c27ec8Sbaban }
1137e8c27ec8Sbaban 
1138e8c27ec8Sbaban /*
113948258c6bSjp151216  * Set the rule with sepecified values.
114048258c6bSjp151216  * All the strings are copied.
114148258c6bSjp151216  */
114248258c6bSjp151216 static void
114348258c6bSjp151216 idmap_namerule_set(idmap_namerule *rule, const char *windomain,
114448258c6bSjp151216 		const char *winname, const char *unixname, boolean_t is_user,
114548258c6bSjp151216 		boolean_t is_wuser, boolean_t is_nt4, int direction)
114648258c6bSjp151216 {
114748258c6bSjp151216 	/*
114848258c6bSjp151216 	 * Only update if they differ because we have to free
114948258c6bSjp151216 	 * and duplicate the strings
115048258c6bSjp151216 	 */
115148258c6bSjp151216 	if (rule->windomain == NULL || windomain == NULL ||
115248258c6bSjp151216 	    strcmp(rule->windomain, windomain) != 0) {
115348258c6bSjp151216 		if (rule->windomain != NULL) {
115448258c6bSjp151216 			free(rule->windomain);
115548258c6bSjp151216 			rule->windomain = NULL;
115648258c6bSjp151216 		}
115748258c6bSjp151216 		if (windomain != NULL)
115848258c6bSjp151216 			rule->windomain = strdup(windomain);
115948258c6bSjp151216 	}
116048258c6bSjp151216 
116148258c6bSjp151216 	if (rule->winname == NULL || winname == NULL ||
116248258c6bSjp151216 	    strcmp(rule->winname, winname) != 0) {
116348258c6bSjp151216 		if (rule->winname != NULL) {
116448258c6bSjp151216 			free(rule->winname);
116548258c6bSjp151216 			rule->winname = NULL;
116648258c6bSjp151216 		}
116748258c6bSjp151216 		if (winname != NULL)
116848258c6bSjp151216 			rule->winname = strdup(winname);
116948258c6bSjp151216 	}
117048258c6bSjp151216 
117148258c6bSjp151216 	if (rule->unixname == NULL || unixname == NULL ||
117248258c6bSjp151216 	    strcmp(rule->unixname, unixname) != 0) {
117348258c6bSjp151216 		if (rule->unixname != NULL) {
117448258c6bSjp151216 			free(rule->unixname);
117548258c6bSjp151216 			rule->unixname = NULL;
117648258c6bSjp151216 		}
117748258c6bSjp151216 		if (unixname != NULL)
117848258c6bSjp151216 			rule->unixname = strdup(unixname);
117948258c6bSjp151216 	}
118048258c6bSjp151216 
118148258c6bSjp151216 	rule->is_user = is_user;
118248258c6bSjp151216 	rule->is_wuser = is_wuser;
118348258c6bSjp151216 	rule->is_nt4 = is_nt4;
118448258c6bSjp151216 	rule->direction = direction;
118548258c6bSjp151216 }
118648258c6bSjp151216 
118748258c6bSjp151216 
118848258c6bSjp151216 /*
118962c60062Sbaban  * Table for well-known SIDs.
119062c60062Sbaban  *
119162c60062Sbaban  * Background:
119262c60062Sbaban  *
119376b27f93Sbaban  * Some of the well-known principals are stored under:
119462c60062Sbaban  * cn=WellKnown Security Principals, cn=Configuration, dc=<forestRootDomain>
119562c60062Sbaban  * They belong to objectClass "foreignSecurityPrincipal". They don't have
119662c60062Sbaban  * "samAccountName" nor "userPrincipalName" attributes. Their names are
119762c60062Sbaban  * available in "cn" and "name" attributes. Some of these principals have a
119862c60062Sbaban  * second entry under CN=ForeignSecurityPrincipals,dc=<forestRootDomain> and
119962c60062Sbaban  * these duplicate entries have the stringified SID in the "name" and "cn"
120062c60062Sbaban  * attributes instead of the actual name.
120162c60062Sbaban  *
120276b27f93Sbaban  * Those of the form S-1-5-32-X are Builtin groups and are stored in the
120376b27f93Sbaban  * cn=builtin container (except, Power Users which is not stored in AD)
120462c60062Sbaban  *
120576b27f93Sbaban  * These principals are and will remain constant. Therefore doing AD lookups
120676b27f93Sbaban  * provides no benefit. Also, using hard-coded table (and thus avoiding AD
120776b27f93Sbaban  * lookup) improves performance and avoids additional complexity in the
120876b27f93Sbaban  * adutils.c code. Moreover these SIDs can be used when no Active Directory
120976b27f93Sbaban  * is available (such as the CIFS server's "workgroup" mode).
121076b27f93Sbaban  *
121176b27f93Sbaban  * Notes:
121276b27f93Sbaban  * 1. Currently we don't support localization of well-known SID names,
121362c60062Sbaban  * unlike Windows.
121462c60062Sbaban  *
121576b27f93Sbaban  * 2. Other well-known SIDs i.e. S-1-5-<domain>-<w-k RID> are not stored
121676b27f93Sbaban  * here. AD does have normal user/group objects for these objects and
121776b27f93Sbaban  * can be looked up using the existing AD lookup code.
1218e8c27ec8Sbaban  *
1219e8c27ec8Sbaban  * 3. See comments above lookup_wksids_sid2pid() for more information
1220e8c27ec8Sbaban  * on how we lookup the wksids table.
122162c60062Sbaban  */
122262c60062Sbaban static wksids_table_t wksids[] = {
1223e8c27ec8Sbaban 	{"S-1-0", 0, "Nobody", 0, SENTINEL_PID, -1, 1},
1224e8c27ec8Sbaban 	{"S-1-1", 0, "Everyone", 0, SENTINEL_PID, -1, -1},
1225e8c27ec8Sbaban 	{"S-1-3", 0, "Creator Owner", 1, IDMAP_WK_CREATOR_OWNER_UID, 1, 0},
1226e8c27ec8Sbaban 	{"S-1-3", 1, "Creator Group", 0, IDMAP_WK_CREATOR_GROUP_GID, 0, 0},
1227e8c27ec8Sbaban 	{"S-1-3", 2, "Creator Owner Server", 1, SENTINEL_PID, -1, -1},
1228e8c27ec8Sbaban 	{"S-1-3", 3, "Creator Group Server", 0, SENTINEL_PID, -1, 1},
1229e8c27ec8Sbaban 	{"S-1-3", 4, "Owner Rights", 0, SENTINEL_PID, -1, -1},
1230e8c27ec8Sbaban 	{"S-1-5", 1, "Dialup", 0, SENTINEL_PID, -1, -1},
1231e8c27ec8Sbaban 	{"S-1-5", 2, "Network", 0, SENTINEL_PID, -1, -1},
1232e8c27ec8Sbaban 	{"S-1-5", 3, "Batch", 0, SENTINEL_PID, -1, -1},
1233e8c27ec8Sbaban 	{"S-1-5", 4, "Interactive", 0, SENTINEL_PID, -1, -1},
1234e8c27ec8Sbaban 	{"S-1-5", 6, "Service", 0, SENTINEL_PID, -1, -1},
1235e8c27ec8Sbaban 	{"S-1-5", 7, "Anonymous Logon", 0, GID_NOBODY, 0, 0},
1236e8c27ec8Sbaban 	{"S-1-5", 7, "Anonymous Logon", 0, UID_NOBODY, 1, 0},
1237e8c27ec8Sbaban 	{"S-1-5", 8, "Proxy", 0, SENTINEL_PID, -1, -1},
1238e8c27ec8Sbaban 	{"S-1-5", 9, "Enterprise Domain Controllers", 0, SENTINEL_PID, -1, -1},
1239e8c27ec8Sbaban 	{"S-1-5", 10, "Self", 0, SENTINEL_PID, -1, -1},
1240e8c27ec8Sbaban 	{"S-1-5", 11, "Authenticated Users", 0, SENTINEL_PID, -1, -1},
1241e8c27ec8Sbaban 	{"S-1-5", 12, "Restricted Code", 0, SENTINEL_PID, -1, -1},
1242e8c27ec8Sbaban 	{"S-1-5", 13, "Terminal Server User", 0, SENTINEL_PID, -1, -1},
1243e8c27ec8Sbaban 	{"S-1-5", 14, "Remote Interactive Logon", 0, SENTINEL_PID, -1, -1},
1244e8c27ec8Sbaban 	{"S-1-5", 15, "This Organization", 0, SENTINEL_PID, -1, -1},
1245e8c27ec8Sbaban 	{"S-1-5", 17, "IUSR", 0, SENTINEL_PID, -1, -1},
1246e8c27ec8Sbaban 	{"S-1-5", 18, "Local System", 0, IDMAP_WK_LOCAL_SYSTEM_GID, 0, 0},
1247e8c27ec8Sbaban 	{"S-1-5", 19, "Local Service", 0, SENTINEL_PID, -1, -1},
1248e8c27ec8Sbaban 	{"S-1-5", 20, "Network Service", 0, SENTINEL_PID, -1, -1},
1249e8c27ec8Sbaban 	{"S-1-5", 1000, "Other Organization", 0, SENTINEL_PID, -1, -1},
1250e8c27ec8Sbaban 	{"S-1-5-32", 544, "Administrators", 0, SENTINEL_PID, -1, -1},
1251e8c27ec8Sbaban 	{"S-1-5-32", 545, "Users", 0, SENTINEL_PID, -1, -1},
1252e8c27ec8Sbaban 	{"S-1-5-32", 546, "Guests", 0, SENTINEL_PID, -1, -1},
1253e8c27ec8Sbaban 	{"S-1-5-32", 547, "Power Users", 0, SENTINEL_PID, -1, -1},
1254e8c27ec8Sbaban 	{"S-1-5-32", 548, "Account Operators", 0, SENTINEL_PID, -1, -1},
1255e8c27ec8Sbaban 	{"S-1-5-32", 549, "Server Operators", 0, SENTINEL_PID, -1, -1},
1256e8c27ec8Sbaban 	{"S-1-5-32", 550, "Print Operators", 0, SENTINEL_PID, -1, -1},
1257e8c27ec8Sbaban 	{"S-1-5-32", 551, "Backup Operators", 0, SENTINEL_PID, -1, -1},
1258e8c27ec8Sbaban 	{"S-1-5-32", 552, "Replicator", 0, SENTINEL_PID, -1, -1},
125976b27f93Sbaban 	{"S-1-5-32", 554, "Pre-Windows 2000 Compatible Access", 0,
1260e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1261e8c27ec8Sbaban 	{"S-1-5-32", 555, "Remote Desktop Users", 0, SENTINEL_PID, -1, -1},
126276b27f93Sbaban 	{"S-1-5-32", 556, "Network Configuration Operators", 0,
1263e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
126476b27f93Sbaban 	{"S-1-5-32", 557, "Incoming Forest Trust Builders", 0,
1265e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1266e8c27ec8Sbaban 	{"S-1-5-32", 558, "Performance Monitor Users", 0, SENTINEL_PID, -1, -1},
1267e8c27ec8Sbaban 	{"S-1-5-32", 559, "Performance Log Users", 0, SENTINEL_PID, -1, -1},
126876b27f93Sbaban 	{"S-1-5-32", 560, "Windows Authorization Access Group", 0,
1269e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
127076b27f93Sbaban 	{"S-1-5-32", 561, "Terminal Server License Servers", 0,
1271e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1272e8c27ec8Sbaban 	{"S-1-5-32", 561, "Distributed COM Users", 0, SENTINEL_PID, -1, -1},
1273e8c27ec8Sbaban 	{"S-1-5-32", 568, "IIS_IUSRS", 0, SENTINEL_PID, -1, -1},
1274e8c27ec8Sbaban 	{"S-1-5-32", 569, "Cryptographic Operators", 0, SENTINEL_PID, -1, -1},
1275e8c27ec8Sbaban 	{"S-1-5-32", 573, "Event Log Readers", 0, SENTINEL_PID, -1, -1},
127676b27f93Sbaban 	{"S-1-5-32", 574, "Certificate Service DCOM Access", 0,
1277e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1278e8c27ec8Sbaban 	{"S-1-5-64", 21, "Digest Authentication", 0, SENTINEL_PID, -1, -1},
1279e8c27ec8Sbaban 	{"S-1-5-64", 10, "NTLM Authentication", 0, SENTINEL_PID, -1, -1},
1280e8c27ec8Sbaban 	{"S-1-5-64", 14, "SChannel Authentication", 0, SENTINEL_PID, -1, -1},
1281e8c27ec8Sbaban 	{NULL, UINT32_MAX, NULL, -1, SENTINEL_PID, -1, -1}
1282c5c4113dSnw141292 };
1283c5c4113dSnw141292 
1284e8c27ec8Sbaban /*
1285e8c27ec8Sbaban  * Lookup well-known SIDs table either by winname or by SID.
1286e8c27ec8Sbaban  * If the given winname or SID is a well-known SID then we set wksid
1287e8c27ec8Sbaban  * variable and then proceed to see if the SID has a hard mapping to
1288e8c27ec8Sbaban  * a particular UID/GID (Ex: Creator Owner/Creator Group mapped to
1289e8c27ec8Sbaban  * fixed ephemeral ids). If we find such mapping then we return
1290e8c27ec8Sbaban  * success otherwise notfound. If a well-known SID is mapped to
1291e8c27ec8Sbaban  * SENTINEL_PID and the direction field is set (bi-directional or
1292e8c27ec8Sbaban  * win2unix) then we treat it as inhibited mapping and return no
1293e8c27ec8Sbaban  * mapping (Ex. S-1-0-0).
1294e8c27ec8Sbaban  */
1295cd37da74Snw141292 static
1296cd37da74Snw141292 idmap_retcode
1297e8c27ec8Sbaban lookup_wksids_sid2pid(idmap_mapping *req, idmap_id_res *res, int *wksid)
1298cd37da74Snw141292 {
1299c5c4113dSnw141292 	int i;
130062c60062Sbaban 
1301e8c27ec8Sbaban 	*wksid = 0;
1302e8c27ec8Sbaban 
1303e8c27ec8Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
1304e8c27ec8Sbaban 		if (req->id1.idmap_id_u.sid.prefix != NULL) {
1305e8c27ec8Sbaban 			if ((strcasecmp(wksids[i].sidprefix,
1306e8c27ec8Sbaban 			    req->id1.idmap_id_u.sid.prefix) != 0) ||
1307e8c27ec8Sbaban 			    wksids[i].rid != req->id1.idmap_id_u.sid.rid)
1308e8c27ec8Sbaban 				/* this is not our SID */
1309e8c27ec8Sbaban 				continue;
1310e8c27ec8Sbaban 			if (req->id1name == NULL) {
1311e8c27ec8Sbaban 				req->id1name = strdup(wksids[i].winname);
1312e8c27ec8Sbaban 				if (req->id1name == NULL)
1313e8c27ec8Sbaban 					return (IDMAP_ERR_MEMORY);
1314e8c27ec8Sbaban 			}
1315e8c27ec8Sbaban 		} else if (req->id1name != NULL) {
1316e8c27ec8Sbaban 			if (strcasecmp(wksids[i].winname, req->id1name) != 0)
1317e8c27ec8Sbaban 				/* this is not our winname */
1318e8c27ec8Sbaban 				continue;
1319e8c27ec8Sbaban 			req->id1.idmap_id_u.sid.prefix =
1320e8c27ec8Sbaban 			    strdup(wksids[i].sidprefix);
1321e8c27ec8Sbaban 			if (req->id1.idmap_id_u.sid.prefix == NULL)
1322e8c27ec8Sbaban 				return (IDMAP_ERR_MEMORY);
1323e8c27ec8Sbaban 			req->id1.idmap_id_u.sid.rid = wksids[i].rid;
1324e8c27ec8Sbaban 		}
1325e8c27ec8Sbaban 
1326e8c27ec8Sbaban 		*wksid = 1;
1327e8c27ec8Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
1328e8c27ec8Sbaban 
1329e8c27ec8Sbaban 		req->id1.idtype = (wksids[i].is_wuser) ?
1330e8c27ec8Sbaban 		    IDMAP_USID : IDMAP_GSID;
1331e8c27ec8Sbaban 
1332e8c27ec8Sbaban 		if (wksids[i].pid == SENTINEL_PID) {
1333e8c27ec8Sbaban 			if (wksids[i].direction == IDMAP_DIRECTION_BI ||
1334e8c27ec8Sbaban 			    wksids[i].direction == IDMAP_DIRECTION_W2U)
1335e8c27ec8Sbaban 				/* Inhibited */
1336e8c27ec8Sbaban 				return (IDMAP_ERR_NOMAPPING);
1337e8c27ec8Sbaban 			/* Not mapped */
1338479ac375Sdm199847 			if (res->id.idtype == IDMAP_POSIXID) {
1339479ac375Sdm199847 				res->id.idtype =
1340479ac375Sdm199847 				    (wksids[i].is_wuser) ?
1341479ac375Sdm199847 				    IDMAP_UID : IDMAP_GID;
1342479ac375Sdm199847 			}
1343e8c27ec8Sbaban 			return (IDMAP_ERR_NOTFOUND);
1344e8c27ec8Sbaban 		} else if (wksids[i].direction == IDMAP_DIRECTION_U2W)
134562c60062Sbaban 			continue;
134662c60062Sbaban 
1347e8c27ec8Sbaban 		switch (res->id.idtype) {
1348c5c4113dSnw141292 		case IDMAP_UID:
134962c60062Sbaban 			if (wksids[i].is_user == 0)
135062c60062Sbaban 				continue;
135162c60062Sbaban 			res->id.idmap_id_u.uid = wksids[i].pid;
135262c60062Sbaban 			res->direction = wksids[i].direction;
135348258c6bSjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
135448258c6bSjp151216 				res->info.how.map_type =
135548258c6bSjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
135648258c6bSjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
135748258c6bSjp151216 			}
1358c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1359c5c4113dSnw141292 		case IDMAP_GID:
136062c60062Sbaban 			if (wksids[i].is_user == 1)
136162c60062Sbaban 				continue;
136262c60062Sbaban 			res->id.idmap_id_u.gid = wksids[i].pid;
136362c60062Sbaban 			res->direction = wksids[i].direction;
136448258c6bSjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
136548258c6bSjp151216 				res->info.how.map_type =
136648258c6bSjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
136748258c6bSjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
136848258c6bSjp151216 			}
1369c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1370c5c4113dSnw141292 		case IDMAP_POSIXID:
137162c60062Sbaban 			res->id.idmap_id_u.uid = wksids[i].pid;
137262c60062Sbaban 			res->id.idtype = (!wksids[i].is_user) ?
1373c5c4113dSnw141292 			    IDMAP_GID : IDMAP_UID;
137462c60062Sbaban 			res->direction = wksids[i].direction;
137548258c6bSjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
137648258c6bSjp151216 				res->info.how.map_type =
137748258c6bSjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
137848258c6bSjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
137948258c6bSjp151216 			}
1380c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1381c5c4113dSnw141292 		default:
1382c5c4113dSnw141292 			return (IDMAP_ERR_NOTSUPPORTED);
1383c5c4113dSnw141292 		}
1384c5c4113dSnw141292 	}
1385c5c4113dSnw141292 	return (IDMAP_ERR_NOTFOUND);
1386c5c4113dSnw141292 }
1387c5c4113dSnw141292 
1388cd37da74Snw141292 
1389cd37da74Snw141292 static
1390cd37da74Snw141292 idmap_retcode
1391cd37da74Snw141292 lookup_wksids_pid2sid(idmap_mapping *req, idmap_id_res *res, int is_user)
1392cd37da74Snw141292 {
1393c5c4113dSnw141292 	int i;
1394e8c27ec8Sbaban 	if (req->id1.idmap_id_u.uid == SENTINEL_PID)
1395e8c27ec8Sbaban 		return (IDMAP_ERR_NOTFOUND);
139662c60062Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
139762c60062Sbaban 		if (wksids[i].pid == req->id1.idmap_id_u.uid &&
139862c60062Sbaban 		    wksids[i].is_user == is_user &&
139962c60062Sbaban 		    wksids[i].direction != IDMAP_DIRECTION_W2U) {
1400e8c27ec8Sbaban 			if (res->id.idtype == IDMAP_SID) {
1401e8c27ec8Sbaban 				res->id.idtype = (wksids[i].is_wuser) ?
1402e8c27ec8Sbaban 				    IDMAP_USID : IDMAP_GSID;
1403e8c27ec8Sbaban 			}
140462c60062Sbaban 			res->id.idmap_id_u.sid.rid = wksids[i].rid;
1405c5c4113dSnw141292 			res->id.idmap_id_u.sid.prefix =
140662c60062Sbaban 			    strdup(wksids[i].sidprefix);
1407c5c4113dSnw141292 			if (res->id.idmap_id_u.sid.prefix == NULL) {
1408c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1409c5c4113dSnw141292 				return (IDMAP_ERR_MEMORY);
1410c5c4113dSnw141292 			}
141162c60062Sbaban 			res->direction = wksids[i].direction;
141248258c6bSjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
141348258c6bSjp151216 				res->info.how.map_type =
141448258c6bSjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
141548258c6bSjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
141648258c6bSjp151216 			}
1417c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1418c5c4113dSnw141292 		}
1419c5c4113dSnw141292 	}
142062c60062Sbaban 	return (IDMAP_ERR_NOTFOUND);
142162c60062Sbaban }
142262c60062Sbaban 
1423cd37da74Snw141292 idmap_retcode
1424cd37da74Snw141292 lookup_wksids_name2sid(const char *name, char **canonname, char **sidprefix,
1425cd37da74Snw141292 	idmap_rid_t *rid, int *type)
1426cd37da74Snw141292 {
142762c60062Sbaban 	int	i;
1428479ac375Sdm199847 
1429479ac375Sdm199847 	if ((strncasecmp(name, "BUILTIN\\", 8) == 0) ||
1430479ac375Sdm199847 	    (strncasecmp(name, "BUILTIN/", 8) == 0))
1431479ac375Sdm199847 		name += 8;
1432479ac375Sdm199847 
143362c60062Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
1434e8c27ec8Sbaban 		if (strcasecmp(wksids[i].winname, name) != 0)
1435e8c27ec8Sbaban 			continue;
1436e8c27ec8Sbaban 		if (sidprefix != NULL &&
1437e8c27ec8Sbaban 		    (*sidprefix = strdup(wksids[i].sidprefix)) == NULL) {
143862c60062Sbaban 			idmapdlog(LOG_ERR, "Out of memory");
143962c60062Sbaban 			return (IDMAP_ERR_MEMORY);
144062c60062Sbaban 		}
1441cd37da74Snw141292 		if (canonname != NULL &&
1442cd37da74Snw141292 		    (*canonname = strdup(wksids[i].winname)) == NULL) {
1443cd37da74Snw141292 			idmapdlog(LOG_ERR, "Out of memory");
1444e8c27ec8Sbaban 			if (sidprefix != NULL) {
1445e8c27ec8Sbaban 				free(*sidprefix);
1446e8c27ec8Sbaban 				*sidprefix = NULL;
1447e8c27ec8Sbaban 			}
1448cd37da74Snw141292 			return (IDMAP_ERR_MEMORY);
1449cd37da74Snw141292 		}
145062c60062Sbaban 		if (type != NULL)
1451e8c27ec8Sbaban 			*type = (wksids[i].is_wuser) ?
145262c60062Sbaban 			    _IDMAP_T_USER : _IDMAP_T_GROUP;
145362c60062Sbaban 		if (rid != NULL)
145462c60062Sbaban 			*rid = wksids[i].rid;
145562c60062Sbaban 		return (IDMAP_SUCCESS);
145662c60062Sbaban 	}
1457c5c4113dSnw141292 	return (IDMAP_ERR_NOTFOUND);
1458c5c4113dSnw141292 }
1459c5c4113dSnw141292 
1460cd37da74Snw141292 static
1461cd37da74Snw141292 idmap_retcode
1462cd37da74Snw141292 lookup_cache_sid2pid(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
1463cd37da74Snw141292 {
1464c5c4113dSnw141292 	char		*end;
1465c5c4113dSnw141292 	char		*sql = NULL;
1466c5c4113dSnw141292 	const char	**values;
1467c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
1468c5c4113dSnw141292 	int		ncol, is_user;
1469c5c4113dSnw141292 	uid_t		pid;
1470c5c4113dSnw141292 	time_t		curtime, exp;
1471c5c4113dSnw141292 	idmap_retcode	retcode;
1472042addd6Sbaban 	char		*is_user_string, *lower_name;
1473c5c4113dSnw141292 
1474c5c4113dSnw141292 	/* Current time */
1475c5c4113dSnw141292 	errno = 0;
1476c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
1477cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
1478c5c4113dSnw141292 		    strerror(errno));
1479c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
1480c5c4113dSnw141292 		goto out;
1481c5c4113dSnw141292 	}
1482c5c4113dSnw141292 
1483e8c27ec8Sbaban 	switch (res->id.idtype) {
1484cd37da74Snw141292 	case IDMAP_UID:
1485cd37da74Snw141292 		is_user_string = "1";
1486cd37da74Snw141292 		break;
1487cd37da74Snw141292 	case IDMAP_GID:
1488cd37da74Snw141292 		is_user_string = "0";
1489cd37da74Snw141292 		break;
1490cd37da74Snw141292 	case IDMAP_POSIXID:
1491cd37da74Snw141292 		/* the non-diagonal mapping */
1492cd37da74Snw141292 		is_user_string = "is_wuser";
1493cd37da74Snw141292 		break;
1494cd37da74Snw141292 	default:
1495cd37da74Snw141292 		retcode = IDMAP_ERR_NOTSUPPORTED;
1496cd37da74Snw141292 		goto out;
1497cd37da74Snw141292 	}
1498cd37da74Snw141292 
1499c5c4113dSnw141292 	/* SQL to lookup the cache */
150048258c6bSjp151216 
1501e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
1502e8c27ec8Sbaban 		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
150348258c6bSjp151216 		    "unixname, u2w, is_wuser, "
150448258c6bSjp151216 		    "map_type, map_dn, map_attr, map_value, "
150548258c6bSjp151216 		    "map_windomain, map_winname, map_unixname, map_is_nt4 "
1506cd37da74Snw141292 		    "FROM idmap_cache WHERE is_user = %s AND "
1507c5c4113dSnw141292 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
1508c5c4113dSnw141292 		    "(pid >= 2147483648 OR "
1509c5c4113dSnw141292 		    "(expiration = 0 OR expiration ISNULL OR "
1510c5c4113dSnw141292 		    "expiration > %d));",
1511e8c27ec8Sbaban 		    is_user_string, req->id1.idmap_id_u.sid.prefix,
1512e8c27ec8Sbaban 		    req->id1.idmap_id_u.sid.rid, curtime);
1513e8c27ec8Sbaban 	} else if (req->id1name != NULL) {
1514042addd6Sbaban 		if ((lower_name = tolower_u8(req->id1name)) == NULL)
1515042addd6Sbaban 			lower_name = req->id1name;
1516e8c27ec8Sbaban 		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
151748258c6bSjp151216 		    "unixname, u2w, is_wuser, "
151848258c6bSjp151216 		    "map_type, map_dn, map_attr, map_value, "
151948258c6bSjp151216 		    "map_windomain, map_winname, map_unixname, map_is_nt4 "
1520e8c27ec8Sbaban 		    "FROM idmap_cache WHERE is_user = %s AND "
1521e8c27ec8Sbaban 		    "winname = %Q AND windomain = %Q AND w2u = 1 AND "
1522e8c27ec8Sbaban 		    "(pid >= 2147483648 OR "
1523e8c27ec8Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
1524e8c27ec8Sbaban 		    "expiration > %d));",
152548258c6bSjp151216 		    is_user_string, lower_name, req->id1domain,
152648258c6bSjp151216 		    curtime);
1527042addd6Sbaban 		if (lower_name != req->id1name)
1528042addd6Sbaban 			free(lower_name);
1529e8c27ec8Sbaban 	} else {
1530e8c27ec8Sbaban 		retcode = IDMAP_ERR_ARG;
1531e8c27ec8Sbaban 		goto out;
1532e8c27ec8Sbaban 	}
1533c5c4113dSnw141292 	if (sql == NULL) {
1534c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
1535c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
1536c5c4113dSnw141292 		goto out;
1537c5c4113dSnw141292 	}
153848258c6bSjp151216 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol,
153948258c6bSjp151216 	    14, &values);
1540c5c4113dSnw141292 	sqlite_freemem(sql);
1541c5c4113dSnw141292 
1542c5c4113dSnw141292 	if (retcode == IDMAP_ERR_NOTFOUND) {
1543c5c4113dSnw141292 		goto out;
1544c5c4113dSnw141292 	} else if (retcode == IDMAP_SUCCESS) {
1545c5c4113dSnw141292 		/* sanity checks */
1546c5c4113dSnw141292 		if (values[0] == NULL || values[1] == NULL) {
1547c5c4113dSnw141292 			retcode = IDMAP_ERR_CACHE;
1548c5c4113dSnw141292 			goto out;
1549c5c4113dSnw141292 		}
1550c5c4113dSnw141292 
1551c5c4113dSnw141292 		pid = strtoul(values[0], &end, 10);
1552c5c4113dSnw141292 		is_user = strncmp(values[1], "0", 2) ? 1 : 0;
1553c5c4113dSnw141292 
1554cd37da74Snw141292 		if (is_user) {
1555cd37da74Snw141292 			res->id.idtype = IDMAP_UID;
1556cd37da74Snw141292 			res->id.idmap_id_u.uid = pid;
1557cd37da74Snw141292 		} else {
1558cd37da74Snw141292 			res->id.idtype = IDMAP_GID;
1559cd37da74Snw141292 			res->id.idmap_id_u.gid = pid;
1560cd37da74Snw141292 		}
1561cd37da74Snw141292 
1562c5c4113dSnw141292 		/*
1563c5c4113dSnw141292 		 * We may have an expired ephemeral mapping. Consider
1564c5c4113dSnw141292 		 * the expired entry as valid if we are not going to
1565c5c4113dSnw141292 		 * perform name-based mapping. But do not renew the
1566c5c4113dSnw141292 		 * expiration.
1567c5c4113dSnw141292 		 * If we will be doing name-based mapping then store the
1568c5c4113dSnw141292 		 * ephemeral pid in the result so that we can use it
1569c5c4113dSnw141292 		 * if we end up doing dynamic mapping again.
1570c5c4113dSnw141292 		 */
1571c5c4113dSnw141292 		if (!DO_NOT_ALLOC_NEW_ID_MAPPING(req) &&
1572cd37da74Snw141292 		    !AVOID_NAMESERVICE(req) &&
1573cd37da74Snw141292 		    IS_EPHEMERAL(pid) && values[2] != NULL) {
1574c5c4113dSnw141292 			exp = strtoll(values[2], &end, 10);
1575c5c4113dSnw141292 			if (exp && exp <= curtime) {
1576c5c4113dSnw141292 				/* Store the ephemeral pid */
1577651c0131Sbaban 				res->direction = IDMAP_DIRECTION_BI;
1578cd37da74Snw141292 				req->direction |= is_user
1579cd37da74Snw141292 				    ? _IDMAP_F_EXP_EPH_UID
1580cd37da74Snw141292 				    : _IDMAP_F_EXP_EPH_GID;
1581c5c4113dSnw141292 				retcode = IDMAP_ERR_NOTFOUND;
1582c5c4113dSnw141292 			}
1583c5c4113dSnw141292 		}
1584c5c4113dSnw141292 	}
1585c5c4113dSnw141292 
1586c5c4113dSnw141292 out:
1587c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
158862c60062Sbaban 		if (values[4] != NULL)
1589c5c4113dSnw141292 			res->direction =
1590651c0131Sbaban 			    (strtol(values[4], &end, 10) == 0)?
1591651c0131Sbaban 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
1592c5c4113dSnw141292 		else
1593651c0131Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
1594c5c4113dSnw141292 
159562c60062Sbaban 		if (values[3] != NULL) {
1596e8c27ec8Sbaban 			if (req->id2name != NULL)
1597e8c27ec8Sbaban 				free(req->id2name);
15988e228215Sdm199847 			req->id2name = strdup(values[3]);
15998e228215Sdm199847 			if (req->id2name == NULL) {
1600c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1601c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
1602c5c4113dSnw141292 			}
1603c5c4113dSnw141292 		}
1604e8c27ec8Sbaban 
1605e8c27ec8Sbaban 		req->id1.idtype = strncmp(values[5], "0", 2) ?
1606e8c27ec8Sbaban 		    IDMAP_USID : IDMAP_GSID;
160748258c6bSjp151216 
160848258c6bSjp151216 		if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
160948258c6bSjp151216 			res->info.src = IDMAP_MAP_SRC_CACHE;
161048258c6bSjp151216 			res->info.how.map_type = strtoul(values[6], &end, 10);
161148258c6bSjp151216 			switch (res->info.how.map_type) {
161248258c6bSjp151216 			case IDMAP_MAP_TYPE_DS_AD:
161348258c6bSjp151216 				res->info.how.idmap_how_u.ad.dn =
161448258c6bSjp151216 				    strdup(values[7]);
161548258c6bSjp151216 				res->info.how.idmap_how_u.ad.attr =
161648258c6bSjp151216 				    strdup(values[8]);
161748258c6bSjp151216 				res->info.how.idmap_how_u.ad.value =
161848258c6bSjp151216 				    strdup(values[9]);
161948258c6bSjp151216 				break;
162048258c6bSjp151216 
162148258c6bSjp151216 			case IDMAP_MAP_TYPE_DS_NLDAP:
162248258c6bSjp151216 				res->info.how.idmap_how_u.nldap.dn =
162348258c6bSjp151216 				    strdup(values[7]);
162448258c6bSjp151216 				res->info.how.idmap_how_u.nldap.attr =
162548258c6bSjp151216 				    strdup(values[8]);
162648258c6bSjp151216 				res->info.how.idmap_how_u.nldap.value =
162748258c6bSjp151216 				    strdup(values[9]);
162848258c6bSjp151216 				break;
162948258c6bSjp151216 
163048258c6bSjp151216 			case IDMAP_MAP_TYPE_RULE_BASED:
163148258c6bSjp151216 				res->info.how.idmap_how_u.rule.windomain =
163248258c6bSjp151216 				    strdup(values[10]);
163348258c6bSjp151216 				res->info.how.idmap_how_u.rule.winname =
163448258c6bSjp151216 				    strdup(values[11]);
163548258c6bSjp151216 				res->info.how.idmap_how_u.rule.unixname =
163648258c6bSjp151216 				    strdup(values[12]);
163748258c6bSjp151216 				res->info.how.idmap_how_u.rule.is_nt4 =
163848258c6bSjp151216 				    strtoul(values[13], &end, 1);
163948258c6bSjp151216 				res->info.how.idmap_how_u.rule.is_user =
164048258c6bSjp151216 				    is_user;
164148258c6bSjp151216 				res->info.how.idmap_how_u.rule.is_wuser =
164248258c6bSjp151216 				    strtoul(values[5], &end, 1);
164348258c6bSjp151216 				break;
164448258c6bSjp151216 
164548258c6bSjp151216 			case IDMAP_MAP_TYPE_EPHEMERAL:
164648258c6bSjp151216 				break;
164748258c6bSjp151216 
164848258c6bSjp151216 			case IDMAP_MAP_TYPE_LOCAL_SID:
164948258c6bSjp151216 				break;
165048258c6bSjp151216 
165148258c6bSjp151216 			case IDMAP_MAP_TYPE_KNOWN_SID:
165248258c6bSjp151216 				break;
165348258c6bSjp151216 
165448258c6bSjp151216 			default:
165548258c6bSjp151216 				/* Unknow mapping type */
165648258c6bSjp151216 				assert(FALSE);
165748258c6bSjp151216 			}
165848258c6bSjp151216 		}
1659c5c4113dSnw141292 	}
166062c60062Sbaban 	if (vm != NULL)
1661c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
1662c5c4113dSnw141292 	return (retcode);
1663c5c4113dSnw141292 }
1664c5c4113dSnw141292 
1665cd37da74Snw141292 static
1666cd37da74Snw141292 idmap_retcode
166762c60062Sbaban lookup_cache_sid2name(sqlite *cache, const char *sidprefix, idmap_rid_t rid,
1668cd37da74Snw141292 		char **name, char **domain, int *type)
1669cd37da74Snw141292 {
1670c5c4113dSnw141292 	char		*end;
1671c5c4113dSnw141292 	char		*sql = NULL;
1672c5c4113dSnw141292 	const char	**values;
1673c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
1674c5c4113dSnw141292 	int		ncol;
1675c5c4113dSnw141292 	time_t		curtime;
1676c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
1677c5c4113dSnw141292 
1678c5c4113dSnw141292 	/* Get current time */
1679c5c4113dSnw141292 	errno = 0;
1680c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
1681cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
1682c5c4113dSnw141292 		    strerror(errno));
1683c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
1684c5c4113dSnw141292 		goto out;
1685c5c4113dSnw141292 	}
1686c5c4113dSnw141292 
1687c5c4113dSnw141292 	/* SQL to lookup the cache */
1688cd37da74Snw141292 	sql = sqlite_mprintf("SELECT canon_name, domain, type "
1689cd37da74Snw141292 	    "FROM name_cache WHERE "
1690c5c4113dSnw141292 	    "sidprefix = %Q AND rid = %u AND "
1691c5c4113dSnw141292 	    "(expiration = 0 OR expiration ISNULL OR "
1692c5c4113dSnw141292 	    "expiration > %d);",
1693c5c4113dSnw141292 	    sidprefix, rid, curtime);
1694c5c4113dSnw141292 	if (sql == NULL) {
1695c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
1696c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
1697c5c4113dSnw141292 		goto out;
1698c5c4113dSnw141292 	}
1699c5c4113dSnw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 3, &values);
1700c5c4113dSnw141292 	sqlite_freemem(sql);
1701c5c4113dSnw141292 
1702c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
170362c60062Sbaban 		if (type != NULL) {
1704c5c4113dSnw141292 			if (values[2] == NULL) {
1705c5c4113dSnw141292 				retcode = IDMAP_ERR_CACHE;
1706c5c4113dSnw141292 				goto out;
1707c5c4113dSnw141292 			}
1708c5c4113dSnw141292 			*type = strtol(values[2], &end, 10);
1709c5c4113dSnw141292 		}
1710c5c4113dSnw141292 
171162c60062Sbaban 		if (name != NULL && values[0] != NULL) {
1712c5c4113dSnw141292 			if ((*name = strdup(values[0])) == NULL) {
1713c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1714c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
1715c5c4113dSnw141292 				goto out;
1716c5c4113dSnw141292 			}
1717c5c4113dSnw141292 		}
1718c5c4113dSnw141292 
171962c60062Sbaban 		if (domain != NULL && values[1] != NULL) {
1720c5c4113dSnw141292 			if ((*domain = strdup(values[1])) == NULL) {
172162c60062Sbaban 				if (name != NULL && *name) {
1722c5c4113dSnw141292 					free(*name);
1723c5c4113dSnw141292 					*name = NULL;
1724c5c4113dSnw141292 				}
1725c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1726c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
1727c5c4113dSnw141292 				goto out;
1728c5c4113dSnw141292 			}
1729c5c4113dSnw141292 		}
1730c5c4113dSnw141292 	}
1731c5c4113dSnw141292 
1732c5c4113dSnw141292 out:
173362c60062Sbaban 	if (vm != NULL)
1734c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
1735c5c4113dSnw141292 	return (retcode);
1736c5c4113dSnw141292 }
1737c5c4113dSnw141292 
1738c5c4113dSnw141292 /*
1739e8c27ec8Sbaban  * Given SID, find winname using name_cache OR
1740e8c27ec8Sbaban  * Given winname, find SID using name_cache.
1741e8c27ec8Sbaban  * Used when mapping win to unix i.e. req->id1 is windows id and
1742e8c27ec8Sbaban  * req->id2 is unix id
1743c5c4113dSnw141292  */
1744cd37da74Snw141292 static
1745cd37da74Snw141292 idmap_retcode
1746e8c27ec8Sbaban lookup_name_cache(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
1747cd37da74Snw141292 {
1748c5c4113dSnw141292 	int		type = -1;
1749c5c4113dSnw141292 	idmap_retcode	retcode;
1750e8c27ec8Sbaban 	char		*sidprefix = NULL;
1751c5c4113dSnw141292 	idmap_rid_t	rid;
1752c5c4113dSnw141292 	char		*name = NULL, *domain = NULL;
1753c5c4113dSnw141292 
1754e8c27ec8Sbaban 	/* Done if we've both sid and winname */
1755e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL && req->id1name != NULL)
1756e8c27ec8Sbaban 		return (IDMAP_SUCCESS);
1757c5c4113dSnw141292 
1758e8c27ec8Sbaban 	/* Lookup sid to winname */
1759e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
1760e8c27ec8Sbaban 		retcode = lookup_cache_sid2name(cache,
1761e8c27ec8Sbaban 		    req->id1.idmap_id_u.sid.prefix,
1762e8c27ec8Sbaban 		    req->id1.idmap_id_u.sid.rid, &name, &domain, &type);
176362c60062Sbaban 		goto out;
1764e8c27ec8Sbaban 	}
176562c60062Sbaban 
1766e8c27ec8Sbaban 	/* Lookup winame to sid */
1767e8c27ec8Sbaban 	retcode = lookup_cache_name2sid(cache, req->id1name, req->id1domain,
1768e8c27ec8Sbaban 	    &name, &sidprefix, &rid, &type);
1769c5c4113dSnw141292 
177062c60062Sbaban out:
1771e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
1772c5c4113dSnw141292 		free(name);
1773c5c4113dSnw141292 		free(domain);
1774e8c27ec8Sbaban 		free(sidprefix);
1775e8c27ec8Sbaban 		return (retcode);
1776e8c27ec8Sbaban 	}
1777e8c27ec8Sbaban 
1778e8c27ec8Sbaban 	if (res->id.idtype == IDMAP_POSIXID) {
1779e8c27ec8Sbaban 		res->id.idtype = (type == _IDMAP_T_USER) ?
1780e8c27ec8Sbaban 		    IDMAP_UID : IDMAP_GID;
1781e8c27ec8Sbaban 	}
1782e8c27ec8Sbaban 	req->id1.idtype = (type == _IDMAP_T_USER) ?
1783e8c27ec8Sbaban 	    IDMAP_USID : IDMAP_GSID;
1784e8c27ec8Sbaban 
1785e8c27ec8Sbaban 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
1786e8c27ec8Sbaban 	if (name != NULL) {
1787e8c27ec8Sbaban 		free(req->id1name);	/* Free existing winname */
1788e8c27ec8Sbaban 		req->id1name = name;	/* and use canonical name instead */
1789e8c27ec8Sbaban 	}
1790e8c27ec8Sbaban 	if (req->id1domain == NULL)
1791e8c27ec8Sbaban 		req->id1domain = domain;
1792e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix == NULL) {
1793e8c27ec8Sbaban 		req->id1.idmap_id_u.sid.prefix = sidprefix;
1794e8c27ec8Sbaban 		req->id1.idmap_id_u.sid.rid = rid;
1795c5c4113dSnw141292 	}
1796c5c4113dSnw141292 	return (retcode);
1797c5c4113dSnw141292 }
1798c5c4113dSnw141292 
1799e8c27ec8Sbaban /*
1800e8c27ec8Sbaban  * Batch AD lookups
1801e8c27ec8Sbaban  */
1802c5c4113dSnw141292 idmap_retcode
1803e8c27ec8Sbaban ad_lookup_batch(lookup_state_t *state, idmap_mapping_batch *batch,
1804cd37da74Snw141292 		idmap_ids_res *result)
1805cd37da74Snw141292 {
1806c5c4113dSnw141292 	idmap_retcode	retcode;
1807e8c27ec8Sbaban 	int		i, add, type, is_wuser, is_user;
1808e8c27ec8Sbaban 	int		retries = 0, eunixtype;
1809e8c27ec8Sbaban 	char		**unixname;
1810c5c4113dSnw141292 	idmap_mapping	*req;
1811c5c4113dSnw141292 	idmap_id_res	*res;
1812e8c27ec8Sbaban 	idmap_query_state_t	*qs = NULL;
181348258c6bSjp151216 	idmap_how	*how;
1814479ac375Sdm199847 	char		**dn, **attr, **value;
1815e8c27ec8Sbaban 
1816e8c27ec8Sbaban 	/*
1817e8c27ec8Sbaban 	 * Since req->id2.idtype is unused, we will use it here
1818e8c27ec8Sbaban 	 * to retrieve the value of sid_type. But it needs to be
1819e8c27ec8Sbaban 	 * reset to IDMAP_NONE before we return to prevent xdr
1820e8c27ec8Sbaban 	 * from mis-interpreting req->id2 when it tries to free
1821e8c27ec8Sbaban 	 * the input argument. Other option is to allocate an
1822e8c27ec8Sbaban 	 * array of integers and use it instead for the batched
1823e8c27ec8Sbaban 	 * call. But why un-necessarily allocate memory. That may
1824e8c27ec8Sbaban 	 * be an option if req->id2.idtype cannot be re-used in
1825e8c27ec8Sbaban 	 * future.
1826e8c27ec8Sbaban 	 */
1827c5c4113dSnw141292 
1828c5c4113dSnw141292 	if (state->ad_nqueries == 0)
1829c5c4113dSnw141292 		return (IDMAP_SUCCESS);
1830c5c4113dSnw141292 
1831*96c3a9a0Sbaban 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
1832*96c3a9a0Sbaban 		req = &batch->idmap_mapping_batch_val[i];
1833*96c3a9a0Sbaban 		res = &result->ids.ids_val[i];
1834*96c3a9a0Sbaban 
1835*96c3a9a0Sbaban 		/* Skip if not marked for AD lookup or already in error. */
1836*96c3a9a0Sbaban 		if (!(req->direction & _IDMAP_F_LOOKUP_AD) ||
1837*96c3a9a0Sbaban 		    res->retcode != IDMAP_SUCCESS)
1838*96c3a9a0Sbaban 			continue;
1839*96c3a9a0Sbaban 
1840*96c3a9a0Sbaban 		/* Init status */
1841*96c3a9a0Sbaban 		res->retcode = IDMAP_ERR_RETRIABLE_NET_ERR;
1842*96c3a9a0Sbaban 	}
1843*96c3a9a0Sbaban 
1844c5c4113dSnw141292 retry:
1845e8c27ec8Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, state->ad_nqueries,
1846e8c27ec8Sbaban 	    &qs);
1847e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
18480dcc7149Snw141292 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
18490dcc7149Snw141292 			goto retry;
1850349d5d8fSnw141292 		degrade_svc(1, "failed to create batch for AD lookup");
1851e8c27ec8Sbaban 		goto out;
1852c5c4113dSnw141292 	}
1853c5c4113dSnw141292 
1854c8e26105Sjp151216 	restore_svc();
1855c8e26105Sjp151216 
1856e8c27ec8Sbaban 	idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
1857e8c27ec8Sbaban 	    state->ad_unixgroup_attr);
1858e8c27ec8Sbaban 
1859e8c27ec8Sbaban 	for (i = 0, add = 0; i < batch->idmap_mapping_batch_len; i++) {
1860c5c4113dSnw141292 		req = &batch->idmap_mapping_batch_val[i];
1861c5c4113dSnw141292 		res = &result->ids.ids_val[i];
186248258c6bSjp151216 		how = &res->info.how;
186348258c6bSjp151216 
1864e8c27ec8Sbaban 		retcode = IDMAP_SUCCESS;
1865e8c27ec8Sbaban 		req->id2.idtype = IDMAP_NONE;
1866c5c4113dSnw141292 
1867e8c27ec8Sbaban 		/* Skip if not marked for AD lookup */
1868e8c27ec8Sbaban 		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
1869e8c27ec8Sbaban 			continue;
1870e8c27ec8Sbaban 
1871*96c3a9a0Sbaban 		if (res->retcode != IDMAP_ERR_RETRIABLE_NET_ERR)
1872c5c4113dSnw141292 			continue;
1873e8c27ec8Sbaban 
1874e8c27ec8Sbaban 		if (IS_REQUEST_SID(*req, 1)) {
1875e8c27ec8Sbaban 
1876479ac375Sdm199847 			/* win2unix request: */
1877e8c27ec8Sbaban 
1878479ac375Sdm199847 			unixname = dn = attr = value = NULL;
1879e8c27ec8Sbaban 			eunixtype = _IDMAP_T_UNDEF;
1880e8c27ec8Sbaban 			if (req->id2name == NULL) {
1881e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_UID &&
1882e8c27ec8Sbaban 				    AD_OR_MIXED(state->nm_siduid)) {
1883e8c27ec8Sbaban 					eunixtype = _IDMAP_T_USER;
1884e8c27ec8Sbaban 					unixname = &req->id2name;
1885e8c27ec8Sbaban 				} else if (res->id.idtype == IDMAP_GID &&
1886e8c27ec8Sbaban 				    AD_OR_MIXED(state->nm_sidgid)) {
1887e8c27ec8Sbaban 					eunixtype = _IDMAP_T_GROUP;
1888e8c27ec8Sbaban 					unixname = &req->id2name;
1889e8c27ec8Sbaban 				} else if (AD_OR_MIXED(state->nm_siduid) ||
1890e8c27ec8Sbaban 				    AD_OR_MIXED(state->nm_sidgid)) {
1891e8c27ec8Sbaban 					unixname = &req->id2name;
1892e8c27ec8Sbaban 				}
1893e8c27ec8Sbaban 			}
1894e8c27ec8Sbaban 			add = 1;
1895479ac375Sdm199847 			if (unixname != NULL) {
1896479ac375Sdm199847 				/*
1897479ac375Sdm199847 				 * Get how info for DS-based name
1898479ac375Sdm199847 				 * mapping only if AD or MIXED
1899479ac375Sdm199847 				 * mode is enabled.
1900479ac375Sdm199847 				 */
1901479ac375Sdm199847 				idmap_info_free(&res->info);
190248258c6bSjp151216 				res->info.src = IDMAP_MAP_SRC_NEW;
190348258c6bSjp151216 				how->map_type = IDMAP_MAP_TYPE_DS_AD;
1904479ac375Sdm199847 				dn = &how->idmap_how_u.ad.dn;
1905479ac375Sdm199847 				attr = &how->idmap_how_u.ad.attr;
1906479ac375Sdm199847 				value = &how->idmap_how_u.ad.value;
1907479ac375Sdm199847 			}
1908479ac375Sdm199847 			if (req->id1.idmap_id_u.sid.prefix != NULL) {
1909479ac375Sdm199847 				/* Lookup AD by SID */
1910c5c4113dSnw141292 				retcode = idmap_sid2name_batch_add1(
1911e8c27ec8Sbaban 				    qs, req->id1.idmap_id_u.sid.prefix,
1912e8c27ec8Sbaban 				    &req->id1.idmap_id_u.sid.rid, eunixtype,
1913479ac375Sdm199847 				    dn, attr, value,
1914479ac375Sdm199847 				    (req->id1name == NULL) ?
1915479ac375Sdm199847 				    &req->id1name : NULL,
1916479ac375Sdm199847 				    (req->id1domain == NULL) ?
1917479ac375Sdm199847 				    &req->id1domain : NULL,
1918479ac375Sdm199847 				    (int *)&req->id2.idtype, unixname,
1919479ac375Sdm199847 				    &res->retcode);
1920479ac375Sdm199847 			} else {
1921479ac375Sdm199847 				/* Lookup AD by winname */
1922479ac375Sdm199847 				assert(req->id1name != NULL);
1923479ac375Sdm199847 				retcode = idmap_name2sid_batch_add1(
1924479ac375Sdm199847 				    qs, req->id1name, req->id1domain,
1925479ac375Sdm199847 				    eunixtype,
1926479ac375Sdm199847 				    dn, attr, value,
1927479ac375Sdm199847 				    &req->id1name,
1928479ac375Sdm199847 				    &req->id1.idmap_id_u.sid.prefix,
1929479ac375Sdm199847 				    &req->id1.idmap_id_u.sid.rid,
1930479ac375Sdm199847 				    (int *)&req->id2.idtype, unixname,
1931479ac375Sdm199847 				    &res->retcode);
1932479ac375Sdm199847 			}
1933c5c4113dSnw141292 
1934e8c27ec8Sbaban 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
1935479ac375Sdm199847 
1936479ac375Sdm199847 			/* unix2win request: */
1937e8c27ec8Sbaban 
1938e8c27ec8Sbaban 			if (res->id.idmap_id_u.sid.prefix != NULL &&
1939e8c27ec8Sbaban 			    req->id2name != NULL) {
1940e8c27ec8Sbaban 				/* Already have SID and winname -- done */
1941e8c27ec8Sbaban 				res->retcode = IDMAP_SUCCESS;
1942e8c27ec8Sbaban 				continue;
1943c5c4113dSnw141292 			}
1944c5c4113dSnw141292 
1945e8c27ec8Sbaban 			if (res->id.idmap_id_u.sid.prefix != NULL) {
1946cd37da74Snw141292 				/*
1947e8c27ec8Sbaban 				 * SID but no winname -- lookup AD by
1948e8c27ec8Sbaban 				 * SID to get winname.
1949479ac375Sdm199847 				 * how info is not needed here because
1950479ac375Sdm199847 				 * we are not retrieving unixname from
1951479ac375Sdm199847 				 * AD.
1952cd37da74Snw141292 				 */
1953e8c27ec8Sbaban 				add = 1;
1954e8c27ec8Sbaban 				retcode = idmap_sid2name_batch_add1(
1955e8c27ec8Sbaban 				    qs, res->id.idmap_id_u.sid.prefix,
1956e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.rid,
195748258c6bSjp151216 				    _IDMAP_T_UNDEF,
1958479ac375Sdm199847 				    NULL, NULL, NULL,
195948258c6bSjp151216 				    &req->id2name,
1960e8c27ec8Sbaban 				    &req->id2domain, (int *)&req->id2.idtype,
1961e8c27ec8Sbaban 				    NULL, &res->retcode);
1962e8c27ec8Sbaban 			} else if (req->id2name != NULL) {
1963e8c27ec8Sbaban 				/*
1964e8c27ec8Sbaban 				 * winname but no SID -- lookup AD by
1965e8c27ec8Sbaban 				 * winname to get SID.
1966479ac375Sdm199847 				 * how info is not needed here because
1967479ac375Sdm199847 				 * we are not retrieving unixname from
1968479ac375Sdm199847 				 * AD.
1969e8c27ec8Sbaban 				 */
1970e8c27ec8Sbaban 				add = 1;
1971e8c27ec8Sbaban 				retcode = idmap_name2sid_batch_add1(
1972e8c27ec8Sbaban 				    qs, req->id2name, req->id2domain,
197348258c6bSjp151216 				    _IDMAP_T_UNDEF,
1974479ac375Sdm199847 				    NULL, NULL, NULL, NULL,
1975e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.prefix,
1976e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.rid,
1977e8c27ec8Sbaban 				    (int *)&req->id2.idtype, NULL,
1978e8c27ec8Sbaban 				    &res->retcode);
1979e8c27ec8Sbaban 			} else if (req->id1name != NULL) {
1980e8c27ec8Sbaban 				/*
1981e8c27ec8Sbaban 				 * No SID and no winname but we've unixname --
1982e8c27ec8Sbaban 				 * lookup AD by unixname to get SID.
1983e8c27ec8Sbaban 				 */
1984e8c27ec8Sbaban 				is_user = (IS_REQUEST_UID(*req)) ? 1 : 0;
1985e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_USID)
1986e8c27ec8Sbaban 					is_wuser = 1;
1987e8c27ec8Sbaban 				else if (res->id.idtype == IDMAP_GSID)
1988e8c27ec8Sbaban 					is_wuser = 0;
1989e8c27ec8Sbaban 				else
1990e8c27ec8Sbaban 					is_wuser = is_user;
1991e8c27ec8Sbaban 				add = 1;
1992479ac375Sdm199847 				idmap_info_free(&res->info);
199348258c6bSjp151216 				res->info.src = IDMAP_MAP_SRC_NEW;
199448258c6bSjp151216 				how->map_type = IDMAP_MAP_TYPE_DS_AD;
1995e8c27ec8Sbaban 				retcode = idmap_unixname2sid_batch_add1(
1996e8c27ec8Sbaban 				    qs, req->id1name, is_user, is_wuser,
199748258c6bSjp151216 				    &how->idmap_how_u.ad.dn,
199848258c6bSjp151216 				    &how->idmap_how_u.ad.attr,
199948258c6bSjp151216 				    &how->idmap_how_u.ad.value,
2000e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.prefix,
2001e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.rid,
2002e8c27ec8Sbaban 				    &req->id2name, &req->id2domain,
2003e8c27ec8Sbaban 				    (int *)&req->id2.idtype, &res->retcode);
2004e8c27ec8Sbaban 			}
2005e8c27ec8Sbaban 		}
2006e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS) {
2007e8c27ec8Sbaban 			idmap_lookup_release_batch(&qs);
2008e8c27ec8Sbaban 			break;
2009e8c27ec8Sbaban 		}
2010cd37da74Snw141292 	}
2011cd37da74Snw141292 
2012*96c3a9a0Sbaban 	if (retcode == IDMAP_SUCCESS) {
2013*96c3a9a0Sbaban 		/* add keeps track if we added an entry to the batch */
2014*96c3a9a0Sbaban 		if (add)
20150dcc7149Snw141292 			retcode = idmap_lookup_batch_end(&qs);
2016*96c3a9a0Sbaban 		else
2017*96c3a9a0Sbaban 			idmap_lookup_release_batch(&qs);
2018*96c3a9a0Sbaban 	}
2019cd37da74Snw141292 
2020c5c4113dSnw141292 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
2021c5c4113dSnw141292 		goto retry;
2022c8e26105Sjp151216 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
2023349d5d8fSnw141292 		degrade_svc(1, "some AD lookups timed out repeatedly");
2024c5c4113dSnw141292 
2025e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
2026e8c27ec8Sbaban 		idmapdlog(LOG_NOTICE, "Failed to batch AD lookup requests");
2027c5c4113dSnw141292 
2028c5c4113dSnw141292 out:
2029e8c27ec8Sbaban 	/*
2030e8c27ec8Sbaban 	 * This loop does the following:
2031479ac375Sdm199847 	 * 1. Reset _IDMAP_F_LOOKUP_AD flag from the request.
2032479ac375Sdm199847 	 * 2. Reset req->id2.idtype to IDMAP_NONE
2033479ac375Sdm199847 	 * 3. If batch_start or batch_add failed then set the status
2034479ac375Sdm199847 	 *    of each request marked for AD lookup to that error.
2035479ac375Sdm199847 	 * 4. Evaluate the type of the AD object (i.e. user or group) and
2036479ac375Sdm199847 	 *    update the idtype in request.
2037e8c27ec8Sbaban 	 */
2038e8c27ec8Sbaban 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
2039e8c27ec8Sbaban 		req = &batch->idmap_mapping_batch_val[i];
2040e8c27ec8Sbaban 		type = req->id2.idtype;
2041e8c27ec8Sbaban 		req->id2.idtype = IDMAP_NONE;
20425e0794bcSbaban 		res = &result->ids.ids_val[i];
204348258c6bSjp151216 		how = &res->info.how;
2044e8c27ec8Sbaban 		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
2045e8c27ec8Sbaban 			continue;
2046e8c27ec8Sbaban 
2047479ac375Sdm199847 		/* Reset AD lookup flag */
2048479ac375Sdm199847 		req->direction &= ~(_IDMAP_F_LOOKUP_AD);
2049479ac375Sdm199847 
2050479ac375Sdm199847 		/*
2051479ac375Sdm199847 		 * If batch_start or batch_add failed then set the status
2052479ac375Sdm199847 		 * of each request marked for AD lookup to that error.
2053479ac375Sdm199847 		 */
2054e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS) {
2055e8c27ec8Sbaban 			res->retcode = retcode;
2056e8c27ec8Sbaban 			continue;
2057e8c27ec8Sbaban 		}
2058e8c27ec8Sbaban 
2059e8c27ec8Sbaban 		if (!add)
2060e8c27ec8Sbaban 			continue;
2061e8c27ec8Sbaban 
206248258c6bSjp151216 		if (res->retcode == IDMAP_ERR_NOTFOUND) {
206348258c6bSjp151216 			/* Nothing found - remove the preset info */
2064479ac375Sdm199847 			idmap_info_free(&res->info);
206548258c6bSjp151216 		}
206648258c6bSjp151216 
2067e8c27ec8Sbaban 		if (IS_REQUEST_SID(*req, 1)) {
2068e8c27ec8Sbaban 			if (res->retcode != IDMAP_SUCCESS)
2069e8c27ec8Sbaban 				continue;
2070479ac375Sdm199847 			/* Evaluate result type */
2071e8c27ec8Sbaban 			switch (type) {
2072e8c27ec8Sbaban 			case _IDMAP_T_USER:
2073e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
2074e8c27ec8Sbaban 					res->id.idtype = IDMAP_UID;
2075e8c27ec8Sbaban 				req->id1.idtype = IDMAP_USID;
2076e8c27ec8Sbaban 				break;
2077e8c27ec8Sbaban 			case _IDMAP_T_GROUP:
2078e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
2079e8c27ec8Sbaban 					res->id.idtype = IDMAP_GID;
2080e8c27ec8Sbaban 				req->id1.idtype = IDMAP_GSID;
2081e8c27ec8Sbaban 				break;
2082e8c27ec8Sbaban 			default:
2083e8c27ec8Sbaban 				res->retcode = IDMAP_ERR_SID;
2084e8c27ec8Sbaban 				break;
2085e8c27ec8Sbaban 			}
2086479ac375Sdm199847 			if (res->retcode == IDMAP_SUCCESS &&
2087479ac375Sdm199847 			    req->id1name != NULL &&
2088479ac375Sdm199847 			    (req->id2name == NULL ||
2089479ac375Sdm199847 			    res->id.idmap_id_u.uid == SENTINEL_PID) &&
2090479ac375Sdm199847 			    NLDAP_MODE(res->id.idtype, state)) {
2091479ac375Sdm199847 				req->direction |= _IDMAP_F_LOOKUP_NLDAP;
2092479ac375Sdm199847 				state->nldap_nqueries++;
2093479ac375Sdm199847 			}
2094e8c27ec8Sbaban 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
2095e8c27ec8Sbaban 			if (res->retcode != IDMAP_SUCCESS) {
2096e8c27ec8Sbaban 				if ((!(IDMAP_FATAL_ERROR(res->retcode))) &&
2097e8c27ec8Sbaban 				    res->id.idmap_id_u.sid.prefix == NULL &&
2098e8c27ec8Sbaban 				    req->id2name == NULL && /* no winname */
2099e8c27ec8Sbaban 				    req->id1name != NULL) /* unixname */
2100e8c27ec8Sbaban 					/*
2101479ac375Sdm199847 					 * If AD lookup by unixname failed
2102479ac375Sdm199847 					 * with non fatal error then clear
2103479ac375Sdm199847 					 * the error (i.e set res->retcode
2104479ac375Sdm199847 					 * to success). This allows the next
2105479ac375Sdm199847 					 * pass to process other mapping
2106479ac375Sdm199847 					 * mechanisms for this request.
2107e8c27ec8Sbaban 					 */
2108e8c27ec8Sbaban 					res->retcode = IDMAP_SUCCESS;
2109e8c27ec8Sbaban 				continue;
2110e8c27ec8Sbaban 			}
2111479ac375Sdm199847 			/* Evaluate result type */
2112e8c27ec8Sbaban 			switch (type) {
2113e8c27ec8Sbaban 			case _IDMAP_T_USER:
2114e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_SID)
2115e8c27ec8Sbaban 					res->id.idtype = IDMAP_USID;
2116e8c27ec8Sbaban 				break;
2117e8c27ec8Sbaban 			case _IDMAP_T_GROUP:
2118e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_SID)
2119e8c27ec8Sbaban 					res->id.idtype = IDMAP_GSID;
2120e8c27ec8Sbaban 				break;
2121e8c27ec8Sbaban 			default:
2122e8c27ec8Sbaban 				res->retcode = IDMAP_ERR_SID;
2123e8c27ec8Sbaban 				break;
2124e8c27ec8Sbaban 			}
2125e8c27ec8Sbaban 		}
2126e8c27ec8Sbaban 	}
2127e8c27ec8Sbaban 
2128e8c27ec8Sbaban 	/* AD lookups done. Reset state->ad_nqueries and return */
2129e8c27ec8Sbaban 	state->ad_nqueries = 0;
2130c5c4113dSnw141292 	return (retcode);
2131c5c4113dSnw141292 }
2132c5c4113dSnw141292 
2133cd37da74Snw141292 /*
2134cd37da74Snw141292  * Convention when processing win2unix requests:
2135cd37da74Snw141292  *
2136cd37da74Snw141292  * Windows identity:
2137cd37da74Snw141292  * req->id1name =
2138cd37da74Snw141292  *              winname if given otherwise winname found will be placed
2139cd37da74Snw141292  *              here.
2140cd37da74Snw141292  * req->id1domain =
2141cd37da74Snw141292  *              windomain if given otherwise windomain found will be
2142cd37da74Snw141292  *              placed here.
2143cd37da74Snw141292  * req->id1.idtype =
2144cd37da74Snw141292  *              Either IDMAP_SID/USID/GSID. If this is IDMAP_SID then it'll
2145cd37da74Snw141292  *              be set to IDMAP_USID/GSID depending upon whether the
2146cd37da74Snw141292  *              given SID is user or group respectively. The user/group-ness
2147cd37da74Snw141292  *              is determined either when looking up well-known SIDs table OR
2148479ac375Sdm199847  *              if the SID is found in namecache OR by ad_lookup_one() OR by
2149cd37da74Snw141292  *              ad_lookup_batch().
2150cd37da74Snw141292  * req->id1..sid.[prefix, rid] =
2151cd37da74Snw141292  *              SID if given otherwise SID found will be placed here.
2152cd37da74Snw141292  *
2153cd37da74Snw141292  * Unix identity:
2154cd37da74Snw141292  * req->id2name =
2155cd37da74Snw141292  *              unixname found will be placed here.
2156cd37da74Snw141292  * req->id2domain =
2157cd37da74Snw141292  *              NOT USED
2158cd37da74Snw141292  * res->id.idtype =
2159cd37da74Snw141292  *              Target type initialized from req->id2.idtype. If
2160cd37da74Snw141292  *              it is IDMAP_POSIXID then actual type (IDMAP_UID/GID) found
2161cd37da74Snw141292  *              will be placed here.
2162cd37da74Snw141292  * res->id..[uid or gid] =
2163cd37da74Snw141292  *              UID/GID found will be placed here.
2164cd37da74Snw141292  *
2165cd37da74Snw141292  * Others:
2166cd37da74Snw141292  * res->retcode =
2167cd37da74Snw141292  *              Return status for this request will be placed here.
2168cd37da74Snw141292  * res->direction =
2169cd37da74Snw141292  *              Direction found will be placed here. Direction
2170cd37da74Snw141292  *              meaning whether the resultant mapping is valid
2171cd37da74Snw141292  *              only from win2unix or bi-directional.
2172cd37da74Snw141292  * req->direction =
2173cd37da74Snw141292  *              INTERNAL USE. Used by idmapd to set various
2174cd37da74Snw141292  *              flags (_IDMAP_F_xxxx) to aid in processing
2175cd37da74Snw141292  *              of the request.
2176cd37da74Snw141292  * req->id2.idtype =
2177cd37da74Snw141292  *              INTERNAL USE. Initially this is the requested target
2178cd37da74Snw141292  *              type and is used to initialize res->id.idtype.
2179cd37da74Snw141292  *              ad_lookup_batch() uses this field temporarily to store
2180cd37da74Snw141292  *              sid_type obtained by the batched AD lookups and after
2181cd37da74Snw141292  *              use resets it to IDMAP_NONE to prevent xdr from
2182cd37da74Snw141292  *              mis-interpreting the contents of req->id2.
2183cd37da74Snw141292  * req->id2..[uid or gid or sid] =
2184cd37da74Snw141292  *              NOT USED
2185cd37da74Snw141292  */
2186cd37da74Snw141292 
2187cd37da74Snw141292 /*
2188cd37da74Snw141292  * This function does the following:
2189cd37da74Snw141292  * 1. Lookup well-known SIDs table.
2190cd37da74Snw141292  * 2. Check if the given SID is a local-SID and if so extract UID/GID from it.
2191cd37da74Snw141292  * 3. Lookup cache.
2192cd37da74Snw141292  * 4. Check if the client does not want new mapping to be allocated
2193cd37da74Snw141292  *    in which case this pass is the final pass.
2194cd37da74Snw141292  * 5. Set AD lookup flag if it determines that the next stage needs
2195cd37da74Snw141292  *    to do AD lookup.
2196cd37da74Snw141292  */
2197c5c4113dSnw141292 idmap_retcode
2198479ac375Sdm199847 sid2pid_first_pass(lookup_state_t *state, idmap_mapping *req,
2199cd37da74Snw141292 		idmap_id_res *res)
2200cd37da74Snw141292 {
2201c5c4113dSnw141292 	idmap_retcode	retcode;
2202e8c27ec8Sbaban 	int		wksid;
2203c5c4113dSnw141292 
2204e8c27ec8Sbaban 	/* Initialize result */
2205e8c27ec8Sbaban 	res->id.idtype = req->id2.idtype;
2206e8c27ec8Sbaban 	res->id.idmap_id_u.uid = SENTINEL_PID;
2207e8c27ec8Sbaban 	res->direction = IDMAP_DIRECTION_UNDEF;
2208e8c27ec8Sbaban 	wksid = 0;
2209c5c4113dSnw141292 
2210cf5b5989Sdm199847 	if (EMPTY_STRING(req->id1.idmap_id_u.sid.prefix)) {
2211e8c27ec8Sbaban 		if (req->id1name == NULL) {
2212e8c27ec8Sbaban 			retcode = IDMAP_ERR_ARG;
2213c5c4113dSnw141292 			goto out;
2214c5c4113dSnw141292 		}
2215e8c27ec8Sbaban 		/* sanitize sidprefix */
2216e8c27ec8Sbaban 		free(req->id1.idmap_id_u.sid.prefix);
2217e8c27ec8Sbaban 		req->id1.idmap_id_u.sid.prefix = NULL;
2218e8c27ec8Sbaban 	}
2219c5c4113dSnw141292 
2220e8c27ec8Sbaban 	/* Lookup well-known SIDs table */
2221e8c27ec8Sbaban 	retcode = lookup_wksids_sid2pid(req, res, &wksid);
2222c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
2223c5c4113dSnw141292 		goto out;
2224c5c4113dSnw141292 
2225e8c27ec8Sbaban 	/* Check if this is a localsid */
2226e8c27ec8Sbaban 	if (!wksid) {
2227e8c27ec8Sbaban 		retcode = lookup_localsid2pid(req, res);
2228e8c27ec8Sbaban 		if (retcode != IDMAP_ERR_NOTFOUND)
2229e8c27ec8Sbaban 			goto out;
2230e8c27ec8Sbaban 	}
2231e8c27ec8Sbaban 
2232e8c27ec8Sbaban 	/* Lookup cache */
2233479ac375Sdm199847 	retcode = lookup_cache_sid2pid(state->cache, req, res);
2234c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
2235c5c4113dSnw141292 		goto out;
2236c5c4113dSnw141292 
2237c5c4113dSnw141292 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req) || AVOID_NAMESERVICE(req)) {
223848258c6bSjp151216 		retcode = IDMAP_ERR_NONEGENERATED;
2239c5c4113dSnw141292 		goto out;
2240c5c4113dSnw141292 	}
2241c5c4113dSnw141292 
2242c5c4113dSnw141292 	/*
2243e8c27ec8Sbaban 	 * Failed to find non-expired entry in cache. Next step is
2244e8c27ec8Sbaban 	 * to determine if this request needs to be batched for AD lookup.
2245e8c27ec8Sbaban 	 *
2246e8c27ec8Sbaban 	 * At this point we have either sid or winname or both. If we don't
2247e8c27ec8Sbaban 	 * have both then lookup name_cache for the sid or winname
2248e8c27ec8Sbaban 	 * whichever is missing. If not found then this request will be
2249e8c27ec8Sbaban 	 * batched for AD lookup.
2250e8c27ec8Sbaban 	 */
2251479ac375Sdm199847 	retcode = lookup_name_cache(state->cache, req, res);
2252e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS && retcode != IDMAP_ERR_NOTFOUND)
2253e8c27ec8Sbaban 		goto out;
2254e8c27ec8Sbaban 
2255e8c27ec8Sbaban 	/*
2256e8c27ec8Sbaban 	 * Set the flag to indicate that we are not done yet so that
2257e8c27ec8Sbaban 	 * subsequent passes considers this request for name-based
2258e8c27ec8Sbaban 	 * mapping and ephemeral mapping.
2259c5c4113dSnw141292 	 */
2260c5c4113dSnw141292 	state->sid2pid_done = FALSE;
2261e8c27ec8Sbaban 	req->direction |= _IDMAP_F_NOTDONE;
2262c5c4113dSnw141292 
2263c5c4113dSnw141292 	/*
2264e8c27ec8Sbaban 	 * Even if we have both sid and winname, we still may need to batch
2265e8c27ec8Sbaban 	 * this request for AD lookup if we don't have unixname and
2266e8c27ec8Sbaban 	 * directory-based name mapping (AD or mixed) is enabled.
2267e8c27ec8Sbaban 	 * We avoid AD lookup for well-known SIDs because they don't have
2268e8c27ec8Sbaban 	 * regular AD objects.
2269c5c4113dSnw141292 	 */
2270e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS ||
2271e8c27ec8Sbaban 	    (!wksid && req->id2name == NULL &&
2272e8c27ec8Sbaban 	    AD_OR_MIXED_MODE(res->id.idtype, state))) {
2273c5c4113dSnw141292 		retcode = IDMAP_SUCCESS;
2274e8c27ec8Sbaban 		req->direction |= _IDMAP_F_LOOKUP_AD;
2275c5c4113dSnw141292 		state->ad_nqueries++;
2276479ac375Sdm199847 	} else if (NLDAP_MODE(res->id.idtype, state)) {
2277479ac375Sdm199847 		req->direction |= _IDMAP_F_LOOKUP_NLDAP;
2278479ac375Sdm199847 		state->nldap_nqueries++;
2279c5c4113dSnw141292 	}
2280c5c4113dSnw141292 
2281c5c4113dSnw141292 
2282c5c4113dSnw141292 out:
2283c5c4113dSnw141292 	res->retcode = idmap_stat4prot(retcode);
2284e8c27ec8Sbaban 	/*
2285e8c27ec8Sbaban 	 * If we are done and there was an error then set fallback pid
2286e8c27ec8Sbaban 	 * in the result.
2287e8c27ec8Sbaban 	 */
2288e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
2289e8c27ec8Sbaban 		res->id.idmap_id_u.uid = UID_NOBODY;
2290c5c4113dSnw141292 	return (retcode);
2291c5c4113dSnw141292 }
2292c5c4113dSnw141292 
2293c5c4113dSnw141292 /*
2294c5c4113dSnw141292  * Generate SID using the following convention
2295c5c4113dSnw141292  * 	<machine-sid-prefix>-<1000 + uid>
2296c5c4113dSnw141292  * 	<machine-sid-prefix>-<2^31 + gid>
2297c5c4113dSnw141292  */
2298cd37da74Snw141292 static
2299cd37da74Snw141292 idmap_retcode
230048258c6bSjp151216 generate_localsid(idmap_mapping *req, idmap_id_res *res, int is_user,
230148258c6bSjp151216 		int fallback)
2302cd37da74Snw141292 {
2303e8c27ec8Sbaban 	free(res->id.idmap_id_u.sid.prefix);
2304e8c27ec8Sbaban 	res->id.idmap_id_u.sid.prefix = NULL;
2305e8c27ec8Sbaban 
2306e8c27ec8Sbaban 	/*
2307e8c27ec8Sbaban 	 * Diagonal mapping for localSIDs not supported because of the
2308e8c27ec8Sbaban 	 * way we generate localSIDs.
2309e8c27ec8Sbaban 	 */
2310e8c27ec8Sbaban 	if (is_user && res->id.idtype == IDMAP_GSID)
2311e8c27ec8Sbaban 		return (IDMAP_ERR_NOMAPPING);
2312e8c27ec8Sbaban 	if (!is_user && res->id.idtype == IDMAP_USID)
2313e8c27ec8Sbaban 		return (IDMAP_ERR_NOMAPPING);
2314e8c27ec8Sbaban 
2315c5c4113dSnw141292 	/* Skip 1000 UIDs */
2316c5c4113dSnw141292 	if (is_user && req->id1.idmap_id_u.uid >
2317c5c4113dSnw141292 	    (INT32_MAX - LOCALRID_MIN))
231862c60062Sbaban 		return (IDMAP_ERR_NOMAPPING);
2319c5c4113dSnw141292 
2320c5c4113dSnw141292 	RDLOCK_CONFIG();
2321e8c27ec8Sbaban 	/*
2322e8c27ec8Sbaban 	 * machine_sid is never NULL because if it is we won't be here.
2323e8c27ec8Sbaban 	 * No need to assert because stdrup(NULL) will core anyways.
2324e8c27ec8Sbaban 	 */
2325c5c4113dSnw141292 	res->id.idmap_id_u.sid.prefix =
2326c5c4113dSnw141292 	    strdup(_idmapdstate.cfg->pgcfg.machine_sid);
2327c5c4113dSnw141292 	if (res->id.idmap_id_u.sid.prefix == NULL) {
2328c5c4113dSnw141292 		UNLOCK_CONFIG();
2329c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2330c5c4113dSnw141292 		return (IDMAP_ERR_MEMORY);
2331c5c4113dSnw141292 	}
2332c5c4113dSnw141292 	UNLOCK_CONFIG();
2333c5c4113dSnw141292 	res->id.idmap_id_u.sid.rid =
2334c5c4113dSnw141292 	    (is_user) ? req->id1.idmap_id_u.uid + LOCALRID_MIN :
2335c5c4113dSnw141292 	    req->id1.idmap_id_u.gid + INT32_MAX + 1;
2336651c0131Sbaban 	res->direction = IDMAP_DIRECTION_BI;
2337e8c27ec8Sbaban 	if (res->id.idtype == IDMAP_SID)
2338e8c27ec8Sbaban 		res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
2339c5c4113dSnw141292 
234048258c6bSjp151216 	if (!fallback && req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
234148258c6bSjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_LOCAL_SID;
234248258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_ALGORITHMIC;
234348258c6bSjp151216 	}
234448258c6bSjp151216 
2345c5c4113dSnw141292 	/*
2346c5c4113dSnw141292 	 * Don't update name_cache because local sids don't have
2347c5c4113dSnw141292 	 * valid windows names.
2348c5c4113dSnw141292 	 */
2349e8c27ec8Sbaban 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
2350947c7bc0Sbaban 	return (IDMAP_SUCCESS);
2351c5c4113dSnw141292 }
2352c5c4113dSnw141292 
2353cd37da74Snw141292 static
2354cd37da74Snw141292 idmap_retcode
2355cd37da74Snw141292 lookup_localsid2pid(idmap_mapping *req, idmap_id_res *res)
2356cd37da74Snw141292 {
2357c5c4113dSnw141292 	char		*sidprefix;
2358c5c4113dSnw141292 	uint32_t	rid;
2359c5c4113dSnw141292 	int		s;
2360c5c4113dSnw141292 
2361c5c4113dSnw141292 	/*
2362c5c4113dSnw141292 	 * If the sidprefix == localsid then UID = last RID - 1000 or
2363c5c4113dSnw141292 	 * GID = last RID - 2^31.
2364c5c4113dSnw141292 	 */
2365e8c27ec8Sbaban 	if ((sidprefix = req->id1.idmap_id_u.sid.prefix) == NULL)
2366e8c27ec8Sbaban 		/* This means we are looking up by winname */
2367e8c27ec8Sbaban 		return (IDMAP_ERR_NOTFOUND);
2368c5c4113dSnw141292 	rid = req->id1.idmap_id_u.sid.rid;
2369c5c4113dSnw141292 
2370c5c4113dSnw141292 	RDLOCK_CONFIG();
2371c5c4113dSnw141292 	s = (_idmapdstate.cfg->pgcfg.machine_sid) ?
2372cd37da74Snw141292 	    strcasecmp(sidprefix, _idmapdstate.cfg->pgcfg.machine_sid) : 1;
2373c5c4113dSnw141292 	UNLOCK_CONFIG();
2374c5c4113dSnw141292 
2375e8c27ec8Sbaban 	/*
2376e8c27ec8Sbaban 	 * If the given sidprefix does not match machine_sid then this is
2377e8c27ec8Sbaban 	 * not a local SID.
2378e8c27ec8Sbaban 	 */
2379e8c27ec8Sbaban 	if (s != 0)
2380e8c27ec8Sbaban 		return (IDMAP_ERR_NOTFOUND);
2381e8c27ec8Sbaban 
2382e8c27ec8Sbaban 	switch (res->id.idtype) {
2383c5c4113dSnw141292 	case IDMAP_UID:
2384e8c27ec8Sbaban 		if (rid > INT32_MAX || rid < LOCALRID_MIN)
2385e8c27ec8Sbaban 			return (IDMAP_ERR_ARG);
2386c5c4113dSnw141292 		res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
2387c5c4113dSnw141292 		break;
2388c5c4113dSnw141292 	case IDMAP_GID:
2389e8c27ec8Sbaban 		if (rid <= INT32_MAX)
2390e8c27ec8Sbaban 			return (IDMAP_ERR_ARG);
2391c5c4113dSnw141292 		res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
2392c5c4113dSnw141292 		break;
2393c5c4113dSnw141292 	case IDMAP_POSIXID:
2394c5c4113dSnw141292 		if (rid > INT32_MAX) {
2395cd37da74Snw141292 			res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
2396c5c4113dSnw141292 			res->id.idtype = IDMAP_GID;
2397c5c4113dSnw141292 		} else if (rid < LOCALRID_MIN) {
2398e8c27ec8Sbaban 			return (IDMAP_ERR_ARG);
2399c5c4113dSnw141292 		} else {
2400c5c4113dSnw141292 			res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
2401c5c4113dSnw141292 			res->id.idtype = IDMAP_UID;
2402c5c4113dSnw141292 		}
2403c5c4113dSnw141292 		break;
2404c5c4113dSnw141292 	default:
2405c5c4113dSnw141292 		return (IDMAP_ERR_NOTSUPPORTED);
2406c5c4113dSnw141292 	}
240748258c6bSjp151216 	if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
240848258c6bSjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_LOCAL_SID;
240948258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_ALGORITHMIC;
241048258c6bSjp151216 	}
2411c5c4113dSnw141292 	return (IDMAP_SUCCESS);
2412c5c4113dSnw141292 }
2413c5c4113dSnw141292 
2414e8c27ec8Sbaban /*
2415e8c27ec8Sbaban  * Name service lookup by unixname to get pid
2416e8c27ec8Sbaban  */
2417cd37da74Snw141292 static
2418cd37da74Snw141292 idmap_retcode
2419e8c27ec8Sbaban ns_lookup_byname(const char *name, const char *lower_name, idmap_id *id)
2420cd37da74Snw141292 {
2421cd37da74Snw141292 	struct passwd	pwd, *pwdp;
2422cd37da74Snw141292 	struct group	grp, *grpp;
2423c5c4113dSnw141292 	char		buf[1024];
2424c5c4113dSnw141292 	int		errnum;
2425c5c4113dSnw141292 	const char	*me = "ns_lookup_byname";
2426c5c4113dSnw141292 
2427e8c27ec8Sbaban 	switch (id->idtype) {
2428e8c27ec8Sbaban 	case IDMAP_UID:
2429cd37da74Snw141292 		pwdp = getpwnam_r(name, &pwd, buf, sizeof (buf));
2430e8c27ec8Sbaban 		if (pwdp == NULL && errno == 0 && lower_name != NULL &&
2431cd37da74Snw141292 		    name != lower_name && strcmp(name, lower_name) != 0)
2432cd37da74Snw141292 			pwdp = getpwnam_r(lower_name, &pwd, buf, sizeof (buf));
2433cd37da74Snw141292 		if (pwdp == NULL) {
2434c5c4113dSnw141292 			errnum = errno;
2435c5c4113dSnw141292 			idmapdlog(LOG_WARNING,
2436c5c4113dSnw141292 			    "%s: getpwnam_r(%s) failed (%s).",
2437cd37da74Snw141292 			    me, name, errnum ? strerror(errnum) : "not found");
2438c5c4113dSnw141292 			if (errnum == 0)
2439c5c4113dSnw141292 				return (IDMAP_ERR_NOTFOUND);
2440c5c4113dSnw141292 			else
2441c5c4113dSnw141292 				return (IDMAP_ERR_INTERNAL);
2442c5c4113dSnw141292 		}
2443e8c27ec8Sbaban 		id->idmap_id_u.uid = pwd.pw_uid;
2444e8c27ec8Sbaban 		break;
2445e8c27ec8Sbaban 	case IDMAP_GID:
2446cd37da74Snw141292 		grpp = getgrnam_r(name, &grp, buf, sizeof (buf));
2447e8c27ec8Sbaban 		if (grpp == NULL && errno == 0 && lower_name != NULL &&
2448cd37da74Snw141292 		    name != lower_name && strcmp(name, lower_name) != 0)
2449cd37da74Snw141292 			grpp = getgrnam_r(lower_name, &grp, buf, sizeof (buf));
2450cd37da74Snw141292 		if (grpp == NULL) {
2451c5c4113dSnw141292 			errnum = errno;
2452c5c4113dSnw141292 			idmapdlog(LOG_WARNING,
2453c5c4113dSnw141292 			    "%s: getgrnam_r(%s) failed (%s).",
2454cd37da74Snw141292 			    me, name, errnum ? strerror(errnum) : "not found");
2455c5c4113dSnw141292 			if (errnum == 0)
2456c5c4113dSnw141292 				return (IDMAP_ERR_NOTFOUND);
2457c5c4113dSnw141292 			else
2458c5c4113dSnw141292 				return (IDMAP_ERR_INTERNAL);
2459c5c4113dSnw141292 		}
2460e8c27ec8Sbaban 		id->idmap_id_u.gid = grp.gr_gid;
2461e8c27ec8Sbaban 		break;
2462e8c27ec8Sbaban 	default:
2463e8c27ec8Sbaban 		return (IDMAP_ERR_ARG);
2464c5c4113dSnw141292 	}
2465c5c4113dSnw141292 	return (IDMAP_SUCCESS);
2466c5c4113dSnw141292 }
2467c5c4113dSnw141292 
2468e8c27ec8Sbaban 
2469e8c27ec8Sbaban /*
2470e8c27ec8Sbaban  * Name service lookup by pid to get unixname
2471e8c27ec8Sbaban  */
2472e8c27ec8Sbaban static
2473e8c27ec8Sbaban idmap_retcode
2474e8c27ec8Sbaban ns_lookup_bypid(uid_t pid, int is_user, char **unixname)
2475e8c27ec8Sbaban {
2476e8c27ec8Sbaban 	struct passwd	pwd;
2477e8c27ec8Sbaban 	struct group	grp;
2478e8c27ec8Sbaban 	char		buf[1024];
2479e8c27ec8Sbaban 	int		errnum;
2480e8c27ec8Sbaban 	const char	*me = "ns_lookup_bypid";
2481e8c27ec8Sbaban 
2482e8c27ec8Sbaban 	if (is_user) {
2483e8c27ec8Sbaban 		errno = 0;
2484e8c27ec8Sbaban 		if (getpwuid_r(pid, &pwd, buf, sizeof (buf)) == NULL) {
2485e8c27ec8Sbaban 			errnum = errno;
2486e8c27ec8Sbaban 			idmapdlog(LOG_WARNING,
2487e8c27ec8Sbaban 			    "%s: getpwuid_r(%u) failed (%s).",
2488e8c27ec8Sbaban 			    me, pid, errnum ? strerror(errnum) : "not found");
2489e8c27ec8Sbaban 			if (errnum == 0)
2490e8c27ec8Sbaban 				return (IDMAP_ERR_NOTFOUND);
2491e8c27ec8Sbaban 			else
2492e8c27ec8Sbaban 				return (IDMAP_ERR_INTERNAL);
2493e8c27ec8Sbaban 		}
2494e8c27ec8Sbaban 		*unixname = strdup(pwd.pw_name);
2495e8c27ec8Sbaban 	} else {
2496e8c27ec8Sbaban 		errno = 0;
2497e8c27ec8Sbaban 		if (getgrgid_r(pid, &grp, buf, sizeof (buf)) == NULL) {
2498e8c27ec8Sbaban 			errnum = errno;
2499e8c27ec8Sbaban 			idmapdlog(LOG_WARNING,
2500e8c27ec8Sbaban 			    "%s: getgrgid_r(%u) failed (%s).",
2501e8c27ec8Sbaban 			    me, pid, errnum ? strerror(errnum) : "not found");
2502e8c27ec8Sbaban 			if (errnum == 0)
2503e8c27ec8Sbaban 				return (IDMAP_ERR_NOTFOUND);
2504e8c27ec8Sbaban 			else
2505e8c27ec8Sbaban 				return (IDMAP_ERR_INTERNAL);
2506e8c27ec8Sbaban 		}
2507e8c27ec8Sbaban 		*unixname = strdup(grp.gr_name);
2508e8c27ec8Sbaban 	}
2509e8c27ec8Sbaban 	if (*unixname == NULL)
2510e8c27ec8Sbaban 		return (IDMAP_ERR_MEMORY);
2511e8c27ec8Sbaban 	return (IDMAP_SUCCESS);
2512e8c27ec8Sbaban }
2513e8c27ec8Sbaban 
2514c5c4113dSnw141292 /*
2515c5c4113dSnw141292  * Name-based mapping
2516c5c4113dSnw141292  *
2517c5c4113dSnw141292  * Case 1: If no rule matches do ephemeral
2518c5c4113dSnw141292  *
2519c5c4113dSnw141292  * Case 2: If rule matches and unixname is "" then return no mapping.
2520c5c4113dSnw141292  *
2521c5c4113dSnw141292  * Case 3: If rule matches and unixname is specified then lookup name
2522c5c4113dSnw141292  *  service using the unixname. If unixname not found then return no mapping.
2523c5c4113dSnw141292  *
2524c5c4113dSnw141292  * Case 4: If rule matches and unixname is * then lookup name service
2525c5c4113dSnw141292  *  using winname as the unixname. If unixname not found then process
2526c5c4113dSnw141292  *  other rules using the lookup order. If no other rule matches then do
2527c5c4113dSnw141292  *  ephemeral. Otherwise, based on the matched rule do Case 2 or 3 or 4.
2528c5c4113dSnw141292  *  This allows us to specify a fallback unixname per _domain_ or no mapping
2529c5c4113dSnw141292  *  instead of the default behaviour of doing ephemeral mapping.
2530c5c4113dSnw141292  *
2531c5c4113dSnw141292  * Example 1:
2532c5c4113dSnw141292  * *@sfbay == *
2533c5c4113dSnw141292  * If looking up windows users foo@sfbay and foo does not exists in
2534c5c4113dSnw141292  * the name service then foo@sfbay will be mapped to an ephemeral id.
2535c5c4113dSnw141292  *
2536c5c4113dSnw141292  * Example 2:
2537c5c4113dSnw141292  * *@sfbay == *
2538c5c4113dSnw141292  * *@sfbay => guest
2539c5c4113dSnw141292  * If looking up windows users foo@sfbay and foo does not exists in
2540c5c4113dSnw141292  * the name service then foo@sfbay will be mapped to guest.
2541c5c4113dSnw141292  *
2542c5c4113dSnw141292  * Example 3:
2543c5c4113dSnw141292  * *@sfbay == *
2544c5c4113dSnw141292  * *@sfbay => ""
2545c5c4113dSnw141292  * If looking up windows users foo@sfbay and foo does not exists in
2546c5c4113dSnw141292  * the name service then we will return no mapping for foo@sfbay.
2547c5c4113dSnw141292  *
2548c5c4113dSnw141292  */
2549cd37da74Snw141292 static
2550cd37da74Snw141292 idmap_retcode
2551479ac375Sdm199847 name_based_mapping_sid2pid(lookup_state_t *state,
2552479ac375Sdm199847 		idmap_mapping *req, idmap_id_res *res)
2553cd37da74Snw141292 {
2554cd37da74Snw141292 	const char	*unixname, *windomain;
2555cd37da74Snw141292 	char		*sql = NULL, *errmsg = NULL, *lower_winname = NULL;
2556c5c4113dSnw141292 	idmap_retcode	retcode;
2557cd37da74Snw141292 	char		*end, *lower_unixname, *winname;
2558c5c4113dSnw141292 	const char	**values;
2559c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
2560cd37da74Snw141292 	int		ncol, r, i, is_user, is_wuser;
256148258c6bSjp151216 	idmap_namerule	*rule = &res->info.how.idmap_how_u.rule;
256248258c6bSjp151216 	int		direction;
2563c5c4113dSnw141292 	const char	*me = "name_based_mapping_sid2pid";
2564c5c4113dSnw141292 
2565e8c27ec8Sbaban 	assert(req->id1name != NULL); /* We have winname */
2566e8c27ec8Sbaban 	assert(req->id2name == NULL); /* We don't have unixname */
2567e8c27ec8Sbaban 
25688e228215Sdm199847 	winname = req->id1name;
25698e228215Sdm199847 	windomain = req->id1domain;
2570cd37da74Snw141292 
2571cd37da74Snw141292 	switch (req->id1.idtype) {
2572cd37da74Snw141292 	case IDMAP_USID:
2573cd37da74Snw141292 		is_wuser = 1;
2574cd37da74Snw141292 		break;
2575cd37da74Snw141292 	case IDMAP_GSID:
2576cd37da74Snw141292 		is_wuser = 0;
2577cd37da74Snw141292 		break;
2578cd37da74Snw141292 	default:
2579e8c27ec8Sbaban 		idmapdlog(LOG_ERR, "%s: Unable to determine if the "
2580e8c27ec8Sbaban 		    "given Windows id is user or group.", me);
2581cd37da74Snw141292 		return (IDMAP_ERR_INTERNAL);
2582cd37da74Snw141292 	}
2583cd37da74Snw141292 
2584e8c27ec8Sbaban 	switch (res->id.idtype) {
2585cd37da74Snw141292 	case IDMAP_UID:
2586cd37da74Snw141292 		is_user = 1;
2587cd37da74Snw141292 		break;
2588cd37da74Snw141292 	case IDMAP_GID:
2589cd37da74Snw141292 		is_user = 0;
2590cd37da74Snw141292 		break;
2591cd37da74Snw141292 	case IDMAP_POSIXID:
2592cd37da74Snw141292 		is_user = is_wuser;
2593cd37da74Snw141292 		res->id.idtype = is_user ? IDMAP_UID : IDMAP_GID;
2594cd37da74Snw141292 		break;
2595cd37da74Snw141292 	}
2596c5c4113dSnw141292 
2597c5c4113dSnw141292 	i = 0;
2598479ac375Sdm199847 	if (windomain == NULL)
259962c60062Sbaban 		windomain = "";
260082da9f60Sbaban 	else if (state->defdom != NULL &&
260182da9f60Sbaban 	    strcasecmp(state->defdom, windomain) == 0)
2602c5c4113dSnw141292 		i = 1;
2603c5c4113dSnw141292 
2604cd37da74Snw141292 	if ((lower_winname = tolower_u8(winname)) == NULL)
2605cd37da74Snw141292 		lower_winname = winname;    /* hope for the best */
2606c5c4113dSnw141292 	sql = sqlite_mprintf(
260748258c6bSjp151216 	    "SELECT unixname, u2w_order, winname_display, windomain, is_nt4 "
260848258c6bSjp151216 	    "FROM namerules WHERE "
2609cd37da74Snw141292 	    "w2u_order > 0 AND is_user = %d AND is_wuser = %d AND "
2610c5c4113dSnw141292 	    "(winname = %Q OR winname = '*') AND "
2611c5c4113dSnw141292 	    "(windomain = %Q OR windomain = '*' %s) "
2612c5c4113dSnw141292 	    "ORDER BY w2u_order ASC;",
2613cd37da74Snw141292 	    is_user, is_wuser, lower_winname, windomain,
261462c60062Sbaban 	    i ? "OR windomain ISNULL OR windomain = ''" : "");
2615c5c4113dSnw141292 	if (sql == NULL) {
2616c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2617c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
2618c5c4113dSnw141292 		goto out;
2619c5c4113dSnw141292 	}
2620c5c4113dSnw141292 
2621479ac375Sdm199847 	if (sqlite_compile(state->db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
2622c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
2623cd37da74Snw141292 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
2624cd37da74Snw141292 		    CHECK_NULL(errmsg));
2625c5c4113dSnw141292 		sqlite_freemem(errmsg);
2626c5c4113dSnw141292 		goto out;
2627c5c4113dSnw141292 	}
2628c5c4113dSnw141292 
262984decf41Sjp151216 	for (;;) {
2630c5c4113dSnw141292 		r = sqlite_step(vm, &ncol, &values, NULL);
263184decf41Sjp151216 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
2632c5c4113dSnw141292 
263384decf41Sjp151216 		if (r == SQLITE_ROW) {
263448258c6bSjp151216 			if (ncol < 5) {
2635c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
2636c5c4113dSnw141292 				goto out;
2637c5c4113dSnw141292 			}
2638c5c4113dSnw141292 			if (values[0] == NULL) {
2639c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
2640c5c4113dSnw141292 				goto out;
2641c5c4113dSnw141292 			}
2642c5c4113dSnw141292 
264348258c6bSjp151216 			if (values[1] != NULL)
264448258c6bSjp151216 				direction =
264548258c6bSjp151216 				    (strtol(values[1], &end, 10) == 0)?
264648258c6bSjp151216 				    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
264748258c6bSjp151216 			else
264848258c6bSjp151216 				direction = IDMAP_DIRECTION_W2U;
264948258c6bSjp151216 
2650c5c4113dSnw141292 			if (EMPTY_NAME(values[0])) {
265148258c6bSjp151216 				idmap_namerule_set(rule, values[3], values[2],
265248258c6bSjp151216 				    values[0], is_wuser, is_user,
265348258c6bSjp151216 				    strtol(values[4], &end, 10),
265448258c6bSjp151216 				    direction);
2655c5c4113dSnw141292 				retcode = IDMAP_ERR_NOMAPPING;
2656c5c4113dSnw141292 				goto out;
2657c5c4113dSnw141292 			}
265848258c6bSjp151216 
265948258c6bSjp151216 			if (values[0][0] == '*') {
266048258c6bSjp151216 				unixname = winname;
266148258c6bSjp151216 				lower_unixname = lower_winname;
266248258c6bSjp151216 			} else {
266348258c6bSjp151216 				unixname = values[0];
266448258c6bSjp151216 				lower_unixname = NULL;
266548258c6bSjp151216 			}
266648258c6bSjp151216 
2667e8c27ec8Sbaban 			retcode = ns_lookup_byname(unixname, lower_unixname,
2668e8c27ec8Sbaban 			    &res->id);
2669c5c4113dSnw141292 			if (retcode == IDMAP_ERR_NOTFOUND) {
267048258c6bSjp151216 				if (values[0][0] == '*')
2671c5c4113dSnw141292 					/* Case 4 */
2672c5c4113dSnw141292 					continue;
267348258c6bSjp151216 				else {
2674c5c4113dSnw141292 					/* Case 3 */
267548258c6bSjp151216 					idmap_namerule_set(rule, values[3],
267648258c6bSjp151216 					    values[2], values[0], is_wuser,
267748258c6bSjp151216 					    is_user,
267848258c6bSjp151216 					    strtol(values[4], &end, 10),
267948258c6bSjp151216 					    direction);
2680c5c4113dSnw141292 					retcode = IDMAP_ERR_NOMAPPING;
2681c5c4113dSnw141292 				}
268248258c6bSjp151216 			}
2683c5c4113dSnw141292 			goto out;
2684c5c4113dSnw141292 		} else if (r == SQLITE_DONE) {
2685c5c4113dSnw141292 			retcode = IDMAP_ERR_NOTFOUND;
2686c5c4113dSnw141292 			goto out;
2687c5c4113dSnw141292 		} else {
2688c5c4113dSnw141292 			(void) sqlite_finalize(vm, &errmsg);
2689c5c4113dSnw141292 			vm = NULL;
2690cd37da74Snw141292 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
2691cd37da74Snw141292 			    CHECK_NULL(errmsg));
2692c5c4113dSnw141292 			sqlite_freemem(errmsg);
2693c5c4113dSnw141292 			retcode = IDMAP_ERR_INTERNAL;
2694c5c4113dSnw141292 			goto out;
2695c5c4113dSnw141292 		}
2696c5c4113dSnw141292 	}
2697c5c4113dSnw141292 
2698c5c4113dSnw141292 out:
269948258c6bSjp151216 	if (sql != NULL)
2700c5c4113dSnw141292 		sqlite_freemem(sql);
270148258c6bSjp151216 	res->info.how.map_type = IDMAP_MAP_TYPE_RULE_BASED;
2702c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
270362c60062Sbaban 		if (values[1] != NULL)
2704c5c4113dSnw141292 			res->direction =
2705651c0131Sbaban 			    (strtol(values[1], &end, 10) == 0)?
2706651c0131Sbaban 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
2707c5c4113dSnw141292 		else
2708651c0131Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
270948258c6bSjp151216 
27108e228215Sdm199847 		req->id2name = strdup(unixname);
2711479ac375Sdm199847 		if (req->id2name == NULL) {
2712479ac375Sdm199847 			retcode = IDMAP_ERR_MEMORY;
2713479ac375Sdm199847 		}
2714479ac375Sdm199847 	}
2715479ac375Sdm199847 
2716479ac375Sdm199847 	if (retcode == IDMAP_SUCCESS) {
271748258c6bSjp151216 		idmap_namerule_set(rule, values[3], values[2],
271848258c6bSjp151216 		    values[0], is_wuser, is_user, strtol(values[4], &end, 10),
271948258c6bSjp151216 		    res->direction);
272048258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
2721c5c4113dSnw141292 	}
2722479ac375Sdm199847 
2723cd37da74Snw141292 	if (lower_winname != NULL && lower_winname != winname)
2724cd37da74Snw141292 		free(lower_winname);
272562c60062Sbaban 	if (vm != NULL)
2726c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
2727c5c4113dSnw141292 	return (retcode);
2728c5c4113dSnw141292 }
2729c5c4113dSnw141292 
2730c5c4113dSnw141292 static
2731c5c4113dSnw141292 int
2732c5c4113dSnw141292 get_next_eph_uid(uid_t *next_uid)
2733c5c4113dSnw141292 {
2734c5c4113dSnw141292 	uid_t uid;
2735c5c4113dSnw141292 	gid_t gid;
2736c5c4113dSnw141292 	int err;
2737c5c4113dSnw141292 
2738c5c4113dSnw141292 	*next_uid = (uid_t)-1;
2739c5c4113dSnw141292 	uid = _idmapdstate.next_uid++;
2740c5c4113dSnw141292 	if (uid >= _idmapdstate.limit_uid) {
2741c5c4113dSnw141292 		if ((err = allocids(0, 8192, &uid, 0, &gid)) != 0)
2742c5c4113dSnw141292 			return (err);
2743c5c4113dSnw141292 
2744c5c4113dSnw141292 		_idmapdstate.limit_uid = uid + 8192;
2745c5c4113dSnw141292 		_idmapdstate.next_uid = uid;
2746c5c4113dSnw141292 	}
2747c5c4113dSnw141292 	*next_uid = uid;
2748c5c4113dSnw141292 
2749c5c4113dSnw141292 	return (0);
2750c5c4113dSnw141292 }
2751c5c4113dSnw141292 
2752c5c4113dSnw141292 static
2753c5c4113dSnw141292 int
2754c5c4113dSnw141292 get_next_eph_gid(gid_t *next_gid)
2755c5c4113dSnw141292 {
2756c5c4113dSnw141292 	uid_t uid;
2757c5c4113dSnw141292 	gid_t gid;
2758c5c4113dSnw141292 	int err;
2759c5c4113dSnw141292 
2760c5c4113dSnw141292 	*next_gid = (uid_t)-1;
2761c5c4113dSnw141292 	gid = _idmapdstate.next_gid++;
2762c5c4113dSnw141292 	if (gid >= _idmapdstate.limit_gid) {
2763c5c4113dSnw141292 		if ((err = allocids(0, 0, &uid, 8192, &gid)) != 0)
2764c5c4113dSnw141292 			return (err);
2765c5c4113dSnw141292 
2766c5c4113dSnw141292 		_idmapdstate.limit_gid = gid + 8192;
2767c5c4113dSnw141292 		_idmapdstate.next_gid = gid;
2768c5c4113dSnw141292 	}
2769c5c4113dSnw141292 	*next_gid = gid;
2770c5c4113dSnw141292 
2771c5c4113dSnw141292 	return (0);
2772c5c4113dSnw141292 }
2773c5c4113dSnw141292 
277462c60062Sbaban static
277562c60062Sbaban int
2776cd37da74Snw141292 gethash(const char *str, uint32_t num, uint_t htsize)
2777cd37da74Snw141292 {
277862c60062Sbaban 	uint_t  hval, i, len;
277962c60062Sbaban 
278062c60062Sbaban 	if (str == NULL)
278162c60062Sbaban 		return (0);
278262c60062Sbaban 	for (len = strlen(str), hval = 0, i = 0; i < len; i++) {
278362c60062Sbaban 		hval += str[i];
278462c60062Sbaban 		hval += (hval << 10);
278562c60062Sbaban 		hval ^= (hval >> 6);
278662c60062Sbaban 	}
278762c60062Sbaban 	for (str = (const char *)&num, i = 0; i < sizeof (num); i++) {
278862c60062Sbaban 		hval += str[i];
278962c60062Sbaban 		hval += (hval << 10);
279062c60062Sbaban 		hval ^= (hval >> 6);
279162c60062Sbaban 	}
279262c60062Sbaban 	hval += (hval << 3);
279362c60062Sbaban 	hval ^= (hval >> 11);
279462c60062Sbaban 	hval += (hval << 15);
279562c60062Sbaban 	return (hval % htsize);
279662c60062Sbaban }
279762c60062Sbaban 
279862c60062Sbaban static
279962c60062Sbaban int
280062c60062Sbaban get_from_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid,
2801cd37da74Snw141292 		uid_t *pid)
2802cd37da74Snw141292 {
280362c60062Sbaban 	uint_t		next, key;
280462c60062Sbaban 	uint_t		htsize = state->sid_history_size;
280562c60062Sbaban 	idmap_sid	*sid;
280662c60062Sbaban 
280762c60062Sbaban 	next = gethash(prefix, rid, htsize);
280862c60062Sbaban 	while (next != htsize) {
280962c60062Sbaban 		key = state->sid_history[next].key;
281062c60062Sbaban 		if (key == htsize)
281162c60062Sbaban 			return (0);
281262c60062Sbaban 		sid = &state->batch->idmap_mapping_batch_val[key].id1.
281362c60062Sbaban 		    idmap_id_u.sid;
281462c60062Sbaban 		if (sid->rid == rid && strcmp(sid->prefix, prefix) == 0) {
281562c60062Sbaban 			*pid = state->result->ids.ids_val[key].id.
281662c60062Sbaban 			    idmap_id_u.uid;
281762c60062Sbaban 			return (1);
281862c60062Sbaban 		}
281962c60062Sbaban 		next = state->sid_history[next].next;
282062c60062Sbaban 	}
282162c60062Sbaban 	return (0);
282262c60062Sbaban }
282362c60062Sbaban 
282462c60062Sbaban static
282562c60062Sbaban void
2826cd37da74Snw141292 add_to_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid)
2827cd37da74Snw141292 {
282862c60062Sbaban 	uint_t		hash, next;
282962c60062Sbaban 	uint_t		htsize = state->sid_history_size;
283062c60062Sbaban 
283162c60062Sbaban 	hash = next = gethash(prefix, rid, htsize);
283262c60062Sbaban 	while (state->sid_history[next].key != htsize) {
283362c60062Sbaban 		next++;
283462c60062Sbaban 		next %= htsize;
283562c60062Sbaban 	}
283662c60062Sbaban 	state->sid_history[next].key = state->curpos;
283762c60062Sbaban 	if (hash == next)
283862c60062Sbaban 		return;
283962c60062Sbaban 	state->sid_history[next].next = state->sid_history[hash].next;
284062c60062Sbaban 	state->sid_history[hash].next = next;
284162c60062Sbaban }
2842c5c4113dSnw141292 
2843e8c27ec8Sbaban void
2844e8c27ec8Sbaban cleanup_lookup_state(lookup_state_t *state)
2845e8c27ec8Sbaban {
2846e8c27ec8Sbaban 	free(state->sid_history);
2847e8c27ec8Sbaban 	free(state->ad_unixuser_attr);
2848e8c27ec8Sbaban 	free(state->ad_unixgroup_attr);
2849479ac375Sdm199847 	free(state->nldap_winname_attr);
2850479ac375Sdm199847 	free(state->defdom);
2851e8c27ec8Sbaban }
2852e8c27ec8Sbaban 
2853c5c4113dSnw141292 /* ARGSUSED */
2854c5c4113dSnw141292 static
2855c5c4113dSnw141292 idmap_retcode
2856479ac375Sdm199847 dynamic_ephemeral_mapping(lookup_state_t *state,
2857cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
2858cd37da74Snw141292 {
2859c5c4113dSnw141292 
2860c5c4113dSnw141292 	uid_t		next_pid;
2861c5c4113dSnw141292 
2862651c0131Sbaban 	res->direction = IDMAP_DIRECTION_BI;
286362c60062Sbaban 
286448258c6bSjp151216 	if (IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
286548258c6bSjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
286648258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_CACHE;
286762c60062Sbaban 		return (IDMAP_SUCCESS);
286848258c6bSjp151216 	}
286962c60062Sbaban 
287062c60062Sbaban 	if (state->sid_history != NULL &&
287162c60062Sbaban 	    get_from_sid_history(state, req->id1.idmap_id_u.sid.prefix,
287262c60062Sbaban 	    req->id1.idmap_id_u.sid.rid, &next_pid)) {
287362c60062Sbaban 		res->id.idmap_id_u.uid = next_pid;
287448258c6bSjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
287548258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
287662c60062Sbaban 		return (IDMAP_SUCCESS);
287762c60062Sbaban 	}
287862c60062Sbaban 
287962c60062Sbaban 	if (res->id.idtype == IDMAP_UID) {
2880c5c4113dSnw141292 		if (get_next_eph_uid(&next_pid) != 0)
2881c5c4113dSnw141292 			return (IDMAP_ERR_INTERNAL);
2882c5c4113dSnw141292 		res->id.idmap_id_u.uid = next_pid;
2883c5c4113dSnw141292 	} else {
2884c5c4113dSnw141292 		if (get_next_eph_gid(&next_pid) != 0)
2885c5c4113dSnw141292 			return (IDMAP_ERR_INTERNAL);
2886c5c4113dSnw141292 		res->id.idmap_id_u.gid = next_pid;
2887c5c4113dSnw141292 	}
2888c5c4113dSnw141292 
288948258c6bSjp151216 	res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
289048258c6bSjp151216 	res->info.src = IDMAP_MAP_SRC_NEW;
289162c60062Sbaban 	if (state->sid_history != NULL)
289262c60062Sbaban 		add_to_sid_history(state, req->id1.idmap_id_u.sid.prefix,
289362c60062Sbaban 		    req->id1.idmap_id_u.sid.rid);
289462c60062Sbaban 
2895c5c4113dSnw141292 	return (IDMAP_SUCCESS);
2896c5c4113dSnw141292 }
2897c5c4113dSnw141292 
2898c5c4113dSnw141292 idmap_retcode
2899479ac375Sdm199847 sid2pid_second_pass(lookup_state_t *state,
2900cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
2901cd37da74Snw141292 {
2902c5c4113dSnw141292 	idmap_retcode	retcode;
2903c5c4113dSnw141292 
2904c5c4113dSnw141292 	/* Check if second pass is needed */
2905e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
2906c5c4113dSnw141292 		return (res->retcode);
2907c5c4113dSnw141292 
2908c5c4113dSnw141292 	/* Get status from previous pass */
2909e8c27ec8Sbaban 	retcode = res->retcode;
2910e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
2911e8c27ec8Sbaban 		goto out;
2912c5c4113dSnw141292 
2913e8c27ec8Sbaban 	/*
2914e8c27ec8Sbaban 	 * If directory-based name mapping is enabled then the unixname
2915e8c27ec8Sbaban 	 * may already have been retrieved from the AD object (AD-mode or
2916e8c27ec8Sbaban 	 * mixed-mode) or from native LDAP object (nldap-mode) -- done.
2917e8c27ec8Sbaban 	 */
2918e8c27ec8Sbaban 	if (req->id2name != NULL) {
2919e8c27ec8Sbaban 		assert(res->id.idtype != IDMAP_POSIXID);
2920e8c27ec8Sbaban 		if (AD_MODE(res->id.idtype, state))
2921e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
2922e8c27ec8Sbaban 		else if (NLDAP_MODE(res->id.idtype, state))
2923e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
2924e8c27ec8Sbaban 		else if (MIXED_MODE(res->id.idtype, state))
2925e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
2926c5c4113dSnw141292 
2927e8c27ec8Sbaban 		/*
2928e8c27ec8Sbaban 		 * Special case: (1) If the ad_unixuser_attr and
2929e8c27ec8Sbaban 		 * ad_unixgroup_attr uses the same attribute
2930e8c27ec8Sbaban 		 * name and (2) if this is a diagonal mapping
2931e8c27ec8Sbaban 		 * request and (3) the unixname has been retrieved
2932e8c27ec8Sbaban 		 * from the AD object -- then we ignore it and fallback
2933e8c27ec8Sbaban 		 * to name-based mapping rules and ephemeral mapping
2934e8c27ec8Sbaban 		 *
2935e8c27ec8Sbaban 		 * Example:
2936e8c27ec8Sbaban 		 *  Properties:
2937e8c27ec8Sbaban 		 *    config/ad_unixuser_attr = "unixname"
2938e8c27ec8Sbaban 		 *    config/ad_unixgroup_attr = "unixname"
2939e8c27ec8Sbaban 		 *  AD user object:
2940e8c27ec8Sbaban 		 *    dn: cn=bob ...
2941e8c27ec8Sbaban 		 *    objectclass: user
2942e8c27ec8Sbaban 		 *    sam: bob
2943e8c27ec8Sbaban 		 *    unixname: bob1234
2944e8c27ec8Sbaban 		 *  AD group object:
2945e8c27ec8Sbaban 		 *    dn: cn=winadmins ...
2946e8c27ec8Sbaban 		 *    objectclass: group
2947e8c27ec8Sbaban 		 *    sam: winadmins
2948e8c27ec8Sbaban 		 *    unixname: unixadmins
2949e8c27ec8Sbaban 		 *
2950e8c27ec8Sbaban 		 *  In this example whether "unixname" refers to a unixuser
2951e8c27ec8Sbaban 		 *  or unixgroup depends upon the AD object.
2952e8c27ec8Sbaban 		 *
2953e8c27ec8Sbaban 		 * $idmap show -c winname:bob gid
2954e8c27ec8Sbaban 		 *    AD lookup by "samAccountName=bob" for
2955e8c27ec8Sbaban 		 *    "ad_unixgroup_attr (i.e unixname)" for directory-based
2956e8c27ec8Sbaban 		 *    mapping would get "bob1234" which is not what we want.
2957e8c27ec8Sbaban 		 *    Now why not getgrnam_r("bob1234") and use it if it
2958e8c27ec8Sbaban 		 *    is indeed a unixgroup? That's because Unix can have
2959e8c27ec8Sbaban 		 *    users and groups with the same name and we clearly
2960e8c27ec8Sbaban 		 *    don't know the intention of the admin here.
2961e8c27ec8Sbaban 		 *    Therefore we ignore this and fallback to name-based
2962e8c27ec8Sbaban 		 *    mapping rules or ephemeral mapping.
2963e8c27ec8Sbaban 		 */
2964e8c27ec8Sbaban 		if ((AD_MODE(res->id.idtype, state) ||
2965e8c27ec8Sbaban 		    MIXED_MODE(res->id.idtype, state)) &&
2966e8c27ec8Sbaban 		    state->ad_unixuser_attr != NULL &&
2967e8c27ec8Sbaban 		    state->ad_unixgroup_attr != NULL &&
2968e8c27ec8Sbaban 		    strcasecmp(state->ad_unixuser_attr,
2969e8c27ec8Sbaban 		    state->ad_unixgroup_attr) == 0 &&
2970e8c27ec8Sbaban 		    ((req->id1.idtype == IDMAP_USID &&
2971e8c27ec8Sbaban 		    res->id.idtype == IDMAP_GID) ||
2972e8c27ec8Sbaban 		    (req->id1.idtype == IDMAP_GSID &&
2973e8c27ec8Sbaban 		    res->id.idtype == IDMAP_UID))) {
2974e8c27ec8Sbaban 			free(req->id2name);
2975e8c27ec8Sbaban 			req->id2name = NULL;
2976e8c27ec8Sbaban 			res->id.idmap_id_u.uid = SENTINEL_PID;
2977e8c27ec8Sbaban 			/* fallback */
2978e8c27ec8Sbaban 		} else {
2979e8c27ec8Sbaban 			if (res->id.idmap_id_u.uid == SENTINEL_PID)
2980e8c27ec8Sbaban 				retcode = ns_lookup_byname(req->id2name,
2981e8c27ec8Sbaban 				    NULL, &res->id);
2982e8c27ec8Sbaban 			/*
2983479ac375Sdm199847 			 * If ns_lookup_byname() fails that means the
2984479ac375Sdm199847 			 * unixname (req->id2name), which was obtained
2985479ac375Sdm199847 			 * from the AD object by directory-based mapping,
2986479ac375Sdm199847 			 * is not a valid Unix user/group and therefore
2987479ac375Sdm199847 			 * we return the error to the client instead of
2988479ac375Sdm199847 			 * doing rule-based mapping or ephemeral mapping.
2989479ac375Sdm199847 			 * This way the client can detect the issue.
2990e8c27ec8Sbaban 			 */
2991c5c4113dSnw141292 			goto out;
2992c5c4113dSnw141292 		}
2993e8c27ec8Sbaban 	}
2994c5c4113dSnw141292 
299548258c6bSjp151216 	/* Free any mapping info from Directory based mapping */
299648258c6bSjp151216 	if (res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN)
299748258c6bSjp151216 		idmap_info_free(&res->info);
299848258c6bSjp151216 
2999e8c27ec8Sbaban 	/*
3000e8c27ec8Sbaban 	 * If we don't have unixname then evaluate local name-based
3001e8c27ec8Sbaban 	 * mapping rules.
3002e8c27ec8Sbaban 	 */
3003479ac375Sdm199847 	retcode = name_based_mapping_sid2pid(state, req, res);
3004e8c27ec8Sbaban 	if (retcode != IDMAP_ERR_NOTFOUND)
3005e8c27ec8Sbaban 		goto out;
3006e8c27ec8Sbaban 
3007c5c4113dSnw141292 	/* If not found, do ephemeral mapping */
3008479ac375Sdm199847 	retcode = dynamic_ephemeral_mapping(state, req, res);
3009c5c4113dSnw141292 
3010c5c4113dSnw141292 out:
3011c5c4113dSnw141292 	res->retcode = idmap_stat4prot(retcode);
3012e8c27ec8Sbaban 	if (res->retcode != IDMAP_SUCCESS) {
3013e8c27ec8Sbaban 		req->direction = _IDMAP_F_DONE;
3014e8c27ec8Sbaban 		res->id.idmap_id_u.uid = UID_NOBODY;
3015e8c27ec8Sbaban 	}
3016e8c27ec8Sbaban 	if (!ARE_WE_DONE(req->direction))
3017e8c27ec8Sbaban 		state->sid2pid_done = FALSE;
3018c5c4113dSnw141292 	return (retcode);
3019c5c4113dSnw141292 }
3020c5c4113dSnw141292 
3021c5c4113dSnw141292 idmap_retcode
3022479ac375Sdm199847 update_cache_pid2sid(lookup_state_t *state,
3023cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
3024cd37da74Snw141292 {
3025c5c4113dSnw141292 	char		*sql = NULL;
3026c5c4113dSnw141292 	idmap_retcode	retcode;
302748258c6bSjp151216 	char		*map_dn = NULL;
302848258c6bSjp151216 	char		*map_attr = NULL;
302948258c6bSjp151216 	char		*map_value = NULL;
303048258c6bSjp151216 	char 		*map_windomain = NULL;
303148258c6bSjp151216 	char		*map_winname = NULL;
303248258c6bSjp151216 	char		*map_unixname = NULL;
303348258c6bSjp151216 	int		map_is_nt4 = FALSE;
3034c5c4113dSnw141292 
3035c5c4113dSnw141292 	/* Check if we need to cache anything */
3036e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
3037c5c4113dSnw141292 		return (IDMAP_SUCCESS);
3038c5c4113dSnw141292 
3039c5c4113dSnw141292 	/* We don't cache negative entries */
3040c5c4113dSnw141292 	if (res->retcode != IDMAP_SUCCESS)
3041c5c4113dSnw141292 		return (IDMAP_SUCCESS);
3042c5c4113dSnw141292 
3043e8c27ec8Sbaban 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
304448258c6bSjp151216 	assert(req->id1.idmap_id_u.uid != SENTINEL_PID);
304548258c6bSjp151216 	assert(res->id.idtype != IDMAP_SID);
304648258c6bSjp151216 
304748258c6bSjp151216 	assert(res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN);
304848258c6bSjp151216 	switch (res->info.how.map_type) {
304948258c6bSjp151216 	case IDMAP_MAP_TYPE_DS_AD:
305048258c6bSjp151216 		map_dn = res->info.how.idmap_how_u.ad.dn;
305148258c6bSjp151216 		map_attr = res->info.how.idmap_how_u.ad.attr;
305248258c6bSjp151216 		map_value = res->info.how.idmap_how_u.ad.value;
305348258c6bSjp151216 		break;
305448258c6bSjp151216 
305548258c6bSjp151216 	case IDMAP_MAP_TYPE_DS_NLDAP:
305648258c6bSjp151216 		map_dn = res->info.how.idmap_how_u.nldap.dn;
305748258c6bSjp151216 		map_attr = res->info.how.idmap_how_u.nldap.attr;
305848258c6bSjp151216 		map_value = res->info.how.idmap_how_u.nldap.value;
305948258c6bSjp151216 		break;
306048258c6bSjp151216 
306148258c6bSjp151216 	case IDMAP_MAP_TYPE_RULE_BASED:
306248258c6bSjp151216 		map_windomain = res->info.how.idmap_how_u.rule.windomain;
306348258c6bSjp151216 		map_winname = res->info.how.idmap_how_u.rule.winname;
306448258c6bSjp151216 		map_unixname = res->info.how.idmap_how_u.rule.unixname;
306548258c6bSjp151216 		map_is_nt4 = res->info.how.idmap_how_u.rule.is_nt4;
306648258c6bSjp151216 		break;
306748258c6bSjp151216 
306848258c6bSjp151216 	case IDMAP_MAP_TYPE_EPHEMERAL:
306948258c6bSjp151216 		break;
307048258c6bSjp151216 
307148258c6bSjp151216 	case IDMAP_MAP_TYPE_LOCAL_SID:
307248258c6bSjp151216 		break;
307348258c6bSjp151216 
307448258c6bSjp151216 	default:
307548258c6bSjp151216 		/* Dont cache other mapping types */
307648258c6bSjp151216 		assert(FALSE);
307748258c6bSjp151216 	}
3078e8c27ec8Sbaban 
3079c5c4113dSnw141292 	/*
3080c5c4113dSnw141292 	 * Using NULL for u2w instead of 0 so that our trigger allows
3081c5c4113dSnw141292 	 * the same pid to be the destination in multiple entries
3082c5c4113dSnw141292 	 */
3083c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
3084cd37da74Snw141292 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
308548258c6bSjp151216 	    "is_user, is_wuser, expiration, w2u, u2w, "
308648258c6bSjp151216 	    "map_type, map_dn, map_attr, map_value, map_windomain, "
308748258c6bSjp151216 	    "map_winname, map_unixname, map_is_nt4) "
3088cd37da74Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
308948258c6bSjp151216 	    "strftime('%%s','now') + 600, %q, 1, "
309048258c6bSjp151216 	    "%d, %Q, %Q, %Q, %Q, %Q, %Q, %d); ",
3091cd37da74Snw141292 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
3092cd37da74Snw141292 	    req->id2domain, req->id2name, req->id1.idmap_id_u.uid,
3093cd37da74Snw141292 	    req->id1name, (req->id1.idtype == IDMAP_UID) ? 1 : 0,
3094e8c27ec8Sbaban 	    (res->id.idtype == IDMAP_USID) ? 1 : 0,
309548258c6bSjp151216 	    (res->direction == 0) ? "1" : NULL,
309648258c6bSjp151216 	    res->info.how.map_type, map_dn, map_attr, map_value,
309748258c6bSjp151216 	    map_windomain, map_winname, map_unixname, map_is_nt4);
3098c5c4113dSnw141292 
3099c5c4113dSnw141292 	if (sql == NULL) {
3100c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3101c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3102c5c4113dSnw141292 		goto out;
3103c5c4113dSnw141292 	}
3104c5c4113dSnw141292 
3105479ac375Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
3106c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
3107c5c4113dSnw141292 		goto out;
3108c5c4113dSnw141292 
3109c5c4113dSnw141292 	state->pid2sid_done = FALSE;
3110c5c4113dSnw141292 	sqlite_freemem(sql);
3111c5c4113dSnw141292 	sql = NULL;
3112c5c4113dSnw141292 
3113e8c27ec8Sbaban 	/* Check if we need to update namecache */
3114e8c27ec8Sbaban 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
3115c5c4113dSnw141292 		goto out;
3116c5c4113dSnw141292 
31178e228215Sdm199847 	if (req->id2name == NULL)
3118c5c4113dSnw141292 		goto out;
3119c5c4113dSnw141292 
3120c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
3121cd37da74Snw141292 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
3122c5c4113dSnw141292 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
3123cd37da74Snw141292 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
3124cd37da74Snw141292 	    req->id2name, req->id2domain,
3125e8c27ec8Sbaban 	    (res->id.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
3126c5c4113dSnw141292 
3127c5c4113dSnw141292 	if (sql == NULL) {
3128c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3129c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3130c5c4113dSnw141292 		goto out;
3131c5c4113dSnw141292 	}
3132c5c4113dSnw141292 
3133479ac375Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
3134c5c4113dSnw141292 
3135c5c4113dSnw141292 out:
313648258c6bSjp151216 	if (!(req->flag & IDMAP_REQ_FLG_MAPPING_INFO))
313748258c6bSjp151216 		idmap_info_free(&res->info);
313862c60062Sbaban 	if (sql != NULL)
3139c5c4113dSnw141292 		sqlite_freemem(sql);
3140c5c4113dSnw141292 	return (retcode);
3141c5c4113dSnw141292 }
3142c5c4113dSnw141292 
3143c5c4113dSnw141292 idmap_retcode
3144479ac375Sdm199847 update_cache_sid2pid(lookup_state_t *state,
3145cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
3146cd37da74Snw141292 {
3147c5c4113dSnw141292 	char		*sql = NULL;
3148c5c4113dSnw141292 	idmap_retcode	retcode;
3149c5c4113dSnw141292 	int		is_eph_user;
315048258c6bSjp151216 	char		*map_dn = NULL;
315148258c6bSjp151216 	char		*map_attr = NULL;
315248258c6bSjp151216 	char		*map_value = NULL;
315348258c6bSjp151216 	char 		*map_windomain = NULL;
315448258c6bSjp151216 	char		*map_winname = NULL;
315548258c6bSjp151216 	char		*map_unixname = NULL;
315648258c6bSjp151216 	int		map_is_nt4 = FALSE;
3157c5c4113dSnw141292 
3158c5c4113dSnw141292 	/* Check if we need to cache anything */
3159e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
3160c5c4113dSnw141292 		return (IDMAP_SUCCESS);
3161c5c4113dSnw141292 
3162c5c4113dSnw141292 	/* We don't cache negative entries */
3163c5c4113dSnw141292 	if (res->retcode != IDMAP_SUCCESS)
3164c5c4113dSnw141292 		return (IDMAP_SUCCESS);
3165c5c4113dSnw141292 
3166c5c4113dSnw141292 	if (req->direction & _IDMAP_F_EXP_EPH_UID)
3167c5c4113dSnw141292 		is_eph_user = 1;
3168c5c4113dSnw141292 	else if (req->direction & _IDMAP_F_EXP_EPH_GID)
3169c5c4113dSnw141292 		is_eph_user = 0;
3170c5c4113dSnw141292 	else
3171c5c4113dSnw141292 		is_eph_user = -1;
3172c5c4113dSnw141292 
3173c5c4113dSnw141292 	if (is_eph_user >= 0 && !IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
3174c5c4113dSnw141292 		sql = sqlite_mprintf("UPDATE idmap_cache "
3175c5c4113dSnw141292 		    "SET w2u = 0 WHERE "
3176c5c4113dSnw141292 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
3177c5c4113dSnw141292 		    "pid >= 2147483648 AND is_user = %d;",
3178c5c4113dSnw141292 		    req->id1.idmap_id_u.sid.prefix,
3179c5c4113dSnw141292 		    req->id1.idmap_id_u.sid.rid,
3180c5c4113dSnw141292 		    is_eph_user);
3181c5c4113dSnw141292 		if (sql == NULL) {
3182c5c4113dSnw141292 			retcode = IDMAP_ERR_INTERNAL;
3183c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
3184c5c4113dSnw141292 			goto out;
3185c5c4113dSnw141292 		}
3186c5c4113dSnw141292 
3187479ac375Sdm199847 		retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
3188c5c4113dSnw141292 		if (retcode != IDMAP_SUCCESS)
3189c5c4113dSnw141292 			goto out;
3190c5c4113dSnw141292 
3191c5c4113dSnw141292 		sqlite_freemem(sql);
3192c5c4113dSnw141292 		sql = NULL;
3193c5c4113dSnw141292 	}
3194c5c4113dSnw141292 
3195e8c27ec8Sbaban 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
319648258c6bSjp151216 	assert(res->id.idmap_id_u.uid != SENTINEL_PID);
319748258c6bSjp151216 
319848258c6bSjp151216 	switch (res->info.how.map_type) {
319948258c6bSjp151216 	case IDMAP_MAP_TYPE_DS_AD:
320048258c6bSjp151216 		map_dn = res->info.how.idmap_how_u.ad.dn;
320148258c6bSjp151216 		map_attr = res->info.how.idmap_how_u.ad.attr;
320248258c6bSjp151216 		map_value = res->info.how.idmap_how_u.ad.value;
320348258c6bSjp151216 		break;
320448258c6bSjp151216 
320548258c6bSjp151216 	case IDMAP_MAP_TYPE_DS_NLDAP:
320648258c6bSjp151216 		map_dn = res->info.how.idmap_how_u.nldap.dn;
320748258c6bSjp151216 		map_attr = res->info.how.idmap_how_u.ad.attr;
320848258c6bSjp151216 		map_value = res->info.how.idmap_how_u.nldap.value;
320948258c6bSjp151216 		break;
321048258c6bSjp151216 
321148258c6bSjp151216 	case IDMAP_MAP_TYPE_RULE_BASED:
321248258c6bSjp151216 		map_windomain = res->info.how.idmap_how_u.rule.windomain;
321348258c6bSjp151216 		map_winname = res->info.how.idmap_how_u.rule.winname;
321448258c6bSjp151216 		map_unixname = res->info.how.idmap_how_u.rule.unixname;
321548258c6bSjp151216 		map_is_nt4 = res->info.how.idmap_how_u.rule.is_nt4;
321648258c6bSjp151216 		break;
321748258c6bSjp151216 
321848258c6bSjp151216 	case IDMAP_MAP_TYPE_EPHEMERAL:
321948258c6bSjp151216 		break;
322048258c6bSjp151216 
322148258c6bSjp151216 	default:
322248258c6bSjp151216 		/* Dont cache other mapping types */
322348258c6bSjp151216 		assert(FALSE);
322448258c6bSjp151216 	}
3225cd37da74Snw141292 
3226c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
3227cd37da74Snw141292 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
322848258c6bSjp151216 	    "is_user, is_wuser, expiration, w2u, u2w, "
322948258c6bSjp151216 	    "map_type, map_dn, map_attr, map_value, map_windomain, "
323048258c6bSjp151216 	    "map_winname, map_unixname, map_is_nt4) "
3231cd37da74Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
323248258c6bSjp151216 	    "strftime('%%s','now') + 600, 1, %q, "
323348258c6bSjp151216 	    "%d, %Q, %Q, %Q, %Q, %Q, %Q, %d);",
3234cd37da74Snw141292 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
3235e8c27ec8Sbaban 	    (req->id1domain != NULL) ? req->id1domain : "", req->id1name,
3236e8c27ec8Sbaban 	    res->id.idmap_id_u.uid, req->id2name,
3237e8c27ec8Sbaban 	    (res->id.idtype == IDMAP_UID) ? 1 : 0,
3238cd37da74Snw141292 	    (req->id1.idtype == IDMAP_USID) ? 1 : 0,
323948258c6bSjp151216 	    (res->direction == 0) ? "1" : NULL,
324048258c6bSjp151216 	    res->info.how.map_type, map_dn, map_attr, map_value,
324148258c6bSjp151216 	    map_windomain, map_winname, map_unixname, map_is_nt4);
3242c5c4113dSnw141292 
3243c5c4113dSnw141292 	if (sql == NULL) {
3244c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3245c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3246c5c4113dSnw141292 		goto out;
3247c5c4113dSnw141292 	}
3248c5c4113dSnw141292 
3249479ac375Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
3250c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
3251c5c4113dSnw141292 		goto out;
3252c5c4113dSnw141292 
3253c5c4113dSnw141292 	state->sid2pid_done = FALSE;
3254c5c4113dSnw141292 	sqlite_freemem(sql);
3255c5c4113dSnw141292 	sql = NULL;
3256c5c4113dSnw141292 
3257e8c27ec8Sbaban 	/* Check if we need to update namecache */
3258e8c27ec8Sbaban 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
3259c5c4113dSnw141292 		goto out;
3260c5c4113dSnw141292 
3261cf5b5989Sdm199847 	if (EMPTY_STRING(req->id1name))
3262c5c4113dSnw141292 		goto out;
3263c5c4113dSnw141292 
3264c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
3265cd37da74Snw141292 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
3266c5c4113dSnw141292 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
3267cd37da74Snw141292 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
3268cd37da74Snw141292 	    req->id1name, req->id1domain,
3269cd37da74Snw141292 	    (req->id1.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
3270c5c4113dSnw141292 
3271c5c4113dSnw141292 	if (sql == NULL) {
3272c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3273c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3274c5c4113dSnw141292 		goto out;
3275c5c4113dSnw141292 	}
3276c5c4113dSnw141292 
3277479ac375Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
3278c5c4113dSnw141292 
3279c5c4113dSnw141292 out:
328048258c6bSjp151216 	if (!(req->flag & IDMAP_REQ_FLG_MAPPING_INFO))
328148258c6bSjp151216 		idmap_info_free(&res->info);
328248258c6bSjp151216 
328362c60062Sbaban 	if (sql != NULL)
3284c5c4113dSnw141292 		sqlite_freemem(sql);
3285c5c4113dSnw141292 	return (retcode);
3286c5c4113dSnw141292 }
3287c5c4113dSnw141292 
3288cd37da74Snw141292 static
3289cd37da74Snw141292 idmap_retcode
3290c5c4113dSnw141292 lookup_cache_pid2sid(sqlite *cache, idmap_mapping *req, idmap_id_res *res,
3291cd37da74Snw141292 		int is_user, int getname)
3292cd37da74Snw141292 {
3293c5c4113dSnw141292 	char		*end;
3294c5c4113dSnw141292 	char		*sql = NULL;
3295c5c4113dSnw141292 	const char	**values;
3296c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
3297c5c4113dSnw141292 	int		ncol;
3298c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
3299c5c4113dSnw141292 	time_t		curtime;
3300e8c27ec8Sbaban 	idmap_id_type	idtype;
3301c5c4113dSnw141292 
3302c5c4113dSnw141292 	/* Current time */
3303c5c4113dSnw141292 	errno = 0;
3304c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
3305cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
3306c5c4113dSnw141292 		    strerror(errno));
3307c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3308c5c4113dSnw141292 		goto out;
3309c5c4113dSnw141292 	}
3310c5c4113dSnw141292 
3311e8c27ec8Sbaban 	/* SQL to lookup the cache by pid or by unixname */
3312e8c27ec8Sbaban 	if (req->id1.idmap_id_u.uid != SENTINEL_PID) {
331348258c6bSjp151216 		sql = sqlite_mprintf("SELECT sidprefix, rid, "
331448258c6bSjp151216 		    "canon_winname, windomain, w2u, is_wuser, "
331548258c6bSjp151216 		    "map_type, map_dn, map_attr, map_value, map_windomain, "
331648258c6bSjp151216 		    "map_winname, map_unixname, map_is_nt4 "
3317c5c4113dSnw141292 		    "FROM idmap_cache WHERE "
3318c5c4113dSnw141292 		    "pid = %u AND u2w = 1 AND is_user = %d AND "
3319c5c4113dSnw141292 		    "(pid >= 2147483648 OR "
3320c5c4113dSnw141292 		    "(expiration = 0 OR expiration ISNULL OR "
3321c5c4113dSnw141292 		    "expiration > %d));",
3322c5c4113dSnw141292 		    req->id1.idmap_id_u.uid, is_user, curtime);
3323e8c27ec8Sbaban 	} else if (req->id1name != NULL) {
332448258c6bSjp151216 		sql = sqlite_mprintf("SELECT sidprefix, rid, "
332548258c6bSjp151216 		    "canon_winname, windomain, w2u, is_wuser, "
332648258c6bSjp151216 		    "map_type, map_dn, map_attr, map_value, map_windomain, "
332748258c6bSjp151216 		    "map_winname, map_unixname, map_is_nt4 "
3328e8c27ec8Sbaban 		    "FROM idmap_cache WHERE "
3329e8c27ec8Sbaban 		    "unixname = %Q AND u2w = 1 AND is_user = %d AND "
3330e8c27ec8Sbaban 		    "(pid >= 2147483648 OR "
3331e8c27ec8Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
3332e8c27ec8Sbaban 		    "expiration > %d));",
3333e8c27ec8Sbaban 		    req->id1name, is_user, curtime);
333448258c6bSjp151216 	} else {
333548258c6bSjp151216 		retcode = IDMAP_ERR_ARG;
333648258c6bSjp151216 		goto out;
3337e8c27ec8Sbaban 	}
3338e8c27ec8Sbaban 
3339c5c4113dSnw141292 	if (sql == NULL) {
3340c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3341c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
3342c5c4113dSnw141292 		goto out;
3343c5c4113dSnw141292 	}
334448258c6bSjp151216 	retcode = sql_compile_n_step_once(
334548258c6bSjp151216 	    cache, sql, &vm, &ncol, 14, &values);
3346c5c4113dSnw141292 	sqlite_freemem(sql);
3347c5c4113dSnw141292 
3348c5c4113dSnw141292 	if (retcode == IDMAP_ERR_NOTFOUND)
3349c5c4113dSnw141292 		goto out;
3350c5c4113dSnw141292 	else if (retcode == IDMAP_SUCCESS) {
3351c5c4113dSnw141292 		/* sanity checks */
3352c5c4113dSnw141292 		if (values[0] == NULL || values[1] == NULL) {
3353c5c4113dSnw141292 			retcode = IDMAP_ERR_CACHE;
3354c5c4113dSnw141292 			goto out;
3355c5c4113dSnw141292 		}
3356c5c4113dSnw141292 
3357e8c27ec8Sbaban 		switch (res->id.idtype) {
3358c5c4113dSnw141292 		case IDMAP_SID:
3359cd37da74Snw141292 		case IDMAP_USID:
3360cd37da74Snw141292 		case IDMAP_GSID:
3361e8c27ec8Sbaban 			idtype = strtol(values[5], &end, 10) == 1
3362cd37da74Snw141292 			    ? IDMAP_USID : IDMAP_GSID;
3363cd37da74Snw141292 
3364e8c27ec8Sbaban 			if (res->id.idtype == IDMAP_USID &&
3365e8c27ec8Sbaban 			    idtype != IDMAP_USID) {
3366cd37da74Snw141292 				retcode = IDMAP_ERR_NOTUSER;
3367cd37da74Snw141292 				goto out;
3368e8c27ec8Sbaban 			} else if (res->id.idtype == IDMAP_GSID &&
3369e8c27ec8Sbaban 			    idtype != IDMAP_GSID) {
3370cd37da74Snw141292 				retcode = IDMAP_ERR_NOTGROUP;
3371cd37da74Snw141292 				goto out;
3372cd37da74Snw141292 			}
3373e8c27ec8Sbaban 			res->id.idtype = idtype;
3374cd37da74Snw141292 
3375c5c4113dSnw141292 			res->id.idmap_id_u.sid.rid =
3376c5c4113dSnw141292 			    strtoul(values[1], &end, 10);
3377c5c4113dSnw141292 			res->id.idmap_id_u.sid.prefix = strdup(values[0]);
3378c5c4113dSnw141292 			if (res->id.idmap_id_u.sid.prefix == NULL) {
3379c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
3380c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
3381c5c4113dSnw141292 				goto out;
3382c5c4113dSnw141292 			}
3383c5c4113dSnw141292 
338462c60062Sbaban 			if (values[4] != NULL)
3385c5c4113dSnw141292 				res->direction =
3386651c0131Sbaban 				    (strtol(values[4], &end, 10) == 0)?
3387651c0131Sbaban 				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
3388c5c4113dSnw141292 			else
3389651c0131Sbaban 				res->direction = IDMAP_DIRECTION_U2W;
3390c5c4113dSnw141292 
3391c5c4113dSnw141292 			if (getname == 0 || values[2] == NULL)
3392c5c4113dSnw141292 				break;
33938e228215Sdm199847 			req->id2name = strdup(values[2]);
33948e228215Sdm199847 			if (req->id2name == NULL) {
3395c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
3396c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
3397c5c4113dSnw141292 				goto out;
3398c5c4113dSnw141292 			}
3399c5c4113dSnw141292 
3400c5c4113dSnw141292 			if (values[3] == NULL)
3401c5c4113dSnw141292 				break;
34028e228215Sdm199847 			req->id2domain = strdup(values[3]);
34038e228215Sdm199847 			if (req->id2domain == NULL) {
3404c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
3405c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
3406c5c4113dSnw141292 				goto out;
3407c5c4113dSnw141292 			}
3408cd37da74Snw141292 
3409c5c4113dSnw141292 			break;
3410c5c4113dSnw141292 		default:
3411c5c4113dSnw141292 			retcode = IDMAP_ERR_NOTSUPPORTED;
3412c5c4113dSnw141292 			break;
3413c5c4113dSnw141292 		}
341448258c6bSjp151216 		if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
341548258c6bSjp151216 			res->info.src = IDMAP_MAP_SRC_CACHE;
341648258c6bSjp151216 			res->info.how.map_type = strtoul(values[6], &end, 10);
341748258c6bSjp151216 			switch (res->info.how.map_type) {
341848258c6bSjp151216 			case IDMAP_MAP_TYPE_DS_AD:
341948258c6bSjp151216 				res->info.how.idmap_how_u.ad.dn =
342048258c6bSjp151216 				    strdup(values[7]);
342148258c6bSjp151216 				res->info.how.idmap_how_u.ad.attr =
342248258c6bSjp151216 				    strdup(values[8]);
342348258c6bSjp151216 				res->info.how.idmap_how_u.ad.value =
342448258c6bSjp151216 				    strdup(values[9]);
342548258c6bSjp151216 				break;
342648258c6bSjp151216 
342748258c6bSjp151216 			case IDMAP_MAP_TYPE_DS_NLDAP:
342848258c6bSjp151216 				res->info.how.idmap_how_u.nldap.dn =
342948258c6bSjp151216 				    strdup(values[7]);
343048258c6bSjp151216 				res->info.how.idmap_how_u.nldap.attr =
343148258c6bSjp151216 				    strdup(values[8]);
343248258c6bSjp151216 				res->info.how.idmap_how_u.nldap.value =
343348258c6bSjp151216 				    strdup(values[9]);
343448258c6bSjp151216 				break;
343548258c6bSjp151216 
343648258c6bSjp151216 			case IDMAP_MAP_TYPE_RULE_BASED:
343748258c6bSjp151216 				res->info.how.idmap_how_u.rule.windomain =
343848258c6bSjp151216 				    strdup(values[10]);
343948258c6bSjp151216 				res->info.how.idmap_how_u.rule.winname =
344048258c6bSjp151216 				    strdup(values[11]);
344148258c6bSjp151216 				res->info.how.idmap_how_u.rule.unixname =
344248258c6bSjp151216 				    strdup(values[12]);
344348258c6bSjp151216 				res->info.how.idmap_how_u.rule.is_nt4 =
344448258c6bSjp151216 				    strtoul(values[13], &end, 10);
344548258c6bSjp151216 				res->info.how.idmap_how_u.rule.is_user =
344648258c6bSjp151216 				    is_user;
344748258c6bSjp151216 				res->info.how.idmap_how_u.rule.is_wuser =
344848258c6bSjp151216 				    strtol(values[5], &end, 10);
344948258c6bSjp151216 				break;
345048258c6bSjp151216 
345148258c6bSjp151216 			case IDMAP_MAP_TYPE_EPHEMERAL:
345248258c6bSjp151216 				break;
345348258c6bSjp151216 
345448258c6bSjp151216 			case IDMAP_MAP_TYPE_LOCAL_SID:
345548258c6bSjp151216 				break;
345648258c6bSjp151216 
345748258c6bSjp151216 			case IDMAP_MAP_TYPE_KNOWN_SID:
345848258c6bSjp151216 				break;
345948258c6bSjp151216 
346048258c6bSjp151216 			default:
346148258c6bSjp151216 				/* Unknow mapping type */
346248258c6bSjp151216 				assert(FALSE);
346348258c6bSjp151216 			}
346448258c6bSjp151216 		}
3465c5c4113dSnw141292 	}
3466c5c4113dSnw141292 
3467c5c4113dSnw141292 out:
346862c60062Sbaban 	if (vm != NULL)
3469c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
3470c5c4113dSnw141292 	return (retcode);
3471c5c4113dSnw141292 }
3472c5c4113dSnw141292 
3473cd37da74Snw141292 static
3474cd37da74Snw141292 idmap_retcode
3475c5c4113dSnw141292 lookup_cache_name2sid(sqlite *cache, const char *name, const char *domain,
3476cd37da74Snw141292 	char **canonname, char **sidprefix, idmap_rid_t *rid, int *type)
3477cd37da74Snw141292 {
3478cd37da74Snw141292 	char		*end, *lower_name;
3479c5c4113dSnw141292 	char		*sql = NULL;
3480c5c4113dSnw141292 	const char	**values;
3481c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
3482c5c4113dSnw141292 	int		ncol;
3483c5c4113dSnw141292 	time_t		curtime;
3484c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
3485c5c4113dSnw141292 
3486c5c4113dSnw141292 	/* Get current time */
3487c5c4113dSnw141292 	errno = 0;
3488c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
3489cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
3490c5c4113dSnw141292 		    strerror(errno));
3491c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3492c5c4113dSnw141292 		goto out;
3493c5c4113dSnw141292 	}
3494c5c4113dSnw141292 
3495c5c4113dSnw141292 	/* SQL to lookup the cache */
3496cd37da74Snw141292 	if ((lower_name = tolower_u8(name)) == NULL)
3497cd37da74Snw141292 		lower_name = (char *)name;
3498cd37da74Snw141292 	sql = sqlite_mprintf("SELECT sidprefix, rid, type, canon_name "
3499cd37da74Snw141292 	    "FROM name_cache WHERE name = %Q AND domain = %Q AND "
3500c5c4113dSnw141292 	    "(expiration = 0 OR expiration ISNULL OR "
3501cd37da74Snw141292 	    "expiration > %d);", lower_name, domain, curtime);
3502cd37da74Snw141292 	if (lower_name != name)
3503cd37da74Snw141292 		free(lower_name);
3504c5c4113dSnw141292 	if (sql == NULL) {
3505c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3506c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
3507c5c4113dSnw141292 		goto out;
3508c5c4113dSnw141292 	}
3509cd37da74Snw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 4, &values);
3510c5c4113dSnw141292 	sqlite_freemem(sql);
3511c5c4113dSnw141292 
3512c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
351362c60062Sbaban 		if (type != NULL) {
3514c5c4113dSnw141292 			if (values[2] == NULL) {
3515c5c4113dSnw141292 				retcode = IDMAP_ERR_CACHE;
3516c5c4113dSnw141292 				goto out;
3517c5c4113dSnw141292 			}
3518c5c4113dSnw141292 			*type = strtol(values[2], &end, 10);
3519c5c4113dSnw141292 		}
3520c5c4113dSnw141292 
3521e8c27ec8Sbaban 		if (values[0] == NULL || values[1] == NULL) {
3522e8c27ec8Sbaban 			retcode = IDMAP_ERR_CACHE;
3523e8c27ec8Sbaban 			goto out;
3524e8c27ec8Sbaban 		}
3525e8c27ec8Sbaban 
3526cd37da74Snw141292 		if (canonname != NULL) {
3527cd37da74Snw141292 			assert(values[3] != NULL);
3528cd37da74Snw141292 			if ((*canonname = strdup(values[3])) == NULL) {
3529cd37da74Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
3530cd37da74Snw141292 				retcode = IDMAP_ERR_MEMORY;
3531cd37da74Snw141292 				goto out;
3532cd37da74Snw141292 			}
3533cd37da74Snw141292 		}
3534cd37da74Snw141292 
3535c5c4113dSnw141292 		if ((*sidprefix = strdup(values[0])) == NULL) {
3536c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
3537c5c4113dSnw141292 			retcode = IDMAP_ERR_MEMORY;
3538e8c27ec8Sbaban 			if (canonname != NULL) {
3539e8c27ec8Sbaban 				free(*canonname);
3540e8c27ec8Sbaban 				*canonname = NULL;
3541e8c27ec8Sbaban 			}
3542c5c4113dSnw141292 			goto out;
3543c5c4113dSnw141292 		}
3544c5c4113dSnw141292 		*rid = strtoul(values[1], &end, 10);
3545c5c4113dSnw141292 	}
3546c5c4113dSnw141292 
3547c5c4113dSnw141292 out:
354862c60062Sbaban 	if (vm != NULL)
3549c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
3550c5c4113dSnw141292 	return (retcode);
3551c5c4113dSnw141292 }
3552c5c4113dSnw141292 
3553cd37da74Snw141292 static
3554cd37da74Snw141292 idmap_retcode
3555e8c27ec8Sbaban ad_lookup_by_winname(lookup_state_t *state,
3556e8c27ec8Sbaban 		const char *name, const char *domain, int eunixtype,
355748258c6bSjp151216 		char **dn, char **attr, char **value, char **canonname,
355848258c6bSjp151216 		char **sidprefix, idmap_rid_t *rid, int *wintype,
355948258c6bSjp151216 		char **unixname)
3560cd37da74Snw141292 {
3561c5c4113dSnw141292 	int			retries = 0;
3562c5c4113dSnw141292 	idmap_query_state_t	*qs = NULL;
3563c5c4113dSnw141292 	idmap_retcode		rc, retcode;
3564c5c4113dSnw141292 
3565c5c4113dSnw141292 retry:
3566e8c27ec8Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, 1, &qs);
3567e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
35680dcc7149Snw141292 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
35690dcc7149Snw141292 			goto retry;
3570349d5d8fSnw141292 		degrade_svc(1, "failed to create request for AD lookup "
35710dcc7149Snw141292 		    "by winname");
3572e8c27ec8Sbaban 		return (retcode);
3573c5c4113dSnw141292 	}
3574c5c4113dSnw141292 
3575c8e26105Sjp151216 	restore_svc();
3576c8e26105Sjp151216 
3577e8c27ec8Sbaban 	if (state != NULL)
3578e8c27ec8Sbaban 		idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
3579e8c27ec8Sbaban 		    state->ad_unixgroup_attr);
3580c5c4113dSnw141292 
3581e8c27ec8Sbaban 	retcode = idmap_name2sid_batch_add1(qs, name, domain, eunixtype,
358248258c6bSjp151216 	    dn, attr, value, canonname, sidprefix, rid, wintype, unixname, &rc);
3583c5c4113dSnw141292 
3584e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
358584decf41Sjp151216 		idmap_lookup_release_batch(&qs);
3586c5c4113dSnw141292 	else
35870dcc7149Snw141292 		retcode = idmap_lookup_batch_end(&qs);
3588c5c4113dSnw141292 
3589c5c4113dSnw141292 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
3590c5c4113dSnw141292 		goto retry;
3591c8e26105Sjp151216 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
3592349d5d8fSnw141292 		degrade_svc(1, "some AD lookups timed out repeatedly");
3593c5c4113dSnw141292 
3594c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS) {
3595e8c27ec8Sbaban 		idmapdlog(LOG_NOTICE, "AD lookup by winname failed");
3596c5c4113dSnw141292 		return (retcode);
3597e8c27ec8Sbaban 	}
3598c5c4113dSnw141292 	return (rc);
3599c5c4113dSnw141292 }
3600c5c4113dSnw141292 
3601cd37da74Snw141292 idmap_retcode
3602c5c4113dSnw141292 lookup_name2sid(sqlite *cache, const char *name, const char *domain,
3603cd37da74Snw141292 		int *is_wuser, char **canonname, char **sidprefix,
3604479ac375Sdm199847 		idmap_rid_t *rid, idmap_mapping *req, int local_only)
3605cd37da74Snw141292 {
3606c5c4113dSnw141292 	int		type;
3607c5c4113dSnw141292 	idmap_retcode	retcode;
3608c5c4113dSnw141292 
3609cd37da74Snw141292 	*sidprefix = NULL;
3610e8c27ec8Sbaban 	if (canonname != NULL)
3611cd37da74Snw141292 		*canonname = NULL;
3612cd37da74Snw141292 
3613e8c27ec8Sbaban 	/* Lookup well-known SIDs table */
3614cd37da74Snw141292 	retcode = lookup_wksids_name2sid(name, canonname, sidprefix, rid,
3615cd37da74Snw141292 	    &type);
361662c60062Sbaban 	if (retcode == IDMAP_SUCCESS) {
3617e8c27ec8Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
361862c60062Sbaban 		goto out;
361962c60062Sbaban 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
362062c60062Sbaban 		return (retcode);
362162c60062Sbaban 	}
362262c60062Sbaban 
3623e8c27ec8Sbaban 	/* Lookup cache */
3624cd37da74Snw141292 	retcode = lookup_cache_name2sid(cache, name, domain, canonname,
3625cd37da74Snw141292 	    sidprefix, rid, &type);
3626e8c27ec8Sbaban 	if (retcode == IDMAP_SUCCESS) {
3627e8c27ec8Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
3628e8c27ec8Sbaban 		goto out;
3629e8c27ec8Sbaban 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
3630e8c27ec8Sbaban 		return (retcode);
3631e8c27ec8Sbaban 	}
3632e8c27ec8Sbaban 
3633479ac375Sdm199847 	/*
3634479ac375Sdm199847 	 * The caller may be using this function to determine if this
3635479ac375Sdm199847 	 * request needs to be marked for AD lookup or not
3636479ac375Sdm199847 	 * (i.e. _IDMAP_F_LOOKUP_AD) and therefore may not want this
3637479ac375Sdm199847 	 * function to AD lookup now.
3638479ac375Sdm199847 	 */
3639479ac375Sdm199847 	if (local_only)
3640479ac375Sdm199847 		return (retcode);
3641479ac375Sdm199847 
3642e8c27ec8Sbaban 	/* Lookup AD */
3643e8c27ec8Sbaban 	retcode = ad_lookup_by_winname(NULL, name, domain, _IDMAP_T_UNDEF,
364448258c6bSjp151216 	    NULL, NULL, NULL, canonname, sidprefix, rid, &type, NULL);
3645c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
3646c5c4113dSnw141292 		return (retcode);
3647c5c4113dSnw141292 
364862c60062Sbaban out:
3649c5c4113dSnw141292 	/*
3650c5c4113dSnw141292 	 * Entry found (cache or Windows lookup)
3651cd37da74Snw141292 	 * is_wuser is both input as well as output parameter
3652c5c4113dSnw141292 	 */
3653e8c27ec8Sbaban 	if (*is_wuser == 1 && type != _IDMAP_T_USER)
3654e8c27ec8Sbaban 		retcode = IDMAP_ERR_NOTUSER;
3655e8c27ec8Sbaban 	else if (*is_wuser == 0 && type != _IDMAP_T_GROUP)
3656e8c27ec8Sbaban 		retcode = IDMAP_ERR_NOTGROUP;
3657e8c27ec8Sbaban 	else if (*is_wuser == -1) {
3658c5c4113dSnw141292 		/* Caller wants to know if its user or group */
3659c5c4113dSnw141292 		if (type == _IDMAP_T_USER)
3660cd37da74Snw141292 			*is_wuser = 1;
3661c5c4113dSnw141292 		else if (type == _IDMAP_T_GROUP)
3662cd37da74Snw141292 			*is_wuser = 0;
3663e8c27ec8Sbaban 		else
3664e8c27ec8Sbaban 			retcode = IDMAP_ERR_SID;
3665e8c27ec8Sbaban 	}
3666e8c27ec8Sbaban 
3667e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
3668cd37da74Snw141292 		free(*sidprefix);
3669cd37da74Snw141292 		*sidprefix = NULL;
3670e8c27ec8Sbaban 		if (canonname != NULL) {
3671cd37da74Snw141292 			free(*canonname);
3672cd37da74Snw141292 			*canonname = NULL;
3673cd37da74Snw141292 		}
3674c5c4113dSnw141292 	}
3675c5c4113dSnw141292 	return (retcode);
3676c5c4113dSnw141292 }
3677c5c4113dSnw141292 
3678cd37da74Snw141292 static
3679cd37da74Snw141292 idmap_retcode
3680479ac375Sdm199847 name_based_mapping_pid2sid(lookup_state_t *state, const char *unixname,
3681cd37da74Snw141292 		int is_user, idmap_mapping *req, idmap_id_res *res)
3682cd37da74Snw141292 {
3683c5c4113dSnw141292 	const char	*winname, *windomain;
3684cd37da74Snw141292 	char		*canonname;
3685c5c4113dSnw141292 	char		*sql = NULL, *errmsg = NULL;
3686c5c4113dSnw141292 	idmap_retcode	retcode;
3687c5c4113dSnw141292 	char		*end;
3688c5c4113dSnw141292 	const char	**values;
3689c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
369048258c6bSjp151216 	int		ncol, r;
3691cd37da74Snw141292 	int		is_wuser;
3692e8c27ec8Sbaban 	const char	*me = "name_based_mapping_pid2sid";
369348258c6bSjp151216 	int 		non_wild_match = FALSE;
369448258c6bSjp151216 	idmap_namerule	*rule = &res->info.how.idmap_how_u.rule;
369548258c6bSjp151216 	int direction;
3696e8c27ec8Sbaban 
3697e8c27ec8Sbaban 	assert(unixname != NULL); /* We have unixname */
3698e8c27ec8Sbaban 	assert(req->id2name == NULL); /* We don't have winname */
3699e8c27ec8Sbaban 	assert(res->id.idmap_id_u.sid.prefix == NULL); /* No SID either */
3700c5c4113dSnw141292 
3701c5c4113dSnw141292 	sql = sqlite_mprintf(
370248258c6bSjp151216 	    "SELECT winname_display, windomain, w2u_order, "
370348258c6bSjp151216 	    "is_wuser, unixname, is_nt4 "
370448258c6bSjp151216 	    "FROM namerules WHERE "
3705c5c4113dSnw141292 	    "u2w_order > 0 AND is_user = %d AND "
3706c5c4113dSnw141292 	    "(unixname = %Q OR unixname = '*') "
3707cd37da74Snw141292 	    "ORDER BY u2w_order ASC;", is_user, unixname);
3708c5c4113dSnw141292 	if (sql == NULL) {
3709c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3710c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
3711c5c4113dSnw141292 		goto out;
3712c5c4113dSnw141292 	}
3713c5c4113dSnw141292 
3714479ac375Sdm199847 	if (sqlite_compile(state->db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
3715c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3716cd37da74Snw141292 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
3717cd37da74Snw141292 		    CHECK_NULL(errmsg));
3718c5c4113dSnw141292 		sqlite_freemem(errmsg);
3719c5c4113dSnw141292 		goto out;
3720c5c4113dSnw141292 	}
3721c5c4113dSnw141292 
372248258c6bSjp151216 	for (;;) {
3723c5c4113dSnw141292 		r = sqlite_step(vm, &ncol, &values, NULL);
372484decf41Sjp151216 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
372584decf41Sjp151216 		if (r == SQLITE_ROW) {
372648258c6bSjp151216 			if (ncol < 6) {
3727c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
3728c5c4113dSnw141292 				goto out;
3729c5c4113dSnw141292 			}
3730c5c4113dSnw141292 			if (values[0] == NULL) {
3731c5c4113dSnw141292 				/* values [1] and [2] can be null */
3732c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
3733c5c4113dSnw141292 				goto out;
3734c5c4113dSnw141292 			}
373548258c6bSjp151216 
373648258c6bSjp151216 			if (values[2] != NULL)
373748258c6bSjp151216 				direction =
373848258c6bSjp151216 				    (strtol(values[2], &end, 10) == 0)?
373948258c6bSjp151216 				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
374048258c6bSjp151216 			else
374148258c6bSjp151216 				direction = IDMAP_DIRECTION_U2W;
374248258c6bSjp151216 
3743c5c4113dSnw141292 			if (EMPTY_NAME(values[0])) {
374448258c6bSjp151216 				idmap_namerule_set(rule, values[1], values[0],
374548258c6bSjp151216 				    values[4], is_user,
374648258c6bSjp151216 				    strtol(values[3], &end, 10),
374748258c6bSjp151216 				    strtol(values[5], &end, 10),
374848258c6bSjp151216 				    direction);
3749c5c4113dSnw141292 				retcode = IDMAP_ERR_NOMAPPING;
3750c5c4113dSnw141292 				goto out;
3751c5c4113dSnw141292 			}
3752cd37da74Snw141292 
3753cd37da74Snw141292 			if (values[0][0] == '*') {
375448258c6bSjp151216 				winname = unixname;
375548258c6bSjp151216 				if (non_wild_match) {
3756cd37da74Snw141292 					/*
375748258c6bSjp151216 					 * There were non-wildcard rules
375848258c6bSjp151216 					 * where the Windows identity doesn't
375948258c6bSjp151216 					 * exist. Return no mapping.
3760cd37da74Snw141292 					 */
3761cd37da74Snw141292 					retcode = IDMAP_ERR_NOMAPPING;
3762cd37da74Snw141292 					goto out;
3763cd37da74Snw141292 				}
3764cd37da74Snw141292 			} else {
376548258c6bSjp151216 				/* Save first non-wild match rule */
376648258c6bSjp151216 				if (!non_wild_match) {
376748258c6bSjp151216 					idmap_namerule_set(rule, values[1],
376848258c6bSjp151216 					    values[0], values[4],
376948258c6bSjp151216 					    is_user,
377048258c6bSjp151216 					    strtol(values[3], &end, 10),
377148258c6bSjp151216 					    strtol(values[5], &end, 10),
377248258c6bSjp151216 					    direction);
377348258c6bSjp151216 					non_wild_match = TRUE;
377448258c6bSjp151216 				}
3775cd37da74Snw141292 				winname = values[0];
3776cd37da74Snw141292 			}
377748258c6bSjp151216 			is_wuser = res->id.idtype == IDMAP_USID ? 1
377848258c6bSjp151216 			    : res->id.idtype == IDMAP_GSID ? 0
377948258c6bSjp151216 			    : -1;
378062c60062Sbaban 			if (values[1] != NULL)
3781c5c4113dSnw141292 				windomain = values[1];
3782479ac375Sdm199847 			else if (state->defdom != NULL)
3783479ac375Sdm199847 				windomain = state->defdom;
3784c5c4113dSnw141292 			else {
3785cd37da74Snw141292 				idmapdlog(LOG_ERR, "%s: no domain", me);
3786c5c4113dSnw141292 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
3787c5c4113dSnw141292 				goto out;
3788c5c4113dSnw141292 			}
3789cd37da74Snw141292 
3790479ac375Sdm199847 			retcode = lookup_name2sid(state->cache,
3791479ac375Sdm199847 			    winname, windomain,
3792cd37da74Snw141292 			    &is_wuser, &canonname,
3793cd37da74Snw141292 			    &res->id.idmap_id_u.sid.prefix,
3794479ac375Sdm199847 			    &res->id.idmap_id_u.sid.rid, req, 0);
3795e8c27ec8Sbaban 
3796c5c4113dSnw141292 			if (retcode == IDMAP_ERR_NOTFOUND) {
3797c5c4113dSnw141292 				continue;
3798c5c4113dSnw141292 			}
3799c5c4113dSnw141292 			goto out;
380048258c6bSjp151216 
3801c5c4113dSnw141292 		} else if (r == SQLITE_DONE) {
380248258c6bSjp151216 			/*
380348258c6bSjp151216 			 * If there were non-wildcard rules where
380448258c6bSjp151216 			 * Windows identity doesn't exist
380548258c6bSjp151216 			 * return no mapping.
380648258c6bSjp151216 			 */
380748258c6bSjp151216 			if (non_wild_match)
380848258c6bSjp151216 				retcode = IDMAP_ERR_NOMAPPING;
380948258c6bSjp151216 			else
3810c5c4113dSnw141292 				retcode = IDMAP_ERR_NOTFOUND;
3811c5c4113dSnw141292 			goto out;
3812c5c4113dSnw141292 		} else {
3813c5c4113dSnw141292 			(void) sqlite_finalize(vm, &errmsg);
3814c5c4113dSnw141292 			vm = NULL;
3815cd37da74Snw141292 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
3816cd37da74Snw141292 			    CHECK_NULL(errmsg));
3817c5c4113dSnw141292 			sqlite_freemem(errmsg);
3818c5c4113dSnw141292 			retcode = IDMAP_ERR_INTERNAL;
3819c5c4113dSnw141292 			goto out;
3820c5c4113dSnw141292 		}
3821c5c4113dSnw141292 	}
3822c5c4113dSnw141292 
3823c5c4113dSnw141292 out:
382462c60062Sbaban 	if (sql != NULL)
3825c5c4113dSnw141292 		sqlite_freemem(sql);
382648258c6bSjp151216 	res->info.how.map_type = IDMAP_MAP_TYPE_RULE_BASED;
3827c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
3828cd37da74Snw141292 		res->id.idtype = is_wuser ? IDMAP_USID : IDMAP_GSID;
3829cd37da74Snw141292 
383062c60062Sbaban 		if (values[2] != NULL)
3831c5c4113dSnw141292 			res->direction =
3832651c0131Sbaban 			    (strtol(values[2], &end, 10) == 0)?
3833651c0131Sbaban 			    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
3834c5c4113dSnw141292 		else
3835651c0131Sbaban 			res->direction = IDMAP_DIRECTION_U2W;
38368e228215Sdm199847 
3837cd37da74Snw141292 		req->id2name = canonname;
38388e228215Sdm199847 		if (req->id2name != NULL) {
38398e228215Sdm199847 			req->id2domain = strdup(windomain);
3840479ac375Sdm199847 			if (req->id2domain == NULL)
3841479ac375Sdm199847 				retcode = IDMAP_ERR_MEMORY;
38428e228215Sdm199847 		}
3843c5c4113dSnw141292 	}
3844479ac375Sdm199847 
3845479ac375Sdm199847 	if (retcode == IDMAP_SUCCESS) {
384648258c6bSjp151216 		idmap_namerule_set(rule, values[1], values[0], values[4],
384748258c6bSjp151216 		    is_user, strtol(values[3], &end, 10),
384848258c6bSjp151216 		    strtol(values[5], &end, 10),
384948258c6bSjp151216 		    rule->direction);
385048258c6bSjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
3851c5c4113dSnw141292 	}
385262c60062Sbaban 	if (vm != NULL)
3853c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
3854c5c4113dSnw141292 	return (retcode);
3855c5c4113dSnw141292 }
3856c5c4113dSnw141292 
3857cd37da74Snw141292 /*
3858cd37da74Snw141292  * Convention when processing unix2win requests:
3859cd37da74Snw141292  *
3860cd37da74Snw141292  * Unix identity:
3861cd37da74Snw141292  * req->id1name =
3862cd37da74Snw141292  *              unixname if given otherwise unixname found will be placed
3863cd37da74Snw141292  *              here.
3864cd37da74Snw141292  * req->id1domain =
3865cd37da74Snw141292  *              NOT USED
3866cd37da74Snw141292  * req->id1.idtype =
3867cd37da74Snw141292  *              Given type (IDMAP_UID or IDMAP_GID)
3868cd37da74Snw141292  * req->id1..[uid or gid] =
3869cd37da74Snw141292  *              UID/GID if given otherwise UID/GID found will be placed here.
3870cd37da74Snw141292  *
3871cd37da74Snw141292  * Windows identity:
3872cd37da74Snw141292  * req->id2name =
3873cd37da74Snw141292  *              winname found will be placed here.
3874cd37da74Snw141292  * req->id2domain =
3875cd37da74Snw141292  *              windomain found will be placed here.
3876cd37da74Snw141292  * res->id.idtype =
3877cd37da74Snw141292  *              Target type initialized from req->id2.idtype. If
3878cd37da74Snw141292  *              it is IDMAP_SID then actual type (IDMAP_USID/GSID) found
3879cd37da74Snw141292  *              will be placed here.
3880cd37da74Snw141292  * req->id..sid.[prefix, rid] =
3881cd37da74Snw141292  *              SID found will be placed here.
3882cd37da74Snw141292  *
3883cd37da74Snw141292  * Others:
3884cd37da74Snw141292  * res->retcode =
3885cd37da74Snw141292  *              Return status for this request will be placed here.
3886cd37da74Snw141292  * res->direction =
3887cd37da74Snw141292  *              Direction found will be placed here. Direction
3888cd37da74Snw141292  *              meaning whether the resultant mapping is valid
3889cd37da74Snw141292  *              only from unix2win or bi-directional.
3890cd37da74Snw141292  * req->direction =
3891cd37da74Snw141292  *              INTERNAL USE. Used by idmapd to set various
3892cd37da74Snw141292  *              flags (_IDMAP_F_xxxx) to aid in processing
3893cd37da74Snw141292  *              of the request.
3894cd37da74Snw141292  * req->id2.idtype =
3895cd37da74Snw141292  *              INTERNAL USE. Initially this is the requested target
3896cd37da74Snw141292  *              type and is used to initialize res->id.idtype.
3897cd37da74Snw141292  *              ad_lookup_batch() uses this field temporarily to store
3898cd37da74Snw141292  *              sid_type obtained by the batched AD lookups and after
3899cd37da74Snw141292  *              use resets it to IDMAP_NONE to prevent xdr from
3900cd37da74Snw141292  *              mis-interpreting the contents of req->id2.
3901cd37da74Snw141292  * req->id2..[uid or gid or sid] =
3902cd37da74Snw141292  *              NOT USED
3903cd37da74Snw141292  */
3904cd37da74Snw141292 
3905cd37da74Snw141292 /*
3906cd37da74Snw141292  * This function does the following:
3907cd37da74Snw141292  * 1. Lookup well-known SIDs table.
3908cd37da74Snw141292  * 2. Lookup cache.
3909cd37da74Snw141292  * 3. Check if the client does not want new mapping to be allocated
3910cd37da74Snw141292  *    in which case this pass is the final pass.
3911e8c27ec8Sbaban  * 4. Set AD/NLDAP lookup flags if it determines that the next stage needs
3912e8c27ec8Sbaban  *    to do AD/NLDAP lookup.
3913cd37da74Snw141292  */
3914c5c4113dSnw141292 idmap_retcode
3915479ac375Sdm199847 pid2sid_first_pass(lookup_state_t *state, idmap_mapping *req,
3916479ac375Sdm199847 		idmap_id_res *res, int is_user, int getname)
3917cd37da74Snw141292 {
3918e8c27ec8Sbaban 	idmap_retcode	retcode;
3919e8c27ec8Sbaban 	bool_t		gen_localsid_on_err = FALSE;
3920c5c4113dSnw141292 
3921e8c27ec8Sbaban 	/* Initialize result */
3922c5c4113dSnw141292 	res->id.idtype = req->id2.idtype;
3923e8c27ec8Sbaban 	res->direction = IDMAP_DIRECTION_UNDEF;
3924c5c4113dSnw141292 
3925e8c27ec8Sbaban 	if (req->id2.idmap_id_u.sid.prefix != NULL) {
3926e8c27ec8Sbaban 		/* sanitize sidprefix */
3927e8c27ec8Sbaban 		free(req->id2.idmap_id_u.sid.prefix);
3928e8c27ec8Sbaban 		req->id2.idmap_id_u.sid.prefix = NULL;
3929e8c27ec8Sbaban 	}
3930e8c27ec8Sbaban 
393148258c6bSjp151216 	/* Find pid */
393248258c6bSjp151216 	if (req->id1.idmap_id_u.uid == SENTINEL_PID) {
393348258c6bSjp151216 		if (ns_lookup_byname(req->id1name, NULL, &req->id1)
393448258c6bSjp151216 		    != IDMAP_SUCCESS) {
393548258c6bSjp151216 			retcode = IDMAP_ERR_NOMAPPING;
393648258c6bSjp151216 			goto out;
393748258c6bSjp151216 		}
393848258c6bSjp151216 	}
393948258c6bSjp151216 
3940e8c27ec8Sbaban 	/* Lookup well-known SIDs table */
3941c5c4113dSnw141292 	retcode = lookup_wksids_pid2sid(req, res, is_user);
3942c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
3943c5c4113dSnw141292 		goto out;
3944c5c4113dSnw141292 
3945e8c27ec8Sbaban 	/* Lookup cache */
3946479ac375Sdm199847 	retcode = lookup_cache_pid2sid(state->cache, req, res, is_user,
3947479ac375Sdm199847 	    getname);
3948c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
3949c5c4113dSnw141292 		goto out;
3950c5c4113dSnw141292 
3951c5c4113dSnw141292 	/* Ephemeral ids cannot be allocated during pid2sid */
3952c5c4113dSnw141292 	if (IS_EPHEMERAL(req->id1.idmap_id_u.uid)) {
395362c60062Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
3954c5c4113dSnw141292 		goto out;
3955c5c4113dSnw141292 	}
3956c5c4113dSnw141292 
395748258c6bSjp151216 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req)) {
395848258c6bSjp151216 		retcode = IDMAP_ERR_NONEGENERATED;
395948258c6bSjp151216 		goto out;
396048258c6bSjp151216 	}
396148258c6bSjp151216 
396248258c6bSjp151216 	if (AVOID_NAMESERVICE(req)) {
3963e8c27ec8Sbaban 		gen_localsid_on_err = TRUE;
396462c60062Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
3965c5c4113dSnw141292 		goto out;
3966c5c4113dSnw141292 	}
3967c5c4113dSnw141292 
3968e8c27ec8Sbaban 	/* Set flags for the next stage */
3969e8c27ec8Sbaban 	if (AD_MODE(req->id1.idtype, state)) {
3970e8c27ec8Sbaban 		/*
3971e8c27ec8Sbaban 		 * If AD-based name mapping is enabled then the next stage
3972e8c27ec8Sbaban 		 * will need to lookup AD using unixname to get the
3973e8c27ec8Sbaban 		 * corresponding winname.
3974e8c27ec8Sbaban 		 */
3975e8c27ec8Sbaban 		if (req->id1name == NULL) {
3976e8c27ec8Sbaban 			/* Get unixname if only pid is given. */
3977e8c27ec8Sbaban 			retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid,
3978e8c27ec8Sbaban 			    is_user, &req->id1name);
3979479ac375Sdm199847 			if (retcode != IDMAP_SUCCESS) {
3980479ac375Sdm199847 				gen_localsid_on_err = TRUE;
3981e8c27ec8Sbaban 				goto out;
3982c5c4113dSnw141292 			}
3983479ac375Sdm199847 		}
3984e8c27ec8Sbaban 		req->direction |= _IDMAP_F_LOOKUP_AD;
3985e8c27ec8Sbaban 		state->ad_nqueries++;
3986e8c27ec8Sbaban 	} else if (NLDAP_OR_MIXED_MODE(req->id1.idtype, state)) {
3987e8c27ec8Sbaban 		/*
3988e8c27ec8Sbaban 		 * If native LDAP or mixed mode is enabled for name mapping
3989e8c27ec8Sbaban 		 * then the next stage will need to lookup native LDAP using
3990e8c27ec8Sbaban 		 * unixname/pid to get the corresponding winname.
3991e8c27ec8Sbaban 		 */
3992e8c27ec8Sbaban 		req->direction |= _IDMAP_F_LOOKUP_NLDAP;
3993e8c27ec8Sbaban 		state->nldap_nqueries++;
3994c5c4113dSnw141292 	}
3995c5c4113dSnw141292 
3996e8c27ec8Sbaban 	/*
3997e8c27ec8Sbaban 	 * Failed to find non-expired entry in cache. Set the flag to
3998e8c27ec8Sbaban 	 * indicate that we are not done yet.
3999e8c27ec8Sbaban 	 */
4000e8c27ec8Sbaban 	state->pid2sid_done = FALSE;
4001e8c27ec8Sbaban 	req->direction |= _IDMAP_F_NOTDONE;
4002e8c27ec8Sbaban 	retcode = IDMAP_SUCCESS;
4003e8c27ec8Sbaban 
4004e8c27ec8Sbaban out:
4005e8c27ec8Sbaban 	res->retcode = idmap_stat4prot(retcode);
4006e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
4007e8c27ec8Sbaban 		if (gen_localsid_on_err == TRUE)
400848258c6bSjp151216 			(void) generate_localsid(req, res, is_user, TRUE);
4009e8c27ec8Sbaban 	return (retcode);
4010e8c27ec8Sbaban }
4011e8c27ec8Sbaban 
4012e8c27ec8Sbaban idmap_retcode
4013479ac375Sdm199847 pid2sid_second_pass(lookup_state_t *state, idmap_mapping *req,
4014479ac375Sdm199847 	idmap_id_res *res, int is_user)
4015e8c27ec8Sbaban {
4016e8c27ec8Sbaban 	bool_t		gen_localsid_on_err = TRUE;
4017e8c27ec8Sbaban 	idmap_retcode	retcode = IDMAP_SUCCESS;
4018e8c27ec8Sbaban 
4019e8c27ec8Sbaban 	/* Check if second pass is needed */
4020e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
4021e8c27ec8Sbaban 		return (res->retcode);
4022e8c27ec8Sbaban 
4023e8c27ec8Sbaban 	/* Get status from previous pass */
4024e8c27ec8Sbaban 	retcode = res->retcode;
4025e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
4026e8c27ec8Sbaban 		goto out;
4027e8c27ec8Sbaban 
4028e8c27ec8Sbaban 	/*
4029e8c27ec8Sbaban 	 * If directory-based name mapping is enabled then the winname
4030e8c27ec8Sbaban 	 * may already have been retrieved from the AD object (AD-mode)
4031479ac375Sdm199847 	 * or from native LDAP object (nldap-mode or mixed-mode).
4032479ac375Sdm199847 	 * Note that if we have winname but no SID then it's an error
4033479ac375Sdm199847 	 * because this implies that the Native LDAP entry contains
4034479ac375Sdm199847 	 * winname which does not exist and it's better that we return
4035479ac375Sdm199847 	 * an error instead of doing rule-based mapping so that the user
4036479ac375Sdm199847 	 * can detect the issue and take appropriate action.
4037e8c27ec8Sbaban 	 */
4038479ac375Sdm199847 	if (req->id2name != NULL) {
4039479ac375Sdm199847 		/* Return notfound if we've winname but no SID. */
4040479ac375Sdm199847 		if (res->id.idmap_id_u.sid.prefix == NULL) {
4041479ac375Sdm199847 			retcode = IDMAP_ERR_NOTFOUND;
4042479ac375Sdm199847 			goto out;
4043479ac375Sdm199847 		}
4044e8c27ec8Sbaban 		if (AD_MODE(req->id1.idtype, state))
4045e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
4046e8c27ec8Sbaban 		else if (NLDAP_MODE(req->id1.idtype, state))
4047e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
4048e8c27ec8Sbaban 		else if (MIXED_MODE(req->id1.idtype, state))
4049e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
4050e8c27ec8Sbaban 		goto out;
4051479ac375Sdm199847 	} else if (res->id.idmap_id_u.sid.prefix != NULL) {
4052479ac375Sdm199847 		/*
4053479ac375Sdm199847 		 * We've SID but no winname. This is fine because
4054479ac375Sdm199847 		 * the caller may have only requested SID.
4055479ac375Sdm199847 		 */
4056479ac375Sdm199847 		goto out;
4057e8c27ec8Sbaban 	}
4058e8c27ec8Sbaban 
4059479ac375Sdm199847 	/* Free any mapping info from Directory based mapping */
4060479ac375Sdm199847 	if (res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN)
4061479ac375Sdm199847 		idmap_info_free(&res->info);
4062479ac375Sdm199847 
4063e8c27ec8Sbaban 	if (req->id1name == NULL) {
4064e8c27ec8Sbaban 		/* Get unixname from name service */
4065e8c27ec8Sbaban 		retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid, is_user,
4066e8c27ec8Sbaban 		    &req->id1name);
4067e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS)
4068e8c27ec8Sbaban 			goto out;
4069e8c27ec8Sbaban 	} else if (req->id1.idmap_id_u.uid == SENTINEL_PID) {
4070e8c27ec8Sbaban 		/* Get pid from name service */
4071e8c27ec8Sbaban 		retcode = ns_lookup_byname(req->id1name, NULL, &req->id1);
4072e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS) {
4073e8c27ec8Sbaban 			gen_localsid_on_err = FALSE;
4074e8c27ec8Sbaban 			goto out;
4075e8c27ec8Sbaban 		}
4076e8c27ec8Sbaban 	}
4077e8c27ec8Sbaban 
4078e8c27ec8Sbaban 	/* Use unixname to evaluate local name-based mapping rules */
4079479ac375Sdm199847 	retcode = name_based_mapping_pid2sid(state, req->id1name, is_user,
4080c5c4113dSnw141292 	    req, res);
4081c5c4113dSnw141292 	if (retcode == IDMAP_ERR_NOTFOUND) {
408248258c6bSjp151216 		retcode = generate_localsid(req, res, is_user, FALSE);
4083e8c27ec8Sbaban 		gen_localsid_on_err = FALSE;
4084e8c27ec8Sbaban 	}
4085c5c4113dSnw141292 
4086c5c4113dSnw141292 out:
4087c5c4113dSnw141292 	res->retcode = idmap_stat4prot(retcode);
4088e8c27ec8Sbaban 	if (res->retcode != IDMAP_SUCCESS) {
4089e8c27ec8Sbaban 		req->direction = _IDMAP_F_DONE;
4090479ac375Sdm199847 		free(req->id2name);
4091479ac375Sdm199847 		req->id2name = NULL;
4092479ac375Sdm199847 		free(req->id2domain);
4093479ac375Sdm199847 		req->id2domain = NULL;
4094e8c27ec8Sbaban 		if (gen_localsid_on_err == TRUE)
409548258c6bSjp151216 			(void) generate_localsid(req, res, is_user, TRUE);
4096479ac375Sdm199847 		else
4097479ac375Sdm199847 			res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
4098e8c27ec8Sbaban 	}
4099e8c27ec8Sbaban 	if (!ARE_WE_DONE(req->direction))
4100e8c27ec8Sbaban 		state->pid2sid_done = FALSE;
4101c5c4113dSnw141292 	return (retcode);
4102c5c4113dSnw141292 }
4103c5c4113dSnw141292 
4104cd37da74Snw141292 static
4105cd37da74Snw141292 int
4106651c0131Sbaban copy_mapping_request(idmap_mapping *mapping, idmap_mapping *request)
4107c5c4113dSnw141292 {
4108651c0131Sbaban 	(void) memset(mapping, 0, sizeof (*mapping));
4109651c0131Sbaban 
4110c5c4113dSnw141292 	mapping->flag = request->flag;
4111e8c27ec8Sbaban 	mapping->direction = _IDMAP_F_DONE;
4112651c0131Sbaban 	mapping->id2.idtype = request->id2.idtype;
4113c5c4113dSnw141292 
4114c5c4113dSnw141292 	mapping->id1.idtype = request->id1.idtype;
4115cd37da74Snw141292 	if (IS_REQUEST_SID(*request, 1)) {
4116c5c4113dSnw141292 		mapping->id1.idmap_id_u.sid.rid =
4117c5c4113dSnw141292 		    request->id1.idmap_id_u.sid.rid;
4118651c0131Sbaban 		if (!EMPTY_STRING(request->id1.idmap_id_u.sid.prefix)) {
4119c5c4113dSnw141292 			mapping->id1.idmap_id_u.sid.prefix =
4120c5c4113dSnw141292 			    strdup(request->id1.idmap_id_u.sid.prefix);
4121651c0131Sbaban 			if (mapping->id1.idmap_id_u.sid.prefix == NULL)
41228e228215Sdm199847 				goto errout;
4123651c0131Sbaban 		}
4124c5c4113dSnw141292 	} else {
4125c5c4113dSnw141292 		mapping->id1.idmap_id_u.uid = request->id1.idmap_id_u.uid;
4126c5c4113dSnw141292 	}
4127c5c4113dSnw141292 
4128e8c27ec8Sbaban 	if (!EMPTY_STRING(request->id1domain)) {
41298e228215Sdm199847 		mapping->id1domain = strdup(request->id1domain);
41308e228215Sdm199847 		if (mapping->id1domain == NULL)
41318e228215Sdm199847 			goto errout;
4132e8c27ec8Sbaban 	}
4133c5c4113dSnw141292 
4134e8c27ec8Sbaban 	if (!EMPTY_STRING(request->id1name)) {
41358e228215Sdm199847 		mapping->id1name = strdup(request->id1name);
41368e228215Sdm199847 		if (mapping->id1name == NULL)
41378e228215Sdm199847 			goto errout;
4138e8c27ec8Sbaban 	}
4139c5c4113dSnw141292 
4140651c0131Sbaban 	/* We don't need the rest of the request i.e request->id2 */
4141651c0131Sbaban 	return (0);
4142c5c4113dSnw141292 
4143651c0131Sbaban errout:
41448e228215Sdm199847 	if (mapping->id1.idmap_id_u.sid.prefix != NULL)
4145651c0131Sbaban 		free(mapping->id1.idmap_id_u.sid.prefix);
41468e228215Sdm199847 	if (mapping->id1domain != NULL)
41478e228215Sdm199847 		free(mapping->id1domain);
41488e228215Sdm199847 	if (mapping->id1name != NULL)
41498e228215Sdm199847 		free(mapping->id1name);
4150651c0131Sbaban 
4151651c0131Sbaban 	(void) memset(mapping, 0, sizeof (*mapping));
4152651c0131Sbaban 	return (-1);
4153c5c4113dSnw141292 }
4154c5c4113dSnw141292 
4155c5c4113dSnw141292 
4156c5c4113dSnw141292 idmap_retcode
4157c5c4113dSnw141292 get_w2u_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
4158cd37da74Snw141292 		idmap_mapping *mapping)
4159cd37da74Snw141292 {
4160c5c4113dSnw141292 	idmap_id_res	idres;
4161c5c4113dSnw141292 	lookup_state_t	state;
4162dd5829d1Sbaban 	char		*cp;
4163c5c4113dSnw141292 	idmap_retcode	retcode;
4164c5c4113dSnw141292 	const char	*winname, *windomain;
4165c5c4113dSnw141292 
4166c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
4167c5c4113dSnw141292 	(void) memset(&state, 0, sizeof (state));
4168479ac375Sdm199847 	state.cache = cache;
4169479ac375Sdm199847 	state.db = db;
4170c5c4113dSnw141292 
4171e8c27ec8Sbaban 	/* Get directory-based name mapping info */
4172479ac375Sdm199847 	retcode = load_cfg_in_state(&state);
4173e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
4174c5c4113dSnw141292 		goto out;
4175c5c4113dSnw141292 
4176e8c27ec8Sbaban 	/*
4177e8c27ec8Sbaban 	 * Copy data from "request" to "mapping". Note that
4178e8c27ec8Sbaban 	 * empty strings are not copied from "request" to
4179e8c27ec8Sbaban 	 * "mapping" and therefore the coresponding strings in
4180e8c27ec8Sbaban 	 * "mapping" will be NULL. This eliminates having to
4181e8c27ec8Sbaban 	 * check for empty strings henceforth.
4182e8c27ec8Sbaban 	 */
4183651c0131Sbaban 	if (copy_mapping_request(mapping, request) < 0) {
4184651c0131Sbaban 		retcode = IDMAP_ERR_MEMORY;
4185651c0131Sbaban 		goto out;
4186651c0131Sbaban 	}
4187c5c4113dSnw141292 
41888e228215Sdm199847 	winname = mapping->id1name;
41898e228215Sdm199847 	windomain = mapping->id1domain;
4190c5c4113dSnw141292 
4191e8c27ec8Sbaban 	if (winname == NULL && windomain != NULL) {
4192c5c4113dSnw141292 		retcode = IDMAP_ERR_ARG;
4193c5c4113dSnw141292 		goto out;
4194c5c4113dSnw141292 	}
4195c5c4113dSnw141292 
4196e8c27ec8Sbaban 	/* Need atleast winname or sid to proceed */
4197e8c27ec8Sbaban 	if (winname == NULL && mapping->id1.idmap_id_u.sid.prefix == NULL) {
4198e8c27ec8Sbaban 		retcode = IDMAP_ERR_ARG;
4199e8c27ec8Sbaban 		goto out;
4200e8c27ec8Sbaban 	}
4201e8c27ec8Sbaban 
4202e8c27ec8Sbaban 	/*
4203e8c27ec8Sbaban 	 * If domainname is not given but we have a fully qualified
4204e8c27ec8Sbaban 	 * winname then extract the domainname from the winname,
4205e8c27ec8Sbaban 	 * otherwise use the default_domain from the config
4206e8c27ec8Sbaban 	 */
4207e8c27ec8Sbaban 	if (winname != NULL && windomain == NULL) {
42088e228215Sdm199847 		retcode = IDMAP_SUCCESS;
4209dd5829d1Sbaban 		if ((cp = strchr(winname, '@')) != NULL) {
4210dd5829d1Sbaban 			*cp = '\0';
42118e228215Sdm199847 			mapping->id1domain = strdup(cp + 1);
42128e228215Sdm199847 			if (mapping->id1domain == NULL)
42138e228215Sdm199847 				retcode = IDMAP_ERR_MEMORY;
4214e8c27ec8Sbaban 		} else if (lookup_wksids_name2sid(winname, NULL, NULL, NULL,
4215e8c27ec8Sbaban 		    NULL) != IDMAP_SUCCESS) {
421682da9f60Sbaban 			if (state.defdom == NULL) {
421782da9f60Sbaban 				/*
421882da9f60Sbaban 				 * We have a non-qualified winname which is
421982da9f60Sbaban 				 * neither the name of a well-known SID nor
422082da9f60Sbaban 				 * there is a default domain with which we can
422182da9f60Sbaban 				 * qualify it.
422282da9f60Sbaban 				 */
422382da9f60Sbaban 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
422482da9f60Sbaban 			} else {
4225479ac375Sdm199847 				mapping->id1domain = strdup(state.defdom);
42268e228215Sdm199847 				if (mapping->id1domain == NULL)
42278e228215Sdm199847 					retcode = IDMAP_ERR_MEMORY;
42288e228215Sdm199847 			}
422982da9f60Sbaban 		}
4230c5c4113dSnw141292 		if (retcode != IDMAP_SUCCESS)
4231c5c4113dSnw141292 			goto out;
4232c5c4113dSnw141292 	}
4233c5c4113dSnw141292 
4234e8c27ec8Sbaban 	/*
4235e8c27ec8Sbaban 	 * First pass looks up the well-known SIDs table and cache
4236e8c27ec8Sbaban 	 * and handles localSIDs
4237e8c27ec8Sbaban 	 */
4238c5c4113dSnw141292 	state.sid2pid_done = TRUE;
4239479ac375Sdm199847 	retcode = sid2pid_first_pass(&state, mapping, &idres);
4240c5c4113dSnw141292 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
4241c5c4113dSnw141292 		goto out;
4242c5c4113dSnw141292 
4243479ac375Sdm199847 	/* AD lookup */
4244e8c27ec8Sbaban 	if (state.ad_nqueries > 0) {
4245479ac375Sdm199847 		retcode = ad_lookup_one(&state, mapping, &idres);
4246e8c27ec8Sbaban 		if (IDMAP_ERROR(retcode))
4247e8c27ec8Sbaban 			goto out;
4248c5c4113dSnw141292 	}
4249c5c4113dSnw141292 
4250479ac375Sdm199847 	/* nldap lookup */
4251479ac375Sdm199847 	if (state.nldap_nqueries > 0) {
4252479ac375Sdm199847 		retcode = nldap_lookup_one(&state, mapping, &idres);
4253479ac375Sdm199847 		if (IDMAP_FATAL_ERROR(retcode))
4254e8c27ec8Sbaban 			goto out;
425548258c6bSjp151216 	}
4256e8c27ec8Sbaban 
4257e8c27ec8Sbaban 	/* Next pass performs name-based mapping and ephemeral mapping. */
4258c5c4113dSnw141292 	state.sid2pid_done = TRUE;
4259479ac375Sdm199847 	retcode = sid2pid_second_pass(&state, mapping, &idres);
4260c5c4113dSnw141292 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
4261c5c4113dSnw141292 		goto out;
4262c5c4113dSnw141292 
4263c5c4113dSnw141292 	/* Update cache */
4264479ac375Sdm199847 	(void) update_cache_sid2pid(&state, mapping, &idres);
4265c5c4113dSnw141292 
4266c5c4113dSnw141292 out:
4267e8c27ec8Sbaban 	/*
4268e8c27ec8Sbaban 	 * Note that "mapping" is returned to the client. Therefore
4269e8c27ec8Sbaban 	 * copy whatever we have in "idres" to mapping->id2 and
4270e8c27ec8Sbaban 	 * free idres.
4271e8c27ec8Sbaban 	 */
4272c5c4113dSnw141292 	mapping->direction = idres.direction;
4273c5c4113dSnw141292 	mapping->id2 = idres.id;
427448258c6bSjp151216 	if (mapping->flag & IDMAP_REQ_FLG_MAPPING_INFO ||
427548258c6bSjp151216 	    retcode != IDMAP_SUCCESS)
427648258c6bSjp151216 		(void) idmap_info_mov(&mapping->info, &idres.info);
427748258c6bSjp151216 	else
427848258c6bSjp151216 		idmap_info_free(&idres.info);
4279c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
4280e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
428162c60062Sbaban 		mapping->id2.idmap_id_u.uid = UID_NOBODY;
4282c5c4113dSnw141292 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
4283e8c27ec8Sbaban 	cleanup_lookup_state(&state);
4284c5c4113dSnw141292 	return (retcode);
4285c5c4113dSnw141292 }
4286c5c4113dSnw141292 
4287c5c4113dSnw141292 idmap_retcode
4288c5c4113dSnw141292 get_u2w_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
4289cd37da74Snw141292 		idmap_mapping *mapping, int is_user)
4290cd37da74Snw141292 {
4291c5c4113dSnw141292 	idmap_id_res	idres;
4292c5c4113dSnw141292 	lookup_state_t	state;
4293c5c4113dSnw141292 	idmap_retcode	retcode;
4294c5c4113dSnw141292 
4295c5c4113dSnw141292 	/*
4296c5c4113dSnw141292 	 * In order to re-use the pid2sid code, we convert
4297c5c4113dSnw141292 	 * our input data into structs that are expected by
4298c5c4113dSnw141292 	 * pid2sid_first_pass.
4299c5c4113dSnw141292 	 */
4300c5c4113dSnw141292 
4301c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
4302c5c4113dSnw141292 	(void) memset(&state, 0, sizeof (state));
4303479ac375Sdm199847 	state.cache = cache;
4304479ac375Sdm199847 	state.db = db;
4305c5c4113dSnw141292 
4306e8c27ec8Sbaban 	/* Get directory-based name mapping info */
4307479ac375Sdm199847 	retcode = load_cfg_in_state(&state);
4308e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
4309e8c27ec8Sbaban 		goto out;
4310e8c27ec8Sbaban 
4311e8c27ec8Sbaban 	/*
4312e8c27ec8Sbaban 	 * Copy data from "request" to "mapping". Note that
4313e8c27ec8Sbaban 	 * empty strings are not copied from "request" to
4314e8c27ec8Sbaban 	 * "mapping" and therefore the coresponding strings in
4315e8c27ec8Sbaban 	 * "mapping" will be NULL. This eliminates having to
4316e8c27ec8Sbaban 	 * check for empty strings henceforth.
4317e8c27ec8Sbaban 	 */
4318651c0131Sbaban 	if (copy_mapping_request(mapping, request) < 0) {
4319651c0131Sbaban 		retcode = IDMAP_ERR_MEMORY;
4320651c0131Sbaban 		goto out;
4321651c0131Sbaban 	}
4322c5c4113dSnw141292 
4323e8c27ec8Sbaban 	/*
4324e8c27ec8Sbaban 	 * For unix to windows mapping request, we need atleast a
4325e8c27ec8Sbaban 	 * unixname or uid/gid to proceed
4326e8c27ec8Sbaban 	 */
4327e8c27ec8Sbaban 	if (mapping->id1name == NULL &&
4328cf5b5989Sdm199847 	    mapping->id1.idmap_id_u.uid == SENTINEL_PID) {
4329c5c4113dSnw141292 		retcode = IDMAP_ERR_ARG;
4330c5c4113dSnw141292 		goto out;
4331c5c4113dSnw141292 	}
4332c5c4113dSnw141292 
4333e8c27ec8Sbaban 	/* First pass looks up cache and well-known SIDs */
4334e8c27ec8Sbaban 	state.pid2sid_done = TRUE;
4335479ac375Sdm199847 	retcode = pid2sid_first_pass(&state, mapping, &idres, is_user, 1);
4336e8c27ec8Sbaban 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
4337c5c4113dSnw141292 		goto out;
4338e8c27ec8Sbaban 
4339479ac375Sdm199847 	/* nldap lookup */
4340e8c27ec8Sbaban 	if (state.nldap_nqueries > 0) {
4341479ac375Sdm199847 		retcode = nldap_lookup_one(&state, mapping, &idres);
4342e8c27ec8Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
4343c5c4113dSnw141292 			goto out;
4344479ac375Sdm199847 	}
4345e8c27ec8Sbaban 
4346479ac375Sdm199847 	/* AD lookup */
4347479ac375Sdm199847 	if (state.ad_nqueries > 0) {
4348479ac375Sdm199847 		retcode = ad_lookup_one(&state, mapping, &idres);
4349e8c27ec8Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
4350e8c27ec8Sbaban 			goto out;
4351c5c4113dSnw141292 	}
4352c5c4113dSnw141292 
4353e8c27ec8Sbaban 	/*
4354e8c27ec8Sbaban 	 * Next pass processes the result of the preceding passes/lookups.
4355e8c27ec8Sbaban 	 * It returns if there's nothing more to be done otherwise it
4356e8c27ec8Sbaban 	 * evaluates local name-based mapping rules
4357e8c27ec8Sbaban 	 */
4358c5c4113dSnw141292 	state.pid2sid_done = TRUE;
4359479ac375Sdm199847 	retcode = pid2sid_second_pass(&state, mapping, &idres, is_user);
4360c5c4113dSnw141292 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
4361c5c4113dSnw141292 		goto out;
4362c5c4113dSnw141292 
4363c5c4113dSnw141292 	/* Update cache */
4364479ac375Sdm199847 	(void) update_cache_pid2sid(&state, mapping, &idres);
4365c5c4113dSnw141292 
4366c5c4113dSnw141292 out:
4367e8c27ec8Sbaban 	/*
4368e8c27ec8Sbaban 	 * Note that "mapping" is returned to the client. Therefore
4369e8c27ec8Sbaban 	 * copy whatever we have in "idres" to mapping->id2 and
4370e8c27ec8Sbaban 	 * free idres.
4371e8c27ec8Sbaban 	 */
4372c5c4113dSnw141292 	mapping->direction = idres.direction;
4373c5c4113dSnw141292 	mapping->id2 = idres.id;
437448258c6bSjp151216 	if (mapping->flag & IDMAP_REQ_FLG_MAPPING_INFO ||
437548258c6bSjp151216 	    retcode != IDMAP_SUCCESS)
437648258c6bSjp151216 		(void) idmap_info_mov(&mapping->info, &idres.info);
437748258c6bSjp151216 	else
437848258c6bSjp151216 		idmap_info_free(&idres.info);
4379c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
4380c5c4113dSnw141292 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
4381e8c27ec8Sbaban 	cleanup_lookup_state(&state);
4382e8c27ec8Sbaban 	return (retcode);
4383e8c27ec8Sbaban }
4384e8c27ec8Sbaban 
4385479ac375Sdm199847 /*ARGSUSED*/
4386e8c27ec8Sbaban static
4387e8c27ec8Sbaban idmap_retcode
4388479ac375Sdm199847 ad_lookup_one(lookup_state_t *state, idmap_mapping *req, idmap_id_res *res)
4389e8c27ec8Sbaban {
4390479ac375Sdm199847 	idmap_mapping_batch	batch;
4391479ac375Sdm199847 	idmap_ids_res		result;
4392e8c27ec8Sbaban 
4393479ac375Sdm199847 	batch.idmap_mapping_batch_len = 1;
4394479ac375Sdm199847 	batch.idmap_mapping_batch_val = req;
4395479ac375Sdm199847 	result.ids.ids_len = 1;
4396479ac375Sdm199847 	result.ids.ids_val = res;
4397479ac375Sdm199847 	return (ad_lookup_batch(state, &batch, &result));
4398c5c4113dSnw141292 }
4399