xref: /titanic_50/usr/src/cmd/idmap/idmapd/dbutils.c (revision 349d5d8f2e43f7f425bc3d025dda555187160ab7)
1c5c4113dSnw141292 /*
2c5c4113dSnw141292  * CDDL HEADER START
3c5c4113dSnw141292  *
4c5c4113dSnw141292  * The contents of this file are subject to the terms of the
5c5c4113dSnw141292  * Common Development and Distribution License (the "License").
6c5c4113dSnw141292  * You may not use this file except in compliance with the License.
7c5c4113dSnw141292  *
8c5c4113dSnw141292  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9c5c4113dSnw141292  * or http://www.opensolaris.org/os/licensing.
10c5c4113dSnw141292  * See the License for the specific language governing permissions
11c5c4113dSnw141292  * and limitations under the License.
12c5c4113dSnw141292  *
13c5c4113dSnw141292  * When distributing Covered Code, include this CDDL HEADER in each
14c5c4113dSnw141292  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15c5c4113dSnw141292  * If applicable, add the following below this CDDL HEADER, with the
16c5c4113dSnw141292  * fields enclosed by brackets "[]" replaced with your own identifying
17c5c4113dSnw141292  * information: Portions Copyright [yyyy] [name of copyright owner]
18c5c4113dSnw141292  *
19c5c4113dSnw141292  * CDDL HEADER END
20c5c4113dSnw141292  */
21c5c4113dSnw141292 /*
22042addd6Sbaban  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23c5c4113dSnw141292  * Use is subject to license terms.
24c5c4113dSnw141292  */
25c5c4113dSnw141292 
26c5c4113dSnw141292 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27c5c4113dSnw141292 
28c5c4113dSnw141292 /*
29c5c4113dSnw141292  * Database related utility routines
30c5c4113dSnw141292  */
31c5c4113dSnw141292 
32c5c4113dSnw141292 #include <stdio.h>
33c5c4113dSnw141292 #include <stdlib.h>
34c5c4113dSnw141292 #include <string.h>
35c5c4113dSnw141292 #include <errno.h>
36c5c4113dSnw141292 #include <sys/types.h>
37c5c4113dSnw141292 #include <sys/stat.h>
38c5c4113dSnw141292 #include <rpc/rpc.h>
39c5c4113dSnw141292 #include <sys/sid.h>
40c5c4113dSnw141292 #include <time.h>
41c5c4113dSnw141292 #include <pwd.h>
42c5c4113dSnw141292 #include <grp.h>
4384decf41Sjp151216 #include <pthread.h>
4484decf41Sjp151216 #include <assert.h>
45cd37da74Snw141292 #include <sys/u8_textprep.h>
46c5c4113dSnw141292 
47c5c4113dSnw141292 #include "idmapd.h"
48c5c4113dSnw141292 #include "adutils.h"
49c5c4113dSnw141292 #include "string.h"
50c5c4113dSnw141292 #include "idmap_priv.h"
51cd37da74Snw141292 #include "schema.h"
52e8c27ec8Sbaban #include "nldaputils.h"
53c5c4113dSnw141292 
5484decf41Sjp151216 
55c5c4113dSnw141292 static idmap_retcode sql_compile_n_step_once(sqlite *, char *,
56c5c4113dSnw141292 		sqlite_vm **, int *, int, const char ***);
57cd37da74Snw141292 static idmap_retcode lookup_wksids_name2sid(const char *, char **, char **,
5862c60062Sbaban 		idmap_rid_t *, int *);
59e8c27ec8Sbaban static idmap_retcode ad_lookup(lookup_state_t *, idmap_mapping *,
60e8c27ec8Sbaban 		idmap_id_res *, int, int, int);
61e8c27ec8Sbaban static idmap_retcode lookup_localsid2pid(idmap_mapping *, idmap_id_res *);
62e8c27ec8Sbaban static idmap_retcode lookup_cache_name2sid(sqlite *, const char *,
63e8c27ec8Sbaban 		const char *, char **, char **, idmap_rid_t *, int *);
64e8c27ec8Sbaban 
65c5c4113dSnw141292 
66c5c4113dSnw141292 #define	EMPTY_NAME(name)	(*name == 0 || strcmp(name, "\"\"") == 0)
67c5c4113dSnw141292 
68c5c4113dSnw141292 #define	DO_NOT_ALLOC_NEW_ID_MAPPING(req)\
69c5c4113dSnw141292 		(req->flag & IDMAP_REQ_FLG_NO_NEW_ID_ALLOC)
70c5c4113dSnw141292 
71c5c4113dSnw141292 #define	AVOID_NAMESERVICE(req)\
72c5c4113dSnw141292 		(req->flag & IDMAP_REQ_FLG_NO_NAMESERVICE)
73c5c4113dSnw141292 
74e8c27ec8Sbaban #define	IS_EPHEMERAL(pid)	(pid > INT32_MAX && pid != SENTINEL_PID)
75c5c4113dSnw141292 
76c5c4113dSnw141292 #define	LOCALRID_MIN	1000
77c5c4113dSnw141292 
78c5c4113dSnw141292 
79c5c4113dSnw141292 typedef enum init_db_option {
80c5c4113dSnw141292 	FAIL_IF_CORRUPT = 0,
81c5c4113dSnw141292 	REMOVE_IF_CORRUPT = 1
82c5c4113dSnw141292 } init_db_option_t;
83c5c4113dSnw141292 
8484decf41Sjp151216 /*
85e8c27ec8Sbaban  * Data structure to store well-known SIDs and
86e8c27ec8Sbaban  * associated mappings (if any)
87e8c27ec8Sbaban  */
88e8c27ec8Sbaban typedef struct wksids_table {
89e8c27ec8Sbaban 	const char	*sidprefix;
90e8c27ec8Sbaban 	uint32_t	rid;
91e8c27ec8Sbaban 	const char	*winname;
92e8c27ec8Sbaban 	int		is_wuser;
93e8c27ec8Sbaban 	uid_t		pid;
94e8c27ec8Sbaban 	int		is_user;
95e8c27ec8Sbaban 	int		direction;
96e8c27ec8Sbaban } wksids_table_t;
97e8c27ec8Sbaban 
98e8c27ec8Sbaban /*
9984decf41Sjp151216  * Thread specfic data to hold the database handles so that the
10084decf41Sjp151216  * databaes are not opened and closed for every request. It also
10184decf41Sjp151216  * contains the sqlite busy handler structure.
10284decf41Sjp151216  */
10384decf41Sjp151216 
10484decf41Sjp151216 struct idmap_busy {
10584decf41Sjp151216 	const char *name;
10684decf41Sjp151216 	const int *delays;
10784decf41Sjp151216 	int delay_size;
10884decf41Sjp151216 	int total;
10984decf41Sjp151216 	int sec;
11084decf41Sjp151216 };
11184decf41Sjp151216 
11284decf41Sjp151216 
11384decf41Sjp151216 typedef struct idmap_tsd {
11484decf41Sjp151216 	sqlite *db_db;
11584decf41Sjp151216 	sqlite *cache_db;
11684decf41Sjp151216 	struct idmap_busy cache_busy;
11784decf41Sjp151216 	struct idmap_busy db_busy;
11884decf41Sjp151216 } idmap_tsd_t;
11984decf41Sjp151216 
12084decf41Sjp151216 
12184decf41Sjp151216 
12284decf41Sjp151216 static const int cache_delay_table[] =
12384decf41Sjp151216 		{ 1, 2, 5, 10, 15, 20, 25, 30,  35,  40,
12484decf41Sjp151216 		50,  50, 60, 70, 80, 90, 100};
12584decf41Sjp151216 
12684decf41Sjp151216 static const int db_delay_table[] =
12784decf41Sjp151216 		{ 5, 10, 15, 20, 30,  40,  55,  70, 100};
12884decf41Sjp151216 
12984decf41Sjp151216 
13084decf41Sjp151216 static pthread_key_t	idmap_tsd_key;
13184decf41Sjp151216 
13284decf41Sjp151216 void
13384decf41Sjp151216 idmap_tsd_destroy(void *key)
13484decf41Sjp151216 {
13584decf41Sjp151216 
13684decf41Sjp151216 	idmap_tsd_t	*tsd = (idmap_tsd_t *)key;
13784decf41Sjp151216 	if (tsd) {
13884decf41Sjp151216 		if (tsd->db_db)
13984decf41Sjp151216 			(void) sqlite_close(tsd->db_db);
14084decf41Sjp151216 		if (tsd->cache_db)
14184decf41Sjp151216 			(void) sqlite_close(tsd->cache_db);
14284decf41Sjp151216 		free(tsd);
14384decf41Sjp151216 	}
14484decf41Sjp151216 }
14584decf41Sjp151216 
14684decf41Sjp151216 int
147cd37da74Snw141292 idmap_init_tsd_key(void)
148cd37da74Snw141292 {
14984decf41Sjp151216 	return (pthread_key_create(&idmap_tsd_key, idmap_tsd_destroy));
15084decf41Sjp151216 }
15184decf41Sjp151216 
15284decf41Sjp151216 
15384decf41Sjp151216 
15484decf41Sjp151216 idmap_tsd_t *
15584decf41Sjp151216 idmap_get_tsd(void)
15684decf41Sjp151216 {
15784decf41Sjp151216 	idmap_tsd_t	*tsd;
15884decf41Sjp151216 
15984decf41Sjp151216 	if ((tsd = pthread_getspecific(idmap_tsd_key)) == NULL) {
16084decf41Sjp151216 		/* No thread specific data so create it */
16184decf41Sjp151216 		if ((tsd = malloc(sizeof (*tsd))) != NULL) {
16284decf41Sjp151216 			/* Initialize thread specific data */
16384decf41Sjp151216 			(void) memset(tsd, 0, sizeof (*tsd));
16484decf41Sjp151216 			/* save the trhread specific data */
16584decf41Sjp151216 			if (pthread_setspecific(idmap_tsd_key, tsd) != 0) {
16684decf41Sjp151216 				/* Can't store key */
16784decf41Sjp151216 				free(tsd);
16884decf41Sjp151216 				tsd = NULL;
16984decf41Sjp151216 			}
17084decf41Sjp151216 		} else {
17184decf41Sjp151216 			tsd = NULL;
17284decf41Sjp151216 		}
17384decf41Sjp151216 	}
17484decf41Sjp151216 
17584decf41Sjp151216 	return (tsd);
17684decf41Sjp151216 }
17784decf41Sjp151216 
178cd37da74Snw141292 /*
179cd37da74Snw141292  * A simple wrapper around u8_textprep_str() that returns the Unicode
180cd37da74Snw141292  * lower-case version of some string.  The result must be freed.
181cd37da74Snw141292  */
182cd37da74Snw141292 char *
183cd37da74Snw141292 tolower_u8(const char *s)
184cd37da74Snw141292 {
185cd37da74Snw141292 	char *res = NULL;
186cd37da74Snw141292 	char *outs;
187cd37da74Snw141292 	size_t inlen, outlen, inbytesleft, outbytesleft;
188cd37da74Snw141292 	int rc, err;
189cd37da74Snw141292 
190cd37da74Snw141292 	/*
191cd37da74Snw141292 	 * u8_textprep_str() does not allocate memory.  The input and
192cd37da74Snw141292 	 * output buffers may differ in size (though that would be more
193cd37da74Snw141292 	 * likely when normalization is done).  We have to loop over it...
194cd37da74Snw141292 	 *
195cd37da74Snw141292 	 * To improve the chances that we can avoid looping we add 10
196cd37da74Snw141292 	 * bytes of output buffer room the first go around.
197cd37da74Snw141292 	 */
198cd37da74Snw141292 	inlen = inbytesleft = strlen(s);
199cd37da74Snw141292 	outlen = outbytesleft = inlen + 10;
200cd37da74Snw141292 	if ((res = malloc(outlen)) == NULL)
201cd37da74Snw141292 		return (NULL);
202cd37da74Snw141292 	outs = res;
203cd37da74Snw141292 
204cd37da74Snw141292 	while ((rc = u8_textprep_str((char *)s, &inbytesleft, outs,
205cd37da74Snw141292 	    &outbytesleft, U8_TEXTPREP_TOLOWER, U8_UNICODE_LATEST, &err)) < 0 &&
206cd37da74Snw141292 	    err == E2BIG) {
207cd37da74Snw141292 		if ((res = realloc(res, outlen + inbytesleft)) == NULL)
208cd37da74Snw141292 			return (NULL);
209cd37da74Snw141292 		/* adjust input/output buffer pointers */
210cd37da74Snw141292 		s += (inlen - inbytesleft);
211cd37da74Snw141292 		outs = res + outlen - outbytesleft;
212cd37da74Snw141292 		/* adjust outbytesleft and outlen */
213cd37da74Snw141292 		outlen += inbytesleft;
214cd37da74Snw141292 		outbytesleft += inbytesleft;
215cd37da74Snw141292 	}
216cd37da74Snw141292 
217cd37da74Snw141292 	if (rc < 0) {
218cd37da74Snw141292 		free(res);
219cd37da74Snw141292 		res = NULL;
220cd37da74Snw141292 		return (NULL);
221cd37da74Snw141292 	}
222cd37da74Snw141292 
223cd37da74Snw141292 	res[outlen - outbytesleft] = '\0';
224cd37da74Snw141292 
225cd37da74Snw141292 	return (res);
226cd37da74Snw141292 }
227cd37da74Snw141292 
228cd37da74Snw141292 static int sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
229cd37da74Snw141292 	const char *while_doing);
230cd37da74Snw141292 
231c5c4113dSnw141292 
232c5c4113dSnw141292 /*
233c5c4113dSnw141292  * Initialize 'dbname' using 'sql'
234c5c4113dSnw141292  */
235cd37da74Snw141292 static
236cd37da74Snw141292 int
237cd37da74Snw141292 init_db_instance(const char *dbname, int version,
238cd37da74Snw141292 	const char *detect_version_sql, char * const *sql,
239cd37da74Snw141292 	init_db_option_t opt, int *created, int *upgraded)
240c5c4113dSnw141292 {
241cd37da74Snw141292 	int rc, curr_version;
242cd37da74Snw141292 	int tries = 1;
243cd37da74Snw141292 	int prio = LOG_NOTICE;
244c5c4113dSnw141292 	sqlite *db = NULL;
245cd37da74Snw141292 	char *errmsg = NULL;
246c5c4113dSnw141292 
247cd37da74Snw141292 	*created = 0;
248cd37da74Snw141292 	*upgraded = 0;
249c5c4113dSnw141292 
250cd37da74Snw141292 	if (opt == REMOVE_IF_CORRUPT)
251cd37da74Snw141292 		tries = 3;
252cd37da74Snw141292 
253cd37da74Snw141292 rinse_repeat:
254cd37da74Snw141292 	if (tries == 0) {
255cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to initialize db %s", dbname);
256c5c4113dSnw141292 		return (-1);
257cd37da74Snw141292 	}
258cd37da74Snw141292 	if (tries-- == 1)
259cd37da74Snw141292 		/* Last try, log errors */
260cd37da74Snw141292 		prio = LOG_ERR;
261c5c4113dSnw141292 
262cd37da74Snw141292 	db = sqlite_open(dbname, 0600, &errmsg);
263cd37da74Snw141292 	if (db == NULL) {
264cd37da74Snw141292 		idmapdlog(prio, "Error creating database %s (%s)",
265cd37da74Snw141292 		    dbname, CHECK_NULL(errmsg));
266cd37da74Snw141292 		sqlite_freemem(errmsg);
267cd37da74Snw141292 		if (opt == REMOVE_IF_CORRUPT)
268c5c4113dSnw141292 			(void) unlink(dbname);
269cd37da74Snw141292 		goto rinse_repeat;
270c5c4113dSnw141292 	}
271c5c4113dSnw141292 
272c5c4113dSnw141292 	sqlite_busy_timeout(db, 3000);
273cd37da74Snw141292 
274cd37da74Snw141292 	/* Detect current version of schema in the db, if any */
275cd37da74Snw141292 	curr_version = 0;
276cd37da74Snw141292 	if (detect_version_sql != NULL) {
277cd37da74Snw141292 		char *end, **results;
278cd37da74Snw141292 		int nrow;
279cd37da74Snw141292 
280cd37da74Snw141292 #ifdef	IDMAPD_DEBUG
281cd37da74Snw141292 		(void) fprintf(stderr, "Schema version detection SQL: %s\n",
282cd37da74Snw141292 		    detect_version_sql);
283cd37da74Snw141292 #endif	/* IDMAPD_DEBUG */
284cd37da74Snw141292 		rc = sqlite_get_table(db, detect_version_sql, &results,
285cd37da74Snw141292 		    &nrow, NULL, &errmsg);
286cd37da74Snw141292 		if (rc != SQLITE_OK) {
287cd37da74Snw141292 			idmapdlog(prio,
288cd37da74Snw141292 			    "Error detecting schema version of db %s (%s)",
289cd37da74Snw141292 			    dbname, errmsg);
290cd37da74Snw141292 			sqlite_freemem(errmsg);
291cd37da74Snw141292 			sqlite_free_table(results);
292c5c4113dSnw141292 			sqlite_close(db);
293cd37da74Snw141292 			return (-1);
294cd37da74Snw141292 		}
295cd37da74Snw141292 		if (nrow != 1) {
296cd37da74Snw141292 			idmapdlog(prio,
297cd37da74Snw141292 			    "Error detecting schema version of db %s", dbname);
298cd37da74Snw141292 			sqlite_close(db);
299cd37da74Snw141292 			sqlite_free_table(results);
300cd37da74Snw141292 			return (-1);
301cd37da74Snw141292 		}
302cd37da74Snw141292 		curr_version = strtol(results[1], &end, 10);
303cd37da74Snw141292 		sqlite_free_table(results);
304c5c4113dSnw141292 	}
305c5c4113dSnw141292 
306cd37da74Snw141292 	if (curr_version < 0) {
307cd37da74Snw141292 		if (opt == REMOVE_IF_CORRUPT)
308cd37da74Snw141292 			(void) unlink(dbname);
309cd37da74Snw141292 		goto rinse_repeat;
310c5c4113dSnw141292 	}
311c5c4113dSnw141292 
312cd37da74Snw141292 	if (curr_version == version)
313cd37da74Snw141292 		goto done;
314cd37da74Snw141292 
315cd37da74Snw141292 	/* Install or upgrade schema */
316cd37da74Snw141292 #ifdef	IDMAPD_DEBUG
317cd37da74Snw141292 	(void) fprintf(stderr, "Schema init/upgrade SQL: %s\n",
318cd37da74Snw141292 	    sql[curr_version]);
319cd37da74Snw141292 #endif	/* IDMAPD_DEBUG */
320cd37da74Snw141292 	rc = sql_exec_tran_no_cb(db, sql[curr_version], dbname,
321cd37da74Snw141292 	    (curr_version == 0) ? "installing schema" : "upgrading schema");
322cd37da74Snw141292 	if (rc != 0) {
323cd37da74Snw141292 		idmapdlog(prio, "Error %s schema for db %s", dbname,
324cd37da74Snw141292 		    (curr_version == 0) ? "installing schema" :
325cd37da74Snw141292 		    "upgrading schema");
326cd37da74Snw141292 		if (opt == REMOVE_IF_CORRUPT)
327cd37da74Snw141292 			(void) unlink(dbname);
328cd37da74Snw141292 		goto rinse_repeat;
329c5c4113dSnw141292 	}
330c5c4113dSnw141292 
331cd37da74Snw141292 	*upgraded = (curr_version > 0);
332cd37da74Snw141292 	*created = (curr_version == 0);
333cd37da74Snw141292 
334cd37da74Snw141292 done:
335c5c4113dSnw141292 	(void) sqlite_close(db);
336cd37da74Snw141292 	return (0);
337c5c4113dSnw141292 }
338c5c4113dSnw141292 
33984decf41Sjp151216 
34084decf41Sjp151216 /*
34184decf41Sjp151216  * This is the SQLite database busy handler that retries the SQL
34284decf41Sjp151216  * operation until it is successful.
34384decf41Sjp151216  */
34484decf41Sjp151216 int
34584decf41Sjp151216 /* LINTED E_FUNC_ARG_UNUSED */
34684decf41Sjp151216 idmap_sqlite_busy_handler(void *arg, const char *table_name, int count)
34784decf41Sjp151216 {
34884decf41Sjp151216 	struct idmap_busy	*busy = arg;
34984decf41Sjp151216 	int			delay;
35084decf41Sjp151216 	struct timespec		rqtp;
35184decf41Sjp151216 
35284decf41Sjp151216 	if (count == 1)  {
35384decf41Sjp151216 		busy->total = 0;
35484decf41Sjp151216 		busy->sec = 2;
35584decf41Sjp151216 	}
35684decf41Sjp151216 	if (busy->total > 1000 * busy->sec) {
35784decf41Sjp151216 		idmapdlog(LOG_ERR,
35884decf41Sjp151216 		    "Thread %d waited %d sec for the %s database",
35984decf41Sjp151216 		    pthread_self(), busy->sec, busy->name);
36084decf41Sjp151216 		busy->sec++;
36184decf41Sjp151216 	}
36284decf41Sjp151216 
36384decf41Sjp151216 	if (count <= busy->delay_size) {
36484decf41Sjp151216 		delay = busy->delays[count-1];
36584decf41Sjp151216 	} else {
36684decf41Sjp151216 		delay = busy->delays[busy->delay_size - 1];
36784decf41Sjp151216 	}
36884decf41Sjp151216 	busy->total += delay;
36984decf41Sjp151216 	rqtp.tv_sec = 0;
37084decf41Sjp151216 	rqtp.tv_nsec = delay * (NANOSEC / MILLISEC);
37184decf41Sjp151216 	(void) nanosleep(&rqtp, NULL);
37284decf41Sjp151216 	return (1);
37384decf41Sjp151216 }
37484decf41Sjp151216 
37584decf41Sjp151216 
376c5c4113dSnw141292 /*
377c5c4113dSnw141292  * Get the database handle
378c5c4113dSnw141292  */
379c5c4113dSnw141292 idmap_retcode
380cd37da74Snw141292 get_db_handle(sqlite **db)
381cd37da74Snw141292 {
382c5c4113dSnw141292 	char		*errmsg;
38384decf41Sjp151216 	idmap_tsd_t	*tsd;
384c5c4113dSnw141292 
385c5c4113dSnw141292 	/*
38684decf41Sjp151216 	 * Retrieve the db handle from thread-specific storage
387c5c4113dSnw141292 	 * If none exists, open and store in thread-specific storage.
388c5c4113dSnw141292 	 */
38984decf41Sjp151216 	if ((tsd = idmap_get_tsd()) == NULL) {
39084decf41Sjp151216 		idmapdlog(LOG_ERR,
391cd37da74Snw141292 		    "Error getting thread specific data for %s", IDMAP_DBNAME);
39284decf41Sjp151216 		return (IDMAP_ERR_MEMORY);
39384decf41Sjp151216 	}
394c5c4113dSnw141292 
39584decf41Sjp151216 	if (tsd->db_db == NULL) {
39684decf41Sjp151216 		tsd->db_db = sqlite_open(IDMAP_DBNAME, 0, &errmsg);
39784decf41Sjp151216 		if (tsd->db_db == NULL) {
398cd37da74Snw141292 			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
399c5c4113dSnw141292 			    IDMAP_DBNAME, CHECK_NULL(errmsg));
400c5c4113dSnw141292 			sqlite_freemem(errmsg);
401cd37da74Snw141292 			return (IDMAP_ERR_DB);
402c5c4113dSnw141292 		}
403cd37da74Snw141292 
40484decf41Sjp151216 		tsd->db_busy.name = IDMAP_DBNAME;
40584decf41Sjp151216 		tsd->db_busy.delays = db_delay_table;
40684decf41Sjp151216 		tsd->db_busy.delay_size = sizeof (db_delay_table) /
40784decf41Sjp151216 		    sizeof (int);
40884decf41Sjp151216 		sqlite_busy_handler(tsd->db_db, idmap_sqlite_busy_handler,
40984decf41Sjp151216 		    &tsd->db_busy);
41084decf41Sjp151216 	}
41184decf41Sjp151216 	*db = tsd->db_db;
412c5c4113dSnw141292 	return (IDMAP_SUCCESS);
413c5c4113dSnw141292 }
414c5c4113dSnw141292 
415c5c4113dSnw141292 /*
416c5c4113dSnw141292  * Get the cache handle
417c5c4113dSnw141292  */
418c5c4113dSnw141292 idmap_retcode
419cd37da74Snw141292 get_cache_handle(sqlite **cache)
420cd37da74Snw141292 {
421c5c4113dSnw141292 	char		*errmsg;
42284decf41Sjp151216 	idmap_tsd_t	*tsd;
423c5c4113dSnw141292 
424c5c4113dSnw141292 	/*
42584decf41Sjp151216 	 * Retrieve the db handle from thread-specific storage
426c5c4113dSnw141292 	 * If none exists, open and store in thread-specific storage.
427c5c4113dSnw141292 	 */
42884decf41Sjp151216 	if ((tsd = idmap_get_tsd()) == NULL) {
429cd37da74Snw141292 		idmapdlog(LOG_ERR, "Error getting thread specific data for %s",
43084decf41Sjp151216 		    IDMAP_DBNAME);
43184decf41Sjp151216 		return (IDMAP_ERR_MEMORY);
43284decf41Sjp151216 	}
433c5c4113dSnw141292 
43484decf41Sjp151216 	if (tsd->cache_db == NULL) {
43584decf41Sjp151216 		tsd->cache_db = sqlite_open(IDMAP_CACHENAME, 0, &errmsg);
43684decf41Sjp151216 		if (tsd->cache_db == NULL) {
437cd37da74Snw141292 			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
438c5c4113dSnw141292 			    IDMAP_CACHENAME, CHECK_NULL(errmsg));
439c5c4113dSnw141292 			sqlite_freemem(errmsg);
440cd37da74Snw141292 			return (IDMAP_ERR_DB);
441c5c4113dSnw141292 		}
442cd37da74Snw141292 
44384decf41Sjp151216 		tsd->cache_busy.name = IDMAP_CACHENAME;
44484decf41Sjp151216 		tsd->cache_busy.delays = cache_delay_table;
44584decf41Sjp151216 		tsd->cache_busy.delay_size = sizeof (cache_delay_table) /
44684decf41Sjp151216 		    sizeof (int);
44784decf41Sjp151216 		sqlite_busy_handler(tsd->cache_db, idmap_sqlite_busy_handler,
44884decf41Sjp151216 		    &tsd->cache_busy);
44984decf41Sjp151216 	}
45084decf41Sjp151216 	*cache = tsd->cache_db;
451c5c4113dSnw141292 	return (IDMAP_SUCCESS);
452c5c4113dSnw141292 }
453c5c4113dSnw141292 
454c5c4113dSnw141292 /*
455c5c4113dSnw141292  * Initialize cache and db
456c5c4113dSnw141292  */
457c5c4113dSnw141292 int
458cd37da74Snw141292 init_dbs()
459cd37da74Snw141292 {
460cd37da74Snw141292 	char *sql[2];
461cd37da74Snw141292 	int created, upgraded;
462cd37da74Snw141292 
463c5c4113dSnw141292 	/* name-based mappings; probably OK to blow away in a pinch(?) */
464cd37da74Snw141292 	sql[0] = DB_INSTALL_SQL;
465cd37da74Snw141292 	sql[1] = DB_UPGRADE_FROM_v1_SQL;
466cd37da74Snw141292 
467cd37da74Snw141292 	if (init_db_instance(IDMAP_DBNAME, DB_VERSION, DB_VERSION_SQL, sql,
468cd37da74Snw141292 	    FAIL_IF_CORRUPT, &created, &upgraded) < 0)
469c5c4113dSnw141292 		return (-1);
470c5c4113dSnw141292 
471c5c4113dSnw141292 	/* mappings, name/SID lookup cache + ephemeral IDs; OK to blow away */
472cd37da74Snw141292 	sql[0] = CACHE_INSTALL_SQL;
473cd37da74Snw141292 	sql[1] = CACHE_UPGRADE_FROM_v1_SQL;
474cd37da74Snw141292 	if (init_db_instance(IDMAP_CACHENAME, CACHE_VERSION, CACHE_VERSION_SQL,
475cd37da74Snw141292 	    sql, REMOVE_IF_CORRUPT, &created, &upgraded) < 0)
476c5c4113dSnw141292 		return (-1);
477c5c4113dSnw141292 
478cd37da74Snw141292 	_idmapdstate.new_eph_db = (created || upgraded) ? 1 : 0;
479cd37da74Snw141292 
480c5c4113dSnw141292 	return (0);
481c5c4113dSnw141292 }
482c5c4113dSnw141292 
483c5c4113dSnw141292 /*
484c5c4113dSnw141292  * Finalize databases
485c5c4113dSnw141292  */
486c5c4113dSnw141292 void
487cd37da74Snw141292 fini_dbs()
488cd37da74Snw141292 {
489c5c4113dSnw141292 }
490c5c4113dSnw141292 
491c5c4113dSnw141292 /*
492e8c27ec8Sbaban  * This table is a listing of status codes that will be returned to the
493c5c4113dSnw141292  * client when a SQL command fails with the corresponding error message.
494c5c4113dSnw141292  */
495c5c4113dSnw141292 static msg_table_t sqlmsgtable[] = {
49662c60062Sbaban 	{IDMAP_ERR_U2W_NAMERULE_CONFLICT,
497c5c4113dSnw141292 	"columns unixname, is_user, u2w_order are not unique"},
49862c60062Sbaban 	{IDMAP_ERR_W2U_NAMERULE_CONFLICT,
499cd37da74Snw141292 	"columns winname, windomain, is_user, is_wuser, w2u_order are not"
500cd37da74Snw141292 	" unique"},
501cd37da74Snw141292 	{IDMAP_ERR_W2U_NAMERULE_CONFLICT, "Conflicting w2u namerules"},
502c5c4113dSnw141292 	{-1, NULL}
503c5c4113dSnw141292 };
504c5c4113dSnw141292 
505c5c4113dSnw141292 /*
506c5c4113dSnw141292  * idmapd's version of string2stat to map SQLite messages to
507c5c4113dSnw141292  * status codes
508c5c4113dSnw141292  */
509c5c4113dSnw141292 idmap_retcode
510cd37da74Snw141292 idmapd_string2stat(const char *msg)
511cd37da74Snw141292 {
512c5c4113dSnw141292 	int i;
513c5c4113dSnw141292 	for (i = 0; sqlmsgtable[i].msg; i++) {
514c5c4113dSnw141292 		if (strcasecmp(sqlmsgtable[i].msg, msg) == 0)
515c5c4113dSnw141292 			return (sqlmsgtable[i].retcode);
516c5c4113dSnw141292 	}
517c5c4113dSnw141292 	return (IDMAP_ERR_OTHER);
518c5c4113dSnw141292 }
519c5c4113dSnw141292 
520c5c4113dSnw141292 /*
521cd37da74Snw141292  * Executes some SQL in a transaction.
522cd37da74Snw141292  *
523cd37da74Snw141292  * Returns 0 on success, -1 if it failed but the rollback succeeded, -2
524cd37da74Snw141292  * if the rollback failed.
525cd37da74Snw141292  */
526cd37da74Snw141292 static
527cd37da74Snw141292 int
528cd37da74Snw141292 sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
529cd37da74Snw141292 	const char *while_doing)
530cd37da74Snw141292 {
531cd37da74Snw141292 	char		*errmsg = NULL;
532cd37da74Snw141292 	int		rc;
533cd37da74Snw141292 
534cd37da74Snw141292 	rc = sqlite_exec(db, "BEGIN TRANSACTION;", NULL, NULL, &errmsg);
535cd37da74Snw141292 	if (rc != SQLITE_OK) {
536cd37da74Snw141292 		idmapdlog(LOG_ERR, "Begin transaction failed (%s) "
537cd37da74Snw141292 		    "while %s (%s)", errmsg, while_doing, dbname);
538cd37da74Snw141292 		sqlite_freemem(errmsg);
539cd37da74Snw141292 		return (-1);
540cd37da74Snw141292 	}
541cd37da74Snw141292 
542cd37da74Snw141292 	rc = sqlite_exec(db, sql, NULL, NULL, &errmsg);
543cd37da74Snw141292 	if (rc != SQLITE_OK) {
544cd37da74Snw141292 		idmapdlog(LOG_ERR, "Database error (%s) while %s (%s)", errmsg,
545cd37da74Snw141292 		    while_doing, dbname);
546cd37da74Snw141292 		sqlite_freemem(errmsg);
547cd37da74Snw141292 		errmsg = NULL;
548cd37da74Snw141292 		goto rollback;
549cd37da74Snw141292 	}
550cd37da74Snw141292 
551cd37da74Snw141292 	rc = sqlite_exec(db, "COMMIT TRANSACTION", NULL, NULL, &errmsg);
552cd37da74Snw141292 	if (rc == SQLITE_OK) {
553cd37da74Snw141292 		sqlite_freemem(errmsg);
554cd37da74Snw141292 		return (0);
555cd37da74Snw141292 	}
556cd37da74Snw141292 
557cd37da74Snw141292 	idmapdlog(LOG_ERR, "Database commit error (%s) while s (%s)",
558cd37da74Snw141292 	    errmsg, while_doing, dbname);
559cd37da74Snw141292 	sqlite_freemem(errmsg);
560cd37da74Snw141292 	errmsg = NULL;
561cd37da74Snw141292 
562cd37da74Snw141292 rollback:
563cd37da74Snw141292 	rc = sqlite_exec(db, "ROLLBACK TRANSACTION", NULL, NULL, &errmsg);
564cd37da74Snw141292 	if (rc != SQLITE_OK) {
565cd37da74Snw141292 		idmapdlog(LOG_ERR, "Rollback failed (%s) while %s (%s)",
566cd37da74Snw141292 		    errmsg, while_doing, dbname);
567cd37da74Snw141292 		sqlite_freemem(errmsg);
568cd37da74Snw141292 		return (-2);
569cd37da74Snw141292 	}
570cd37da74Snw141292 	sqlite_freemem(errmsg);
571cd37da74Snw141292 
572cd37da74Snw141292 	return (-1);
573cd37da74Snw141292 }
574cd37da74Snw141292 
575cd37da74Snw141292 /*
576c5c4113dSnw141292  * Execute the given SQL statment without using any callbacks
577c5c4113dSnw141292  */
578c5c4113dSnw141292 idmap_retcode
57971590c90Snw141292 sql_exec_no_cb(sqlite *db, const char *dbname, char *sql)
580cd37da74Snw141292 {
581c5c4113dSnw141292 	char		*errmsg = NULL;
58284decf41Sjp151216 	int		r;
583c5c4113dSnw141292 	idmap_retcode	retcode;
584c5c4113dSnw141292 
585c5c4113dSnw141292 	r = sqlite_exec(db, sql, NULL, NULL, &errmsg);
58684decf41Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
587c5c4113dSnw141292 
588c5c4113dSnw141292 	if (r != SQLITE_OK) {
58971590c90Snw141292 		idmapdlog(LOG_ERR, "Database error on %s while executing %s "
59071590c90Snw141292 		    "(%s)", dbname, sql, CHECK_NULL(errmsg));
591c5c4113dSnw141292 		retcode = idmapd_string2stat(errmsg);
59262c60062Sbaban 		if (errmsg != NULL)
593c5c4113dSnw141292 			sqlite_freemem(errmsg);
594c5c4113dSnw141292 		return (retcode);
595c5c4113dSnw141292 	}
596c5c4113dSnw141292 
597c5c4113dSnw141292 	return (IDMAP_SUCCESS);
598c5c4113dSnw141292 }
599c5c4113dSnw141292 
600c5c4113dSnw141292 /*
601c5c4113dSnw141292  * Generate expression that can be used in WHERE statements.
602c5c4113dSnw141292  * Examples:
603c5c4113dSnw141292  * <prefix> <col>      <op> <value>   <suffix>
604c5c4113dSnw141292  * ""       "unixuser" "="  "foo" "AND"
605c5c4113dSnw141292  */
606c5c4113dSnw141292 idmap_retcode
607cd37da74Snw141292 gen_sql_expr_from_rule(idmap_namerule *rule, char **out)
608cd37da74Snw141292 {
609cd37da74Snw141292 	char	*s_windomain = NULL, *s_winname = NULL;
610cd37da74Snw141292 	char	*s_unixname = NULL;
611cd37da74Snw141292 	char	*lower_winname;
612cd37da74Snw141292 	int	retcode = IDMAP_SUCCESS;
613cd37da74Snw141292 
614c5c4113dSnw141292 	if (out == NULL)
615c5c4113dSnw141292 		return (IDMAP_ERR_ARG);
616c5c4113dSnw141292 
617c5c4113dSnw141292 
618cd37da74Snw141292 	if (!EMPTY_STRING(rule->windomain)) {
619cd37da74Snw141292 		s_windomain =  sqlite_mprintf("AND windomain = %Q ",
620cd37da74Snw141292 		    rule->windomain);
621cd37da74Snw141292 		if (s_windomain == NULL) {
622cd37da74Snw141292 			retcode = IDMAP_ERR_MEMORY;
623cd37da74Snw141292 			goto out;
624c5c4113dSnw141292 		}
625cd37da74Snw141292 	}
626cd37da74Snw141292 
627cd37da74Snw141292 	if (!EMPTY_STRING(rule->winname)) {
628cd37da74Snw141292 		if ((lower_winname = tolower_u8(rule->winname)) == NULL)
629cd37da74Snw141292 			lower_winname = rule->winname;
630cd37da74Snw141292 		s_winname = sqlite_mprintf(
631cd37da74Snw141292 		    "AND winname = %Q AND is_wuser = %d ",
632cd37da74Snw141292 		    lower_winname, rule->is_wuser ? 1 : 0);
633cd37da74Snw141292 		if (lower_winname != rule->winname)
634cd37da74Snw141292 			free(lower_winname);
635cd37da74Snw141292 		if (s_winname == NULL) {
636cd37da74Snw141292 			retcode = IDMAP_ERR_MEMORY;
637cd37da74Snw141292 			goto out;
638cd37da74Snw141292 		}
639cd37da74Snw141292 	}
640cd37da74Snw141292 
641cd37da74Snw141292 	if (!EMPTY_STRING(rule->unixname)) {
642cd37da74Snw141292 		s_unixname = sqlite_mprintf(
643cd37da74Snw141292 		    "AND unixname = %Q AND is_user = %d ",
644cd37da74Snw141292 		    rule->unixname, rule->is_user ? 1 : 0);
645cd37da74Snw141292 		if (s_unixname == NULL) {
646cd37da74Snw141292 			retcode = IDMAP_ERR_MEMORY;
647cd37da74Snw141292 			goto out;
648cd37da74Snw141292 		}
649cd37da74Snw141292 	}
650cd37da74Snw141292 
651cd37da74Snw141292 	*out = sqlite_mprintf("%s %s %s",
652cd37da74Snw141292 	    s_windomain ? s_windomain : "",
653cd37da74Snw141292 	    s_winname ? s_winname : "",
654cd37da74Snw141292 	    s_unixname ? s_unixname : "");
655cd37da74Snw141292 
656cd37da74Snw141292 	if (*out == NULL) {
657cd37da74Snw141292 		retcode = IDMAP_ERR_MEMORY;
658cd37da74Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
659cd37da74Snw141292 		goto out;
660cd37da74Snw141292 	}
661cd37da74Snw141292 
662cd37da74Snw141292 out:
663cd37da74Snw141292 	if (s_windomain != NULL)
664cd37da74Snw141292 		sqlite_freemem(s_windomain);
665cd37da74Snw141292 	if (s_winname != NULL)
666cd37da74Snw141292 		sqlite_freemem(s_winname);
667cd37da74Snw141292 	if (s_unixname != NULL)
668cd37da74Snw141292 		sqlite_freemem(s_unixname);
669cd37da74Snw141292 
670cd37da74Snw141292 	return (retcode);
671cd37da74Snw141292 }
672cd37da74Snw141292 
673cd37da74Snw141292 
674c5c4113dSnw141292 
675c5c4113dSnw141292 /*
676c5c4113dSnw141292  * Generate and execute SQL statement for LIST RPC calls
677c5c4113dSnw141292  */
678c5c4113dSnw141292 idmap_retcode
67971590c90Snw141292 process_list_svc_sql(sqlite *db, const char *dbname, char *sql, uint64_t limit,
680cd37da74Snw141292 		list_svc_cb cb, void *result)
681cd37da74Snw141292 {
682c5c4113dSnw141292 	list_cb_data_t	cb_data;
683c5c4113dSnw141292 	char		*errmsg = NULL;
68484decf41Sjp151216 	int		r;
685c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_ERR_INTERNAL;
686c5c4113dSnw141292 
687c5c4113dSnw141292 	(void) memset(&cb_data, 0, sizeof (cb_data));
688c5c4113dSnw141292 	cb_data.result = result;
689c5c4113dSnw141292 	cb_data.limit = limit;
690c5c4113dSnw141292 
69184decf41Sjp151216 
692c5c4113dSnw141292 	r = sqlite_exec(db, sql, cb, &cb_data, &errmsg);
69384decf41Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
694c5c4113dSnw141292 	switch (r) {
695c5c4113dSnw141292 	case SQLITE_OK:
696c5c4113dSnw141292 		retcode = IDMAP_SUCCESS;
69784decf41Sjp151216 		break;
69884decf41Sjp151216 
699c5c4113dSnw141292 	default:
700c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
70171590c90Snw141292 		idmapdlog(LOG_ERR, "Database error on %s while executing "
70271590c90Snw141292 		    "%s (%s)", dbname, sql, CHECK_NULL(errmsg));
70384decf41Sjp151216 		break;
704c5c4113dSnw141292 	}
70562c60062Sbaban 	if (errmsg != NULL)
706c5c4113dSnw141292 		sqlite_freemem(errmsg);
707c5c4113dSnw141292 	return (retcode);
708c5c4113dSnw141292 }
709c5c4113dSnw141292 
710c5c4113dSnw141292 /*
711c5c4113dSnw141292  * This routine is called by callbacks that process the results of
712c5c4113dSnw141292  * LIST RPC calls to validate data and to allocate memory for
713c5c4113dSnw141292  * the result array.
714c5c4113dSnw141292  */
715c5c4113dSnw141292 idmap_retcode
716c5c4113dSnw141292 validate_list_cb_data(list_cb_data_t *cb_data, int argc, char **argv,
717cd37da74Snw141292 		int ncol, uchar_t **list, size_t valsize)
718cd37da74Snw141292 {
719c5c4113dSnw141292 	size_t	nsize;
720c5c4113dSnw141292 	void	*tmplist;
721c5c4113dSnw141292 
722c5c4113dSnw141292 	if (cb_data->limit > 0 && cb_data->next == cb_data->limit)
723c5c4113dSnw141292 		return (IDMAP_NEXT);
724c5c4113dSnw141292 
725c5c4113dSnw141292 	if (argc < ncol || argv == NULL) {
726c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Invalid data");
727c5c4113dSnw141292 		return (IDMAP_ERR_INTERNAL);
728c5c4113dSnw141292 	}
729c5c4113dSnw141292 
730c5c4113dSnw141292 	/* alloc in bulk to reduce number of reallocs */
731c5c4113dSnw141292 	if (cb_data->next >= cb_data->len) {
732c5c4113dSnw141292 		nsize = (cb_data->len + SIZE_INCR) * valsize;
733c5c4113dSnw141292 		tmplist = realloc(*list, nsize);
734c5c4113dSnw141292 		if (tmplist == NULL) {
735c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
736c5c4113dSnw141292 			return (IDMAP_ERR_MEMORY);
737c5c4113dSnw141292 		}
738c5c4113dSnw141292 		*list = tmplist;
739c5c4113dSnw141292 		(void) memset(*list + (cb_data->len * valsize), 0,
740c5c4113dSnw141292 		    SIZE_INCR * valsize);
741c5c4113dSnw141292 		cb_data->len += SIZE_INCR;
742c5c4113dSnw141292 	}
743c5c4113dSnw141292 	return (IDMAP_SUCCESS);
744c5c4113dSnw141292 }
745c5c4113dSnw141292 
746cd37da74Snw141292 static
747cd37da74Snw141292 idmap_retcode
748c5c4113dSnw141292 get_namerule_order(char *winname, char *windomain, char *unixname,
749cd37da74Snw141292 	int direction, int is_diagonal, int *w2u_order, int *u2w_order)
750cd37da74Snw141292 {
751c5c4113dSnw141292 	*w2u_order = 0;
752c5c4113dSnw141292 	*u2w_order = 0;
753c5c4113dSnw141292 
754c5c4113dSnw141292 	/*
755c5c4113dSnw141292 	 * Windows to UNIX lookup order:
756c5c4113dSnw141292 	 *  1. winname@domain (or winname) to ""
757c5c4113dSnw141292 	 *  2. winname@domain (or winname) to unixname
758c5c4113dSnw141292 	 *  3. winname@* to ""
759c5c4113dSnw141292 	 *  4. winname@* to unixname
760c5c4113dSnw141292 	 *  5. *@domain (or *) to *
761c5c4113dSnw141292 	 *  6. *@domain (or *) to ""
762c5c4113dSnw141292 	 *  7. *@domain (or *) to unixname
763c5c4113dSnw141292 	 *  8. *@* to *
764c5c4113dSnw141292 	 *  9. *@* to ""
765c5c4113dSnw141292 	 * 10. *@* to unixname
766c5c4113dSnw141292 	 *
767c5c4113dSnw141292 	 * winname is a special case of winname@domain when domain is the
768c5c4113dSnw141292 	 * default domain. Similarly * is a special case of *@domain when
769c5c4113dSnw141292 	 * domain is the default domain.
770c5c4113dSnw141292 	 *
771c5c4113dSnw141292 	 * Note that "" has priority over specific names because "" inhibits
772c5c4113dSnw141292 	 * mappings and traditionally deny rules always had higher priority.
773c5c4113dSnw141292 	 */
774651c0131Sbaban 	if (direction != IDMAP_DIRECTION_U2W) {
775651c0131Sbaban 		/* bi-directional or from windows to unix */
776c5c4113dSnw141292 		if (winname == NULL)
777c5c4113dSnw141292 			return (IDMAP_ERR_W2U_NAMERULE);
778c5c4113dSnw141292 		else if (unixname == NULL)
779c5c4113dSnw141292 			return (IDMAP_ERR_W2U_NAMERULE);
780c5c4113dSnw141292 		else if (EMPTY_NAME(winname))
781c5c4113dSnw141292 			return (IDMAP_ERR_W2U_NAMERULE);
782c5c4113dSnw141292 		else if (*winname == '*' && windomain && *windomain == '*') {
783c5c4113dSnw141292 			if (*unixname == '*')
784c5c4113dSnw141292 				*w2u_order = 8;
785c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
786c5c4113dSnw141292 				*w2u_order = 9;
787c5c4113dSnw141292 			else /* unixname == name */
788c5c4113dSnw141292 				*w2u_order = 10;
789c5c4113dSnw141292 		} else if (*winname == '*') {
790c5c4113dSnw141292 			if (*unixname == '*')
791c5c4113dSnw141292 				*w2u_order = 5;
792c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
793c5c4113dSnw141292 				*w2u_order = 6;
794c5c4113dSnw141292 			else /* name */
795c5c4113dSnw141292 				*w2u_order = 7;
79662c60062Sbaban 		} else if (windomain != NULL && *windomain == '*') {
797c5c4113dSnw141292 			/* winname == name */
798c5c4113dSnw141292 			if (*unixname == '*')
799c5c4113dSnw141292 				return (IDMAP_ERR_W2U_NAMERULE);
800c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
801c5c4113dSnw141292 				*w2u_order = 3;
802c5c4113dSnw141292 			else /* name */
803c5c4113dSnw141292 				*w2u_order = 4;
804c5c4113dSnw141292 		} else  {
805c5c4113dSnw141292 			/* winname == name && windomain == null or name */
806c5c4113dSnw141292 			if (*unixname == '*')
807c5c4113dSnw141292 				return (IDMAP_ERR_W2U_NAMERULE);
808c5c4113dSnw141292 			else if (EMPTY_NAME(unixname))
809c5c4113dSnw141292 				*w2u_order = 1;
810c5c4113dSnw141292 			else /* name */
811c5c4113dSnw141292 				*w2u_order = 2;
812c5c4113dSnw141292 		}
813cd37da74Snw141292 
814c5c4113dSnw141292 	}
815c5c4113dSnw141292 
816c5c4113dSnw141292 	/*
817cd37da74Snw141292 	 * 1. unixname to "", non-diagonal
818cd37da74Snw141292 	 * 2. unixname to winname@domain (or winname), non-diagonal
819cd37da74Snw141292 	 * 3. unixname to "", diagonal
820cd37da74Snw141292 	 * 4. unixname to winname@domain (or winname), diagonal
821cd37da74Snw141292 	 * 5. * to *@domain (or *), non-diagonal
822cd37da74Snw141292 	 * 5. * to *@domain (or *), diagonal
823cd37da74Snw141292 	 * 7. * to ""
824cd37da74Snw141292 	 * 8. * to winname@domain (or winname)
825cd37da74Snw141292 	 * 9. * to "", non-diagonal
826cd37da74Snw141292 	 * 10. * to winname@domain (or winname), diagonal
827c5c4113dSnw141292 	 */
828651c0131Sbaban 	if (direction != IDMAP_DIRECTION_W2U) {
829cd37da74Snw141292 		int diagonal = is_diagonal ? 1 : 0;
830cd37da74Snw141292 
831651c0131Sbaban 		/* bi-directional or from unix to windows */
832c5c4113dSnw141292 		if (unixname == NULL || EMPTY_NAME(unixname))
833c5c4113dSnw141292 			return (IDMAP_ERR_U2W_NAMERULE);
834c5c4113dSnw141292 		else if (winname == NULL)
835c5c4113dSnw141292 			return (IDMAP_ERR_U2W_NAMERULE);
83662c60062Sbaban 		else if (windomain != NULL && *windomain == '*')
837651c0131Sbaban 			return (IDMAP_ERR_U2W_NAMERULE);
838c5c4113dSnw141292 		else if (*unixname == '*') {
839c5c4113dSnw141292 			if (*winname == '*')
840cd37da74Snw141292 				*u2w_order = 5 + diagonal;
841c5c4113dSnw141292 			else if (EMPTY_NAME(winname))
842cd37da74Snw141292 				*u2w_order = 7 + 2 * diagonal;
843c5c4113dSnw141292 			else
844cd37da74Snw141292 				*u2w_order = 8 + 2 * diagonal;
845c5c4113dSnw141292 		} else {
846c5c4113dSnw141292 			if (*winname == '*')
847c5c4113dSnw141292 				return (IDMAP_ERR_U2W_NAMERULE);
848c5c4113dSnw141292 			else if (EMPTY_NAME(winname))
849cd37da74Snw141292 				*u2w_order = 1 + 2 * diagonal;
850c5c4113dSnw141292 			else
851cd37da74Snw141292 				*u2w_order = 2 + 2 * diagonal;
852c5c4113dSnw141292 		}
853c5c4113dSnw141292 	}
854c5c4113dSnw141292 	return (IDMAP_SUCCESS);
855c5c4113dSnw141292 }
856c5c4113dSnw141292 
857c5c4113dSnw141292 /*
858c5c4113dSnw141292  * Generate and execute SQL statement to add name-based mapping rule
859c5c4113dSnw141292  */
860c5c4113dSnw141292 idmap_retcode
861cd37da74Snw141292 add_namerule(sqlite *db, idmap_namerule *rule)
862cd37da74Snw141292 {
863c5c4113dSnw141292 	char		*sql = NULL;
864c5c4113dSnw141292 	idmap_stat	retcode;
8658e228215Sdm199847 	char		*dom = NULL;
866c5c4113dSnw141292 	int		w2u_order, u2w_order;
867c5c4113dSnw141292 	char		w2ubuf[11], u2wbuf[11];
868c5c4113dSnw141292 
8698e228215Sdm199847 	retcode = get_namerule_order(rule->winname, rule->windomain,
870cd37da74Snw141292 	    rule->unixname, rule->direction,
871cd37da74Snw141292 	    rule->is_user == rule->is_wuser ? 0 : 1, &w2u_order, &u2w_order);
872c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
873c5c4113dSnw141292 		goto out;
874c5c4113dSnw141292 
875c5c4113dSnw141292 	if (w2u_order)
876c5c4113dSnw141292 		(void) snprintf(w2ubuf, sizeof (w2ubuf), "%d", w2u_order);
877c5c4113dSnw141292 	if (u2w_order)
878c5c4113dSnw141292 		(void) snprintf(u2wbuf, sizeof (u2wbuf), "%d", u2w_order);
879c5c4113dSnw141292 
88062c60062Sbaban 	/*
88162c60062Sbaban 	 * For the triggers on namerules table to work correctly:
88262c60062Sbaban 	 * 1) Use NULL instead of 0 for w2u_order and u2w_order
88362c60062Sbaban 	 * 2) Use "" instead of NULL for "no domain"
88462c60062Sbaban 	 */
88562c60062Sbaban 
886e8c27ec8Sbaban 	if (!EMPTY_STRING(rule->windomain))
8878e228215Sdm199847 		dom = rule->windomain;
888cd37da74Snw141292 	else if (lookup_wksids_name2sid(rule->winname, NULL, NULL, NULL, NULL)
88962c60062Sbaban 	    == IDMAP_SUCCESS) {
89062c60062Sbaban 		/* well-known SIDs don't need domain */
89162c60062Sbaban 		dom = "";
89262c60062Sbaban 	}
893c5c4113dSnw141292 
894c5c4113dSnw141292 	RDLOCK_CONFIG();
89562c60062Sbaban 	if (dom == NULL) {
896c8e26105Sjp151216 		if (_idmapdstate.cfg->pgcfg.default_domain)
897c8e26105Sjp151216 			dom = _idmapdstate.cfg->pgcfg.default_domain;
898c5c4113dSnw141292 		else
899c5c4113dSnw141292 			dom = "";
90062c60062Sbaban 	}
90184decf41Sjp151216 	sql = sqlite_mprintf("INSERT into namerules "
902cd37da74Snw141292 	    "(is_user, is_wuser, windomain, winname_display, is_nt4, "
903c5c4113dSnw141292 	    "unixname, w2u_order, u2w_order) "
904cd37da74Snw141292 	    "VALUES(%d, %d, %Q, %Q, %d, %Q, %q, %q);",
905cd37da74Snw141292 	    rule->is_user ? 1 : 0, rule->is_wuser ? 1 : 0, dom,
906cd37da74Snw141292 	    rule->winname, rule->is_nt4 ? 1 : 0, rule->unixname,
907cd37da74Snw141292 	    w2u_order ? w2ubuf : NULL, u2w_order ? u2wbuf : NULL);
908c5c4113dSnw141292 	UNLOCK_CONFIG();
909c5c4113dSnw141292 
910c5c4113dSnw141292 	if (sql == NULL) {
911c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
912c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
913c5c4113dSnw141292 		goto out;
914c5c4113dSnw141292 	}
915c5c4113dSnw141292 
91671590c90Snw141292 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, sql);
917c5c4113dSnw141292 
918c5c4113dSnw141292 	if (retcode == IDMAP_ERR_OTHER)
919c5c4113dSnw141292 		retcode = IDMAP_ERR_CFG;
920c5c4113dSnw141292 
921c5c4113dSnw141292 out:
92262c60062Sbaban 	if (sql != NULL)
923c5c4113dSnw141292 		sqlite_freemem(sql);
924c5c4113dSnw141292 	return (retcode);
925c5c4113dSnw141292 }
926c5c4113dSnw141292 
927c5c4113dSnw141292 /*
928c5c4113dSnw141292  * Flush name-based mapping rules
929c5c4113dSnw141292  */
930c5c4113dSnw141292 idmap_retcode
931cd37da74Snw141292 flush_namerules(sqlite *db)
932cd37da74Snw141292 {
933c5c4113dSnw141292 	idmap_stat	retcode;
934c5c4113dSnw141292 
93571590c90Snw141292 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, "DELETE FROM namerules;");
936c5c4113dSnw141292 
937c5c4113dSnw141292 	return (retcode);
938c5c4113dSnw141292 }
939c5c4113dSnw141292 
940c5c4113dSnw141292 /*
941c5c4113dSnw141292  * Generate and execute SQL statement to remove a name-based mapping rule
942c5c4113dSnw141292  */
943c5c4113dSnw141292 idmap_retcode
944cd37da74Snw141292 rm_namerule(sqlite *db, idmap_namerule *rule)
945cd37da74Snw141292 {
946c5c4113dSnw141292 	char		*sql = NULL;
947c5c4113dSnw141292 	idmap_stat	retcode;
948c5c4113dSnw141292 	char		buf[80];
949cd37da74Snw141292 	char		*expr = NULL;
950c5c4113dSnw141292 
9518e228215Sdm199847 	if (rule->direction < 0 && EMPTY_STRING(rule->windomain) &&
9528e228215Sdm199847 	    EMPTY_STRING(rule->winname) && EMPTY_STRING(rule->unixname))
953c5c4113dSnw141292 		return (IDMAP_SUCCESS);
954c5c4113dSnw141292 
955c5c4113dSnw141292 	buf[0] = 0;
956cd37da74Snw141292 
957cd37da74Snw141292 	if (rule->direction == IDMAP_DIRECTION_BI)
958c5c4113dSnw141292 		(void) snprintf(buf, sizeof (buf), "AND w2u_order > 0"
959c5c4113dSnw141292 		    " AND u2w_order > 0");
960cd37da74Snw141292 	else if (rule->direction == IDMAP_DIRECTION_W2U)
961c5c4113dSnw141292 		(void) snprintf(buf, sizeof (buf), "AND w2u_order > 0"
962c5c4113dSnw141292 		    " AND (u2w_order = 0 OR u2w_order ISNULL)");
963cd37da74Snw141292 	else if (rule->direction == IDMAP_DIRECTION_U2W)
964c5c4113dSnw141292 		(void) snprintf(buf, sizeof (buf), "AND u2w_order > 0"
965c5c4113dSnw141292 		    " AND (w2u_order = 0 OR w2u_order ISNULL)");
966c5c4113dSnw141292 
967cd37da74Snw141292 	retcode = gen_sql_expr_from_rule(rule, &expr);
968cd37da74Snw141292 	if (retcode != IDMAP_SUCCESS)
969c5c4113dSnw141292 		goto out;
970c5c4113dSnw141292 
971cd37da74Snw141292 	sql = sqlite_mprintf("DELETE FROM namerules WHERE 1 %s %s;", expr,
972c5c4113dSnw141292 	    buf);
973c5c4113dSnw141292 
974c5c4113dSnw141292 	if (sql == NULL) {
975c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
976c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
977c5c4113dSnw141292 		goto out;
978c5c4113dSnw141292 	}
979c5c4113dSnw141292 
980cd37da74Snw141292 
98171590c90Snw141292 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, sql);
982c5c4113dSnw141292 
983c5c4113dSnw141292 out:
984cd37da74Snw141292 	if (expr != NULL)
985cd37da74Snw141292 		sqlite_freemem(expr);
98662c60062Sbaban 	if (sql != NULL)
987c5c4113dSnw141292 		sqlite_freemem(sql);
988c5c4113dSnw141292 	return (retcode);
989c5c4113dSnw141292 }
990c5c4113dSnw141292 
991c5c4113dSnw141292 /*
992c5c4113dSnw141292  * Compile the given SQL query and step just once.
993c5c4113dSnw141292  *
994c5c4113dSnw141292  * Input:
995c5c4113dSnw141292  * db  - db handle
996c5c4113dSnw141292  * sql - SQL statement
997c5c4113dSnw141292  *
998c5c4113dSnw141292  * Output:
999c5c4113dSnw141292  * vm     -  virtual SQL machine
1000c5c4113dSnw141292  * ncol   - number of columns in the result
1001c5c4113dSnw141292  * values - column values
1002c5c4113dSnw141292  *
1003c5c4113dSnw141292  * Return values:
1004c5c4113dSnw141292  * IDMAP_SUCCESS
1005c5c4113dSnw141292  * IDMAP_ERR_NOTFOUND
1006c5c4113dSnw141292  * IDMAP_ERR_INTERNAL
1007c5c4113dSnw141292  */
1008c5c4113dSnw141292 
1009cd37da74Snw141292 static
1010cd37da74Snw141292 idmap_retcode
1011c5c4113dSnw141292 sql_compile_n_step_once(sqlite *db, char *sql, sqlite_vm **vm, int *ncol,
1012cd37da74Snw141292 		int reqcol, const char ***values)
1013cd37da74Snw141292 {
1014c5c4113dSnw141292 	char		*errmsg = NULL;
101584decf41Sjp151216 	int		r;
1016c5c4113dSnw141292 
101784decf41Sjp151216 	if ((r = sqlite_compile(db, sql, NULL, vm, &errmsg)) != SQLITE_OK) {
1018cd37da74Snw141292 		idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
1019cd37da74Snw141292 		    CHECK_NULL(errmsg));
1020c5c4113dSnw141292 		sqlite_freemem(errmsg);
1021c5c4113dSnw141292 		return (IDMAP_ERR_INTERNAL);
1022c5c4113dSnw141292 	}
1023c5c4113dSnw141292 
1024c5c4113dSnw141292 	r = sqlite_step(*vm, ncol, values, NULL);
102584decf41Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
1026c5c4113dSnw141292 
102784decf41Sjp151216 	if (r == SQLITE_ROW) {
102862c60062Sbaban 		if (ncol != NULL && *ncol < reqcol) {
1029c5c4113dSnw141292 			(void) sqlite_finalize(*vm, NULL);
1030c5c4113dSnw141292 			*vm = NULL;
1031c5c4113dSnw141292 			return (IDMAP_ERR_INTERNAL);
1032c5c4113dSnw141292 		}
1033c5c4113dSnw141292 		/* Caller will call finalize after using the results */
1034c5c4113dSnw141292 		return (IDMAP_SUCCESS);
1035c5c4113dSnw141292 	} else if (r == SQLITE_DONE) {
1036c5c4113dSnw141292 		(void) sqlite_finalize(*vm, NULL);
1037c5c4113dSnw141292 		*vm = NULL;
1038c5c4113dSnw141292 		return (IDMAP_ERR_NOTFOUND);
1039c5c4113dSnw141292 	}
1040c5c4113dSnw141292 
1041c5c4113dSnw141292 	(void) sqlite_finalize(*vm, &errmsg);
1042c5c4113dSnw141292 	*vm = NULL;
1043cd37da74Snw141292 	idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
1044cd37da74Snw141292 	    CHECK_NULL(errmsg));
1045c5c4113dSnw141292 	sqlite_freemem(errmsg);
1046c5c4113dSnw141292 	return (IDMAP_ERR_INTERNAL);
1047c5c4113dSnw141292 }
1048c5c4113dSnw141292 
104962c60062Sbaban /*
1050e8c27ec8Sbaban  * Update nm_siduid and nm_sidgid fields in the lookup state.
1051e8c27ec8Sbaban  *
1052e8c27ec8Sbaban  * state->nm_siduid represents mode used by sid2uid and uid2sid
1053e8c27ec8Sbaban  * requests for directory-based name mappings. Similarly,
1054e8c27ec8Sbaban  * state->nm_sidgid represents mode used by sid2gid and gid2sid
1055e8c27ec8Sbaban  * requests.
1056e8c27ec8Sbaban  *
1057e8c27ec8Sbaban  * sid2uid/uid2sid:
1058e8c27ec8Sbaban  * none       -> ds_name_mapping_enabled != true
1059e8c27ec8Sbaban  * AD-mode    -> !nldap_winname_attr && ad_unixuser_attr
1060e8c27ec8Sbaban  * nldap-mode -> nldap_winname_attr && !ad_unixuser_attr
1061e8c27ec8Sbaban  * mixed-mode -> nldap_winname_attr && ad_unixuser_attr
1062e8c27ec8Sbaban  *
1063e8c27ec8Sbaban  * sid2gid/gid2sid:
1064e8c27ec8Sbaban  * none       -> ds_name_mapping_enabled != true
1065e8c27ec8Sbaban  * AD-mode    -> !nldap_winname_attr && ad_unixgroup_attr
1066e8c27ec8Sbaban  * nldap-mode -> nldap_winname_attr && !ad_unixgroup_attr
1067e8c27ec8Sbaban  * mixed-mode -> nldap_winname_attr && ad_unixgroup_attr
1068e8c27ec8Sbaban  */
1069e8c27ec8Sbaban idmap_retcode
1070e8c27ec8Sbaban get_ds_namemap_type(lookup_state_t *state)
1071e8c27ec8Sbaban {
1072e8c27ec8Sbaban 	state->nm_siduid = IDMAP_NM_NONE;
1073e8c27ec8Sbaban 	state->nm_sidgid = IDMAP_NM_NONE;
1074e8c27ec8Sbaban 	RDLOCK_CONFIG();
1075e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.ds_name_mapping_enabled == FALSE) {
1076e8c27ec8Sbaban 		UNLOCK_CONFIG();
1077e8c27ec8Sbaban 		return (IDMAP_SUCCESS);
1078e8c27ec8Sbaban 	}
1079e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.nldap_winname_attr != NULL) {
1080e8c27ec8Sbaban 		state->nm_siduid =
1081e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
1082e8c27ec8Sbaban 		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
1083e8c27ec8Sbaban 		state->nm_sidgid =
1084e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
1085e8c27ec8Sbaban 		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
1086e8c27ec8Sbaban 	} else {
1087e8c27ec8Sbaban 		state->nm_siduid =
1088e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
1089e8c27ec8Sbaban 		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
1090e8c27ec8Sbaban 		state->nm_sidgid =
1091e8c27ec8Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
1092e8c27ec8Sbaban 		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
1093e8c27ec8Sbaban 	}
1094e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL) {
1095e8c27ec8Sbaban 		state->ad_unixuser_attr =
1096e8c27ec8Sbaban 		    strdup(_idmapdstate.cfg->pgcfg.ad_unixuser_attr);
1097e8c27ec8Sbaban 		if (state->ad_unixuser_attr == NULL) {
1098e8c27ec8Sbaban 			UNLOCK_CONFIG();
1099e8c27ec8Sbaban 			return (IDMAP_ERR_MEMORY);
1100e8c27ec8Sbaban 		}
1101e8c27ec8Sbaban 	}
1102e8c27ec8Sbaban 	if (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL) {
1103e8c27ec8Sbaban 		state->ad_unixgroup_attr =
1104e8c27ec8Sbaban 		    strdup(_idmapdstate.cfg->pgcfg.ad_unixgroup_attr);
1105e8c27ec8Sbaban 		if (state->ad_unixgroup_attr == NULL) {
1106e8c27ec8Sbaban 			UNLOCK_CONFIG();
1107e8c27ec8Sbaban 			return (IDMAP_ERR_MEMORY);
1108e8c27ec8Sbaban 		}
1109e8c27ec8Sbaban 	}
1110e8c27ec8Sbaban 	UNLOCK_CONFIG();
1111e8c27ec8Sbaban 	return (IDMAP_SUCCESS);
1112e8c27ec8Sbaban }
1113e8c27ec8Sbaban 
1114e8c27ec8Sbaban /*
111562c60062Sbaban  * Table for well-known SIDs.
111662c60062Sbaban  *
111762c60062Sbaban  * Background:
111862c60062Sbaban  *
111976b27f93Sbaban  * Some of the well-known principals are stored under:
112062c60062Sbaban  * cn=WellKnown Security Principals, cn=Configuration, dc=<forestRootDomain>
112162c60062Sbaban  * They belong to objectClass "foreignSecurityPrincipal". They don't have
112262c60062Sbaban  * "samAccountName" nor "userPrincipalName" attributes. Their names are
112362c60062Sbaban  * available in "cn" and "name" attributes. Some of these principals have a
112462c60062Sbaban  * second entry under CN=ForeignSecurityPrincipals,dc=<forestRootDomain> and
112562c60062Sbaban  * these duplicate entries have the stringified SID in the "name" and "cn"
112662c60062Sbaban  * attributes instead of the actual name.
112762c60062Sbaban  *
112876b27f93Sbaban  * Those of the form S-1-5-32-X are Builtin groups and are stored in the
112976b27f93Sbaban  * cn=builtin container (except, Power Users which is not stored in AD)
113062c60062Sbaban  *
113176b27f93Sbaban  * These principals are and will remain constant. Therefore doing AD lookups
113276b27f93Sbaban  * provides no benefit. Also, using hard-coded table (and thus avoiding AD
113376b27f93Sbaban  * lookup) improves performance and avoids additional complexity in the
113476b27f93Sbaban  * adutils.c code. Moreover these SIDs can be used when no Active Directory
113576b27f93Sbaban  * is available (such as the CIFS server's "workgroup" mode).
113676b27f93Sbaban  *
113776b27f93Sbaban  * Notes:
113876b27f93Sbaban  * 1. Currently we don't support localization of well-known SID names,
113962c60062Sbaban  * unlike Windows.
114062c60062Sbaban  *
114176b27f93Sbaban  * 2. Other well-known SIDs i.e. S-1-5-<domain>-<w-k RID> are not stored
114276b27f93Sbaban  * here. AD does have normal user/group objects for these objects and
114376b27f93Sbaban  * can be looked up using the existing AD lookup code.
1144e8c27ec8Sbaban  *
1145e8c27ec8Sbaban  * 3. See comments above lookup_wksids_sid2pid() for more information
1146e8c27ec8Sbaban  * on how we lookup the wksids table.
114762c60062Sbaban  */
114862c60062Sbaban static wksids_table_t wksids[] = {
1149e8c27ec8Sbaban 	{"S-1-0", 0, "Nobody", 0, SENTINEL_PID, -1, 1},
1150e8c27ec8Sbaban 	{"S-1-1", 0, "Everyone", 0, SENTINEL_PID, -1, -1},
1151e8c27ec8Sbaban 	{"S-1-3", 0, "Creator Owner", 1, IDMAP_WK_CREATOR_OWNER_UID, 1, 0},
1152e8c27ec8Sbaban 	{"S-1-3", 1, "Creator Group", 0, IDMAP_WK_CREATOR_GROUP_GID, 0, 0},
1153e8c27ec8Sbaban 	{"S-1-3", 2, "Creator Owner Server", 1, SENTINEL_PID, -1, -1},
1154e8c27ec8Sbaban 	{"S-1-3", 3, "Creator Group Server", 0, SENTINEL_PID, -1, 1},
1155e8c27ec8Sbaban 	{"S-1-3", 4, "Owner Rights", 0, SENTINEL_PID, -1, -1},
1156e8c27ec8Sbaban 	{"S-1-5", 1, "Dialup", 0, SENTINEL_PID, -1, -1},
1157e8c27ec8Sbaban 	{"S-1-5", 2, "Network", 0, SENTINEL_PID, -1, -1},
1158e8c27ec8Sbaban 	{"S-1-5", 3, "Batch", 0, SENTINEL_PID, -1, -1},
1159e8c27ec8Sbaban 	{"S-1-5", 4, "Interactive", 0, SENTINEL_PID, -1, -1},
1160e8c27ec8Sbaban 	{"S-1-5", 6, "Service", 0, SENTINEL_PID, -1, -1},
1161e8c27ec8Sbaban 	{"S-1-5", 7, "Anonymous Logon", 0, GID_NOBODY, 0, 0},
1162e8c27ec8Sbaban 	{"S-1-5", 7, "Anonymous Logon", 0, UID_NOBODY, 1, 0},
1163e8c27ec8Sbaban 	{"S-1-5", 8, "Proxy", 0, SENTINEL_PID, -1, -1},
1164e8c27ec8Sbaban 	{"S-1-5", 9, "Enterprise Domain Controllers", 0, SENTINEL_PID, -1, -1},
1165e8c27ec8Sbaban 	{"S-1-5", 10, "Self", 0, SENTINEL_PID, -1, -1},
1166e8c27ec8Sbaban 	{"S-1-5", 11, "Authenticated Users", 0, SENTINEL_PID, -1, -1},
1167e8c27ec8Sbaban 	{"S-1-5", 12, "Restricted Code", 0, SENTINEL_PID, -1, -1},
1168e8c27ec8Sbaban 	{"S-1-5", 13, "Terminal Server User", 0, SENTINEL_PID, -1, -1},
1169e8c27ec8Sbaban 	{"S-1-5", 14, "Remote Interactive Logon", 0, SENTINEL_PID, -1, -1},
1170e8c27ec8Sbaban 	{"S-1-5", 15, "This Organization", 0, SENTINEL_PID, -1, -1},
1171e8c27ec8Sbaban 	{"S-1-5", 17, "IUSR", 0, SENTINEL_PID, -1, -1},
1172e8c27ec8Sbaban 	{"S-1-5", 18, "Local System", 0, IDMAP_WK_LOCAL_SYSTEM_GID, 0, 0},
1173e8c27ec8Sbaban 	{"S-1-5", 19, "Local Service", 0, SENTINEL_PID, -1, -1},
1174e8c27ec8Sbaban 	{"S-1-5", 20, "Network Service", 0, SENTINEL_PID, -1, -1},
1175e8c27ec8Sbaban 	{"S-1-5", 1000, "Other Organization", 0, SENTINEL_PID, -1, -1},
1176e8c27ec8Sbaban 	{"S-1-5-32", 544, "Administrators", 0, SENTINEL_PID, -1, -1},
1177e8c27ec8Sbaban 	{"S-1-5-32", 545, "Users", 0, SENTINEL_PID, -1, -1},
1178e8c27ec8Sbaban 	{"S-1-5-32", 546, "Guests", 0, SENTINEL_PID, -1, -1},
1179e8c27ec8Sbaban 	{"S-1-5-32", 547, "Power Users", 0, SENTINEL_PID, -1, -1},
1180e8c27ec8Sbaban 	{"S-1-5-32", 548, "Account Operators", 0, SENTINEL_PID, -1, -1},
1181e8c27ec8Sbaban 	{"S-1-5-32", 549, "Server Operators", 0, SENTINEL_PID, -1, -1},
1182e8c27ec8Sbaban 	{"S-1-5-32", 550, "Print Operators", 0, SENTINEL_PID, -1, -1},
1183e8c27ec8Sbaban 	{"S-1-5-32", 551, "Backup Operators", 0, SENTINEL_PID, -1, -1},
1184e8c27ec8Sbaban 	{"S-1-5-32", 552, "Replicator", 0, SENTINEL_PID, -1, -1},
118576b27f93Sbaban 	{"S-1-5-32", 554, "Pre-Windows 2000 Compatible Access", 0,
1186e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1187e8c27ec8Sbaban 	{"S-1-5-32", 555, "Remote Desktop Users", 0, SENTINEL_PID, -1, -1},
118876b27f93Sbaban 	{"S-1-5-32", 556, "Network Configuration Operators", 0,
1189e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
119076b27f93Sbaban 	{"S-1-5-32", 557, "Incoming Forest Trust Builders", 0,
1191e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1192e8c27ec8Sbaban 	{"S-1-5-32", 558, "Performance Monitor Users", 0, SENTINEL_PID, -1, -1},
1193e8c27ec8Sbaban 	{"S-1-5-32", 559, "Performance Log Users", 0, SENTINEL_PID, -1, -1},
119476b27f93Sbaban 	{"S-1-5-32", 560, "Windows Authorization Access Group", 0,
1195e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
119676b27f93Sbaban 	{"S-1-5-32", 561, "Terminal Server License Servers", 0,
1197e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1198e8c27ec8Sbaban 	{"S-1-5-32", 561, "Distributed COM Users", 0, SENTINEL_PID, -1, -1},
1199e8c27ec8Sbaban 	{"S-1-5-32", 568, "IIS_IUSRS", 0, SENTINEL_PID, -1, -1},
1200e8c27ec8Sbaban 	{"S-1-5-32", 569, "Cryptographic Operators", 0, SENTINEL_PID, -1, -1},
1201e8c27ec8Sbaban 	{"S-1-5-32", 573, "Event Log Readers", 0, SENTINEL_PID, -1, -1},
120276b27f93Sbaban 	{"S-1-5-32", 574, "Certificate Service DCOM Access", 0,
1203e8c27ec8Sbaban 	    SENTINEL_PID, -1, -1},
1204e8c27ec8Sbaban 	{"S-1-5-64", 21, "Digest Authentication", 0, SENTINEL_PID, -1, -1},
1205e8c27ec8Sbaban 	{"S-1-5-64", 10, "NTLM Authentication", 0, SENTINEL_PID, -1, -1},
1206e8c27ec8Sbaban 	{"S-1-5-64", 14, "SChannel Authentication", 0, SENTINEL_PID, -1, -1},
1207e8c27ec8Sbaban 	{NULL, UINT32_MAX, NULL, -1, SENTINEL_PID, -1, -1}
1208c5c4113dSnw141292 };
1209c5c4113dSnw141292 
1210e8c27ec8Sbaban /*
1211e8c27ec8Sbaban  * Lookup well-known SIDs table either by winname or by SID.
1212e8c27ec8Sbaban  * If the given winname or SID is a well-known SID then we set wksid
1213e8c27ec8Sbaban  * variable and then proceed to see if the SID has a hard mapping to
1214e8c27ec8Sbaban  * a particular UID/GID (Ex: Creator Owner/Creator Group mapped to
1215e8c27ec8Sbaban  * fixed ephemeral ids). If we find such mapping then we return
1216e8c27ec8Sbaban  * success otherwise notfound. If a well-known SID is mapped to
1217e8c27ec8Sbaban  * SENTINEL_PID and the direction field is set (bi-directional or
1218e8c27ec8Sbaban  * win2unix) then we treat it as inhibited mapping and return no
1219e8c27ec8Sbaban  * mapping (Ex. S-1-0-0).
1220e8c27ec8Sbaban  */
1221cd37da74Snw141292 static
1222cd37da74Snw141292 idmap_retcode
1223e8c27ec8Sbaban lookup_wksids_sid2pid(idmap_mapping *req, idmap_id_res *res, int *wksid)
1224cd37da74Snw141292 {
1225c5c4113dSnw141292 	int i;
122662c60062Sbaban 
1227e8c27ec8Sbaban 	*wksid = 0;
1228e8c27ec8Sbaban 
1229e8c27ec8Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
1230e8c27ec8Sbaban 		if (req->id1.idmap_id_u.sid.prefix != NULL) {
1231e8c27ec8Sbaban 			if ((strcasecmp(wksids[i].sidprefix,
1232e8c27ec8Sbaban 			    req->id1.idmap_id_u.sid.prefix) != 0) ||
1233e8c27ec8Sbaban 			    wksids[i].rid != req->id1.idmap_id_u.sid.rid)
1234e8c27ec8Sbaban 				/* this is not our SID */
1235e8c27ec8Sbaban 				continue;
1236e8c27ec8Sbaban 			if (req->id1name == NULL) {
1237e8c27ec8Sbaban 				req->id1name = strdup(wksids[i].winname);
1238e8c27ec8Sbaban 				if (req->id1name == NULL)
1239e8c27ec8Sbaban 					return (IDMAP_ERR_MEMORY);
1240e8c27ec8Sbaban 			}
1241e8c27ec8Sbaban 		} else if (req->id1name != NULL) {
1242e8c27ec8Sbaban 			if (strcasecmp(wksids[i].winname, req->id1name) != 0)
1243e8c27ec8Sbaban 				/* this is not our winname */
1244e8c27ec8Sbaban 				continue;
1245e8c27ec8Sbaban 			req->id1.idmap_id_u.sid.prefix =
1246e8c27ec8Sbaban 			    strdup(wksids[i].sidprefix);
1247e8c27ec8Sbaban 			if (req->id1.idmap_id_u.sid.prefix == NULL)
1248e8c27ec8Sbaban 				return (IDMAP_ERR_MEMORY);
1249e8c27ec8Sbaban 			req->id1.idmap_id_u.sid.rid = wksids[i].rid;
1250e8c27ec8Sbaban 		}
1251e8c27ec8Sbaban 
1252e8c27ec8Sbaban 		*wksid = 1;
1253e8c27ec8Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
1254e8c27ec8Sbaban 
1255e8c27ec8Sbaban 		req->id1.idtype = (wksids[i].is_wuser) ?
1256e8c27ec8Sbaban 		    IDMAP_USID : IDMAP_GSID;
1257e8c27ec8Sbaban 
1258e8c27ec8Sbaban 		if (wksids[i].pid == SENTINEL_PID) {
1259e8c27ec8Sbaban 			if (wksids[i].direction == IDMAP_DIRECTION_BI ||
1260e8c27ec8Sbaban 			    wksids[i].direction == IDMAP_DIRECTION_W2U)
1261e8c27ec8Sbaban 				/* Inhibited */
1262e8c27ec8Sbaban 				return (IDMAP_ERR_NOMAPPING);
1263e8c27ec8Sbaban 			/* Not mapped */
1264e8c27ec8Sbaban 			return (IDMAP_ERR_NOTFOUND);
1265e8c27ec8Sbaban 		} else if (wksids[i].direction == IDMAP_DIRECTION_U2W)
126662c60062Sbaban 			continue;
126762c60062Sbaban 
1268e8c27ec8Sbaban 		switch (res->id.idtype) {
1269c5c4113dSnw141292 		case IDMAP_UID:
127062c60062Sbaban 			if (wksids[i].is_user == 0)
127162c60062Sbaban 				continue;
127262c60062Sbaban 			res->id.idmap_id_u.uid = wksids[i].pid;
127362c60062Sbaban 			res->direction = wksids[i].direction;
1274c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1275c5c4113dSnw141292 		case IDMAP_GID:
127662c60062Sbaban 			if (wksids[i].is_user == 1)
127762c60062Sbaban 				continue;
127862c60062Sbaban 			res->id.idmap_id_u.gid = wksids[i].pid;
127962c60062Sbaban 			res->direction = wksids[i].direction;
1280c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1281c5c4113dSnw141292 		case IDMAP_POSIXID:
128262c60062Sbaban 			res->id.idmap_id_u.uid = wksids[i].pid;
128362c60062Sbaban 			res->id.idtype = (!wksids[i].is_user) ?
1284c5c4113dSnw141292 			    IDMAP_GID : IDMAP_UID;
128562c60062Sbaban 			res->direction = wksids[i].direction;
1286c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1287c5c4113dSnw141292 		default:
1288c5c4113dSnw141292 			return (IDMAP_ERR_NOTSUPPORTED);
1289c5c4113dSnw141292 		}
1290c5c4113dSnw141292 	}
1291c5c4113dSnw141292 	return (IDMAP_ERR_NOTFOUND);
1292c5c4113dSnw141292 }
1293c5c4113dSnw141292 
1294cd37da74Snw141292 
1295cd37da74Snw141292 static
1296cd37da74Snw141292 idmap_retcode
1297cd37da74Snw141292 lookup_wksids_pid2sid(idmap_mapping *req, idmap_id_res *res, int is_user)
1298cd37da74Snw141292 {
1299c5c4113dSnw141292 	int i;
1300e8c27ec8Sbaban 	if (req->id1.idmap_id_u.uid == SENTINEL_PID)
1301e8c27ec8Sbaban 		return (IDMAP_ERR_NOTFOUND);
130262c60062Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
130362c60062Sbaban 		if (wksids[i].pid == req->id1.idmap_id_u.uid &&
130462c60062Sbaban 		    wksids[i].is_user == is_user &&
130562c60062Sbaban 		    wksids[i].direction != IDMAP_DIRECTION_W2U) {
1306e8c27ec8Sbaban 			if (res->id.idtype == IDMAP_SID) {
1307e8c27ec8Sbaban 				res->id.idtype = (wksids[i].is_wuser) ?
1308e8c27ec8Sbaban 				    IDMAP_USID : IDMAP_GSID;
1309e8c27ec8Sbaban 			}
131062c60062Sbaban 			res->id.idmap_id_u.sid.rid = wksids[i].rid;
1311c5c4113dSnw141292 			res->id.idmap_id_u.sid.prefix =
131262c60062Sbaban 			    strdup(wksids[i].sidprefix);
1313c5c4113dSnw141292 			if (res->id.idmap_id_u.sid.prefix == NULL) {
1314c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1315c5c4113dSnw141292 				return (IDMAP_ERR_MEMORY);
1316c5c4113dSnw141292 			}
131762c60062Sbaban 			res->direction = wksids[i].direction;
1318c5c4113dSnw141292 			return (IDMAP_SUCCESS);
1319c5c4113dSnw141292 		}
1320c5c4113dSnw141292 	}
132162c60062Sbaban 	return (IDMAP_ERR_NOTFOUND);
132262c60062Sbaban }
132362c60062Sbaban 
1324cd37da74Snw141292 static
1325cd37da74Snw141292 idmap_retcode
1326cd37da74Snw141292 lookup_wksids_name2sid(const char *name, char **canonname, char **sidprefix,
1327cd37da74Snw141292 	idmap_rid_t *rid, int *type)
1328cd37da74Snw141292 {
132962c60062Sbaban 	int i;
133062c60062Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
1331e8c27ec8Sbaban 		if (strcasecmp(wksids[i].winname, name) != 0)
1332e8c27ec8Sbaban 			continue;
1333e8c27ec8Sbaban 		if (sidprefix != NULL &&
1334e8c27ec8Sbaban 		    (*sidprefix = strdup(wksids[i].sidprefix)) == NULL) {
133562c60062Sbaban 			idmapdlog(LOG_ERR, "Out of memory");
133662c60062Sbaban 			return (IDMAP_ERR_MEMORY);
133762c60062Sbaban 		}
1338cd37da74Snw141292 		if (canonname != NULL &&
1339cd37da74Snw141292 		    (*canonname = strdup(wksids[i].winname)) == NULL) {
1340cd37da74Snw141292 			idmapdlog(LOG_ERR, "Out of memory");
1341e8c27ec8Sbaban 			if (sidprefix != NULL) {
1342e8c27ec8Sbaban 				free(*sidprefix);
1343e8c27ec8Sbaban 				*sidprefix = NULL;
1344e8c27ec8Sbaban 			}
1345cd37da74Snw141292 			return (IDMAP_ERR_MEMORY);
1346cd37da74Snw141292 		}
134762c60062Sbaban 		if (type != NULL)
1348e8c27ec8Sbaban 			*type = (wksids[i].is_wuser) ?
134962c60062Sbaban 			    _IDMAP_T_USER : _IDMAP_T_GROUP;
135062c60062Sbaban 		if (rid != NULL)
135162c60062Sbaban 			*rid = wksids[i].rid;
135262c60062Sbaban 		return (IDMAP_SUCCESS);
135362c60062Sbaban 	}
1354c5c4113dSnw141292 	return (IDMAP_ERR_NOTFOUND);
1355c5c4113dSnw141292 }
1356c5c4113dSnw141292 
1357cd37da74Snw141292 static
1358cd37da74Snw141292 idmap_retcode
1359cd37da74Snw141292 lookup_cache_sid2pid(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
1360cd37da74Snw141292 {
1361c5c4113dSnw141292 	char		*end;
1362c5c4113dSnw141292 	char		*sql = NULL;
1363c5c4113dSnw141292 	const char	**values;
1364c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
1365c5c4113dSnw141292 	int		ncol, is_user;
1366c5c4113dSnw141292 	uid_t		pid;
1367c5c4113dSnw141292 	time_t		curtime, exp;
1368c5c4113dSnw141292 	idmap_retcode	retcode;
1369042addd6Sbaban 	char		*is_user_string, *lower_name;
1370c5c4113dSnw141292 
1371c5c4113dSnw141292 	/* Current time */
1372c5c4113dSnw141292 	errno = 0;
1373c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
1374cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
1375c5c4113dSnw141292 		    strerror(errno));
1376c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
1377c5c4113dSnw141292 		goto out;
1378c5c4113dSnw141292 	}
1379c5c4113dSnw141292 
1380e8c27ec8Sbaban 	switch (res->id.idtype) {
1381cd37da74Snw141292 	case IDMAP_UID:
1382cd37da74Snw141292 		is_user_string = "1";
1383cd37da74Snw141292 		break;
1384cd37da74Snw141292 	case IDMAP_GID:
1385cd37da74Snw141292 		is_user_string = "0";
1386cd37da74Snw141292 		break;
1387cd37da74Snw141292 	case IDMAP_POSIXID:
1388cd37da74Snw141292 		/* the non-diagonal mapping */
1389cd37da74Snw141292 		is_user_string = "is_wuser";
1390cd37da74Snw141292 		break;
1391cd37da74Snw141292 	default:
1392cd37da74Snw141292 		retcode = IDMAP_ERR_NOTSUPPORTED;
1393cd37da74Snw141292 		goto out;
1394cd37da74Snw141292 	}
1395cd37da74Snw141292 
1396c5c4113dSnw141292 	/* SQL to lookup the cache */
1397e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
1398e8c27ec8Sbaban 		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
1399e8c27ec8Sbaban 		    "unixname, u2w, is_wuser "
1400cd37da74Snw141292 		    "FROM idmap_cache WHERE is_user = %s AND "
1401c5c4113dSnw141292 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
1402c5c4113dSnw141292 		    "(pid >= 2147483648 OR "
1403c5c4113dSnw141292 		    "(expiration = 0 OR expiration ISNULL OR "
1404c5c4113dSnw141292 		    "expiration > %d));",
1405e8c27ec8Sbaban 		    is_user_string, req->id1.idmap_id_u.sid.prefix,
1406e8c27ec8Sbaban 		    req->id1.idmap_id_u.sid.rid, curtime);
1407e8c27ec8Sbaban 	} else if (req->id1name != NULL) {
1408042addd6Sbaban 		if ((lower_name = tolower_u8(req->id1name)) == NULL)
1409042addd6Sbaban 			lower_name = req->id1name;
1410e8c27ec8Sbaban 		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
1411e8c27ec8Sbaban 		    "unixname, u2w, is_wuser "
1412e8c27ec8Sbaban 		    "FROM idmap_cache WHERE is_user = %s AND "
1413e8c27ec8Sbaban 		    "winname = %Q AND windomain = %Q AND w2u = 1 AND "
1414e8c27ec8Sbaban 		    "(pid >= 2147483648 OR "
1415e8c27ec8Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
1416e8c27ec8Sbaban 		    "expiration > %d));",
1417042addd6Sbaban 		    is_user_string, lower_name, req->id1domain, curtime);
1418042addd6Sbaban 		if (lower_name != req->id1name)
1419042addd6Sbaban 			free(lower_name);
1420e8c27ec8Sbaban 	} else {
1421e8c27ec8Sbaban 		retcode = IDMAP_ERR_ARG;
1422e8c27ec8Sbaban 		goto out;
1423e8c27ec8Sbaban 	}
1424e8c27ec8Sbaban 
1425c5c4113dSnw141292 	if (sql == NULL) {
1426c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
1427c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
1428c5c4113dSnw141292 		goto out;
1429c5c4113dSnw141292 	}
1430e8c27ec8Sbaban 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 6, &values);
1431c5c4113dSnw141292 	sqlite_freemem(sql);
1432c5c4113dSnw141292 
1433c5c4113dSnw141292 	if (retcode == IDMAP_ERR_NOTFOUND) {
1434c5c4113dSnw141292 		goto out;
1435c5c4113dSnw141292 	} else if (retcode == IDMAP_SUCCESS) {
1436c5c4113dSnw141292 		/* sanity checks */
1437c5c4113dSnw141292 		if (values[0] == NULL || values[1] == NULL) {
1438c5c4113dSnw141292 			retcode = IDMAP_ERR_CACHE;
1439c5c4113dSnw141292 			goto out;
1440c5c4113dSnw141292 		}
1441c5c4113dSnw141292 
1442c5c4113dSnw141292 		pid = strtoul(values[0], &end, 10);
1443c5c4113dSnw141292 		is_user = strncmp(values[1], "0", 2) ? 1 : 0;
1444c5c4113dSnw141292 
1445cd37da74Snw141292 		if (is_user) {
1446cd37da74Snw141292 			res->id.idtype = IDMAP_UID;
1447cd37da74Snw141292 			res->id.idmap_id_u.uid = pid;
1448cd37da74Snw141292 		} else {
1449cd37da74Snw141292 			res->id.idtype = IDMAP_GID;
1450cd37da74Snw141292 			res->id.idmap_id_u.gid = pid;
1451cd37da74Snw141292 		}
1452cd37da74Snw141292 
1453c5c4113dSnw141292 		/*
1454c5c4113dSnw141292 		 * We may have an expired ephemeral mapping. Consider
1455c5c4113dSnw141292 		 * the expired entry as valid if we are not going to
1456c5c4113dSnw141292 		 * perform name-based mapping. But do not renew the
1457c5c4113dSnw141292 		 * expiration.
1458c5c4113dSnw141292 		 * If we will be doing name-based mapping then store the
1459c5c4113dSnw141292 		 * ephemeral pid in the result so that we can use it
1460c5c4113dSnw141292 		 * if we end up doing dynamic mapping again.
1461c5c4113dSnw141292 		 */
1462c5c4113dSnw141292 		if (!DO_NOT_ALLOC_NEW_ID_MAPPING(req) &&
1463cd37da74Snw141292 		    !AVOID_NAMESERVICE(req) &&
1464cd37da74Snw141292 		    IS_EPHEMERAL(pid) && values[2] != NULL) {
1465c5c4113dSnw141292 			exp = strtoll(values[2], &end, 10);
1466c5c4113dSnw141292 			if (exp && exp <= curtime) {
1467c5c4113dSnw141292 				/* Store the ephemeral pid */
1468651c0131Sbaban 				res->direction = IDMAP_DIRECTION_BI;
1469cd37da74Snw141292 				req->direction |= is_user
1470cd37da74Snw141292 				    ? _IDMAP_F_EXP_EPH_UID
1471cd37da74Snw141292 				    : _IDMAP_F_EXP_EPH_GID;
1472c5c4113dSnw141292 				retcode = IDMAP_ERR_NOTFOUND;
1473c5c4113dSnw141292 			}
1474c5c4113dSnw141292 		}
1475c5c4113dSnw141292 	}
1476c5c4113dSnw141292 
1477c5c4113dSnw141292 out:
1478c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
147962c60062Sbaban 		if (values[4] != NULL)
1480c5c4113dSnw141292 			res->direction =
1481651c0131Sbaban 			    (strtol(values[4], &end, 10) == 0)?
1482651c0131Sbaban 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
1483c5c4113dSnw141292 		else
1484651c0131Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
1485c5c4113dSnw141292 
148662c60062Sbaban 		if (values[3] != NULL) {
1487e8c27ec8Sbaban 			if (req->id2name != NULL)
1488e8c27ec8Sbaban 				free(req->id2name);
14898e228215Sdm199847 			req->id2name = strdup(values[3]);
14908e228215Sdm199847 			if (req->id2name == NULL) {
1491c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1492c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
1493c5c4113dSnw141292 			}
1494c5c4113dSnw141292 		}
1495e8c27ec8Sbaban 
1496e8c27ec8Sbaban 		req->id1.idtype = strncmp(values[5], "0", 2) ?
1497e8c27ec8Sbaban 		    IDMAP_USID : IDMAP_GSID;
1498c5c4113dSnw141292 	}
149962c60062Sbaban 	if (vm != NULL)
1500c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
1501c5c4113dSnw141292 	return (retcode);
1502c5c4113dSnw141292 }
1503c5c4113dSnw141292 
1504cd37da74Snw141292 static
1505cd37da74Snw141292 idmap_retcode
150662c60062Sbaban lookup_cache_sid2name(sqlite *cache, const char *sidprefix, idmap_rid_t rid,
1507cd37da74Snw141292 		char **name, char **domain, int *type)
1508cd37da74Snw141292 {
1509c5c4113dSnw141292 	char		*end;
1510c5c4113dSnw141292 	char		*sql = NULL;
1511c5c4113dSnw141292 	const char	**values;
1512c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
1513c5c4113dSnw141292 	int		ncol;
1514c5c4113dSnw141292 	time_t		curtime;
1515c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
1516c5c4113dSnw141292 
1517c5c4113dSnw141292 	/* Get current time */
1518c5c4113dSnw141292 	errno = 0;
1519c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
1520cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
1521c5c4113dSnw141292 		    strerror(errno));
1522c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
1523c5c4113dSnw141292 		goto out;
1524c5c4113dSnw141292 	}
1525c5c4113dSnw141292 
1526c5c4113dSnw141292 	/* SQL to lookup the cache */
1527cd37da74Snw141292 	sql = sqlite_mprintf("SELECT canon_name, domain, type "
1528cd37da74Snw141292 	    "FROM name_cache WHERE "
1529c5c4113dSnw141292 	    "sidprefix = %Q AND rid = %u AND "
1530c5c4113dSnw141292 	    "(expiration = 0 OR expiration ISNULL OR "
1531c5c4113dSnw141292 	    "expiration > %d);",
1532c5c4113dSnw141292 	    sidprefix, rid, curtime);
1533c5c4113dSnw141292 	if (sql == NULL) {
1534c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
1535c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
1536c5c4113dSnw141292 		goto out;
1537c5c4113dSnw141292 	}
1538c5c4113dSnw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 3, &values);
1539c5c4113dSnw141292 	sqlite_freemem(sql);
1540c5c4113dSnw141292 
1541c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
154262c60062Sbaban 		if (type != NULL) {
1543c5c4113dSnw141292 			if (values[2] == NULL) {
1544c5c4113dSnw141292 				retcode = IDMAP_ERR_CACHE;
1545c5c4113dSnw141292 				goto out;
1546c5c4113dSnw141292 			}
1547c5c4113dSnw141292 			*type = strtol(values[2], &end, 10);
1548c5c4113dSnw141292 		}
1549c5c4113dSnw141292 
155062c60062Sbaban 		if (name != NULL && values[0] != NULL) {
1551c5c4113dSnw141292 			if ((*name = strdup(values[0])) == NULL) {
1552c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1553c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
1554c5c4113dSnw141292 				goto out;
1555c5c4113dSnw141292 			}
1556c5c4113dSnw141292 		}
1557c5c4113dSnw141292 
155862c60062Sbaban 		if (domain != NULL && values[1] != NULL) {
1559c5c4113dSnw141292 			if ((*domain = strdup(values[1])) == NULL) {
156062c60062Sbaban 				if (name != NULL && *name) {
1561c5c4113dSnw141292 					free(*name);
1562c5c4113dSnw141292 					*name = NULL;
1563c5c4113dSnw141292 				}
1564c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
1565c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
1566c5c4113dSnw141292 				goto out;
1567c5c4113dSnw141292 			}
1568c5c4113dSnw141292 		}
1569c5c4113dSnw141292 	}
1570c5c4113dSnw141292 
1571c5c4113dSnw141292 out:
157262c60062Sbaban 	if (vm != NULL)
1573c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
1574c5c4113dSnw141292 	return (retcode);
1575c5c4113dSnw141292 }
1576c5c4113dSnw141292 
1577c5c4113dSnw141292 /*
1578e8c27ec8Sbaban  * Given SID, find winname using name_cache OR
1579e8c27ec8Sbaban  * Given winname, find SID using name_cache.
1580e8c27ec8Sbaban  * Used when mapping win to unix i.e. req->id1 is windows id and
1581e8c27ec8Sbaban  * req->id2 is unix id
1582c5c4113dSnw141292  */
1583cd37da74Snw141292 static
1584cd37da74Snw141292 idmap_retcode
1585e8c27ec8Sbaban lookup_name_cache(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
1586cd37da74Snw141292 {
1587c5c4113dSnw141292 	int		type = -1;
1588c5c4113dSnw141292 	idmap_retcode	retcode;
1589e8c27ec8Sbaban 	char		*sidprefix = NULL;
1590c5c4113dSnw141292 	idmap_rid_t	rid;
1591c5c4113dSnw141292 	char		*name = NULL, *domain = NULL;
1592c5c4113dSnw141292 
1593e8c27ec8Sbaban 	/* Done if we've both sid and winname */
1594e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL && req->id1name != NULL)
1595e8c27ec8Sbaban 		return (IDMAP_SUCCESS);
1596c5c4113dSnw141292 
1597e8c27ec8Sbaban 	/* Lookup sid to winname */
1598e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
1599e8c27ec8Sbaban 		retcode = lookup_cache_sid2name(cache,
1600e8c27ec8Sbaban 		    req->id1.idmap_id_u.sid.prefix,
1601e8c27ec8Sbaban 		    req->id1.idmap_id_u.sid.rid, &name, &domain, &type);
160262c60062Sbaban 		goto out;
1603e8c27ec8Sbaban 	}
160462c60062Sbaban 
1605e8c27ec8Sbaban 	/* Lookup winame to sid */
1606e8c27ec8Sbaban 	retcode = lookup_cache_name2sid(cache, req->id1name, req->id1domain,
1607e8c27ec8Sbaban 	    &name, &sidprefix, &rid, &type);
1608c5c4113dSnw141292 
160962c60062Sbaban out:
1610e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
1611c5c4113dSnw141292 		free(name);
1612c5c4113dSnw141292 		free(domain);
1613e8c27ec8Sbaban 		free(sidprefix);
1614e8c27ec8Sbaban 		return (retcode);
1615e8c27ec8Sbaban 	}
1616e8c27ec8Sbaban 
1617e8c27ec8Sbaban 	if (res->id.idtype == IDMAP_POSIXID) {
1618e8c27ec8Sbaban 		res->id.idtype = (type == _IDMAP_T_USER) ?
1619e8c27ec8Sbaban 		    IDMAP_UID : IDMAP_GID;
1620e8c27ec8Sbaban 	}
1621e8c27ec8Sbaban 	req->id1.idtype = (type == _IDMAP_T_USER) ?
1622e8c27ec8Sbaban 	    IDMAP_USID : IDMAP_GSID;
1623e8c27ec8Sbaban 
1624e8c27ec8Sbaban 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
1625e8c27ec8Sbaban 	if (name != NULL) {
1626e8c27ec8Sbaban 		free(req->id1name);	/* Free existing winname */
1627e8c27ec8Sbaban 		req->id1name = name;	/* and use canonical name instead */
1628e8c27ec8Sbaban 	}
1629e8c27ec8Sbaban 	if (req->id1domain == NULL)
1630e8c27ec8Sbaban 		req->id1domain = domain;
1631e8c27ec8Sbaban 	if (req->id1.idmap_id_u.sid.prefix == NULL) {
1632e8c27ec8Sbaban 		req->id1.idmap_id_u.sid.prefix = sidprefix;
1633e8c27ec8Sbaban 		req->id1.idmap_id_u.sid.rid = rid;
1634c5c4113dSnw141292 	}
1635c5c4113dSnw141292 	return (retcode);
1636c5c4113dSnw141292 }
1637c5c4113dSnw141292 
1638e8c27ec8Sbaban /*
1639e8c27ec8Sbaban  * Batch AD lookups
1640e8c27ec8Sbaban  */
1641c5c4113dSnw141292 idmap_retcode
1642e8c27ec8Sbaban ad_lookup_batch(lookup_state_t *state, idmap_mapping_batch *batch,
1643cd37da74Snw141292 		idmap_ids_res *result)
1644cd37da74Snw141292 {
1645c5c4113dSnw141292 	idmap_retcode	retcode;
1646e8c27ec8Sbaban 	int		i, add, type, is_wuser, is_user;
1647e8c27ec8Sbaban 	int		retries = 0, eunixtype;
1648e8c27ec8Sbaban 	char		**unixname;
1649c5c4113dSnw141292 	idmap_mapping	*req;
1650c5c4113dSnw141292 	idmap_id_res	*res;
1651e8c27ec8Sbaban 	idmap_query_state_t	*qs = NULL;
1652e8c27ec8Sbaban 
1653e8c27ec8Sbaban 	/*
1654e8c27ec8Sbaban 	 * Since req->id2.idtype is unused, we will use it here
1655e8c27ec8Sbaban 	 * to retrieve the value of sid_type. But it needs to be
1656e8c27ec8Sbaban 	 * reset to IDMAP_NONE before we return to prevent xdr
1657e8c27ec8Sbaban 	 * from mis-interpreting req->id2 when it tries to free
1658e8c27ec8Sbaban 	 * the input argument. Other option is to allocate an
1659e8c27ec8Sbaban 	 * array of integers and use it instead for the batched
1660e8c27ec8Sbaban 	 * call. But why un-necessarily allocate memory. That may
1661e8c27ec8Sbaban 	 * be an option if req->id2.idtype cannot be re-used in
1662e8c27ec8Sbaban 	 * future.
1663e8c27ec8Sbaban 	 */
1664c5c4113dSnw141292 
1665c5c4113dSnw141292 	if (state->ad_nqueries == 0)
1666c5c4113dSnw141292 		return (IDMAP_SUCCESS);
1667c5c4113dSnw141292 
1668c5c4113dSnw141292 retry:
1669e8c27ec8Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, state->ad_nqueries,
1670e8c27ec8Sbaban 	    &qs);
1671e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
16720dcc7149Snw141292 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
16730dcc7149Snw141292 			goto retry;
1674*349d5d8fSnw141292 		degrade_svc(1, "failed to create batch for AD lookup");
1675e8c27ec8Sbaban 		goto out;
1676c5c4113dSnw141292 	}
1677c5c4113dSnw141292 
1678c8e26105Sjp151216 	restore_svc();
1679c8e26105Sjp151216 
1680e8c27ec8Sbaban 	idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
1681e8c27ec8Sbaban 	    state->ad_unixgroup_attr);
1682e8c27ec8Sbaban 
1683e8c27ec8Sbaban 	for (i = 0, add = 0; i < batch->idmap_mapping_batch_len; i++) {
1684c5c4113dSnw141292 		req = &batch->idmap_mapping_batch_val[i];
1685c5c4113dSnw141292 		res = &result->ids.ids_val[i];
1686e8c27ec8Sbaban 		retcode = IDMAP_SUCCESS;
1687e8c27ec8Sbaban 		req->id2.idtype = IDMAP_NONE;
1688c5c4113dSnw141292 
1689e8c27ec8Sbaban 		/* Skip if not marked for AD lookup */
1690e8c27ec8Sbaban 		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
1691e8c27ec8Sbaban 			continue;
1692e8c27ec8Sbaban 
1693c5c4113dSnw141292 		if (retries == 0)
1694c5c4113dSnw141292 			res->retcode = IDMAP_ERR_RETRIABLE_NET_ERR;
1695c5c4113dSnw141292 		else if (res->retcode != IDMAP_ERR_RETRIABLE_NET_ERR)
1696c5c4113dSnw141292 			continue;
1697e8c27ec8Sbaban 
1698e8c27ec8Sbaban 		if (IS_REQUEST_SID(*req, 1)) {
1699e8c27ec8Sbaban 			/* win to unix */
1700e8c27ec8Sbaban 
1701e8c27ec8Sbaban 			assert(req->id1.idmap_id_u.sid.prefix != NULL);
1702e8c27ec8Sbaban 
1703e8c27ec8Sbaban 			/* Lookup AD by SID */
1704e8c27ec8Sbaban 			unixname = NULL;
1705e8c27ec8Sbaban 			eunixtype = _IDMAP_T_UNDEF;
1706e8c27ec8Sbaban 			if (req->id2name == NULL) {
1707e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_UID &&
1708e8c27ec8Sbaban 				    AD_OR_MIXED(state->nm_siduid)) {
1709e8c27ec8Sbaban 					eunixtype = _IDMAP_T_USER;
1710e8c27ec8Sbaban 					unixname = &req->id2name;
1711e8c27ec8Sbaban 				} else if (res->id.idtype == IDMAP_GID &&
1712e8c27ec8Sbaban 				    AD_OR_MIXED(state->nm_sidgid)) {
1713e8c27ec8Sbaban 					eunixtype = _IDMAP_T_GROUP;
1714e8c27ec8Sbaban 					unixname = &req->id2name;
1715e8c27ec8Sbaban 				} else if (AD_OR_MIXED(state->nm_siduid) ||
1716e8c27ec8Sbaban 				    AD_OR_MIXED(state->nm_sidgid)) {
1717e8c27ec8Sbaban 					unixname = &req->id2name;
1718e8c27ec8Sbaban 				}
1719e8c27ec8Sbaban 			}
1720e8c27ec8Sbaban 			add = 1;
1721c5c4113dSnw141292 			retcode = idmap_sid2name_batch_add1(
1722e8c27ec8Sbaban 			    qs, req->id1.idmap_id_u.sid.prefix,
1723e8c27ec8Sbaban 			    &req->id1.idmap_id_u.sid.rid, eunixtype,
1724e8c27ec8Sbaban 			    (req->id1name == NULL) ? &req->id1name : NULL,
1725e8c27ec8Sbaban 			    (req->id1domain == NULL) ? &req->id1domain : NULL,
1726e8c27ec8Sbaban 			    (int *)&req->id2.idtype, unixname, &res->retcode);
1727c5c4113dSnw141292 
1728e8c27ec8Sbaban 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
1729e8c27ec8Sbaban 			/* unix to win */
1730e8c27ec8Sbaban 
1731e8c27ec8Sbaban 			if (res->id.idmap_id_u.sid.prefix != NULL &&
1732e8c27ec8Sbaban 			    req->id2name != NULL) {
1733e8c27ec8Sbaban 				/* Already have SID and winname -- done */
1734e8c27ec8Sbaban 				res->retcode = IDMAP_SUCCESS;
1735e8c27ec8Sbaban 				continue;
1736c5c4113dSnw141292 			}
1737c5c4113dSnw141292 
1738e8c27ec8Sbaban 			if (res->id.idmap_id_u.sid.prefix != NULL) {
1739cd37da74Snw141292 				/*
1740e8c27ec8Sbaban 				 * SID but no winname -- lookup AD by
1741e8c27ec8Sbaban 				 * SID to get winname.
1742cd37da74Snw141292 				 */
1743e8c27ec8Sbaban 				add = 1;
1744e8c27ec8Sbaban 				retcode = idmap_sid2name_batch_add1(
1745e8c27ec8Sbaban 				    qs, res->id.idmap_id_u.sid.prefix,
1746e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.rid,
1747e8c27ec8Sbaban 				    _IDMAP_T_UNDEF, &req->id2name,
1748e8c27ec8Sbaban 				    &req->id2domain, (int *)&req->id2.idtype,
1749e8c27ec8Sbaban 				    NULL, &res->retcode);
1750e8c27ec8Sbaban 			} else if (req->id2name != NULL) {
1751e8c27ec8Sbaban 				/*
1752e8c27ec8Sbaban 				 * winname but no SID -- lookup AD by
1753e8c27ec8Sbaban 				 * winname to get SID.
1754e8c27ec8Sbaban 				 */
1755e8c27ec8Sbaban 				add = 1;
1756e8c27ec8Sbaban 				retcode = idmap_name2sid_batch_add1(
1757e8c27ec8Sbaban 				    qs, req->id2name, req->id2domain,
1758e8c27ec8Sbaban 				    _IDMAP_T_UNDEF, NULL,
1759e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.prefix,
1760e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.rid,
1761e8c27ec8Sbaban 				    (int *)&req->id2.idtype, NULL,
1762e8c27ec8Sbaban 				    &res->retcode);
1763e8c27ec8Sbaban 			} else if (req->id1name != NULL) {
1764e8c27ec8Sbaban 				/*
1765e8c27ec8Sbaban 				 * No SID and no winname but we've unixname --
1766e8c27ec8Sbaban 				 * lookup AD by unixname to get SID.
1767e8c27ec8Sbaban 				 */
1768e8c27ec8Sbaban 				is_user = (IS_REQUEST_UID(*req)) ? 1 : 0;
1769e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_USID)
1770e8c27ec8Sbaban 					is_wuser = 1;
1771e8c27ec8Sbaban 				else if (res->id.idtype == IDMAP_GSID)
1772e8c27ec8Sbaban 					is_wuser = 0;
1773e8c27ec8Sbaban 				else
1774e8c27ec8Sbaban 					is_wuser = is_user;
1775e8c27ec8Sbaban 				add = 1;
1776e8c27ec8Sbaban 				retcode = idmap_unixname2sid_batch_add1(
1777e8c27ec8Sbaban 				    qs, req->id1name, is_user, is_wuser,
1778e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.prefix,
1779e8c27ec8Sbaban 				    &res->id.idmap_id_u.sid.rid,
1780e8c27ec8Sbaban 				    &req->id2name, &req->id2domain,
1781e8c27ec8Sbaban 				    (int *)&req->id2.idtype, &res->retcode);
1782e8c27ec8Sbaban 			}
1783e8c27ec8Sbaban 		}
1784e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS) {
1785e8c27ec8Sbaban 			idmap_lookup_release_batch(&qs);
1786e8c27ec8Sbaban 			break;
1787e8c27ec8Sbaban 		}
1788cd37da74Snw141292 	}
1789cd37da74Snw141292 
1790e8c27ec8Sbaban 	if (retcode == IDMAP_SUCCESS && add)
17910dcc7149Snw141292 		retcode = idmap_lookup_batch_end(&qs);
1792cd37da74Snw141292 
1793c5c4113dSnw141292 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
1794c5c4113dSnw141292 		goto retry;
1795c8e26105Sjp151216 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
1796*349d5d8fSnw141292 		degrade_svc(1, "some AD lookups timed out repeatedly");
1797c5c4113dSnw141292 
1798e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
1799e8c27ec8Sbaban 		idmapdlog(LOG_NOTICE, "Failed to batch AD lookup requests");
1800c5c4113dSnw141292 
1801c5c4113dSnw141292 out:
1802e8c27ec8Sbaban 	/*
1803e8c27ec8Sbaban 	 * This loop does the following:
1804e8c27ec8Sbaban 	 * 1) If there are errors in creating or submitting the batch then
1805e8c27ec8Sbaban 	 *    we set the retcode for each request (res->retcode) that's part
1806e8c27ec8Sbaban 	 *    of the batch to that error. If there were no such errors then
1807e8c27ec8Sbaban 	 *    res->retcode for each request will reflect the status of AD
1808e8c27ec8Sbaban 	 *    lookup for that particular request. Initial value of
1809e8c27ec8Sbaban 	 *    res->retcode is IDMAP_ERR_RETRIABLE_NET_ERR.
1810e8c27ec8Sbaban 	 * 2) If AD lookup for a given request succeeds then evaluate the
1811e8c27ec8Sbaban 	 *    type of the AD object (i.e user or group) and update the
1812e8c27ec8Sbaban 	 *    idtype in res and req.
1813e8c27ec8Sbaban 	 * 3) Reset req->id2.idtype to IDMAP_NONE.
1814e8c27ec8Sbaban 	 */
1815e8c27ec8Sbaban 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
1816e8c27ec8Sbaban 		req = &batch->idmap_mapping_batch_val[i];
1817e8c27ec8Sbaban 		type = req->id2.idtype;
1818e8c27ec8Sbaban 		req->id2.idtype = IDMAP_NONE;
18195e0794bcSbaban 		res = &result->ids.ids_val[i];
18205e0794bcSbaban 
1821e8c27ec8Sbaban 		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
1822e8c27ec8Sbaban 			/* Entry that wasn't marked for AD lookup - skip */
1823e8c27ec8Sbaban 			continue;
1824e8c27ec8Sbaban 
1825e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS) {
1826e8c27ec8Sbaban 			res->retcode = retcode;
1827e8c27ec8Sbaban 			continue;
1828e8c27ec8Sbaban 		}
1829e8c27ec8Sbaban 
1830e8c27ec8Sbaban 		if (!add)
1831e8c27ec8Sbaban 			continue;
1832e8c27ec8Sbaban 
1833e8c27ec8Sbaban 
1834e8c27ec8Sbaban 		if (IS_REQUEST_SID(*req, 1)) {
1835e8c27ec8Sbaban 			if (res->retcode != IDMAP_SUCCESS)
1836e8c27ec8Sbaban 				continue;
1837e8c27ec8Sbaban 			switch (type) {
1838e8c27ec8Sbaban 			case _IDMAP_T_USER:
1839e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
1840e8c27ec8Sbaban 					res->id.idtype = IDMAP_UID;
1841e8c27ec8Sbaban 				req->id1.idtype = IDMAP_USID;
1842e8c27ec8Sbaban 				break;
1843e8c27ec8Sbaban 			case _IDMAP_T_GROUP:
1844e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
1845e8c27ec8Sbaban 					res->id.idtype = IDMAP_GID;
1846e8c27ec8Sbaban 				req->id1.idtype = IDMAP_GSID;
1847e8c27ec8Sbaban 				break;
1848e8c27ec8Sbaban 			default:
1849e8c27ec8Sbaban 				res->retcode = IDMAP_ERR_SID;
1850e8c27ec8Sbaban 				break;
1851e8c27ec8Sbaban 			}
1852e8c27ec8Sbaban 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
1853e8c27ec8Sbaban 			if (res->retcode != IDMAP_SUCCESS) {
1854e8c27ec8Sbaban 				if ((!(IDMAP_FATAL_ERROR(res->retcode))) &&
1855e8c27ec8Sbaban 				    res->id.idmap_id_u.sid.prefix == NULL &&
1856e8c27ec8Sbaban 				    req->id2name == NULL && /* no winname */
1857e8c27ec8Sbaban 				    req->id1name != NULL) /* unixname */
1858e8c27ec8Sbaban 					/*
1859e8c27ec8Sbaban 					 * Here we have a pid2sid request
1860e8c27ec8Sbaban 					 * that was marked for AD lookup
1861e8c27ec8Sbaban 					 * with no SID, no winname but with
1862e8c27ec8Sbaban 					 * unixname. This request was
1863e8c27ec8Sbaban 					 * added to the batch to do AD lookup
1864e8c27ec8Sbaban 					 * by unixname but it failed with non
1865e8c27ec8Sbaban 					 * fatal error. In such case we
1866e8c27ec8Sbaban 					 * ignore the error (i.e set
1867e8c27ec8Sbaban 					 * res->retcode to success) so that
1868e8c27ec8Sbaban 					 * next pass considers it for name
1869e8c27ec8Sbaban 					 * based mapping rules or ephemeral
1870e8c27ec8Sbaban 					 * mapping.
1871e8c27ec8Sbaban 					 */
1872e8c27ec8Sbaban 					res->retcode = IDMAP_SUCCESS;
1873e8c27ec8Sbaban 				continue;
1874e8c27ec8Sbaban 			}
1875e8c27ec8Sbaban 			switch (type) {
1876e8c27ec8Sbaban 			case _IDMAP_T_USER:
1877e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_SID)
1878e8c27ec8Sbaban 					res->id.idtype = IDMAP_USID;
1879e8c27ec8Sbaban 				break;
1880e8c27ec8Sbaban 			case _IDMAP_T_GROUP:
1881e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_SID)
1882e8c27ec8Sbaban 					res->id.idtype = IDMAP_GSID;
1883e8c27ec8Sbaban 				break;
1884e8c27ec8Sbaban 			default:
1885e8c27ec8Sbaban 				res->retcode = IDMAP_ERR_SID;
1886e8c27ec8Sbaban 				break;
1887e8c27ec8Sbaban 			}
1888e8c27ec8Sbaban 		}
1889e8c27ec8Sbaban 	}
1890e8c27ec8Sbaban 
1891e8c27ec8Sbaban 	/* AD lookups done. Reset state->ad_nqueries and return */
1892e8c27ec8Sbaban 	state->ad_nqueries = 0;
1893c5c4113dSnw141292 	return (retcode);
1894c5c4113dSnw141292 }
1895c5c4113dSnw141292 
1896cd37da74Snw141292 /*
1897cd37da74Snw141292  * Convention when processing win2unix requests:
1898cd37da74Snw141292  *
1899cd37da74Snw141292  * Windows identity:
1900cd37da74Snw141292  * req->id1name =
1901cd37da74Snw141292  *              winname if given otherwise winname found will be placed
1902cd37da74Snw141292  *              here.
1903cd37da74Snw141292  * req->id1domain =
1904cd37da74Snw141292  *              windomain if given otherwise windomain found will be
1905cd37da74Snw141292  *              placed here.
1906cd37da74Snw141292  * req->id1.idtype =
1907cd37da74Snw141292  *              Either IDMAP_SID/USID/GSID. If this is IDMAP_SID then it'll
1908cd37da74Snw141292  *              be set to IDMAP_USID/GSID depending upon whether the
1909cd37da74Snw141292  *              given SID is user or group respectively. The user/group-ness
1910cd37da74Snw141292  *              is determined either when looking up well-known SIDs table OR
1911cd37da74Snw141292  *              if the SID is found in namecache OR by ad_lookup() OR by
1912cd37da74Snw141292  *              ad_lookup_batch().
1913cd37da74Snw141292  * req->id1..sid.[prefix, rid] =
1914cd37da74Snw141292  *              SID if given otherwise SID found will be placed here.
1915cd37da74Snw141292  *
1916cd37da74Snw141292  * Unix identity:
1917cd37da74Snw141292  * req->id2name =
1918cd37da74Snw141292  *              unixname found will be placed here.
1919cd37da74Snw141292  * req->id2domain =
1920cd37da74Snw141292  *              NOT USED
1921cd37da74Snw141292  * res->id.idtype =
1922cd37da74Snw141292  *              Target type initialized from req->id2.idtype. If
1923cd37da74Snw141292  *              it is IDMAP_POSIXID then actual type (IDMAP_UID/GID) found
1924cd37da74Snw141292  *              will be placed here.
1925cd37da74Snw141292  * res->id..[uid or gid] =
1926cd37da74Snw141292  *              UID/GID found will be placed here.
1927cd37da74Snw141292  *
1928cd37da74Snw141292  * Others:
1929cd37da74Snw141292  * res->retcode =
1930cd37da74Snw141292  *              Return status for this request will be placed here.
1931cd37da74Snw141292  * res->direction =
1932cd37da74Snw141292  *              Direction found will be placed here. Direction
1933cd37da74Snw141292  *              meaning whether the resultant mapping is valid
1934cd37da74Snw141292  *              only from win2unix or bi-directional.
1935cd37da74Snw141292  * req->direction =
1936cd37da74Snw141292  *              INTERNAL USE. Used by idmapd to set various
1937cd37da74Snw141292  *              flags (_IDMAP_F_xxxx) to aid in processing
1938cd37da74Snw141292  *              of the request.
1939cd37da74Snw141292  * req->id2.idtype =
1940cd37da74Snw141292  *              INTERNAL USE. Initially this is the requested target
1941cd37da74Snw141292  *              type and is used to initialize res->id.idtype.
1942cd37da74Snw141292  *              ad_lookup_batch() uses this field temporarily to store
1943cd37da74Snw141292  *              sid_type obtained by the batched AD lookups and after
1944cd37da74Snw141292  *              use resets it to IDMAP_NONE to prevent xdr from
1945cd37da74Snw141292  *              mis-interpreting the contents of req->id2.
1946cd37da74Snw141292  * req->id2..[uid or gid or sid] =
1947cd37da74Snw141292  *              NOT USED
1948cd37da74Snw141292  */
1949cd37da74Snw141292 
1950cd37da74Snw141292 /*
1951cd37da74Snw141292  * This function does the following:
1952cd37da74Snw141292  * 1. Lookup well-known SIDs table.
1953cd37da74Snw141292  * 2. Check if the given SID is a local-SID and if so extract UID/GID from it.
1954cd37da74Snw141292  * 3. Lookup cache.
1955cd37da74Snw141292  * 4. Check if the client does not want new mapping to be allocated
1956cd37da74Snw141292  *    in which case this pass is the final pass.
1957cd37da74Snw141292  * 5. Set AD lookup flag if it determines that the next stage needs
1958cd37da74Snw141292  *    to do AD lookup.
1959cd37da74Snw141292  */
1960c5c4113dSnw141292 idmap_retcode
1961c5c4113dSnw141292 sid2pid_first_pass(lookup_state_t *state, sqlite *cache, idmap_mapping *req,
1962cd37da74Snw141292 		idmap_id_res *res)
1963cd37da74Snw141292 {
1964c5c4113dSnw141292 	idmap_retcode	retcode;
1965e8c27ec8Sbaban 	int		wksid;
1966c5c4113dSnw141292 
1967e8c27ec8Sbaban 	/* Initialize result */
1968e8c27ec8Sbaban 	res->id.idtype = req->id2.idtype;
1969e8c27ec8Sbaban 	res->id.idmap_id_u.uid = SENTINEL_PID;
1970e8c27ec8Sbaban 	res->direction = IDMAP_DIRECTION_UNDEF;
1971e8c27ec8Sbaban 	wksid = 0;
1972c5c4113dSnw141292 
1973cf5b5989Sdm199847 	if (EMPTY_STRING(req->id1.idmap_id_u.sid.prefix)) {
1974e8c27ec8Sbaban 		if (req->id1name == NULL) {
1975e8c27ec8Sbaban 			retcode = IDMAP_ERR_ARG;
1976c5c4113dSnw141292 			goto out;
1977c5c4113dSnw141292 		}
1978e8c27ec8Sbaban 		/* sanitize sidprefix */
1979e8c27ec8Sbaban 		free(req->id1.idmap_id_u.sid.prefix);
1980e8c27ec8Sbaban 		req->id1.idmap_id_u.sid.prefix = NULL;
1981e8c27ec8Sbaban 	}
1982c5c4113dSnw141292 
1983e8c27ec8Sbaban 	/* Lookup well-known SIDs table */
1984e8c27ec8Sbaban 	retcode = lookup_wksids_sid2pid(req, res, &wksid);
1985c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
1986c5c4113dSnw141292 		goto out;
1987c5c4113dSnw141292 
1988e8c27ec8Sbaban 	/* Check if this is a localsid */
1989e8c27ec8Sbaban 	if (!wksid) {
1990e8c27ec8Sbaban 		retcode = lookup_localsid2pid(req, res);
1991e8c27ec8Sbaban 		if (retcode != IDMAP_ERR_NOTFOUND)
1992e8c27ec8Sbaban 			goto out;
1993e8c27ec8Sbaban 	}
1994e8c27ec8Sbaban 
1995e8c27ec8Sbaban 	/* Lookup cache */
1996c5c4113dSnw141292 	retcode = lookup_cache_sid2pid(cache, req, res);
1997c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
1998c5c4113dSnw141292 		goto out;
1999c5c4113dSnw141292 
2000c5c4113dSnw141292 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req) || AVOID_NAMESERVICE(req)) {
2001e8c27ec8Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
2002c5c4113dSnw141292 		goto out;
2003c5c4113dSnw141292 	}
2004c5c4113dSnw141292 
2005c5c4113dSnw141292 	/*
2006e8c27ec8Sbaban 	 * Failed to find non-expired entry in cache. Next step is
2007e8c27ec8Sbaban 	 * to determine if this request needs to be batched for AD lookup.
2008e8c27ec8Sbaban 	 *
2009e8c27ec8Sbaban 	 * At this point we have either sid or winname or both. If we don't
2010e8c27ec8Sbaban 	 * have both then lookup name_cache for the sid or winname
2011e8c27ec8Sbaban 	 * whichever is missing. If not found then this request will be
2012e8c27ec8Sbaban 	 * batched for AD lookup.
2013e8c27ec8Sbaban 	 */
2014e8c27ec8Sbaban 	retcode = lookup_name_cache(cache, req, res);
2015e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS && retcode != IDMAP_ERR_NOTFOUND)
2016e8c27ec8Sbaban 		goto out;
2017e8c27ec8Sbaban 
2018e8c27ec8Sbaban 	/*
2019e8c27ec8Sbaban 	 * Set the flag to indicate that we are not done yet so that
2020e8c27ec8Sbaban 	 * subsequent passes considers this request for name-based
2021e8c27ec8Sbaban 	 * mapping and ephemeral mapping.
2022c5c4113dSnw141292 	 */
2023c5c4113dSnw141292 	state->sid2pid_done = FALSE;
2024e8c27ec8Sbaban 	req->direction |= _IDMAP_F_NOTDONE;
2025c5c4113dSnw141292 
2026c5c4113dSnw141292 	/*
2027e8c27ec8Sbaban 	 * Even if we have both sid and winname, we still may need to batch
2028e8c27ec8Sbaban 	 * this request for AD lookup if we don't have unixname and
2029e8c27ec8Sbaban 	 * directory-based name mapping (AD or mixed) is enabled.
2030e8c27ec8Sbaban 	 * We avoid AD lookup for well-known SIDs because they don't have
2031e8c27ec8Sbaban 	 * regular AD objects.
2032c5c4113dSnw141292 	 */
2033e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS ||
2034e8c27ec8Sbaban 	    (!wksid && req->id2name == NULL &&
2035e8c27ec8Sbaban 	    AD_OR_MIXED_MODE(res->id.idtype, state))) {
2036c5c4113dSnw141292 		retcode = IDMAP_SUCCESS;
2037e8c27ec8Sbaban 		req->direction |= _IDMAP_F_LOOKUP_AD;
2038c5c4113dSnw141292 		state->ad_nqueries++;
2039c5c4113dSnw141292 	}
2040c5c4113dSnw141292 
2041c5c4113dSnw141292 
2042c5c4113dSnw141292 out:
2043c5c4113dSnw141292 	res->retcode = idmap_stat4prot(retcode);
2044e8c27ec8Sbaban 	/*
2045e8c27ec8Sbaban 	 * If we are done and there was an error then set fallback pid
2046e8c27ec8Sbaban 	 * in the result.
2047e8c27ec8Sbaban 	 */
2048e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
2049e8c27ec8Sbaban 		res->id.idmap_id_u.uid = UID_NOBODY;
2050c5c4113dSnw141292 	return (retcode);
2051c5c4113dSnw141292 }
2052c5c4113dSnw141292 
2053c5c4113dSnw141292 /*
2054c5c4113dSnw141292  * Generate SID using the following convention
2055c5c4113dSnw141292  * 	<machine-sid-prefix>-<1000 + uid>
2056c5c4113dSnw141292  * 	<machine-sid-prefix>-<2^31 + gid>
2057c5c4113dSnw141292  */
2058cd37da74Snw141292 static
2059cd37da74Snw141292 idmap_retcode
2060cd37da74Snw141292 generate_localsid(idmap_mapping *req, idmap_id_res *res, int is_user)
2061cd37da74Snw141292 {
2062e8c27ec8Sbaban 	free(res->id.idmap_id_u.sid.prefix);
2063e8c27ec8Sbaban 	res->id.idmap_id_u.sid.prefix = NULL;
2064e8c27ec8Sbaban 
2065e8c27ec8Sbaban 	/*
2066e8c27ec8Sbaban 	 * Diagonal mapping for localSIDs not supported because of the
2067e8c27ec8Sbaban 	 * way we generate localSIDs.
2068e8c27ec8Sbaban 	 */
2069e8c27ec8Sbaban 	if (is_user && res->id.idtype == IDMAP_GSID)
2070e8c27ec8Sbaban 		return (IDMAP_ERR_NOMAPPING);
2071e8c27ec8Sbaban 	if (!is_user && res->id.idtype == IDMAP_USID)
2072e8c27ec8Sbaban 		return (IDMAP_ERR_NOMAPPING);
2073e8c27ec8Sbaban 
2074c5c4113dSnw141292 	/* Skip 1000 UIDs */
2075c5c4113dSnw141292 	if (is_user && req->id1.idmap_id_u.uid >
2076c5c4113dSnw141292 	    (INT32_MAX - LOCALRID_MIN))
207762c60062Sbaban 		return (IDMAP_ERR_NOMAPPING);
2078c5c4113dSnw141292 
2079c5c4113dSnw141292 	RDLOCK_CONFIG();
2080e8c27ec8Sbaban 	/*
2081e8c27ec8Sbaban 	 * machine_sid is never NULL because if it is we won't be here.
2082e8c27ec8Sbaban 	 * No need to assert because stdrup(NULL) will core anyways.
2083e8c27ec8Sbaban 	 */
2084c5c4113dSnw141292 	res->id.idmap_id_u.sid.prefix =
2085c5c4113dSnw141292 	    strdup(_idmapdstate.cfg->pgcfg.machine_sid);
2086c5c4113dSnw141292 	if (res->id.idmap_id_u.sid.prefix == NULL) {
2087c5c4113dSnw141292 		UNLOCK_CONFIG();
2088c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2089c5c4113dSnw141292 		return (IDMAP_ERR_MEMORY);
2090c5c4113dSnw141292 	}
2091c5c4113dSnw141292 	UNLOCK_CONFIG();
2092c5c4113dSnw141292 	res->id.idmap_id_u.sid.rid =
2093c5c4113dSnw141292 	    (is_user) ? req->id1.idmap_id_u.uid + LOCALRID_MIN :
2094c5c4113dSnw141292 	    req->id1.idmap_id_u.gid + INT32_MAX + 1;
2095651c0131Sbaban 	res->direction = IDMAP_DIRECTION_BI;
2096e8c27ec8Sbaban 	if (res->id.idtype == IDMAP_SID)
2097e8c27ec8Sbaban 		res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
2098c5c4113dSnw141292 
2099c5c4113dSnw141292 	/*
2100c5c4113dSnw141292 	 * Don't update name_cache because local sids don't have
2101c5c4113dSnw141292 	 * valid windows names.
2102c5c4113dSnw141292 	 */
2103e8c27ec8Sbaban 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
2104947c7bc0Sbaban 	return (IDMAP_SUCCESS);
2105c5c4113dSnw141292 }
2106c5c4113dSnw141292 
2107cd37da74Snw141292 static
2108cd37da74Snw141292 idmap_retcode
2109cd37da74Snw141292 lookup_localsid2pid(idmap_mapping *req, idmap_id_res *res)
2110cd37da74Snw141292 {
2111c5c4113dSnw141292 	char		*sidprefix;
2112c5c4113dSnw141292 	uint32_t	rid;
2113c5c4113dSnw141292 	int		s;
2114c5c4113dSnw141292 
2115c5c4113dSnw141292 	/*
2116c5c4113dSnw141292 	 * If the sidprefix == localsid then UID = last RID - 1000 or
2117c5c4113dSnw141292 	 * GID = last RID - 2^31.
2118c5c4113dSnw141292 	 */
2119e8c27ec8Sbaban 	if ((sidprefix = req->id1.idmap_id_u.sid.prefix) == NULL)
2120e8c27ec8Sbaban 		/* This means we are looking up by winname */
2121e8c27ec8Sbaban 		return (IDMAP_ERR_NOTFOUND);
2122c5c4113dSnw141292 	rid = req->id1.idmap_id_u.sid.rid;
2123c5c4113dSnw141292 
2124c5c4113dSnw141292 	RDLOCK_CONFIG();
2125c5c4113dSnw141292 	s = (_idmapdstate.cfg->pgcfg.machine_sid) ?
2126cd37da74Snw141292 	    strcasecmp(sidprefix, _idmapdstate.cfg->pgcfg.machine_sid) : 1;
2127c5c4113dSnw141292 	UNLOCK_CONFIG();
2128c5c4113dSnw141292 
2129e8c27ec8Sbaban 	/*
2130e8c27ec8Sbaban 	 * If the given sidprefix does not match machine_sid then this is
2131e8c27ec8Sbaban 	 * not a local SID.
2132e8c27ec8Sbaban 	 */
2133e8c27ec8Sbaban 	if (s != 0)
2134e8c27ec8Sbaban 		return (IDMAP_ERR_NOTFOUND);
2135e8c27ec8Sbaban 
2136e8c27ec8Sbaban 	switch (res->id.idtype) {
2137c5c4113dSnw141292 	case IDMAP_UID:
2138e8c27ec8Sbaban 		if (rid > INT32_MAX || rid < LOCALRID_MIN)
2139e8c27ec8Sbaban 			return (IDMAP_ERR_ARG);
2140c5c4113dSnw141292 		res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
2141c5c4113dSnw141292 		break;
2142c5c4113dSnw141292 	case IDMAP_GID:
2143e8c27ec8Sbaban 		if (rid <= INT32_MAX)
2144e8c27ec8Sbaban 			return (IDMAP_ERR_ARG);
2145c5c4113dSnw141292 		res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
2146c5c4113dSnw141292 		break;
2147c5c4113dSnw141292 	case IDMAP_POSIXID:
2148c5c4113dSnw141292 		if (rid > INT32_MAX) {
2149cd37da74Snw141292 			res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
2150c5c4113dSnw141292 			res->id.idtype = IDMAP_GID;
2151c5c4113dSnw141292 		} else if (rid < LOCALRID_MIN) {
2152e8c27ec8Sbaban 			return (IDMAP_ERR_ARG);
2153c5c4113dSnw141292 		} else {
2154c5c4113dSnw141292 			res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
2155c5c4113dSnw141292 			res->id.idtype = IDMAP_UID;
2156c5c4113dSnw141292 		}
2157c5c4113dSnw141292 		break;
2158c5c4113dSnw141292 	default:
2159c5c4113dSnw141292 		return (IDMAP_ERR_NOTSUPPORTED);
2160c5c4113dSnw141292 	}
2161c5c4113dSnw141292 	return (IDMAP_SUCCESS);
2162c5c4113dSnw141292 }
2163c5c4113dSnw141292 
2164e8c27ec8Sbaban /*
2165e8c27ec8Sbaban  * Name service lookup by unixname to get pid
2166e8c27ec8Sbaban  */
2167cd37da74Snw141292 static
2168cd37da74Snw141292 idmap_retcode
2169e8c27ec8Sbaban ns_lookup_byname(const char *name, const char *lower_name, idmap_id *id)
2170cd37da74Snw141292 {
2171cd37da74Snw141292 	struct passwd	pwd, *pwdp;
2172cd37da74Snw141292 	struct group	grp, *grpp;
2173c5c4113dSnw141292 	char		buf[1024];
2174c5c4113dSnw141292 	int		errnum;
2175c5c4113dSnw141292 	const char	*me = "ns_lookup_byname";
2176c5c4113dSnw141292 
2177e8c27ec8Sbaban 	switch (id->idtype) {
2178e8c27ec8Sbaban 	case IDMAP_UID:
2179cd37da74Snw141292 		pwdp = getpwnam_r(name, &pwd, buf, sizeof (buf));
2180e8c27ec8Sbaban 		if (pwdp == NULL && errno == 0 && lower_name != NULL &&
2181cd37da74Snw141292 		    name != lower_name && strcmp(name, lower_name) != 0)
2182cd37da74Snw141292 			pwdp = getpwnam_r(lower_name, &pwd, buf, sizeof (buf));
2183cd37da74Snw141292 		if (pwdp == NULL) {
2184c5c4113dSnw141292 			errnum = errno;
2185c5c4113dSnw141292 			idmapdlog(LOG_WARNING,
2186c5c4113dSnw141292 			    "%s: getpwnam_r(%s) failed (%s).",
2187cd37da74Snw141292 			    me, name, errnum ? strerror(errnum) : "not found");
2188c5c4113dSnw141292 			if (errnum == 0)
2189c5c4113dSnw141292 				return (IDMAP_ERR_NOTFOUND);
2190c5c4113dSnw141292 			else
2191c5c4113dSnw141292 				return (IDMAP_ERR_INTERNAL);
2192c5c4113dSnw141292 		}
2193e8c27ec8Sbaban 		id->idmap_id_u.uid = pwd.pw_uid;
2194e8c27ec8Sbaban 		break;
2195e8c27ec8Sbaban 	case IDMAP_GID:
2196cd37da74Snw141292 		grpp = getgrnam_r(name, &grp, buf, sizeof (buf));
2197e8c27ec8Sbaban 		if (grpp == NULL && errno == 0 && lower_name != NULL &&
2198cd37da74Snw141292 		    name != lower_name && strcmp(name, lower_name) != 0)
2199cd37da74Snw141292 			grpp = getgrnam_r(lower_name, &grp, buf, sizeof (buf));
2200cd37da74Snw141292 		if (grpp == NULL) {
2201c5c4113dSnw141292 			errnum = errno;
2202c5c4113dSnw141292 			idmapdlog(LOG_WARNING,
2203c5c4113dSnw141292 			    "%s: getgrnam_r(%s) failed (%s).",
2204cd37da74Snw141292 			    me, name, errnum ? strerror(errnum) : "not found");
2205c5c4113dSnw141292 			if (errnum == 0)
2206c5c4113dSnw141292 				return (IDMAP_ERR_NOTFOUND);
2207c5c4113dSnw141292 			else
2208c5c4113dSnw141292 				return (IDMAP_ERR_INTERNAL);
2209c5c4113dSnw141292 		}
2210e8c27ec8Sbaban 		id->idmap_id_u.gid = grp.gr_gid;
2211e8c27ec8Sbaban 		break;
2212e8c27ec8Sbaban 	default:
2213e8c27ec8Sbaban 		return (IDMAP_ERR_ARG);
2214c5c4113dSnw141292 	}
2215c5c4113dSnw141292 	return (IDMAP_SUCCESS);
2216c5c4113dSnw141292 }
2217c5c4113dSnw141292 
2218e8c27ec8Sbaban 
2219e8c27ec8Sbaban /*
2220e8c27ec8Sbaban  * Name service lookup by pid to get unixname
2221e8c27ec8Sbaban  */
2222e8c27ec8Sbaban static
2223e8c27ec8Sbaban idmap_retcode
2224e8c27ec8Sbaban ns_lookup_bypid(uid_t pid, int is_user, char **unixname)
2225e8c27ec8Sbaban {
2226e8c27ec8Sbaban 	struct passwd	pwd;
2227e8c27ec8Sbaban 	struct group	grp;
2228e8c27ec8Sbaban 	char		buf[1024];
2229e8c27ec8Sbaban 	int		errnum;
2230e8c27ec8Sbaban 	const char	*me = "ns_lookup_bypid";
2231e8c27ec8Sbaban 
2232e8c27ec8Sbaban 	if (is_user) {
2233e8c27ec8Sbaban 		errno = 0;
2234e8c27ec8Sbaban 		if (getpwuid_r(pid, &pwd, buf, sizeof (buf)) == NULL) {
2235e8c27ec8Sbaban 			errnum = errno;
2236e8c27ec8Sbaban 			idmapdlog(LOG_WARNING,
2237e8c27ec8Sbaban 			    "%s: getpwuid_r(%u) failed (%s).",
2238e8c27ec8Sbaban 			    me, pid, errnum ? strerror(errnum) : "not found");
2239e8c27ec8Sbaban 			if (errnum == 0)
2240e8c27ec8Sbaban 				return (IDMAP_ERR_NOTFOUND);
2241e8c27ec8Sbaban 			else
2242e8c27ec8Sbaban 				return (IDMAP_ERR_INTERNAL);
2243e8c27ec8Sbaban 		}
2244e8c27ec8Sbaban 		*unixname = strdup(pwd.pw_name);
2245e8c27ec8Sbaban 	} else {
2246e8c27ec8Sbaban 		errno = 0;
2247e8c27ec8Sbaban 		if (getgrgid_r(pid, &grp, buf, sizeof (buf)) == NULL) {
2248e8c27ec8Sbaban 			errnum = errno;
2249e8c27ec8Sbaban 			idmapdlog(LOG_WARNING,
2250e8c27ec8Sbaban 			    "%s: getgrgid_r(%u) failed (%s).",
2251e8c27ec8Sbaban 			    me, pid, errnum ? strerror(errnum) : "not found");
2252e8c27ec8Sbaban 			if (errnum == 0)
2253e8c27ec8Sbaban 				return (IDMAP_ERR_NOTFOUND);
2254e8c27ec8Sbaban 			else
2255e8c27ec8Sbaban 				return (IDMAP_ERR_INTERNAL);
2256e8c27ec8Sbaban 		}
2257e8c27ec8Sbaban 		*unixname = strdup(grp.gr_name);
2258e8c27ec8Sbaban 	}
2259e8c27ec8Sbaban 	if (*unixname == NULL)
2260e8c27ec8Sbaban 		return (IDMAP_ERR_MEMORY);
2261e8c27ec8Sbaban 	return (IDMAP_SUCCESS);
2262e8c27ec8Sbaban }
2263e8c27ec8Sbaban 
2264c5c4113dSnw141292 /*
2265c5c4113dSnw141292  * Name-based mapping
2266c5c4113dSnw141292  *
2267c5c4113dSnw141292  * Case 1: If no rule matches do ephemeral
2268c5c4113dSnw141292  *
2269c5c4113dSnw141292  * Case 2: If rule matches and unixname is "" then return no mapping.
2270c5c4113dSnw141292  *
2271c5c4113dSnw141292  * Case 3: If rule matches and unixname is specified then lookup name
2272c5c4113dSnw141292  *  service using the unixname. If unixname not found then return no mapping.
2273c5c4113dSnw141292  *
2274c5c4113dSnw141292  * Case 4: If rule matches and unixname is * then lookup name service
2275c5c4113dSnw141292  *  using winname as the unixname. If unixname not found then process
2276c5c4113dSnw141292  *  other rules using the lookup order. If no other rule matches then do
2277c5c4113dSnw141292  *  ephemeral. Otherwise, based on the matched rule do Case 2 or 3 or 4.
2278c5c4113dSnw141292  *  This allows us to specify a fallback unixname per _domain_ or no mapping
2279c5c4113dSnw141292  *  instead of the default behaviour of doing ephemeral mapping.
2280c5c4113dSnw141292  *
2281c5c4113dSnw141292  * Example 1:
2282c5c4113dSnw141292  * *@sfbay == *
2283c5c4113dSnw141292  * If looking up windows users foo@sfbay and foo does not exists in
2284c5c4113dSnw141292  * the name service then foo@sfbay will be mapped to an ephemeral id.
2285c5c4113dSnw141292  *
2286c5c4113dSnw141292  * Example 2:
2287c5c4113dSnw141292  * *@sfbay == *
2288c5c4113dSnw141292  * *@sfbay => guest
2289c5c4113dSnw141292  * If looking up windows users foo@sfbay and foo does not exists in
2290c5c4113dSnw141292  * the name service then foo@sfbay will be mapped to guest.
2291c5c4113dSnw141292  *
2292c5c4113dSnw141292  * Example 3:
2293c5c4113dSnw141292  * *@sfbay == *
2294c5c4113dSnw141292  * *@sfbay => ""
2295c5c4113dSnw141292  * If looking up windows users foo@sfbay and foo does not exists in
2296c5c4113dSnw141292  * the name service then we will return no mapping for foo@sfbay.
2297c5c4113dSnw141292  *
2298c5c4113dSnw141292  */
2299cd37da74Snw141292 static
2300cd37da74Snw141292 idmap_retcode
2301cd37da74Snw141292 name_based_mapping_sid2pid(sqlite *db, idmap_mapping *req, idmap_id_res *res)
2302cd37da74Snw141292 {
2303cd37da74Snw141292 	const char	*unixname, *windomain;
2304cd37da74Snw141292 	char		*sql = NULL, *errmsg = NULL, *lower_winname = NULL;
2305c5c4113dSnw141292 	idmap_retcode	retcode;
2306cd37da74Snw141292 	char		*end, *lower_unixname, *winname;
2307c5c4113dSnw141292 	const char	**values;
2308c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
2309cd37da74Snw141292 	int		ncol, r, i, is_user, is_wuser;
2310c5c4113dSnw141292 	const char	*me = "name_based_mapping_sid2pid";
2311c5c4113dSnw141292 
2312e8c27ec8Sbaban 	assert(req->id1name != NULL); /* We have winname */
2313e8c27ec8Sbaban 	assert(req->id2name == NULL); /* We don't have unixname */
2314e8c27ec8Sbaban 
23158e228215Sdm199847 	winname = req->id1name;
23168e228215Sdm199847 	windomain = req->id1domain;
2317cd37da74Snw141292 
2318cd37da74Snw141292 	switch (req->id1.idtype) {
2319cd37da74Snw141292 	case IDMAP_USID:
2320cd37da74Snw141292 		is_wuser = 1;
2321cd37da74Snw141292 		break;
2322cd37da74Snw141292 	case IDMAP_GSID:
2323cd37da74Snw141292 		is_wuser = 0;
2324cd37da74Snw141292 		break;
2325cd37da74Snw141292 	default:
2326e8c27ec8Sbaban 		idmapdlog(LOG_ERR, "%s: Unable to determine if the "
2327e8c27ec8Sbaban 		    "given Windows id is user or group.", me);
2328cd37da74Snw141292 		return (IDMAP_ERR_INTERNAL);
2329cd37da74Snw141292 	}
2330cd37da74Snw141292 
2331e8c27ec8Sbaban 	switch (res->id.idtype) {
2332cd37da74Snw141292 	case IDMAP_UID:
2333cd37da74Snw141292 		is_user = 1;
2334cd37da74Snw141292 		break;
2335cd37da74Snw141292 	case IDMAP_GID:
2336cd37da74Snw141292 		is_user = 0;
2337cd37da74Snw141292 		break;
2338cd37da74Snw141292 	case IDMAP_POSIXID:
2339cd37da74Snw141292 		is_user = is_wuser;
2340cd37da74Snw141292 		res->id.idtype = is_user ? IDMAP_UID : IDMAP_GID;
2341cd37da74Snw141292 		break;
2342cd37da74Snw141292 	}
2343c5c4113dSnw141292 
2344c5c4113dSnw141292 	i = 0;
234562c60062Sbaban 	if (windomain == NULL) {
234662c60062Sbaban 		windomain = "";
234762c60062Sbaban 	} else {
234862c60062Sbaban 		RDLOCK_CONFIG();
2349c8e26105Sjp151216 		if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
2350c8e26105Sjp151216 			if (strcasecmp(_idmapdstate.cfg->pgcfg.default_domain,
2351c5c4113dSnw141292 			    windomain) == 0)
2352c5c4113dSnw141292 				i = 1;
2353c5c4113dSnw141292 		}
2354c5c4113dSnw141292 		UNLOCK_CONFIG();
235562c60062Sbaban 	}
2356c5c4113dSnw141292 
2357cd37da74Snw141292 	if ((lower_winname = tolower_u8(winname)) == NULL)
2358cd37da74Snw141292 		lower_winname = winname;    /* hope for the best */
2359c5c4113dSnw141292 	sql = sqlite_mprintf(
2360c5c4113dSnw141292 	    "SELECT unixname, u2w_order FROM namerules WHERE "
2361cd37da74Snw141292 	    "w2u_order > 0 AND is_user = %d AND is_wuser = %d AND "
2362c5c4113dSnw141292 	    "(winname = %Q OR winname = '*') AND "
2363c5c4113dSnw141292 	    "(windomain = %Q OR windomain = '*' %s) "
2364c5c4113dSnw141292 	    "ORDER BY w2u_order ASC;",
2365cd37da74Snw141292 	    is_user, is_wuser, lower_winname, windomain,
236662c60062Sbaban 	    i ? "OR windomain ISNULL OR windomain = ''" : "");
2367c5c4113dSnw141292 	if (sql == NULL) {
2368c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2369c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
2370c5c4113dSnw141292 		goto out;
2371c5c4113dSnw141292 	}
2372c5c4113dSnw141292 
2373c5c4113dSnw141292 	if (sqlite_compile(db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
2374c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
2375cd37da74Snw141292 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
2376cd37da74Snw141292 		    CHECK_NULL(errmsg));
2377c5c4113dSnw141292 		sqlite_freemem(errmsg);
2378c5c4113dSnw141292 		goto out;
2379c5c4113dSnw141292 	}
2380c5c4113dSnw141292 
238184decf41Sjp151216 	for (; ; ) {
2382c5c4113dSnw141292 		r = sqlite_step(vm, &ncol, &values, NULL);
238384decf41Sjp151216 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
2384c5c4113dSnw141292 
238584decf41Sjp151216 		if (r == SQLITE_ROW) {
2386c5c4113dSnw141292 			if (ncol < 2) {
2387c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
2388c5c4113dSnw141292 				goto out;
2389c5c4113dSnw141292 			}
2390c5c4113dSnw141292 			if (values[0] == NULL) {
2391c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
2392c5c4113dSnw141292 				goto out;
2393c5c4113dSnw141292 			}
2394c5c4113dSnw141292 
2395c5c4113dSnw141292 			if (EMPTY_NAME(values[0])) {
2396c5c4113dSnw141292 				retcode = IDMAP_ERR_NOMAPPING;
2397c5c4113dSnw141292 				goto out;
2398c5c4113dSnw141292 			}
2399c5c4113dSnw141292 			unixname = (values[0][0] == '*') ? winname : values[0];
2400cd37da74Snw141292 			lower_unixname = (values[0][0] == '*') ?
2401cd37da74Snw141292 			    lower_winname : NULL;
2402e8c27ec8Sbaban 			retcode = ns_lookup_byname(unixname, lower_unixname,
2403e8c27ec8Sbaban 			    &res->id);
2404c5c4113dSnw141292 			if (retcode == IDMAP_ERR_NOTFOUND) {
2405c5c4113dSnw141292 				if (unixname == winname)
2406c5c4113dSnw141292 					/* Case 4 */
2407c5c4113dSnw141292 					continue;
2408c5c4113dSnw141292 				else
2409c5c4113dSnw141292 					/* Case 3 */
2410c5c4113dSnw141292 					retcode = IDMAP_ERR_NOMAPPING;
2411c5c4113dSnw141292 			}
2412c5c4113dSnw141292 			goto out;
2413c5c4113dSnw141292 		} else if (r == SQLITE_DONE) {
2414c5c4113dSnw141292 			retcode = IDMAP_ERR_NOTFOUND;
2415c5c4113dSnw141292 			goto out;
2416c5c4113dSnw141292 		} else {
2417c5c4113dSnw141292 			(void) sqlite_finalize(vm, &errmsg);
2418c5c4113dSnw141292 			vm = NULL;
2419cd37da74Snw141292 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
2420cd37da74Snw141292 			    CHECK_NULL(errmsg));
2421c5c4113dSnw141292 			sqlite_freemem(errmsg);
2422c5c4113dSnw141292 			retcode = IDMAP_ERR_INTERNAL;
2423c5c4113dSnw141292 			goto out;
2424c5c4113dSnw141292 		}
2425c5c4113dSnw141292 	}
2426c5c4113dSnw141292 
2427c5c4113dSnw141292 out:
2428c5c4113dSnw141292 	sqlite_freemem(sql);
2429c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
243062c60062Sbaban 		if (values[1] != NULL)
2431c5c4113dSnw141292 			res->direction =
2432651c0131Sbaban 			    (strtol(values[1], &end, 10) == 0)?
2433651c0131Sbaban 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
2434c5c4113dSnw141292 		else
2435651c0131Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
24368e228215Sdm199847 		req->id2name = strdup(unixname);
2437c5c4113dSnw141292 	}
2438cd37da74Snw141292 	if (lower_winname != NULL && lower_winname != winname)
2439cd37da74Snw141292 		free(lower_winname);
244062c60062Sbaban 	if (vm != NULL)
2441c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
2442c5c4113dSnw141292 	return (retcode);
2443c5c4113dSnw141292 }
2444c5c4113dSnw141292 
2445c5c4113dSnw141292 static
2446c5c4113dSnw141292 int
2447c5c4113dSnw141292 get_next_eph_uid(uid_t *next_uid)
2448c5c4113dSnw141292 {
2449c5c4113dSnw141292 	uid_t uid;
2450c5c4113dSnw141292 	gid_t gid;
2451c5c4113dSnw141292 	int err;
2452c5c4113dSnw141292 
2453c5c4113dSnw141292 	*next_uid = (uid_t)-1;
2454c5c4113dSnw141292 	uid = _idmapdstate.next_uid++;
2455c5c4113dSnw141292 	if (uid >= _idmapdstate.limit_uid) {
2456c5c4113dSnw141292 		if ((err = allocids(0, 8192, &uid, 0, &gid)) != 0)
2457c5c4113dSnw141292 			return (err);
2458c5c4113dSnw141292 
2459c5c4113dSnw141292 		_idmapdstate.limit_uid = uid + 8192;
2460c5c4113dSnw141292 		_idmapdstate.next_uid = uid;
2461c5c4113dSnw141292 	}
2462c5c4113dSnw141292 	*next_uid = uid;
2463c5c4113dSnw141292 
2464c5c4113dSnw141292 	return (0);
2465c5c4113dSnw141292 }
2466c5c4113dSnw141292 
2467c5c4113dSnw141292 static
2468c5c4113dSnw141292 int
2469c5c4113dSnw141292 get_next_eph_gid(gid_t *next_gid)
2470c5c4113dSnw141292 {
2471c5c4113dSnw141292 	uid_t uid;
2472c5c4113dSnw141292 	gid_t gid;
2473c5c4113dSnw141292 	int err;
2474c5c4113dSnw141292 
2475c5c4113dSnw141292 	*next_gid = (uid_t)-1;
2476c5c4113dSnw141292 	gid = _idmapdstate.next_gid++;
2477c5c4113dSnw141292 	if (gid >= _idmapdstate.limit_gid) {
2478c5c4113dSnw141292 		if ((err = allocids(0, 0, &uid, 8192, &gid)) != 0)
2479c5c4113dSnw141292 			return (err);
2480c5c4113dSnw141292 
2481c5c4113dSnw141292 		_idmapdstate.limit_gid = gid + 8192;
2482c5c4113dSnw141292 		_idmapdstate.next_gid = gid;
2483c5c4113dSnw141292 	}
2484c5c4113dSnw141292 	*next_gid = gid;
2485c5c4113dSnw141292 
2486c5c4113dSnw141292 	return (0);
2487c5c4113dSnw141292 }
2488c5c4113dSnw141292 
248962c60062Sbaban static
249062c60062Sbaban int
2491cd37da74Snw141292 gethash(const char *str, uint32_t num, uint_t htsize)
2492cd37da74Snw141292 {
249362c60062Sbaban 	uint_t  hval, i, len;
249462c60062Sbaban 
249562c60062Sbaban 	if (str == NULL)
249662c60062Sbaban 		return (0);
249762c60062Sbaban 	for (len = strlen(str), hval = 0, i = 0; i < len; i++) {
249862c60062Sbaban 		hval += str[i];
249962c60062Sbaban 		hval += (hval << 10);
250062c60062Sbaban 		hval ^= (hval >> 6);
250162c60062Sbaban 	}
250262c60062Sbaban 	for (str = (const char *)&num, i = 0; i < sizeof (num); i++) {
250362c60062Sbaban 		hval += str[i];
250462c60062Sbaban 		hval += (hval << 10);
250562c60062Sbaban 		hval ^= (hval >> 6);
250662c60062Sbaban 	}
250762c60062Sbaban 	hval += (hval << 3);
250862c60062Sbaban 	hval ^= (hval >> 11);
250962c60062Sbaban 	hval += (hval << 15);
251062c60062Sbaban 	return (hval % htsize);
251162c60062Sbaban }
251262c60062Sbaban 
251362c60062Sbaban static
251462c60062Sbaban int
251562c60062Sbaban get_from_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid,
2516cd37da74Snw141292 		uid_t *pid)
2517cd37da74Snw141292 {
251862c60062Sbaban 	uint_t		next, key;
251962c60062Sbaban 	uint_t		htsize = state->sid_history_size;
252062c60062Sbaban 	idmap_sid	*sid;
252162c60062Sbaban 
252262c60062Sbaban 	next = gethash(prefix, rid, htsize);
252362c60062Sbaban 	while (next != htsize) {
252462c60062Sbaban 		key = state->sid_history[next].key;
252562c60062Sbaban 		if (key == htsize)
252662c60062Sbaban 			return (0);
252762c60062Sbaban 		sid = &state->batch->idmap_mapping_batch_val[key].id1.
252862c60062Sbaban 		    idmap_id_u.sid;
252962c60062Sbaban 		if (sid->rid == rid && strcmp(sid->prefix, prefix) == 0) {
253062c60062Sbaban 			*pid = state->result->ids.ids_val[key].id.
253162c60062Sbaban 			    idmap_id_u.uid;
253262c60062Sbaban 			return (1);
253362c60062Sbaban 		}
253462c60062Sbaban 		next = state->sid_history[next].next;
253562c60062Sbaban 	}
253662c60062Sbaban 	return (0);
253762c60062Sbaban }
253862c60062Sbaban 
253962c60062Sbaban static
254062c60062Sbaban void
2541cd37da74Snw141292 add_to_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid)
2542cd37da74Snw141292 {
254362c60062Sbaban 	uint_t		hash, next;
254462c60062Sbaban 	uint_t		htsize = state->sid_history_size;
254562c60062Sbaban 
254662c60062Sbaban 	hash = next = gethash(prefix, rid, htsize);
254762c60062Sbaban 	while (state->sid_history[next].key != htsize) {
254862c60062Sbaban 		next++;
254962c60062Sbaban 		next %= htsize;
255062c60062Sbaban 	}
255162c60062Sbaban 	state->sid_history[next].key = state->curpos;
255262c60062Sbaban 	if (hash == next)
255362c60062Sbaban 		return;
255462c60062Sbaban 	state->sid_history[next].next = state->sid_history[hash].next;
255562c60062Sbaban 	state->sid_history[hash].next = next;
255662c60062Sbaban }
2557c5c4113dSnw141292 
2558e8c27ec8Sbaban void
2559e8c27ec8Sbaban cleanup_lookup_state(lookup_state_t *state)
2560e8c27ec8Sbaban {
2561e8c27ec8Sbaban 	free(state->sid_history);
2562e8c27ec8Sbaban 	free(state->ad_unixuser_attr);
2563e8c27ec8Sbaban 	free(state->ad_unixgroup_attr);
2564e8c27ec8Sbaban }
2565e8c27ec8Sbaban 
2566c5c4113dSnw141292 /* ARGSUSED */
2567c5c4113dSnw141292 static
2568c5c4113dSnw141292 idmap_retcode
256962c60062Sbaban dynamic_ephemeral_mapping(lookup_state_t *state, sqlite *cache,
2570cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
2571cd37da74Snw141292 {
2572c5c4113dSnw141292 
2573c5c4113dSnw141292 	uid_t		next_pid;
2574c5c4113dSnw141292 
2575651c0131Sbaban 	res->direction = IDMAP_DIRECTION_BI;
257662c60062Sbaban 
257762c60062Sbaban 	if (IS_EPHEMERAL(res->id.idmap_id_u.uid))
257862c60062Sbaban 		return (IDMAP_SUCCESS);
257962c60062Sbaban 
258062c60062Sbaban 	if (state->sid_history != NULL &&
258162c60062Sbaban 	    get_from_sid_history(state, req->id1.idmap_id_u.sid.prefix,
258262c60062Sbaban 	    req->id1.idmap_id_u.sid.rid, &next_pid)) {
258362c60062Sbaban 		res->id.idmap_id_u.uid = next_pid;
258462c60062Sbaban 		return (IDMAP_SUCCESS);
258562c60062Sbaban 	}
258662c60062Sbaban 
258762c60062Sbaban 	if (res->id.idtype == IDMAP_UID) {
2588c5c4113dSnw141292 		if (get_next_eph_uid(&next_pid) != 0)
2589c5c4113dSnw141292 			return (IDMAP_ERR_INTERNAL);
2590c5c4113dSnw141292 		res->id.idmap_id_u.uid = next_pid;
2591c5c4113dSnw141292 	} else {
2592c5c4113dSnw141292 		if (get_next_eph_gid(&next_pid) != 0)
2593c5c4113dSnw141292 			return (IDMAP_ERR_INTERNAL);
2594c5c4113dSnw141292 		res->id.idmap_id_u.gid = next_pid;
2595c5c4113dSnw141292 	}
2596c5c4113dSnw141292 
259762c60062Sbaban 	if (state->sid_history != NULL)
259862c60062Sbaban 		add_to_sid_history(state, req->id1.idmap_id_u.sid.prefix,
259962c60062Sbaban 		    req->id1.idmap_id_u.sid.rid);
260062c60062Sbaban 
2601c5c4113dSnw141292 	return (IDMAP_SUCCESS);
2602c5c4113dSnw141292 }
2603c5c4113dSnw141292 
2604c5c4113dSnw141292 idmap_retcode
2605c5c4113dSnw141292 sid2pid_second_pass(lookup_state_t *state, sqlite *cache, sqlite *db,
2606cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
2607cd37da74Snw141292 {
2608c5c4113dSnw141292 	idmap_retcode	retcode;
2609c5c4113dSnw141292 
2610c5c4113dSnw141292 	/* Check if second pass is needed */
2611e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
2612c5c4113dSnw141292 		return (res->retcode);
2613c5c4113dSnw141292 
2614c5c4113dSnw141292 	/* Get status from previous pass */
2615e8c27ec8Sbaban 	retcode = res->retcode;
2616e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
2617e8c27ec8Sbaban 		goto out;
2618c5c4113dSnw141292 
2619e8c27ec8Sbaban 	/*
2620e8c27ec8Sbaban 	 * If directory-based name mapping is enabled then the unixname
2621e8c27ec8Sbaban 	 * may already have been retrieved from the AD object (AD-mode or
2622e8c27ec8Sbaban 	 * mixed-mode) or from native LDAP object (nldap-mode) -- done.
2623e8c27ec8Sbaban 	 */
2624e8c27ec8Sbaban 	if (req->id2name != NULL) {
2625e8c27ec8Sbaban 		assert(res->id.idtype != IDMAP_POSIXID);
2626e8c27ec8Sbaban 		if (AD_MODE(res->id.idtype, state))
2627e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
2628e8c27ec8Sbaban 		else if (NLDAP_MODE(res->id.idtype, state))
2629e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
2630e8c27ec8Sbaban 		else if (MIXED_MODE(res->id.idtype, state))
2631e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
2632c5c4113dSnw141292 
2633e8c27ec8Sbaban 		/*
2634e8c27ec8Sbaban 		 * Special case: (1) If the ad_unixuser_attr and
2635e8c27ec8Sbaban 		 * ad_unixgroup_attr uses the same attribute
2636e8c27ec8Sbaban 		 * name and (2) if this is a diagonal mapping
2637e8c27ec8Sbaban 		 * request and (3) the unixname has been retrieved
2638e8c27ec8Sbaban 		 * from the AD object -- then we ignore it and fallback
2639e8c27ec8Sbaban 		 * to name-based mapping rules and ephemeral mapping
2640e8c27ec8Sbaban 		 *
2641e8c27ec8Sbaban 		 * Example:
2642e8c27ec8Sbaban 		 *  Properties:
2643e8c27ec8Sbaban 		 *    config/ad_unixuser_attr = "unixname"
2644e8c27ec8Sbaban 		 *    config/ad_unixgroup_attr = "unixname"
2645e8c27ec8Sbaban 		 *  AD user object:
2646e8c27ec8Sbaban 		 *    dn: cn=bob ...
2647e8c27ec8Sbaban 		 *    objectclass: user
2648e8c27ec8Sbaban 		 *    sam: bob
2649e8c27ec8Sbaban 		 *    unixname: bob1234
2650e8c27ec8Sbaban 		 *  AD group object:
2651e8c27ec8Sbaban 		 *    dn: cn=winadmins ...
2652e8c27ec8Sbaban 		 *    objectclass: group
2653e8c27ec8Sbaban 		 *    sam: winadmins
2654e8c27ec8Sbaban 		 *    unixname: unixadmins
2655e8c27ec8Sbaban 		 *
2656e8c27ec8Sbaban 		 *  In this example whether "unixname" refers to a unixuser
2657e8c27ec8Sbaban 		 *  or unixgroup depends upon the AD object.
2658e8c27ec8Sbaban 		 *
2659e8c27ec8Sbaban 		 * $idmap show -c winname:bob gid
2660e8c27ec8Sbaban 		 *    AD lookup by "samAccountName=bob" for
2661e8c27ec8Sbaban 		 *    "ad_unixgroup_attr (i.e unixname)" for directory-based
2662e8c27ec8Sbaban 		 *    mapping would get "bob1234" which is not what we want.
2663e8c27ec8Sbaban 		 *    Now why not getgrnam_r("bob1234") and use it if it
2664e8c27ec8Sbaban 		 *    is indeed a unixgroup? That's because Unix can have
2665e8c27ec8Sbaban 		 *    users and groups with the same name and we clearly
2666e8c27ec8Sbaban 		 *    don't know the intention of the admin here.
2667e8c27ec8Sbaban 		 *    Therefore we ignore this and fallback to name-based
2668e8c27ec8Sbaban 		 *    mapping rules or ephemeral mapping.
2669e8c27ec8Sbaban 		 */
2670e8c27ec8Sbaban 		if ((AD_MODE(res->id.idtype, state) ||
2671e8c27ec8Sbaban 		    MIXED_MODE(res->id.idtype, state)) &&
2672e8c27ec8Sbaban 		    state->ad_unixuser_attr != NULL &&
2673e8c27ec8Sbaban 		    state->ad_unixgroup_attr != NULL &&
2674e8c27ec8Sbaban 		    strcasecmp(state->ad_unixuser_attr,
2675e8c27ec8Sbaban 		    state->ad_unixgroup_attr) == 0 &&
2676e8c27ec8Sbaban 		    ((req->id1.idtype == IDMAP_USID &&
2677e8c27ec8Sbaban 		    res->id.idtype == IDMAP_GID) ||
2678e8c27ec8Sbaban 		    (req->id1.idtype == IDMAP_GSID &&
2679e8c27ec8Sbaban 		    res->id.idtype == IDMAP_UID))) {
2680e8c27ec8Sbaban 			free(req->id2name);
2681e8c27ec8Sbaban 			req->id2name = NULL;
2682e8c27ec8Sbaban 			res->id.idmap_id_u.uid = SENTINEL_PID;
2683e8c27ec8Sbaban 			/* fallback */
2684e8c27ec8Sbaban 		} else {
2685e8c27ec8Sbaban 			if (res->id.idmap_id_u.uid == SENTINEL_PID)
2686e8c27ec8Sbaban 				retcode = ns_lookup_byname(req->id2name,
2687e8c27ec8Sbaban 				    NULL, &res->id);
2688e8c27ec8Sbaban 			/*
2689e8c27ec8Sbaban 			 * We don't fallback to name-based mapping rules
2690e8c27ec8Sbaban 			 * or ephemeral mapping.
2691e8c27ec8Sbaban 			 */
2692c5c4113dSnw141292 			goto out;
2693c5c4113dSnw141292 		}
2694e8c27ec8Sbaban 	}
2695c5c4113dSnw141292 
2696e8c27ec8Sbaban 	/*
2697e8c27ec8Sbaban 	 * If we don't have unixname then evaluate local name-based
2698e8c27ec8Sbaban 	 * mapping rules.
2699e8c27ec8Sbaban 	 */
2700c5c4113dSnw141292 	retcode = name_based_mapping_sid2pid(db, req, res);
2701e8c27ec8Sbaban 	if (retcode != IDMAP_ERR_NOTFOUND)
2702e8c27ec8Sbaban 		goto out;
2703e8c27ec8Sbaban 
2704c5c4113dSnw141292 	/* If not found, do ephemeral mapping */
270562c60062Sbaban 	retcode = dynamic_ephemeral_mapping(state, cache, req, res);
2706c5c4113dSnw141292 
2707c5c4113dSnw141292 out:
2708c5c4113dSnw141292 	res->retcode = idmap_stat4prot(retcode);
2709e8c27ec8Sbaban 	if (res->retcode != IDMAP_SUCCESS) {
2710e8c27ec8Sbaban 		req->direction = _IDMAP_F_DONE;
2711e8c27ec8Sbaban 		res->id.idmap_id_u.uid = UID_NOBODY;
2712e8c27ec8Sbaban 	}
2713e8c27ec8Sbaban 	if (!ARE_WE_DONE(req->direction))
2714e8c27ec8Sbaban 		state->sid2pid_done = FALSE;
2715c5c4113dSnw141292 	return (retcode);
2716c5c4113dSnw141292 }
2717c5c4113dSnw141292 
2718c5c4113dSnw141292 idmap_retcode
2719c5c4113dSnw141292 update_cache_pid2sid(lookup_state_t *state, sqlite *cache,
2720cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
2721cd37da74Snw141292 {
2722c5c4113dSnw141292 	char		*sql = NULL;
2723c5c4113dSnw141292 	idmap_retcode	retcode;
2724c5c4113dSnw141292 
2725c5c4113dSnw141292 	/* Check if we need to cache anything */
2726e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
2727c5c4113dSnw141292 		return (IDMAP_SUCCESS);
2728c5c4113dSnw141292 
2729c5c4113dSnw141292 	/* We don't cache negative entries */
2730c5c4113dSnw141292 	if (res->retcode != IDMAP_SUCCESS)
2731c5c4113dSnw141292 		return (IDMAP_SUCCESS);
2732c5c4113dSnw141292 
2733e8c27ec8Sbaban 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
2734e8c27ec8Sbaban 
2735c5c4113dSnw141292 	/*
2736c5c4113dSnw141292 	 * Using NULL for u2w instead of 0 so that our trigger allows
2737c5c4113dSnw141292 	 * the same pid to be the destination in multiple entries
2738c5c4113dSnw141292 	 */
2739c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
2740cd37da74Snw141292 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
2741cd37da74Snw141292 	    "is_user, is_wuser, expiration, w2u, u2w) "
2742cd37da74Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
2743c5c4113dSnw141292 	    "strftime('%%s','now') + 600, %q, 1); ",
2744cd37da74Snw141292 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
2745cd37da74Snw141292 	    req->id2domain, req->id2name, req->id1.idmap_id_u.uid,
2746cd37da74Snw141292 	    req->id1name, (req->id1.idtype == IDMAP_UID) ? 1 : 0,
2747e8c27ec8Sbaban 	    (res->id.idtype == IDMAP_USID) ? 1 : 0,
2748c5c4113dSnw141292 	    (res->direction == 0) ? "1" : NULL);
2749c5c4113dSnw141292 
2750c5c4113dSnw141292 	if (sql == NULL) {
2751c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
2752c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2753c5c4113dSnw141292 		goto out;
2754c5c4113dSnw141292 	}
2755c5c4113dSnw141292 
275671590c90Snw141292 	retcode = sql_exec_no_cb(cache, IDMAP_CACHENAME, sql);
2757c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
2758c5c4113dSnw141292 		goto out;
2759c5c4113dSnw141292 
2760c5c4113dSnw141292 	state->pid2sid_done = FALSE;
2761c5c4113dSnw141292 	sqlite_freemem(sql);
2762c5c4113dSnw141292 	sql = NULL;
2763c5c4113dSnw141292 
2764e8c27ec8Sbaban 	/* Check if we need to update namecache */
2765e8c27ec8Sbaban 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
2766c5c4113dSnw141292 		goto out;
2767c5c4113dSnw141292 
27688e228215Sdm199847 	if (req->id2name == NULL)
2769c5c4113dSnw141292 		goto out;
2770c5c4113dSnw141292 
2771c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
2772cd37da74Snw141292 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
2773c5c4113dSnw141292 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
2774cd37da74Snw141292 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
2775cd37da74Snw141292 	    req->id2name, req->id2domain,
2776e8c27ec8Sbaban 	    (res->id.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
2777c5c4113dSnw141292 
2778c5c4113dSnw141292 	if (sql == NULL) {
2779c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
2780c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2781c5c4113dSnw141292 		goto out;
2782c5c4113dSnw141292 	}
2783c5c4113dSnw141292 
278471590c90Snw141292 	retcode = sql_exec_no_cb(cache, IDMAP_CACHENAME, sql);
2785c5c4113dSnw141292 
2786c5c4113dSnw141292 out:
278762c60062Sbaban 	if (sql != NULL)
2788c5c4113dSnw141292 		sqlite_freemem(sql);
2789c5c4113dSnw141292 	return (retcode);
2790c5c4113dSnw141292 }
2791c5c4113dSnw141292 
2792c5c4113dSnw141292 idmap_retcode
2793c5c4113dSnw141292 update_cache_sid2pid(lookup_state_t *state, sqlite *cache,
2794cd37da74Snw141292 		idmap_mapping *req, idmap_id_res *res)
2795cd37da74Snw141292 {
2796c5c4113dSnw141292 	char		*sql = NULL;
2797c5c4113dSnw141292 	idmap_retcode	retcode;
2798c5c4113dSnw141292 	int		is_eph_user;
2799c5c4113dSnw141292 
2800c5c4113dSnw141292 	/* Check if we need to cache anything */
2801e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
2802c5c4113dSnw141292 		return (IDMAP_SUCCESS);
2803c5c4113dSnw141292 
2804c5c4113dSnw141292 	/* We don't cache negative entries */
2805c5c4113dSnw141292 	if (res->retcode != IDMAP_SUCCESS)
2806c5c4113dSnw141292 		return (IDMAP_SUCCESS);
2807c5c4113dSnw141292 
2808c5c4113dSnw141292 	if (req->direction & _IDMAP_F_EXP_EPH_UID)
2809c5c4113dSnw141292 		is_eph_user = 1;
2810c5c4113dSnw141292 	else if (req->direction & _IDMAP_F_EXP_EPH_GID)
2811c5c4113dSnw141292 		is_eph_user = 0;
2812c5c4113dSnw141292 	else
2813c5c4113dSnw141292 		is_eph_user = -1;
2814c5c4113dSnw141292 
2815c5c4113dSnw141292 	if (is_eph_user >= 0 && !IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
2816c5c4113dSnw141292 		sql = sqlite_mprintf("UPDATE idmap_cache "
2817c5c4113dSnw141292 		    "SET w2u = 0 WHERE "
2818c5c4113dSnw141292 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
2819c5c4113dSnw141292 		    "pid >= 2147483648 AND is_user = %d;",
2820c5c4113dSnw141292 		    req->id1.idmap_id_u.sid.prefix,
2821c5c4113dSnw141292 		    req->id1.idmap_id_u.sid.rid,
2822c5c4113dSnw141292 		    is_eph_user);
2823c5c4113dSnw141292 		if (sql == NULL) {
2824c5c4113dSnw141292 			retcode = IDMAP_ERR_INTERNAL;
2825c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
2826c5c4113dSnw141292 			goto out;
2827c5c4113dSnw141292 		}
2828c5c4113dSnw141292 
282971590c90Snw141292 		retcode = sql_exec_no_cb(cache, IDMAP_CACHENAME, sql);
2830c5c4113dSnw141292 		if (retcode != IDMAP_SUCCESS)
2831c5c4113dSnw141292 			goto out;
2832c5c4113dSnw141292 
2833c5c4113dSnw141292 		sqlite_freemem(sql);
2834c5c4113dSnw141292 		sql = NULL;
2835c5c4113dSnw141292 	}
2836c5c4113dSnw141292 
2837e8c27ec8Sbaban 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
2838cd37da74Snw141292 
2839c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
2840cd37da74Snw141292 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
2841cd37da74Snw141292 	    "is_user, is_wuser, expiration, w2u, u2w) "
2842cd37da74Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
2843c5c4113dSnw141292 	    "strftime('%%s','now') + 600, 1, %q); ",
2844cd37da74Snw141292 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
2845e8c27ec8Sbaban 	    (req->id1domain != NULL) ? req->id1domain : "", req->id1name,
2846e8c27ec8Sbaban 	    res->id.idmap_id_u.uid, req->id2name,
2847e8c27ec8Sbaban 	    (res->id.idtype == IDMAP_UID) ? 1 : 0,
2848cd37da74Snw141292 	    (req->id1.idtype == IDMAP_USID) ? 1 : 0,
2849c5c4113dSnw141292 	    (res->direction == 0) ? "1" : NULL);
2850c5c4113dSnw141292 
2851c5c4113dSnw141292 	if (sql == NULL) {
2852c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
2853c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2854c5c4113dSnw141292 		goto out;
2855c5c4113dSnw141292 	}
2856c5c4113dSnw141292 
285771590c90Snw141292 	retcode = sql_exec_no_cb(cache, IDMAP_CACHENAME, sql);
2858c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
2859c5c4113dSnw141292 		goto out;
2860c5c4113dSnw141292 
2861c5c4113dSnw141292 	state->sid2pid_done = FALSE;
2862c5c4113dSnw141292 	sqlite_freemem(sql);
2863c5c4113dSnw141292 	sql = NULL;
2864c5c4113dSnw141292 
2865e8c27ec8Sbaban 	/* Check if we need to update namecache */
2866e8c27ec8Sbaban 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
2867c5c4113dSnw141292 		goto out;
2868c5c4113dSnw141292 
2869cf5b5989Sdm199847 	if (EMPTY_STRING(req->id1name))
2870c5c4113dSnw141292 		goto out;
2871c5c4113dSnw141292 
2872c5c4113dSnw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
2873cd37da74Snw141292 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
2874c5c4113dSnw141292 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
2875cd37da74Snw141292 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
2876cd37da74Snw141292 	    req->id1name, req->id1domain,
2877cd37da74Snw141292 	    (req->id1.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
2878c5c4113dSnw141292 
2879c5c4113dSnw141292 	if (sql == NULL) {
2880c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
2881c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2882c5c4113dSnw141292 		goto out;
2883c5c4113dSnw141292 	}
2884c5c4113dSnw141292 
288571590c90Snw141292 	retcode = sql_exec_no_cb(cache, IDMAP_CACHENAME, sql);
2886c5c4113dSnw141292 
2887c5c4113dSnw141292 out:
288862c60062Sbaban 	if (sql != NULL)
2889c5c4113dSnw141292 		sqlite_freemem(sql);
2890c5c4113dSnw141292 	return (retcode);
2891c5c4113dSnw141292 }
2892c5c4113dSnw141292 
2893cd37da74Snw141292 static
2894cd37da74Snw141292 idmap_retcode
2895c5c4113dSnw141292 lookup_cache_pid2sid(sqlite *cache, idmap_mapping *req, idmap_id_res *res,
2896cd37da74Snw141292 		int is_user, int getname)
2897cd37da74Snw141292 {
2898c5c4113dSnw141292 	char		*end;
2899c5c4113dSnw141292 	char		*sql = NULL;
2900c5c4113dSnw141292 	const char	**values;
2901c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
2902c5c4113dSnw141292 	int		ncol;
2903c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
2904c5c4113dSnw141292 	time_t		curtime;
2905e8c27ec8Sbaban 	idmap_id_type	idtype;
2906c5c4113dSnw141292 
2907c5c4113dSnw141292 	/* Current time */
2908c5c4113dSnw141292 	errno = 0;
2909c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
2910cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
2911c5c4113dSnw141292 		    strerror(errno));
2912c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
2913c5c4113dSnw141292 		goto out;
2914c5c4113dSnw141292 	}
2915c5c4113dSnw141292 
2916e8c27ec8Sbaban 	/* SQL to lookup the cache by pid or by unixname */
2917e8c27ec8Sbaban 	if (req->id1.idmap_id_u.uid != SENTINEL_PID) {
2918e8c27ec8Sbaban 		sql = sqlite_mprintf("SELECT sidprefix, rid, canon_winname, "
2919e8c27ec8Sbaban 		    "windomain, w2u, is_wuser "
2920c5c4113dSnw141292 		    "FROM idmap_cache WHERE "
2921c5c4113dSnw141292 		    "pid = %u AND u2w = 1 AND is_user = %d AND "
2922c5c4113dSnw141292 		    "(pid >= 2147483648 OR "
2923c5c4113dSnw141292 		    "(expiration = 0 OR expiration ISNULL OR "
2924c5c4113dSnw141292 		    "expiration > %d));",
2925c5c4113dSnw141292 		    req->id1.idmap_id_u.uid, is_user, curtime);
2926e8c27ec8Sbaban 	} else if (req->id1name != NULL) {
2927e8c27ec8Sbaban 		sql = sqlite_mprintf("SELECT sidprefix, rid, canon_winname, "
2928e8c27ec8Sbaban 		    "windomain, w2u, is_wuser "
2929e8c27ec8Sbaban 		    "FROM idmap_cache WHERE "
2930e8c27ec8Sbaban 		    "unixname = %Q AND u2w = 1 AND is_user = %d AND "
2931e8c27ec8Sbaban 		    "(pid >= 2147483648 OR "
2932e8c27ec8Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
2933e8c27ec8Sbaban 		    "expiration > %d));",
2934e8c27ec8Sbaban 		    req->id1name, is_user, curtime);
2935e8c27ec8Sbaban 	}
2936e8c27ec8Sbaban 
2937c5c4113dSnw141292 	if (sql == NULL) {
2938c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
2939c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
2940c5c4113dSnw141292 		goto out;
2941c5c4113dSnw141292 	}
2942c5c4113dSnw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 5, &values);
2943c5c4113dSnw141292 	sqlite_freemem(sql);
2944c5c4113dSnw141292 
2945c5c4113dSnw141292 	if (retcode == IDMAP_ERR_NOTFOUND)
2946c5c4113dSnw141292 		goto out;
2947c5c4113dSnw141292 	else if (retcode == IDMAP_SUCCESS) {
2948c5c4113dSnw141292 		/* sanity checks */
2949c5c4113dSnw141292 		if (values[0] == NULL || values[1] == NULL) {
2950c5c4113dSnw141292 			retcode = IDMAP_ERR_CACHE;
2951c5c4113dSnw141292 			goto out;
2952c5c4113dSnw141292 		}
2953c5c4113dSnw141292 
2954e8c27ec8Sbaban 		switch (res->id.idtype) {
2955c5c4113dSnw141292 		case IDMAP_SID:
2956cd37da74Snw141292 		case IDMAP_USID:
2957cd37da74Snw141292 		case IDMAP_GSID:
2958e8c27ec8Sbaban 			idtype = strtol(values[5], &end, 10) == 1
2959cd37da74Snw141292 			    ? IDMAP_USID : IDMAP_GSID;
2960cd37da74Snw141292 
2961e8c27ec8Sbaban 			if (res->id.idtype == IDMAP_USID &&
2962e8c27ec8Sbaban 			    idtype != IDMAP_USID) {
2963cd37da74Snw141292 				retcode = IDMAP_ERR_NOTUSER;
2964cd37da74Snw141292 				goto out;
2965e8c27ec8Sbaban 			} else if (res->id.idtype == IDMAP_GSID &&
2966e8c27ec8Sbaban 			    idtype != IDMAP_GSID) {
2967cd37da74Snw141292 				retcode = IDMAP_ERR_NOTGROUP;
2968cd37da74Snw141292 				goto out;
2969cd37da74Snw141292 			}
2970e8c27ec8Sbaban 			res->id.idtype = idtype;
2971cd37da74Snw141292 
2972c5c4113dSnw141292 			res->id.idmap_id_u.sid.rid =
2973c5c4113dSnw141292 			    strtoul(values[1], &end, 10);
2974c5c4113dSnw141292 			res->id.idmap_id_u.sid.prefix = strdup(values[0]);
2975c5c4113dSnw141292 			if (res->id.idmap_id_u.sid.prefix == NULL) {
2976c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
2977c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
2978c5c4113dSnw141292 				goto out;
2979c5c4113dSnw141292 			}
2980c5c4113dSnw141292 
298162c60062Sbaban 			if (values[4] != NULL)
2982c5c4113dSnw141292 				res->direction =
2983651c0131Sbaban 				    (strtol(values[4], &end, 10) == 0)?
2984651c0131Sbaban 				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
2985c5c4113dSnw141292 			else
2986651c0131Sbaban 				res->direction = IDMAP_DIRECTION_U2W;
2987c5c4113dSnw141292 
2988c5c4113dSnw141292 			if (getname == 0 || values[2] == NULL)
2989c5c4113dSnw141292 				break;
29908e228215Sdm199847 			req->id2name = strdup(values[2]);
29918e228215Sdm199847 			if (req->id2name == NULL) {
2992c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
2993c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
2994c5c4113dSnw141292 				goto out;
2995c5c4113dSnw141292 			}
2996c5c4113dSnw141292 
2997c5c4113dSnw141292 			if (values[3] == NULL)
2998c5c4113dSnw141292 				break;
29998e228215Sdm199847 			req->id2domain = strdup(values[3]);
30008e228215Sdm199847 			if (req->id2domain == NULL) {
3001c5c4113dSnw141292 				idmapdlog(LOG_ERR, "Out of memory");
3002c5c4113dSnw141292 				retcode = IDMAP_ERR_MEMORY;
3003c5c4113dSnw141292 				goto out;
3004c5c4113dSnw141292 			}
3005cd37da74Snw141292 
3006c5c4113dSnw141292 			break;
3007c5c4113dSnw141292 		default:
3008c5c4113dSnw141292 			retcode = IDMAP_ERR_NOTSUPPORTED;
3009c5c4113dSnw141292 			break;
3010c5c4113dSnw141292 		}
3011c5c4113dSnw141292 	}
3012c5c4113dSnw141292 
3013c5c4113dSnw141292 out:
301462c60062Sbaban 	if (vm != NULL)
3015c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
3016c5c4113dSnw141292 	return (retcode);
3017c5c4113dSnw141292 }
3018c5c4113dSnw141292 
3019cd37da74Snw141292 static
3020cd37da74Snw141292 idmap_retcode
3021c5c4113dSnw141292 lookup_cache_name2sid(sqlite *cache, const char *name, const char *domain,
3022cd37da74Snw141292 	char **canonname, char **sidprefix, idmap_rid_t *rid, int *type)
3023cd37da74Snw141292 {
3024cd37da74Snw141292 	char		*end, *lower_name;
3025c5c4113dSnw141292 	char		*sql = NULL;
3026c5c4113dSnw141292 	const char	**values;
3027c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
3028c5c4113dSnw141292 	int		ncol;
3029c5c4113dSnw141292 	time_t		curtime;
3030c5c4113dSnw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
3031c5c4113dSnw141292 
3032c5c4113dSnw141292 	/* Get current time */
3033c5c4113dSnw141292 	errno = 0;
3034c5c4113dSnw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
3035cd37da74Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
3036c5c4113dSnw141292 		    strerror(errno));
3037c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3038c5c4113dSnw141292 		goto out;
3039c5c4113dSnw141292 	}
3040c5c4113dSnw141292 
3041c5c4113dSnw141292 	/* SQL to lookup the cache */
3042cd37da74Snw141292 	if ((lower_name = tolower_u8(name)) == NULL)
3043cd37da74Snw141292 		lower_name = (char *)name;
3044cd37da74Snw141292 	sql = sqlite_mprintf("SELECT sidprefix, rid, type, canon_name "
3045cd37da74Snw141292 	    "FROM name_cache WHERE name = %Q AND domain = %Q AND "
3046c5c4113dSnw141292 	    "(expiration = 0 OR expiration ISNULL OR "
3047cd37da74Snw141292 	    "expiration > %d);", lower_name, domain, curtime);
3048cd37da74Snw141292 	if (lower_name != name)
3049cd37da74Snw141292 		free(lower_name);
3050c5c4113dSnw141292 	if (sql == NULL) {
3051c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3052c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
3053c5c4113dSnw141292 		goto out;
3054c5c4113dSnw141292 	}
3055cd37da74Snw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 4, &values);
3056c5c4113dSnw141292 	sqlite_freemem(sql);
3057c5c4113dSnw141292 
3058c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
305962c60062Sbaban 		if (type != NULL) {
3060c5c4113dSnw141292 			if (values[2] == NULL) {
3061c5c4113dSnw141292 				retcode = IDMAP_ERR_CACHE;
3062c5c4113dSnw141292 				goto out;
3063c5c4113dSnw141292 			}
3064c5c4113dSnw141292 			*type = strtol(values[2], &end, 10);
3065c5c4113dSnw141292 		}
3066c5c4113dSnw141292 
3067e8c27ec8Sbaban 		if (values[0] == NULL || values[1] == NULL) {
3068e8c27ec8Sbaban 			retcode = IDMAP_ERR_CACHE;
3069e8c27ec8Sbaban 			goto out;
3070e8c27ec8Sbaban 		}
3071e8c27ec8Sbaban 
3072cd37da74Snw141292 		if (canonname != NULL) {
3073cd37da74Snw141292 			assert(values[3] != NULL);
3074cd37da74Snw141292 			if ((*canonname = strdup(values[3])) == NULL) {
3075cd37da74Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
3076cd37da74Snw141292 				retcode = IDMAP_ERR_MEMORY;
3077cd37da74Snw141292 				goto out;
3078cd37da74Snw141292 			}
3079cd37da74Snw141292 		}
3080cd37da74Snw141292 
3081c5c4113dSnw141292 		if ((*sidprefix = strdup(values[0])) == NULL) {
3082c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
3083c5c4113dSnw141292 			retcode = IDMAP_ERR_MEMORY;
3084e8c27ec8Sbaban 			if (canonname != NULL) {
3085e8c27ec8Sbaban 				free(*canonname);
3086e8c27ec8Sbaban 				*canonname = NULL;
3087e8c27ec8Sbaban 			}
3088c5c4113dSnw141292 			goto out;
3089c5c4113dSnw141292 		}
3090c5c4113dSnw141292 		*rid = strtoul(values[1], &end, 10);
3091c5c4113dSnw141292 	}
3092c5c4113dSnw141292 
3093c5c4113dSnw141292 out:
309462c60062Sbaban 	if (vm != NULL)
3095c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
3096c5c4113dSnw141292 	return (retcode);
3097c5c4113dSnw141292 }
3098c5c4113dSnw141292 
3099cd37da74Snw141292 static
3100cd37da74Snw141292 idmap_retcode
3101e8c27ec8Sbaban ad_lookup_by_winname(lookup_state_t *state,
3102e8c27ec8Sbaban 		const char *name, const char *domain, int eunixtype,
3103e8c27ec8Sbaban 		char **canonname, char **sidprefix,
3104e8c27ec8Sbaban 		idmap_rid_t *rid, int *wintype, char **unixname)
3105cd37da74Snw141292 {
3106c5c4113dSnw141292 	int			retries = 0;
3107c5c4113dSnw141292 	idmap_query_state_t	*qs = NULL;
3108c5c4113dSnw141292 	idmap_retcode		rc, retcode;
3109c5c4113dSnw141292 
3110c5c4113dSnw141292 retry:
3111e8c27ec8Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, 1, &qs);
3112e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
31130dcc7149Snw141292 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
31140dcc7149Snw141292 			goto retry;
3115*349d5d8fSnw141292 		degrade_svc(1, "failed to create request for AD lookup "
31160dcc7149Snw141292 		    "by winname");
3117e8c27ec8Sbaban 		return (retcode);
3118c5c4113dSnw141292 	}
3119c5c4113dSnw141292 
3120c8e26105Sjp151216 	restore_svc();
3121c8e26105Sjp151216 
3122e8c27ec8Sbaban 	if (state != NULL)
3123e8c27ec8Sbaban 		idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
3124e8c27ec8Sbaban 		    state->ad_unixgroup_attr);
3125c5c4113dSnw141292 
3126e8c27ec8Sbaban 	retcode = idmap_name2sid_batch_add1(qs, name, domain, eunixtype,
3127e8c27ec8Sbaban 	    canonname, sidprefix, rid, wintype, unixname, &rc);
3128c5c4113dSnw141292 
3129e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
313084decf41Sjp151216 		idmap_lookup_release_batch(&qs);
3131c5c4113dSnw141292 	else
31320dcc7149Snw141292 		retcode = idmap_lookup_batch_end(&qs);
3133c5c4113dSnw141292 
3134c5c4113dSnw141292 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
3135c5c4113dSnw141292 		goto retry;
3136c8e26105Sjp151216 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
3137*349d5d8fSnw141292 		degrade_svc(1, "some AD lookups timed out repeatedly");
3138c5c4113dSnw141292 
3139c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS) {
3140e8c27ec8Sbaban 		idmapdlog(LOG_NOTICE, "AD lookup by winname failed");
3141c5c4113dSnw141292 		return (retcode);
3142e8c27ec8Sbaban 	}
3143c5c4113dSnw141292 	return (rc);
3144c5c4113dSnw141292 }
3145c5c4113dSnw141292 
3146cd37da74Snw141292 static
3147cd37da74Snw141292 idmap_retcode
3148c5c4113dSnw141292 lookup_name2sid(sqlite *cache, const char *name, const char *domain,
3149cd37da74Snw141292 		int *is_wuser, char **canonname, char **sidprefix,
3150cd37da74Snw141292 		idmap_rid_t *rid, idmap_mapping *req)
3151cd37da74Snw141292 {
3152c5c4113dSnw141292 	int		type;
3153c5c4113dSnw141292 	idmap_retcode	retcode;
3154c5c4113dSnw141292 
3155cd37da74Snw141292 	*sidprefix = NULL;
3156e8c27ec8Sbaban 	if (canonname != NULL)
3157cd37da74Snw141292 		*canonname = NULL;
3158cd37da74Snw141292 
3159e8c27ec8Sbaban 	/* Lookup well-known SIDs table */
3160cd37da74Snw141292 	retcode = lookup_wksids_name2sid(name, canonname, sidprefix, rid,
3161cd37da74Snw141292 	    &type);
316262c60062Sbaban 	if (retcode == IDMAP_SUCCESS) {
3163e8c27ec8Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
316462c60062Sbaban 		goto out;
316562c60062Sbaban 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
316662c60062Sbaban 		return (retcode);
316762c60062Sbaban 	}
316862c60062Sbaban 
3169e8c27ec8Sbaban 	/* Lookup cache */
3170cd37da74Snw141292 	retcode = lookup_cache_name2sid(cache, name, domain, canonname,
3171cd37da74Snw141292 	    sidprefix, rid, &type);
3172e8c27ec8Sbaban 	if (retcode == IDMAP_SUCCESS) {
3173e8c27ec8Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
3174e8c27ec8Sbaban 		goto out;
3175e8c27ec8Sbaban 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
3176e8c27ec8Sbaban 		return (retcode);
3177e8c27ec8Sbaban 	}
3178e8c27ec8Sbaban 
3179e8c27ec8Sbaban 	/* Lookup AD */
3180e8c27ec8Sbaban 	retcode = ad_lookup_by_winname(NULL, name, domain, _IDMAP_T_UNDEF,
3181e8c27ec8Sbaban 	    canonname, sidprefix, rid, &type, NULL);
3182c5c4113dSnw141292 	if (retcode != IDMAP_SUCCESS)
3183c5c4113dSnw141292 		return (retcode);
3184e8c27ec8Sbaban 	/* Don't need to set req->direction |= _IDMAP_F_LOOKUP_AD; */
3185c5c4113dSnw141292 
318662c60062Sbaban out:
3187c5c4113dSnw141292 	/*
3188c5c4113dSnw141292 	 * Entry found (cache or Windows lookup)
3189cd37da74Snw141292 	 * is_wuser is both input as well as output parameter
3190c5c4113dSnw141292 	 */
3191e8c27ec8Sbaban 	if (*is_wuser == 1 && type != _IDMAP_T_USER)
3192e8c27ec8Sbaban 		retcode = IDMAP_ERR_NOTUSER;
3193e8c27ec8Sbaban 	else if (*is_wuser == 0 && type != _IDMAP_T_GROUP)
3194e8c27ec8Sbaban 		retcode = IDMAP_ERR_NOTGROUP;
3195e8c27ec8Sbaban 	else if (*is_wuser == -1) {
3196c5c4113dSnw141292 		/* Caller wants to know if its user or group */
3197c5c4113dSnw141292 		if (type == _IDMAP_T_USER)
3198cd37da74Snw141292 			*is_wuser = 1;
3199c5c4113dSnw141292 		else if (type == _IDMAP_T_GROUP)
3200cd37da74Snw141292 			*is_wuser = 0;
3201e8c27ec8Sbaban 		else
3202e8c27ec8Sbaban 			retcode = IDMAP_ERR_SID;
3203e8c27ec8Sbaban 	}
3204e8c27ec8Sbaban 
3205e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
3206cd37da74Snw141292 		free(*sidprefix);
3207cd37da74Snw141292 		*sidprefix = NULL;
3208e8c27ec8Sbaban 		if (canonname != NULL) {
3209cd37da74Snw141292 			free(*canonname);
3210cd37da74Snw141292 			*canonname = NULL;
3211cd37da74Snw141292 		}
3212c5c4113dSnw141292 	}
3213c5c4113dSnw141292 	return (retcode);
3214c5c4113dSnw141292 }
3215c5c4113dSnw141292 
3216cd37da74Snw141292 static
3217cd37da74Snw141292 idmap_retcode
3218c5c4113dSnw141292 name_based_mapping_pid2sid(sqlite *db, sqlite *cache, const char *unixname,
3219cd37da74Snw141292 		int is_user, idmap_mapping *req, idmap_id_res *res)
3220cd37da74Snw141292 {
3221c5c4113dSnw141292 	const char	*winname, *windomain;
3222cd37da74Snw141292 	char		*canonname;
3223c8e26105Sjp151216 	char		*default_domain = NULL;
3224c5c4113dSnw141292 	char		*sql = NULL, *errmsg = NULL;
3225c5c4113dSnw141292 	idmap_retcode	retcode;
3226c5c4113dSnw141292 	char		*end;
3227c5c4113dSnw141292 	const char	**values;
3228c5c4113dSnw141292 	sqlite_vm	*vm = NULL;
3229cd37da74Snw141292 	int		ncol, r, nrow;
3230cd37da74Snw141292 	int		is_wuser;
3231e8c27ec8Sbaban 	const char	*me = "name_based_mapping_pid2sid";
3232e8c27ec8Sbaban 
3233e8c27ec8Sbaban 	assert(unixname != NULL); /* We have unixname */
3234e8c27ec8Sbaban 	assert(req->id2name == NULL); /* We don't have winname */
3235e8c27ec8Sbaban 	assert(res->id.idmap_id_u.sid.prefix == NULL); /* No SID either */
3236c5c4113dSnw141292 
3237c5c4113dSnw141292 	RDLOCK_CONFIG();
3238c8e26105Sjp151216 	if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
3239c8e26105Sjp151216 		default_domain =
3240c8e26105Sjp151216 		    strdup(_idmapdstate.cfg->pgcfg.default_domain);
3241c8e26105Sjp151216 		if (default_domain == NULL) {
3242c5c4113dSnw141292 			UNLOCK_CONFIG();
3243c5c4113dSnw141292 			idmapdlog(LOG_ERR, "Out of memory");
3244c5c4113dSnw141292 			retcode = IDMAP_ERR_MEMORY;
3245c5c4113dSnw141292 			goto out;
3246c5c4113dSnw141292 		}
3247c5c4113dSnw141292 	}
3248c5c4113dSnw141292 	UNLOCK_CONFIG();
3249c5c4113dSnw141292 
3250c5c4113dSnw141292 	sql = sqlite_mprintf(
3251cd37da74Snw141292 	    "SELECT winname_display, windomain, w2u_order FROM namerules WHERE "
3252c5c4113dSnw141292 	    "u2w_order > 0 AND is_user = %d AND "
3253c5c4113dSnw141292 	    "(unixname = %Q OR unixname = '*') "
3254cd37da74Snw141292 	    "ORDER BY u2w_order ASC;", is_user, unixname);
3255c5c4113dSnw141292 	if (sql == NULL) {
3256c5c4113dSnw141292 		idmapdlog(LOG_ERR, "Out of memory");
3257c5c4113dSnw141292 		retcode = IDMAP_ERR_MEMORY;
3258c5c4113dSnw141292 		goto out;
3259c5c4113dSnw141292 	}
3260c5c4113dSnw141292 
3261c5c4113dSnw141292 	if (sqlite_compile(db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
3262c5c4113dSnw141292 		retcode = IDMAP_ERR_INTERNAL;
3263cd37da74Snw141292 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
3264cd37da74Snw141292 		    CHECK_NULL(errmsg));
3265c5c4113dSnw141292 		sqlite_freemem(errmsg);
3266c5c4113dSnw141292 		goto out;
3267c5c4113dSnw141292 	}
3268c5c4113dSnw141292 
3269cd37da74Snw141292 	for (nrow = 0; ; ) {
3270c5c4113dSnw141292 		r = sqlite_step(vm, &ncol, &values, NULL);
327184decf41Sjp151216 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
327284decf41Sjp151216 		if (r == SQLITE_ROW) {
3273cd37da74Snw141292 			nrow++;
3274c5c4113dSnw141292 			if (ncol < 3) {
3275c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
3276c5c4113dSnw141292 				goto out;
3277c5c4113dSnw141292 			}
3278c5c4113dSnw141292 			if (values[0] == NULL) {
3279c5c4113dSnw141292 				/* values [1] and [2] can be null */
3280c5c4113dSnw141292 				retcode = IDMAP_ERR_INTERNAL;
3281c5c4113dSnw141292 				goto out;
3282c5c4113dSnw141292 			}
3283c5c4113dSnw141292 			if (EMPTY_NAME(values[0])) {
3284c5c4113dSnw141292 				retcode = IDMAP_ERR_NOMAPPING;
3285c5c4113dSnw141292 				goto out;
3286c5c4113dSnw141292 			}
3287cd37da74Snw141292 
3288cd37da74Snw141292 			if (values[0][0] == '*') {
3289cd37da74Snw141292 				if (nrow > 1) {
3290cd37da74Snw141292 					/*
3291cd37da74Snw141292 					 * There were non-wildcard rules where
3292cd37da74Snw141292 					 * windows identity doesn't exist
3293cd37da74Snw141292 					 */
3294cd37da74Snw141292 					retcode = IDMAP_ERR_NOMAPPING;
3295cd37da74Snw141292 					goto out;
3296cd37da74Snw141292 				}
3297cd37da74Snw141292 				winname = unixname;
3298cd37da74Snw141292 			} else {
3299cd37da74Snw141292 				winname = values[0];
3300cd37da74Snw141292 			}
3301cd37da74Snw141292 
330262c60062Sbaban 			if (values[1] != NULL)
3303c5c4113dSnw141292 				windomain = values[1];
3304c8e26105Sjp151216 			else if (default_domain != NULL)
3305c8e26105Sjp151216 				windomain = default_domain;
3306c5c4113dSnw141292 			else {
3307cd37da74Snw141292 				idmapdlog(LOG_ERR, "%s: no domain", me);
3308c5c4113dSnw141292 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
3309c5c4113dSnw141292 				goto out;
3310c5c4113dSnw141292 			}
3311c5c4113dSnw141292 			/* Lookup winname@domain to sid */
3312cd37da74Snw141292 
3313cd37da74Snw141292 			is_wuser = res->id.idtype == IDMAP_USID ? 1
3314cd37da74Snw141292 			    : res->id.idtype == IDMAP_GSID ? 0
3315cd37da74Snw141292 			    : -1;
3316cd37da74Snw141292 
3317c5c4113dSnw141292 			retcode = lookup_name2sid(cache, winname, windomain,
3318cd37da74Snw141292 			    &is_wuser, &canonname,
3319cd37da74Snw141292 			    &res->id.idmap_id_u.sid.prefix,
3320c5c4113dSnw141292 			    &res->id.idmap_id_u.sid.rid, req);
3321e8c27ec8Sbaban 
3322c5c4113dSnw141292 			if (retcode == IDMAP_ERR_NOTFOUND) {
3323c5c4113dSnw141292 				continue;
3324c5c4113dSnw141292 			}
3325cd37da74Snw141292 
3326c5c4113dSnw141292 			goto out;
3327c5c4113dSnw141292 		} else if (r == SQLITE_DONE) {
3328c5c4113dSnw141292 			retcode = IDMAP_ERR_NOTFOUND;
3329c5c4113dSnw141292 			goto out;
3330c5c4113dSnw141292 		} else {
3331c5c4113dSnw141292 			(void) sqlite_finalize(vm, &errmsg);
3332c5c4113dSnw141292 			vm = NULL;
3333cd37da74Snw141292 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
3334cd37da74Snw141292 			    CHECK_NULL(errmsg));
3335c5c4113dSnw141292 			sqlite_freemem(errmsg);
3336c5c4113dSnw141292 			retcode = IDMAP_ERR_INTERNAL;
3337c5c4113dSnw141292 			goto out;
3338c5c4113dSnw141292 		}
3339c5c4113dSnw141292 	}
3340c5c4113dSnw141292 
3341c5c4113dSnw141292 out:
334262c60062Sbaban 	if (sql != NULL)
3343c5c4113dSnw141292 		sqlite_freemem(sql);
3344c5c4113dSnw141292 	if (retcode == IDMAP_SUCCESS) {
3345cd37da74Snw141292 		res->id.idtype = is_wuser ? IDMAP_USID : IDMAP_GSID;
3346cd37da74Snw141292 
334762c60062Sbaban 		if (values[2] != NULL)
3348c5c4113dSnw141292 			res->direction =
3349651c0131Sbaban 			    (strtol(values[2], &end, 10) == 0)?
3350651c0131Sbaban 			    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
3351c5c4113dSnw141292 		else
3352651c0131Sbaban 			res->direction = IDMAP_DIRECTION_U2W;
33538e228215Sdm199847 
3354cd37da74Snw141292 		req->id2name = canonname;
33558e228215Sdm199847 		if (req->id2name != NULL) {
3356c8e26105Sjp151216 			if (windomain == default_domain) {
33578e228215Sdm199847 				req->id2domain = (char *)windomain;
3358c8e26105Sjp151216 				default_domain = NULL;
33598e228215Sdm199847 			} else {
33608e228215Sdm199847 				req->id2domain = strdup(windomain);
33618e228215Sdm199847 			}
3362c5c4113dSnw141292 		}
3363c5c4113dSnw141292 	}
336462c60062Sbaban 	if (vm != NULL)
3365c5c4113dSnw141292 		(void) sqlite_finalize(vm, NULL);
3366c8e26105Sjp151216 	if (default_domain != NULL)
3367c8e26105Sjp151216 		free(default_domain);
3368c5c4113dSnw141292 	return (retcode);
3369c5c4113dSnw141292 }
3370c5c4113dSnw141292 
3371cd37da74Snw141292 /*
3372cd37da74Snw141292  * Convention when processing unix2win requests:
3373cd37da74Snw141292  *
3374cd37da74Snw141292  * Unix identity:
3375cd37da74Snw141292  * req->id1name =
3376cd37da74Snw141292  *              unixname if given otherwise unixname found will be placed
3377cd37da74Snw141292  *              here.
3378cd37da74Snw141292  * req->id1domain =
3379cd37da74Snw141292  *              NOT USED
3380cd37da74Snw141292  * req->id1.idtype =
3381cd37da74Snw141292  *              Given type (IDMAP_UID or IDMAP_GID)
3382cd37da74Snw141292  * req->id1..[uid or gid] =
3383cd37da74Snw141292  *              UID/GID if given otherwise UID/GID found will be placed here.
3384cd37da74Snw141292  *
3385cd37da74Snw141292  * Windows identity:
3386cd37da74Snw141292  * req->id2name =
3387cd37da74Snw141292  *              winname found will be placed here.
3388cd37da74Snw141292  * req->id2domain =
3389cd37da74Snw141292  *              windomain found will be placed here.
3390cd37da74Snw141292  * res->id.idtype =
3391cd37da74Snw141292  *              Target type initialized from req->id2.idtype. If
3392cd37da74Snw141292  *              it is IDMAP_SID then actual type (IDMAP_USID/GSID) found
3393cd37da74Snw141292  *              will be placed here.
3394cd37da74Snw141292  * req->id..sid.[prefix, rid] =
3395cd37da74Snw141292  *              SID found will be placed here.
3396cd37da74Snw141292  *
3397cd37da74Snw141292  * Others:
3398cd37da74Snw141292  * res->retcode =
3399cd37da74Snw141292  *              Return status for this request will be placed here.
3400cd37da74Snw141292  * res->direction =
3401cd37da74Snw141292  *              Direction found will be placed here. Direction
3402cd37da74Snw141292  *              meaning whether the resultant mapping is valid
3403cd37da74Snw141292  *              only from unix2win or bi-directional.
3404cd37da74Snw141292  * req->direction =
3405cd37da74Snw141292  *              INTERNAL USE. Used by idmapd to set various
3406cd37da74Snw141292  *              flags (_IDMAP_F_xxxx) to aid in processing
3407cd37da74Snw141292  *              of the request.
3408cd37da74Snw141292  * req->id2.idtype =
3409cd37da74Snw141292  *              INTERNAL USE. Initially this is the requested target
3410cd37da74Snw141292  *              type and is used to initialize res->id.idtype.
3411cd37da74Snw141292  *              ad_lookup_batch() uses this field temporarily to store
3412cd37da74Snw141292  *              sid_type obtained by the batched AD lookups and after
3413cd37da74Snw141292  *              use resets it to IDMAP_NONE to prevent xdr from
3414cd37da74Snw141292  *              mis-interpreting the contents of req->id2.
3415cd37da74Snw141292  * req->id2..[uid or gid or sid] =
3416cd37da74Snw141292  *              NOT USED
3417cd37da74Snw141292  */
3418cd37da74Snw141292 
3419cd37da74Snw141292 /*
3420cd37da74Snw141292  * This function does the following:
3421cd37da74Snw141292  * 1. Lookup well-known SIDs table.
3422cd37da74Snw141292  * 2. Lookup cache.
3423cd37da74Snw141292  * 3. Check if the client does not want new mapping to be allocated
3424cd37da74Snw141292  *    in which case this pass is the final pass.
3425e8c27ec8Sbaban  * 4. Set AD/NLDAP lookup flags if it determines that the next stage needs
3426e8c27ec8Sbaban  *    to do AD/NLDAP lookup.
3427cd37da74Snw141292  */
3428c5c4113dSnw141292 idmap_retcode
3429e8c27ec8Sbaban pid2sid_first_pass(lookup_state_t *state, sqlite *cache,
3430c5c4113dSnw141292 		idmap_mapping *req, idmap_id_res *res, int is_user,
3431cd37da74Snw141292 		int getname)
3432cd37da74Snw141292 {
3433e8c27ec8Sbaban 	idmap_retcode	retcode;
3434e8c27ec8Sbaban 	bool_t		gen_localsid_on_err = FALSE;
3435c5c4113dSnw141292 
3436e8c27ec8Sbaban 	/* Initialize result */
3437c5c4113dSnw141292 	res->id.idtype = req->id2.idtype;
3438e8c27ec8Sbaban 	res->direction = IDMAP_DIRECTION_UNDEF;
3439c5c4113dSnw141292 
3440e8c27ec8Sbaban 	if (req->id2.idmap_id_u.sid.prefix != NULL) {
3441e8c27ec8Sbaban 		/* sanitize sidprefix */
3442e8c27ec8Sbaban 		free(req->id2.idmap_id_u.sid.prefix);
3443e8c27ec8Sbaban 		req->id2.idmap_id_u.sid.prefix = NULL;
3444e8c27ec8Sbaban 	}
3445e8c27ec8Sbaban 
3446e8c27ec8Sbaban 	/* Lookup well-known SIDs table */
3447c5c4113dSnw141292 	retcode = lookup_wksids_pid2sid(req, res, is_user);
3448c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
3449c5c4113dSnw141292 		goto out;
3450c5c4113dSnw141292 
3451e8c27ec8Sbaban 	/* Lookup cache */
3452c5c4113dSnw141292 	retcode = lookup_cache_pid2sid(cache, req, res, is_user, getname);
3453c5c4113dSnw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
3454c5c4113dSnw141292 		goto out;
3455c5c4113dSnw141292 
3456c5c4113dSnw141292 	/* Ephemeral ids cannot be allocated during pid2sid */
3457c5c4113dSnw141292 	if (IS_EPHEMERAL(req->id1.idmap_id_u.uid)) {
345862c60062Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
3459c5c4113dSnw141292 		goto out;
3460c5c4113dSnw141292 	}
3461c5c4113dSnw141292 
3462c5c4113dSnw141292 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req) || AVOID_NAMESERVICE(req)) {
3463e8c27ec8Sbaban 		gen_localsid_on_err = TRUE;
346462c60062Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
3465c5c4113dSnw141292 		goto out;
3466c5c4113dSnw141292 	}
3467c5c4113dSnw141292 
3468e8c27ec8Sbaban 	/* Set flags for the next stage */
3469e8c27ec8Sbaban 	if (AD_MODE(req->id1.idtype, state)) {
3470e8c27ec8Sbaban 		/*
3471e8c27ec8Sbaban 		 * If AD-based name mapping is enabled then the next stage
3472e8c27ec8Sbaban 		 * will need to lookup AD using unixname to get the
3473e8c27ec8Sbaban 		 * corresponding winname.
3474e8c27ec8Sbaban 		 */
3475e8c27ec8Sbaban 		if (req->id1name == NULL) {
3476e8c27ec8Sbaban 			/* Get unixname if only pid is given. */
3477e8c27ec8Sbaban 			retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid,
3478e8c27ec8Sbaban 			    is_user, &req->id1name);
3479e8c27ec8Sbaban 			if (retcode != IDMAP_SUCCESS)
3480e8c27ec8Sbaban 				goto out;
3481c5c4113dSnw141292 		}
3482e8c27ec8Sbaban 		req->direction |= _IDMAP_F_LOOKUP_AD;
3483e8c27ec8Sbaban 		state->ad_nqueries++;
3484e8c27ec8Sbaban 	} else if (NLDAP_OR_MIXED_MODE(req->id1.idtype, state)) {
3485e8c27ec8Sbaban 		/*
3486e8c27ec8Sbaban 		 * If native LDAP or mixed mode is enabled for name mapping
3487e8c27ec8Sbaban 		 * then the next stage will need to lookup native LDAP using
3488e8c27ec8Sbaban 		 * unixname/pid to get the corresponding winname.
3489e8c27ec8Sbaban 		 */
3490e8c27ec8Sbaban 		req->direction |= _IDMAP_F_LOOKUP_NLDAP;
3491e8c27ec8Sbaban 		state->nldap_nqueries++;
3492c5c4113dSnw141292 	}
3493c5c4113dSnw141292 
3494e8c27ec8Sbaban 	/*
3495e8c27ec8Sbaban 	 * Failed to find non-expired entry in cache. Set the flag to
3496e8c27ec8Sbaban 	 * indicate that we are not done yet.
3497e8c27ec8Sbaban 	 */
3498e8c27ec8Sbaban 	state->pid2sid_done = FALSE;
3499e8c27ec8Sbaban 	req->direction |= _IDMAP_F_NOTDONE;
3500e8c27ec8Sbaban 	retcode = IDMAP_SUCCESS;
3501e8c27ec8Sbaban 
3502e8c27ec8Sbaban out:
3503e8c27ec8Sbaban 	res->retcode = idmap_stat4prot(retcode);
3504e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
3505e8c27ec8Sbaban 		if (gen_localsid_on_err == TRUE)
3506e8c27ec8Sbaban 			(void) generate_localsid(req, res, is_user);
3507e8c27ec8Sbaban 	return (retcode);
3508e8c27ec8Sbaban }
3509e8c27ec8Sbaban 
3510e8c27ec8Sbaban idmap_retcode
3511e8c27ec8Sbaban pid2sid_second_pass(lookup_state_t *state, sqlite *cache, sqlite *db,
3512e8c27ec8Sbaban 		idmap_mapping *req, idmap_id_res *res, int is_user)
3513e8c27ec8Sbaban {
3514e8c27ec8Sbaban 	bool_t		gen_localsid_on_err = TRUE;
3515e8c27ec8Sbaban 	idmap_retcode	retcode = IDMAP_SUCCESS;
3516e8c27ec8Sbaban 
3517e8c27ec8Sbaban 	/* Check if second pass is needed */
3518e8c27ec8Sbaban 	if (ARE_WE_DONE(req->direction))
3519e8c27ec8Sbaban 		return (res->retcode);
3520e8c27ec8Sbaban 
3521e8c27ec8Sbaban 	/* Get status from previous pass */
3522e8c27ec8Sbaban 	retcode = res->retcode;
3523e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
3524e8c27ec8Sbaban 		goto out;
3525e8c27ec8Sbaban 
3526e8c27ec8Sbaban 	/*
3527e8c27ec8Sbaban 	 * If directory-based name mapping is enabled then the winname
3528e8c27ec8Sbaban 	 * may already have been retrieved from the AD object (AD-mode)
3529e8c27ec8Sbaban 	 * or from native LDAP object (nldap-mode or mixed-mode) -- done.
3530e8c27ec8Sbaban 	 */
3531e8c27ec8Sbaban 	if (res->id.idmap_id_u.sid.prefix != NULL || req->id2name != NULL) {
3532e8c27ec8Sbaban 		if (AD_MODE(req->id1.idtype, state))
3533e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
3534e8c27ec8Sbaban 		else if (NLDAP_MODE(req->id1.idtype, state))
3535e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_BI;
3536e8c27ec8Sbaban 		else if (MIXED_MODE(req->id1.idtype, state))
3537e8c27ec8Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
3538e8c27ec8Sbaban 		goto out;
3539e8c27ec8Sbaban 	}
3540e8c27ec8Sbaban 
3541e8c27ec8Sbaban 	if (req->id1name == NULL) {
3542e8c27ec8Sbaban 		/* Get unixname from name service */
3543e8c27ec8Sbaban 		retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid, is_user,
3544e8c27ec8Sbaban 		    &req->id1name);
3545e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS)
3546e8c27ec8Sbaban 			goto out;
3547e8c27ec8Sbaban 	} else if (req->id1.idmap_id_u.uid == SENTINEL_PID) {
3548e8c27ec8Sbaban 		/* Get pid from name service */
3549e8c27ec8Sbaban 		retcode = ns_lookup_byname(req->id1name, NULL, &req->id1);
3550e8c27ec8Sbaban 		if (retcode != IDMAP_SUCCESS) {
3551e8c27ec8Sbaban 			gen_localsid_on_err = FALSE;
3552e8c27ec8Sbaban 			goto out;
3553e8c27ec8Sbaban 		}
3554e8c27ec8Sbaban 	}
3555e8c27ec8Sbaban 
3556e8c27ec8Sbaban 	/* Use unixname to evaluate local name-based mapping rules */
3557e8c27ec8Sbaban 	retcode = name_based_mapping_pid2sid(db, cache, req->id1name, is_user,
3558c5c4113dSnw141292 	    req, res);
3559c5c4113dSnw141292 	if (retcode == IDMAP_ERR_NOTFOUND) {
3560c5c4113dSnw141292 		retcode = generate_localsid(req, res, is_user);
3561e8c27ec8Sbaban 		gen_localsid_on_err = FALSE;
3562e8c27ec8Sbaban 	}
3563c5c4113dSnw141292 
3564c5c4113dSnw141292 out:
3565c5c4113dSnw141292 	res->retcode = idmap_stat4prot(retcode);
3566e8c27ec8Sbaban 	if (res->retcode != IDMAP_SUCCESS) {
3567e8c27ec8Sbaban 		req->direction = _IDMAP_F_DONE;
3568e8c27ec8Sbaban 		if (gen_localsid_on_err == TRUE)
3569e8c27ec8Sbaban 			(void) generate_localsid(req, res, is_user);
3570e8c27ec8Sbaban 	}
3571e8c27ec8Sbaban 	if (!ARE_WE_DONE(req->direction))
3572e8c27ec8Sbaban 		state->pid2sid_done = FALSE;
3573c5c4113dSnw141292 	return (retcode);
3574c5c4113dSnw141292 }
3575c5c4113dSnw141292 
3576cd37da74Snw141292 static
3577cd37da74Snw141292 idmap_retcode
3578e8c27ec8Sbaban ad_lookup_by_sid(lookup_state_t *state,
3579e8c27ec8Sbaban 		const char *sidprefix, idmap_rid_t rid, int eunixtype,
3580e8c27ec8Sbaban 		char **name, char **domain, int *type, char **unixname)
3581cd37da74Snw141292 {
3582e8c27ec8Sbaban 	int			retries = 0;
3583c5c4113dSnw141292 	idmap_query_state_t	*qs = NULL;
3584c5c4113dSnw141292 	idmap_retcode		rc, retcode;
3585c5c4113dSnw141292 
3586e8c27ec8Sbaban retry:
3587e8c27ec8Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, 1, &qs);
3588e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
35890dcc7149Snw141292 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
35900dcc7149Snw141292 			goto retry;
3591*349d5d8fSnw141292 		degrade_svc(1, "failed to create request for AD lookup by SID");
3592e8c27ec8Sbaban 		return (retcode);
3593c5c4113dSnw141292 	}
3594c5c4113dSnw141292 
3595c8e26105Sjp151216 	restore_svc();
3596c8e26105Sjp151216 
3597e8c27ec8Sbaban 	if (state != NULL)
3598e8c27ec8Sbaban 		idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
3599e8c27ec8Sbaban 		    state->ad_unixgroup_attr);
3600c5c4113dSnw141292 
3601e8c27ec8Sbaban 	retcode = idmap_sid2name_batch_add1(qs, sidprefix, &rid, eunixtype,
3602e8c27ec8Sbaban 	    name, domain, type, unixname, &rc);
3603e8c27ec8Sbaban 
3604e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
3605e8c27ec8Sbaban 		idmap_lookup_release_batch(&qs);
3606e8c27ec8Sbaban 	else
36070dcc7149Snw141292 		retcode = idmap_lookup_batch_end(&qs);
3608e8c27ec8Sbaban 
3609e8c27ec8Sbaban 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
3610e8c27ec8Sbaban 		goto retry;
3611e8c27ec8Sbaban 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
3612*349d5d8fSnw141292 		degrade_svc(1, "some AD lookups timed out repeatedly");
3613c5c4113dSnw141292 
3614e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
3615e8c27ec8Sbaban 		idmapdlog(LOG_NOTICE, "AD lookup by SID failed");
3616c5c4113dSnw141292 		return (retcode);
3617c5c4113dSnw141292 	}
3618e8c27ec8Sbaban 	return (rc);
3619e8c27ec8Sbaban }
3620c5c4113dSnw141292 
3621cd37da74Snw141292 static
3622cd37da74Snw141292 int
3623651c0131Sbaban copy_mapping_request(idmap_mapping *mapping, idmap_mapping *request)
3624c5c4113dSnw141292 {
3625651c0131Sbaban 	(void) memset(mapping, 0, sizeof (*mapping));
3626651c0131Sbaban 
3627c5c4113dSnw141292 	mapping->flag = request->flag;
3628e8c27ec8Sbaban 	mapping->direction = _IDMAP_F_DONE;
3629651c0131Sbaban 	mapping->id2.idtype = request->id2.idtype;
3630c5c4113dSnw141292 
3631c5c4113dSnw141292 	mapping->id1.idtype = request->id1.idtype;
3632cd37da74Snw141292 	if (IS_REQUEST_SID(*request, 1)) {
3633c5c4113dSnw141292 		mapping->id1.idmap_id_u.sid.rid =
3634c5c4113dSnw141292 		    request->id1.idmap_id_u.sid.rid;
3635651c0131Sbaban 		if (!EMPTY_STRING(request->id1.idmap_id_u.sid.prefix)) {
3636c5c4113dSnw141292 			mapping->id1.idmap_id_u.sid.prefix =
3637c5c4113dSnw141292 			    strdup(request->id1.idmap_id_u.sid.prefix);
3638651c0131Sbaban 			if (mapping->id1.idmap_id_u.sid.prefix == NULL)
36398e228215Sdm199847 				goto errout;
3640651c0131Sbaban 		}
3641c5c4113dSnw141292 	} else {
3642c5c4113dSnw141292 		mapping->id1.idmap_id_u.uid = request->id1.idmap_id_u.uid;
3643c5c4113dSnw141292 	}
3644c5c4113dSnw141292 
3645e8c27ec8Sbaban 	if (!EMPTY_STRING(request->id1domain)) {
36468e228215Sdm199847 		mapping->id1domain = strdup(request->id1domain);
36478e228215Sdm199847 		if (mapping->id1domain == NULL)
36488e228215Sdm199847 			goto errout;
3649e8c27ec8Sbaban 	}
3650c5c4113dSnw141292 
3651e8c27ec8Sbaban 	if (!EMPTY_STRING(request->id1name)) {
36528e228215Sdm199847 		mapping->id1name = strdup(request->id1name);
36538e228215Sdm199847 		if (mapping->id1name == NULL)
36548e228215Sdm199847 			goto errout;
3655e8c27ec8Sbaban 	}
3656c5c4113dSnw141292 
3657651c0131Sbaban 	/* We don't need the rest of the request i.e request->id2 */
3658651c0131Sbaban 	return (0);
3659c5c4113dSnw141292 
3660651c0131Sbaban errout:
36618e228215Sdm199847 	if (mapping->id1.idmap_id_u.sid.prefix != NULL)
3662651c0131Sbaban 		free(mapping->id1.idmap_id_u.sid.prefix);
36638e228215Sdm199847 	if (mapping->id1domain != NULL)
36648e228215Sdm199847 		free(mapping->id1domain);
36658e228215Sdm199847 	if (mapping->id1name != NULL)
36668e228215Sdm199847 		free(mapping->id1name);
3667651c0131Sbaban 
3668651c0131Sbaban 	(void) memset(mapping, 0, sizeof (*mapping));
3669651c0131Sbaban 	return (-1);
3670c5c4113dSnw141292 }
3671c5c4113dSnw141292 
3672c5c4113dSnw141292 
3673c5c4113dSnw141292 idmap_retcode
3674c5c4113dSnw141292 get_w2u_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
3675cd37da74Snw141292 		idmap_mapping *mapping)
3676cd37da74Snw141292 {
3677c5c4113dSnw141292 	idmap_id_res	idres;
3678c5c4113dSnw141292 	lookup_state_t	state;
3679dd5829d1Sbaban 	char		*cp;
3680c5c4113dSnw141292 	idmap_retcode	retcode;
3681c5c4113dSnw141292 	const char	*winname, *windomain;
3682c5c4113dSnw141292 
3683c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
3684c5c4113dSnw141292 	(void) memset(&state, 0, sizeof (state));
3685c5c4113dSnw141292 
3686e8c27ec8Sbaban 	/* Get directory-based name mapping info */
3687e8c27ec8Sbaban 	retcode = get_ds_namemap_type(&state);
3688e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
3689c5c4113dSnw141292 		goto out;
3690c5c4113dSnw141292 
3691e8c27ec8Sbaban 	/*
3692e8c27ec8Sbaban 	 * Copy data from "request" to "mapping". Note that
3693e8c27ec8Sbaban 	 * empty strings are not copied from "request" to
3694e8c27ec8Sbaban 	 * "mapping" and therefore the coresponding strings in
3695e8c27ec8Sbaban 	 * "mapping" will be NULL. This eliminates having to
3696e8c27ec8Sbaban 	 * check for empty strings henceforth.
3697e8c27ec8Sbaban 	 */
3698651c0131Sbaban 	if (copy_mapping_request(mapping, request) < 0) {
3699651c0131Sbaban 		retcode = IDMAP_ERR_MEMORY;
3700651c0131Sbaban 		goto out;
3701651c0131Sbaban 	}
3702c5c4113dSnw141292 
37038e228215Sdm199847 	winname = mapping->id1name;
37048e228215Sdm199847 	windomain = mapping->id1domain;
3705c5c4113dSnw141292 
3706e8c27ec8Sbaban 	if (winname == NULL && windomain != NULL) {
3707c5c4113dSnw141292 		retcode = IDMAP_ERR_ARG;
3708c5c4113dSnw141292 		goto out;
3709c5c4113dSnw141292 	}
3710c5c4113dSnw141292 
3711e8c27ec8Sbaban 	/* Need atleast winname or sid to proceed */
3712e8c27ec8Sbaban 	if (winname == NULL && mapping->id1.idmap_id_u.sid.prefix == NULL) {
3713e8c27ec8Sbaban 		retcode = IDMAP_ERR_ARG;
3714e8c27ec8Sbaban 		goto out;
3715e8c27ec8Sbaban 	}
3716e8c27ec8Sbaban 
3717e8c27ec8Sbaban 	/*
3718e8c27ec8Sbaban 	 * If domainname is not given but we have a fully qualified
3719e8c27ec8Sbaban 	 * winname then extract the domainname from the winname,
3720e8c27ec8Sbaban 	 * otherwise use the default_domain from the config
3721e8c27ec8Sbaban 	 */
3722e8c27ec8Sbaban 	if (winname != NULL && windomain == NULL) {
37238e228215Sdm199847 		retcode = IDMAP_SUCCESS;
3724dd5829d1Sbaban 		if ((cp = strchr(winname, '@')) != NULL) {
3725dd5829d1Sbaban 			*cp = '\0';
37268e228215Sdm199847 			mapping->id1domain = strdup(cp + 1);
37278e228215Sdm199847 			if (mapping->id1domain == NULL)
37288e228215Sdm199847 				retcode = IDMAP_ERR_MEMORY;
3729e8c27ec8Sbaban 		} else if (lookup_wksids_name2sid(winname, NULL, NULL, NULL,
3730e8c27ec8Sbaban 		    NULL) != IDMAP_SUCCESS) {
3731e8c27ec8Sbaban 			/* well-known SIDs don't need domain */
37328e228215Sdm199847 			RDLOCK_CONFIG();
3733c8e26105Sjp151216 			if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
37348e228215Sdm199847 				mapping->id1domain =
37358e228215Sdm199847 				    strdup(_idmapdstate.cfg->
3736c8e26105Sjp151216 				    pgcfg.default_domain);
37378e228215Sdm199847 				if (mapping->id1domain == NULL)
37388e228215Sdm199847 					retcode = IDMAP_ERR_MEMORY;
3739e8c27ec8Sbaban 			} else {
3740e8c27ec8Sbaban 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
37418e228215Sdm199847 			}
3742c5c4113dSnw141292 			UNLOCK_CONFIG();
37438e228215Sdm199847 		}
3744c5c4113dSnw141292 		if (retcode != IDMAP_SUCCESS)
3745c5c4113dSnw141292 			goto out;
3746c5c4113dSnw141292 	}
3747c5c4113dSnw141292 
3748e8c27ec8Sbaban 	/*
3749e8c27ec8Sbaban 	 * First pass looks up the well-known SIDs table and cache
3750e8c27ec8Sbaban 	 * and handles localSIDs
3751e8c27ec8Sbaban 	 */
3752c5c4113dSnw141292 	state.sid2pid_done = TRUE;
3753c5c4113dSnw141292 	retcode = sid2pid_first_pass(&state, cache, mapping, &idres);
3754c5c4113dSnw141292 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
3755c5c4113dSnw141292 		goto out;
3756c5c4113dSnw141292 
3757e8c27ec8Sbaban 	/* AD lookup by winname or by sid */
3758e8c27ec8Sbaban 	if (state.ad_nqueries > 0) {
3759e8c27ec8Sbaban 		retcode = ad_lookup(&state, mapping, &idres, 1, 1, 0);
3760e8c27ec8Sbaban 		if (IDMAP_ERROR(retcode))
3761e8c27ec8Sbaban 			goto out;
3762c5c4113dSnw141292 	}
3763c5c4113dSnw141292 
3764e8c27ec8Sbaban 	/*
3765e8c27ec8Sbaban 	 * If nldap-based name mapping is enabled then lookup native LDAP
3766e8c27ec8Sbaban 	 * directory service by winname to get pid and unixname. Ignore
3767e8c27ec8Sbaban 	 * non-fatal errors in which case we simply fallback to evaluating
3768e8c27ec8Sbaban 	 * local name-based mapping rules.
3769e8c27ec8Sbaban 	 */
3770e8c27ec8Sbaban 	if (mapping->id1name != NULL && NLDAP_MODE(idres.id.idtype, (&state))) {
3771e8c27ec8Sbaban 		retcode = nldap_lookup(mapping, &idres, 1, 1);
3772e8c27ec8Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
3773e8c27ec8Sbaban 			goto out;
3774e8c27ec8Sbaban 		idres.retcode = IDMAP_SUCCESS;
3775e8c27ec8Sbaban 	}
3776e8c27ec8Sbaban 
3777e8c27ec8Sbaban 	/* Next pass performs name-based mapping and ephemeral mapping. */
3778c5c4113dSnw141292 	state.sid2pid_done = TRUE;
3779c5c4113dSnw141292 	retcode = sid2pid_second_pass(&state, cache, db, mapping, &idres);
3780c5c4113dSnw141292 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
3781c5c4113dSnw141292 		goto out;
3782c5c4113dSnw141292 
3783c5c4113dSnw141292 	/* Update cache */
3784c5c4113dSnw141292 	(void) update_cache_sid2pid(&state, cache, mapping, &idres);
3785c5c4113dSnw141292 
3786c5c4113dSnw141292 out:
3787e8c27ec8Sbaban 	/*
3788e8c27ec8Sbaban 	 * Note that "mapping" is returned to the client. Therefore
3789e8c27ec8Sbaban 	 * copy whatever we have in "idres" to mapping->id2 and
3790e8c27ec8Sbaban 	 * free idres.
3791e8c27ec8Sbaban 	 */
3792c5c4113dSnw141292 	mapping->direction = idres.direction;
3793c5c4113dSnw141292 	mapping->id2 = idres.id;
3794c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
3795e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
379662c60062Sbaban 		mapping->id2.idmap_id_u.uid = UID_NOBODY;
3797c5c4113dSnw141292 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
3798e8c27ec8Sbaban 	cleanup_lookup_state(&state);
3799c5c4113dSnw141292 	return (retcode);
3800c5c4113dSnw141292 }
3801c5c4113dSnw141292 
3802c5c4113dSnw141292 idmap_retcode
3803c5c4113dSnw141292 get_u2w_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
3804cd37da74Snw141292 		idmap_mapping *mapping, int is_user)
3805cd37da74Snw141292 {
3806c5c4113dSnw141292 	idmap_id_res	idres;
3807c5c4113dSnw141292 	lookup_state_t	state;
3808c5c4113dSnw141292 	idmap_retcode	retcode;
3809e8c27ec8Sbaban 	char		*canonname;
3810e8c27ec8Sbaban 	int		is_wuser;
3811c5c4113dSnw141292 
3812c5c4113dSnw141292 	/*
3813c5c4113dSnw141292 	 * In order to re-use the pid2sid code, we convert
3814c5c4113dSnw141292 	 * our input data into structs that are expected by
3815c5c4113dSnw141292 	 * pid2sid_first_pass.
3816c5c4113dSnw141292 	 */
3817c5c4113dSnw141292 
3818c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
3819c5c4113dSnw141292 	(void) memset(&state, 0, sizeof (state));
3820c5c4113dSnw141292 
3821e8c27ec8Sbaban 	/* Get directory-based name mapping info */
3822e8c27ec8Sbaban 	retcode = get_ds_namemap_type(&state);
3823e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
3824e8c27ec8Sbaban 		goto out;
3825e8c27ec8Sbaban 
3826e8c27ec8Sbaban 	/*
3827e8c27ec8Sbaban 	 * Copy data from "request" to "mapping". Note that
3828e8c27ec8Sbaban 	 * empty strings are not copied from "request" to
3829e8c27ec8Sbaban 	 * "mapping" and therefore the coresponding strings in
3830e8c27ec8Sbaban 	 * "mapping" will be NULL. This eliminates having to
3831e8c27ec8Sbaban 	 * check for empty strings henceforth.
3832e8c27ec8Sbaban 	 */
3833651c0131Sbaban 	if (copy_mapping_request(mapping, request) < 0) {
3834651c0131Sbaban 		retcode = IDMAP_ERR_MEMORY;
3835651c0131Sbaban 		goto out;
3836651c0131Sbaban 	}
3837c5c4113dSnw141292 
3838e8c27ec8Sbaban 	/*
3839e8c27ec8Sbaban 	 * For unix to windows mapping request, we need atleast a
3840e8c27ec8Sbaban 	 * unixname or uid/gid to proceed
3841e8c27ec8Sbaban 	 */
3842e8c27ec8Sbaban 	if (mapping->id1name == NULL &&
3843cf5b5989Sdm199847 	    mapping->id1.idmap_id_u.uid == SENTINEL_PID) {
3844c5c4113dSnw141292 		retcode = IDMAP_ERR_ARG;
3845c5c4113dSnw141292 		goto out;
3846c5c4113dSnw141292 	}
3847c5c4113dSnw141292 
3848e8c27ec8Sbaban 	/* First pass looks up cache and well-known SIDs */
3849e8c27ec8Sbaban 	state.pid2sid_done = TRUE;
3850e8c27ec8Sbaban 	retcode = pid2sid_first_pass(&state, cache, mapping, &idres,
3851e8c27ec8Sbaban 	    is_user, 1);
3852e8c27ec8Sbaban 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
3853c5c4113dSnw141292 		goto out;
3854e8c27ec8Sbaban 
3855e8c27ec8Sbaban 	if (state.nldap_nqueries > 0) {
3856e8c27ec8Sbaban 		/*
3857e8c27ec8Sbaban 		 * This means directory-based name mapping (nldap or mixed
3858e8c27ec8Sbaban 		 * mode) is enabled. Lookup native LDAP directory service
3859e8c27ec8Sbaban 		 * by unixname or pid to get the winname. Ignore non-fatal
3860e8c27ec8Sbaban 		 * errors in which case we simply fallback to local name
3861e8c27ec8Sbaban 		 * based mapping rules.
3862e8c27ec8Sbaban 		 */
3863e8c27ec8Sbaban 		retcode = nldap_lookup(mapping, &idres, 0, 0);
3864e8c27ec8Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
3865c5c4113dSnw141292 			goto out;
3866e8c27ec8Sbaban 		idres.retcode = IDMAP_SUCCESS;
3867e8c27ec8Sbaban 
3868e8c27ec8Sbaban 		/*
3869e8c27ec8Sbaban 		 * If we've winname then get SID. We use lookup_name2sid()
3870e8c27ec8Sbaban 		 * instead of ad_lookup() in order to first resolve name2sid
3871e8c27ec8Sbaban 		 * using well-known SIDs table and name_cache before trying
3872e8c27ec8Sbaban 		 * AD.
3873e8c27ec8Sbaban 		 */
3874e8c27ec8Sbaban 		if (mapping->id2name != NULL) {
3875e8c27ec8Sbaban 			canonname = NULL;
3876e8c27ec8Sbaban 			is_wuser = -1;
3877e8c27ec8Sbaban 			retcode = lookup_name2sid(cache, mapping->id2name,
3878e8c27ec8Sbaban 			    mapping->id2domain, &is_wuser, &canonname,
3879e8c27ec8Sbaban 			    &idres.id.idmap_id_u.sid.prefix,
3880e8c27ec8Sbaban 			    &idres.id.idmap_id_u.sid.rid, mapping);
3881e8c27ec8Sbaban 			if (canonname != NULL) {
3882e8c27ec8Sbaban 				free(mapping->id2name);
3883e8c27ec8Sbaban 				mapping->id2name = canonname;
3884c5c4113dSnw141292 			}
3885e8c27ec8Sbaban 			if (retcode == IDMAP_SUCCESS)
3886e8c27ec8Sbaban 				idres.id.idtype = is_wuser ? IDMAP_USID :
3887e8c27ec8Sbaban 				    IDMAP_GSID;
3888e8c27ec8Sbaban 			idres.retcode = retcode;
3889c5c4113dSnw141292 		}
3890e8c27ec8Sbaban 	} else if (state.ad_nqueries > 0) {
3891e8c27ec8Sbaban 		/*
3892e8c27ec8Sbaban 		 * This means AD-based name mapping is enabled.
3893e8c27ec8Sbaban 		 * Lookup AD by unixname to get winname and sid.
3894e8c27ec8Sbaban 		 * Ignore non-fatal errors in which case we simply fallback
3895e8c27ec8Sbaban 		 * to local name based mapping rules.
3896e8c27ec8Sbaban 		 */
3897e8c27ec8Sbaban 		retcode = ad_lookup(&state, mapping, &idres, 0, 0, 1);
3898e8c27ec8Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
3899e8c27ec8Sbaban 			goto out;
3900e8c27ec8Sbaban 		idres.retcode = IDMAP_SUCCESS;
3901c5c4113dSnw141292 	}
3902c5c4113dSnw141292 
3903e8c27ec8Sbaban 	/*
3904e8c27ec8Sbaban 	 * Next pass processes the result of the preceding passes/lookups.
3905e8c27ec8Sbaban 	 * It returns if there's nothing more to be done otherwise it
3906e8c27ec8Sbaban 	 * evaluates local name-based mapping rules
3907e8c27ec8Sbaban 	 */
3908c5c4113dSnw141292 	state.pid2sid_done = TRUE;
3909e8c27ec8Sbaban 	retcode = pid2sid_second_pass(&state, cache, db, mapping, &idres,
3910e8c27ec8Sbaban 	    is_user);
3911c5c4113dSnw141292 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
3912c5c4113dSnw141292 		goto out;
3913c5c4113dSnw141292 
3914c5c4113dSnw141292 	/* Update cache */
3915c5c4113dSnw141292 	(void) update_cache_pid2sid(&state, cache, mapping, &idres);
3916c5c4113dSnw141292 
3917c5c4113dSnw141292 out:
3918e8c27ec8Sbaban 	/*
3919e8c27ec8Sbaban 	 * Note that "mapping" is returned to the client. Therefore
3920e8c27ec8Sbaban 	 * copy whatever we have in "idres" to mapping->id2 and
3921e8c27ec8Sbaban 	 * free idres.
3922e8c27ec8Sbaban 	 */
3923c5c4113dSnw141292 	mapping->direction = idres.direction;
3924c5c4113dSnw141292 	mapping->id2 = idres.id;
3925c5c4113dSnw141292 	(void) memset(&idres, 0, sizeof (idres));
3926c5c4113dSnw141292 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
3927e8c27ec8Sbaban 	cleanup_lookup_state(&state);
3928e8c27ec8Sbaban 	return (retcode);
3929e8c27ec8Sbaban }
3930e8c27ec8Sbaban 
3931e8c27ec8Sbaban static
3932e8c27ec8Sbaban idmap_retcode
3933e8c27ec8Sbaban ad_lookup_by_unixname(lookup_state_t *state,
3934e8c27ec8Sbaban 		const char *unixname, int is_user, int is_wuser,
3935e8c27ec8Sbaban 		char **sidprefix, idmap_rid_t *rid, char **winname,
3936e8c27ec8Sbaban 		char **domain, int *type)
3937e8c27ec8Sbaban {
3938e8c27ec8Sbaban 	/* Lookup AD by unixname */
3939e8c27ec8Sbaban 	int			retries = 0;
3940e8c27ec8Sbaban 	idmap_query_state_t	*qs = NULL;
3941e8c27ec8Sbaban 	idmap_retcode		rc, retcode;
3942e8c27ec8Sbaban 
3943e8c27ec8Sbaban retry:
3944e8c27ec8Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, 1, &qs);
3945e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
39460dcc7149Snw141292 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
39470dcc7149Snw141292 			goto retry;
3948*349d5d8fSnw141292 		degrade_svc(1, "failed to create request for AD lookup "
39490dcc7149Snw141292 		    "by unixname");
3950e8c27ec8Sbaban 		return (IDMAP_ERR_INTERNAL);
3951e8c27ec8Sbaban 	}
3952e8c27ec8Sbaban 
3953e8c27ec8Sbaban 	restore_svc();
3954e8c27ec8Sbaban 
3955e8c27ec8Sbaban 	if (state != NULL)
3956e8c27ec8Sbaban 		idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
3957e8c27ec8Sbaban 		    state->ad_unixgroup_attr);
3958e8c27ec8Sbaban 
3959e8c27ec8Sbaban 	retcode = idmap_unixname2sid_batch_add1(qs, unixname, is_user,
3960e8c27ec8Sbaban 	    is_wuser, sidprefix, rid, winname, domain, type, &rc);
3961e8c27ec8Sbaban 
3962e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS)
3963e8c27ec8Sbaban 		idmap_lookup_release_batch(&qs);
3964e8c27ec8Sbaban 	else
39650dcc7149Snw141292 		retcode = idmap_lookup_batch_end(&qs);
3966e8c27ec8Sbaban 
3967e8c27ec8Sbaban 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
3968e8c27ec8Sbaban 		goto retry;
3969e8c27ec8Sbaban 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
3970*349d5d8fSnw141292 		degrade_svc(1, "some AD lookups timed out repeatedly");
3971e8c27ec8Sbaban 
3972e8c27ec8Sbaban 	if (retcode != IDMAP_SUCCESS) {
3973e8c27ec8Sbaban 		idmapdlog(LOG_NOTICE, "AD lookup by unixname failed");
3974e8c27ec8Sbaban 		return (retcode);
3975e8c27ec8Sbaban 	}
3976e8c27ec8Sbaban 	return (rc);
3977e8c27ec8Sbaban }
3978e8c27ec8Sbaban 
3979e8c27ec8Sbaban /*
3980e8c27ec8Sbaban  * This function is called whenever a non-batched AD lookup needs to be
3981e8c27ec8Sbaban  * done (e.g. get_w2u_mapping() and get_u2w_mapping()). It's already
3982e8c27ec8Sbaban  * determined by the caller before calling this function that AD lookup is
3983e8c27ec8Sbaban  * needed and has already searched the well-known SIDs table and name_cache.
3984e8c27ec8Sbaban  */
3985e8c27ec8Sbaban static
3986e8c27ec8Sbaban idmap_retcode
3987e8c27ec8Sbaban ad_lookup(lookup_state_t *state, idmap_mapping *req, idmap_id_res *res,
3988e8c27ec8Sbaban 		int w2u, int getunixattr, int byunixattr)
3989e8c27ec8Sbaban {
3990e8c27ec8Sbaban 	idmap_retcode	retcode;
3991e8c27ec8Sbaban 	int		type, eunixtype, is_user, is_wuser;
3992e8c27ec8Sbaban 	char		*canonname = NULL;
3993e8c27ec8Sbaban 
3994e8c27ec8Sbaban 	if (w2u) {
3995e8c27ec8Sbaban 		/*
3996e8c27ec8Sbaban 		 * win2unix lookup requests (get_w2u_mapping()) calls this
3997e8c27ec8Sbaban 		 * function to lookup by sid OR winname and to retrieve
3998e8c27ec8Sbaban 		 * SID, winname, sidtype (user or group) and unixnames
3999e8c27ec8Sbaban 		 * from AD.
4000e8c27ec8Sbaban 		 */
4001e8c27ec8Sbaban 
4002e8c27ec8Sbaban 		/* Set the expected unixtype */
4003e8c27ec8Sbaban 		if (res->id.idtype == IDMAP_UID)
4004e8c27ec8Sbaban 			eunixtype = _IDMAP_T_USER;
4005e8c27ec8Sbaban 		else if (res->id.idtype == IDMAP_GID)
4006e8c27ec8Sbaban 			eunixtype = _IDMAP_T_GROUP;
4007e8c27ec8Sbaban 		else
4008e8c27ec8Sbaban 			eunixtype = _IDMAP_T_UNDEF;
4009e8c27ec8Sbaban 
4010e8c27ec8Sbaban 		if (req->id1.idmap_id_u.sid.prefix != NULL) {
4011e8c27ec8Sbaban 			/* AD lookup by sid */
4012e8c27ec8Sbaban 			retcode = ad_lookup_by_sid(
4013e8c27ec8Sbaban 			    state, req->id1.idmap_id_u.sid.prefix,
4014e8c27ec8Sbaban 			    req->id1.idmap_id_u.sid.rid, eunixtype,
4015e8c27ec8Sbaban 			    (req->id1name == NULL) ? &req->id1name : NULL,
4016e8c27ec8Sbaban 			    (req->id1domain == NULL) ? &req->id1domain : NULL,
4017e8c27ec8Sbaban 			    &type, (getunixattr && req->id2name == NULL)
4018e8c27ec8Sbaban 			    ? &req->id2name : NULL);
4019e8c27ec8Sbaban 		} else {
4020e8c27ec8Sbaban 			assert(req->id1name != NULL);
4021e8c27ec8Sbaban 			/* AD lookup by winname */
4022e8c27ec8Sbaban 			retcode = ad_lookup_by_winname(
4023e8c27ec8Sbaban 			    state, req->id1name, req->id1domain, eunixtype,
4024e8c27ec8Sbaban 			    &canonname, &req->id1.idmap_id_u.sid.prefix,
4025e8c27ec8Sbaban 			    &req->id1.idmap_id_u.sid.rid, &type,
4026e8c27ec8Sbaban 			    (getunixattr && req->id2name == NULL)
4027e8c27ec8Sbaban 			    ? &req->id2name : NULL);
4028e8c27ec8Sbaban 
4029e8c27ec8Sbaban 			if (canonname != NULL) {
4030e8c27ec8Sbaban 				free(req->id1name);
4031e8c27ec8Sbaban 				req->id1name = canonname;
4032e8c27ec8Sbaban 			}
4033e8c27ec8Sbaban 		}
4034e8c27ec8Sbaban 		if (retcode == IDMAP_SUCCESS) {
4035e8c27ec8Sbaban 			switch (type) {
4036e8c27ec8Sbaban 			case _IDMAP_T_USER:
4037e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
4038e8c27ec8Sbaban 					res->id.idtype = IDMAP_UID;
4039e8c27ec8Sbaban 				req->id1.idtype = IDMAP_USID;
4040e8c27ec8Sbaban 				break;
4041e8c27ec8Sbaban 			case _IDMAP_T_GROUP:
4042e8c27ec8Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
4043e8c27ec8Sbaban 					res->id.idtype = IDMAP_GID;
4044e8c27ec8Sbaban 				req->id1.idtype = IDMAP_GSID;
4045e8c27ec8Sbaban 				break;
4046e8c27ec8Sbaban 			default:
4047e8c27ec8Sbaban 				return (IDMAP_ERR_SID);
4048e8c27ec8Sbaban 			}
4049e8c27ec8Sbaban 		}
4050e8c27ec8Sbaban 		return (retcode);
4051e8c27ec8Sbaban 	}
4052e8c27ec8Sbaban 
4053e8c27ec8Sbaban 	/*
4054e8c27ec8Sbaban 	 * unix2win lookup requests (get_u2w_mapping()) calls this
4055e8c27ec8Sbaban 	 * function to lookup AD by unixname and to retrieve
4056e8c27ec8Sbaban 	 * SID, winname, and sidtype (user or group) from AD.
4057e8c27ec8Sbaban 	 */
4058e8c27ec8Sbaban 
4059e8c27ec8Sbaban 	/* Set the expected unixtype */
4060e8c27ec8Sbaban 	eunixtype = (req->id1.idtype == IDMAP_UID) ? _IDMAP_T_USER :
4061e8c27ec8Sbaban 	    _IDMAP_T_GROUP;
4062e8c27ec8Sbaban 
4063e8c27ec8Sbaban 	if (byunixattr) {
4064e8c27ec8Sbaban 		/* AD lookup by unixname */
4065e8c27ec8Sbaban 		is_user = (IS_REQUEST_UID(*req)) ? 1 : 0;
4066e8c27ec8Sbaban 		if (res->id.idtype == IDMAP_USID)
4067e8c27ec8Sbaban 			is_wuser = 1;
4068e8c27ec8Sbaban 		else if (res->id.idtype == IDMAP_GSID)
4069e8c27ec8Sbaban 			is_wuser = 0;
4070e8c27ec8Sbaban 		else
4071e8c27ec8Sbaban 			is_wuser = is_user;
4072e8c27ec8Sbaban 		retcode = ad_lookup_by_unixname(
4073e8c27ec8Sbaban 		    state, req->id1name, is_user, is_wuser,
4074e8c27ec8Sbaban 		    (res->id.idmap_id_u.sid.prefix == NULL) ?
4075e8c27ec8Sbaban 		    &res->id.idmap_id_u.sid.prefix : NULL,
4076e8c27ec8Sbaban 		    (res->id.idmap_id_u.sid.prefix == NULL) ?
4077e8c27ec8Sbaban 		    &res->id.idmap_id_u.sid.rid : NULL,
4078e8c27ec8Sbaban 		    (req->id2name == NULL) ? &req->id2name : NULL,
4079e8c27ec8Sbaban 		    (req->id2domain == NULL) ? &req->id2domain : NULL, NULL);
4080e8c27ec8Sbaban 	} else if (res->id.idmap_id_u.sid.prefix != NULL) {
4081e8c27ec8Sbaban 		/* AD lookup by sid */
4082e8c27ec8Sbaban 		retcode = ad_lookup_by_sid(
4083e8c27ec8Sbaban 		    state, res->id.idmap_id_u.sid.prefix,
4084e8c27ec8Sbaban 		    res->id.idmap_id_u.sid.rid, eunixtype,
4085e8c27ec8Sbaban 		    (req->id2name == NULL) ? &req->id2name : NULL,
4086e8c27ec8Sbaban 		    (req->id2domain == NULL) ? &req->id2domain : NULL,
4087e8c27ec8Sbaban 		    NULL, (getunixattr && req->id1name == NULL)
4088e8c27ec8Sbaban 		    ? &req->id1name : NULL);
4089e8c27ec8Sbaban 	} else {
4090e8c27ec8Sbaban 		/* AD lookup by winname */
4091e8c27ec8Sbaban 		assert(req->id2name != NULL);
4092e8c27ec8Sbaban 		retcode = ad_lookup_by_winname(
4093e8c27ec8Sbaban 		    state, req->id2name, req->id2domain, eunixtype,
4094e8c27ec8Sbaban 		    &canonname, &res->id.idmap_id_u.sid.prefix,
4095e8c27ec8Sbaban 		    &res->id.idmap_id_u.sid.rid, NULL,
4096e8c27ec8Sbaban 		    (getunixattr && req->id1name == NULL)
4097e8c27ec8Sbaban 		    ? &req->id1name : NULL);
4098e8c27ec8Sbaban 
4099e8c27ec8Sbaban 		if (canonname != NULL) {
4100e8c27ec8Sbaban 			free(req->id2name);
4101e8c27ec8Sbaban 			req->id2name = canonname;
4102e8c27ec8Sbaban 		}
4103e8c27ec8Sbaban 	}
4104e8c27ec8Sbaban 
4105e8c27ec8Sbaban 	if (retcode == IDMAP_SUCCESS) {
4106e8c27ec8Sbaban 		switch (type) {
4107e8c27ec8Sbaban 		case _IDMAP_T_USER:
4108e8c27ec8Sbaban 			if (res->id.idtype == IDMAP_SID)
4109e8c27ec8Sbaban 				res->id.idtype = IDMAP_USID;
4110e8c27ec8Sbaban 			break;
4111e8c27ec8Sbaban 		case _IDMAP_T_GROUP:
4112e8c27ec8Sbaban 			if (res->id.idtype == IDMAP_SID)
4113e8c27ec8Sbaban 				res->id.idtype = IDMAP_GSID;
4114e8c27ec8Sbaban 			break;
4115e8c27ec8Sbaban 		default:
4116e8c27ec8Sbaban 			return (IDMAP_ERR_SID);
4117e8c27ec8Sbaban 		}
4118e8c27ec8Sbaban 	}
4119c5c4113dSnw141292 	return (retcode);
4120c5c4113dSnw141292 }
4121