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