xref: /onnv-gate/usr/src/cmd/idmap/idmapd/dbutils.c (revision 7818:905d0a87b27b)
14520Snw141292 /*
24520Snw141292  * CDDL HEADER START
34520Snw141292  *
44520Snw141292  * The contents of this file are subject to the terms of the
54520Snw141292  * Common Development and Distribution License (the "License").
64520Snw141292  * You may not use this file except in compliance with the License.
74520Snw141292  *
84520Snw141292  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
94520Snw141292  * or http://www.opensolaris.org/os/licensing.
104520Snw141292  * See the License for the specific language governing permissions
114520Snw141292  * and limitations under the License.
124520Snw141292  *
134520Snw141292  * When distributing Covered Code, include this CDDL HEADER in each
144520Snw141292  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
154520Snw141292  * If applicable, add the following below this CDDL HEADER, with the
164520Snw141292  * fields enclosed by brackets "[]" replaced with your own identifying
174520Snw141292  * information: Portions Copyright [yyyy] [name of copyright owner]
184520Snw141292  *
194520Snw141292  * CDDL HEADER END
204520Snw141292  */
214520Snw141292 /*
225932Sbaban  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
234520Snw141292  * Use is subject to license terms.
244520Snw141292  */
254520Snw141292 
264520Snw141292 /*
274520Snw141292  * Database related utility routines
284520Snw141292  */
294520Snw141292 
304520Snw141292 #include <stdio.h>
314520Snw141292 #include <stdlib.h>
324520Snw141292 #include <string.h>
334520Snw141292 #include <errno.h>
344520Snw141292 #include <sys/types.h>
354520Snw141292 #include <sys/stat.h>
364520Snw141292 #include <rpc/rpc.h>
374520Snw141292 #include <sys/sid.h>
384520Snw141292 #include <time.h>
394520Snw141292 #include <pwd.h>
404520Snw141292 #include <grp.h>
414884Sjp151216 #include <pthread.h>
424884Sjp151216 #include <assert.h>
435696Snw141292 #include <sys/u8_textprep.h>
444520Snw141292 
454520Snw141292 #include "idmapd.h"
464520Snw141292 #include "adutils.h"
474520Snw141292 #include "string.h"
484520Snw141292 #include "idmap_priv.h"
495696Snw141292 #include "schema.h"
505731Sbaban #include "nldaputils.h"
514520Snw141292 
524884Sjp151216 
534520Snw141292 static idmap_retcode sql_compile_n_step_once(sqlite *, char *,
544520Snw141292 		sqlite_vm **, int *, int, const char ***);
556616Sdm199847 static idmap_retcode ad_lookup_one(lookup_state_t *, idmap_mapping *,
566616Sdm199847 		idmap_id_res *);
575731Sbaban static idmap_retcode lookup_localsid2pid(idmap_mapping *, idmap_id_res *);
585731Sbaban static idmap_retcode lookup_cache_name2sid(sqlite *, const char *,
595731Sbaban 		const char *, char **, char **, idmap_rid_t *, int *);
605731Sbaban 
614520Snw141292 
624520Snw141292 #define	EMPTY_NAME(name)	(*name == 0 || strcmp(name, "\"\"") == 0)
634520Snw141292 
644520Snw141292 #define	DO_NOT_ALLOC_NEW_ID_MAPPING(req)\
654520Snw141292 		(req->flag & IDMAP_REQ_FLG_NO_NEW_ID_ALLOC)
664520Snw141292 
674520Snw141292 #define	AVOID_NAMESERVICE(req)\
684520Snw141292 		(req->flag & IDMAP_REQ_FLG_NO_NAMESERVICE)
694520Snw141292 
705731Sbaban #define	IS_EPHEMERAL(pid)	(pid > INT32_MAX && pid != SENTINEL_PID)
714520Snw141292 
724520Snw141292 #define	LOCALRID_MIN	1000
734520Snw141292 
744520Snw141292 
754520Snw141292 typedef enum init_db_option {
764520Snw141292 	FAIL_IF_CORRUPT = 0,
774520Snw141292 	REMOVE_IF_CORRUPT = 1
784520Snw141292 } init_db_option_t;
794520Snw141292 
804884Sjp151216 /*
815731Sbaban  * Data structure to store well-known SIDs and
825731Sbaban  * associated mappings (if any)
835731Sbaban  */
845731Sbaban typedef struct wksids_table {
855731Sbaban 	const char	*sidprefix;
865731Sbaban 	uint32_t	rid;
875731Sbaban 	const char	*winname;
885731Sbaban 	int		is_wuser;
895731Sbaban 	uid_t		pid;
905731Sbaban 	int		is_user;
915731Sbaban 	int		direction;
925731Sbaban } wksids_table_t;
935731Sbaban 
945731Sbaban /*
954884Sjp151216  * Thread specfic data to hold the database handles so that the
964884Sjp151216  * databaes are not opened and closed for every request. It also
974884Sjp151216  * contains the sqlite busy handler structure.
984884Sjp151216  */
994884Sjp151216 
1004884Sjp151216 struct idmap_busy {
1014884Sjp151216 	const char *name;
1024884Sjp151216 	const int *delays;
1034884Sjp151216 	int delay_size;
1044884Sjp151216 	int total;
1054884Sjp151216 	int sec;
1064884Sjp151216 };
1074884Sjp151216 
1084884Sjp151216 
1094884Sjp151216 typedef struct idmap_tsd {
1104884Sjp151216 	sqlite *db_db;
1114884Sjp151216 	sqlite *cache_db;
1124884Sjp151216 	struct idmap_busy cache_busy;
1134884Sjp151216 	struct idmap_busy db_busy;
1144884Sjp151216 } idmap_tsd_t;
1154884Sjp151216 
1164884Sjp151216 
1174884Sjp151216 
1184884Sjp151216 static const int cache_delay_table[] =
1194884Sjp151216 		{ 1, 2, 5, 10, 15, 20, 25, 30,  35,  40,
1204884Sjp151216 		50,  50, 60, 70, 80, 90, 100};
1214884Sjp151216 
1224884Sjp151216 static const int db_delay_table[] =
1234884Sjp151216 		{ 5, 10, 15, 20, 30,  40,  55,  70, 100};
1244884Sjp151216 
1254884Sjp151216 
1264884Sjp151216 static pthread_key_t	idmap_tsd_key;
1274884Sjp151216 
1284884Sjp151216 void
1294884Sjp151216 idmap_tsd_destroy(void *key)
1304884Sjp151216 {
1314884Sjp151216 
1324884Sjp151216 	idmap_tsd_t	*tsd = (idmap_tsd_t *)key;
1334884Sjp151216 	if (tsd) {
1344884Sjp151216 		if (tsd->db_db)
1354884Sjp151216 			(void) sqlite_close(tsd->db_db);
1364884Sjp151216 		if (tsd->cache_db)
1374884Sjp151216 			(void) sqlite_close(tsd->cache_db);
1384884Sjp151216 		free(tsd);
1394884Sjp151216 	}
1404884Sjp151216 }
1414884Sjp151216 
1424884Sjp151216 int
1435696Snw141292 idmap_init_tsd_key(void)
1445696Snw141292 {
1454884Sjp151216 	return (pthread_key_create(&idmap_tsd_key, idmap_tsd_destroy));
1464884Sjp151216 }
1474884Sjp151216 
1484884Sjp151216 
1494884Sjp151216 
1504884Sjp151216 idmap_tsd_t *
1514884Sjp151216 idmap_get_tsd(void)
1524884Sjp151216 {
1534884Sjp151216 	idmap_tsd_t	*tsd;
1544884Sjp151216 
1554884Sjp151216 	if ((tsd = pthread_getspecific(idmap_tsd_key)) == NULL) {
1564884Sjp151216 		/* No thread specific data so create it */
1574884Sjp151216 		if ((tsd = malloc(sizeof (*tsd))) != NULL) {
1584884Sjp151216 			/* Initialize thread specific data */
1594884Sjp151216 			(void) memset(tsd, 0, sizeof (*tsd));
1604884Sjp151216 			/* save the trhread specific data */
1614884Sjp151216 			if (pthread_setspecific(idmap_tsd_key, tsd) != 0) {
1624884Sjp151216 				/* Can't store key */
1634884Sjp151216 				free(tsd);
1644884Sjp151216 				tsd = NULL;
1654884Sjp151216 			}
1664884Sjp151216 		} else {
1674884Sjp151216 			tsd = NULL;
1684884Sjp151216 		}
1694884Sjp151216 	}
1704884Sjp151216 
1714884Sjp151216 	return (tsd);
1724884Sjp151216 }
1734884Sjp151216 
1745696Snw141292 /*
1755696Snw141292  * A simple wrapper around u8_textprep_str() that returns the Unicode
1765696Snw141292  * lower-case version of some string.  The result must be freed.
1775696Snw141292  */
1785696Snw141292 char *
1795696Snw141292 tolower_u8(const char *s)
1805696Snw141292 {
1815696Snw141292 	char *res = NULL;
1825696Snw141292 	char *outs;
1835696Snw141292 	size_t inlen, outlen, inbytesleft, outbytesleft;
1845696Snw141292 	int rc, err;
1855696Snw141292 
1865696Snw141292 	/*
1875696Snw141292 	 * u8_textprep_str() does not allocate memory.  The input and
1885696Snw141292 	 * output buffers may differ in size (though that would be more
1895696Snw141292 	 * likely when normalization is done).  We have to loop over it...
1905696Snw141292 	 *
1915696Snw141292 	 * To improve the chances that we can avoid looping we add 10
1925696Snw141292 	 * bytes of output buffer room the first go around.
1935696Snw141292 	 */
1945696Snw141292 	inlen = inbytesleft = strlen(s);
1955696Snw141292 	outlen = outbytesleft = inlen + 10;
1965696Snw141292 	if ((res = malloc(outlen)) == NULL)
1975696Snw141292 		return (NULL);
1985696Snw141292 	outs = res;
1995696Snw141292 
2005696Snw141292 	while ((rc = u8_textprep_str((char *)s, &inbytesleft, outs,
2015696Snw141292 	    &outbytesleft, U8_TEXTPREP_TOLOWER, U8_UNICODE_LATEST, &err)) < 0 &&
2025696Snw141292 	    err == E2BIG) {
2035696Snw141292 		if ((res = realloc(res, outlen + inbytesleft)) == NULL)
2045696Snw141292 			return (NULL);
2055696Snw141292 		/* adjust input/output buffer pointers */
2065696Snw141292 		s += (inlen - inbytesleft);
2075696Snw141292 		outs = res + outlen - outbytesleft;
2085696Snw141292 		/* adjust outbytesleft and outlen */
2095696Snw141292 		outlen += inbytesleft;
2105696Snw141292 		outbytesleft += inbytesleft;
2115696Snw141292 	}
2125696Snw141292 
2135696Snw141292 	if (rc < 0) {
2145696Snw141292 		free(res);
2155696Snw141292 		res = NULL;
2165696Snw141292 		return (NULL);
2175696Snw141292 	}
2185696Snw141292 
2195696Snw141292 	res[outlen - outbytesleft] = '\0';
2205696Snw141292 
2215696Snw141292 	return (res);
2225696Snw141292 }
2235696Snw141292 
2245696Snw141292 static int sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
2255696Snw141292 	const char *while_doing);
2265696Snw141292 
2274520Snw141292 
2284520Snw141292 /*
2294520Snw141292  * Initialize 'dbname' using 'sql'
2304520Snw141292  */
2315696Snw141292 static
2325696Snw141292 int
2335696Snw141292 init_db_instance(const char *dbname, int version,
2345696Snw141292 	const char *detect_version_sql, char * const *sql,
2355696Snw141292 	init_db_option_t opt, int *created, int *upgraded)
2364520Snw141292 {
2375696Snw141292 	int rc, curr_version;
2385696Snw141292 	int tries = 1;
2395696Snw141292 	int prio = LOG_NOTICE;
2404520Snw141292 	sqlite *db = NULL;
2415696Snw141292 	char *errmsg = NULL;
2425696Snw141292 
2435696Snw141292 	*created = 0;
2445696Snw141292 	*upgraded = 0;
2455696Snw141292 
2465696Snw141292 	if (opt == REMOVE_IF_CORRUPT)
2475696Snw141292 		tries = 3;
2485696Snw141292 
2495696Snw141292 rinse_repeat:
2505696Snw141292 	if (tries == 0) {
2515696Snw141292 		idmapdlog(LOG_ERR, "Failed to initialize db %s", dbname);
2525696Snw141292 		return (-1);
2535696Snw141292 	}
2545696Snw141292 	if (tries-- == 1)
2555696Snw141292 		/* Last try, log errors */
2565696Snw141292 		prio = LOG_ERR;
2575696Snw141292 
2585696Snw141292 	db = sqlite_open(dbname, 0600, &errmsg);
2595696Snw141292 	if (db == NULL) {
2605696Snw141292 		idmapdlog(prio, "Error creating database %s (%s)",
2615696Snw141292 		    dbname, CHECK_NULL(errmsg));
2625696Snw141292 		sqlite_freemem(errmsg);
2635696Snw141292 		if (opt == REMOVE_IF_CORRUPT)
2645696Snw141292 			(void) unlink(dbname);
2655696Snw141292 		goto rinse_repeat;
2664520Snw141292 	}
2674520Snw141292 
2684520Snw141292 	sqlite_busy_timeout(db, 3000);
2695696Snw141292 
2705696Snw141292 	/* Detect current version of schema in the db, if any */
2715696Snw141292 	curr_version = 0;
2725696Snw141292 	if (detect_version_sql != NULL) {
2735696Snw141292 		char *end, **results;
2745696Snw141292 		int nrow;
2755696Snw141292 
2765696Snw141292 #ifdef	IDMAPD_DEBUG
2775696Snw141292 		(void) fprintf(stderr, "Schema version detection SQL: %s\n",
2785696Snw141292 		    detect_version_sql);
2795696Snw141292 #endif	/* IDMAPD_DEBUG */
2805696Snw141292 		rc = sqlite_get_table(db, detect_version_sql, &results,
2815696Snw141292 		    &nrow, NULL, &errmsg);
2825696Snw141292 		if (rc != SQLITE_OK) {
2835696Snw141292 			idmapdlog(prio,
2845696Snw141292 			    "Error detecting schema version of db %s (%s)",
2855696Snw141292 			    dbname, errmsg);
2865696Snw141292 			sqlite_freemem(errmsg);
2875696Snw141292 			sqlite_free_table(results);
2885696Snw141292 			sqlite_close(db);
2895696Snw141292 			return (-1);
2905696Snw141292 		}
2915696Snw141292 		if (nrow != 1) {
2925696Snw141292 			idmapdlog(prio,
2935696Snw141292 			    "Error detecting schema version of db %s", dbname);
2945696Snw141292 			sqlite_close(db);
2955696Snw141292 			sqlite_free_table(results);
2965696Snw141292 			return (-1);
2975696Snw141292 		}
2985696Snw141292 		curr_version = strtol(results[1], &end, 10);
2995696Snw141292 		sqlite_free_table(results);
3004520Snw141292 	}
3014520Snw141292 
3025696Snw141292 	if (curr_version < 0) {
3035696Snw141292 		if (opt == REMOVE_IF_CORRUPT)
3045696Snw141292 			(void) unlink(dbname);
3055696Snw141292 		goto rinse_repeat;
3064520Snw141292 	}
3074520Snw141292 
3085696Snw141292 	if (curr_version == version)
3095696Snw141292 		goto done;
3105696Snw141292 
3115696Snw141292 	/* Install or upgrade schema */
3125696Snw141292 #ifdef	IDMAPD_DEBUG
3135696Snw141292 	(void) fprintf(stderr, "Schema init/upgrade SQL: %s\n",
3145696Snw141292 	    sql[curr_version]);
3155696Snw141292 #endif	/* IDMAPD_DEBUG */
3165696Snw141292 	rc = sql_exec_tran_no_cb(db, sql[curr_version], dbname,
3175696Snw141292 	    (curr_version == 0) ? "installing schema" : "upgrading schema");
3185696Snw141292 	if (rc != 0) {
3195696Snw141292 		idmapdlog(prio, "Error %s schema for db %s", dbname,
3205696Snw141292 		    (curr_version == 0) ? "installing schema" :
3215696Snw141292 		    "upgrading schema");
3225696Snw141292 		if (opt == REMOVE_IF_CORRUPT)
3235696Snw141292 			(void) unlink(dbname);
3245696Snw141292 		goto rinse_repeat;
3254520Snw141292 	}
3264520Snw141292 
3275696Snw141292 	*upgraded = (curr_version > 0);
3285696Snw141292 	*created = (curr_version == 0);
3295696Snw141292 
3305696Snw141292 done:
3314520Snw141292 	(void) sqlite_close(db);
3325696Snw141292 	return (0);
3334520Snw141292 }
3344520Snw141292 
3354884Sjp151216 
3364884Sjp151216 /*
3374884Sjp151216  * This is the SQLite database busy handler that retries the SQL
3384884Sjp151216  * operation until it is successful.
3394884Sjp151216  */
3404884Sjp151216 int
3414884Sjp151216 /* LINTED E_FUNC_ARG_UNUSED */
3424884Sjp151216 idmap_sqlite_busy_handler(void *arg, const char *table_name, int count)
3434884Sjp151216 {
3444884Sjp151216 	struct idmap_busy	*busy = arg;
3454884Sjp151216 	int			delay;
3464884Sjp151216 	struct timespec		rqtp;
3474884Sjp151216 
3484884Sjp151216 	if (count == 1)  {
3494884Sjp151216 		busy->total = 0;
3504884Sjp151216 		busy->sec = 2;
3514884Sjp151216 	}
3524884Sjp151216 	if (busy->total > 1000 * busy->sec) {
3536414Sjp151216 		idmapdlog(LOG_DEBUG,
3544884Sjp151216 		    "Thread %d waited %d sec for the %s database",
3554884Sjp151216 		    pthread_self(), busy->sec, busy->name);
3564884Sjp151216 		busy->sec++;
3574884Sjp151216 	}
3584884Sjp151216 
3594884Sjp151216 	if (count <= busy->delay_size) {
3604884Sjp151216 		delay = busy->delays[count-1];
3614884Sjp151216 	} else {
3624884Sjp151216 		delay = busy->delays[busy->delay_size - 1];
3634884Sjp151216 	}
3644884Sjp151216 	busy->total += delay;
3654884Sjp151216 	rqtp.tv_sec = 0;
3664884Sjp151216 	rqtp.tv_nsec = delay * (NANOSEC / MILLISEC);
3674884Sjp151216 	(void) nanosleep(&rqtp, NULL);
3684884Sjp151216 	return (1);
3694884Sjp151216 }
3704884Sjp151216 
3714884Sjp151216 
3724520Snw141292 /*
3734520Snw141292  * Get the database handle
3744520Snw141292  */
3754520Snw141292 idmap_retcode
3765696Snw141292 get_db_handle(sqlite **db)
3775696Snw141292 {
3785696Snw141292 	char		*errmsg;
3795696Snw141292 	idmap_tsd_t	*tsd;
3804520Snw141292 
3814520Snw141292 	/*
3824884Sjp151216 	 * Retrieve the db handle from thread-specific storage
3834520Snw141292 	 * If none exists, open and store in thread-specific storage.
3844520Snw141292 	 */
3854884Sjp151216 	if ((tsd = idmap_get_tsd()) == NULL) {
3864520Snw141292 		idmapdlog(LOG_ERR,
3875696Snw141292 		    "Error getting thread specific data for %s", IDMAP_DBNAME);
3884884Sjp151216 		return (IDMAP_ERR_MEMORY);
3894520Snw141292 	}
3904884Sjp151216 
3914884Sjp151216 	if (tsd->db_db == NULL) {
3924884Sjp151216 		tsd->db_db = sqlite_open(IDMAP_DBNAME, 0, &errmsg);
3934884Sjp151216 		if (tsd->db_db == NULL) {
3945696Snw141292 			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
3955696Snw141292 			    IDMAP_DBNAME, CHECK_NULL(errmsg));
3964884Sjp151216 			sqlite_freemem(errmsg);
3975696Snw141292 			return (IDMAP_ERR_DB);
3984884Sjp151216 		}
3995696Snw141292 
4004884Sjp151216 		tsd->db_busy.name = IDMAP_DBNAME;
4014884Sjp151216 		tsd->db_busy.delays = db_delay_table;
4024884Sjp151216 		tsd->db_busy.delay_size = sizeof (db_delay_table) /
4034884Sjp151216 		    sizeof (int);
4044884Sjp151216 		sqlite_busy_handler(tsd->db_db, idmap_sqlite_busy_handler,
4054884Sjp151216 		    &tsd->db_busy);
4064884Sjp151216 	}
4074884Sjp151216 	*db = tsd->db_db;
4084520Snw141292 	return (IDMAP_SUCCESS);
4094520Snw141292 }
4104520Snw141292 
4114520Snw141292 /*
4124520Snw141292  * Get the cache handle
4134520Snw141292  */
4144520Snw141292 idmap_retcode
4155696Snw141292 get_cache_handle(sqlite **cache)
4165696Snw141292 {
4175696Snw141292 	char		*errmsg;
4185696Snw141292 	idmap_tsd_t	*tsd;
4194520Snw141292 
4204520Snw141292 	/*
4214884Sjp151216 	 * Retrieve the db handle from thread-specific storage
4224520Snw141292 	 * If none exists, open and store in thread-specific storage.
4234520Snw141292 	 */
4244884Sjp151216 	if ((tsd = idmap_get_tsd()) == NULL) {
4255696Snw141292 		idmapdlog(LOG_ERR, "Error getting thread specific data for %s",
4265696Snw141292 		    IDMAP_DBNAME);
4274884Sjp151216 		return (IDMAP_ERR_MEMORY);
4284520Snw141292 	}
4294884Sjp151216 
4304884Sjp151216 	if (tsd->cache_db == NULL) {
4314884Sjp151216 		tsd->cache_db = sqlite_open(IDMAP_CACHENAME, 0, &errmsg);
4324884Sjp151216 		if (tsd->cache_db == NULL) {
4335696Snw141292 			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
4345696Snw141292 			    IDMAP_CACHENAME, CHECK_NULL(errmsg));
4354884Sjp151216 			sqlite_freemem(errmsg);
4365696Snw141292 			return (IDMAP_ERR_DB);
4374884Sjp151216 		}
4385696Snw141292 
4394884Sjp151216 		tsd->cache_busy.name = IDMAP_CACHENAME;
4404884Sjp151216 		tsd->cache_busy.delays = cache_delay_table;
4414884Sjp151216 		tsd->cache_busy.delay_size = sizeof (cache_delay_table) /
4424884Sjp151216 		    sizeof (int);
4434884Sjp151216 		sqlite_busy_handler(tsd->cache_db, idmap_sqlite_busy_handler,
4444884Sjp151216 		    &tsd->cache_busy);
4454884Sjp151216 	}
4464884Sjp151216 	*cache = tsd->cache_db;
4474520Snw141292 	return (IDMAP_SUCCESS);
4484520Snw141292 }
4494520Snw141292 
4504520Snw141292 /*
4514520Snw141292  * Initialize cache and db
4524520Snw141292  */
4534520Snw141292 int
4545696Snw141292 init_dbs()
4555696Snw141292 {
4566386Sjp151216 	char *sql[4];
4575696Snw141292 	int created, upgraded;
4585696Snw141292 
4594520Snw141292 	/* name-based mappings; probably OK to blow away in a pinch(?) */
4605696Snw141292 	sql[0] = DB_INSTALL_SQL;
4615696Snw141292 	sql[1] = DB_UPGRADE_FROM_v1_SQL;
4626386Sjp151216 	sql[2] = NULL;
4635696Snw141292 
4645696Snw141292 	if (init_db_instance(IDMAP_DBNAME, DB_VERSION, DB_VERSION_SQL, sql,
4655696Snw141292 	    FAIL_IF_CORRUPT, &created, &upgraded) < 0)
4664520Snw141292 		return (-1);
4674520Snw141292 
4684520Snw141292 	/* mappings, name/SID lookup cache + ephemeral IDs; OK to blow away */
4695696Snw141292 	sql[0] = CACHE_INSTALL_SQL;
4705696Snw141292 	sql[1] = CACHE_UPGRADE_FROM_v1_SQL;
4716386Sjp151216 	sql[2] = CACHE_UPGRADE_FROM_v2_SQL;
4726386Sjp151216 	sql[3] = NULL;
4736386Sjp151216 
4745696Snw141292 	if (init_db_instance(IDMAP_CACHENAME, CACHE_VERSION, CACHE_VERSION_SQL,
4755696Snw141292 	    sql, REMOVE_IF_CORRUPT, &created, &upgraded) < 0)
4764520Snw141292 		return (-1);
4774520Snw141292 
4785696Snw141292 	_idmapdstate.new_eph_db = (created || upgraded) ? 1 : 0;
4795696Snw141292 
4804520Snw141292 	return (0);
4814520Snw141292 }
4824520Snw141292 
4834520Snw141292 /*
4844520Snw141292  * Finalize databases
4854520Snw141292  */
4864520Snw141292 void
4875696Snw141292 fini_dbs()
4885696Snw141292 {
4894520Snw141292 }
4904520Snw141292 
4914520Snw141292 /*
4925731Sbaban  * This table is a listing of status codes that will be returned to the
4934520Snw141292  * client when a SQL command fails with the corresponding error message.
4944520Snw141292  */
4954520Snw141292 static msg_table_t sqlmsgtable[] = {
4964864Sbaban 	{IDMAP_ERR_U2W_NAMERULE_CONFLICT,
4974520Snw141292 	"columns unixname, is_user, u2w_order are not unique"},
4984864Sbaban 	{IDMAP_ERR_W2U_NAMERULE_CONFLICT,
4995696Snw141292 	"columns winname, windomain, is_user, is_wuser, w2u_order are not"
5005696Snw141292 	" unique"},
5015696Snw141292 	{IDMAP_ERR_W2U_NAMERULE_CONFLICT, "Conflicting w2u namerules"},
5024520Snw141292 	{-1, NULL}
5034520Snw141292 };
5044520Snw141292 
5054520Snw141292 /*
5064520Snw141292  * idmapd's version of string2stat to map SQLite messages to
5074520Snw141292  * status codes
5084520Snw141292  */
5094520Snw141292 idmap_retcode
5105696Snw141292 idmapd_string2stat(const char *msg)
5115696Snw141292 {
5124520Snw141292 	int i;
5134520Snw141292 	for (i = 0; sqlmsgtable[i].msg; i++) {
5144520Snw141292 		if (strcasecmp(sqlmsgtable[i].msg, msg) == 0)
5154520Snw141292 			return (sqlmsgtable[i].retcode);
5164520Snw141292 	}
5174520Snw141292 	return (IDMAP_ERR_OTHER);
5184520Snw141292 }
5194520Snw141292 
5204520Snw141292 /*
5215696Snw141292  * Executes some SQL in a transaction.
5225696Snw141292  *
5235696Snw141292  * Returns 0 on success, -1 if it failed but the rollback succeeded, -2
5245696Snw141292  * if the rollback failed.
5255696Snw141292  */
5265696Snw141292 static
5275696Snw141292 int
5285696Snw141292 sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
5295696Snw141292 	const char *while_doing)
5305696Snw141292 {
5315696Snw141292 	char		*errmsg = NULL;
5325696Snw141292 	int		rc;
5335696Snw141292 
5345696Snw141292 	rc = sqlite_exec(db, "BEGIN TRANSACTION;", NULL, NULL, &errmsg);
5355696Snw141292 	if (rc != SQLITE_OK) {
5365696Snw141292 		idmapdlog(LOG_ERR, "Begin transaction failed (%s) "
5375696Snw141292 		    "while %s (%s)", errmsg, while_doing, dbname);
5385696Snw141292 		sqlite_freemem(errmsg);
5395696Snw141292 		return (-1);
5405696Snw141292 	}
5415696Snw141292 
5425696Snw141292 	rc = sqlite_exec(db, sql, NULL, NULL, &errmsg);
5435696Snw141292 	if (rc != SQLITE_OK) {
5445696Snw141292 		idmapdlog(LOG_ERR, "Database error (%s) while %s (%s)", errmsg,
5455696Snw141292 		    while_doing, dbname);
5465696Snw141292 		sqlite_freemem(errmsg);
5475696Snw141292 		errmsg = NULL;
5485696Snw141292 		goto rollback;
5495696Snw141292 	}
5505696Snw141292 
5515696Snw141292 	rc = sqlite_exec(db, "COMMIT TRANSACTION", NULL, NULL, &errmsg);
5525696Snw141292 	if (rc == SQLITE_OK) {
5535696Snw141292 		sqlite_freemem(errmsg);
5545696Snw141292 		return (0);
5555696Snw141292 	}
5565696Snw141292 
5575696Snw141292 	idmapdlog(LOG_ERR, "Database commit error (%s) while s (%s)",
5585696Snw141292 	    errmsg, while_doing, dbname);
5595696Snw141292 	sqlite_freemem(errmsg);
5605696Snw141292 	errmsg = NULL;
5615696Snw141292 
5625696Snw141292 rollback:
5635696Snw141292 	rc = sqlite_exec(db, "ROLLBACK TRANSACTION", NULL, NULL, &errmsg);
5645696Snw141292 	if (rc != SQLITE_OK) {
5655696Snw141292 		idmapdlog(LOG_ERR, "Rollback failed (%s) while %s (%s)",
5665696Snw141292 		    errmsg, while_doing, dbname);
5675696Snw141292 		sqlite_freemem(errmsg);
5685696Snw141292 		return (-2);
5695696Snw141292 	}
5705696Snw141292 	sqlite_freemem(errmsg);
5715696Snw141292 
5725696Snw141292 	return (-1);
5735696Snw141292 }
5745696Snw141292 
5755696Snw141292 /*
5764520Snw141292  * Execute the given SQL statment without using any callbacks
5774520Snw141292  */
5784520Snw141292 idmap_retcode
5796017Snw141292 sql_exec_no_cb(sqlite *db, const char *dbname, char *sql)
5805696Snw141292 {
5814520Snw141292 	char		*errmsg = NULL;
5824884Sjp151216 	int		r;
5834520Snw141292 	idmap_retcode	retcode;
5844520Snw141292 
5854884Sjp151216 	r = sqlite_exec(db, sql, NULL, NULL, &errmsg);
5864884Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
5874520Snw141292 
5884520Snw141292 	if (r != SQLITE_OK) {
5896017Snw141292 		idmapdlog(LOG_ERR, "Database error on %s while executing %s "
5906017Snw141292 		    "(%s)", dbname, sql, CHECK_NULL(errmsg));
5914884Sjp151216 		retcode = idmapd_string2stat(errmsg);
5924864Sbaban 		if (errmsg != NULL)
5934520Snw141292 			sqlite_freemem(errmsg);
5944520Snw141292 		return (retcode);
5954520Snw141292 	}
5964520Snw141292 
5974520Snw141292 	return (IDMAP_SUCCESS);
5984520Snw141292 }
5994520Snw141292 
6004520Snw141292 /*
6014520Snw141292  * Generate expression that can be used in WHERE statements.
6024520Snw141292  * Examples:
6034520Snw141292  * <prefix> <col>      <op> <value>   <suffix>
6044520Snw141292  * ""       "unixuser" "="  "foo" "AND"
6054520Snw141292  */
6064520Snw141292 idmap_retcode
6075696Snw141292 gen_sql_expr_from_rule(idmap_namerule *rule, char **out)
6085696Snw141292 {
6095696Snw141292 	char	*s_windomain = NULL, *s_winname = NULL;
6105696Snw141292 	char	*s_unixname = NULL;
6115696Snw141292 	char	*lower_winname;
6125696Snw141292 	int	retcode = IDMAP_SUCCESS;
6135696Snw141292 
6144520Snw141292 	if (out == NULL)
6154520Snw141292 		return (IDMAP_ERR_ARG);
6164520Snw141292 
6175696Snw141292 
6185696Snw141292 	if (!EMPTY_STRING(rule->windomain)) {
6195696Snw141292 		s_windomain =  sqlite_mprintf("AND windomain = %Q ",
6205696Snw141292 		    rule->windomain);
6215696Snw141292 		if (s_windomain == NULL) {
6225696Snw141292 			retcode = IDMAP_ERR_MEMORY;
6235696Snw141292 			goto out;
6245696Snw141292 		}
6255696Snw141292 	}
6265696Snw141292 
6275696Snw141292 	if (!EMPTY_STRING(rule->winname)) {
6285696Snw141292 		if ((lower_winname = tolower_u8(rule->winname)) == NULL)
6295696Snw141292 			lower_winname = rule->winname;
6305696Snw141292 		s_winname = sqlite_mprintf(
6315696Snw141292 		    "AND winname = %Q AND is_wuser = %d ",
6325696Snw141292 		    lower_winname, rule->is_wuser ? 1 : 0);
6335696Snw141292 		if (lower_winname != rule->winname)
6345696Snw141292 			free(lower_winname);
6355696Snw141292 		if (s_winname == NULL) {
6365696Snw141292 			retcode = IDMAP_ERR_MEMORY;
6375696Snw141292 			goto out;
6385696Snw141292 		}
6395696Snw141292 	}
6405696Snw141292 
6415696Snw141292 	if (!EMPTY_STRING(rule->unixname)) {
6425696Snw141292 		s_unixname = sqlite_mprintf(
6435696Snw141292 		    "AND unixname = %Q AND is_user = %d ",
6445696Snw141292 		    rule->unixname, rule->is_user ? 1 : 0);
6455696Snw141292 		if (s_unixname == NULL) {
6465696Snw141292 			retcode = IDMAP_ERR_MEMORY;
6475696Snw141292 			goto out;
6485696Snw141292 		}
6495696Snw141292 	}
6505696Snw141292 
6515696Snw141292 	*out = sqlite_mprintf("%s %s %s",
6525696Snw141292 	    s_windomain ? s_windomain : "",
6535696Snw141292 	    s_winname ? s_winname : "",
6545696Snw141292 	    s_unixname ? s_unixname : "");
6555696Snw141292 
6565696Snw141292 	if (*out == NULL) {
6575696Snw141292 		retcode = IDMAP_ERR_MEMORY;
6585696Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
6595696Snw141292 		goto out;
6605696Snw141292 	}
6615696Snw141292 
6625696Snw141292 out:
6635696Snw141292 	if (s_windomain != NULL)
6645696Snw141292 		sqlite_freemem(s_windomain);
6655696Snw141292 	if (s_winname != NULL)
6665696Snw141292 		sqlite_freemem(s_winname);
6675696Snw141292 	if (s_unixname != NULL)
6685696Snw141292 		sqlite_freemem(s_unixname);
6695696Snw141292 
6705696Snw141292 	return (retcode);
6714520Snw141292 }
6724520Snw141292 
6735696Snw141292 
6745696Snw141292 
6754520Snw141292 /*
6764520Snw141292  * Generate and execute SQL statement for LIST RPC calls
6774520Snw141292  */
6784520Snw141292 idmap_retcode
6796017Snw141292 process_list_svc_sql(sqlite *db, const char *dbname, char *sql, uint64_t limit,
6806386Sjp151216 		int flag, list_svc_cb cb, void *result)
6815696Snw141292 {
6824520Snw141292 	list_cb_data_t	cb_data;
6834520Snw141292 	char		*errmsg = NULL;
6844884Sjp151216 	int		r;
6854520Snw141292 	idmap_retcode	retcode = IDMAP_ERR_INTERNAL;
6864520Snw141292 
6874520Snw141292 	(void) memset(&cb_data, 0, sizeof (cb_data));
6884520Snw141292 	cb_data.result = result;
6894520Snw141292 	cb_data.limit = limit;
6906386Sjp151216 	cb_data.flag = flag;
6914520Snw141292 
6924884Sjp151216 
6934884Sjp151216 	r = sqlite_exec(db, sql, cb, &cb_data, &errmsg);
6944884Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
6954884Sjp151216 	switch (r) {
6964884Sjp151216 	case SQLITE_OK:
6974884Sjp151216 		retcode = IDMAP_SUCCESS;
6984884Sjp151216 		break;
6994884Sjp151216 
7004884Sjp151216 	default:
7014884Sjp151216 		retcode = IDMAP_ERR_INTERNAL;
7026017Snw141292 		idmapdlog(LOG_ERR, "Database error on %s while executing "
7036017Snw141292 		    "%s (%s)", dbname, sql, CHECK_NULL(errmsg));
7044884Sjp151216 		break;
7054520Snw141292 	}
7064864Sbaban 	if (errmsg != NULL)
7074520Snw141292 		sqlite_freemem(errmsg);
7084520Snw141292 	return (retcode);
7094520Snw141292 }
7104520Snw141292 
7114520Snw141292 /*
7124520Snw141292  * This routine is called by callbacks that process the results of
7134520Snw141292  * LIST RPC calls to validate data and to allocate memory for
7144520Snw141292  * the result array.
7154520Snw141292  */
7164520Snw141292 idmap_retcode
7174520Snw141292 validate_list_cb_data(list_cb_data_t *cb_data, int argc, char **argv,
7185696Snw141292 		int ncol, uchar_t **list, size_t valsize)
7195696Snw141292 {
7204520Snw141292 	size_t	nsize;
7214520Snw141292 	void	*tmplist;
7224520Snw141292 
7234520Snw141292 	if (cb_data->limit > 0 && cb_data->next == cb_data->limit)
7244520Snw141292 		return (IDMAP_NEXT);
7254520Snw141292 
7264520Snw141292 	if (argc < ncol || argv == NULL) {
7274520Snw141292 		idmapdlog(LOG_ERR, "Invalid data");
7284520Snw141292 		return (IDMAP_ERR_INTERNAL);
7294520Snw141292 	}
7304520Snw141292 
7314520Snw141292 	/* alloc in bulk to reduce number of reallocs */
7324520Snw141292 	if (cb_data->next >= cb_data->len) {
7334520Snw141292 		nsize = (cb_data->len + SIZE_INCR) * valsize;
7344520Snw141292 		tmplist = realloc(*list, nsize);
7354520Snw141292 		if (tmplist == NULL) {
7364520Snw141292 			idmapdlog(LOG_ERR, "Out of memory");
7374520Snw141292 			return (IDMAP_ERR_MEMORY);
7384520Snw141292 		}
7394520Snw141292 		*list = tmplist;
7404520Snw141292 		(void) memset(*list + (cb_data->len * valsize), 0,
7415696Snw141292 		    SIZE_INCR * valsize);
7424520Snw141292 		cb_data->len += SIZE_INCR;
7434520Snw141292 	}
7444520Snw141292 	return (IDMAP_SUCCESS);
7454520Snw141292 }
7464520Snw141292 
7475696Snw141292 static
7485696Snw141292 idmap_retcode
7494520Snw141292 get_namerule_order(char *winname, char *windomain, char *unixname,
7505696Snw141292 	int direction, int is_diagonal, int *w2u_order, int *u2w_order)
7515696Snw141292 {
7524520Snw141292 	*w2u_order = 0;
7534520Snw141292 	*u2w_order = 0;
7544520Snw141292 
7554520Snw141292 	/*
7564520Snw141292 	 * Windows to UNIX lookup order:
7574520Snw141292 	 *  1. winname@domain (or winname) to ""
7584520Snw141292 	 *  2. winname@domain (or winname) to unixname
7594520Snw141292 	 *  3. winname@* to ""
7604520Snw141292 	 *  4. winname@* to unixname
7614520Snw141292 	 *  5. *@domain (or *) to *
7624520Snw141292 	 *  6. *@domain (or *) to ""
7634520Snw141292 	 *  7. *@domain (or *) to unixname
7644520Snw141292 	 *  8. *@* to *
7654520Snw141292 	 *  9. *@* to ""
7664520Snw141292 	 * 10. *@* to unixname
7674520Snw141292 	 *
7684520Snw141292 	 * winname is a special case of winname@domain when domain is the
7694520Snw141292 	 * default domain. Similarly * is a special case of *@domain when
7704520Snw141292 	 * domain is the default domain.
7714520Snw141292 	 *
7724520Snw141292 	 * Note that "" has priority over specific names because "" inhibits
7734520Snw141292 	 * mappings and traditionally deny rules always had higher priority.
7744520Snw141292 	 */
7754644Sbaban 	if (direction != IDMAP_DIRECTION_U2W) {
7764644Sbaban 		/* bi-directional or from windows to unix */
7774520Snw141292 		if (winname == NULL)
7784520Snw141292 			return (IDMAP_ERR_W2U_NAMERULE);
7794520Snw141292 		else if (unixname == NULL)
7804520Snw141292 			return (IDMAP_ERR_W2U_NAMERULE);
7814520Snw141292 		else if (EMPTY_NAME(winname))
7824520Snw141292 			return (IDMAP_ERR_W2U_NAMERULE);
7834520Snw141292 		else if (*winname == '*' && windomain && *windomain == '*') {
7844520Snw141292 			if (*unixname == '*')
7854520Snw141292 				*w2u_order = 8;
7864520Snw141292 			else if (EMPTY_NAME(unixname))
7874520Snw141292 				*w2u_order = 9;
7884520Snw141292 			else /* unixname == name */
7894520Snw141292 				*w2u_order = 10;
7904520Snw141292 		} else if (*winname == '*') {
7914520Snw141292 			if (*unixname == '*')
7924520Snw141292 				*w2u_order = 5;
7934520Snw141292 			else if (EMPTY_NAME(unixname))
7944520Snw141292 				*w2u_order = 6;
7954520Snw141292 			else /* name */
7964520Snw141292 				*w2u_order = 7;
7974864Sbaban 		} else if (windomain != NULL && *windomain == '*') {
7984520Snw141292 			/* winname == name */
7994520Snw141292 			if (*unixname == '*')
8004520Snw141292 				return (IDMAP_ERR_W2U_NAMERULE);
8014520Snw141292 			else if (EMPTY_NAME(unixname))
8024520Snw141292 				*w2u_order = 3;
8034520Snw141292 			else /* name */
8044520Snw141292 				*w2u_order = 4;
8054520Snw141292 		} else  {
8064520Snw141292 			/* winname == name && windomain == null or name */
8074520Snw141292 			if (*unixname == '*')
8084520Snw141292 				return (IDMAP_ERR_W2U_NAMERULE);
8094520Snw141292 			else if (EMPTY_NAME(unixname))
8104520Snw141292 				*w2u_order = 1;
8114520Snw141292 			else /* name */
8124520Snw141292 				*w2u_order = 2;
8134520Snw141292 		}
8145696Snw141292 
8154520Snw141292 	}
8164520Snw141292 
8174520Snw141292 	/*
8185696Snw141292 	 * 1. unixname to "", non-diagonal
8195696Snw141292 	 * 2. unixname to winname@domain (or winname), non-diagonal
8205696Snw141292 	 * 3. unixname to "", diagonal
8215696Snw141292 	 * 4. unixname to winname@domain (or winname), diagonal
8225696Snw141292 	 * 5. * to *@domain (or *), non-diagonal
8235696Snw141292 	 * 5. * to *@domain (or *), diagonal
8245696Snw141292 	 * 7. * to ""
8255696Snw141292 	 * 8. * to winname@domain (or winname)
8265696Snw141292 	 * 9. * to "", non-diagonal
8275696Snw141292 	 * 10. * to winname@domain (or winname), diagonal
8284520Snw141292 	 */
8294644Sbaban 	if (direction != IDMAP_DIRECTION_W2U) {
8305696Snw141292 		int diagonal = is_diagonal ? 1 : 0;
8315696Snw141292 
8324644Sbaban 		/* bi-directional or from unix to windows */
8334520Snw141292 		if (unixname == NULL || EMPTY_NAME(unixname))
8344520Snw141292 			return (IDMAP_ERR_U2W_NAMERULE);
8354520Snw141292 		else if (winname == NULL)
8364520Snw141292 			return (IDMAP_ERR_U2W_NAMERULE);
8374864Sbaban 		else if (windomain != NULL && *windomain == '*')
8384644Sbaban 			return (IDMAP_ERR_U2W_NAMERULE);
8394520Snw141292 		else if (*unixname == '*') {
8404520Snw141292 			if (*winname == '*')
8415696Snw141292 				*u2w_order = 5 + diagonal;
8424520Snw141292 			else if (EMPTY_NAME(winname))
8435696Snw141292 				*u2w_order = 7 + 2 * diagonal;
8444520Snw141292 			else
8455696Snw141292 				*u2w_order = 8 + 2 * diagonal;
8464520Snw141292 		} else {
8474520Snw141292 			if (*winname == '*')
8484520Snw141292 				return (IDMAP_ERR_U2W_NAMERULE);
8494520Snw141292 			else if (EMPTY_NAME(winname))
8505696Snw141292 				*u2w_order = 1 + 2 * diagonal;
8514520Snw141292 			else
8525696Snw141292 				*u2w_order = 2 + 2 * diagonal;
8534520Snw141292 		}
8544520Snw141292 	}
8554520Snw141292 	return (IDMAP_SUCCESS);
8564520Snw141292 }
8574520Snw141292 
8584520Snw141292 /*
8594520Snw141292  * Generate and execute SQL statement to add name-based mapping rule
8604520Snw141292  */
8614520Snw141292 idmap_retcode
8625696Snw141292 add_namerule(sqlite *db, idmap_namerule *rule)
8635696Snw141292 {
8644520Snw141292 	char		*sql = NULL;
8654520Snw141292 	idmap_stat	retcode;
8665064Sdm199847 	char		*dom = NULL;
8674520Snw141292 	int		w2u_order, u2w_order;
8684520Snw141292 	char		w2ubuf[11], u2wbuf[11];
8694520Snw141292 
8705064Sdm199847 	retcode = get_namerule_order(rule->winname, rule->windomain,
8715696Snw141292 	    rule->unixname, rule->direction,
8725696Snw141292 	    rule->is_user == rule->is_wuser ? 0 : 1, &w2u_order, &u2w_order);
8734520Snw141292 	if (retcode != IDMAP_SUCCESS)
8744520Snw141292 		goto out;
8754520Snw141292 
8764520Snw141292 	if (w2u_order)
8774520Snw141292 		(void) snprintf(w2ubuf, sizeof (w2ubuf), "%d", w2u_order);
8784520Snw141292 	if (u2w_order)
8794520Snw141292 		(void) snprintf(u2wbuf, sizeof (u2wbuf), "%d", u2w_order);
8804520Snw141292 
8814864Sbaban 	/*
8824864Sbaban 	 * For the triggers on namerules table to work correctly:
8834864Sbaban 	 * 1) Use NULL instead of 0 for w2u_order and u2w_order
8844864Sbaban 	 * 2) Use "" instead of NULL for "no domain"
8854864Sbaban 	 */
8864864Sbaban 
8875731Sbaban 	if (!EMPTY_STRING(rule->windomain))
8885064Sdm199847 		dom = rule->windomain;
8895696Snw141292 	else if (lookup_wksids_name2sid(rule->winname, NULL, NULL, NULL, NULL)
8904864Sbaban 	    == IDMAP_SUCCESS) {
8914864Sbaban 		/* well-known SIDs don't need domain */
8924864Sbaban 		dom = "";
8934864Sbaban 	}
8944520Snw141292 
8954520Snw141292 	RDLOCK_CONFIG();
8964864Sbaban 	if (dom == NULL) {
8975317Sjp151216 		if (_idmapdstate.cfg->pgcfg.default_domain)
8985317Sjp151216 			dom = _idmapdstate.cfg->pgcfg.default_domain;
8994864Sbaban 		else
9004864Sbaban 			dom = "";
9014864Sbaban 	}
9024884Sjp151216 	sql = sqlite_mprintf("INSERT into namerules "
9035696Snw141292 	    "(is_user, is_wuser, windomain, winname_display, is_nt4, "
9045696Snw141292 	    "unixname, w2u_order, u2w_order) "
9055696Snw141292 	    "VALUES(%d, %d, %Q, %Q, %d, %Q, %q, %q);",
9065696Snw141292 	    rule->is_user ? 1 : 0, rule->is_wuser ? 1 : 0, dom,
9075696Snw141292 	    rule->winname, rule->is_nt4 ? 1 : 0, rule->unixname,
9085696Snw141292 	    w2u_order ? w2ubuf : NULL, u2w_order ? u2wbuf : NULL);
9094520Snw141292 	UNLOCK_CONFIG();
9104520Snw141292 
9114520Snw141292 	if (sql == NULL) {
9124520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
9134520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
9144520Snw141292 		goto out;
9154520Snw141292 	}
9164520Snw141292 
9176017Snw141292 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, sql);
9184520Snw141292 
9194520Snw141292 	if (retcode == IDMAP_ERR_OTHER)
9204520Snw141292 		retcode = IDMAP_ERR_CFG;
9214520Snw141292 
9224520Snw141292 out:
9234864Sbaban 	if (sql != NULL)
9244520Snw141292 		sqlite_freemem(sql);
9254520Snw141292 	return (retcode);
9264520Snw141292 }
9274520Snw141292 
9284520Snw141292 /*
9294520Snw141292  * Flush name-based mapping rules
9304520Snw141292  */
9314520Snw141292 idmap_retcode
9325696Snw141292 flush_namerules(sqlite *db)
9335696Snw141292 {
9344520Snw141292 	idmap_stat	retcode;
9354520Snw141292 
9366017Snw141292 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, "DELETE FROM namerules;");
9375696Snw141292 
9384520Snw141292 	return (retcode);
9394520Snw141292 }
9404520Snw141292 
9414520Snw141292 /*
9424520Snw141292  * Generate and execute SQL statement to remove a name-based mapping rule
9434520Snw141292  */
9444520Snw141292 idmap_retcode
9455696Snw141292 rm_namerule(sqlite *db, idmap_namerule *rule)
9465696Snw141292 {
9474520Snw141292 	char		*sql = NULL;
9484520Snw141292 	idmap_stat	retcode;
9494520Snw141292 	char		buf[80];
9505696Snw141292 	char		*expr = NULL;
9514520Snw141292 
9525064Sdm199847 	if (rule->direction < 0 && EMPTY_STRING(rule->windomain) &&
9535064Sdm199847 	    EMPTY_STRING(rule->winname) && EMPTY_STRING(rule->unixname))
9544520Snw141292 		return (IDMAP_SUCCESS);
9554520Snw141292 
9565696Snw141292 	buf[0] = 0;
9575696Snw141292 
9585696Snw141292 	if (rule->direction == IDMAP_DIRECTION_BI)
9594520Snw141292 		(void) snprintf(buf, sizeof (buf), "AND w2u_order > 0"
9605696Snw141292 		    " AND u2w_order > 0");
9615696Snw141292 	else if (rule->direction == IDMAP_DIRECTION_W2U)
9624520Snw141292 		(void) snprintf(buf, sizeof (buf), "AND w2u_order > 0"
9635696Snw141292 		    " AND (u2w_order = 0 OR u2w_order ISNULL)");
9645696Snw141292 	else if (rule->direction == IDMAP_DIRECTION_U2W)
9654520Snw141292 		(void) snprintf(buf, sizeof (buf), "AND u2w_order > 0"
9665696Snw141292 		    " AND (w2u_order = 0 OR w2u_order ISNULL)");
9675696Snw141292 
9685696Snw141292 	retcode = gen_sql_expr_from_rule(rule, &expr);
9695696Snw141292 	if (retcode != IDMAP_SUCCESS)
9705696Snw141292 		goto out;
9715696Snw141292 
9725696Snw141292 	sql = sqlite_mprintf("DELETE FROM namerules WHERE 1 %s %s;", expr,
9735696Snw141292 	    buf);
9744520Snw141292 
9754520Snw141292 	if (sql == NULL) {
9764520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
9774520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
9784520Snw141292 		goto out;
9794520Snw141292 	}
9804520Snw141292 
9815696Snw141292 
9826017Snw141292 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, sql);
9834520Snw141292 
9844520Snw141292 out:
9855696Snw141292 	if (expr != NULL)
9865696Snw141292 		sqlite_freemem(expr);
9874864Sbaban 	if (sql != NULL)
9884520Snw141292 		sqlite_freemem(sql);
9894520Snw141292 	return (retcode);
9904520Snw141292 }
9914520Snw141292 
9924520Snw141292 /*
9934520Snw141292  * Compile the given SQL query and step just once.
9944520Snw141292  *
9954520Snw141292  * Input:
9964520Snw141292  * db  - db handle
9974520Snw141292  * sql - SQL statement
9984520Snw141292  *
9994520Snw141292  * Output:
10004520Snw141292  * vm     -  virtual SQL machine
10014520Snw141292  * ncol   - number of columns in the result
10024520Snw141292  * values - column values
10034520Snw141292  *
10044520Snw141292  * Return values:
10054520Snw141292  * IDMAP_SUCCESS
10064520Snw141292  * IDMAP_ERR_NOTFOUND
10074520Snw141292  * IDMAP_ERR_INTERNAL
10084520Snw141292  */
10094520Snw141292 
10105696Snw141292 static
10115696Snw141292 idmap_retcode
10124520Snw141292 sql_compile_n_step_once(sqlite *db, char *sql, sqlite_vm **vm, int *ncol,
10135696Snw141292 		int reqcol, const char ***values)
10145696Snw141292 {
10154520Snw141292 	char		*errmsg = NULL;
10164884Sjp151216 	int		r;
10174884Sjp151216 
10184884Sjp151216 	if ((r = sqlite_compile(db, sql, NULL, vm, &errmsg)) != SQLITE_OK) {
10195696Snw141292 		idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
10205696Snw141292 		    CHECK_NULL(errmsg));
10214520Snw141292 		sqlite_freemem(errmsg);
10224520Snw141292 		return (IDMAP_ERR_INTERNAL);
10234520Snw141292 	}
10244520Snw141292 
10254884Sjp151216 	r = sqlite_step(*vm, ncol, values, NULL);
10264884Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
10274884Sjp151216 
10284884Sjp151216 	if (r == SQLITE_ROW) {
10294864Sbaban 		if (ncol != NULL && *ncol < reqcol) {
10304520Snw141292 			(void) sqlite_finalize(*vm, NULL);
10314520Snw141292 			*vm = NULL;
10324520Snw141292 			return (IDMAP_ERR_INTERNAL);
10334520Snw141292 		}
10344520Snw141292 		/* Caller will call finalize after using the results */
10354520Snw141292 		return (IDMAP_SUCCESS);
10364520Snw141292 	} else if (r == SQLITE_DONE) {
10374520Snw141292 		(void) sqlite_finalize(*vm, NULL);
10384520Snw141292 		*vm = NULL;
10394520Snw141292 		return (IDMAP_ERR_NOTFOUND);
10404520Snw141292 	}
10414520Snw141292 
10424520Snw141292 	(void) sqlite_finalize(*vm, &errmsg);
10434520Snw141292 	*vm = NULL;
10445696Snw141292 	idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
10455696Snw141292 	    CHECK_NULL(errmsg));
10464520Snw141292 	sqlite_freemem(errmsg);
10474520Snw141292 	return (IDMAP_ERR_INTERNAL);
10484520Snw141292 }
10494520Snw141292 
10504864Sbaban /*
10516616Sdm199847  * Load config in the state.
10525731Sbaban  *
10536616Sdm199847  * nm_siduid and nm_sidgid fields:
10545731Sbaban  * state->nm_siduid represents mode used by sid2uid and uid2sid
10555731Sbaban  * requests for directory-based name mappings. Similarly,
10565731Sbaban  * state->nm_sidgid represents mode used by sid2gid and gid2sid
10575731Sbaban  * requests.
10585731Sbaban  *
10595731Sbaban  * sid2uid/uid2sid:
10605731Sbaban  * none       -> ds_name_mapping_enabled != true
10615731Sbaban  * AD-mode    -> !nldap_winname_attr && ad_unixuser_attr
10625731Sbaban  * nldap-mode -> nldap_winname_attr && !ad_unixuser_attr
10635731Sbaban  * mixed-mode -> nldap_winname_attr && ad_unixuser_attr
10645731Sbaban  *
10655731Sbaban  * sid2gid/gid2sid:
10665731Sbaban  * none       -> ds_name_mapping_enabled != true
10675731Sbaban  * AD-mode    -> !nldap_winname_attr && ad_unixgroup_attr
10685731Sbaban  * nldap-mode -> nldap_winname_attr && !ad_unixgroup_attr
10695731Sbaban  * mixed-mode -> nldap_winname_attr && ad_unixgroup_attr
10705731Sbaban  */
10715731Sbaban idmap_retcode
10726616Sdm199847 load_cfg_in_state(lookup_state_t *state)
10735731Sbaban {
10745731Sbaban 	state->nm_siduid = IDMAP_NM_NONE;
10755731Sbaban 	state->nm_sidgid = IDMAP_NM_NONE;
10765731Sbaban 	RDLOCK_CONFIG();
10776616Sdm199847 
10787031Snw141292 	state->eph_map_unres_sids = 0;
10797031Snw141292 	if (_idmapdstate.cfg->pgcfg.eph_map_unres_sids)
10807031Snw141292 		state->eph_map_unres_sids = 1;
10817031Snw141292 
10826616Sdm199847 	if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
10836616Sdm199847 		state->defdom =
10846616Sdm199847 		    strdup(_idmapdstate.cfg->pgcfg.default_domain);
10856616Sdm199847 		if (state->defdom == NULL) {
10866616Sdm199847 			UNLOCK_CONFIG();
10876616Sdm199847 			return (IDMAP_ERR_MEMORY);
10886616Sdm199847 		}
10896616Sdm199847 	} else {
10906616Sdm199847 		UNLOCK_CONFIG();
10916813Sdm199847 		return (IDMAP_SUCCESS);
10926616Sdm199847 	}
10935731Sbaban 	if (_idmapdstate.cfg->pgcfg.ds_name_mapping_enabled == FALSE) {
10945731Sbaban 		UNLOCK_CONFIG();
10955731Sbaban 		return (IDMAP_SUCCESS);
10965731Sbaban 	}
10975731Sbaban 	if (_idmapdstate.cfg->pgcfg.nldap_winname_attr != NULL) {
10985731Sbaban 		state->nm_siduid =
10995731Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
11005731Sbaban 		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
11015731Sbaban 		state->nm_sidgid =
11025731Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
11035731Sbaban 		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
11045731Sbaban 	} else {
11055731Sbaban 		state->nm_siduid =
11065731Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
11075731Sbaban 		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
11085731Sbaban 		state->nm_sidgid =
11095731Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
11105731Sbaban 		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
11115731Sbaban 	}
11125731Sbaban 	if (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL) {
11135731Sbaban 		state->ad_unixuser_attr =
11145731Sbaban 		    strdup(_idmapdstate.cfg->pgcfg.ad_unixuser_attr);
11155731Sbaban 		if (state->ad_unixuser_attr == NULL) {
11165731Sbaban 			UNLOCK_CONFIG();
11175731Sbaban 			return (IDMAP_ERR_MEMORY);
11185731Sbaban 		}
11195731Sbaban 	}
11205731Sbaban 	if (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL) {
11215731Sbaban 		state->ad_unixgroup_attr =
11225731Sbaban 		    strdup(_idmapdstate.cfg->pgcfg.ad_unixgroup_attr);
11235731Sbaban 		if (state->ad_unixgroup_attr == NULL) {
11245731Sbaban 			UNLOCK_CONFIG();
11255731Sbaban 			return (IDMAP_ERR_MEMORY);
11265731Sbaban 		}
11275731Sbaban 	}
11286616Sdm199847 	if (_idmapdstate.cfg->pgcfg.nldap_winname_attr != NULL) {
11296616Sdm199847 		state->nldap_winname_attr =
11306616Sdm199847 		    strdup(_idmapdstate.cfg->pgcfg.nldap_winname_attr);
11316616Sdm199847 		if (state->nldap_winname_attr == NULL) {
11326616Sdm199847 			UNLOCK_CONFIG();
11336616Sdm199847 			return (IDMAP_ERR_MEMORY);
11346616Sdm199847 		}
11356616Sdm199847 	}
11365731Sbaban 	UNLOCK_CONFIG();
11375731Sbaban 	return (IDMAP_SUCCESS);
11385731Sbaban }
11395731Sbaban 
11405731Sbaban /*
11416386Sjp151216  * Set the rule with sepecified values.
11426386Sjp151216  * All the strings are copied.
11436386Sjp151216  */
11446386Sjp151216 static void
11456386Sjp151216 idmap_namerule_set(idmap_namerule *rule, const char *windomain,
11466386Sjp151216 		const char *winname, const char *unixname, boolean_t is_user,
11476386Sjp151216 		boolean_t is_wuser, boolean_t is_nt4, int direction)
11486386Sjp151216 {
11496386Sjp151216 	/*
11506386Sjp151216 	 * Only update if they differ because we have to free
11516386Sjp151216 	 * and duplicate the strings
11526386Sjp151216 	 */
11536386Sjp151216 	if (rule->windomain == NULL || windomain == NULL ||
11546386Sjp151216 	    strcmp(rule->windomain, windomain) != 0) {
11556386Sjp151216 		if (rule->windomain != NULL) {
11566386Sjp151216 			free(rule->windomain);
11576386Sjp151216 			rule->windomain = NULL;
11586386Sjp151216 		}
11596386Sjp151216 		if (windomain != NULL)
11606386Sjp151216 			rule->windomain = strdup(windomain);
11616386Sjp151216 	}
11626386Sjp151216 
11636386Sjp151216 	if (rule->winname == NULL || winname == NULL ||
11646386Sjp151216 	    strcmp(rule->winname, winname) != 0) {
11656386Sjp151216 		if (rule->winname != NULL) {
11666386Sjp151216 			free(rule->winname);
11676386Sjp151216 			rule->winname = NULL;
11686386Sjp151216 		}
11696386Sjp151216 		if (winname != NULL)
11706386Sjp151216 			rule->winname = strdup(winname);
11716386Sjp151216 	}
11726386Sjp151216 
11736386Sjp151216 	if (rule->unixname == NULL || unixname == NULL ||
11746386Sjp151216 	    strcmp(rule->unixname, unixname) != 0) {
11756386Sjp151216 		if (rule->unixname != NULL) {
11766386Sjp151216 			free(rule->unixname);
11776386Sjp151216 			rule->unixname = NULL;
11786386Sjp151216 		}
11796386Sjp151216 		if (unixname != NULL)
11806386Sjp151216 			rule->unixname = strdup(unixname);
11816386Sjp151216 	}
11826386Sjp151216 
11836386Sjp151216 	rule->is_user = is_user;
11846386Sjp151216 	rule->is_wuser = is_wuser;
11856386Sjp151216 	rule->is_nt4 = is_nt4;
11866386Sjp151216 	rule->direction = direction;
11876386Sjp151216 }
11886386Sjp151216 
11896386Sjp151216 
11906386Sjp151216 /*
11914864Sbaban  * Table for well-known SIDs.
11924864Sbaban  *
11934864Sbaban  * Background:
11944864Sbaban  *
11955191Sbaban  * Some of the well-known principals are stored under:
11964864Sbaban  * cn=WellKnown Security Principals, cn=Configuration, dc=<forestRootDomain>
11974864Sbaban  * They belong to objectClass "foreignSecurityPrincipal". They don't have
11984864Sbaban  * "samAccountName" nor "userPrincipalName" attributes. Their names are
11994864Sbaban  * available in "cn" and "name" attributes. Some of these principals have a
12004864Sbaban  * second entry under CN=ForeignSecurityPrincipals,dc=<forestRootDomain> and
12014864Sbaban  * these duplicate entries have the stringified SID in the "name" and "cn"
12024864Sbaban  * attributes instead of the actual name.
12034864Sbaban  *
12045191Sbaban  * Those of the form S-1-5-32-X are Builtin groups and are stored in the
12055191Sbaban  * cn=builtin container (except, Power Users which is not stored in AD)
12064864Sbaban  *
12075191Sbaban  * These principals are and will remain constant. Therefore doing AD lookups
12085191Sbaban  * provides no benefit. Also, using hard-coded table (and thus avoiding AD
12095191Sbaban  * lookup) improves performance and avoids additional complexity in the
12105191Sbaban  * adutils.c code. Moreover these SIDs can be used when no Active Directory
12115191Sbaban  * is available (such as the CIFS server's "workgroup" mode).
12125191Sbaban  *
12135191Sbaban  * Notes:
12145191Sbaban  * 1. Currently we don't support localization of well-known SID names,
12154864Sbaban  * unlike Windows.
12164864Sbaban  *
12175191Sbaban  * 2. Other well-known SIDs i.e. S-1-5-<domain>-<w-k RID> are not stored
12185191Sbaban  * here. AD does have normal user/group objects for these objects and
12195191Sbaban  * can be looked up using the existing AD lookup code.
12205731Sbaban  *
12215731Sbaban  * 3. See comments above lookup_wksids_sid2pid() for more information
12225731Sbaban  * on how we lookup the wksids table.
12234864Sbaban  */
12244864Sbaban static wksids_table_t wksids[] = {
12255731Sbaban 	{"S-1-0", 0, "Nobody", 0, SENTINEL_PID, -1, 1},
12265731Sbaban 	{"S-1-1", 0, "Everyone", 0, SENTINEL_PID, -1, -1},
12275731Sbaban 	{"S-1-3", 0, "Creator Owner", 1, IDMAP_WK_CREATOR_OWNER_UID, 1, 0},
12285731Sbaban 	{"S-1-3", 1, "Creator Group", 0, IDMAP_WK_CREATOR_GROUP_GID, 0, 0},
12295731Sbaban 	{"S-1-3", 2, "Creator Owner Server", 1, SENTINEL_PID, -1, -1},
12305731Sbaban 	{"S-1-3", 3, "Creator Group Server", 0, SENTINEL_PID, -1, 1},
12315731Sbaban 	{"S-1-3", 4, "Owner Rights", 0, SENTINEL_PID, -1, -1},
12325731Sbaban 	{"S-1-5", 1, "Dialup", 0, SENTINEL_PID, -1, -1},
12335731Sbaban 	{"S-1-5", 2, "Network", 0, SENTINEL_PID, -1, -1},
12345731Sbaban 	{"S-1-5", 3, "Batch", 0, SENTINEL_PID, -1, -1},
12355731Sbaban 	{"S-1-5", 4, "Interactive", 0, SENTINEL_PID, -1, -1},
12365731Sbaban 	{"S-1-5", 6, "Service", 0, SENTINEL_PID, -1, -1},
12375731Sbaban 	{"S-1-5", 7, "Anonymous Logon", 0, GID_NOBODY, 0, 0},
12385731Sbaban 	{"S-1-5", 7, "Anonymous Logon", 0, UID_NOBODY, 1, 0},
12395731Sbaban 	{"S-1-5", 8, "Proxy", 0, SENTINEL_PID, -1, -1},
12405731Sbaban 	{"S-1-5", 9, "Enterprise Domain Controllers", 0, SENTINEL_PID, -1, -1},
12415731Sbaban 	{"S-1-5", 10, "Self", 0, SENTINEL_PID, -1, -1},
12425731Sbaban 	{"S-1-5", 11, "Authenticated Users", 0, SENTINEL_PID, -1, -1},
12435731Sbaban 	{"S-1-5", 12, "Restricted Code", 0, SENTINEL_PID, -1, -1},
12445731Sbaban 	{"S-1-5", 13, "Terminal Server User", 0, SENTINEL_PID, -1, -1},
12455731Sbaban 	{"S-1-5", 14, "Remote Interactive Logon", 0, SENTINEL_PID, -1, -1},
12465731Sbaban 	{"S-1-5", 15, "This Organization", 0, SENTINEL_PID, -1, -1},
12475731Sbaban 	{"S-1-5", 17, "IUSR", 0, SENTINEL_PID, -1, -1},
12485731Sbaban 	{"S-1-5", 18, "Local System", 0, IDMAP_WK_LOCAL_SYSTEM_GID, 0, 0},
12495731Sbaban 	{"S-1-5", 19, "Local Service", 0, SENTINEL_PID, -1, -1},
12505731Sbaban 	{"S-1-5", 20, "Network Service", 0, SENTINEL_PID, -1, -1},
12515731Sbaban 	{"S-1-5", 1000, "Other Organization", 0, SENTINEL_PID, -1, -1},
12525731Sbaban 	{"S-1-5-32", 544, "Administrators", 0, SENTINEL_PID, -1, -1},
12535731Sbaban 	{"S-1-5-32", 545, "Users", 0, SENTINEL_PID, -1, -1},
12545731Sbaban 	{"S-1-5-32", 546, "Guests", 0, SENTINEL_PID, -1, -1},
12555731Sbaban 	{"S-1-5-32", 547, "Power Users", 0, SENTINEL_PID, -1, -1},
12565731Sbaban 	{"S-1-5-32", 548, "Account Operators", 0, SENTINEL_PID, -1, -1},
12575731Sbaban 	{"S-1-5-32", 549, "Server Operators", 0, SENTINEL_PID, -1, -1},
12585731Sbaban 	{"S-1-5-32", 550, "Print Operators", 0, SENTINEL_PID, -1, -1},
12595731Sbaban 	{"S-1-5-32", 551, "Backup Operators", 0, SENTINEL_PID, -1, -1},
12605731Sbaban 	{"S-1-5-32", 552, "Replicator", 0, SENTINEL_PID, -1, -1},
12615191Sbaban 	{"S-1-5-32", 554, "Pre-Windows 2000 Compatible Access", 0,
12625731Sbaban 	    SENTINEL_PID, -1, -1},
12635731Sbaban 	{"S-1-5-32", 555, "Remote Desktop Users", 0, SENTINEL_PID, -1, -1},
12645191Sbaban 	{"S-1-5-32", 556, "Network Configuration Operators", 0,
12655731Sbaban 	    SENTINEL_PID, -1, -1},
12665191Sbaban 	{"S-1-5-32", 557, "Incoming Forest Trust Builders", 0,
12675731Sbaban 	    SENTINEL_PID, -1, -1},
12685731Sbaban 	{"S-1-5-32", 558, "Performance Monitor Users", 0, SENTINEL_PID, -1, -1},
12695731Sbaban 	{"S-1-5-32", 559, "Performance Log Users", 0, SENTINEL_PID, -1, -1},
12705191Sbaban 	{"S-1-5-32", 560, "Windows Authorization Access Group", 0,
12715731Sbaban 	    SENTINEL_PID, -1, -1},
12725191Sbaban 	{"S-1-5-32", 561, "Terminal Server License Servers", 0,
12735731Sbaban 	    SENTINEL_PID, -1, -1},
12745731Sbaban 	{"S-1-5-32", 561, "Distributed COM Users", 0, SENTINEL_PID, -1, -1},
12755731Sbaban 	{"S-1-5-32", 568, "IIS_IUSRS", 0, SENTINEL_PID, -1, -1},
12765731Sbaban 	{"S-1-5-32", 569, "Cryptographic Operators", 0, SENTINEL_PID, -1, -1},
12775731Sbaban 	{"S-1-5-32", 573, "Event Log Readers", 0, SENTINEL_PID, -1, -1},
12785191Sbaban 	{"S-1-5-32", 574, "Certificate Service DCOM Access", 0,
12795731Sbaban 	    SENTINEL_PID, -1, -1},
12805731Sbaban 	{"S-1-5-64", 21, "Digest Authentication", 0, SENTINEL_PID, -1, -1},
12815731Sbaban 	{"S-1-5-64", 10, "NTLM Authentication", 0, SENTINEL_PID, -1, -1},
12825731Sbaban 	{"S-1-5-64", 14, "SChannel Authentication", 0, SENTINEL_PID, -1, -1},
12835731Sbaban 	{NULL, UINT32_MAX, NULL, -1, SENTINEL_PID, -1, -1}
12844520Snw141292 };
12854520Snw141292 
12865731Sbaban /*
12875731Sbaban  * Lookup well-known SIDs table either by winname or by SID.
12885731Sbaban  * If the given winname or SID is a well-known SID then we set wksid
12895731Sbaban  * variable and then proceed to see if the SID has a hard mapping to
12905731Sbaban  * a particular UID/GID (Ex: Creator Owner/Creator Group mapped to
12915731Sbaban  * fixed ephemeral ids). If we find such mapping then we return
12925731Sbaban  * success otherwise notfound. If a well-known SID is mapped to
12935731Sbaban  * SENTINEL_PID and the direction field is set (bi-directional or
12945731Sbaban  * win2unix) then we treat it as inhibited mapping and return no
12955731Sbaban  * mapping (Ex. S-1-0-0).
12965731Sbaban  */
12975696Snw141292 static
12985696Snw141292 idmap_retcode
12995731Sbaban lookup_wksids_sid2pid(idmap_mapping *req, idmap_id_res *res, int *wksid)
13005696Snw141292 {
13014520Snw141292 	int i;
13025731Sbaban 
13035731Sbaban 	*wksid = 0;
13045731Sbaban 
13054864Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
13065731Sbaban 		if (req->id1.idmap_id_u.sid.prefix != NULL) {
13075731Sbaban 			if ((strcasecmp(wksids[i].sidprefix,
13085731Sbaban 			    req->id1.idmap_id_u.sid.prefix) != 0) ||
13095731Sbaban 			    wksids[i].rid != req->id1.idmap_id_u.sid.rid)
13105731Sbaban 				/* this is not our SID */
13115731Sbaban 				continue;
13125731Sbaban 			if (req->id1name == NULL) {
13135731Sbaban 				req->id1name = strdup(wksids[i].winname);
13145731Sbaban 				if (req->id1name == NULL)
13155731Sbaban 					return (IDMAP_ERR_MEMORY);
13165731Sbaban 			}
13175731Sbaban 		} else if (req->id1name != NULL) {
13185731Sbaban 			if (strcasecmp(wksids[i].winname, req->id1name) != 0)
13195731Sbaban 				/* this is not our winname */
13204864Sbaban 				continue;
13215731Sbaban 			req->id1.idmap_id_u.sid.prefix =
13225731Sbaban 			    strdup(wksids[i].sidprefix);
13235731Sbaban 			if (req->id1.idmap_id_u.sid.prefix == NULL)
13245731Sbaban 				return (IDMAP_ERR_MEMORY);
13255731Sbaban 			req->id1.idmap_id_u.sid.rid = wksids[i].rid;
13265731Sbaban 		}
13275731Sbaban 
13285731Sbaban 		*wksid = 1;
13295731Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
13305731Sbaban 
13315731Sbaban 		req->id1.idtype = (wksids[i].is_wuser) ?
13325731Sbaban 		    IDMAP_USID : IDMAP_GSID;
13335731Sbaban 
13345731Sbaban 		if (wksids[i].pid == SENTINEL_PID) {
13355731Sbaban 			if (wksids[i].direction == IDMAP_DIRECTION_BI ||
13365731Sbaban 			    wksids[i].direction == IDMAP_DIRECTION_W2U)
13375731Sbaban 				/* Inhibited */
13385731Sbaban 				return (IDMAP_ERR_NOMAPPING);
13395731Sbaban 			/* Not mapped */
13406616Sdm199847 			if (res->id.idtype == IDMAP_POSIXID) {
13416616Sdm199847 				res->id.idtype =
13426616Sdm199847 				    (wksids[i].is_wuser) ?
13436616Sdm199847 				    IDMAP_UID : IDMAP_GID;
13446616Sdm199847 			}
13455731Sbaban 			return (IDMAP_ERR_NOTFOUND);
13465731Sbaban 		} else if (wksids[i].direction == IDMAP_DIRECTION_U2W)
13475731Sbaban 			continue;
13485731Sbaban 
13495731Sbaban 		switch (res->id.idtype) {
13505731Sbaban 		case IDMAP_UID:
13515731Sbaban 			if (wksids[i].is_user == 0)
13525731Sbaban 				continue;
13535731Sbaban 			res->id.idmap_id_u.uid = wksids[i].pid;
13545731Sbaban 			res->direction = wksids[i].direction;
13556386Sjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
13566386Sjp151216 				res->info.how.map_type =
13576386Sjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
13586386Sjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
13596386Sjp151216 			}
13605731Sbaban 			return (IDMAP_SUCCESS);
13615731Sbaban 		case IDMAP_GID:
13625731Sbaban 			if (wksids[i].is_user == 1)
13635731Sbaban 				continue;
13645731Sbaban 			res->id.idmap_id_u.gid = wksids[i].pid;
13655731Sbaban 			res->direction = wksids[i].direction;
13666386Sjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
13676386Sjp151216 				res->info.how.map_type =
13686386Sjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
13696386Sjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
13706386Sjp151216 			}
13715731Sbaban 			return (IDMAP_SUCCESS);
13725731Sbaban 		case IDMAP_POSIXID:
13735731Sbaban 			res->id.idmap_id_u.uid = wksids[i].pid;
13745731Sbaban 			res->id.idtype = (!wksids[i].is_user) ?
13755731Sbaban 			    IDMAP_GID : IDMAP_UID;
13765731Sbaban 			res->direction = wksids[i].direction;
13776386Sjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
13786386Sjp151216 				res->info.how.map_type =
13796386Sjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
13806386Sjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
13816386Sjp151216 			}
13825731Sbaban 			return (IDMAP_SUCCESS);
13835731Sbaban 		default:
13845731Sbaban 			return (IDMAP_ERR_NOTSUPPORTED);
13854520Snw141292 		}
13864520Snw141292 	}
13874520Snw141292 	return (IDMAP_ERR_NOTFOUND);
13884520Snw141292 }
13894520Snw141292 
13905696Snw141292 
13915696Snw141292 static
13925696Snw141292 idmap_retcode
13935696Snw141292 lookup_wksids_pid2sid(idmap_mapping *req, idmap_id_res *res, int is_user)
13945696Snw141292 {
13954520Snw141292 	int i;
13965731Sbaban 	if (req->id1.idmap_id_u.uid == SENTINEL_PID)
13975731Sbaban 		return (IDMAP_ERR_NOTFOUND);
13984864Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
13994864Sbaban 		if (wksids[i].pid == req->id1.idmap_id_u.uid &&
14004864Sbaban 		    wksids[i].is_user == is_user &&
14014864Sbaban 		    wksids[i].direction != IDMAP_DIRECTION_W2U) {
14025731Sbaban 			if (res->id.idtype == IDMAP_SID) {
14035731Sbaban 				res->id.idtype = (wksids[i].is_wuser) ?
14045731Sbaban 				    IDMAP_USID : IDMAP_GSID;
14055731Sbaban 			}
14064864Sbaban 			res->id.idmap_id_u.sid.rid = wksids[i].rid;
14074864Sbaban 			res->id.idmap_id_u.sid.prefix =
14085696Snw141292 			    strdup(wksids[i].sidprefix);
14094864Sbaban 			if (res->id.idmap_id_u.sid.prefix == NULL) {
14104864Sbaban 				idmapdlog(LOG_ERR, "Out of memory");
14114864Sbaban 				return (IDMAP_ERR_MEMORY);
14124520Snw141292 			}
14134864Sbaban 			res->direction = wksids[i].direction;
14146386Sjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
14156386Sjp151216 				res->info.how.map_type =
14166386Sjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
14176386Sjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
14186386Sjp151216 			}
14194864Sbaban 			return (IDMAP_SUCCESS);
14204864Sbaban 		}
14214864Sbaban 	}
14224864Sbaban 	return (IDMAP_ERR_NOTFOUND);
14234864Sbaban }
14244864Sbaban 
14255696Snw141292 idmap_retcode
14265696Snw141292 lookup_wksids_name2sid(const char *name, char **canonname, char **sidprefix,
14275696Snw141292 	idmap_rid_t *rid, int *type)
14285696Snw141292 {
14296616Sdm199847 	int	i;
14306616Sdm199847 
14316616Sdm199847 	if ((strncasecmp(name, "BUILTIN\\", 8) == 0) ||
14326616Sdm199847 	    (strncasecmp(name, "BUILTIN/", 8) == 0))
14336616Sdm199847 		name += 8;
14346616Sdm199847 
14354864Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
14365731Sbaban 		if (strcasecmp(wksids[i].winname, name) != 0)
14375731Sbaban 			continue;
14385731Sbaban 		if (sidprefix != NULL &&
14395731Sbaban 		    (*sidprefix = strdup(wksids[i].sidprefix)) == NULL) {
14405731Sbaban 			idmapdlog(LOG_ERR, "Out of memory");
14415731Sbaban 			return (IDMAP_ERR_MEMORY);
14425731Sbaban 		}
14435731Sbaban 		if (canonname != NULL &&
14445731Sbaban 		    (*canonname = strdup(wksids[i].winname)) == NULL) {
14455731Sbaban 			idmapdlog(LOG_ERR, "Out of memory");
14465731Sbaban 			if (sidprefix != NULL) {
14475731Sbaban 				free(*sidprefix);
14485731Sbaban 				*sidprefix = NULL;
14494864Sbaban 			}
14505731Sbaban 			return (IDMAP_ERR_MEMORY);
14514520Snw141292 		}
14525731Sbaban 		if (type != NULL)
14535731Sbaban 			*type = (wksids[i].is_wuser) ?
14545731Sbaban 			    _IDMAP_T_USER : _IDMAP_T_GROUP;
14555731Sbaban 		if (rid != NULL)
14565731Sbaban 			*rid = wksids[i].rid;
14575731Sbaban 		return (IDMAP_SUCCESS);
14584520Snw141292 	}
14594520Snw141292 	return (IDMAP_ERR_NOTFOUND);
14604520Snw141292 }
14614520Snw141292 
14625696Snw141292 static
14635696Snw141292 idmap_retcode
14645696Snw141292 lookup_cache_sid2pid(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
14655696Snw141292 {
14664520Snw141292 	char		*end;
14674520Snw141292 	char		*sql = NULL;
14684520Snw141292 	const char	**values;
14694520Snw141292 	sqlite_vm	*vm = NULL;
14704520Snw141292 	int		ncol, is_user;
14714520Snw141292 	uid_t		pid;
14724520Snw141292 	time_t		curtime, exp;
14734520Snw141292 	idmap_retcode	retcode;
14745932Sbaban 	char		*is_user_string, *lower_name;
14754520Snw141292 
14764520Snw141292 	/* Current time */
14774520Snw141292 	errno = 0;
14784520Snw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
14795696Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
14805696Snw141292 		    strerror(errno));
14814520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
14824520Snw141292 		goto out;
14834520Snw141292 	}
14844520Snw141292 
14855731Sbaban 	switch (res->id.idtype) {
14865696Snw141292 	case IDMAP_UID:
14875696Snw141292 		is_user_string = "1";
14885696Snw141292 		break;
14895696Snw141292 	case IDMAP_GID:
14905696Snw141292 		is_user_string = "0";
14915696Snw141292 		break;
14925696Snw141292 	case IDMAP_POSIXID:
14935696Snw141292 		/* the non-diagonal mapping */
14945696Snw141292 		is_user_string = "is_wuser";
14955696Snw141292 		break;
14965696Snw141292 	default:
14975696Snw141292 		retcode = IDMAP_ERR_NOTSUPPORTED;
14985696Snw141292 		goto out;
14995696Snw141292 	}
15005696Snw141292 
15014520Snw141292 	/* SQL to lookup the cache */
15026386Sjp151216 
15035731Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
15045731Sbaban 		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
15056386Sjp151216 		    "unixname, u2w, is_wuser, "
15066386Sjp151216 		    "map_type, map_dn, map_attr, map_value, "
15076386Sjp151216 		    "map_windomain, map_winname, map_unixname, map_is_nt4 "
15085731Sbaban 		    "FROM idmap_cache WHERE is_user = %s AND "
15095731Sbaban 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
15105731Sbaban 		    "(pid >= 2147483648 OR "
15115731Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
15125731Sbaban 		    "expiration > %d));",
15135731Sbaban 		    is_user_string, req->id1.idmap_id_u.sid.prefix,
15145731Sbaban 		    req->id1.idmap_id_u.sid.rid, curtime);
15155731Sbaban 	} else if (req->id1name != NULL) {
15165932Sbaban 		if ((lower_name = tolower_u8(req->id1name)) == NULL)
15175932Sbaban 			lower_name = req->id1name;
15185731Sbaban 		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
15196386Sjp151216 		    "unixname, u2w, is_wuser, "
15206386Sjp151216 		    "map_type, map_dn, map_attr, map_value, "
15216386Sjp151216 		    "map_windomain, map_winname, map_unixname, map_is_nt4 "
15225731Sbaban 		    "FROM idmap_cache WHERE is_user = %s AND "
15235731Sbaban 		    "winname = %Q AND windomain = %Q AND w2u = 1 AND "
15245731Sbaban 		    "(pid >= 2147483648 OR "
15255731Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
15265731Sbaban 		    "expiration > %d));",
15276386Sjp151216 		    is_user_string, lower_name, req->id1domain,
15286386Sjp151216 		    curtime);
15295932Sbaban 		if (lower_name != req->id1name)
15305932Sbaban 			free(lower_name);
15315731Sbaban 	} else {
15325731Sbaban 		retcode = IDMAP_ERR_ARG;
15335731Sbaban 		goto out;
15345731Sbaban 	}
15354520Snw141292 	if (sql == NULL) {
15364520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
15374520Snw141292 		retcode = IDMAP_ERR_MEMORY;
15384520Snw141292 		goto out;
15394520Snw141292 	}
15406386Sjp151216 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol,
15416386Sjp151216 	    14, &values);
15424520Snw141292 	sqlite_freemem(sql);
15434520Snw141292 
15444520Snw141292 	if (retcode == IDMAP_ERR_NOTFOUND) {
15454520Snw141292 		goto out;
15464520Snw141292 	} else if (retcode == IDMAP_SUCCESS) {
15474520Snw141292 		/* sanity checks */
15484520Snw141292 		if (values[0] == NULL || values[1] == NULL) {
15494520Snw141292 			retcode = IDMAP_ERR_CACHE;
15504520Snw141292 			goto out;
15514520Snw141292 		}
15524520Snw141292 
15534520Snw141292 		pid = strtoul(values[0], &end, 10);
15545731Sbaban 		is_user = strncmp(values[1], "0", 2) ? 1 : 0;
15554520Snw141292 
15565696Snw141292 		if (is_user) {
15575696Snw141292 			res->id.idtype = IDMAP_UID;
15585696Snw141292 			res->id.idmap_id_u.uid = pid;
15595696Snw141292 		} else {
15605696Snw141292 			res->id.idtype = IDMAP_GID;
15615696Snw141292 			res->id.idmap_id_u.gid = pid;
15625696Snw141292 		}
15635696Snw141292 
15644520Snw141292 		/*
15654520Snw141292 		 * We may have an expired ephemeral mapping. Consider
15664520Snw141292 		 * the expired entry as valid if we are not going to
15674520Snw141292 		 * perform name-based mapping. But do not renew the
15684520Snw141292 		 * expiration.
15694520Snw141292 		 * If we will be doing name-based mapping then store the
15704520Snw141292 		 * ephemeral pid in the result so that we can use it
15714520Snw141292 		 * if we end up doing dynamic mapping again.
15724520Snw141292 		 */
15734520Snw141292 		if (!DO_NOT_ALLOC_NEW_ID_MAPPING(req) &&
15745696Snw141292 		    !AVOID_NAMESERVICE(req) &&
15755696Snw141292 		    IS_EPHEMERAL(pid) && values[2] != NULL) {
15765696Snw141292 			exp = strtoll(values[2], &end, 10);
15775696Snw141292 			if (exp && exp <= curtime) {
15785696Snw141292 				/* Store the ephemeral pid */
15795696Snw141292 				res->direction = IDMAP_DIRECTION_BI;
15805696Snw141292 				req->direction |= is_user
15815696Snw141292 				    ? _IDMAP_F_EXP_EPH_UID
15825696Snw141292 				    : _IDMAP_F_EXP_EPH_GID;
15835696Snw141292 				retcode = IDMAP_ERR_NOTFOUND;
15844520Snw141292 			}
15854520Snw141292 		}
15864520Snw141292 	}
15874520Snw141292 
15884520Snw141292 out:
15894520Snw141292 	if (retcode == IDMAP_SUCCESS) {
15904864Sbaban 		if (values[4] != NULL)
15914520Snw141292 			res->direction =
15924644Sbaban 			    (strtol(values[4], &end, 10) == 0)?
15934644Sbaban 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
15944520Snw141292 		else
15954644Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
15964520Snw141292 
15974864Sbaban 		if (values[3] != NULL) {
15985731Sbaban 			if (req->id2name != NULL)
15995731Sbaban 				free(req->id2name);
16005064Sdm199847 			req->id2name = strdup(values[3]);
16015064Sdm199847 			if (req->id2name == NULL) {
16024520Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
16034520Snw141292 				retcode = IDMAP_ERR_MEMORY;
16044520Snw141292 			}
16054520Snw141292 		}
16065731Sbaban 
16075731Sbaban 		req->id1.idtype = strncmp(values[5], "0", 2) ?
16085731Sbaban 		    IDMAP_USID : IDMAP_GSID;
16096386Sjp151216 
16106386Sjp151216 		if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
16116386Sjp151216 			res->info.src = IDMAP_MAP_SRC_CACHE;
16126386Sjp151216 			res->info.how.map_type = strtoul(values[6], &end, 10);
16136386Sjp151216 			switch (res->info.how.map_type) {
16146386Sjp151216 			case IDMAP_MAP_TYPE_DS_AD:
16156386Sjp151216 				res->info.how.idmap_how_u.ad.dn =
16166386Sjp151216 				    strdup(values[7]);
16176386Sjp151216 				res->info.how.idmap_how_u.ad.attr =
16186386Sjp151216 				    strdup(values[8]);
16196386Sjp151216 				res->info.how.idmap_how_u.ad.value =
16206386Sjp151216 				    strdup(values[9]);
16216386Sjp151216 				break;
16226386Sjp151216 
16236386Sjp151216 			case IDMAP_MAP_TYPE_DS_NLDAP:
16246386Sjp151216 				res->info.how.idmap_how_u.nldap.dn =
16256386Sjp151216 				    strdup(values[7]);
16266386Sjp151216 				res->info.how.idmap_how_u.nldap.attr =
16276386Sjp151216 				    strdup(values[8]);
16286386Sjp151216 				res->info.how.idmap_how_u.nldap.value =
16296386Sjp151216 				    strdup(values[9]);
16306386Sjp151216 				break;
16316386Sjp151216 
16326386Sjp151216 			case IDMAP_MAP_TYPE_RULE_BASED:
16336386Sjp151216 				res->info.how.idmap_how_u.rule.windomain =
16346386Sjp151216 				    strdup(values[10]);
16356386Sjp151216 				res->info.how.idmap_how_u.rule.winname =
16366386Sjp151216 				    strdup(values[11]);
16376386Sjp151216 				res->info.how.idmap_how_u.rule.unixname =
16386386Sjp151216 				    strdup(values[12]);
16396386Sjp151216 				res->info.how.idmap_how_u.rule.is_nt4 =
16406386Sjp151216 				    strtoul(values[13], &end, 1);
16416386Sjp151216 				res->info.how.idmap_how_u.rule.is_user =
16426386Sjp151216 				    is_user;
16436386Sjp151216 				res->info.how.idmap_how_u.rule.is_wuser =
16446386Sjp151216 				    strtoul(values[5], &end, 1);
16456386Sjp151216 				break;
16466386Sjp151216 
16476386Sjp151216 			case IDMAP_MAP_TYPE_EPHEMERAL:
16486386Sjp151216 				break;
16496386Sjp151216 
16506386Sjp151216 			case IDMAP_MAP_TYPE_LOCAL_SID:
16516386Sjp151216 				break;
16526386Sjp151216 
16536386Sjp151216 			case IDMAP_MAP_TYPE_KNOWN_SID:
16546386Sjp151216 				break;
16556386Sjp151216 
16566386Sjp151216 			default:
16576386Sjp151216 				/* Unknow mapping type */
16586386Sjp151216 				assert(FALSE);
16596386Sjp151216 			}
16606386Sjp151216 		}
16614520Snw141292 	}
16624864Sbaban 	if (vm != NULL)
16634520Snw141292 		(void) sqlite_finalize(vm, NULL);
16644520Snw141292 	return (retcode);
16654520Snw141292 }
16664520Snw141292 
16675696Snw141292 static
16685696Snw141292 idmap_retcode
16694864Sbaban lookup_cache_sid2name(sqlite *cache, const char *sidprefix, idmap_rid_t rid,
16705696Snw141292 		char **name, char **domain, int *type)
16715696Snw141292 {
16724520Snw141292 	char		*end;
16734520Snw141292 	char		*sql = NULL;
16744520Snw141292 	const char	**values;
16754520Snw141292 	sqlite_vm	*vm = NULL;
16764520Snw141292 	int		ncol;
16774520Snw141292 	time_t		curtime;
16784520Snw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
16794520Snw141292 
16804520Snw141292 	/* Get current time */
16814520Snw141292 	errno = 0;
16824520Snw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
16835696Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
16845696Snw141292 		    strerror(errno));
16854520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
16864520Snw141292 		goto out;
16874520Snw141292 	}
16884520Snw141292 
16894520Snw141292 	/* SQL to lookup the cache */
16905696Snw141292 	sql = sqlite_mprintf("SELECT canon_name, domain, type "
16915696Snw141292 	    "FROM name_cache WHERE "
16925696Snw141292 	    "sidprefix = %Q AND rid = %u AND "
16935696Snw141292 	    "(expiration = 0 OR expiration ISNULL OR "
16945696Snw141292 	    "expiration > %d);",
16955696Snw141292 	    sidprefix, rid, curtime);
16964520Snw141292 	if (sql == NULL) {
16974520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
16984520Snw141292 		retcode = IDMAP_ERR_MEMORY;
16994520Snw141292 		goto out;
17004520Snw141292 	}
17014520Snw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 3, &values);
17024520Snw141292 	sqlite_freemem(sql);
17034520Snw141292 
17044520Snw141292 	if (retcode == IDMAP_SUCCESS) {
17054864Sbaban 		if (type != NULL) {
17064520Snw141292 			if (values[2] == NULL) {
17074520Snw141292 				retcode = IDMAP_ERR_CACHE;
17084520Snw141292 				goto out;
17094520Snw141292 			}
17104520Snw141292 			*type = strtol(values[2], &end, 10);
17114520Snw141292 		}
17124520Snw141292 
17134864Sbaban 		if (name != NULL && values[0] != NULL) {
17144520Snw141292 			if ((*name = strdup(values[0])) == NULL) {
17154520Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
17164520Snw141292 				retcode = IDMAP_ERR_MEMORY;
17174520Snw141292 				goto out;
17184520Snw141292 			}
17194520Snw141292 		}
17204520Snw141292 
17214864Sbaban 		if (domain != NULL && values[1] != NULL) {
17224520Snw141292 			if ((*domain = strdup(values[1])) == NULL) {
17234864Sbaban 				if (name != NULL && *name) {
17244520Snw141292 					free(*name);
17254520Snw141292 					*name = NULL;
17264520Snw141292 				}
17274520Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
17284520Snw141292 				retcode = IDMAP_ERR_MEMORY;
17294520Snw141292 				goto out;
17304520Snw141292 			}
17314520Snw141292 		}
17324520Snw141292 	}
17334520Snw141292 
17344520Snw141292 out:
17354864Sbaban 	if (vm != NULL)
17364520Snw141292 		(void) sqlite_finalize(vm, NULL);
17374520Snw141292 	return (retcode);
17384520Snw141292 }
17394520Snw141292 
17404520Snw141292 /*
17415731Sbaban  * Given SID, find winname using name_cache OR
17425731Sbaban  * Given winname, find SID using name_cache.
17435731Sbaban  * Used when mapping win to unix i.e. req->id1 is windows id and
17445731Sbaban  * req->id2 is unix id
17454520Snw141292  */
17465696Snw141292 static
17475696Snw141292 idmap_retcode
17485731Sbaban lookup_name_cache(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
17495696Snw141292 {
17504520Snw141292 	int		type = -1;
17514520Snw141292 	idmap_retcode	retcode;
17525731Sbaban 	char		*sidprefix = NULL;
17534520Snw141292 	idmap_rid_t	rid;
17544520Snw141292 	char		*name = NULL, *domain = NULL;
17554520Snw141292 
17565731Sbaban 	/* Done if we've both sid and winname */
17575731Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL && req->id1name != NULL)
17585731Sbaban 		return (IDMAP_SUCCESS);
17595731Sbaban 
17605731Sbaban 	/* Lookup sid to winname */
17615731Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
17625731Sbaban 		retcode = lookup_cache_sid2name(cache,
17635731Sbaban 		    req->id1.idmap_id_u.sid.prefix,
17645731Sbaban 		    req->id1.idmap_id_u.sid.rid, &name, &domain, &type);
17654864Sbaban 		goto out;
17665731Sbaban 	}
17675731Sbaban 
17685731Sbaban 	/* Lookup winame to sid */
17695731Sbaban 	retcode = lookup_cache_name2sid(cache, req->id1name, req->id1domain,
17705731Sbaban 	    &name, &sidprefix, &rid, &type);
17714520Snw141292 
17724520Snw141292 out:
17735731Sbaban 	if (retcode != IDMAP_SUCCESS) {
17745731Sbaban 		free(name);
17755731Sbaban 		free(domain);
17765731Sbaban 		free(sidprefix);
17775731Sbaban 		return (retcode);
17785731Sbaban 	}
17795731Sbaban 
17805731Sbaban 	if (res->id.idtype == IDMAP_POSIXID) {
17815731Sbaban 		res->id.idtype = (type == _IDMAP_T_USER) ?
17825731Sbaban 		    IDMAP_UID : IDMAP_GID;
17835731Sbaban 	}
17845731Sbaban 	req->id1.idtype = (type == _IDMAP_T_USER) ?
17855731Sbaban 	    IDMAP_USID : IDMAP_GSID;
17865731Sbaban 
17875731Sbaban 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
17885731Sbaban 	if (name != NULL) {
17895731Sbaban 		free(req->id1name);	/* Free existing winname */
17905731Sbaban 		req->id1name = name;	/* and use canonical name instead */
17915731Sbaban 	}
17925731Sbaban 	if (req->id1domain == NULL)
17935731Sbaban 		req->id1domain = domain;
17945731Sbaban 	if (req->id1.idmap_id_u.sid.prefix == NULL) {
17955731Sbaban 		req->id1.idmap_id_u.sid.prefix = sidprefix;
17965731Sbaban 		req->id1.idmap_id_u.sid.rid = rid;
17974520Snw141292 	}
17984520Snw141292 	return (retcode);
17994520Snw141292 }
18004520Snw141292 
18015731Sbaban /*
18025731Sbaban  * Batch AD lookups
18035731Sbaban  */
18044520Snw141292 idmap_retcode
18055731Sbaban ad_lookup_batch(lookup_state_t *state, idmap_mapping_batch *batch,
18065696Snw141292 		idmap_ids_res *result)
18075696Snw141292 {
18084520Snw141292 	idmap_retcode	retcode;
18095731Sbaban 	int		i, add, type, is_wuser, is_user;
18105731Sbaban 	int		retries = 0, eunixtype;
18115731Sbaban 	char		**unixname;
18124520Snw141292 	idmap_mapping	*req;
18134520Snw141292 	idmap_id_res	*res;
18145731Sbaban 	idmap_query_state_t	*qs = NULL;
18156386Sjp151216 	idmap_how	*how;
18166616Sdm199847 	char		**dn, **attr, **value;
18175731Sbaban 
18185731Sbaban 	/*
18195731Sbaban 	 * Since req->id2.idtype is unused, we will use it here
18205731Sbaban 	 * to retrieve the value of sid_type. But it needs to be
18215731Sbaban 	 * reset to IDMAP_NONE before we return to prevent xdr
18225731Sbaban 	 * from mis-interpreting req->id2 when it tries to free
18235731Sbaban 	 * the input argument. Other option is to allocate an
18245731Sbaban 	 * array of integers and use it instead for the batched
18255731Sbaban 	 * call. But why un-necessarily allocate memory. That may
18265731Sbaban 	 * be an option if req->id2.idtype cannot be re-used in
18275731Sbaban 	 * future.
18285731Sbaban 	 */
18294520Snw141292 
18304520Snw141292 	if (state->ad_nqueries == 0)
18314520Snw141292 		return (IDMAP_SUCCESS);
18324520Snw141292 
18336963Sbaban 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
18346963Sbaban 		req = &batch->idmap_mapping_batch_val[i];
18356963Sbaban 		res = &result->ids.ids_val[i];
18366963Sbaban 
18376963Sbaban 		/* Skip if not marked for AD lookup or already in error. */
18386963Sbaban 		if (!(req->direction & _IDMAP_F_LOOKUP_AD) ||
18396963Sbaban 		    res->retcode != IDMAP_SUCCESS)
18406963Sbaban 			continue;
18416963Sbaban 
18426963Sbaban 		/* Init status */
18436963Sbaban 		res->retcode = IDMAP_ERR_RETRIABLE_NET_ERR;
18446963Sbaban 	}
18456963Sbaban 
18464520Snw141292 retry:
18475731Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, state->ad_nqueries,
18485731Sbaban 	    &qs);
18495731Sbaban 	if (retcode != IDMAP_SUCCESS) {
18505968Snw141292 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
18515968Snw141292 			goto retry;
18526097Snw141292 		degrade_svc(1, "failed to create batch for AD lookup");
18535731Sbaban 		goto out;
18544520Snw141292 	}
18554520Snw141292 
18565317Sjp151216 	restore_svc();
18575317Sjp151216 
18585731Sbaban 	idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
18595731Sbaban 	    state->ad_unixgroup_attr);
18605731Sbaban 
18615731Sbaban 	for (i = 0, add = 0; i < batch->idmap_mapping_batch_len; i++) {
18624520Snw141292 		req = &batch->idmap_mapping_batch_val[i];
18634520Snw141292 		res = &result->ids.ids_val[i];
18646386Sjp151216 		how = &res->info.how;
18656386Sjp151216 
18665731Sbaban 		retcode = IDMAP_SUCCESS;
18675731Sbaban 		req->id2.idtype = IDMAP_NONE;
18685731Sbaban 
18695731Sbaban 		/* Skip if not marked for AD lookup */
18705731Sbaban 		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
18715731Sbaban 			continue;
18725731Sbaban 
18736963Sbaban 		if (res->retcode != IDMAP_ERR_RETRIABLE_NET_ERR)
18745731Sbaban 			continue;
18755731Sbaban 
18765731Sbaban 		if (IS_REQUEST_SID(*req, 1)) {
18776616Sdm199847 
18786616Sdm199847 			/* win2unix request: */
18796616Sdm199847 
18806616Sdm199847 			unixname = dn = attr = value = NULL;
18815731Sbaban 			eunixtype = _IDMAP_T_UNDEF;
18825731Sbaban 			if (req->id2name == NULL) {
18835731Sbaban 				if (res->id.idtype == IDMAP_UID &&
18845731Sbaban 				    AD_OR_MIXED(state->nm_siduid)) {
18855731Sbaban 					eunixtype = _IDMAP_T_USER;
18865731Sbaban 					unixname = &req->id2name;
18875731Sbaban 				} else if (res->id.idtype == IDMAP_GID &&
18885731Sbaban 				    AD_OR_MIXED(state->nm_sidgid)) {
18895731Sbaban 					eunixtype = _IDMAP_T_GROUP;
18905731Sbaban 					unixname = &req->id2name;
18915731Sbaban 				} else if (AD_OR_MIXED(state->nm_siduid) ||
18925731Sbaban 				    AD_OR_MIXED(state->nm_sidgid)) {
18935731Sbaban 					unixname = &req->id2name;
18945731Sbaban 				}
18955731Sbaban 			}
18965731Sbaban 			add = 1;
18976616Sdm199847 			if (unixname != NULL) {
18986616Sdm199847 				/*
18996616Sdm199847 				 * Get how info for DS-based name
19006616Sdm199847 				 * mapping only if AD or MIXED
19016616Sdm199847 				 * mode is enabled.
19026616Sdm199847 				 */
19036616Sdm199847 				idmap_info_free(&res->info);
19046616Sdm199847 				res->info.src = IDMAP_MAP_SRC_NEW;
19056616Sdm199847 				how->map_type = IDMAP_MAP_TYPE_DS_AD;
19066616Sdm199847 				dn = &how->idmap_how_u.ad.dn;
19076616Sdm199847 				attr = &how->idmap_how_u.ad.attr;
19086616Sdm199847 				value = &how->idmap_how_u.ad.value;
19096616Sdm199847 			}
19106616Sdm199847 			if (req->id1.idmap_id_u.sid.prefix != NULL) {
19116616Sdm199847 				/* Lookup AD by SID */
19126616Sdm199847 				retcode = idmap_sid2name_batch_add1(
19136616Sdm199847 				    qs, req->id1.idmap_id_u.sid.prefix,
19146616Sdm199847 				    &req->id1.idmap_id_u.sid.rid, eunixtype,
19156616Sdm199847 				    dn, attr, value,
19166616Sdm199847 				    (req->id1name == NULL) ?
19176616Sdm199847 				    &req->id1name : NULL,
19186616Sdm199847 				    (req->id1domain == NULL) ?
19196616Sdm199847 				    &req->id1domain : NULL,
19206616Sdm199847 				    (int *)&req->id2.idtype, unixname,
19216616Sdm199847 				    &res->retcode);
19226616Sdm199847 			} else {
19236616Sdm199847 				/* Lookup AD by winname */
19246616Sdm199847 				assert(req->id1name != NULL);
19256616Sdm199847 				retcode = idmap_name2sid_batch_add1(
19266616Sdm199847 				    qs, req->id1name, req->id1domain,
19276616Sdm199847 				    eunixtype,
19286616Sdm199847 				    dn, attr, value,
19296616Sdm199847 				    &req->id1name,
19306616Sdm199847 				    &req->id1.idmap_id_u.sid.prefix,
19316616Sdm199847 				    &req->id1.idmap_id_u.sid.rid,
19326616Sdm199847 				    (int *)&req->id2.idtype, unixname,
19336616Sdm199847 				    &res->retcode);
19346616Sdm199847 			}
19355731Sbaban 
19365731Sbaban 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
19376616Sdm199847 
19386616Sdm199847 			/* unix2win request: */
19395731Sbaban 
19405731Sbaban 			if (res->id.idmap_id_u.sid.prefix != NULL &&
19415731Sbaban 			    req->id2name != NULL) {
19425731Sbaban 				/* Already have SID and winname -- done */
19435731Sbaban 				res->retcode = IDMAP_SUCCESS;
19445731Sbaban 				continue;
19455731Sbaban 			}
19465731Sbaban 
19475731Sbaban 			if (res->id.idmap_id_u.sid.prefix != NULL) {
19485731Sbaban 				/*
19495731Sbaban 				 * SID but no winname -- lookup AD by
19505731Sbaban 				 * SID to get winname.
19516616Sdm199847 				 * how info is not needed here because
19526616Sdm199847 				 * we are not retrieving unixname from
19536616Sdm199847 				 * AD.
19545731Sbaban 				 */
19555731Sbaban 				add = 1;
19565731Sbaban 				retcode = idmap_sid2name_batch_add1(
19575731Sbaban 				    qs, res->id.idmap_id_u.sid.prefix,
19585731Sbaban 				    &res->id.idmap_id_u.sid.rid,
19596386Sjp151216 				    _IDMAP_T_UNDEF,
19606616Sdm199847 				    NULL, NULL, NULL,
19616386Sjp151216 				    &req->id2name,
19625731Sbaban 				    &req->id2domain, (int *)&req->id2.idtype,
19635731Sbaban 				    NULL, &res->retcode);
19645731Sbaban 			} else if (req->id2name != NULL) {
19655731Sbaban 				/*
19665731Sbaban 				 * winname but no SID -- lookup AD by
19675731Sbaban 				 * winname to get SID.
19686616Sdm199847 				 * how info is not needed here because
19696616Sdm199847 				 * we are not retrieving unixname from
19706616Sdm199847 				 * AD.
19715731Sbaban 				 */
19725731Sbaban 				add = 1;
19735731Sbaban 				retcode = idmap_name2sid_batch_add1(
19745731Sbaban 				    qs, req->id2name, req->id2domain,
19756386Sjp151216 				    _IDMAP_T_UNDEF,
19766616Sdm199847 				    NULL, NULL, NULL, NULL,
19775731Sbaban 				    &res->id.idmap_id_u.sid.prefix,
19785731Sbaban 				    &res->id.idmap_id_u.sid.rid,
19795731Sbaban 				    (int *)&req->id2.idtype, NULL,
19805731Sbaban 				    &res->retcode);
19815731Sbaban 			} else if (req->id1name != NULL) {
19825731Sbaban 				/*
19835731Sbaban 				 * No SID and no winname but we've unixname --
19845731Sbaban 				 * lookup AD by unixname to get SID.
19855731Sbaban 				 */
19865731Sbaban 				is_user = (IS_REQUEST_UID(*req)) ? 1 : 0;
19875731Sbaban 				if (res->id.idtype == IDMAP_USID)
19885731Sbaban 					is_wuser = 1;
19895731Sbaban 				else if (res->id.idtype == IDMAP_GSID)
19905731Sbaban 					is_wuser = 0;
19915731Sbaban 				else
19925731Sbaban 					is_wuser = is_user;
19935731Sbaban 				add = 1;
19946616Sdm199847 				idmap_info_free(&res->info);
19956386Sjp151216 				res->info.src = IDMAP_MAP_SRC_NEW;
19966386Sjp151216 				how->map_type = IDMAP_MAP_TYPE_DS_AD;
19975731Sbaban 				retcode = idmap_unixname2sid_batch_add1(
19985731Sbaban 				    qs, req->id1name, is_user, is_wuser,
19996386Sjp151216 				    &how->idmap_how_u.ad.dn,
20006386Sjp151216 				    &how->idmap_how_u.ad.attr,
20016386Sjp151216 				    &how->idmap_how_u.ad.value,
20025731Sbaban 				    &res->id.idmap_id_u.sid.prefix,
20035731Sbaban 				    &res->id.idmap_id_u.sid.rid,
20045731Sbaban 				    &req->id2name, &req->id2domain,
20055731Sbaban 				    (int *)&req->id2.idtype, &res->retcode);
20065731Sbaban 			}
20075731Sbaban 		}
20085731Sbaban 		if (retcode != IDMAP_SUCCESS) {
20095731Sbaban 			idmap_lookup_release_batch(&qs);
20105731Sbaban 			break;
20114520Snw141292 		}
20124520Snw141292 	}
20134520Snw141292 
20146963Sbaban 	if (retcode == IDMAP_SUCCESS) {
20156963Sbaban 		/* add keeps track if we added an entry to the batch */
20166963Sbaban 		if (add)
20176963Sbaban 			retcode = idmap_lookup_batch_end(&qs);
20186963Sbaban 		else
20196963Sbaban 			idmap_lookup_release_batch(&qs);
20206963Sbaban 	}
20215696Snw141292 
20224520Snw141292 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
20234520Snw141292 		goto retry;
20245317Sjp151216 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
20256097Snw141292 		degrade_svc(1, "some AD lookups timed out repeatedly");
20264520Snw141292 
20275731Sbaban 	if (retcode != IDMAP_SUCCESS)
20285731Sbaban 		idmapdlog(LOG_NOTICE, "Failed to batch AD lookup requests");
20294520Snw141292 
20304520Snw141292 out:
20315731Sbaban 	/*
20325731Sbaban 	 * This loop does the following:
20336616Sdm199847 	 * 1. Reset _IDMAP_F_LOOKUP_AD flag from the request.
20346616Sdm199847 	 * 2. Reset req->id2.idtype to IDMAP_NONE
20356616Sdm199847 	 * 3. If batch_start or batch_add failed then set the status
20366616Sdm199847 	 *    of each request marked for AD lookup to that error.
20376616Sdm199847 	 * 4. Evaluate the type of the AD object (i.e. user or group) and
20386616Sdm199847 	 *    update the idtype in request.
20395731Sbaban 	 */
20405731Sbaban 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
20415731Sbaban 		req = &batch->idmap_mapping_batch_val[i];
20425731Sbaban 		type = req->id2.idtype;
20435731Sbaban 		req->id2.idtype = IDMAP_NONE;
20445746Sbaban 		res = &result->ids.ids_val[i];
20456386Sjp151216 		how = &res->info.how;
20465731Sbaban 		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
20475731Sbaban 			continue;
20485731Sbaban 
20496616Sdm199847 		/* Reset AD lookup flag */
20506616Sdm199847 		req->direction &= ~(_IDMAP_F_LOOKUP_AD);
20516616Sdm199847 
20526616Sdm199847 		/*
20536616Sdm199847 		 * If batch_start or batch_add failed then set the status
20546616Sdm199847 		 * of each request marked for AD lookup to that error.
20556616Sdm199847 		 */
20565731Sbaban 		if (retcode != IDMAP_SUCCESS) {
20575731Sbaban 			res->retcode = retcode;
20585731Sbaban 			continue;
20595731Sbaban 		}
20605731Sbaban 
20615731Sbaban 		if (!add)
20625731Sbaban 			continue;
20635731Sbaban 
20646386Sjp151216 		if (res->retcode == IDMAP_ERR_NOTFOUND) {
20656386Sjp151216 			/* Nothing found - remove the preset info */
20666616Sdm199847 			idmap_info_free(&res->info);
20676386Sjp151216 		}
20686386Sjp151216 
20695731Sbaban 		if (IS_REQUEST_SID(*req, 1)) {
20705731Sbaban 			if (res->retcode != IDMAP_SUCCESS)
20715731Sbaban 				continue;
20726616Sdm199847 			/* Evaluate result type */
20735731Sbaban 			switch (type) {
20745731Sbaban 			case _IDMAP_T_USER:
20755731Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
20765731Sbaban 					res->id.idtype = IDMAP_UID;
20775731Sbaban 				req->id1.idtype = IDMAP_USID;
20785731Sbaban 				break;
20795731Sbaban 			case _IDMAP_T_GROUP:
20805731Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
20815731Sbaban 					res->id.idtype = IDMAP_GID;
20825731Sbaban 				req->id1.idtype = IDMAP_GSID;
20835731Sbaban 				break;
20845731Sbaban 			default:
20855731Sbaban 				res->retcode = IDMAP_ERR_SID;
20865731Sbaban 				break;
20875731Sbaban 			}
20886616Sdm199847 			if (res->retcode == IDMAP_SUCCESS &&
20896616Sdm199847 			    req->id1name != NULL &&
20906616Sdm199847 			    (req->id2name == NULL ||
20916616Sdm199847 			    res->id.idmap_id_u.uid == SENTINEL_PID) &&
20926616Sdm199847 			    NLDAP_MODE(res->id.idtype, state)) {
20936616Sdm199847 				req->direction |= _IDMAP_F_LOOKUP_NLDAP;
20946616Sdm199847 				state->nldap_nqueries++;
20956616Sdm199847 			}
20965731Sbaban 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
20975731Sbaban 			if (res->retcode != IDMAP_SUCCESS) {
20985731Sbaban 				if ((!(IDMAP_FATAL_ERROR(res->retcode))) &&
20995731Sbaban 				    res->id.idmap_id_u.sid.prefix == NULL &&
21005731Sbaban 				    req->id2name == NULL && /* no winname */
21015731Sbaban 				    req->id1name != NULL) /* unixname */
21025731Sbaban 					/*
21036616Sdm199847 					 * If AD lookup by unixname failed
21046616Sdm199847 					 * with non fatal error then clear
21056616Sdm199847 					 * the error (i.e set res->retcode
21066616Sdm199847 					 * to success). This allows the next
21076616Sdm199847 					 * pass to process other mapping
21086616Sdm199847 					 * mechanisms for this request.
21095731Sbaban 					 */
21105731Sbaban 					res->retcode = IDMAP_SUCCESS;
21115731Sbaban 				continue;
21125731Sbaban 			}
21136616Sdm199847 			/* Evaluate result type */
21145731Sbaban 			switch (type) {
21155731Sbaban 			case _IDMAP_T_USER:
21165731Sbaban 				if (res->id.idtype == IDMAP_SID)
21175731Sbaban 					res->id.idtype = IDMAP_USID;
21185731Sbaban 				break;
21195731Sbaban 			case _IDMAP_T_GROUP:
21205731Sbaban 				if (res->id.idtype == IDMAP_SID)
21215731Sbaban 					res->id.idtype = IDMAP_GSID;
21225731Sbaban 				break;
21235731Sbaban 			default:
21245731Sbaban 				res->retcode = IDMAP_ERR_SID;
21255731Sbaban 				break;
21265731Sbaban 			}
21275731Sbaban 		}
21285731Sbaban 	}
21295731Sbaban 
21305731Sbaban 	/* AD lookups done. Reset state->ad_nqueries and return */
21315731Sbaban 	state->ad_nqueries = 0;
21324520Snw141292 	return (retcode);
21334520Snw141292 }
21344520Snw141292 
21355696Snw141292 /*
21365696Snw141292  * Convention when processing win2unix requests:
21375696Snw141292  *
21385696Snw141292  * Windows identity:
21395696Snw141292  * req->id1name =
21405696Snw141292  *              winname if given otherwise winname found will be placed
21415696Snw141292  *              here.
21425696Snw141292  * req->id1domain =
21435696Snw141292  *              windomain if given otherwise windomain found will be
21445696Snw141292  *              placed here.
21455696Snw141292  * req->id1.idtype =
21465696Snw141292  *              Either IDMAP_SID/USID/GSID. If this is IDMAP_SID then it'll
21475696Snw141292  *              be set to IDMAP_USID/GSID depending upon whether the
21485696Snw141292  *              given SID is user or group respectively. The user/group-ness
21495696Snw141292  *              is determined either when looking up well-known SIDs table OR
21506616Sdm199847  *              if the SID is found in namecache OR by ad_lookup_one() OR by
21515696Snw141292  *              ad_lookup_batch().
21525696Snw141292  * req->id1..sid.[prefix, rid] =
21535696Snw141292  *              SID if given otherwise SID found will be placed here.
21545696Snw141292  *
21555696Snw141292  * Unix identity:
21565696Snw141292  * req->id2name =
21575696Snw141292  *              unixname found will be placed here.
21585696Snw141292  * req->id2domain =
21595696Snw141292  *              NOT USED
21605696Snw141292  * res->id.idtype =
21615696Snw141292  *              Target type initialized from req->id2.idtype. If
21625696Snw141292  *              it is IDMAP_POSIXID then actual type (IDMAP_UID/GID) found
21635696Snw141292  *              will be placed here.
21645696Snw141292  * res->id..[uid or gid] =
21655696Snw141292  *              UID/GID found will be placed here.
21665696Snw141292  *
21675696Snw141292  * Others:
21685696Snw141292  * res->retcode =
21695696Snw141292  *              Return status for this request will be placed here.
21705696Snw141292  * res->direction =
21715696Snw141292  *              Direction found will be placed here. Direction
21725696Snw141292  *              meaning whether the resultant mapping is valid
21735696Snw141292  *              only from win2unix or bi-directional.
21745696Snw141292  * req->direction =
21755696Snw141292  *              INTERNAL USE. Used by idmapd to set various
21765696Snw141292  *              flags (_IDMAP_F_xxxx) to aid in processing
21775696Snw141292  *              of the request.
21785696Snw141292  * req->id2.idtype =
21795696Snw141292  *              INTERNAL USE. Initially this is the requested target
21805696Snw141292  *              type and is used to initialize res->id.idtype.
21815696Snw141292  *              ad_lookup_batch() uses this field temporarily to store
21825696Snw141292  *              sid_type obtained by the batched AD lookups and after
21835696Snw141292  *              use resets it to IDMAP_NONE to prevent xdr from
21845696Snw141292  *              mis-interpreting the contents of req->id2.
21855696Snw141292  * req->id2..[uid or gid or sid] =
21865696Snw141292  *              NOT USED
21875696Snw141292  */
21885696Snw141292 
21895696Snw141292 /*
21905696Snw141292  * This function does the following:
21915696Snw141292  * 1. Lookup well-known SIDs table.
21925696Snw141292  * 2. Check if the given SID is a local-SID and if so extract UID/GID from it.
21935696Snw141292  * 3. Lookup cache.
21945696Snw141292  * 4. Check if the client does not want new mapping to be allocated
21955696Snw141292  *    in which case this pass is the final pass.
21965696Snw141292  * 5. Set AD lookup flag if it determines that the next stage needs
21975696Snw141292  *    to do AD lookup.
21985696Snw141292  */
21994520Snw141292 idmap_retcode
22006616Sdm199847 sid2pid_first_pass(lookup_state_t *state, idmap_mapping *req,
22015696Snw141292 		idmap_id_res *res)
22025696Snw141292 {
22034520Snw141292 	idmap_retcode	retcode;
22045731Sbaban 	int		wksid;
22055731Sbaban 
22065731Sbaban 	/* Initialize result */
22075731Sbaban 	res->id.idtype = req->id2.idtype;
22085731Sbaban 	res->id.idmap_id_u.uid = SENTINEL_PID;
22095731Sbaban 	res->direction = IDMAP_DIRECTION_UNDEF;
22105731Sbaban 	wksid = 0;
22114520Snw141292 
22125127Sdm199847 	if (EMPTY_STRING(req->id1.idmap_id_u.sid.prefix)) {
22135731Sbaban 		if (req->id1name == NULL) {
22145731Sbaban 			retcode = IDMAP_ERR_ARG;
22155731Sbaban 			goto out;
22165731Sbaban 		}
22175731Sbaban 		/* sanitize sidprefix */
22185731Sbaban 		free(req->id1.idmap_id_u.sid.prefix);
22195731Sbaban 		req->id1.idmap_id_u.sid.prefix = NULL;
22204520Snw141292 	}
22215731Sbaban 
22225731Sbaban 	/* Lookup well-known SIDs table */
22235731Sbaban 	retcode = lookup_wksids_sid2pid(req, res, &wksid);
22244520Snw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
22254520Snw141292 		goto out;
22264520Snw141292 
22275731Sbaban 	/* Check if this is a localsid */
22285731Sbaban 	if (!wksid) {
22295731Sbaban 		retcode = lookup_localsid2pid(req, res);
22305731Sbaban 		if (retcode != IDMAP_ERR_NOTFOUND)
22315731Sbaban 			goto out;
22325731Sbaban 	}
22335731Sbaban 
22345731Sbaban 	/* Lookup cache */
22356616Sdm199847 	retcode = lookup_cache_sid2pid(state->cache, req, res);
22364520Snw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
22374520Snw141292 		goto out;
22384520Snw141292 
22394520Snw141292 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req) || AVOID_NAMESERVICE(req)) {
22406386Sjp151216 		retcode = IDMAP_ERR_NONEGENERATED;
22414520Snw141292 		goto out;
22424520Snw141292 	}
22434520Snw141292 
22444520Snw141292 	/*
22455731Sbaban 	 * Failed to find non-expired entry in cache. Next step is
22465731Sbaban 	 * to determine if this request needs to be batched for AD lookup.
22475731Sbaban 	 *
22485731Sbaban 	 * At this point we have either sid or winname or both. If we don't
22495731Sbaban 	 * have both then lookup name_cache for the sid or winname
22505731Sbaban 	 * whichever is missing. If not found then this request will be
22515731Sbaban 	 * batched for AD lookup.
22524520Snw141292 	 */
22536616Sdm199847 	retcode = lookup_name_cache(state->cache, req, res);
22545731Sbaban 	if (retcode != IDMAP_SUCCESS && retcode != IDMAP_ERR_NOTFOUND)
22555731Sbaban 		goto out;
22564520Snw141292 
22574520Snw141292 	/*
22585731Sbaban 	 * Set the flag to indicate that we are not done yet so that
22595731Sbaban 	 * subsequent passes considers this request for name-based
22605731Sbaban 	 * mapping and ephemeral mapping.
22614520Snw141292 	 */
22625731Sbaban 	state->sid2pid_done = FALSE;
22635731Sbaban 	req->direction |= _IDMAP_F_NOTDONE;
22645731Sbaban 
22655731Sbaban 	/*
22665731Sbaban 	 * Even if we have both sid and winname, we still may need to batch
22675731Sbaban 	 * this request for AD lookup if we don't have unixname and
22685731Sbaban 	 * directory-based name mapping (AD or mixed) is enabled.
22695731Sbaban 	 * We avoid AD lookup for well-known SIDs because they don't have
22705731Sbaban 	 * regular AD objects.
22715731Sbaban 	 */
22725731Sbaban 	if (retcode != IDMAP_SUCCESS ||
22735731Sbaban 	    (!wksid && req->id2name == NULL &&
22745731Sbaban 	    AD_OR_MIXED_MODE(res->id.idtype, state))) {
22754520Snw141292 		retcode = IDMAP_SUCCESS;
22765731Sbaban 		req->direction |= _IDMAP_F_LOOKUP_AD;
22774520Snw141292 		state->ad_nqueries++;
22786616Sdm199847 	} else if (NLDAP_MODE(res->id.idtype, state)) {
22796616Sdm199847 		req->direction |= _IDMAP_F_LOOKUP_NLDAP;
22806616Sdm199847 		state->nldap_nqueries++;
22814520Snw141292 	}
22824520Snw141292 
22834520Snw141292 
22844520Snw141292 out:
22854520Snw141292 	res->retcode = idmap_stat4prot(retcode);
22865731Sbaban 	/*
22875731Sbaban 	 * If we are done and there was an error then set fallback pid
22885731Sbaban 	 * in the result.
22895731Sbaban 	 */
22905731Sbaban 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
22915731Sbaban 		res->id.idmap_id_u.uid = UID_NOBODY;
22924520Snw141292 	return (retcode);
22934520Snw141292 }
22944520Snw141292 
22954520Snw141292 /*
22964520Snw141292  * Generate SID using the following convention
22974520Snw141292  * 	<machine-sid-prefix>-<1000 + uid>
22984520Snw141292  * 	<machine-sid-prefix>-<2^31 + gid>
22994520Snw141292  */
23005696Snw141292 static
23015696Snw141292 idmap_retcode
23026386Sjp151216 generate_localsid(idmap_mapping *req, idmap_id_res *res, int is_user,
23036386Sjp151216 		int fallback)
23045696Snw141292 {
23055731Sbaban 	free(res->id.idmap_id_u.sid.prefix);
23065731Sbaban 	res->id.idmap_id_u.sid.prefix = NULL;
23075731Sbaban 
23085731Sbaban 	/*
23095731Sbaban 	 * Diagonal mapping for localSIDs not supported because of the
23105731Sbaban 	 * way we generate localSIDs.
23115731Sbaban 	 */
23125731Sbaban 	if (is_user && res->id.idtype == IDMAP_GSID)
23135731Sbaban 		return (IDMAP_ERR_NOMAPPING);
23145731Sbaban 	if (!is_user && res->id.idtype == IDMAP_USID)
23155731Sbaban 		return (IDMAP_ERR_NOMAPPING);
23165731Sbaban 
23175731Sbaban 	/* Skip 1000 UIDs */
23185731Sbaban 	if (is_user && req->id1.idmap_id_u.uid >
23195731Sbaban 	    (INT32_MAX - LOCALRID_MIN))
23205731Sbaban 		return (IDMAP_ERR_NOMAPPING);
23215731Sbaban 
23225731Sbaban 	RDLOCK_CONFIG();
23235731Sbaban 	/*
23245731Sbaban 	 * machine_sid is never NULL because if it is we won't be here.
23255731Sbaban 	 * No need to assert because stdrup(NULL) will core anyways.
23265731Sbaban 	 */
23275731Sbaban 	res->id.idmap_id_u.sid.prefix =
23285731Sbaban 	    strdup(_idmapdstate.cfg->pgcfg.machine_sid);
23295731Sbaban 	if (res->id.idmap_id_u.sid.prefix == NULL) {
23304520Snw141292 		UNLOCK_CONFIG();
23315731Sbaban 		idmapdlog(LOG_ERR, "Out of memory");
23325731Sbaban 		return (IDMAP_ERR_MEMORY);
23334520Snw141292 	}
23345731Sbaban 	UNLOCK_CONFIG();
23355731Sbaban 	res->id.idmap_id_u.sid.rid =
23365731Sbaban 	    (is_user) ? req->id1.idmap_id_u.uid + LOCALRID_MIN :
23375731Sbaban 	    req->id1.idmap_id_u.gid + INT32_MAX + 1;
23385731Sbaban 	res->direction = IDMAP_DIRECTION_BI;
23395731Sbaban 	if (res->id.idtype == IDMAP_SID)
23405731Sbaban 		res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
23415731Sbaban 
23426386Sjp151216 	if (!fallback && req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
23436386Sjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_LOCAL_SID;
23446386Sjp151216 		res->info.src = IDMAP_MAP_SRC_ALGORITHMIC;
23456386Sjp151216 	}
23466386Sjp151216 
23475731Sbaban 	/*
23485731Sbaban 	 * Don't update name_cache because local sids don't have
23495731Sbaban 	 * valid windows names.
23505731Sbaban 	 */
23515731Sbaban 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
23525731Sbaban 	return (IDMAP_SUCCESS);
23534520Snw141292 }
23544520Snw141292 
23555696Snw141292 static
23565696Snw141292 idmap_retcode
23575696Snw141292 lookup_localsid2pid(idmap_mapping *req, idmap_id_res *res)
23585696Snw141292 {
23594520Snw141292 	char		*sidprefix;
23604520Snw141292 	uint32_t	rid;
23614520Snw141292 	int		s;
23624520Snw141292 
23634520Snw141292 	/*
23644520Snw141292 	 * If the sidprefix == localsid then UID = last RID - 1000 or
23654520Snw141292 	 * GID = last RID - 2^31.
23664520Snw141292 	 */
23675731Sbaban 	if ((sidprefix = req->id1.idmap_id_u.sid.prefix) == NULL)
23685731Sbaban 		/* This means we are looking up by winname */
23695731Sbaban 		return (IDMAP_ERR_NOTFOUND);
23704520Snw141292 	rid = req->id1.idmap_id_u.sid.rid;
23714520Snw141292 
23724520Snw141292 	RDLOCK_CONFIG();
23735696Snw141292 	s = (_idmapdstate.cfg->pgcfg.machine_sid) ?
23745696Snw141292 	    strcasecmp(sidprefix, _idmapdstate.cfg->pgcfg.machine_sid) : 1;
23754520Snw141292 	UNLOCK_CONFIG();
23764520Snw141292 
23775731Sbaban 	/*
23785731Sbaban 	 * If the given sidprefix does not match machine_sid then this is
23795731Sbaban 	 * not a local SID.
23805731Sbaban 	 */
23815731Sbaban 	if (s != 0)
23825731Sbaban 		return (IDMAP_ERR_NOTFOUND);
23835731Sbaban 
23845731Sbaban 	switch (res->id.idtype) {
23855731Sbaban 	case IDMAP_UID:
23865731Sbaban 		if (rid > INT32_MAX || rid < LOCALRID_MIN)
23875731Sbaban 			return (IDMAP_ERR_ARG);
23885731Sbaban 		res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
23895731Sbaban 		break;
23905731Sbaban 	case IDMAP_GID:
23915731Sbaban 		if (rid <= INT32_MAX)
23925731Sbaban 			return (IDMAP_ERR_ARG);
23935731Sbaban 		res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
23945731Sbaban 		break;
23955731Sbaban 	case IDMAP_POSIXID:
23965731Sbaban 		if (rid > INT32_MAX) {
23974520Snw141292 			res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
23984520Snw141292 			res->id.idtype = IDMAP_GID;
23995731Sbaban 		} else if (rid < LOCALRID_MIN) {
24005731Sbaban 			return (IDMAP_ERR_ARG);
24015731Sbaban 		} else {
24025731Sbaban 			res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
24035731Sbaban 			res->id.idtype = IDMAP_UID;
24044520Snw141292 		}
24055731Sbaban 		break;
24065731Sbaban 	default:
24075731Sbaban 		return (IDMAP_ERR_NOTSUPPORTED);
24084520Snw141292 	}
24096386Sjp151216 	if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
24106386Sjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_LOCAL_SID;
24116386Sjp151216 		res->info.src = IDMAP_MAP_SRC_ALGORITHMIC;
24126386Sjp151216 	}
24135731Sbaban 	return (IDMAP_SUCCESS);
24144520Snw141292 }
24154520Snw141292 
24165731Sbaban /*
24175731Sbaban  * Name service lookup by unixname to get pid
24185731Sbaban  */
24195696Snw141292 static
24205696Snw141292 idmap_retcode
24215731Sbaban ns_lookup_byname(const char *name, const char *lower_name, idmap_id *id)
24225696Snw141292 {
24235696Snw141292 	struct passwd	pwd, *pwdp;
24245696Snw141292 	struct group	grp, *grpp;
24254520Snw141292 	char		buf[1024];
24264520Snw141292 	int		errnum;
24274520Snw141292 	const char	*me = "ns_lookup_byname";
24284520Snw141292 
24295731Sbaban 	switch (id->idtype) {
24305731Sbaban 	case IDMAP_UID:
24315696Snw141292 		pwdp = getpwnam_r(name, &pwd, buf, sizeof (buf));
24325731Sbaban 		if (pwdp == NULL && errno == 0 && lower_name != NULL &&
24335696Snw141292 		    name != lower_name && strcmp(name, lower_name) != 0)
24345696Snw141292 			pwdp = getpwnam_r(lower_name, &pwd, buf, sizeof (buf));
24355696Snw141292 		if (pwdp == NULL) {
24364520Snw141292 			errnum = errno;
24374520Snw141292 			idmapdlog(LOG_WARNING,
24385696Snw141292 			    "%s: getpwnam_r(%s) failed (%s).",
24395696Snw141292 			    me, name, errnum ? strerror(errnum) : "not found");
24404520Snw141292 			if (errnum == 0)
24414520Snw141292 				return (IDMAP_ERR_NOTFOUND);
24424520Snw141292 			else
24434520Snw141292 				return (IDMAP_ERR_INTERNAL);
24444520Snw141292 		}
24455731Sbaban 		id->idmap_id_u.uid = pwd.pw_uid;
24465731Sbaban 		break;
24475731Sbaban 	case IDMAP_GID:
24485696Snw141292 		grpp = getgrnam_r(name, &grp, buf, sizeof (buf));
24495731Sbaban 		if (grpp == NULL && errno == 0 && lower_name != NULL &&
24505696Snw141292 		    name != lower_name && strcmp(name, lower_name) != 0)
24515696Snw141292 			grpp = getgrnam_r(lower_name, &grp, buf, sizeof (buf));
24525696Snw141292 		if (grpp == NULL) {
24534520Snw141292 			errnum = errno;
24544520Snw141292 			idmapdlog(LOG_WARNING,
24555696Snw141292 			    "%s: getgrnam_r(%s) failed (%s).",
24565696Snw141292 			    me, name, errnum ? strerror(errnum) : "not found");
24574520Snw141292 			if (errnum == 0)
24584520Snw141292 				return (IDMAP_ERR_NOTFOUND);
24594520Snw141292 			else
24604520Snw141292 				return (IDMAP_ERR_INTERNAL);
24614520Snw141292 		}
24625731Sbaban 		id->idmap_id_u.gid = grp.gr_gid;
24635731Sbaban 		break;
24645731Sbaban 	default:
24655731Sbaban 		return (IDMAP_ERR_ARG);
24664520Snw141292 	}
24674520Snw141292 	return (IDMAP_SUCCESS);
24684520Snw141292 }
24694520Snw141292 
24705731Sbaban 
24715731Sbaban /*
24725731Sbaban  * Name service lookup by pid to get unixname
24735731Sbaban  */
24745731Sbaban static
24755731Sbaban idmap_retcode
24765731Sbaban ns_lookup_bypid(uid_t pid, int is_user, char **unixname)
24775731Sbaban {
24785731Sbaban 	struct passwd	pwd;
24795731Sbaban 	struct group	grp;
24805731Sbaban 	char		buf[1024];
24815731Sbaban 	int		errnum;
24825731Sbaban 	const char	*me = "ns_lookup_bypid";
24835731Sbaban 
24845731Sbaban 	if (is_user) {
24855731Sbaban 		errno = 0;
24865731Sbaban 		if (getpwuid_r(pid, &pwd, buf, sizeof (buf)) == NULL) {
24875731Sbaban 			errnum = errno;
24885731Sbaban 			idmapdlog(LOG_WARNING,
24895731Sbaban 			    "%s: getpwuid_r(%u) failed (%s).",
24905731Sbaban 			    me, pid, errnum ? strerror(errnum) : "not found");
24915731Sbaban 			if (errnum == 0)
24925731Sbaban 				return (IDMAP_ERR_NOTFOUND);
24935731Sbaban 			else
24945731Sbaban 				return (IDMAP_ERR_INTERNAL);
24955731Sbaban 		}
24965731Sbaban 		*unixname = strdup(pwd.pw_name);
24975731Sbaban 	} else {
24985731Sbaban 		errno = 0;
24995731Sbaban 		if (getgrgid_r(pid, &grp, buf, sizeof (buf)) == NULL) {
25005731Sbaban 			errnum = errno;
25015731Sbaban 			idmapdlog(LOG_WARNING,
25025731Sbaban 			    "%s: getgrgid_r(%u) failed (%s).",
25035731Sbaban 			    me, pid, errnum ? strerror(errnum) : "not found");
25045731Sbaban 			if (errnum == 0)
25055731Sbaban 				return (IDMAP_ERR_NOTFOUND);
25065731Sbaban 			else
25075731Sbaban 				return (IDMAP_ERR_INTERNAL);
25085731Sbaban 		}
25095731Sbaban 		*unixname = strdup(grp.gr_name);
25105731Sbaban 	}
25115731Sbaban 	if (*unixname == NULL)
25125731Sbaban 		return (IDMAP_ERR_MEMORY);
25135731Sbaban 	return (IDMAP_SUCCESS);
25145731Sbaban }
25155731Sbaban 
25164520Snw141292 /*
25174520Snw141292  * Name-based mapping
25184520Snw141292  *
25194520Snw141292  * Case 1: If no rule matches do ephemeral
25204520Snw141292  *
25214520Snw141292  * Case 2: If rule matches and unixname is "" then return no mapping.
25224520Snw141292  *
25234520Snw141292  * Case 3: If rule matches and unixname is specified then lookup name
25244520Snw141292  *  service using the unixname. If unixname not found then return no mapping.
25254520Snw141292  *
25264520Snw141292  * Case 4: If rule matches and unixname is * then lookup name service
25274520Snw141292  *  using winname as the unixname. If unixname not found then process
25284520Snw141292  *  other rules using the lookup order. If no other rule matches then do
25294520Snw141292  *  ephemeral. Otherwise, based on the matched rule do Case 2 or 3 or 4.
25304520Snw141292  *  This allows us to specify a fallback unixname per _domain_ or no mapping
25314520Snw141292  *  instead of the default behaviour of doing ephemeral mapping.
25324520Snw141292  *
25334520Snw141292  * Example 1:
25344520Snw141292  * *@sfbay == *
25354520Snw141292  * If looking up windows users foo@sfbay and foo does not exists in
25364520Snw141292  * the name service then foo@sfbay will be mapped to an ephemeral id.
25374520Snw141292  *
25384520Snw141292  * Example 2:
25394520Snw141292  * *@sfbay == *
25404520Snw141292  * *@sfbay => guest
25414520Snw141292  * If looking up windows users foo@sfbay and foo does not exists in
25424520Snw141292  * the name service then foo@sfbay will be mapped to guest.
25434520Snw141292  *
25444520Snw141292  * Example 3:
25454520Snw141292  * *@sfbay == *
25464520Snw141292  * *@sfbay => ""
25474520Snw141292  * If looking up windows users foo@sfbay and foo does not exists in
25484520Snw141292  * the name service then we will return no mapping for foo@sfbay.
25494520Snw141292  *
25504520Snw141292  */
25515696Snw141292 static
25525696Snw141292 idmap_retcode
25536616Sdm199847 name_based_mapping_sid2pid(lookup_state_t *state,
25546616Sdm199847 		idmap_mapping *req, idmap_id_res *res)
25555696Snw141292 {
25565696Snw141292 	const char	*unixname, *windomain;
25575696Snw141292 	char		*sql = NULL, *errmsg = NULL, *lower_winname = NULL;
25584520Snw141292 	idmap_retcode	retcode;
25595696Snw141292 	char		*end, *lower_unixname, *winname;
25604520Snw141292 	const char	**values;
25614520Snw141292 	sqlite_vm	*vm = NULL;
25625696Snw141292 	int		ncol, r, i, is_user, is_wuser;
25636386Sjp151216 	idmap_namerule	*rule = &res->info.how.idmap_how_u.rule;
25646386Sjp151216 	int		direction;
25654520Snw141292 	const char	*me = "name_based_mapping_sid2pid";
25664520Snw141292 
25675731Sbaban 	assert(req->id1name != NULL); /* We have winname */
25685731Sbaban 	assert(req->id2name == NULL); /* We don't have unixname */
25695731Sbaban 
25705064Sdm199847 	winname = req->id1name;
25715064Sdm199847 	windomain = req->id1domain;
25725696Snw141292 
25735696Snw141292 	switch (req->id1.idtype) {
25745696Snw141292 	case IDMAP_USID:
25755696Snw141292 		is_wuser = 1;
25765696Snw141292 		break;
25775696Snw141292 	case IDMAP_GSID:
25785696Snw141292 		is_wuser = 0;
25795696Snw141292 		break;
25805696Snw141292 	default:
25815731Sbaban 		idmapdlog(LOG_ERR, "%s: Unable to determine if the "
25825731Sbaban 		    "given Windows id is user or group.", me);
25835696Snw141292 		return (IDMAP_ERR_INTERNAL);
25845696Snw141292 	}
25855696Snw141292 
25865731Sbaban 	switch (res->id.idtype) {
25875696Snw141292 	case IDMAP_UID:
25885696Snw141292 		is_user = 1;
25895696Snw141292 		break;
25905696Snw141292 	case IDMAP_GID:
25915696Snw141292 		is_user = 0;
25925696Snw141292 		break;
25935696Snw141292 	case IDMAP_POSIXID:
25945696Snw141292 		is_user = is_wuser;
25955696Snw141292 		res->id.idtype = is_user ? IDMAP_UID : IDMAP_GID;
25965696Snw141292 		break;
25975696Snw141292 	}
25984520Snw141292 
25994520Snw141292 	i = 0;
26006616Sdm199847 	if (windomain == NULL)
26014864Sbaban 		windomain = "";
26026950Sbaban 	else if (state->defdom != NULL &&
26036950Sbaban 	    strcasecmp(state->defdom, windomain) == 0)
26046616Sdm199847 		i = 1;
26054520Snw141292 
26065696Snw141292 	if ((lower_winname = tolower_u8(winname)) == NULL)
26075696Snw141292 		lower_winname = winname;    /* hope for the best */
26084520Snw141292 	sql = sqlite_mprintf(
26096386Sjp151216 	    "SELECT unixname, u2w_order, winname_display, windomain, is_nt4 "
26106386Sjp151216 	    "FROM namerules WHERE "
26115696Snw141292 	    "w2u_order > 0 AND is_user = %d AND is_wuser = %d AND "
26125696Snw141292 	    "(winname = %Q OR winname = '*') AND "
26135696Snw141292 	    "(windomain = %Q OR windomain = '*' %s) "
26145696Snw141292 	    "ORDER BY w2u_order ASC;",
26155696Snw141292 	    is_user, is_wuser, lower_winname, windomain,
26165696Snw141292 	    i ? "OR windomain ISNULL OR windomain = ''" : "");
26174520Snw141292 	if (sql == NULL) {
26184520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
26194520Snw141292 		retcode = IDMAP_ERR_MEMORY;
26204520Snw141292 		goto out;
26214520Snw141292 	}
26224520Snw141292 
26236616Sdm199847 	if (sqlite_compile(state->db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
26244520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
26255696Snw141292 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
26265696Snw141292 		    CHECK_NULL(errmsg));
26274520Snw141292 		sqlite_freemem(errmsg);
26284520Snw141292 		goto out;
26294520Snw141292 	}
26304520Snw141292 
26316386Sjp151216 	for (;;) {
26324520Snw141292 		r = sqlite_step(vm, &ncol, &values, NULL);
26334884Sjp151216 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
26344884Sjp151216 
26354884Sjp151216 		if (r == SQLITE_ROW) {
26366386Sjp151216 			if (ncol < 5) {
26374520Snw141292 				retcode = IDMAP_ERR_INTERNAL;
26384520Snw141292 				goto out;
26394520Snw141292 			}
26404520Snw141292 			if (values[0] == NULL) {
26414520Snw141292 				retcode = IDMAP_ERR_INTERNAL;
26424520Snw141292 				goto out;
26434520Snw141292 			}
26444520Snw141292 
26456386Sjp151216 			if (values[1] != NULL)
26466386Sjp151216 				direction =
26476386Sjp151216 				    (strtol(values[1], &end, 10) == 0)?
26486386Sjp151216 				    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
26496386Sjp151216 			else
26506386Sjp151216 				direction = IDMAP_DIRECTION_W2U;
26516386Sjp151216 
26524520Snw141292 			if (EMPTY_NAME(values[0])) {
26536386Sjp151216 				idmap_namerule_set(rule, values[3], values[2],
26546386Sjp151216 				    values[0], is_wuser, is_user,
26556386Sjp151216 				    strtol(values[4], &end, 10),
26566386Sjp151216 				    direction);
26574520Snw141292 				retcode = IDMAP_ERR_NOMAPPING;
26584520Snw141292 				goto out;
26594520Snw141292 			}
26606386Sjp151216 
26616386Sjp151216 			if (values[0][0] == '*') {
26626386Sjp151216 				unixname = winname;
26636386Sjp151216 				lower_unixname = lower_winname;
26646386Sjp151216 			} else {
26656386Sjp151216 				unixname = values[0];
26666386Sjp151216 				lower_unixname = NULL;
26676386Sjp151216 			}
26686386Sjp151216 
26695731Sbaban 			retcode = ns_lookup_byname(unixname, lower_unixname,
26705731Sbaban 			    &res->id);
26714520Snw141292 			if (retcode == IDMAP_ERR_NOTFOUND) {
26726386Sjp151216 				if (values[0][0] == '*')
26734520Snw141292 					/* Case 4 */
26744520Snw141292 					continue;
26756386Sjp151216 				else {
26764520Snw141292 					/* Case 3 */
26776386Sjp151216 					idmap_namerule_set(rule, values[3],
26786386Sjp151216 					    values[2], values[0], is_wuser,
26796386Sjp151216 					    is_user,
26806386Sjp151216 					    strtol(values[4], &end, 10),
26816386Sjp151216 					    direction);
26824520Snw141292 					retcode = IDMAP_ERR_NOMAPPING;
26836386Sjp151216 				}
26844520Snw141292 			}
26854520Snw141292 			goto out;
26864520Snw141292 		} else if (r == SQLITE_DONE) {
26874520Snw141292 			retcode = IDMAP_ERR_NOTFOUND;
26884520Snw141292 			goto out;
26894520Snw141292 		} else {
26904520Snw141292 			(void) sqlite_finalize(vm, &errmsg);
26914520Snw141292 			vm = NULL;
26925696Snw141292 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
26935696Snw141292 			    CHECK_NULL(errmsg));
26944520Snw141292 			sqlite_freemem(errmsg);
26954520Snw141292 			retcode = IDMAP_ERR_INTERNAL;
26964520Snw141292 			goto out;
26974520Snw141292 		}
26984520Snw141292 	}
26994520Snw141292 
27004520Snw141292 out:
27016386Sjp151216 	if (sql != NULL)
27026386Sjp151216 		sqlite_freemem(sql);
27036386Sjp151216 	res->info.how.map_type = IDMAP_MAP_TYPE_RULE_BASED;
27044520Snw141292 	if (retcode == IDMAP_SUCCESS) {
27054864Sbaban 		if (values[1] != NULL)
27064520Snw141292 			res->direction =
27074644Sbaban 			    (strtol(values[1], &end, 10) == 0)?
27084644Sbaban 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
27094520Snw141292 		else
27104644Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
27116386Sjp151216 
27125064Sdm199847 		req->id2name = strdup(unixname);
27136616Sdm199847 		if (req->id2name == NULL) {
27146616Sdm199847 			retcode = IDMAP_ERR_MEMORY;
27156616Sdm199847 		}
27166616Sdm199847 	}
27176616Sdm199847 
27186616Sdm199847 	if (retcode == IDMAP_SUCCESS) {
27196386Sjp151216 		idmap_namerule_set(rule, values[3], values[2],
27206386Sjp151216 		    values[0], is_wuser, is_user, strtol(values[4], &end, 10),
27216386Sjp151216 		    res->direction);
27226386Sjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
27234520Snw141292 	}
27246616Sdm199847 
27255696Snw141292 	if (lower_winname != NULL && lower_winname != winname)
27265696Snw141292 		free(lower_winname);
27274864Sbaban 	if (vm != NULL)
27284520Snw141292 		(void) sqlite_finalize(vm, NULL);
27294520Snw141292 	return (retcode);
27304520Snw141292 }
27314520Snw141292 
27324520Snw141292 static
27334520Snw141292 int
27344520Snw141292 get_next_eph_uid(uid_t *next_uid)
27354520Snw141292 {
27364520Snw141292 	uid_t uid;
27374520Snw141292 	gid_t gid;
27384520Snw141292 	int err;
27394520Snw141292 
27404520Snw141292 	*next_uid = (uid_t)-1;
27414520Snw141292 	uid = _idmapdstate.next_uid++;
27424520Snw141292 	if (uid >= _idmapdstate.limit_uid) {
27434520Snw141292 		if ((err = allocids(0, 8192, &uid, 0, &gid)) != 0)
27444520Snw141292 			return (err);
27454520Snw141292 
27464520Snw141292 		_idmapdstate.limit_uid = uid + 8192;
27474520Snw141292 		_idmapdstate.next_uid = uid;
27484520Snw141292 	}
27494520Snw141292 	*next_uid = uid;
27504520Snw141292 
27514520Snw141292 	return (0);
27524520Snw141292 }
27534520Snw141292 
27544520Snw141292 static
27554520Snw141292 int
27564520Snw141292 get_next_eph_gid(gid_t *next_gid)
27574520Snw141292 {
27584520Snw141292 	uid_t uid;
27594520Snw141292 	gid_t gid;
27604520Snw141292 	int err;
27614520Snw141292 
27624520Snw141292 	*next_gid = (uid_t)-1;
27634520Snw141292 	gid = _idmapdstate.next_gid++;
27644520Snw141292 	if (gid >= _idmapdstate.limit_gid) {
27654520Snw141292 		if ((err = allocids(0, 0, &uid, 8192, &gid)) != 0)
27664520Snw141292 			return (err);
27674520Snw141292 
27684520Snw141292 		_idmapdstate.limit_gid = gid + 8192;
27694520Snw141292 		_idmapdstate.next_gid = gid;
27704520Snw141292 	}
27714520Snw141292 	*next_gid = gid;
27724520Snw141292 
27734520Snw141292 	return (0);
27744520Snw141292 }
27754520Snw141292 
27764864Sbaban static
27774864Sbaban int
27785696Snw141292 gethash(const char *str, uint32_t num, uint_t htsize)
27795696Snw141292 {
27804864Sbaban 	uint_t  hval, i, len;
27814864Sbaban 
27824864Sbaban 	if (str == NULL)
27834864Sbaban 		return (0);
27844864Sbaban 	for (len = strlen(str), hval = 0, i = 0; i < len; i++) {
27854864Sbaban 		hval += str[i];
27864864Sbaban 		hval += (hval << 10);
27874864Sbaban 		hval ^= (hval >> 6);
27884864Sbaban 	}
27894864Sbaban 	for (str = (const char *)&num, i = 0; i < sizeof (num); i++) {
27904864Sbaban 		hval += str[i];
27914864Sbaban 		hval += (hval << 10);
27924864Sbaban 		hval ^= (hval >> 6);
27934864Sbaban 	}
27944864Sbaban 	hval += (hval << 3);
27954864Sbaban 	hval ^= (hval >> 11);
27964864Sbaban 	hval += (hval << 15);
27974864Sbaban 	return (hval % htsize);
27984864Sbaban }
27994864Sbaban 
28004864Sbaban static
28014864Sbaban int
28024864Sbaban get_from_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid,
28035696Snw141292 		uid_t *pid)
28045696Snw141292 {
28054864Sbaban 	uint_t		next, key;
28064864Sbaban 	uint_t		htsize = state->sid_history_size;
28074864Sbaban 	idmap_sid	*sid;
28084864Sbaban 
28094864Sbaban 	next = gethash(prefix, rid, htsize);
28104864Sbaban 	while (next != htsize) {
28114864Sbaban 		key = state->sid_history[next].key;
28124864Sbaban 		if (key == htsize)
28134864Sbaban 			return (0);
28144864Sbaban 		sid = &state->batch->idmap_mapping_batch_val[key].id1.
28154864Sbaban 		    idmap_id_u.sid;
28164864Sbaban 		if (sid->rid == rid && strcmp(sid->prefix, prefix) == 0) {
28174864Sbaban 			*pid = state->result->ids.ids_val[key].id.
28184864Sbaban 			    idmap_id_u.uid;
28194864Sbaban 			return (1);
28204864Sbaban 		}
28214864Sbaban 		next = state->sid_history[next].next;
28224864Sbaban 	}
28234864Sbaban 	return (0);
28244864Sbaban }
28254864Sbaban 
28264864Sbaban static
28274864Sbaban void
28285696Snw141292 add_to_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid)
28295696Snw141292 {
28304864Sbaban 	uint_t		hash, next;
28314864Sbaban 	uint_t		htsize = state->sid_history_size;
28324864Sbaban 
28334864Sbaban 	hash = next = gethash(prefix, rid, htsize);
28344864Sbaban 	while (state->sid_history[next].key != htsize) {
28354864Sbaban 		next++;
28364864Sbaban 		next %= htsize;
28374864Sbaban 	}
28384864Sbaban 	state->sid_history[next].key = state->curpos;
28394864Sbaban 	if (hash == next)
28404864Sbaban 		return;
28414864Sbaban 	state->sid_history[next].next = state->sid_history[hash].next;
28424864Sbaban 	state->sid_history[hash].next = next;
28434864Sbaban }
28444520Snw141292 
28455731Sbaban void
28465731Sbaban cleanup_lookup_state(lookup_state_t *state)
28475731Sbaban {
28485731Sbaban 	free(state->sid_history);
28495731Sbaban 	free(state->ad_unixuser_attr);
28505731Sbaban 	free(state->ad_unixgroup_attr);
28516616Sdm199847 	free(state->nldap_winname_attr);
28526616Sdm199847 	free(state->defdom);
28535731Sbaban }
28545731Sbaban 
28554520Snw141292 /* ARGSUSED */
28564520Snw141292 static
28574520Snw141292 idmap_retcode
28586616Sdm199847 dynamic_ephemeral_mapping(lookup_state_t *state,
28595696Snw141292 		idmap_mapping *req, idmap_id_res *res)
28605696Snw141292 {
28614520Snw141292 
28624520Snw141292 	uid_t		next_pid;
28634520Snw141292 
28644864Sbaban 	res->direction = IDMAP_DIRECTION_BI;
28654864Sbaban 
28666386Sjp151216 	if (IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
28676386Sjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
28686386Sjp151216 		res->info.src = IDMAP_MAP_SRC_CACHE;
28694864Sbaban 		return (IDMAP_SUCCESS);
28706386Sjp151216 	}
28714864Sbaban 
28724864Sbaban 	if (state->sid_history != NULL &&
28734864Sbaban 	    get_from_sid_history(state, req->id1.idmap_id_u.sid.prefix,
28744864Sbaban 	    req->id1.idmap_id_u.sid.rid, &next_pid)) {
28754864Sbaban 		res->id.idmap_id_u.uid = next_pid;
28766386Sjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
28776386Sjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
28784864Sbaban 		return (IDMAP_SUCCESS);
28794864Sbaban 	}
28804864Sbaban 
28814864Sbaban 	if (res->id.idtype == IDMAP_UID) {
28824520Snw141292 		if (get_next_eph_uid(&next_pid) != 0)
28834520Snw141292 			return (IDMAP_ERR_INTERNAL);
28844520Snw141292 		res->id.idmap_id_u.uid = next_pid;
28854520Snw141292 	} else {
28864520Snw141292 		if (get_next_eph_gid(&next_pid) != 0)
28874520Snw141292 			return (IDMAP_ERR_INTERNAL);
28884520Snw141292 		res->id.idmap_id_u.gid = next_pid;
28894520Snw141292 	}
28904520Snw141292 
28916386Sjp151216 	res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
28926386Sjp151216 	res->info.src = IDMAP_MAP_SRC_NEW;
28934864Sbaban 	if (state->sid_history != NULL)
28944864Sbaban 		add_to_sid_history(state, req->id1.idmap_id_u.sid.prefix,
28954864Sbaban 		    req->id1.idmap_id_u.sid.rid);
28964864Sbaban 
28974520Snw141292 	return (IDMAP_SUCCESS);
28984520Snw141292 }
28994520Snw141292 
29004520Snw141292 idmap_retcode
29016616Sdm199847 sid2pid_second_pass(lookup_state_t *state,
29025696Snw141292 		idmap_mapping *req, idmap_id_res *res)
29035696Snw141292 {
29044520Snw141292 	idmap_retcode	retcode;
29054520Snw141292 
29064520Snw141292 	/* Check if second pass is needed */
29075731Sbaban 	if (ARE_WE_DONE(req->direction))
29084520Snw141292 		return (res->retcode);
29094520Snw141292 
29104520Snw141292 	/* Get status from previous pass */
29115731Sbaban 	retcode = res->retcode;
29127031Snw141292 	if (retcode != IDMAP_SUCCESS && state->eph_map_unres_sids &&
29137031Snw141292 	    !EMPTY_STRING(req->id1.idmap_id_u.sid.prefix) &&
29147031Snw141292 	    EMPTY_STRING(req->id1name)) {
29157031Snw141292 		/*
29167031Snw141292 		 * We are asked to map an unresolvable SID to a UID or
29177031Snw141292 		 * GID, but, which?  We'll treat all unresolvable SIDs
29187031Snw141292 		 * as users unless the caller specified which of a UID
29197031Snw141292 		 * or GID they want.
29207031Snw141292 		 */
2921*7818SNicolas.Williams@Sun.COM 		if (req->id1.idtype == IDMAP_SID)
2922*7818SNicolas.Williams@Sun.COM 			req->id1.idtype = IDMAP_USID;
29237031Snw141292 		if (res->id.idtype == IDMAP_POSIXID)
29247031Snw141292 			res->id.idtype = IDMAP_UID;
29257031Snw141292 		goto do_eph;
29267031Snw141292 	}
29275731Sbaban 	if (retcode != IDMAP_SUCCESS)
29285731Sbaban 		goto out;
29295731Sbaban 
29305731Sbaban 	/*
29315731Sbaban 	 * If directory-based name mapping is enabled then the unixname
29325731Sbaban 	 * may already have been retrieved from the AD object (AD-mode or
29335731Sbaban 	 * mixed-mode) or from native LDAP object (nldap-mode) -- done.
29345731Sbaban 	 */
29355731Sbaban 	if (req->id2name != NULL) {
29365731Sbaban 		assert(res->id.idtype != IDMAP_POSIXID);
29375731Sbaban 		if (AD_MODE(res->id.idtype, state))
29385731Sbaban 			res->direction = IDMAP_DIRECTION_BI;
29395731Sbaban 		else if (NLDAP_MODE(res->id.idtype, state))
29405731Sbaban 			res->direction = IDMAP_DIRECTION_BI;
29415731Sbaban 		else if (MIXED_MODE(res->id.idtype, state))
29425731Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
29435731Sbaban 
29445731Sbaban 		/*
29455731Sbaban 		 * Special case: (1) If the ad_unixuser_attr and
29465731Sbaban 		 * ad_unixgroup_attr uses the same attribute
29475731Sbaban 		 * name and (2) if this is a diagonal mapping
29485731Sbaban 		 * request and (3) the unixname has been retrieved
29495731Sbaban 		 * from the AD object -- then we ignore it and fallback
29505731Sbaban 		 * to name-based mapping rules and ephemeral mapping
29515731Sbaban 		 *
29525731Sbaban 		 * Example:
29535731Sbaban 		 *  Properties:
29545731Sbaban 		 *    config/ad_unixuser_attr = "unixname"
29555731Sbaban 		 *    config/ad_unixgroup_attr = "unixname"
29565731Sbaban 		 *  AD user object:
29575731Sbaban 		 *    dn: cn=bob ...
29585731Sbaban 		 *    objectclass: user
29595731Sbaban 		 *    sam: bob
29605731Sbaban 		 *    unixname: bob1234
29615731Sbaban 		 *  AD group object:
29625731Sbaban 		 *    dn: cn=winadmins ...
29635731Sbaban 		 *    objectclass: group
29645731Sbaban 		 *    sam: winadmins
29655731Sbaban 		 *    unixname: unixadmins
29665731Sbaban 		 *
29675731Sbaban 		 *  In this example whether "unixname" refers to a unixuser
29685731Sbaban 		 *  or unixgroup depends upon the AD object.
29695731Sbaban 		 *
29705731Sbaban 		 * $idmap show -c winname:bob gid
29715731Sbaban 		 *    AD lookup by "samAccountName=bob" for
29725731Sbaban 		 *    "ad_unixgroup_attr (i.e unixname)" for directory-based
29735731Sbaban 		 *    mapping would get "bob1234" which is not what we want.
29745731Sbaban 		 *    Now why not getgrnam_r("bob1234") and use it if it
29755731Sbaban 		 *    is indeed a unixgroup? That's because Unix can have
29765731Sbaban 		 *    users and groups with the same name and we clearly
29775731Sbaban 		 *    don't know the intention of the admin here.
29785731Sbaban 		 *    Therefore we ignore this and fallback to name-based
29795731Sbaban 		 *    mapping rules or ephemeral mapping.
29805731Sbaban 		 */
29815731Sbaban 		if ((AD_MODE(res->id.idtype, state) ||
29825731Sbaban 		    MIXED_MODE(res->id.idtype, state)) &&
29835731Sbaban 		    state->ad_unixuser_attr != NULL &&
29845731Sbaban 		    state->ad_unixgroup_attr != NULL &&
29855731Sbaban 		    strcasecmp(state->ad_unixuser_attr,
29865731Sbaban 		    state->ad_unixgroup_attr) == 0 &&
29875731Sbaban 		    ((req->id1.idtype == IDMAP_USID &&
29885731Sbaban 		    res->id.idtype == IDMAP_GID) ||
29895731Sbaban 		    (req->id1.idtype == IDMAP_GSID &&
29905731Sbaban 		    res->id.idtype == IDMAP_UID))) {
29915731Sbaban 			free(req->id2name);
29925731Sbaban 			req->id2name = NULL;
29935731Sbaban 			res->id.idmap_id_u.uid = SENTINEL_PID;
29945731Sbaban 			/* fallback */
29955731Sbaban 		} else {
29965731Sbaban 			if (res->id.idmap_id_u.uid == SENTINEL_PID)
29975731Sbaban 				retcode = ns_lookup_byname(req->id2name,
29985731Sbaban 				    NULL, &res->id);
29995731Sbaban 			/*
30006616Sdm199847 			 * If ns_lookup_byname() fails that means the
30016616Sdm199847 			 * unixname (req->id2name), which was obtained
30026616Sdm199847 			 * from the AD object by directory-based mapping,
30036616Sdm199847 			 * is not a valid Unix user/group and therefore
30046616Sdm199847 			 * we return the error to the client instead of
30056616Sdm199847 			 * doing rule-based mapping or ephemeral mapping.
30066616Sdm199847 			 * This way the client can detect the issue.
30075731Sbaban 			 */
30085731Sbaban 			goto out;
30094520Snw141292 		}
30104520Snw141292 	}
30114520Snw141292 
30126386Sjp151216 	/* Free any mapping info from Directory based mapping */
30136386Sjp151216 	if (res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN)
30146386Sjp151216 		idmap_info_free(&res->info);
30156386Sjp151216 
30165731Sbaban 	/*
30175731Sbaban 	 * If we don't have unixname then evaluate local name-based
30185731Sbaban 	 * mapping rules.
30195731Sbaban 	 */
30206616Sdm199847 	retcode = name_based_mapping_sid2pid(state, req, res);
30215731Sbaban 	if (retcode != IDMAP_ERR_NOTFOUND)
30224520Snw141292 		goto out;
30234520Snw141292 
30247031Snw141292 do_eph:
30255731Sbaban 	/* If not found, do ephemeral mapping */
30266616Sdm199847 	retcode = dynamic_ephemeral_mapping(state, req, res);
30274520Snw141292 
30284520Snw141292 out:
30294520Snw141292 	res->retcode = idmap_stat4prot(retcode);
30305731Sbaban 	if (res->retcode != IDMAP_SUCCESS) {
30315731Sbaban 		req->direction = _IDMAP_F_DONE;
30325731Sbaban 		res->id.idmap_id_u.uid = UID_NOBODY;
30335731Sbaban 	}
30345731Sbaban 	if (!ARE_WE_DONE(req->direction))
30355731Sbaban 		state->sid2pid_done = FALSE;
30364520Snw141292 	return (retcode);
30374520Snw141292 }
30384520Snw141292 
30394520Snw141292 idmap_retcode
30406616Sdm199847 update_cache_pid2sid(lookup_state_t *state,
30415696Snw141292 		idmap_mapping *req, idmap_id_res *res)
30425696Snw141292 {
30434520Snw141292 	char		*sql = NULL;
30444520Snw141292 	idmap_retcode	retcode;
30456386Sjp151216 	char		*map_dn = NULL;
30466386Sjp151216 	char		*map_attr = NULL;
30476386Sjp151216 	char		*map_value = NULL;
30486386Sjp151216 	char 		*map_windomain = NULL;
30496386Sjp151216 	char		*map_winname = NULL;
30506386Sjp151216 	char		*map_unixname = NULL;
30516386Sjp151216 	int		map_is_nt4 = FALSE;
30524520Snw141292 
30534520Snw141292 	/* Check if we need to cache anything */
30545731Sbaban 	if (ARE_WE_DONE(req->direction))
30554520Snw141292 		return (IDMAP_SUCCESS);
30564520Snw141292 
30574520Snw141292 	/* We don't cache negative entries */
30584520Snw141292 	if (res->retcode != IDMAP_SUCCESS)
30594520Snw141292 		return (IDMAP_SUCCESS);
30604520Snw141292 
30615731Sbaban 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
30626386Sjp151216 	assert(req->id1.idmap_id_u.uid != SENTINEL_PID);
30636386Sjp151216 	assert(res->id.idtype != IDMAP_SID);
30646386Sjp151216 
30656386Sjp151216 	assert(res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN);
30666386Sjp151216 	switch (res->info.how.map_type) {
30676386Sjp151216 	case IDMAP_MAP_TYPE_DS_AD:
30686386Sjp151216 		map_dn = res->info.how.idmap_how_u.ad.dn;
30696386Sjp151216 		map_attr = res->info.how.idmap_how_u.ad.attr;
30706386Sjp151216 		map_value = res->info.how.idmap_how_u.ad.value;
30716386Sjp151216 		break;
30726386Sjp151216 
30736386Sjp151216 	case IDMAP_MAP_TYPE_DS_NLDAP:
30746386Sjp151216 		map_dn = res->info.how.idmap_how_u.nldap.dn;
30756386Sjp151216 		map_attr = res->info.how.idmap_how_u.nldap.attr;
30766386Sjp151216 		map_value = res->info.how.idmap_how_u.nldap.value;
30776386Sjp151216 		break;
30786386Sjp151216 
30796386Sjp151216 	case IDMAP_MAP_TYPE_RULE_BASED:
30806386Sjp151216 		map_windomain = res->info.how.idmap_how_u.rule.windomain;
30816386Sjp151216 		map_winname = res->info.how.idmap_how_u.rule.winname;
30826386Sjp151216 		map_unixname = res->info.how.idmap_how_u.rule.unixname;
30836386Sjp151216 		map_is_nt4 = res->info.how.idmap_how_u.rule.is_nt4;
30846386Sjp151216 		break;
30856386Sjp151216 
30866386Sjp151216 	case IDMAP_MAP_TYPE_EPHEMERAL:
30876386Sjp151216 		break;
30886386Sjp151216 
30896386Sjp151216 	case IDMAP_MAP_TYPE_LOCAL_SID:
30906386Sjp151216 		break;
30916386Sjp151216 
30926386Sjp151216 	default:
30936386Sjp151216 		/* Dont cache other mapping types */
30946386Sjp151216 		assert(FALSE);
30956386Sjp151216 	}
30965731Sbaban 
30974520Snw141292 	/*
30984520Snw141292 	 * Using NULL for u2w instead of 0 so that our trigger allows
30994520Snw141292 	 * the same pid to be the destination in multiple entries
31004520Snw141292 	 */
31014520Snw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
31025696Snw141292 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
31036386Sjp151216 	    "is_user, is_wuser, expiration, w2u, u2w, "
31046386Sjp151216 	    "map_type, map_dn, map_attr, map_value, map_windomain, "
31056386Sjp151216 	    "map_winname, map_unixname, map_is_nt4) "
31065696Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
31076386Sjp151216 	    "strftime('%%s','now') + 600, %q, 1, "
31086386Sjp151216 	    "%d, %Q, %Q, %Q, %Q, %Q, %Q, %d); ",
31095696Snw141292 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
31105696Snw141292 	    req->id2domain, req->id2name, req->id1.idmap_id_u.uid,
31115696Snw141292 	    req->id1name, (req->id1.idtype == IDMAP_UID) ? 1 : 0,
31125731Sbaban 	    (res->id.idtype == IDMAP_USID) ? 1 : 0,
31136386Sjp151216 	    (res->direction == 0) ? "1" : NULL,
31146386Sjp151216 	    res->info.how.map_type, map_dn, map_attr, map_value,
31156386Sjp151216 	    map_windomain, map_winname, map_unixname, map_is_nt4);
31164520Snw141292 
31174520Snw141292 	if (sql == NULL) {
31184520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
31194520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
31204520Snw141292 		goto out;
31214520Snw141292 	}
31224520Snw141292 
31236616Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
31244520Snw141292 	if (retcode != IDMAP_SUCCESS)
31254520Snw141292 		goto out;
31264520Snw141292 
31274520Snw141292 	state->pid2sid_done = FALSE;
31284520Snw141292 	sqlite_freemem(sql);
31294520Snw141292 	sql = NULL;
31304520Snw141292 
31315731Sbaban 	/* Check if we need to update namecache */
31325731Sbaban 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
31334520Snw141292 		goto out;
31344520Snw141292 
31355064Sdm199847 	if (req->id2name == NULL)
31364520Snw141292 		goto out;
31374520Snw141292 
31384520Snw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
31395696Snw141292 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
31405696Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
31415696Snw141292 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
31425696Snw141292 	    req->id2name, req->id2domain,
31435731Sbaban 	    (res->id.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
31444520Snw141292 
31454520Snw141292 	if (sql == NULL) {
31464520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
31474520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
31484520Snw141292 		goto out;
31494520Snw141292 	}
31504520Snw141292 
31516616Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
31524520Snw141292 
31534520Snw141292 out:
31546386Sjp151216 	if (!(req->flag & IDMAP_REQ_FLG_MAPPING_INFO))
31556386Sjp151216 		idmap_info_free(&res->info);
31564864Sbaban 	if (sql != NULL)
31574520Snw141292 		sqlite_freemem(sql);
31584520Snw141292 	return (retcode);
31594520Snw141292 }
31604520Snw141292 
31614520Snw141292 idmap_retcode
31626616Sdm199847 update_cache_sid2pid(lookup_state_t *state,
31635696Snw141292 		idmap_mapping *req, idmap_id_res *res)
31645696Snw141292 {
31654520Snw141292 	char		*sql = NULL;
31664520Snw141292 	idmap_retcode	retcode;
31674520Snw141292 	int		is_eph_user;
31686386Sjp151216 	char		*map_dn = NULL;
31696386Sjp151216 	char		*map_attr = NULL;
31706386Sjp151216 	char		*map_value = NULL;
31716386Sjp151216 	char 		*map_windomain = NULL;
31726386Sjp151216 	char		*map_winname = NULL;
31736386Sjp151216 	char		*map_unixname = NULL;
31746386Sjp151216 	int		map_is_nt4 = FALSE;
31754520Snw141292 
31764520Snw141292 	/* Check if we need to cache anything */
31775731Sbaban 	if (ARE_WE_DONE(req->direction))
31784520Snw141292 		return (IDMAP_SUCCESS);
31794520Snw141292 
31804520Snw141292 	/* We don't cache negative entries */
31814520Snw141292 	if (res->retcode != IDMAP_SUCCESS)
31824520Snw141292 		return (IDMAP_SUCCESS);
31834520Snw141292 
31844520Snw141292 	if (req->direction & _IDMAP_F_EXP_EPH_UID)
31854520Snw141292 		is_eph_user = 1;
31864520Snw141292 	else if (req->direction & _IDMAP_F_EXP_EPH_GID)
31874520Snw141292 		is_eph_user = 0;
31884520Snw141292 	else
31894520Snw141292 		is_eph_user = -1;
31904520Snw141292 
31914520Snw141292 	if (is_eph_user >= 0 && !IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
31924520Snw141292 		sql = sqlite_mprintf("UPDATE idmap_cache "
31935696Snw141292 		    "SET w2u = 0 WHERE "
31945696Snw141292 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
31955696Snw141292 		    "pid >= 2147483648 AND is_user = %d;",
31965696Snw141292 		    req->id1.idmap_id_u.sid.prefix,
31975696Snw141292 		    req->id1.idmap_id_u.sid.rid,
31985696Snw141292 		    is_eph_user);
31994520Snw141292 		if (sql == NULL) {
32004520Snw141292 			retcode = IDMAP_ERR_INTERNAL;
32014520Snw141292 			idmapdlog(LOG_ERR, "Out of memory");
32024520Snw141292 			goto out;
32034520Snw141292 		}
32044520Snw141292 
32056616Sdm199847 		retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
32064520Snw141292 		if (retcode != IDMAP_SUCCESS)
32074520Snw141292 			goto out;
32084520Snw141292 
32094520Snw141292 		sqlite_freemem(sql);
32104520Snw141292 		sql = NULL;
32114520Snw141292 	}
32124520Snw141292 
32135731Sbaban 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
32146386Sjp151216 	assert(res->id.idmap_id_u.uid != SENTINEL_PID);
32156386Sjp151216 
32166386Sjp151216 	switch (res->info.how.map_type) {
32176386Sjp151216 	case IDMAP_MAP_TYPE_DS_AD:
32186386Sjp151216 		map_dn = res->info.how.idmap_how_u.ad.dn;
32196386Sjp151216 		map_attr = res->info.how.idmap_how_u.ad.attr;
32206386Sjp151216 		map_value = res->info.how.idmap_how_u.ad.value;
32216386Sjp151216 		break;
32226386Sjp151216 
32236386Sjp151216 	case IDMAP_MAP_TYPE_DS_NLDAP:
32246386Sjp151216 		map_dn = res->info.how.idmap_how_u.nldap.dn;
32256386Sjp151216 		map_attr = res->info.how.idmap_how_u.ad.attr;
32266386Sjp151216 		map_value = res->info.how.idmap_how_u.nldap.value;
32276386Sjp151216 		break;
32286386Sjp151216 
32296386Sjp151216 	case IDMAP_MAP_TYPE_RULE_BASED:
32306386Sjp151216 		map_windomain = res->info.how.idmap_how_u.rule.windomain;
32316386Sjp151216 		map_winname = res->info.how.idmap_how_u.rule.winname;
32326386Sjp151216 		map_unixname = res->info.how.idmap_how_u.rule.unixname;
32336386Sjp151216 		map_is_nt4 = res->info.how.idmap_how_u.rule.is_nt4;
32346386Sjp151216 		break;
32356386Sjp151216 
32366386Sjp151216 	case IDMAP_MAP_TYPE_EPHEMERAL:
32376386Sjp151216 		break;
32386386Sjp151216 
32396386Sjp151216 	default:
32406386Sjp151216 		/* Dont cache other mapping types */
32416386Sjp151216 		assert(FALSE);
32426386Sjp151216 	}
32435696Snw141292 
32444520Snw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
32455696Snw141292 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
32466386Sjp151216 	    "is_user, is_wuser, expiration, w2u, u2w, "
32476386Sjp151216 	    "map_type, map_dn, map_attr, map_value, map_windomain, "
32486386Sjp151216 	    "map_winname, map_unixname, map_is_nt4) "
32495696Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
32506386Sjp151216 	    "strftime('%%s','now') + 600, 1, %q, "
32516386Sjp151216 	    "%d, %Q, %Q, %Q, %Q, %Q, %Q, %d);",
32525696Snw141292 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
32535731Sbaban 	    (req->id1domain != NULL) ? req->id1domain : "", req->id1name,
32545731Sbaban 	    res->id.idmap_id_u.uid, req->id2name,
32555731Sbaban 	    (res->id.idtype == IDMAP_UID) ? 1 : 0,
32565696Snw141292 	    (req->id1.idtype == IDMAP_USID) ? 1 : 0,
32576386Sjp151216 	    (res->direction == 0) ? "1" : NULL,
32586386Sjp151216 	    res->info.how.map_type, map_dn, map_attr, map_value,
32596386Sjp151216 	    map_windomain, map_winname, map_unixname, map_is_nt4);
32604520Snw141292 
32614520Snw141292 	if (sql == NULL) {
32624520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
32634520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
32644520Snw141292 		goto out;
32654520Snw141292 	}
32664520Snw141292 
32676616Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
32684520Snw141292 	if (retcode != IDMAP_SUCCESS)
32694520Snw141292 		goto out;
32704520Snw141292 
32714520Snw141292 	state->sid2pid_done = FALSE;
32724520Snw141292 	sqlite_freemem(sql);
32734520Snw141292 	sql = NULL;
32744520Snw141292 
32755731Sbaban 	/* Check if we need to update namecache */
32765731Sbaban 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
32774520Snw141292 		goto out;
32784520Snw141292 
32795127Sdm199847 	if (EMPTY_STRING(req->id1name))
32804520Snw141292 		goto out;
32814520Snw141292 
32824520Snw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
32835696Snw141292 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
32845696Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
32855696Snw141292 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
32865696Snw141292 	    req->id1name, req->id1domain,
32875696Snw141292 	    (req->id1.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
32884520Snw141292 
32894520Snw141292 	if (sql == NULL) {
32904520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
32914520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
32924520Snw141292 		goto out;
32934520Snw141292 	}
32944520Snw141292 
32956616Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
32964520Snw141292 
32974520Snw141292 out:
32986386Sjp151216 	if (!(req->flag & IDMAP_REQ_FLG_MAPPING_INFO))
32996386Sjp151216 		idmap_info_free(&res->info);
33006386Sjp151216 
33014864Sbaban 	if (sql != NULL)
33024520Snw141292 		sqlite_freemem(sql);
33034520Snw141292 	return (retcode);
33044520Snw141292 }
33054520Snw141292 
33065696Snw141292 static
33075696Snw141292 idmap_retcode
33084520Snw141292 lookup_cache_pid2sid(sqlite *cache, idmap_mapping *req, idmap_id_res *res,
33095696Snw141292 		int is_user, int getname)
33105696Snw141292 {
33114520Snw141292 	char		*end;
33124520Snw141292 	char		*sql = NULL;
33134520Snw141292 	const char	**values;
33144520Snw141292 	sqlite_vm	*vm = NULL;
33154520Snw141292 	int		ncol;
33164520Snw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
33174520Snw141292 	time_t		curtime;
33185731Sbaban 	idmap_id_type	idtype;
33194520Snw141292 
33204520Snw141292 	/* Current time */
33214520Snw141292 	errno = 0;
33224520Snw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
33235696Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
33245696Snw141292 		    strerror(errno));
33254520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
33264520Snw141292 		goto out;
33274520Snw141292 	}
33284520Snw141292 
33295731Sbaban 	/* SQL to lookup the cache by pid or by unixname */
33305731Sbaban 	if (req->id1.idmap_id_u.uid != SENTINEL_PID) {
33316386Sjp151216 		sql = sqlite_mprintf("SELECT sidprefix, rid, "
33326386Sjp151216 		    "canon_winname, windomain, w2u, is_wuser, "
33336386Sjp151216 		    "map_type, map_dn, map_attr, map_value, map_windomain, "
33346386Sjp151216 		    "map_winname, map_unixname, map_is_nt4 "
33355731Sbaban 		    "FROM idmap_cache WHERE "
33365731Sbaban 		    "pid = %u AND u2w = 1 AND is_user = %d AND "
33375731Sbaban 		    "(pid >= 2147483648 OR "
33385731Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
33395731Sbaban 		    "expiration > %d));",
33405731Sbaban 		    req->id1.idmap_id_u.uid, is_user, curtime);
33415731Sbaban 	} else if (req->id1name != NULL) {
33426386Sjp151216 		sql = sqlite_mprintf("SELECT sidprefix, rid, "
33436386Sjp151216 		    "canon_winname, windomain, w2u, is_wuser, "
33446386Sjp151216 		    "map_type, map_dn, map_attr, map_value, map_windomain, "
33456386Sjp151216 		    "map_winname, map_unixname, map_is_nt4 "
33465731Sbaban 		    "FROM idmap_cache WHERE "
33475731Sbaban 		    "unixname = %Q AND u2w = 1 AND is_user = %d AND "
33485731Sbaban 		    "(pid >= 2147483648 OR "
33495731Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
33505731Sbaban 		    "expiration > %d));",
33515731Sbaban 		    req->id1name, is_user, curtime);
33526386Sjp151216 	} else {
33536386Sjp151216 		retcode = IDMAP_ERR_ARG;
33546386Sjp151216 		goto out;
33555731Sbaban 	}
33565731Sbaban 
33574520Snw141292 	if (sql == NULL) {
33584520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
33594520Snw141292 		retcode = IDMAP_ERR_MEMORY;
33604520Snw141292 		goto out;
33614520Snw141292 	}
33626386Sjp151216 	retcode = sql_compile_n_step_once(
33636386Sjp151216 	    cache, sql, &vm, &ncol, 14, &values);
33644520Snw141292 	sqlite_freemem(sql);
33654520Snw141292 
33664520Snw141292 	if (retcode == IDMAP_ERR_NOTFOUND)
33674520Snw141292 		goto out;
33684520Snw141292 	else if (retcode == IDMAP_SUCCESS) {
33694520Snw141292 		/* sanity checks */
33704520Snw141292 		if (values[0] == NULL || values[1] == NULL) {
33714520Snw141292 			retcode = IDMAP_ERR_CACHE;
33724520Snw141292 			goto out;
33734520Snw141292 		}
33744520Snw141292 
33755731Sbaban 		switch (res->id.idtype) {
33764520Snw141292 		case IDMAP_SID:
33775696Snw141292 		case IDMAP_USID:
33785696Snw141292 		case IDMAP_GSID:
33795731Sbaban 			idtype = strtol(values[5], &end, 10) == 1
33805696Snw141292 			    ? IDMAP_USID : IDMAP_GSID;
33815696Snw141292 
33825731Sbaban 			if (res->id.idtype == IDMAP_USID &&
33835731Sbaban 			    idtype != IDMAP_USID) {
33845696Snw141292 				retcode = IDMAP_ERR_NOTUSER;
33855696Snw141292 				goto out;
33865731Sbaban 			} else if (res->id.idtype == IDMAP_GSID &&
33875731Sbaban 			    idtype != IDMAP_GSID) {
33885696Snw141292 				retcode = IDMAP_ERR_NOTGROUP;
33895696Snw141292 				goto out;
33905696Snw141292 			}
33915731Sbaban 			res->id.idtype = idtype;
33925696Snw141292 
33934520Snw141292 			res->id.idmap_id_u.sid.rid =
33945696Snw141292 			    strtoul(values[1], &end, 10);
33954520Snw141292 			res->id.idmap_id_u.sid.prefix = strdup(values[0]);
33964520Snw141292 			if (res->id.idmap_id_u.sid.prefix == NULL) {
33974520Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
33984520Snw141292 				retcode = IDMAP_ERR_MEMORY;
33994520Snw141292 				goto out;
34004520Snw141292 			}
34014520Snw141292 
34024864Sbaban 			if (values[4] != NULL)
34034520Snw141292 				res->direction =
34044644Sbaban 				    (strtol(values[4], &end, 10) == 0)?
34054644Sbaban 				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
34064520Snw141292 			else
34074644Sbaban 				res->direction = IDMAP_DIRECTION_U2W;
34084520Snw141292 
34094520Snw141292 			if (getname == 0 || values[2] == NULL)
34104520Snw141292 				break;
34115064Sdm199847 			req->id2name = strdup(values[2]);
34125064Sdm199847 			if (req->id2name == NULL) {
34134520Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
34144520Snw141292 				retcode = IDMAP_ERR_MEMORY;
34154520Snw141292 				goto out;
34164520Snw141292 			}
34174520Snw141292 
34184520Snw141292 			if (values[3] == NULL)
34194520Snw141292 				break;
34205064Sdm199847 			req->id2domain = strdup(values[3]);
34215064Sdm199847 			if (req->id2domain == NULL) {
34224520Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
34234520Snw141292 				retcode = IDMAP_ERR_MEMORY;
34244520Snw141292 				goto out;
34254520Snw141292 			}
34265696Snw141292 
34274520Snw141292 			break;
34284520Snw141292 		default:
34294520Snw141292 			retcode = IDMAP_ERR_NOTSUPPORTED;
34304520Snw141292 			break;
34314520Snw141292 		}
34326386Sjp151216 		if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
34336386Sjp151216 			res->info.src = IDMAP_MAP_SRC_CACHE;
34346386Sjp151216 			res->info.how.map_type = strtoul(values[6], &end, 10);
34356386Sjp151216 			switch (res->info.how.map_type) {
34366386Sjp151216 			case IDMAP_MAP_TYPE_DS_AD:
34376386Sjp151216 				res->info.how.idmap_how_u.ad.dn =
34386386Sjp151216 				    strdup(values[7]);
34396386Sjp151216 				res->info.how.idmap_how_u.ad.attr =
34406386Sjp151216 				    strdup(values[8]);
34416386Sjp151216 				res->info.how.idmap_how_u.ad.value =
34426386Sjp151216 				    strdup(values[9]);
34436386Sjp151216 				break;
34446386Sjp151216 
34456386Sjp151216 			case IDMAP_MAP_TYPE_DS_NLDAP:
34466386Sjp151216 				res->info.how.idmap_how_u.nldap.dn =
34476386Sjp151216 				    strdup(values[7]);
34486386Sjp151216 				res->info.how.idmap_how_u.nldap.attr =
34496386Sjp151216 				    strdup(values[8]);
34506386Sjp151216 				res->info.how.idmap_how_u.nldap.value =
34516386Sjp151216 				    strdup(values[9]);
34526386Sjp151216 				break;
34536386Sjp151216 
34546386Sjp151216 			case IDMAP_MAP_TYPE_RULE_BASED:
34556386Sjp151216 				res->info.how.idmap_how_u.rule.windomain =
34566386Sjp151216 				    strdup(values[10]);
34576386Sjp151216 				res->info.how.idmap_how_u.rule.winname =
34586386Sjp151216 				    strdup(values[11]);
34596386Sjp151216 				res->info.how.idmap_how_u.rule.unixname =
34606386Sjp151216 				    strdup(values[12]);
34616386Sjp151216 				res->info.how.idmap_how_u.rule.is_nt4 =
34626386Sjp151216 				    strtoul(values[13], &end, 10);
34636386Sjp151216 				res->info.how.idmap_how_u.rule.is_user =
34646386Sjp151216 				    is_user;
34656386Sjp151216 				res->info.how.idmap_how_u.rule.is_wuser =
34666386Sjp151216 				    strtol(values[5], &end, 10);
34676386Sjp151216 				break;
34686386Sjp151216 
34696386Sjp151216 			case IDMAP_MAP_TYPE_EPHEMERAL:
34706386Sjp151216 				break;
34716386Sjp151216 
34726386Sjp151216 			case IDMAP_MAP_TYPE_LOCAL_SID:
34736386Sjp151216 				break;
34746386Sjp151216 
34756386Sjp151216 			case IDMAP_MAP_TYPE_KNOWN_SID:
34766386Sjp151216 				break;
34776386Sjp151216 
34786386Sjp151216 			default:
34796386Sjp151216 				/* Unknow mapping type */
34806386Sjp151216 				assert(FALSE);
34816386Sjp151216 			}
34826386Sjp151216 		}
34834520Snw141292 	}
34844520Snw141292 
34854520Snw141292 out:
34864864Sbaban 	if (vm != NULL)
34874520Snw141292 		(void) sqlite_finalize(vm, NULL);
34884520Snw141292 	return (retcode);
34894520Snw141292 }
34904520Snw141292 
34915696Snw141292 static
34925696Snw141292 idmap_retcode
34934520Snw141292 lookup_cache_name2sid(sqlite *cache, const char *name, const char *domain,
34945696Snw141292 	char **canonname, char **sidprefix, idmap_rid_t *rid, int *type)
34955696Snw141292 {
34965696Snw141292 	char		*end, *lower_name;
34974520Snw141292 	char		*sql = NULL;
34984520Snw141292 	const char	**values;
34994520Snw141292 	sqlite_vm	*vm = NULL;
35004520Snw141292 	int		ncol;
35014520Snw141292 	time_t		curtime;
35024520Snw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
35034520Snw141292 
35044520Snw141292 	/* Get current time */
35054520Snw141292 	errno = 0;
35064520Snw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
35075696Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
35085696Snw141292 		    strerror(errno));
35094520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
35104520Snw141292 		goto out;
35114520Snw141292 	}
35124520Snw141292 
35134520Snw141292 	/* SQL to lookup the cache */
35145696Snw141292 	if ((lower_name = tolower_u8(name)) == NULL)
35155696Snw141292 		lower_name = (char *)name;
35165696Snw141292 	sql = sqlite_mprintf("SELECT sidprefix, rid, type, canon_name "
35175696Snw141292 	    "FROM name_cache WHERE name = %Q AND domain = %Q AND "
35185696Snw141292 	    "(expiration = 0 OR expiration ISNULL OR "
35195696Snw141292 	    "expiration > %d);", lower_name, domain, curtime);
35205696Snw141292 	if (lower_name != name)
35215696Snw141292 		free(lower_name);
35224520Snw141292 	if (sql == NULL) {
35234520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
35244520Snw141292 		retcode = IDMAP_ERR_MEMORY;
35254520Snw141292 		goto out;
35264520Snw141292 	}
35275696Snw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 4, &values);
35284520Snw141292 	sqlite_freemem(sql);
35294520Snw141292 
35304520Snw141292 	if (retcode == IDMAP_SUCCESS) {
35314864Sbaban 		if (type != NULL) {
35324520Snw141292 			if (values[2] == NULL) {
35334520Snw141292 				retcode = IDMAP_ERR_CACHE;
35344520Snw141292 				goto out;
35354520Snw141292 			}
35364520Snw141292 			*type = strtol(values[2], &end, 10);
35374520Snw141292 		}
35384520Snw141292 
35395731Sbaban 		if (values[0] == NULL || values[1] == NULL) {
35405731Sbaban 			retcode = IDMAP_ERR_CACHE;
35415731Sbaban 			goto out;
35425731Sbaban 		}
35435731Sbaban 
35445696Snw141292 		if (canonname != NULL) {
35455696Snw141292 			assert(values[3] != NULL);
35465696Snw141292 			if ((*canonname = strdup(values[3])) == NULL) {
35475696Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
35485696Snw141292 				retcode = IDMAP_ERR_MEMORY;
35495696Snw141292 				goto out;
35505696Snw141292 			}
35515696Snw141292 		}
35525696Snw141292 
35534520Snw141292 		if ((*sidprefix = strdup(values[0])) == NULL) {
35544520Snw141292 			idmapdlog(LOG_ERR, "Out of memory");
35554520Snw141292 			retcode = IDMAP_ERR_MEMORY;
35565731Sbaban 			if (canonname != NULL) {
35575731Sbaban 				free(*canonname);
35585731Sbaban 				*canonname = NULL;
35595731Sbaban 			}
35604520Snw141292 			goto out;
35614520Snw141292 		}
35624520Snw141292 		*rid = strtoul(values[1], &end, 10);
35634520Snw141292 	}
35644520Snw141292 
35654520Snw141292 out:
35664864Sbaban 	if (vm != NULL)
35674520Snw141292 		(void) sqlite_finalize(vm, NULL);
35684520Snw141292 	return (retcode);
35694520Snw141292 }
35704520Snw141292 
35715696Snw141292 static
35725696Snw141292 idmap_retcode
35735731Sbaban ad_lookup_by_winname(lookup_state_t *state,
35745731Sbaban 		const char *name, const char *domain, int eunixtype,
35756386Sjp151216 		char **dn, char **attr, char **value, char **canonname,
35766386Sjp151216 		char **sidprefix, idmap_rid_t *rid, int *wintype,
35776386Sjp151216 		char **unixname)
35785696Snw141292 {
35794520Snw141292 	int			retries = 0;
35804520Snw141292 	idmap_query_state_t	*qs = NULL;
35814520Snw141292 	idmap_retcode		rc, retcode;
35824520Snw141292 
35834520Snw141292 retry:
35845731Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, 1, &qs);
35855731Sbaban 	if (retcode != IDMAP_SUCCESS) {
35865968Snw141292 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
35875968Snw141292 			goto retry;
35886097Snw141292 		degrade_svc(1, "failed to create request for AD lookup "
35895968Snw141292 		    "by winname");
35905731Sbaban 		return (retcode);
35914520Snw141292 	}
35924520Snw141292 
35935317Sjp151216 	restore_svc();
35945317Sjp151216 
35955731Sbaban 	if (state != NULL)
35965731Sbaban 		idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
35975731Sbaban 		    state->ad_unixgroup_attr);
35985731Sbaban 
35995731Sbaban 	retcode = idmap_name2sid_batch_add1(qs, name, domain, eunixtype,
36006386Sjp151216 	    dn, attr, value, canonname, sidprefix, rid, wintype, unixname, &rc);
36015731Sbaban 
36025731Sbaban 	if (retcode != IDMAP_SUCCESS)
36034884Sjp151216 		idmap_lookup_release_batch(&qs);
36044520Snw141292 	else
36055968Snw141292 		retcode = idmap_lookup_batch_end(&qs);
36064520Snw141292 
36074520Snw141292 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
36084520Snw141292 		goto retry;
36095317Sjp151216 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
36106097Snw141292 		degrade_svc(1, "some AD lookups timed out repeatedly");
36114520Snw141292 
36124520Snw141292 	if (retcode != IDMAP_SUCCESS) {
36135731Sbaban 		idmapdlog(LOG_NOTICE, "AD lookup by winname failed");
36144520Snw141292 		return (retcode);
36155731Sbaban 	}
36165731Sbaban 	return (rc);
36174520Snw141292 }
36184520Snw141292 
36195696Snw141292 idmap_retcode
36204520Snw141292 lookup_name2sid(sqlite *cache, const char *name, const char *domain,
36215696Snw141292 		int *is_wuser, char **canonname, char **sidprefix,
36226616Sdm199847 		idmap_rid_t *rid, idmap_mapping *req, int local_only)
36235696Snw141292 {
36244520Snw141292 	int		type;
36254520Snw141292 	idmap_retcode	retcode;
36264520Snw141292 
36275696Snw141292 	*sidprefix = NULL;
36285731Sbaban 	if (canonname != NULL)
36295731Sbaban 		*canonname = NULL;
36305731Sbaban 
36315731Sbaban 	/* Lookup well-known SIDs table */
36325696Snw141292 	retcode = lookup_wksids_name2sid(name, canonname, sidprefix, rid,
36335696Snw141292 	    &type);
36344864Sbaban 	if (retcode == IDMAP_SUCCESS) {
36355731Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
36364864Sbaban 		goto out;
36374864Sbaban 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
36384864Sbaban 		return (retcode);
36394864Sbaban 	}
36404864Sbaban 
36415731Sbaban 	/* Lookup cache */
36425696Snw141292 	retcode = lookup_cache_name2sid(cache, name, domain, canonname,
36435696Snw141292 	    sidprefix, rid, &type);
36445731Sbaban 	if (retcode == IDMAP_SUCCESS) {
36455731Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
36465731Sbaban 		goto out;
36475731Sbaban 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
36484520Snw141292 		return (retcode);
36494520Snw141292 	}
36504520Snw141292 
36516616Sdm199847 	/*
36526616Sdm199847 	 * The caller may be using this function to determine if this
36536616Sdm199847 	 * request needs to be marked for AD lookup or not
36546616Sdm199847 	 * (i.e. _IDMAP_F_LOOKUP_AD) and therefore may not want this
36556616Sdm199847 	 * function to AD lookup now.
36566616Sdm199847 	 */
36576616Sdm199847 	if (local_only)
36586616Sdm199847 		return (retcode);
36596616Sdm199847 
36605731Sbaban 	/* Lookup AD */
36615731Sbaban 	retcode = ad_lookup_by_winname(NULL, name, domain, _IDMAP_T_UNDEF,
36626386Sjp151216 	    NULL, NULL, NULL, canonname, sidprefix, rid, &type, NULL);
36635731Sbaban 	if (retcode != IDMAP_SUCCESS)
36645731Sbaban 		return (retcode);
36655731Sbaban 
36664864Sbaban out:
36674520Snw141292 	/*
36684520Snw141292 	 * Entry found (cache or Windows lookup)
36695696Snw141292 	 * is_wuser is both input as well as output parameter
36704520Snw141292 	 */
36715731Sbaban 	if (*is_wuser == 1 && type != _IDMAP_T_USER)
36725731Sbaban 		retcode = IDMAP_ERR_NOTUSER;
36735731Sbaban 	else if (*is_wuser == 0 && type != _IDMAP_T_GROUP)
36745731Sbaban 		retcode = IDMAP_ERR_NOTGROUP;
36755731Sbaban 	else if (*is_wuser == -1) {
36764520Snw141292 		/* Caller wants to know if its user or group */
36774520Snw141292 		if (type == _IDMAP_T_USER)
36785696Snw141292 			*is_wuser = 1;
36794520Snw141292 		else if (type == _IDMAP_T_GROUP)
36805696Snw141292 			*is_wuser = 0;
36815731Sbaban 		else
36825731Sbaban 			retcode = IDMAP_ERR_SID;
36835731Sbaban 	}
36845731Sbaban 
36855731Sbaban 	if (retcode != IDMAP_SUCCESS) {
36865731Sbaban 		free(*sidprefix);
36875731Sbaban 		*sidprefix = NULL;
36885731Sbaban 		if (canonname != NULL) {
36895731Sbaban 			free(*canonname);
36905731Sbaban 			*canonname = NULL;
36915696Snw141292 		}
36924520Snw141292 	}
36934520Snw141292 	return (retcode);
36944520Snw141292 }
36954520Snw141292 
36965696Snw141292 static
36975696Snw141292 idmap_retcode
36986616Sdm199847 name_based_mapping_pid2sid(lookup_state_t *state, const char *unixname,
36995696Snw141292 		int is_user, idmap_mapping *req, idmap_id_res *res)
37005696Snw141292 {
37014520Snw141292 	const char	*winname, *windomain;
37025696Snw141292 	char		*canonname;
37034520Snw141292 	char		*sql = NULL, *errmsg = NULL;
37044520Snw141292 	idmap_retcode	retcode;
37054520Snw141292 	char		*end;
37064520Snw141292 	const char	**values;
37074520Snw141292 	sqlite_vm	*vm = NULL;
37086386Sjp151216 	int		ncol, r;
37095731Sbaban 	int		is_wuser;
37104520Snw141292 	const char	*me = "name_based_mapping_pid2sid";
37116386Sjp151216 	int 		non_wild_match = FALSE;
37126386Sjp151216 	idmap_namerule	*rule = &res->info.how.idmap_how_u.rule;
37136386Sjp151216 	int direction;
37145731Sbaban 
37155731Sbaban 	assert(unixname != NULL); /* We have unixname */
37165731Sbaban 	assert(req->id2name == NULL); /* We don't have winname */
37175731Sbaban 	assert(res->id.idmap_id_u.sid.prefix == NULL); /* No SID either */
37184520Snw141292 
37194520Snw141292 	sql = sqlite_mprintf(
37206386Sjp151216 	    "SELECT winname_display, windomain, w2u_order, "
37216386Sjp151216 	    "is_wuser, unixname, is_nt4 "
37226386Sjp151216 	    "FROM namerules WHERE "
37235696Snw141292 	    "u2w_order > 0 AND is_user = %d AND "
37245696Snw141292 	    "(unixname = %Q OR unixname = '*') "
37255696Snw141292 	    "ORDER BY u2w_order ASC;", is_user, unixname);
37264520Snw141292 	if (sql == NULL) {
37274520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
37284520Snw141292 		retcode = IDMAP_ERR_MEMORY;
37294520Snw141292 		goto out;
37304520Snw141292 	}
37314520Snw141292 
37326616Sdm199847 	if (sqlite_compile(state->db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
37334520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
37345696Snw141292 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
37355696Snw141292 		    CHECK_NULL(errmsg));
37364520Snw141292 		sqlite_freemem(errmsg);
37374520Snw141292 		goto out;
37384520Snw141292 	}
37394520Snw141292 
37406386Sjp151216 	for (;;) {
37414520Snw141292 		r = sqlite_step(vm, &ncol, &values, NULL);
37424884Sjp151216 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
37434884Sjp151216 		if (r == SQLITE_ROW) {
37446386Sjp151216 			if (ncol < 6) {
37454520Snw141292 				retcode = IDMAP_ERR_INTERNAL;
37464520Snw141292 				goto out;
37474520Snw141292 			}
37484520Snw141292 			if (values[0] == NULL) {
37494520Snw141292 				/* values [1] and [2] can be null */
37504520Snw141292 				retcode = IDMAP_ERR_INTERNAL;
37514520Snw141292 				goto out;
37524520Snw141292 			}
37536386Sjp151216 
37546386Sjp151216 			if (values[2] != NULL)
37556386Sjp151216 				direction =
37566386Sjp151216 				    (strtol(values[2], &end, 10) == 0)?
37576386Sjp151216 				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
37586386Sjp151216 			else
37596386Sjp151216 				direction = IDMAP_DIRECTION_U2W;
37606386Sjp151216 
37614520Snw141292 			if (EMPTY_NAME(values[0])) {
37626386Sjp151216 				idmap_namerule_set(rule, values[1], values[0],
37636386Sjp151216 				    values[4], is_user,
37646386Sjp151216 				    strtol(values[3], &end, 10),
37656386Sjp151216 				    strtol(values[5], &end, 10),
37666386Sjp151216 				    direction);
37674520Snw141292 				retcode = IDMAP_ERR_NOMAPPING;
37684520Snw141292 				goto out;
37694520Snw141292 			}
37705696Snw141292 
37715696Snw141292 			if (values[0][0] == '*') {
37726386Sjp151216 				winname = unixname;
37736386Sjp151216 				if (non_wild_match) {
37745696Snw141292 					/*
37756386Sjp151216 					 * There were non-wildcard rules
37766386Sjp151216 					 * where the Windows identity doesn't
37776386Sjp151216 					 * exist. Return no mapping.
37785696Snw141292 					 */
37795696Snw141292 					retcode = IDMAP_ERR_NOMAPPING;
37805696Snw141292 					goto out;
37815696Snw141292 				}
37825696Snw141292 			} else {
37836386Sjp151216 				/* Save first non-wild match rule */
37846386Sjp151216 				if (!non_wild_match) {
37856386Sjp151216 					idmap_namerule_set(rule, values[1],
37866386Sjp151216 					    values[0], values[4],
37876386Sjp151216 					    is_user,
37886386Sjp151216 					    strtol(values[3], &end, 10),
37896386Sjp151216 					    strtol(values[5], &end, 10),
37906386Sjp151216 					    direction);
37916386Sjp151216 					non_wild_match = TRUE;
37926386Sjp151216 				}
37935696Snw141292 				winname = values[0];
37945696Snw141292 			}
37956386Sjp151216 			is_wuser = res->id.idtype == IDMAP_USID ? 1
37966386Sjp151216 			    : res->id.idtype == IDMAP_GSID ? 0
37976386Sjp151216 			    : -1;
37984864Sbaban 			if (values[1] != NULL)
37994520Snw141292 				windomain = values[1];
38006616Sdm199847 			else if (state->defdom != NULL)
38016616Sdm199847 				windomain = state->defdom;
38024520Snw141292 			else {
38035696Snw141292 				idmapdlog(LOG_ERR, "%s: no domain", me);
38044520Snw141292 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
38054520Snw141292 				goto out;
38064520Snw141292 			}
38075696Snw141292 
38086616Sdm199847 			retcode = lookup_name2sid(state->cache,
38096616Sdm199847 			    winname, windomain,
38105696Snw141292 			    &is_wuser, &canonname,
38115696Snw141292 			    &res->id.idmap_id_u.sid.prefix,
38126616Sdm199847 			    &res->id.idmap_id_u.sid.rid, req, 0);
38135731Sbaban 
38144520Snw141292 			if (retcode == IDMAP_ERR_NOTFOUND) {
38155696Snw141292 				continue;
38164520Snw141292 			}
38174520Snw141292 			goto out;
38186386Sjp151216 
38194520Snw141292 		} else if (r == SQLITE_DONE) {
38206386Sjp151216 			/*
38216386Sjp151216 			 * If there were non-wildcard rules where
38226386Sjp151216 			 * Windows identity doesn't exist
38236386Sjp151216 			 * return no mapping.
38246386Sjp151216 			 */
38256386Sjp151216 			if (non_wild_match)
38266386Sjp151216 				retcode = IDMAP_ERR_NOMAPPING;
38276386Sjp151216 			else
38286386Sjp151216 				retcode = IDMAP_ERR_NOTFOUND;
38294520Snw141292 			goto out;
38304520Snw141292 		} else {
38314520Snw141292 			(void) sqlite_finalize(vm, &errmsg);
38324520Snw141292 			vm = NULL;
38335696Snw141292 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
38345696Snw141292 			    CHECK_NULL(errmsg));
38354520Snw141292 			sqlite_freemem(errmsg);
38364520Snw141292 			retcode = IDMAP_ERR_INTERNAL;
38374520Snw141292 			goto out;
38384520Snw141292 		}
38394520Snw141292 	}
38404520Snw141292 
38414520Snw141292 out:
38424864Sbaban 	if (sql != NULL)
38434520Snw141292 		sqlite_freemem(sql);
38446386Sjp151216 	res->info.how.map_type = IDMAP_MAP_TYPE_RULE_BASED;
38454520Snw141292 	if (retcode == IDMAP_SUCCESS) {
38465696Snw141292 		res->id.idtype = is_wuser ? IDMAP_USID : IDMAP_GSID;
38475696Snw141292 
38484864Sbaban 		if (values[2] != NULL)
38494520Snw141292 			res->direction =
38504644Sbaban 			    (strtol(values[2], &end, 10) == 0)?
38514644Sbaban 			    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
38524520Snw141292 		else
38534644Sbaban 			res->direction = IDMAP_DIRECTION_U2W;
38545064Sdm199847 
38555696Snw141292 		req->id2name = canonname;
38565064Sdm199847 		if (req->id2name != NULL) {
38576616Sdm199847 			req->id2domain = strdup(windomain);
38586616Sdm199847 			if (req->id2domain == NULL)
38596616Sdm199847 				retcode = IDMAP_ERR_MEMORY;
38604520Snw141292 		}
38616616Sdm199847 	}
38626616Sdm199847 
38636616Sdm199847 	if (retcode == IDMAP_SUCCESS) {
38646386Sjp151216 		idmap_namerule_set(rule, values[1], values[0], values[4],
38656386Sjp151216 		    is_user, strtol(values[3], &end, 10),
38666386Sjp151216 		    strtol(values[5], &end, 10),
38676386Sjp151216 		    rule->direction);
38686386Sjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
38694520Snw141292 	}
38704864Sbaban 	if (vm != NULL)
38714520Snw141292 		(void) sqlite_finalize(vm, NULL);
38724520Snw141292 	return (retcode);
38734520Snw141292 }
38744520Snw141292 
38755696Snw141292 /*
38765696Snw141292  * Convention when processing unix2win requests:
38775696Snw141292  *
38785696Snw141292  * Unix identity:
38795696Snw141292  * req->id1name =
38805696Snw141292  *              unixname if given otherwise unixname found will be placed
38815696Snw141292  *              here.
38825696Snw141292  * req->id1domain =
38835696Snw141292  *              NOT USED
38845696Snw141292  * req->id1.idtype =
38855696Snw141292  *              Given type (IDMAP_UID or IDMAP_GID)
38865696Snw141292  * req->id1..[uid or gid] =
38875696Snw141292  *              UID/GID if given otherwise UID/GID found will be placed here.
38885696Snw141292  *
38895696Snw141292  * Windows identity:
38905696Snw141292  * req->id2name =
38915696Snw141292  *              winname found will be placed here.
38925696Snw141292  * req->id2domain =
38935696Snw141292  *              windomain found will be placed here.
38945696Snw141292  * res->id.idtype =
38955696Snw141292  *              Target type initialized from req->id2.idtype. If
38965696Snw141292  *              it is IDMAP_SID then actual type (IDMAP_USID/GSID) found
38975696Snw141292  *              will be placed here.
38985696Snw141292  * req->id..sid.[prefix, rid] =
38995696Snw141292  *              SID found will be placed here.
39005696Snw141292  *
39015696Snw141292  * Others:
39025696Snw141292  * res->retcode =
39035696Snw141292  *              Return status for this request will be placed here.
39045696Snw141292  * res->direction =
39055696Snw141292  *              Direction found will be placed here. Direction
39065696Snw141292  *              meaning whether the resultant mapping is valid
39075696Snw141292  *              only from unix2win or bi-directional.
39085696Snw141292  * req->direction =
39095696Snw141292  *              INTERNAL USE. Used by idmapd to set various
39105696Snw141292  *              flags (_IDMAP_F_xxxx) to aid in processing
39115696Snw141292  *              of the request.
39125696Snw141292  * req->id2.idtype =
39135696Snw141292  *              INTERNAL USE. Initially this is the requested target
39145696Snw141292  *              type and is used to initialize res->id.idtype.
39155696Snw141292  *              ad_lookup_batch() uses this field temporarily to store
39165696Snw141292  *              sid_type obtained by the batched AD lookups and after
39175696Snw141292  *              use resets it to IDMAP_NONE to prevent xdr from
39185696Snw141292  *              mis-interpreting the contents of req->id2.
39195696Snw141292  * req->id2..[uid or gid or sid] =
39205696Snw141292  *              NOT USED
39215696Snw141292  */
39225696Snw141292 
39235696Snw141292 /*
39245696Snw141292  * This function does the following:
39255696Snw141292  * 1. Lookup well-known SIDs table.
39265696Snw141292  * 2. Lookup cache.
39275696Snw141292  * 3. Check if the client does not want new mapping to be allocated
39285696Snw141292  *    in which case this pass is the final pass.
39295731Sbaban  * 4. Set AD/NLDAP lookup flags if it determines that the next stage needs
39305731Sbaban  *    to do AD/NLDAP lookup.
39315696Snw141292  */
39324520Snw141292 idmap_retcode
39336616Sdm199847 pid2sid_first_pass(lookup_state_t *state, idmap_mapping *req,
39346616Sdm199847 		idmap_id_res *res, int is_user, int getname)
39355696Snw141292 {
39365731Sbaban 	idmap_retcode	retcode;
39375731Sbaban 	bool_t		gen_localsid_on_err = FALSE;
39385731Sbaban 
39395731Sbaban 	/* Initialize result */
39404520Snw141292 	res->id.idtype = req->id2.idtype;
39415731Sbaban 	res->direction = IDMAP_DIRECTION_UNDEF;
39425731Sbaban 
39435731Sbaban 	if (req->id2.idmap_id_u.sid.prefix != NULL) {
39445731Sbaban 		/* sanitize sidprefix */
39455731Sbaban 		free(req->id2.idmap_id_u.sid.prefix);
39465731Sbaban 		req->id2.idmap_id_u.sid.prefix = NULL;
39475731Sbaban 	}
39485731Sbaban 
39496386Sjp151216 	/* Find pid */
39506386Sjp151216 	if (req->id1.idmap_id_u.uid == SENTINEL_PID) {
39516386Sjp151216 		if (ns_lookup_byname(req->id1name, NULL, &req->id1)
39526386Sjp151216 		    != IDMAP_SUCCESS) {
39536386Sjp151216 			retcode = IDMAP_ERR_NOMAPPING;
39546386Sjp151216 			goto out;
39556386Sjp151216 		}
39566386Sjp151216 	}
39576386Sjp151216 
39585731Sbaban 	/* Lookup well-known SIDs table */
39594520Snw141292 	retcode = lookup_wksids_pid2sid(req, res, is_user);
39604520Snw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
39614520Snw141292 		goto out;
39624520Snw141292 
39635731Sbaban 	/* Lookup cache */
39646616Sdm199847 	retcode = lookup_cache_pid2sid(state->cache, req, res, is_user,
39656616Sdm199847 	    getname);
39664520Snw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
39674520Snw141292 		goto out;
39684520Snw141292 
39694520Snw141292 	/* Ephemeral ids cannot be allocated during pid2sid */
39704520Snw141292 	if (IS_EPHEMERAL(req->id1.idmap_id_u.uid)) {
39714864Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
39724520Snw141292 		goto out;
39734520Snw141292 	}
39744520Snw141292 
39756386Sjp151216 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req)) {
39766386Sjp151216 		retcode = IDMAP_ERR_NONEGENERATED;
39776386Sjp151216 		goto out;
39786386Sjp151216 	}
39796386Sjp151216 
39806386Sjp151216 	if (AVOID_NAMESERVICE(req)) {
39815731Sbaban 		gen_localsid_on_err = TRUE;
39824864Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
39834520Snw141292 		goto out;
39844520Snw141292 	}
39854520Snw141292 
39865731Sbaban 	/* Set flags for the next stage */
39875731Sbaban 	if (AD_MODE(req->id1.idtype, state)) {
39885731Sbaban 		/*
39895731Sbaban 		 * If AD-based name mapping is enabled then the next stage
39905731Sbaban 		 * will need to lookup AD using unixname to get the
39915731Sbaban 		 * corresponding winname.
39925731Sbaban 		 */
39935731Sbaban 		if (req->id1name == NULL) {
39945731Sbaban 			/* Get unixname if only pid is given. */
39955731Sbaban 			retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid,
39965731Sbaban 			    is_user, &req->id1name);
39976616Sdm199847 			if (retcode != IDMAP_SUCCESS) {
39986616Sdm199847 				gen_localsid_on_err = TRUE;
39995731Sbaban 				goto out;
40006616Sdm199847 			}
40014520Snw141292 		}
40025731Sbaban 		req->direction |= _IDMAP_F_LOOKUP_AD;
40035731Sbaban 		state->ad_nqueries++;
40045731Sbaban 	} else if (NLDAP_OR_MIXED_MODE(req->id1.idtype, state)) {
40055731Sbaban 		/*
40065731Sbaban 		 * If native LDAP or mixed mode is enabled for name mapping
40075731Sbaban 		 * then the next stage will need to lookup native LDAP using
40085731Sbaban 		 * unixname/pid to get the corresponding winname.
40095731Sbaban 		 */
40105731Sbaban 		req->direction |= _IDMAP_F_LOOKUP_NLDAP;
40115731Sbaban 		state->nldap_nqueries++;
40125731Sbaban 	}
40135731Sbaban 
40145731Sbaban 	/*
40155731Sbaban 	 * Failed to find non-expired entry in cache. Set the flag to
40165731Sbaban 	 * indicate that we are not done yet.
40175731Sbaban 	 */
40185731Sbaban 	state->pid2sid_done = FALSE;
40195731Sbaban 	req->direction |= _IDMAP_F_NOTDONE;
40205731Sbaban 	retcode = IDMAP_SUCCESS;
40215731Sbaban 
40225731Sbaban out:
40235731Sbaban 	res->retcode = idmap_stat4prot(retcode);
40245731Sbaban 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
40255731Sbaban 		if (gen_localsid_on_err == TRUE)
40266386Sjp151216 			(void) generate_localsid(req, res, is_user, TRUE);
40275731Sbaban 	return (retcode);
40285731Sbaban }
40295731Sbaban 
40305731Sbaban idmap_retcode
40316616Sdm199847 pid2sid_second_pass(lookup_state_t *state, idmap_mapping *req,
40326616Sdm199847 	idmap_id_res *res, int is_user)
40335731Sbaban {
40345731Sbaban 	bool_t		gen_localsid_on_err = TRUE;
40355731Sbaban 	idmap_retcode	retcode = IDMAP_SUCCESS;
40365731Sbaban 
40375731Sbaban 	/* Check if second pass is needed */
40385731Sbaban 	if (ARE_WE_DONE(req->direction))
40395731Sbaban 		return (res->retcode);
40405731Sbaban 
40415731Sbaban 	/* Get status from previous pass */
40425731Sbaban 	retcode = res->retcode;
40435731Sbaban 	if (retcode != IDMAP_SUCCESS)
40445731Sbaban 		goto out;
40455731Sbaban 
40465731Sbaban 	/*
40475731Sbaban 	 * If directory-based name mapping is enabled then the winname
40485731Sbaban 	 * may already have been retrieved from the AD object (AD-mode)
40496616Sdm199847 	 * or from native LDAP object (nldap-mode or mixed-mode).
40506616Sdm199847 	 * Note that if we have winname but no SID then it's an error
40516616Sdm199847 	 * because this implies that the Native LDAP entry contains
40526616Sdm199847 	 * winname which does not exist and it's better that we return
40536616Sdm199847 	 * an error instead of doing rule-based mapping so that the user
40546616Sdm199847 	 * can detect the issue and take appropriate action.
40555731Sbaban 	 */
40566616Sdm199847 	if (req->id2name != NULL) {
40576616Sdm199847 		/* Return notfound if we've winname but no SID. */
40586616Sdm199847 		if (res->id.idmap_id_u.sid.prefix == NULL) {
40596616Sdm199847 			retcode = IDMAP_ERR_NOTFOUND;
40606616Sdm199847 			goto out;
40616616Sdm199847 		}
40625731Sbaban 		if (AD_MODE(req->id1.idtype, state))
40635731Sbaban 			res->direction = IDMAP_DIRECTION_BI;
40645731Sbaban 		else if (NLDAP_MODE(req->id1.idtype, state))
40655731Sbaban 			res->direction = IDMAP_DIRECTION_BI;
40665731Sbaban 		else if (MIXED_MODE(req->id1.idtype, state))
40675731Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
40685731Sbaban 		goto out;
40696616Sdm199847 	} else if (res->id.idmap_id_u.sid.prefix != NULL) {
40706616Sdm199847 		/*
40716616Sdm199847 		 * We've SID but no winname. This is fine because
40726616Sdm199847 		 * the caller may have only requested SID.
40736616Sdm199847 		 */
40746616Sdm199847 		goto out;
40755731Sbaban 	}
40765731Sbaban 
40776616Sdm199847 	/* Free any mapping info from Directory based mapping */
40786616Sdm199847 	if (res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN)
40796616Sdm199847 		idmap_info_free(&res->info);
40806616Sdm199847 
40815731Sbaban 	if (req->id1name == NULL) {
40825731Sbaban 		/* Get unixname from name service */
40835731Sbaban 		retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid, is_user,
40845731Sbaban 		    &req->id1name);
40855731Sbaban 		if (retcode != IDMAP_SUCCESS)
40865731Sbaban 			goto out;
40875731Sbaban 	} else if (req->id1.idmap_id_u.uid == SENTINEL_PID) {
40885731Sbaban 		/* Get pid from name service */
40895731Sbaban 		retcode = ns_lookup_byname(req->id1name, NULL, &req->id1);
40905731Sbaban 		if (retcode != IDMAP_SUCCESS) {
40915731Sbaban 			gen_localsid_on_err = FALSE;
40925731Sbaban 			goto out;
40934520Snw141292 		}
40944520Snw141292 	}
40954520Snw141292 
40965731Sbaban 	/* Use unixname to evaluate local name-based mapping rules */
40976616Sdm199847 	retcode = name_based_mapping_pid2sid(state, req->id1name, is_user,
40985696Snw141292 	    req, res);
40994520Snw141292 	if (retcode == IDMAP_ERR_NOTFOUND) {
41006386Sjp151216 		retcode = generate_localsid(req, res, is_user, FALSE);
41015731Sbaban 		gen_localsid_on_err = FALSE;
41025731Sbaban 	}
41034520Snw141292 
41044520Snw141292 out:
41055731Sbaban 	res->retcode = idmap_stat4prot(retcode);
41065731Sbaban 	if (res->retcode != IDMAP_SUCCESS) {
41075731Sbaban 		req->direction = _IDMAP_F_DONE;
41086616Sdm199847 		free(req->id2name);
41096616Sdm199847 		req->id2name = NULL;
41106616Sdm199847 		free(req->id2domain);
41116616Sdm199847 		req->id2domain = NULL;
41125731Sbaban 		if (gen_localsid_on_err == TRUE)
41136386Sjp151216 			(void) generate_localsid(req, res, is_user, TRUE);
41146616Sdm199847 		else
41156616Sdm199847 			res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
41164520Snw141292 	}
41175731Sbaban 	if (!ARE_WE_DONE(req->direction))
41184520Snw141292 		state->pid2sid_done = FALSE;
41194520Snw141292 	return (retcode);
41204520Snw141292 }
41214520Snw141292 
41225696Snw141292 static
41235696Snw141292 int
41244644Sbaban copy_mapping_request(idmap_mapping *mapping, idmap_mapping *request)
41254520Snw141292 {
41264644Sbaban 	(void) memset(mapping, 0, sizeof (*mapping));
41274644Sbaban 
41284520Snw141292 	mapping->flag = request->flag;
41295731Sbaban 	mapping->direction = _IDMAP_F_DONE;
41304644Sbaban 	mapping->id2.idtype = request->id2.idtype;
41314520Snw141292 
41324520Snw141292 	mapping->id1.idtype = request->id1.idtype;
41335696Snw141292 	if (IS_REQUEST_SID(*request, 1)) {
41344520Snw141292 		mapping->id1.idmap_id_u.sid.rid =
41354520Snw141292 		    request->id1.idmap_id_u.sid.rid;
41364644Sbaban 		if (!EMPTY_STRING(request->id1.idmap_id_u.sid.prefix)) {
41374520Snw141292 			mapping->id1.idmap_id_u.sid.prefix =
41384520Snw141292 			    strdup(request->id1.idmap_id_u.sid.prefix);
41394644Sbaban 			if (mapping->id1.idmap_id_u.sid.prefix == NULL)
41405064Sdm199847 				goto errout;
41414644Sbaban 		}
41424520Snw141292 	} else {
41434520Snw141292 		mapping->id1.idmap_id_u.uid = request->id1.idmap_id_u.uid;
41444520Snw141292 	}
41454520Snw141292 
41465731Sbaban 	if (!EMPTY_STRING(request->id1domain)) {
41475731Sbaban 		mapping->id1domain = strdup(request->id1domain);
41485731Sbaban 		if (mapping->id1domain == NULL)
41495731Sbaban 			goto errout;
41505731Sbaban 	}
41515731Sbaban 
41525731Sbaban 	if (!EMPTY_STRING(request->id1name)) {
41535731Sbaban 		mapping->id1name = strdup(request->id1name);
41545731Sbaban 		if (mapping->id1name == NULL)
41555731Sbaban 			goto errout;
41565731Sbaban 	}
41574520Snw141292 
41584644Sbaban 	/* We don't need the rest of the request i.e request->id2 */
41594644Sbaban 	return (0);
41604644Sbaban 
41614644Sbaban errout:
41625064Sdm199847 	if (mapping->id1.idmap_id_u.sid.prefix != NULL)
41634644Sbaban 		free(mapping->id1.idmap_id_u.sid.prefix);
41645064Sdm199847 	if (mapping->id1domain != NULL)
41655064Sdm199847 		free(mapping->id1domain);
41665064Sdm199847 	if (mapping->id1name != NULL)
41675064Sdm199847 		free(mapping->id1name);
41684644Sbaban 
41694644Sbaban 	(void) memset(mapping, 0, sizeof (*mapping));
41704644Sbaban 	return (-1);
41714520Snw141292 }
41724520Snw141292 
41734520Snw141292 
41744520Snw141292 idmap_retcode
41754520Snw141292 get_w2u_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
41765696Snw141292 		idmap_mapping *mapping)
41775696Snw141292 {
41784520Snw141292 	idmap_id_res	idres;
41794520Snw141292 	lookup_state_t	state;
41805043Sbaban 	char		*cp;
41814520Snw141292 	idmap_retcode	retcode;
41824520Snw141292 	const char	*winname, *windomain;
41834520Snw141292 
41844520Snw141292 	(void) memset(&idres, 0, sizeof (idres));
41854520Snw141292 	(void) memset(&state, 0, sizeof (state));
41866616Sdm199847 	state.cache = cache;
41876616Sdm199847 	state.db = db;
41884520Snw141292 
41895731Sbaban 	/* Get directory-based name mapping info */
41906616Sdm199847 	retcode = load_cfg_in_state(&state);
41915731Sbaban 	if (retcode != IDMAP_SUCCESS)
41924520Snw141292 		goto out;
41935731Sbaban 
41945731Sbaban 	/*
41955731Sbaban 	 * Copy data from "request" to "mapping". Note that
41965731Sbaban 	 * empty strings are not copied from "request" to
41975731Sbaban 	 * "mapping" and therefore the coresponding strings in
41985731Sbaban 	 * "mapping" will be NULL. This eliminates having to
41995731Sbaban 	 * check for empty strings henceforth.
42005731Sbaban 	 */
42014644Sbaban 	if (copy_mapping_request(mapping, request) < 0) {
42024644Sbaban 		retcode = IDMAP_ERR_MEMORY;
42034644Sbaban 		goto out;
42044644Sbaban 	}
42054520Snw141292 
42065064Sdm199847 	winname = mapping->id1name;
42075064Sdm199847 	windomain = mapping->id1domain;
42084520Snw141292 
42095731Sbaban 	if (winname == NULL && windomain != NULL) {
42105731Sbaban 		retcode = IDMAP_ERR_ARG;
42115731Sbaban 		goto out;
42125731Sbaban 	}
42135731Sbaban 
42145731Sbaban 	/* Need atleast winname or sid to proceed */
42155731Sbaban 	if (winname == NULL && mapping->id1.idmap_id_u.sid.prefix == NULL) {
42164520Snw141292 		retcode = IDMAP_ERR_ARG;
42174520Snw141292 		goto out;
42184520Snw141292 	}
42194520Snw141292 
42205731Sbaban 	/*
42215731Sbaban 	 * If domainname is not given but we have a fully qualified
42225731Sbaban 	 * winname then extract the domainname from the winname,
42235731Sbaban 	 * otherwise use the default_domain from the config
42245731Sbaban 	 */
42255731Sbaban 	if (winname != NULL && windomain == NULL) {
42265064Sdm199847 		retcode = IDMAP_SUCCESS;
42275043Sbaban 		if ((cp = strchr(winname, '@')) != NULL) {
42285043Sbaban 			*cp = '\0';
42295064Sdm199847 			mapping->id1domain = strdup(cp + 1);
42305064Sdm199847 			if (mapping->id1domain == NULL)
42315064Sdm199847 				retcode = IDMAP_ERR_MEMORY;
42325731Sbaban 		} else if (lookup_wksids_name2sid(winname, NULL, NULL, NULL,
42335731Sbaban 		    NULL) != IDMAP_SUCCESS) {
42346950Sbaban 			if (state.defdom == NULL) {
42356950Sbaban 				/*
42366950Sbaban 				 * We have a non-qualified winname which is
42376950Sbaban 				 * neither the name of a well-known SID nor
42386950Sbaban 				 * there is a default domain with which we can
42396950Sbaban 				 * qualify it.
42406950Sbaban 				 */
42416950Sbaban 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
42426950Sbaban 			} else {
42436950Sbaban 				mapping->id1domain = strdup(state.defdom);
42446950Sbaban 				if (mapping->id1domain == NULL)
42456950Sbaban 					retcode = IDMAP_ERR_MEMORY;
42466950Sbaban 			}
42475064Sdm199847 		}
42484520Snw141292 		if (retcode != IDMAP_SUCCESS)
42494520Snw141292 			goto out;
42504520Snw141292 	}
42514520Snw141292 
42525731Sbaban 	/*
42535731Sbaban 	 * First pass looks up the well-known SIDs table and cache
42545731Sbaban 	 * and handles localSIDs
42555731Sbaban 	 */
42564520Snw141292 	state.sid2pid_done = TRUE;
42576616Sdm199847 	retcode = sid2pid_first_pass(&state, mapping, &idres);
42584520Snw141292 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
42594520Snw141292 		goto out;
42604520Snw141292 
42616616Sdm199847 	/* AD lookup */
42625731Sbaban 	if (state.ad_nqueries > 0) {
42636616Sdm199847 		retcode = ad_lookup_one(&state, mapping, &idres);
42645731Sbaban 		if (IDMAP_ERROR(retcode))
42655731Sbaban 			goto out;
42664520Snw141292 	}
42674520Snw141292 
42686616Sdm199847 	/* nldap lookup */
42696616Sdm199847 	if (state.nldap_nqueries > 0) {
42706616Sdm199847 		retcode = nldap_lookup_one(&state, mapping, &idres);
42716616Sdm199847 		if (IDMAP_FATAL_ERROR(retcode))
42725731Sbaban 			goto out;
42735731Sbaban 	}
42745731Sbaban 
42755731Sbaban 	/* Next pass performs name-based mapping and ephemeral mapping. */
42764520Snw141292 	state.sid2pid_done = TRUE;
42776616Sdm199847 	retcode = sid2pid_second_pass(&state, mapping, &idres);
42784520Snw141292 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
42794520Snw141292 		goto out;
42804520Snw141292 
42814520Snw141292 	/* Update cache */
42826616Sdm199847 	(void) update_cache_sid2pid(&state, mapping, &idres);
42834520Snw141292 
42844520Snw141292 out:
42855731Sbaban 	/*
42865731Sbaban 	 * Note that "mapping" is returned to the client. Therefore
42875731Sbaban 	 * copy whatever we have in "idres" to mapping->id2 and
42885731Sbaban 	 * free idres.
42895731Sbaban 	 */
42905731Sbaban 	mapping->direction = idres.direction;
42915731Sbaban 	mapping->id2 = idres.id;
42926386Sjp151216 	if (mapping->flag & IDMAP_REQ_FLG_MAPPING_INFO ||
42936386Sjp151216 	    retcode != IDMAP_SUCCESS)
42946386Sjp151216 		(void) idmap_info_mov(&mapping->info, &idres.info);
42956386Sjp151216 	else
42966386Sjp151216 		idmap_info_free(&idres.info);
42975731Sbaban 	(void) memset(&idres, 0, sizeof (idres));
42985731Sbaban 	if (retcode != IDMAP_SUCCESS)
42994864Sbaban 		mapping->id2.idmap_id_u.uid = UID_NOBODY;
43004520Snw141292 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
43015731Sbaban 	cleanup_lookup_state(&state);
43024520Snw141292 	return (retcode);
43034520Snw141292 }
43044520Snw141292 
43054520Snw141292 idmap_retcode
43064520Snw141292 get_u2w_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
43075696Snw141292 		idmap_mapping *mapping, int is_user)
43085696Snw141292 {
43094520Snw141292 	idmap_id_res	idres;
43104520Snw141292 	lookup_state_t	state;
43114520Snw141292 	idmap_retcode	retcode;
43124520Snw141292 
43134520Snw141292 	/*
43144520Snw141292 	 * In order to re-use the pid2sid code, we convert
43154520Snw141292 	 * our input data into structs that are expected by
43164520Snw141292 	 * pid2sid_first_pass.
43174520Snw141292 	 */
43184520Snw141292 
43194520Snw141292 	(void) memset(&idres, 0, sizeof (idres));
43204520Snw141292 	(void) memset(&state, 0, sizeof (state));
43216616Sdm199847 	state.cache = cache;
43226616Sdm199847 	state.db = db;
43234520Snw141292 
43245731Sbaban 	/* Get directory-based name mapping info */
43256616Sdm199847 	retcode = load_cfg_in_state(&state);
43265731Sbaban 	if (retcode != IDMAP_SUCCESS)
43275731Sbaban 		goto out;
43285731Sbaban 
43295731Sbaban 	/*
43305731Sbaban 	 * Copy data from "request" to "mapping". Note that
43315731Sbaban 	 * empty strings are not copied from "request" to
43325731Sbaban 	 * "mapping" and therefore the coresponding strings in
43335731Sbaban 	 * "mapping" will be NULL. This eliminates having to
43345731Sbaban 	 * check for empty strings henceforth.
43355731Sbaban 	 */
43364644Sbaban 	if (copy_mapping_request(mapping, request) < 0) {
43374644Sbaban 		retcode = IDMAP_ERR_MEMORY;
43384644Sbaban 		goto out;
43394644Sbaban 	}
43404520Snw141292 
43415731Sbaban 	/*
43425731Sbaban 	 * For unix to windows mapping request, we need atleast a
43435731Sbaban 	 * unixname or uid/gid to proceed
43445731Sbaban 	 */
43455731Sbaban 	if (mapping->id1name == NULL &&
43465127Sdm199847 	    mapping->id1.idmap_id_u.uid == SENTINEL_PID) {
43474520Snw141292 		retcode = IDMAP_ERR_ARG;
43484520Snw141292 		goto out;
43494520Snw141292 	}
43504520Snw141292 
43515731Sbaban 	/* First pass looks up cache and well-known SIDs */
43525731Sbaban 	state.pid2sid_done = TRUE;
43536616Sdm199847 	retcode = pid2sid_first_pass(&state, mapping, &idres, is_user, 1);
43545731Sbaban 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
43555731Sbaban 		goto out;
43565731Sbaban 
43576616Sdm199847 	/* nldap lookup */
43585731Sbaban 	if (state.nldap_nqueries > 0) {
43596616Sdm199847 		retcode = nldap_lookup_one(&state, mapping, &idres);
43605731Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
43615731Sbaban 			goto out;
43626616Sdm199847 	}
43636616Sdm199847 
43646616Sdm199847 	/* AD lookup */
43656616Sdm199847 	if (state.ad_nqueries > 0) {
43666616Sdm199847 		retcode = ad_lookup_one(&state, mapping, &idres);
43675731Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
43685731Sbaban 			goto out;
43694520Snw141292 	}
43704520Snw141292 
43715731Sbaban 	/*
43725731Sbaban 	 * Next pass processes the result of the preceding passes/lookups.
43735731Sbaban 	 * It returns if there's nothing more to be done otherwise it
43745731Sbaban 	 * evaluates local name-based mapping rules
43755731Sbaban 	 */
43764520Snw141292 	state.pid2sid_done = TRUE;
43776616Sdm199847 	retcode = pid2sid_second_pass(&state, mapping, &idres, is_user);
43784520Snw141292 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
43794520Snw141292 		goto out;
43804520Snw141292 
43814520Snw141292 	/* Update cache */
43826616Sdm199847 	(void) update_cache_pid2sid(&state, mapping, &idres);
43834520Snw141292 
43844520Snw141292 out:
43855731Sbaban 	/*
43865731Sbaban 	 * Note that "mapping" is returned to the client. Therefore
43875731Sbaban 	 * copy whatever we have in "idres" to mapping->id2 and
43885731Sbaban 	 * free idres.
43895731Sbaban 	 */
43904520Snw141292 	mapping->direction = idres.direction;
43914520Snw141292 	mapping->id2 = idres.id;
43926386Sjp151216 	if (mapping->flag & IDMAP_REQ_FLG_MAPPING_INFO ||
43936386Sjp151216 	    retcode != IDMAP_SUCCESS)
43946386Sjp151216 		(void) idmap_info_mov(&mapping->info, &idres.info);
43956386Sjp151216 	else
43966386Sjp151216 		idmap_info_free(&idres.info);
43974520Snw141292 	(void) memset(&idres, 0, sizeof (idres));
43984520Snw141292 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
43995731Sbaban 	cleanup_lookup_state(&state);
44004520Snw141292 	return (retcode);
44014520Snw141292 }
44025731Sbaban 
44036616Sdm199847 /*ARGSUSED*/
44045731Sbaban static
44055731Sbaban idmap_retcode
44066616Sdm199847 ad_lookup_one(lookup_state_t *state, idmap_mapping *req, idmap_id_res *res)
44075731Sbaban {
44086616Sdm199847 	idmap_mapping_batch	batch;
44096616Sdm199847 	idmap_ids_res		result;
44106616Sdm199847 
44116616Sdm199847 	batch.idmap_mapping_batch_len = 1;
44126616Sdm199847 	batch.idmap_mapping_batch_val = req;
44136616Sdm199847 	result.ids.ids_len = 1;
44146616Sdm199847 	result.ids.ids_val = res;
44156616Sdm199847 	return (ad_lookup_batch(state, &batch, &result));
44165731Sbaban }
4417