xref: /onnv-gate/usr/src/cmd/idmap/idmapd/dbutils.c (revision 8671:d3ec1a19966c)
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 /*
22*8671SJulian.Pullen@Sun.COM  * Copyright 2009 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 
708040SBaban.Kenkre@Sun.COM #define	ALLOW_WK_OR_LOCAL_SIDS_ONLY(req)\
718040SBaban.Kenkre@Sun.COM 		(req->flag & IDMAP_REQ_FLG_WK_OR_LOCAL_SIDS_ONLY)
728040SBaban.Kenkre@Sun.COM 
735731Sbaban #define	IS_EPHEMERAL(pid)	(pid > INT32_MAX && pid != SENTINEL_PID)
744520Snw141292 
754520Snw141292 #define	LOCALRID_MIN	1000
764520Snw141292 
774520Snw141292 
784520Snw141292 typedef enum init_db_option {
794520Snw141292 	FAIL_IF_CORRUPT = 0,
804520Snw141292 	REMOVE_IF_CORRUPT = 1
814520Snw141292 } init_db_option_t;
824520Snw141292 
834884Sjp151216 /*
845731Sbaban  * Data structure to store well-known SIDs and
855731Sbaban  * associated mappings (if any)
865731Sbaban  */
875731Sbaban typedef struct wksids_table {
885731Sbaban 	const char	*sidprefix;
895731Sbaban 	uint32_t	rid;
905731Sbaban 	const char	*winname;
915731Sbaban 	int		is_wuser;
925731Sbaban 	uid_t		pid;
935731Sbaban 	int		is_user;
945731Sbaban 	int		direction;
955731Sbaban } wksids_table_t;
965731Sbaban 
975731Sbaban /*
984884Sjp151216  * Thread specfic data to hold the database handles so that the
994884Sjp151216  * databaes are not opened and closed for every request. It also
1004884Sjp151216  * contains the sqlite busy handler structure.
1014884Sjp151216  */
1024884Sjp151216 
1034884Sjp151216 struct idmap_busy {
1044884Sjp151216 	const char *name;
1054884Sjp151216 	const int *delays;
1064884Sjp151216 	int delay_size;
1074884Sjp151216 	int total;
1084884Sjp151216 	int sec;
1094884Sjp151216 };
1104884Sjp151216 
1114884Sjp151216 
1124884Sjp151216 typedef struct idmap_tsd {
1134884Sjp151216 	sqlite *db_db;
1144884Sjp151216 	sqlite *cache_db;
1154884Sjp151216 	struct idmap_busy cache_busy;
1164884Sjp151216 	struct idmap_busy db_busy;
1174884Sjp151216 } idmap_tsd_t;
1184884Sjp151216 
1194884Sjp151216 
1204884Sjp151216 
1214884Sjp151216 static const int cache_delay_table[] =
1224884Sjp151216 		{ 1, 2, 5, 10, 15, 20, 25, 30,  35,  40,
1234884Sjp151216 		50,  50, 60, 70, 80, 90, 100};
1244884Sjp151216 
1254884Sjp151216 static const int db_delay_table[] =
1264884Sjp151216 		{ 5, 10, 15, 20, 30,  40,  55,  70, 100};
1274884Sjp151216 
1284884Sjp151216 
1294884Sjp151216 static pthread_key_t	idmap_tsd_key;
1304884Sjp151216 
1314884Sjp151216 void
1324884Sjp151216 idmap_tsd_destroy(void *key)
1334884Sjp151216 {
1344884Sjp151216 
1354884Sjp151216 	idmap_tsd_t	*tsd = (idmap_tsd_t *)key;
1364884Sjp151216 	if (tsd) {
1374884Sjp151216 		if (tsd->db_db)
1384884Sjp151216 			(void) sqlite_close(tsd->db_db);
1394884Sjp151216 		if (tsd->cache_db)
1404884Sjp151216 			(void) sqlite_close(tsd->cache_db);
1414884Sjp151216 		free(tsd);
1424884Sjp151216 	}
1434884Sjp151216 }
1444884Sjp151216 
1454884Sjp151216 int
1465696Snw141292 idmap_init_tsd_key(void)
1475696Snw141292 {
1484884Sjp151216 	return (pthread_key_create(&idmap_tsd_key, idmap_tsd_destroy));
1494884Sjp151216 }
1504884Sjp151216 
1514884Sjp151216 
1524884Sjp151216 
1534884Sjp151216 idmap_tsd_t *
1544884Sjp151216 idmap_get_tsd(void)
1554884Sjp151216 {
1564884Sjp151216 	idmap_tsd_t	*tsd;
1574884Sjp151216 
1584884Sjp151216 	if ((tsd = pthread_getspecific(idmap_tsd_key)) == NULL) {
1594884Sjp151216 		/* No thread specific data so create it */
1604884Sjp151216 		if ((tsd = malloc(sizeof (*tsd))) != NULL) {
1614884Sjp151216 			/* Initialize thread specific data */
1624884Sjp151216 			(void) memset(tsd, 0, sizeof (*tsd));
1634884Sjp151216 			/* save the trhread specific data */
1644884Sjp151216 			if (pthread_setspecific(idmap_tsd_key, tsd) != 0) {
1654884Sjp151216 				/* Can't store key */
1664884Sjp151216 				free(tsd);
1674884Sjp151216 				tsd = NULL;
1684884Sjp151216 			}
1694884Sjp151216 		} else {
1704884Sjp151216 			tsd = NULL;
1714884Sjp151216 		}
1724884Sjp151216 	}
1734884Sjp151216 
1744884Sjp151216 	return (tsd);
1754884Sjp151216 }
1764884Sjp151216 
1775696Snw141292 /*
1785696Snw141292  * A simple wrapper around u8_textprep_str() that returns the Unicode
1795696Snw141292  * lower-case version of some string.  The result must be freed.
1805696Snw141292  */
1815696Snw141292 char *
1825696Snw141292 tolower_u8(const char *s)
1835696Snw141292 {
1845696Snw141292 	char *res = NULL;
1855696Snw141292 	char *outs;
1865696Snw141292 	size_t inlen, outlen, inbytesleft, outbytesleft;
1875696Snw141292 	int rc, err;
1885696Snw141292 
1895696Snw141292 	/*
1905696Snw141292 	 * u8_textprep_str() does not allocate memory.  The input and
1915696Snw141292 	 * output buffers may differ in size (though that would be more
1925696Snw141292 	 * likely when normalization is done).  We have to loop over it...
1935696Snw141292 	 *
1945696Snw141292 	 * To improve the chances that we can avoid looping we add 10
1955696Snw141292 	 * bytes of output buffer room the first go around.
1965696Snw141292 	 */
1975696Snw141292 	inlen = inbytesleft = strlen(s);
1985696Snw141292 	outlen = outbytesleft = inlen + 10;
1995696Snw141292 	if ((res = malloc(outlen)) == NULL)
2005696Snw141292 		return (NULL);
2015696Snw141292 	outs = res;
2025696Snw141292 
2035696Snw141292 	while ((rc = u8_textprep_str((char *)s, &inbytesleft, outs,
2045696Snw141292 	    &outbytesleft, U8_TEXTPREP_TOLOWER, U8_UNICODE_LATEST, &err)) < 0 &&
2055696Snw141292 	    err == E2BIG) {
2065696Snw141292 		if ((res = realloc(res, outlen + inbytesleft)) == NULL)
2075696Snw141292 			return (NULL);
2085696Snw141292 		/* adjust input/output buffer pointers */
2095696Snw141292 		s += (inlen - inbytesleft);
2105696Snw141292 		outs = res + outlen - outbytesleft;
2115696Snw141292 		/* adjust outbytesleft and outlen */
2125696Snw141292 		outlen += inbytesleft;
2135696Snw141292 		outbytesleft += inbytesleft;
2145696Snw141292 	}
2155696Snw141292 
2165696Snw141292 	if (rc < 0) {
2175696Snw141292 		free(res);
2185696Snw141292 		res = NULL;
2195696Snw141292 		return (NULL);
2205696Snw141292 	}
2215696Snw141292 
2225696Snw141292 	res[outlen - outbytesleft] = '\0';
2235696Snw141292 
2245696Snw141292 	return (res);
2255696Snw141292 }
2265696Snw141292 
2275696Snw141292 static int sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
2285696Snw141292 	const char *while_doing);
2295696Snw141292 
2304520Snw141292 
2314520Snw141292 /*
2324520Snw141292  * Initialize 'dbname' using 'sql'
2334520Snw141292  */
2345696Snw141292 static
2355696Snw141292 int
2365696Snw141292 init_db_instance(const char *dbname, int version,
2375696Snw141292 	const char *detect_version_sql, char * const *sql,
2385696Snw141292 	init_db_option_t opt, int *created, int *upgraded)
2394520Snw141292 {
2405696Snw141292 	int rc, curr_version;
2415696Snw141292 	int tries = 1;
2425696Snw141292 	int prio = LOG_NOTICE;
2434520Snw141292 	sqlite *db = NULL;
2445696Snw141292 	char *errmsg = NULL;
2455696Snw141292 
2465696Snw141292 	*created = 0;
2475696Snw141292 	*upgraded = 0;
2485696Snw141292 
2495696Snw141292 	if (opt == REMOVE_IF_CORRUPT)
2505696Snw141292 		tries = 3;
2515696Snw141292 
2525696Snw141292 rinse_repeat:
2535696Snw141292 	if (tries == 0) {
2545696Snw141292 		idmapdlog(LOG_ERR, "Failed to initialize db %s", dbname);
2555696Snw141292 		return (-1);
2565696Snw141292 	}
2575696Snw141292 	if (tries-- == 1)
2585696Snw141292 		/* Last try, log errors */
2595696Snw141292 		prio = LOG_ERR;
2605696Snw141292 
2615696Snw141292 	db = sqlite_open(dbname, 0600, &errmsg);
2625696Snw141292 	if (db == NULL) {
2635696Snw141292 		idmapdlog(prio, "Error creating database %s (%s)",
2645696Snw141292 		    dbname, CHECK_NULL(errmsg));
2655696Snw141292 		sqlite_freemem(errmsg);
2665696Snw141292 		if (opt == REMOVE_IF_CORRUPT)
2675696Snw141292 			(void) unlink(dbname);
2685696Snw141292 		goto rinse_repeat;
2694520Snw141292 	}
2704520Snw141292 
2714520Snw141292 	sqlite_busy_timeout(db, 3000);
2725696Snw141292 
2735696Snw141292 	/* Detect current version of schema in the db, if any */
2745696Snw141292 	curr_version = 0;
2755696Snw141292 	if (detect_version_sql != NULL) {
2765696Snw141292 		char *end, **results;
2775696Snw141292 		int nrow;
2785696Snw141292 
2795696Snw141292 #ifdef	IDMAPD_DEBUG
2805696Snw141292 		(void) fprintf(stderr, "Schema version detection SQL: %s\n",
2815696Snw141292 		    detect_version_sql);
2825696Snw141292 #endif	/* IDMAPD_DEBUG */
2835696Snw141292 		rc = sqlite_get_table(db, detect_version_sql, &results,
2845696Snw141292 		    &nrow, NULL, &errmsg);
2855696Snw141292 		if (rc != SQLITE_OK) {
2865696Snw141292 			idmapdlog(prio,
2875696Snw141292 			    "Error detecting schema version of db %s (%s)",
2885696Snw141292 			    dbname, errmsg);
2895696Snw141292 			sqlite_freemem(errmsg);
2905696Snw141292 			sqlite_free_table(results);
2915696Snw141292 			sqlite_close(db);
2925696Snw141292 			return (-1);
2935696Snw141292 		}
2945696Snw141292 		if (nrow != 1) {
2955696Snw141292 			idmapdlog(prio,
2965696Snw141292 			    "Error detecting schema version of db %s", dbname);
2975696Snw141292 			sqlite_close(db);
2985696Snw141292 			sqlite_free_table(results);
2995696Snw141292 			return (-1);
3005696Snw141292 		}
3015696Snw141292 		curr_version = strtol(results[1], &end, 10);
3025696Snw141292 		sqlite_free_table(results);
3034520Snw141292 	}
3044520Snw141292 
3055696Snw141292 	if (curr_version < 0) {
3065696Snw141292 		if (opt == REMOVE_IF_CORRUPT)
3075696Snw141292 			(void) unlink(dbname);
3085696Snw141292 		goto rinse_repeat;
3094520Snw141292 	}
3104520Snw141292 
3115696Snw141292 	if (curr_version == version)
3125696Snw141292 		goto done;
3135696Snw141292 
3145696Snw141292 	/* Install or upgrade schema */
3155696Snw141292 #ifdef	IDMAPD_DEBUG
3165696Snw141292 	(void) fprintf(stderr, "Schema init/upgrade SQL: %s\n",
3175696Snw141292 	    sql[curr_version]);
3185696Snw141292 #endif	/* IDMAPD_DEBUG */
3195696Snw141292 	rc = sql_exec_tran_no_cb(db, sql[curr_version], dbname,
3205696Snw141292 	    (curr_version == 0) ? "installing schema" : "upgrading schema");
3215696Snw141292 	if (rc != 0) {
3225696Snw141292 		idmapdlog(prio, "Error %s schema for db %s", dbname,
3235696Snw141292 		    (curr_version == 0) ? "installing schema" :
3245696Snw141292 		    "upgrading schema");
3255696Snw141292 		if (opt == REMOVE_IF_CORRUPT)
3265696Snw141292 			(void) unlink(dbname);
3275696Snw141292 		goto rinse_repeat;
3284520Snw141292 	}
3294520Snw141292 
3305696Snw141292 	*upgraded = (curr_version > 0);
3315696Snw141292 	*created = (curr_version == 0);
3325696Snw141292 
3335696Snw141292 done:
3344520Snw141292 	(void) sqlite_close(db);
3355696Snw141292 	return (0);
3364520Snw141292 }
3374520Snw141292 
3384884Sjp151216 
3394884Sjp151216 /*
3404884Sjp151216  * This is the SQLite database busy handler that retries the SQL
3414884Sjp151216  * operation until it is successful.
3424884Sjp151216  */
3434884Sjp151216 int
3444884Sjp151216 /* LINTED E_FUNC_ARG_UNUSED */
3454884Sjp151216 idmap_sqlite_busy_handler(void *arg, const char *table_name, int count)
3464884Sjp151216 {
3474884Sjp151216 	struct idmap_busy	*busy = arg;
3484884Sjp151216 	int			delay;
3494884Sjp151216 	struct timespec		rqtp;
3504884Sjp151216 
3514884Sjp151216 	if (count == 1)  {
3524884Sjp151216 		busy->total = 0;
3534884Sjp151216 		busy->sec = 2;
3544884Sjp151216 	}
3554884Sjp151216 	if (busy->total > 1000 * busy->sec) {
3566414Sjp151216 		idmapdlog(LOG_DEBUG,
3574884Sjp151216 		    "Thread %d waited %d sec for the %s database",
3584884Sjp151216 		    pthread_self(), busy->sec, busy->name);
3594884Sjp151216 		busy->sec++;
3604884Sjp151216 	}
3614884Sjp151216 
3624884Sjp151216 	if (count <= busy->delay_size) {
3634884Sjp151216 		delay = busy->delays[count-1];
3644884Sjp151216 	} else {
3654884Sjp151216 		delay = busy->delays[busy->delay_size - 1];
3664884Sjp151216 	}
3674884Sjp151216 	busy->total += delay;
3684884Sjp151216 	rqtp.tv_sec = 0;
3694884Sjp151216 	rqtp.tv_nsec = delay * (NANOSEC / MILLISEC);
3704884Sjp151216 	(void) nanosleep(&rqtp, NULL);
3714884Sjp151216 	return (1);
3724884Sjp151216 }
3734884Sjp151216 
3744884Sjp151216 
3754520Snw141292 /*
3764520Snw141292  * Get the database handle
3774520Snw141292  */
3784520Snw141292 idmap_retcode
3795696Snw141292 get_db_handle(sqlite **db)
3805696Snw141292 {
3815696Snw141292 	char		*errmsg;
3825696Snw141292 	idmap_tsd_t	*tsd;
3834520Snw141292 
3844520Snw141292 	/*
3854884Sjp151216 	 * Retrieve the db handle from thread-specific storage
3864520Snw141292 	 * If none exists, open and store in thread-specific storage.
3874520Snw141292 	 */
3884884Sjp151216 	if ((tsd = idmap_get_tsd()) == NULL) {
3894520Snw141292 		idmapdlog(LOG_ERR,
3905696Snw141292 		    "Error getting thread specific data for %s", IDMAP_DBNAME);
3914884Sjp151216 		return (IDMAP_ERR_MEMORY);
3924520Snw141292 	}
3934884Sjp151216 
3944884Sjp151216 	if (tsd->db_db == NULL) {
3954884Sjp151216 		tsd->db_db = sqlite_open(IDMAP_DBNAME, 0, &errmsg);
3964884Sjp151216 		if (tsd->db_db == NULL) {
3975696Snw141292 			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
3985696Snw141292 			    IDMAP_DBNAME, CHECK_NULL(errmsg));
3994884Sjp151216 			sqlite_freemem(errmsg);
4005696Snw141292 			return (IDMAP_ERR_DB);
4014884Sjp151216 		}
4025696Snw141292 
4034884Sjp151216 		tsd->db_busy.name = IDMAP_DBNAME;
4044884Sjp151216 		tsd->db_busy.delays = db_delay_table;
4054884Sjp151216 		tsd->db_busy.delay_size = sizeof (db_delay_table) /
4064884Sjp151216 		    sizeof (int);
4074884Sjp151216 		sqlite_busy_handler(tsd->db_db, idmap_sqlite_busy_handler,
4084884Sjp151216 		    &tsd->db_busy);
4094884Sjp151216 	}
4104884Sjp151216 	*db = tsd->db_db;
4114520Snw141292 	return (IDMAP_SUCCESS);
4124520Snw141292 }
4134520Snw141292 
4144520Snw141292 /*
4154520Snw141292  * Get the cache handle
4164520Snw141292  */
4174520Snw141292 idmap_retcode
4185696Snw141292 get_cache_handle(sqlite **cache)
4195696Snw141292 {
4205696Snw141292 	char		*errmsg;
4215696Snw141292 	idmap_tsd_t	*tsd;
4224520Snw141292 
4234520Snw141292 	/*
4244884Sjp151216 	 * Retrieve the db handle from thread-specific storage
4254520Snw141292 	 * If none exists, open and store in thread-specific storage.
4264520Snw141292 	 */
4274884Sjp151216 	if ((tsd = idmap_get_tsd()) == NULL) {
4285696Snw141292 		idmapdlog(LOG_ERR, "Error getting thread specific data for %s",
4295696Snw141292 		    IDMAP_DBNAME);
4304884Sjp151216 		return (IDMAP_ERR_MEMORY);
4314520Snw141292 	}
4324884Sjp151216 
4334884Sjp151216 	if (tsd->cache_db == NULL) {
4344884Sjp151216 		tsd->cache_db = sqlite_open(IDMAP_CACHENAME, 0, &errmsg);
4354884Sjp151216 		if (tsd->cache_db == NULL) {
4365696Snw141292 			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
4375696Snw141292 			    IDMAP_CACHENAME, CHECK_NULL(errmsg));
4384884Sjp151216 			sqlite_freemem(errmsg);
4395696Snw141292 			return (IDMAP_ERR_DB);
4404884Sjp151216 		}
4415696Snw141292 
4424884Sjp151216 		tsd->cache_busy.name = IDMAP_CACHENAME;
4434884Sjp151216 		tsd->cache_busy.delays = cache_delay_table;
4444884Sjp151216 		tsd->cache_busy.delay_size = sizeof (cache_delay_table) /
4454884Sjp151216 		    sizeof (int);
4464884Sjp151216 		sqlite_busy_handler(tsd->cache_db, idmap_sqlite_busy_handler,
4474884Sjp151216 		    &tsd->cache_busy);
4484884Sjp151216 	}
4494884Sjp151216 	*cache = tsd->cache_db;
4504520Snw141292 	return (IDMAP_SUCCESS);
4514520Snw141292 }
4524520Snw141292 
4534520Snw141292 /*
4544520Snw141292  * Initialize cache and db
4554520Snw141292  */
4564520Snw141292 int
4575696Snw141292 init_dbs()
4585696Snw141292 {
4596386Sjp151216 	char *sql[4];
4605696Snw141292 	int created, upgraded;
4615696Snw141292 
4624520Snw141292 	/* name-based mappings; probably OK to blow away in a pinch(?) */
4635696Snw141292 	sql[0] = DB_INSTALL_SQL;
4645696Snw141292 	sql[1] = DB_UPGRADE_FROM_v1_SQL;
4656386Sjp151216 	sql[2] = NULL;
4665696Snw141292 
4675696Snw141292 	if (init_db_instance(IDMAP_DBNAME, DB_VERSION, DB_VERSION_SQL, sql,
4685696Snw141292 	    FAIL_IF_CORRUPT, &created, &upgraded) < 0)
4694520Snw141292 		return (-1);
4704520Snw141292 
4714520Snw141292 	/* mappings, name/SID lookup cache + ephemeral IDs; OK to blow away */
4725696Snw141292 	sql[0] = CACHE_INSTALL_SQL;
4735696Snw141292 	sql[1] = CACHE_UPGRADE_FROM_v1_SQL;
4746386Sjp151216 	sql[2] = CACHE_UPGRADE_FROM_v2_SQL;
4756386Sjp151216 	sql[3] = NULL;
4766386Sjp151216 
4775696Snw141292 	if (init_db_instance(IDMAP_CACHENAME, CACHE_VERSION, CACHE_VERSION_SQL,
4785696Snw141292 	    sql, REMOVE_IF_CORRUPT, &created, &upgraded) < 0)
4794520Snw141292 		return (-1);
4804520Snw141292 
4815696Snw141292 	_idmapdstate.new_eph_db = (created || upgraded) ? 1 : 0;
4825696Snw141292 
4834520Snw141292 	return (0);
4844520Snw141292 }
4854520Snw141292 
4864520Snw141292 /*
4874520Snw141292  * Finalize databases
4884520Snw141292  */
4894520Snw141292 void
4905696Snw141292 fini_dbs()
4915696Snw141292 {
4924520Snw141292 }
4934520Snw141292 
4944520Snw141292 /*
4955731Sbaban  * This table is a listing of status codes that will be returned to the
4964520Snw141292  * client when a SQL command fails with the corresponding error message.
4974520Snw141292  */
4984520Snw141292 static msg_table_t sqlmsgtable[] = {
4994864Sbaban 	{IDMAP_ERR_U2W_NAMERULE_CONFLICT,
5004520Snw141292 	"columns unixname, is_user, u2w_order are not unique"},
5014864Sbaban 	{IDMAP_ERR_W2U_NAMERULE_CONFLICT,
5025696Snw141292 	"columns winname, windomain, is_user, is_wuser, w2u_order are not"
5035696Snw141292 	" unique"},
5045696Snw141292 	{IDMAP_ERR_W2U_NAMERULE_CONFLICT, "Conflicting w2u namerules"},
5054520Snw141292 	{-1, NULL}
5064520Snw141292 };
5074520Snw141292 
5084520Snw141292 /*
5094520Snw141292  * idmapd's version of string2stat to map SQLite messages to
5104520Snw141292  * status codes
5114520Snw141292  */
5124520Snw141292 idmap_retcode
5135696Snw141292 idmapd_string2stat(const char *msg)
5145696Snw141292 {
5154520Snw141292 	int i;
5164520Snw141292 	for (i = 0; sqlmsgtable[i].msg; i++) {
5174520Snw141292 		if (strcasecmp(sqlmsgtable[i].msg, msg) == 0)
5184520Snw141292 			return (sqlmsgtable[i].retcode);
5194520Snw141292 	}
5204520Snw141292 	return (IDMAP_ERR_OTHER);
5214520Snw141292 }
5224520Snw141292 
5234520Snw141292 /*
5245696Snw141292  * Executes some SQL in a transaction.
5255696Snw141292  *
5265696Snw141292  * Returns 0 on success, -1 if it failed but the rollback succeeded, -2
5275696Snw141292  * if the rollback failed.
5285696Snw141292  */
5295696Snw141292 static
5305696Snw141292 int
5315696Snw141292 sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
5325696Snw141292 	const char *while_doing)
5335696Snw141292 {
5345696Snw141292 	char		*errmsg = NULL;
5355696Snw141292 	int		rc;
5365696Snw141292 
5375696Snw141292 	rc = sqlite_exec(db, "BEGIN TRANSACTION;", NULL, NULL, &errmsg);
5385696Snw141292 	if (rc != SQLITE_OK) {
5395696Snw141292 		idmapdlog(LOG_ERR, "Begin transaction failed (%s) "
5405696Snw141292 		    "while %s (%s)", errmsg, while_doing, dbname);
5415696Snw141292 		sqlite_freemem(errmsg);
5425696Snw141292 		return (-1);
5435696Snw141292 	}
5445696Snw141292 
5455696Snw141292 	rc = sqlite_exec(db, sql, NULL, NULL, &errmsg);
5465696Snw141292 	if (rc != SQLITE_OK) {
5475696Snw141292 		idmapdlog(LOG_ERR, "Database error (%s) while %s (%s)", errmsg,
5485696Snw141292 		    while_doing, dbname);
5495696Snw141292 		sqlite_freemem(errmsg);
5505696Snw141292 		errmsg = NULL;
5515696Snw141292 		goto rollback;
5525696Snw141292 	}
5535696Snw141292 
5545696Snw141292 	rc = sqlite_exec(db, "COMMIT TRANSACTION", NULL, NULL, &errmsg);
5555696Snw141292 	if (rc == SQLITE_OK) {
5565696Snw141292 		sqlite_freemem(errmsg);
5575696Snw141292 		return (0);
5585696Snw141292 	}
5595696Snw141292 
5605696Snw141292 	idmapdlog(LOG_ERR, "Database commit error (%s) while s (%s)",
5615696Snw141292 	    errmsg, while_doing, dbname);
5625696Snw141292 	sqlite_freemem(errmsg);
5635696Snw141292 	errmsg = NULL;
5645696Snw141292 
5655696Snw141292 rollback:
5665696Snw141292 	rc = sqlite_exec(db, "ROLLBACK TRANSACTION", NULL, NULL, &errmsg);
5675696Snw141292 	if (rc != SQLITE_OK) {
5685696Snw141292 		idmapdlog(LOG_ERR, "Rollback failed (%s) while %s (%s)",
5695696Snw141292 		    errmsg, while_doing, dbname);
5705696Snw141292 		sqlite_freemem(errmsg);
5715696Snw141292 		return (-2);
5725696Snw141292 	}
5735696Snw141292 	sqlite_freemem(errmsg);
5745696Snw141292 
5755696Snw141292 	return (-1);
5765696Snw141292 }
5775696Snw141292 
5785696Snw141292 /*
5794520Snw141292  * Execute the given SQL statment without using any callbacks
5804520Snw141292  */
5814520Snw141292 idmap_retcode
5826017Snw141292 sql_exec_no_cb(sqlite *db, const char *dbname, char *sql)
5835696Snw141292 {
5844520Snw141292 	char		*errmsg = NULL;
5854884Sjp151216 	int		r;
5864520Snw141292 	idmap_retcode	retcode;
5874520Snw141292 
5884884Sjp151216 	r = sqlite_exec(db, sql, NULL, NULL, &errmsg);
5894884Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
5904520Snw141292 
5914520Snw141292 	if (r != SQLITE_OK) {
5926017Snw141292 		idmapdlog(LOG_ERR, "Database error on %s while executing %s "
5936017Snw141292 		    "(%s)", dbname, sql, CHECK_NULL(errmsg));
5944884Sjp151216 		retcode = idmapd_string2stat(errmsg);
5954864Sbaban 		if (errmsg != NULL)
5964520Snw141292 			sqlite_freemem(errmsg);
5974520Snw141292 		return (retcode);
5984520Snw141292 	}
5994520Snw141292 
6004520Snw141292 	return (IDMAP_SUCCESS);
6014520Snw141292 }
6024520Snw141292 
6034520Snw141292 /*
6044520Snw141292  * Generate expression that can be used in WHERE statements.
6054520Snw141292  * Examples:
6064520Snw141292  * <prefix> <col>      <op> <value>   <suffix>
6074520Snw141292  * ""       "unixuser" "="  "foo" "AND"
6084520Snw141292  */
6094520Snw141292 idmap_retcode
6105696Snw141292 gen_sql_expr_from_rule(idmap_namerule *rule, char **out)
6115696Snw141292 {
6125696Snw141292 	char	*s_windomain = NULL, *s_winname = NULL;
6135696Snw141292 	char	*s_unixname = NULL;
6145696Snw141292 	char	*lower_winname;
6155696Snw141292 	int	retcode = IDMAP_SUCCESS;
6165696Snw141292 
6174520Snw141292 	if (out == NULL)
6184520Snw141292 		return (IDMAP_ERR_ARG);
6194520Snw141292 
6205696Snw141292 
6215696Snw141292 	if (!EMPTY_STRING(rule->windomain)) {
6225696Snw141292 		s_windomain =  sqlite_mprintf("AND windomain = %Q ",
6235696Snw141292 		    rule->windomain);
6245696Snw141292 		if (s_windomain == NULL) {
6255696Snw141292 			retcode = IDMAP_ERR_MEMORY;
6265696Snw141292 			goto out;
6275696Snw141292 		}
6285696Snw141292 	}
6295696Snw141292 
6305696Snw141292 	if (!EMPTY_STRING(rule->winname)) {
6315696Snw141292 		if ((lower_winname = tolower_u8(rule->winname)) == NULL)
6325696Snw141292 			lower_winname = rule->winname;
6335696Snw141292 		s_winname = sqlite_mprintf(
6345696Snw141292 		    "AND winname = %Q AND is_wuser = %d ",
6355696Snw141292 		    lower_winname, rule->is_wuser ? 1 : 0);
6365696Snw141292 		if (lower_winname != rule->winname)
6375696Snw141292 			free(lower_winname);
6385696Snw141292 		if (s_winname == NULL) {
6395696Snw141292 			retcode = IDMAP_ERR_MEMORY;
6405696Snw141292 			goto out;
6415696Snw141292 		}
6425696Snw141292 	}
6435696Snw141292 
6445696Snw141292 	if (!EMPTY_STRING(rule->unixname)) {
6455696Snw141292 		s_unixname = sqlite_mprintf(
6465696Snw141292 		    "AND unixname = %Q AND is_user = %d ",
6475696Snw141292 		    rule->unixname, rule->is_user ? 1 : 0);
6485696Snw141292 		if (s_unixname == NULL) {
6495696Snw141292 			retcode = IDMAP_ERR_MEMORY;
6505696Snw141292 			goto out;
6515696Snw141292 		}
6525696Snw141292 	}
6535696Snw141292 
6545696Snw141292 	*out = sqlite_mprintf("%s %s %s",
6555696Snw141292 	    s_windomain ? s_windomain : "",
6565696Snw141292 	    s_winname ? s_winname : "",
6575696Snw141292 	    s_unixname ? s_unixname : "");
6585696Snw141292 
6595696Snw141292 	if (*out == NULL) {
6605696Snw141292 		retcode = IDMAP_ERR_MEMORY;
6615696Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
6625696Snw141292 		goto out;
6635696Snw141292 	}
6645696Snw141292 
6655696Snw141292 out:
6665696Snw141292 	if (s_windomain != NULL)
6675696Snw141292 		sqlite_freemem(s_windomain);
6685696Snw141292 	if (s_winname != NULL)
6695696Snw141292 		sqlite_freemem(s_winname);
6705696Snw141292 	if (s_unixname != NULL)
6715696Snw141292 		sqlite_freemem(s_unixname);
6725696Snw141292 
6735696Snw141292 	return (retcode);
6744520Snw141292 }
6754520Snw141292 
6765696Snw141292 
6775696Snw141292 
6784520Snw141292 /*
6794520Snw141292  * Generate and execute SQL statement for LIST RPC calls
6804520Snw141292  */
6814520Snw141292 idmap_retcode
6826017Snw141292 process_list_svc_sql(sqlite *db, const char *dbname, char *sql, uint64_t limit,
6836386Sjp151216 		int flag, list_svc_cb cb, void *result)
6845696Snw141292 {
6854520Snw141292 	list_cb_data_t	cb_data;
6864520Snw141292 	char		*errmsg = NULL;
6874884Sjp151216 	int		r;
6884520Snw141292 	idmap_retcode	retcode = IDMAP_ERR_INTERNAL;
6894520Snw141292 
6904520Snw141292 	(void) memset(&cb_data, 0, sizeof (cb_data));
6914520Snw141292 	cb_data.result = result;
6924520Snw141292 	cb_data.limit = limit;
6936386Sjp151216 	cb_data.flag = flag;
6944520Snw141292 
6954884Sjp151216 
6964884Sjp151216 	r = sqlite_exec(db, sql, cb, &cb_data, &errmsg);
6974884Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
6984884Sjp151216 	switch (r) {
6994884Sjp151216 	case SQLITE_OK:
7004884Sjp151216 		retcode = IDMAP_SUCCESS;
7014884Sjp151216 		break;
7024884Sjp151216 
7034884Sjp151216 	default:
7044884Sjp151216 		retcode = IDMAP_ERR_INTERNAL;
7056017Snw141292 		idmapdlog(LOG_ERR, "Database error on %s while executing "
7066017Snw141292 		    "%s (%s)", dbname, sql, CHECK_NULL(errmsg));
7074884Sjp151216 		break;
7084520Snw141292 	}
7094864Sbaban 	if (errmsg != NULL)
7104520Snw141292 		sqlite_freemem(errmsg);
7114520Snw141292 	return (retcode);
7124520Snw141292 }
7134520Snw141292 
7144520Snw141292 /*
7154520Snw141292  * This routine is called by callbacks that process the results of
7164520Snw141292  * LIST RPC calls to validate data and to allocate memory for
7174520Snw141292  * the result array.
7184520Snw141292  */
7194520Snw141292 idmap_retcode
7204520Snw141292 validate_list_cb_data(list_cb_data_t *cb_data, int argc, char **argv,
7215696Snw141292 		int ncol, uchar_t **list, size_t valsize)
7225696Snw141292 {
7234520Snw141292 	size_t	nsize;
7244520Snw141292 	void	*tmplist;
7254520Snw141292 
7264520Snw141292 	if (cb_data->limit > 0 && cb_data->next == cb_data->limit)
7274520Snw141292 		return (IDMAP_NEXT);
7284520Snw141292 
7294520Snw141292 	if (argc < ncol || argv == NULL) {
7304520Snw141292 		idmapdlog(LOG_ERR, "Invalid data");
7314520Snw141292 		return (IDMAP_ERR_INTERNAL);
7324520Snw141292 	}
7334520Snw141292 
7344520Snw141292 	/* alloc in bulk to reduce number of reallocs */
7354520Snw141292 	if (cb_data->next >= cb_data->len) {
7364520Snw141292 		nsize = (cb_data->len + SIZE_INCR) * valsize;
7374520Snw141292 		tmplist = realloc(*list, nsize);
7384520Snw141292 		if (tmplist == NULL) {
7394520Snw141292 			idmapdlog(LOG_ERR, "Out of memory");
7404520Snw141292 			return (IDMAP_ERR_MEMORY);
7414520Snw141292 		}
7424520Snw141292 		*list = tmplist;
7434520Snw141292 		(void) memset(*list + (cb_data->len * valsize), 0,
7445696Snw141292 		    SIZE_INCR * valsize);
7454520Snw141292 		cb_data->len += SIZE_INCR;
7464520Snw141292 	}
7474520Snw141292 	return (IDMAP_SUCCESS);
7484520Snw141292 }
7494520Snw141292 
7505696Snw141292 static
7515696Snw141292 idmap_retcode
7524520Snw141292 get_namerule_order(char *winname, char *windomain, char *unixname,
7535696Snw141292 	int direction, int is_diagonal, int *w2u_order, int *u2w_order)
7545696Snw141292 {
7554520Snw141292 	*w2u_order = 0;
7564520Snw141292 	*u2w_order = 0;
7574520Snw141292 
7584520Snw141292 	/*
7594520Snw141292 	 * Windows to UNIX lookup order:
7604520Snw141292 	 *  1. winname@domain (or winname) to ""
7614520Snw141292 	 *  2. winname@domain (or winname) to unixname
7624520Snw141292 	 *  3. winname@* to ""
7634520Snw141292 	 *  4. winname@* to unixname
7644520Snw141292 	 *  5. *@domain (or *) to *
7654520Snw141292 	 *  6. *@domain (or *) to ""
7664520Snw141292 	 *  7. *@domain (or *) to unixname
7674520Snw141292 	 *  8. *@* to *
7684520Snw141292 	 *  9. *@* to ""
7694520Snw141292 	 * 10. *@* to unixname
7704520Snw141292 	 *
7714520Snw141292 	 * winname is a special case of winname@domain when domain is the
7724520Snw141292 	 * default domain. Similarly * is a special case of *@domain when
7734520Snw141292 	 * domain is the default domain.
7744520Snw141292 	 *
7754520Snw141292 	 * Note that "" has priority over specific names because "" inhibits
7764520Snw141292 	 * mappings and traditionally deny rules always had higher priority.
7774520Snw141292 	 */
7784644Sbaban 	if (direction != IDMAP_DIRECTION_U2W) {
7794644Sbaban 		/* bi-directional or from windows to unix */
7804520Snw141292 		if (winname == NULL)
7814520Snw141292 			return (IDMAP_ERR_W2U_NAMERULE);
7824520Snw141292 		else if (unixname == NULL)
7834520Snw141292 			return (IDMAP_ERR_W2U_NAMERULE);
7844520Snw141292 		else if (EMPTY_NAME(winname))
7854520Snw141292 			return (IDMAP_ERR_W2U_NAMERULE);
7864520Snw141292 		else if (*winname == '*' && windomain && *windomain == '*') {
7874520Snw141292 			if (*unixname == '*')
7884520Snw141292 				*w2u_order = 8;
7894520Snw141292 			else if (EMPTY_NAME(unixname))
7904520Snw141292 				*w2u_order = 9;
7914520Snw141292 			else /* unixname == name */
7924520Snw141292 				*w2u_order = 10;
7934520Snw141292 		} else if (*winname == '*') {
7944520Snw141292 			if (*unixname == '*')
7954520Snw141292 				*w2u_order = 5;
7964520Snw141292 			else if (EMPTY_NAME(unixname))
7974520Snw141292 				*w2u_order = 6;
7984520Snw141292 			else /* name */
7994520Snw141292 				*w2u_order = 7;
8004864Sbaban 		} else if (windomain != NULL && *windomain == '*') {
8014520Snw141292 			/* winname == name */
8024520Snw141292 			if (*unixname == '*')
8034520Snw141292 				return (IDMAP_ERR_W2U_NAMERULE);
8044520Snw141292 			else if (EMPTY_NAME(unixname))
8054520Snw141292 				*w2u_order = 3;
8064520Snw141292 			else /* name */
8074520Snw141292 				*w2u_order = 4;
8084520Snw141292 		} else  {
8094520Snw141292 			/* winname == name && windomain == null or name */
8104520Snw141292 			if (*unixname == '*')
8114520Snw141292 				return (IDMAP_ERR_W2U_NAMERULE);
8124520Snw141292 			else if (EMPTY_NAME(unixname))
8134520Snw141292 				*w2u_order = 1;
8144520Snw141292 			else /* name */
8154520Snw141292 				*w2u_order = 2;
8164520Snw141292 		}
8175696Snw141292 
8184520Snw141292 	}
8194520Snw141292 
8204520Snw141292 	/*
8215696Snw141292 	 * 1. unixname to "", non-diagonal
8225696Snw141292 	 * 2. unixname to winname@domain (or winname), non-diagonal
8235696Snw141292 	 * 3. unixname to "", diagonal
8245696Snw141292 	 * 4. unixname to winname@domain (or winname), diagonal
8255696Snw141292 	 * 5. * to *@domain (or *), non-diagonal
8265696Snw141292 	 * 5. * to *@domain (or *), diagonal
8275696Snw141292 	 * 7. * to ""
8285696Snw141292 	 * 8. * to winname@domain (or winname)
8295696Snw141292 	 * 9. * to "", non-diagonal
8305696Snw141292 	 * 10. * to winname@domain (or winname), diagonal
8314520Snw141292 	 */
8324644Sbaban 	if (direction != IDMAP_DIRECTION_W2U) {
8335696Snw141292 		int diagonal = is_diagonal ? 1 : 0;
8345696Snw141292 
8354644Sbaban 		/* bi-directional or from unix to windows */
8364520Snw141292 		if (unixname == NULL || EMPTY_NAME(unixname))
8374520Snw141292 			return (IDMAP_ERR_U2W_NAMERULE);
8384520Snw141292 		else if (winname == NULL)
8394520Snw141292 			return (IDMAP_ERR_U2W_NAMERULE);
8404864Sbaban 		else if (windomain != NULL && *windomain == '*')
8414644Sbaban 			return (IDMAP_ERR_U2W_NAMERULE);
8424520Snw141292 		else if (*unixname == '*') {
8434520Snw141292 			if (*winname == '*')
8445696Snw141292 				*u2w_order = 5 + diagonal;
8454520Snw141292 			else if (EMPTY_NAME(winname))
8465696Snw141292 				*u2w_order = 7 + 2 * diagonal;
8474520Snw141292 			else
8485696Snw141292 				*u2w_order = 8 + 2 * diagonal;
8494520Snw141292 		} else {
8504520Snw141292 			if (*winname == '*')
8514520Snw141292 				return (IDMAP_ERR_U2W_NAMERULE);
8524520Snw141292 			else if (EMPTY_NAME(winname))
8535696Snw141292 				*u2w_order = 1 + 2 * diagonal;
8544520Snw141292 			else
8555696Snw141292 				*u2w_order = 2 + 2 * diagonal;
8564520Snw141292 		}
8574520Snw141292 	}
8584520Snw141292 	return (IDMAP_SUCCESS);
8594520Snw141292 }
8604520Snw141292 
8614520Snw141292 /*
8624520Snw141292  * Generate and execute SQL statement to add name-based mapping rule
8634520Snw141292  */
8644520Snw141292 idmap_retcode
8655696Snw141292 add_namerule(sqlite *db, idmap_namerule *rule)
8665696Snw141292 {
8674520Snw141292 	char		*sql = NULL;
8684520Snw141292 	idmap_stat	retcode;
8695064Sdm199847 	char		*dom = NULL;
8704520Snw141292 	int		w2u_order, u2w_order;
8714520Snw141292 	char		w2ubuf[11], u2wbuf[11];
8724520Snw141292 
8735064Sdm199847 	retcode = get_namerule_order(rule->winname, rule->windomain,
8745696Snw141292 	    rule->unixname, rule->direction,
8755696Snw141292 	    rule->is_user == rule->is_wuser ? 0 : 1, &w2u_order, &u2w_order);
8764520Snw141292 	if (retcode != IDMAP_SUCCESS)
8774520Snw141292 		goto out;
8784520Snw141292 
8794520Snw141292 	if (w2u_order)
8804520Snw141292 		(void) snprintf(w2ubuf, sizeof (w2ubuf), "%d", w2u_order);
8814520Snw141292 	if (u2w_order)
8824520Snw141292 		(void) snprintf(u2wbuf, sizeof (u2wbuf), "%d", u2w_order);
8834520Snw141292 
8844864Sbaban 	/*
8854864Sbaban 	 * For the triggers on namerules table to work correctly:
8864864Sbaban 	 * 1) Use NULL instead of 0 for w2u_order and u2w_order
8874864Sbaban 	 * 2) Use "" instead of NULL for "no domain"
8884864Sbaban 	 */
8894864Sbaban 
8905731Sbaban 	if (!EMPTY_STRING(rule->windomain))
8915064Sdm199847 		dom = rule->windomain;
8925696Snw141292 	else if (lookup_wksids_name2sid(rule->winname, NULL, NULL, NULL, NULL)
8934864Sbaban 	    == IDMAP_SUCCESS) {
8944864Sbaban 		/* well-known SIDs don't need domain */
8954864Sbaban 		dom = "";
8964864Sbaban 	}
8974520Snw141292 
8984520Snw141292 	RDLOCK_CONFIG();
8994864Sbaban 	if (dom == NULL) {
9005317Sjp151216 		if (_idmapdstate.cfg->pgcfg.default_domain)
9015317Sjp151216 			dom = _idmapdstate.cfg->pgcfg.default_domain;
9024864Sbaban 		else
9034864Sbaban 			dom = "";
9044864Sbaban 	}
9054884Sjp151216 	sql = sqlite_mprintf("INSERT into namerules "
9065696Snw141292 	    "(is_user, is_wuser, windomain, winname_display, is_nt4, "
9075696Snw141292 	    "unixname, w2u_order, u2w_order) "
9085696Snw141292 	    "VALUES(%d, %d, %Q, %Q, %d, %Q, %q, %q);",
9095696Snw141292 	    rule->is_user ? 1 : 0, rule->is_wuser ? 1 : 0, dom,
9105696Snw141292 	    rule->winname, rule->is_nt4 ? 1 : 0, rule->unixname,
9115696Snw141292 	    w2u_order ? w2ubuf : NULL, u2w_order ? u2wbuf : NULL);
9124520Snw141292 	UNLOCK_CONFIG();
9134520Snw141292 
9144520Snw141292 	if (sql == NULL) {
9154520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
9164520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
9174520Snw141292 		goto out;
9184520Snw141292 	}
9194520Snw141292 
9206017Snw141292 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, sql);
9214520Snw141292 
9224520Snw141292 	if (retcode == IDMAP_ERR_OTHER)
9234520Snw141292 		retcode = IDMAP_ERR_CFG;
9244520Snw141292 
9254520Snw141292 out:
9264864Sbaban 	if (sql != NULL)
9274520Snw141292 		sqlite_freemem(sql);
9284520Snw141292 	return (retcode);
9294520Snw141292 }
9304520Snw141292 
9314520Snw141292 /*
9324520Snw141292  * Flush name-based mapping rules
9334520Snw141292  */
9344520Snw141292 idmap_retcode
9355696Snw141292 flush_namerules(sqlite *db)
9365696Snw141292 {
9374520Snw141292 	idmap_stat	retcode;
9384520Snw141292 
9396017Snw141292 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, "DELETE FROM namerules;");
9405696Snw141292 
9414520Snw141292 	return (retcode);
9424520Snw141292 }
9434520Snw141292 
9444520Snw141292 /*
9454520Snw141292  * Generate and execute SQL statement to remove a name-based mapping rule
9464520Snw141292  */
9474520Snw141292 idmap_retcode
9485696Snw141292 rm_namerule(sqlite *db, idmap_namerule *rule)
9495696Snw141292 {
9504520Snw141292 	char		*sql = NULL;
9514520Snw141292 	idmap_stat	retcode;
9524520Snw141292 	char		buf[80];
9535696Snw141292 	char		*expr = NULL;
9544520Snw141292 
9555064Sdm199847 	if (rule->direction < 0 && EMPTY_STRING(rule->windomain) &&
9565064Sdm199847 	    EMPTY_STRING(rule->winname) && EMPTY_STRING(rule->unixname))
9574520Snw141292 		return (IDMAP_SUCCESS);
9584520Snw141292 
9595696Snw141292 	buf[0] = 0;
9605696Snw141292 
9615696Snw141292 	if (rule->direction == IDMAP_DIRECTION_BI)
9624520Snw141292 		(void) snprintf(buf, sizeof (buf), "AND w2u_order > 0"
9635696Snw141292 		    " AND u2w_order > 0");
9645696Snw141292 	else if (rule->direction == IDMAP_DIRECTION_W2U)
9654520Snw141292 		(void) snprintf(buf, sizeof (buf), "AND w2u_order > 0"
9665696Snw141292 		    " AND (u2w_order = 0 OR u2w_order ISNULL)");
9675696Snw141292 	else if (rule->direction == IDMAP_DIRECTION_U2W)
9684520Snw141292 		(void) snprintf(buf, sizeof (buf), "AND u2w_order > 0"
9695696Snw141292 		    " AND (w2u_order = 0 OR w2u_order ISNULL)");
9705696Snw141292 
9715696Snw141292 	retcode = gen_sql_expr_from_rule(rule, &expr);
9725696Snw141292 	if (retcode != IDMAP_SUCCESS)
9735696Snw141292 		goto out;
9745696Snw141292 
9755696Snw141292 	sql = sqlite_mprintf("DELETE FROM namerules WHERE 1 %s %s;", expr,
9765696Snw141292 	    buf);
9774520Snw141292 
9784520Snw141292 	if (sql == NULL) {
9794520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
9804520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
9814520Snw141292 		goto out;
9824520Snw141292 	}
9834520Snw141292 
9845696Snw141292 
9856017Snw141292 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, sql);
9864520Snw141292 
9874520Snw141292 out:
9885696Snw141292 	if (expr != NULL)
9895696Snw141292 		sqlite_freemem(expr);
9904864Sbaban 	if (sql != NULL)
9914520Snw141292 		sqlite_freemem(sql);
9924520Snw141292 	return (retcode);
9934520Snw141292 }
9944520Snw141292 
9954520Snw141292 /*
9964520Snw141292  * Compile the given SQL query and step just once.
9974520Snw141292  *
9984520Snw141292  * Input:
9994520Snw141292  * db  - db handle
10004520Snw141292  * sql - SQL statement
10014520Snw141292  *
10024520Snw141292  * Output:
10034520Snw141292  * vm     -  virtual SQL machine
10044520Snw141292  * ncol   - number of columns in the result
10054520Snw141292  * values - column values
10064520Snw141292  *
10074520Snw141292  * Return values:
10084520Snw141292  * IDMAP_SUCCESS
10094520Snw141292  * IDMAP_ERR_NOTFOUND
10104520Snw141292  * IDMAP_ERR_INTERNAL
10114520Snw141292  */
10124520Snw141292 
10135696Snw141292 static
10145696Snw141292 idmap_retcode
10154520Snw141292 sql_compile_n_step_once(sqlite *db, char *sql, sqlite_vm **vm, int *ncol,
10165696Snw141292 		int reqcol, const char ***values)
10175696Snw141292 {
10184520Snw141292 	char		*errmsg = NULL;
10194884Sjp151216 	int		r;
10204884Sjp151216 
10214884Sjp151216 	if ((r = sqlite_compile(db, sql, NULL, vm, &errmsg)) != SQLITE_OK) {
10225696Snw141292 		idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
10235696Snw141292 		    CHECK_NULL(errmsg));
10244520Snw141292 		sqlite_freemem(errmsg);
10254520Snw141292 		return (IDMAP_ERR_INTERNAL);
10264520Snw141292 	}
10274520Snw141292 
10284884Sjp151216 	r = sqlite_step(*vm, ncol, values, NULL);
10294884Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
10304884Sjp151216 
10314884Sjp151216 	if (r == SQLITE_ROW) {
10324864Sbaban 		if (ncol != NULL && *ncol < reqcol) {
10334520Snw141292 			(void) sqlite_finalize(*vm, NULL);
10344520Snw141292 			*vm = NULL;
10354520Snw141292 			return (IDMAP_ERR_INTERNAL);
10364520Snw141292 		}
10374520Snw141292 		/* Caller will call finalize after using the results */
10384520Snw141292 		return (IDMAP_SUCCESS);
10394520Snw141292 	} else if (r == SQLITE_DONE) {
10404520Snw141292 		(void) sqlite_finalize(*vm, NULL);
10414520Snw141292 		*vm = NULL;
10424520Snw141292 		return (IDMAP_ERR_NOTFOUND);
10434520Snw141292 	}
10444520Snw141292 
10454520Snw141292 	(void) sqlite_finalize(*vm, &errmsg);
10464520Snw141292 	*vm = NULL;
10475696Snw141292 	idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
10485696Snw141292 	    CHECK_NULL(errmsg));
10494520Snw141292 	sqlite_freemem(errmsg);
10504520Snw141292 	return (IDMAP_ERR_INTERNAL);
10514520Snw141292 }
10524520Snw141292 
10534864Sbaban /*
10546616Sdm199847  * Load config in the state.
10555731Sbaban  *
10566616Sdm199847  * nm_siduid and nm_sidgid fields:
10575731Sbaban  * state->nm_siduid represents mode used by sid2uid and uid2sid
10585731Sbaban  * requests for directory-based name mappings. Similarly,
10595731Sbaban  * state->nm_sidgid represents mode used by sid2gid and gid2sid
10605731Sbaban  * requests.
10615731Sbaban  *
10625731Sbaban  * sid2uid/uid2sid:
10635731Sbaban  * none       -> ds_name_mapping_enabled != true
10645731Sbaban  * AD-mode    -> !nldap_winname_attr && ad_unixuser_attr
10655731Sbaban  * nldap-mode -> nldap_winname_attr && !ad_unixuser_attr
10665731Sbaban  * mixed-mode -> nldap_winname_attr && ad_unixuser_attr
10675731Sbaban  *
10685731Sbaban  * sid2gid/gid2sid:
10695731Sbaban  * none       -> ds_name_mapping_enabled != true
10705731Sbaban  * AD-mode    -> !nldap_winname_attr && ad_unixgroup_attr
10715731Sbaban  * nldap-mode -> nldap_winname_attr && !ad_unixgroup_attr
10725731Sbaban  * mixed-mode -> nldap_winname_attr && ad_unixgroup_attr
10735731Sbaban  */
10745731Sbaban idmap_retcode
10756616Sdm199847 load_cfg_in_state(lookup_state_t *state)
10765731Sbaban {
10775731Sbaban 	state->nm_siduid = IDMAP_NM_NONE;
10785731Sbaban 	state->nm_sidgid = IDMAP_NM_NONE;
10795731Sbaban 	RDLOCK_CONFIG();
10806616Sdm199847 
10817031Snw141292 	state->eph_map_unres_sids = 0;
10827031Snw141292 	if (_idmapdstate.cfg->pgcfg.eph_map_unres_sids)
10837031Snw141292 		state->eph_map_unres_sids = 1;
10847031Snw141292 
10856616Sdm199847 	if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
10866616Sdm199847 		state->defdom =
10876616Sdm199847 		    strdup(_idmapdstate.cfg->pgcfg.default_domain);
10886616Sdm199847 		if (state->defdom == NULL) {
10896616Sdm199847 			UNLOCK_CONFIG();
10906616Sdm199847 			return (IDMAP_ERR_MEMORY);
10916616Sdm199847 		}
10926616Sdm199847 	} else {
10936616Sdm199847 		UNLOCK_CONFIG();
10946813Sdm199847 		return (IDMAP_SUCCESS);
10956616Sdm199847 	}
1096*8671SJulian.Pullen@Sun.COM 	if (!_idmapdstate.cfg->pgcfg.ds_name_mapping_enabled) {
10975731Sbaban 		UNLOCK_CONFIG();
10985731Sbaban 		return (IDMAP_SUCCESS);
10995731Sbaban 	}
11005731Sbaban 	if (_idmapdstate.cfg->pgcfg.nldap_winname_attr != NULL) {
11015731Sbaban 		state->nm_siduid =
11025731Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
11035731Sbaban 		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
11045731Sbaban 		state->nm_sidgid =
11055731Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
11065731Sbaban 		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
11075731Sbaban 	} else {
11085731Sbaban 		state->nm_siduid =
11095731Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
11105731Sbaban 		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
11115731Sbaban 		state->nm_sidgid =
11125731Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
11135731Sbaban 		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
11145731Sbaban 	}
11155731Sbaban 	if (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL) {
11165731Sbaban 		state->ad_unixuser_attr =
11175731Sbaban 		    strdup(_idmapdstate.cfg->pgcfg.ad_unixuser_attr);
11185731Sbaban 		if (state->ad_unixuser_attr == NULL) {
11195731Sbaban 			UNLOCK_CONFIG();
11205731Sbaban 			return (IDMAP_ERR_MEMORY);
11215731Sbaban 		}
11225731Sbaban 	}
11235731Sbaban 	if (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL) {
11245731Sbaban 		state->ad_unixgroup_attr =
11255731Sbaban 		    strdup(_idmapdstate.cfg->pgcfg.ad_unixgroup_attr);
11265731Sbaban 		if (state->ad_unixgroup_attr == NULL) {
11275731Sbaban 			UNLOCK_CONFIG();
11285731Sbaban 			return (IDMAP_ERR_MEMORY);
11295731Sbaban 		}
11305731Sbaban 	}
11316616Sdm199847 	if (_idmapdstate.cfg->pgcfg.nldap_winname_attr != NULL) {
11326616Sdm199847 		state->nldap_winname_attr =
11336616Sdm199847 		    strdup(_idmapdstate.cfg->pgcfg.nldap_winname_attr);
11346616Sdm199847 		if (state->nldap_winname_attr == NULL) {
11356616Sdm199847 			UNLOCK_CONFIG();
11366616Sdm199847 			return (IDMAP_ERR_MEMORY);
11376616Sdm199847 		}
11386616Sdm199847 	}
11395731Sbaban 	UNLOCK_CONFIG();
11405731Sbaban 	return (IDMAP_SUCCESS);
11415731Sbaban }
11425731Sbaban 
11435731Sbaban /*
11446386Sjp151216  * Set the rule with sepecified values.
11456386Sjp151216  * All the strings are copied.
11466386Sjp151216  */
11476386Sjp151216 static void
11486386Sjp151216 idmap_namerule_set(idmap_namerule *rule, const char *windomain,
11496386Sjp151216 		const char *winname, const char *unixname, boolean_t is_user,
11506386Sjp151216 		boolean_t is_wuser, boolean_t is_nt4, int direction)
11516386Sjp151216 {
11526386Sjp151216 	/*
11536386Sjp151216 	 * Only update if they differ because we have to free
11546386Sjp151216 	 * and duplicate the strings
11556386Sjp151216 	 */
11566386Sjp151216 	if (rule->windomain == NULL || windomain == NULL ||
11576386Sjp151216 	    strcmp(rule->windomain, windomain) != 0) {
11586386Sjp151216 		if (rule->windomain != NULL) {
11596386Sjp151216 			free(rule->windomain);
11606386Sjp151216 			rule->windomain = NULL;
11616386Sjp151216 		}
11626386Sjp151216 		if (windomain != NULL)
11636386Sjp151216 			rule->windomain = strdup(windomain);
11646386Sjp151216 	}
11656386Sjp151216 
11666386Sjp151216 	if (rule->winname == NULL || winname == NULL ||
11676386Sjp151216 	    strcmp(rule->winname, winname) != 0) {
11686386Sjp151216 		if (rule->winname != NULL) {
11696386Sjp151216 			free(rule->winname);
11706386Sjp151216 			rule->winname = NULL;
11716386Sjp151216 		}
11726386Sjp151216 		if (winname != NULL)
11736386Sjp151216 			rule->winname = strdup(winname);
11746386Sjp151216 	}
11756386Sjp151216 
11766386Sjp151216 	if (rule->unixname == NULL || unixname == NULL ||
11776386Sjp151216 	    strcmp(rule->unixname, unixname) != 0) {
11786386Sjp151216 		if (rule->unixname != NULL) {
11796386Sjp151216 			free(rule->unixname);
11806386Sjp151216 			rule->unixname = NULL;
11816386Sjp151216 		}
11826386Sjp151216 		if (unixname != NULL)
11836386Sjp151216 			rule->unixname = strdup(unixname);
11846386Sjp151216 	}
11856386Sjp151216 
11866386Sjp151216 	rule->is_user = is_user;
11876386Sjp151216 	rule->is_wuser = is_wuser;
11886386Sjp151216 	rule->is_nt4 = is_nt4;
11896386Sjp151216 	rule->direction = direction;
11906386Sjp151216 }
11916386Sjp151216 
11926386Sjp151216 
11936386Sjp151216 /*
11944864Sbaban  * Table for well-known SIDs.
11954864Sbaban  *
11964864Sbaban  * Background:
11974864Sbaban  *
11985191Sbaban  * Some of the well-known principals are stored under:
11994864Sbaban  * cn=WellKnown Security Principals, cn=Configuration, dc=<forestRootDomain>
12004864Sbaban  * They belong to objectClass "foreignSecurityPrincipal". They don't have
12014864Sbaban  * "samAccountName" nor "userPrincipalName" attributes. Their names are
12024864Sbaban  * available in "cn" and "name" attributes. Some of these principals have a
12034864Sbaban  * second entry under CN=ForeignSecurityPrincipals,dc=<forestRootDomain> and
12044864Sbaban  * these duplicate entries have the stringified SID in the "name" and "cn"
12054864Sbaban  * attributes instead of the actual name.
12064864Sbaban  *
12075191Sbaban  * Those of the form S-1-5-32-X are Builtin groups and are stored in the
12085191Sbaban  * cn=builtin container (except, Power Users which is not stored in AD)
12094864Sbaban  *
12105191Sbaban  * These principals are and will remain constant. Therefore doing AD lookups
12115191Sbaban  * provides no benefit. Also, using hard-coded table (and thus avoiding AD
12125191Sbaban  * lookup) improves performance and avoids additional complexity in the
12135191Sbaban  * adutils.c code. Moreover these SIDs can be used when no Active Directory
12145191Sbaban  * is available (such as the CIFS server's "workgroup" mode).
12155191Sbaban  *
12165191Sbaban  * Notes:
12175191Sbaban  * 1. Currently we don't support localization of well-known SID names,
12184864Sbaban  * unlike Windows.
12194864Sbaban  *
12205191Sbaban  * 2. Other well-known SIDs i.e. S-1-5-<domain>-<w-k RID> are not stored
12215191Sbaban  * here. AD does have normal user/group objects for these objects and
12225191Sbaban  * can be looked up using the existing AD lookup code.
12235731Sbaban  *
12245731Sbaban  * 3. See comments above lookup_wksids_sid2pid() for more information
12255731Sbaban  * on how we lookup the wksids table.
12264864Sbaban  */
12274864Sbaban static wksids_table_t wksids[] = {
12285731Sbaban 	{"S-1-0", 0, "Nobody", 0, SENTINEL_PID, -1, 1},
12295731Sbaban 	{"S-1-1", 0, "Everyone", 0, SENTINEL_PID, -1, -1},
12305731Sbaban 	{"S-1-3", 0, "Creator Owner", 1, IDMAP_WK_CREATOR_OWNER_UID, 1, 0},
12315731Sbaban 	{"S-1-3", 1, "Creator Group", 0, IDMAP_WK_CREATOR_GROUP_GID, 0, 0},
12325731Sbaban 	{"S-1-3", 2, "Creator Owner Server", 1, SENTINEL_PID, -1, -1},
12335731Sbaban 	{"S-1-3", 3, "Creator Group Server", 0, SENTINEL_PID, -1, 1},
12345731Sbaban 	{"S-1-3", 4, "Owner Rights", 0, SENTINEL_PID, -1, -1},
12355731Sbaban 	{"S-1-5", 1, "Dialup", 0, SENTINEL_PID, -1, -1},
12365731Sbaban 	{"S-1-5", 2, "Network", 0, SENTINEL_PID, -1, -1},
12375731Sbaban 	{"S-1-5", 3, "Batch", 0, SENTINEL_PID, -1, -1},
12385731Sbaban 	{"S-1-5", 4, "Interactive", 0, SENTINEL_PID, -1, -1},
12395731Sbaban 	{"S-1-5", 6, "Service", 0, SENTINEL_PID, -1, -1},
12405731Sbaban 	{"S-1-5", 7, "Anonymous Logon", 0, GID_NOBODY, 0, 0},
12415731Sbaban 	{"S-1-5", 7, "Anonymous Logon", 0, UID_NOBODY, 1, 0},
12425731Sbaban 	{"S-1-5", 8, "Proxy", 0, SENTINEL_PID, -1, -1},
12435731Sbaban 	{"S-1-5", 9, "Enterprise Domain Controllers", 0, SENTINEL_PID, -1, -1},
12445731Sbaban 	{"S-1-5", 10, "Self", 0, SENTINEL_PID, -1, -1},
12455731Sbaban 	{"S-1-5", 11, "Authenticated Users", 0, SENTINEL_PID, -1, -1},
12465731Sbaban 	{"S-1-5", 12, "Restricted Code", 0, SENTINEL_PID, -1, -1},
12475731Sbaban 	{"S-1-5", 13, "Terminal Server User", 0, SENTINEL_PID, -1, -1},
12485731Sbaban 	{"S-1-5", 14, "Remote Interactive Logon", 0, SENTINEL_PID, -1, -1},
12495731Sbaban 	{"S-1-5", 15, "This Organization", 0, SENTINEL_PID, -1, -1},
12505731Sbaban 	{"S-1-5", 17, "IUSR", 0, SENTINEL_PID, -1, -1},
12515731Sbaban 	{"S-1-5", 18, "Local System", 0, IDMAP_WK_LOCAL_SYSTEM_GID, 0, 0},
12525731Sbaban 	{"S-1-5", 19, "Local Service", 0, SENTINEL_PID, -1, -1},
12535731Sbaban 	{"S-1-5", 20, "Network Service", 0, SENTINEL_PID, -1, -1},
12545731Sbaban 	{"S-1-5", 1000, "Other Organization", 0, SENTINEL_PID, -1, -1},
12555731Sbaban 	{"S-1-5-32", 544, "Administrators", 0, SENTINEL_PID, -1, -1},
12565731Sbaban 	{"S-1-5-32", 545, "Users", 0, SENTINEL_PID, -1, -1},
12575731Sbaban 	{"S-1-5-32", 546, "Guests", 0, SENTINEL_PID, -1, -1},
12585731Sbaban 	{"S-1-5-32", 547, "Power Users", 0, SENTINEL_PID, -1, -1},
12595731Sbaban 	{"S-1-5-32", 548, "Account Operators", 0, SENTINEL_PID, -1, -1},
12605731Sbaban 	{"S-1-5-32", 549, "Server Operators", 0, SENTINEL_PID, -1, -1},
12615731Sbaban 	{"S-1-5-32", 550, "Print Operators", 0, SENTINEL_PID, -1, -1},
12625731Sbaban 	{"S-1-5-32", 551, "Backup Operators", 0, SENTINEL_PID, -1, -1},
12635731Sbaban 	{"S-1-5-32", 552, "Replicator", 0, SENTINEL_PID, -1, -1},
12645191Sbaban 	{"S-1-5-32", 554, "Pre-Windows 2000 Compatible Access", 0,
12655731Sbaban 	    SENTINEL_PID, -1, -1},
12665731Sbaban 	{"S-1-5-32", 555, "Remote Desktop Users", 0, SENTINEL_PID, -1, -1},
12675191Sbaban 	{"S-1-5-32", 556, "Network Configuration Operators", 0,
12685731Sbaban 	    SENTINEL_PID, -1, -1},
12695191Sbaban 	{"S-1-5-32", 557, "Incoming Forest Trust Builders", 0,
12705731Sbaban 	    SENTINEL_PID, -1, -1},
12715731Sbaban 	{"S-1-5-32", 558, "Performance Monitor Users", 0, SENTINEL_PID, -1, -1},
12725731Sbaban 	{"S-1-5-32", 559, "Performance Log Users", 0, SENTINEL_PID, -1, -1},
12735191Sbaban 	{"S-1-5-32", 560, "Windows Authorization Access Group", 0,
12745731Sbaban 	    SENTINEL_PID, -1, -1},
12755191Sbaban 	{"S-1-5-32", 561, "Terminal Server License Servers", 0,
12765731Sbaban 	    SENTINEL_PID, -1, -1},
12775731Sbaban 	{"S-1-5-32", 561, "Distributed COM Users", 0, SENTINEL_PID, -1, -1},
12785731Sbaban 	{"S-1-5-32", 568, "IIS_IUSRS", 0, SENTINEL_PID, -1, -1},
12795731Sbaban 	{"S-1-5-32", 569, "Cryptographic Operators", 0, SENTINEL_PID, -1, -1},
12805731Sbaban 	{"S-1-5-32", 573, "Event Log Readers", 0, SENTINEL_PID, -1, -1},
12815191Sbaban 	{"S-1-5-32", 574, "Certificate Service DCOM Access", 0,
12825731Sbaban 	    SENTINEL_PID, -1, -1},
12835731Sbaban 	{"S-1-5-64", 21, "Digest Authentication", 0, SENTINEL_PID, -1, -1},
12845731Sbaban 	{"S-1-5-64", 10, "NTLM Authentication", 0, SENTINEL_PID, -1, -1},
12855731Sbaban 	{"S-1-5-64", 14, "SChannel Authentication", 0, SENTINEL_PID, -1, -1},
12865731Sbaban 	{NULL, UINT32_MAX, NULL, -1, SENTINEL_PID, -1, -1}
12874520Snw141292 };
12884520Snw141292 
12895731Sbaban /*
12905731Sbaban  * Lookup well-known SIDs table either by winname or by SID.
12915731Sbaban  * If the given winname or SID is a well-known SID then we set wksid
12925731Sbaban  * variable and then proceed to see if the SID has a hard mapping to
12935731Sbaban  * a particular UID/GID (Ex: Creator Owner/Creator Group mapped to
12945731Sbaban  * fixed ephemeral ids). If we find such mapping then we return
12955731Sbaban  * success otherwise notfound. If a well-known SID is mapped to
12965731Sbaban  * SENTINEL_PID and the direction field is set (bi-directional or
12975731Sbaban  * win2unix) then we treat it as inhibited mapping and return no
12985731Sbaban  * mapping (Ex. S-1-0-0).
12995731Sbaban  */
13005696Snw141292 static
13015696Snw141292 idmap_retcode
13025731Sbaban lookup_wksids_sid2pid(idmap_mapping *req, idmap_id_res *res, int *wksid)
13035696Snw141292 {
13044520Snw141292 	int i;
13055731Sbaban 
13065731Sbaban 	*wksid = 0;
13075731Sbaban 
13084864Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
13095731Sbaban 		if (req->id1.idmap_id_u.sid.prefix != NULL) {
13105731Sbaban 			if ((strcasecmp(wksids[i].sidprefix,
13115731Sbaban 			    req->id1.idmap_id_u.sid.prefix) != 0) ||
13125731Sbaban 			    wksids[i].rid != req->id1.idmap_id_u.sid.rid)
13135731Sbaban 				/* this is not our SID */
13145731Sbaban 				continue;
13155731Sbaban 			if (req->id1name == NULL) {
13165731Sbaban 				req->id1name = strdup(wksids[i].winname);
13175731Sbaban 				if (req->id1name == NULL)
13185731Sbaban 					return (IDMAP_ERR_MEMORY);
13195731Sbaban 			}
13205731Sbaban 		} else if (req->id1name != NULL) {
13215731Sbaban 			if (strcasecmp(wksids[i].winname, req->id1name) != 0)
13225731Sbaban 				/* this is not our winname */
13234864Sbaban 				continue;
13245731Sbaban 			req->id1.idmap_id_u.sid.prefix =
13255731Sbaban 			    strdup(wksids[i].sidprefix);
13265731Sbaban 			if (req->id1.idmap_id_u.sid.prefix == NULL)
13275731Sbaban 				return (IDMAP_ERR_MEMORY);
13285731Sbaban 			req->id1.idmap_id_u.sid.rid = wksids[i].rid;
13295731Sbaban 		}
13305731Sbaban 
13315731Sbaban 		*wksid = 1;
13325731Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
13335731Sbaban 
13345731Sbaban 		req->id1.idtype = (wksids[i].is_wuser) ?
13355731Sbaban 		    IDMAP_USID : IDMAP_GSID;
13365731Sbaban 
13375731Sbaban 		if (wksids[i].pid == SENTINEL_PID) {
13385731Sbaban 			if (wksids[i].direction == IDMAP_DIRECTION_BI ||
13395731Sbaban 			    wksids[i].direction == IDMAP_DIRECTION_W2U)
13405731Sbaban 				/* Inhibited */
13415731Sbaban 				return (IDMAP_ERR_NOMAPPING);
13425731Sbaban 			/* Not mapped */
13436616Sdm199847 			if (res->id.idtype == IDMAP_POSIXID) {
13446616Sdm199847 				res->id.idtype =
13456616Sdm199847 				    (wksids[i].is_wuser) ?
13466616Sdm199847 				    IDMAP_UID : IDMAP_GID;
13476616Sdm199847 			}
13485731Sbaban 			return (IDMAP_ERR_NOTFOUND);
13495731Sbaban 		} else if (wksids[i].direction == IDMAP_DIRECTION_U2W)
13505731Sbaban 			continue;
13515731Sbaban 
13525731Sbaban 		switch (res->id.idtype) {
13535731Sbaban 		case IDMAP_UID:
13545731Sbaban 			if (wksids[i].is_user == 0)
13555731Sbaban 				continue;
13565731Sbaban 			res->id.idmap_id_u.uid = wksids[i].pid;
13575731Sbaban 			res->direction = wksids[i].direction;
13586386Sjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
13596386Sjp151216 				res->info.how.map_type =
13606386Sjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
13616386Sjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
13626386Sjp151216 			}
13635731Sbaban 			return (IDMAP_SUCCESS);
13645731Sbaban 		case IDMAP_GID:
13655731Sbaban 			if (wksids[i].is_user == 1)
13665731Sbaban 				continue;
13675731Sbaban 			res->id.idmap_id_u.gid = wksids[i].pid;
13685731Sbaban 			res->direction = wksids[i].direction;
13696386Sjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
13706386Sjp151216 				res->info.how.map_type =
13716386Sjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
13726386Sjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
13736386Sjp151216 			}
13745731Sbaban 			return (IDMAP_SUCCESS);
13755731Sbaban 		case IDMAP_POSIXID:
13765731Sbaban 			res->id.idmap_id_u.uid = wksids[i].pid;
13775731Sbaban 			res->id.idtype = (!wksids[i].is_user) ?
13785731Sbaban 			    IDMAP_GID : IDMAP_UID;
13795731Sbaban 			res->direction = wksids[i].direction;
13806386Sjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
13816386Sjp151216 				res->info.how.map_type =
13826386Sjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
13836386Sjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
13846386Sjp151216 			}
13855731Sbaban 			return (IDMAP_SUCCESS);
13865731Sbaban 		default:
13875731Sbaban 			return (IDMAP_ERR_NOTSUPPORTED);
13884520Snw141292 		}
13894520Snw141292 	}
13904520Snw141292 	return (IDMAP_ERR_NOTFOUND);
13914520Snw141292 }
13924520Snw141292 
13935696Snw141292 
13945696Snw141292 static
13955696Snw141292 idmap_retcode
13965696Snw141292 lookup_wksids_pid2sid(idmap_mapping *req, idmap_id_res *res, int is_user)
13975696Snw141292 {
13984520Snw141292 	int i;
13995731Sbaban 	if (req->id1.idmap_id_u.uid == SENTINEL_PID)
14005731Sbaban 		return (IDMAP_ERR_NOTFOUND);
14014864Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
14024864Sbaban 		if (wksids[i].pid == req->id1.idmap_id_u.uid &&
14034864Sbaban 		    wksids[i].is_user == is_user &&
14044864Sbaban 		    wksids[i].direction != IDMAP_DIRECTION_W2U) {
14055731Sbaban 			if (res->id.idtype == IDMAP_SID) {
14065731Sbaban 				res->id.idtype = (wksids[i].is_wuser) ?
14075731Sbaban 				    IDMAP_USID : IDMAP_GSID;
14085731Sbaban 			}
14094864Sbaban 			res->id.idmap_id_u.sid.rid = wksids[i].rid;
14104864Sbaban 			res->id.idmap_id_u.sid.prefix =
14115696Snw141292 			    strdup(wksids[i].sidprefix);
14124864Sbaban 			if (res->id.idmap_id_u.sid.prefix == NULL) {
14134864Sbaban 				idmapdlog(LOG_ERR, "Out of memory");
14144864Sbaban 				return (IDMAP_ERR_MEMORY);
14154520Snw141292 			}
14164864Sbaban 			res->direction = wksids[i].direction;
14176386Sjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
14186386Sjp151216 				res->info.how.map_type =
14196386Sjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
14206386Sjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
14216386Sjp151216 			}
14224864Sbaban 			return (IDMAP_SUCCESS);
14234864Sbaban 		}
14244864Sbaban 	}
14254864Sbaban 	return (IDMAP_ERR_NOTFOUND);
14264864Sbaban }
14274864Sbaban 
14285696Snw141292 idmap_retcode
14295696Snw141292 lookup_wksids_name2sid(const char *name, char **canonname, char **sidprefix,
14305696Snw141292 	idmap_rid_t *rid, int *type)
14315696Snw141292 {
14326616Sdm199847 	int	i;
14336616Sdm199847 
14346616Sdm199847 	if ((strncasecmp(name, "BUILTIN\\", 8) == 0) ||
14356616Sdm199847 	    (strncasecmp(name, "BUILTIN/", 8) == 0))
14366616Sdm199847 		name += 8;
14376616Sdm199847 
14384864Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
14395731Sbaban 		if (strcasecmp(wksids[i].winname, name) != 0)
14405731Sbaban 			continue;
14415731Sbaban 		if (sidprefix != NULL &&
14425731Sbaban 		    (*sidprefix = strdup(wksids[i].sidprefix)) == NULL) {
14435731Sbaban 			idmapdlog(LOG_ERR, "Out of memory");
14445731Sbaban 			return (IDMAP_ERR_MEMORY);
14455731Sbaban 		}
14465731Sbaban 		if (canonname != NULL &&
14475731Sbaban 		    (*canonname = strdup(wksids[i].winname)) == NULL) {
14485731Sbaban 			idmapdlog(LOG_ERR, "Out of memory");
14495731Sbaban 			if (sidprefix != NULL) {
14505731Sbaban 				free(*sidprefix);
14515731Sbaban 				*sidprefix = NULL;
14524864Sbaban 			}
14535731Sbaban 			return (IDMAP_ERR_MEMORY);
14544520Snw141292 		}
14555731Sbaban 		if (type != NULL)
14565731Sbaban 			*type = (wksids[i].is_wuser) ?
14575731Sbaban 			    _IDMAP_T_USER : _IDMAP_T_GROUP;
14585731Sbaban 		if (rid != NULL)
14595731Sbaban 			*rid = wksids[i].rid;
14605731Sbaban 		return (IDMAP_SUCCESS);
14614520Snw141292 	}
14624520Snw141292 	return (IDMAP_ERR_NOTFOUND);
14634520Snw141292 }
14644520Snw141292 
14655696Snw141292 static
14665696Snw141292 idmap_retcode
14675696Snw141292 lookup_cache_sid2pid(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
14685696Snw141292 {
14694520Snw141292 	char		*end;
14704520Snw141292 	char		*sql = NULL;
14714520Snw141292 	const char	**values;
14724520Snw141292 	sqlite_vm	*vm = NULL;
14734520Snw141292 	int		ncol, is_user;
14744520Snw141292 	uid_t		pid;
14754520Snw141292 	time_t		curtime, exp;
14764520Snw141292 	idmap_retcode	retcode;
14775932Sbaban 	char		*is_user_string, *lower_name;
14784520Snw141292 
14794520Snw141292 	/* Current time */
14804520Snw141292 	errno = 0;
14814520Snw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
14825696Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
14835696Snw141292 		    strerror(errno));
14844520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
14854520Snw141292 		goto out;
14864520Snw141292 	}
14874520Snw141292 
14885731Sbaban 	switch (res->id.idtype) {
14895696Snw141292 	case IDMAP_UID:
14905696Snw141292 		is_user_string = "1";
14915696Snw141292 		break;
14925696Snw141292 	case IDMAP_GID:
14935696Snw141292 		is_user_string = "0";
14945696Snw141292 		break;
14955696Snw141292 	case IDMAP_POSIXID:
14965696Snw141292 		/* the non-diagonal mapping */
14975696Snw141292 		is_user_string = "is_wuser";
14985696Snw141292 		break;
14995696Snw141292 	default:
15005696Snw141292 		retcode = IDMAP_ERR_NOTSUPPORTED;
15015696Snw141292 		goto out;
15025696Snw141292 	}
15035696Snw141292 
15044520Snw141292 	/* SQL to lookup the cache */
15056386Sjp151216 
15065731Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
15075731Sbaban 		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
15086386Sjp151216 		    "unixname, u2w, is_wuser, "
15096386Sjp151216 		    "map_type, map_dn, map_attr, map_value, "
15106386Sjp151216 		    "map_windomain, map_winname, map_unixname, map_is_nt4 "
15115731Sbaban 		    "FROM idmap_cache WHERE is_user = %s AND "
15125731Sbaban 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
15135731Sbaban 		    "(pid >= 2147483648 OR "
15145731Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
15155731Sbaban 		    "expiration > %d));",
15165731Sbaban 		    is_user_string, req->id1.idmap_id_u.sid.prefix,
15175731Sbaban 		    req->id1.idmap_id_u.sid.rid, curtime);
15185731Sbaban 	} else if (req->id1name != NULL) {
15195932Sbaban 		if ((lower_name = tolower_u8(req->id1name)) == NULL)
15205932Sbaban 			lower_name = req->id1name;
15215731Sbaban 		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
15226386Sjp151216 		    "unixname, u2w, is_wuser, "
15236386Sjp151216 		    "map_type, map_dn, map_attr, map_value, "
15246386Sjp151216 		    "map_windomain, map_winname, map_unixname, map_is_nt4 "
15255731Sbaban 		    "FROM idmap_cache WHERE is_user = %s AND "
15265731Sbaban 		    "winname = %Q AND windomain = %Q AND w2u = 1 AND "
15275731Sbaban 		    "(pid >= 2147483648 OR "
15285731Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
15295731Sbaban 		    "expiration > %d));",
15306386Sjp151216 		    is_user_string, lower_name, req->id1domain,
15316386Sjp151216 		    curtime);
15325932Sbaban 		if (lower_name != req->id1name)
15335932Sbaban 			free(lower_name);
15345731Sbaban 	} else {
15355731Sbaban 		retcode = IDMAP_ERR_ARG;
15365731Sbaban 		goto out;
15375731Sbaban 	}
15384520Snw141292 	if (sql == NULL) {
15394520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
15404520Snw141292 		retcode = IDMAP_ERR_MEMORY;
15414520Snw141292 		goto out;
15424520Snw141292 	}
15436386Sjp151216 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol,
15446386Sjp151216 	    14, &values);
15454520Snw141292 	sqlite_freemem(sql);
15464520Snw141292 
15474520Snw141292 	if (retcode == IDMAP_ERR_NOTFOUND) {
15484520Snw141292 		goto out;
15494520Snw141292 	} else if (retcode == IDMAP_SUCCESS) {
15504520Snw141292 		/* sanity checks */
15514520Snw141292 		if (values[0] == NULL || values[1] == NULL) {
15524520Snw141292 			retcode = IDMAP_ERR_CACHE;
15534520Snw141292 			goto out;
15544520Snw141292 		}
15554520Snw141292 
15564520Snw141292 		pid = strtoul(values[0], &end, 10);
15575731Sbaban 		is_user = strncmp(values[1], "0", 2) ? 1 : 0;
15584520Snw141292 
15595696Snw141292 		if (is_user) {
15605696Snw141292 			res->id.idtype = IDMAP_UID;
15615696Snw141292 			res->id.idmap_id_u.uid = pid;
15625696Snw141292 		} else {
15635696Snw141292 			res->id.idtype = IDMAP_GID;
15645696Snw141292 			res->id.idmap_id_u.gid = pid;
15655696Snw141292 		}
15665696Snw141292 
15674520Snw141292 		/*
15684520Snw141292 		 * We may have an expired ephemeral mapping. Consider
15694520Snw141292 		 * the expired entry as valid if we are not going to
15704520Snw141292 		 * perform name-based mapping. But do not renew the
15714520Snw141292 		 * expiration.
15724520Snw141292 		 * If we will be doing name-based mapping then store the
15734520Snw141292 		 * ephemeral pid in the result so that we can use it
15744520Snw141292 		 * if we end up doing dynamic mapping again.
15754520Snw141292 		 */
15764520Snw141292 		if (!DO_NOT_ALLOC_NEW_ID_MAPPING(req) &&
15775696Snw141292 		    !AVOID_NAMESERVICE(req) &&
15785696Snw141292 		    IS_EPHEMERAL(pid) && values[2] != NULL) {
15795696Snw141292 			exp = strtoll(values[2], &end, 10);
15805696Snw141292 			if (exp && exp <= curtime) {
15815696Snw141292 				/* Store the ephemeral pid */
15825696Snw141292 				res->direction = IDMAP_DIRECTION_BI;
15835696Snw141292 				req->direction |= is_user
15845696Snw141292 				    ? _IDMAP_F_EXP_EPH_UID
15855696Snw141292 				    : _IDMAP_F_EXP_EPH_GID;
15865696Snw141292 				retcode = IDMAP_ERR_NOTFOUND;
15874520Snw141292 			}
15884520Snw141292 		}
15894520Snw141292 	}
15904520Snw141292 
15914520Snw141292 out:
15924520Snw141292 	if (retcode == IDMAP_SUCCESS) {
15934864Sbaban 		if (values[4] != NULL)
15944520Snw141292 			res->direction =
15954644Sbaban 			    (strtol(values[4], &end, 10) == 0)?
15964644Sbaban 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
15974520Snw141292 		else
15984644Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
15994520Snw141292 
16004864Sbaban 		if (values[3] != NULL) {
16015731Sbaban 			if (req->id2name != NULL)
16025731Sbaban 				free(req->id2name);
16035064Sdm199847 			req->id2name = strdup(values[3]);
16045064Sdm199847 			if (req->id2name == NULL) {
16054520Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
16064520Snw141292 				retcode = IDMAP_ERR_MEMORY;
16074520Snw141292 			}
16084520Snw141292 		}
16095731Sbaban 
16105731Sbaban 		req->id1.idtype = strncmp(values[5], "0", 2) ?
16115731Sbaban 		    IDMAP_USID : IDMAP_GSID;
16126386Sjp151216 
16136386Sjp151216 		if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
16146386Sjp151216 			res->info.src = IDMAP_MAP_SRC_CACHE;
16156386Sjp151216 			res->info.how.map_type = strtoul(values[6], &end, 10);
16166386Sjp151216 			switch (res->info.how.map_type) {
16176386Sjp151216 			case IDMAP_MAP_TYPE_DS_AD:
16186386Sjp151216 				res->info.how.idmap_how_u.ad.dn =
16196386Sjp151216 				    strdup(values[7]);
16206386Sjp151216 				res->info.how.idmap_how_u.ad.attr =
16216386Sjp151216 				    strdup(values[8]);
16226386Sjp151216 				res->info.how.idmap_how_u.ad.value =
16236386Sjp151216 				    strdup(values[9]);
16246386Sjp151216 				break;
16256386Sjp151216 
16266386Sjp151216 			case IDMAP_MAP_TYPE_DS_NLDAP:
16276386Sjp151216 				res->info.how.idmap_how_u.nldap.dn =
16286386Sjp151216 				    strdup(values[7]);
16296386Sjp151216 				res->info.how.idmap_how_u.nldap.attr =
16306386Sjp151216 				    strdup(values[8]);
16316386Sjp151216 				res->info.how.idmap_how_u.nldap.value =
16326386Sjp151216 				    strdup(values[9]);
16336386Sjp151216 				break;
16346386Sjp151216 
16356386Sjp151216 			case IDMAP_MAP_TYPE_RULE_BASED:
16366386Sjp151216 				res->info.how.idmap_how_u.rule.windomain =
16376386Sjp151216 				    strdup(values[10]);
16386386Sjp151216 				res->info.how.idmap_how_u.rule.winname =
16396386Sjp151216 				    strdup(values[11]);
16406386Sjp151216 				res->info.how.idmap_how_u.rule.unixname =
16416386Sjp151216 				    strdup(values[12]);
16426386Sjp151216 				res->info.how.idmap_how_u.rule.is_nt4 =
16436386Sjp151216 				    strtoul(values[13], &end, 1);
16446386Sjp151216 				res->info.how.idmap_how_u.rule.is_user =
16456386Sjp151216 				    is_user;
16466386Sjp151216 				res->info.how.idmap_how_u.rule.is_wuser =
16476386Sjp151216 				    strtoul(values[5], &end, 1);
16486386Sjp151216 				break;
16496386Sjp151216 
16506386Sjp151216 			case IDMAP_MAP_TYPE_EPHEMERAL:
16516386Sjp151216 				break;
16526386Sjp151216 
16536386Sjp151216 			case IDMAP_MAP_TYPE_LOCAL_SID:
16546386Sjp151216 				break;
16556386Sjp151216 
16566386Sjp151216 			case IDMAP_MAP_TYPE_KNOWN_SID:
16576386Sjp151216 				break;
16586386Sjp151216 
16596386Sjp151216 			default:
16606386Sjp151216 				/* Unknow mapping type */
16616386Sjp151216 				assert(FALSE);
16626386Sjp151216 			}
16636386Sjp151216 		}
16644520Snw141292 	}
16654864Sbaban 	if (vm != NULL)
16664520Snw141292 		(void) sqlite_finalize(vm, NULL);
16674520Snw141292 	return (retcode);
16684520Snw141292 }
16694520Snw141292 
16705696Snw141292 static
16715696Snw141292 idmap_retcode
16724864Sbaban lookup_cache_sid2name(sqlite *cache, const char *sidprefix, idmap_rid_t rid,
16735696Snw141292 		char **name, char **domain, int *type)
16745696Snw141292 {
16754520Snw141292 	char		*end;
16764520Snw141292 	char		*sql = NULL;
16774520Snw141292 	const char	**values;
16784520Snw141292 	sqlite_vm	*vm = NULL;
16794520Snw141292 	int		ncol;
16804520Snw141292 	time_t		curtime;
16814520Snw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
16824520Snw141292 
16834520Snw141292 	/* Get current time */
16844520Snw141292 	errno = 0;
16854520Snw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
16865696Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
16875696Snw141292 		    strerror(errno));
16884520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
16894520Snw141292 		goto out;
16904520Snw141292 	}
16914520Snw141292 
16924520Snw141292 	/* SQL to lookup the cache */
16935696Snw141292 	sql = sqlite_mprintf("SELECT canon_name, domain, type "
16945696Snw141292 	    "FROM name_cache WHERE "
16955696Snw141292 	    "sidprefix = %Q AND rid = %u AND "
16965696Snw141292 	    "(expiration = 0 OR expiration ISNULL OR "
16975696Snw141292 	    "expiration > %d);",
16985696Snw141292 	    sidprefix, rid, curtime);
16994520Snw141292 	if (sql == NULL) {
17004520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
17014520Snw141292 		retcode = IDMAP_ERR_MEMORY;
17024520Snw141292 		goto out;
17034520Snw141292 	}
17044520Snw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 3, &values);
17054520Snw141292 	sqlite_freemem(sql);
17064520Snw141292 
17074520Snw141292 	if (retcode == IDMAP_SUCCESS) {
17084864Sbaban 		if (type != NULL) {
17094520Snw141292 			if (values[2] == NULL) {
17104520Snw141292 				retcode = IDMAP_ERR_CACHE;
17114520Snw141292 				goto out;
17124520Snw141292 			}
17134520Snw141292 			*type = strtol(values[2], &end, 10);
17144520Snw141292 		}
17154520Snw141292 
17164864Sbaban 		if (name != NULL && values[0] != NULL) {
17174520Snw141292 			if ((*name = strdup(values[0])) == NULL) {
17184520Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
17194520Snw141292 				retcode = IDMAP_ERR_MEMORY;
17204520Snw141292 				goto out;
17214520Snw141292 			}
17224520Snw141292 		}
17234520Snw141292 
17244864Sbaban 		if (domain != NULL && values[1] != NULL) {
17254520Snw141292 			if ((*domain = strdup(values[1])) == NULL) {
17264864Sbaban 				if (name != NULL && *name) {
17274520Snw141292 					free(*name);
17284520Snw141292 					*name = NULL;
17294520Snw141292 				}
17304520Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
17314520Snw141292 				retcode = IDMAP_ERR_MEMORY;
17324520Snw141292 				goto out;
17334520Snw141292 			}
17344520Snw141292 		}
17354520Snw141292 	}
17364520Snw141292 
17374520Snw141292 out:
17384864Sbaban 	if (vm != NULL)
17394520Snw141292 		(void) sqlite_finalize(vm, NULL);
17404520Snw141292 	return (retcode);
17414520Snw141292 }
17424520Snw141292 
17434520Snw141292 /*
17445731Sbaban  * Given SID, find winname using name_cache OR
17455731Sbaban  * Given winname, find SID using name_cache.
17465731Sbaban  * Used when mapping win to unix i.e. req->id1 is windows id and
17475731Sbaban  * req->id2 is unix id
17484520Snw141292  */
17495696Snw141292 static
17505696Snw141292 idmap_retcode
17515731Sbaban lookup_name_cache(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
17525696Snw141292 {
17534520Snw141292 	int		type = -1;
17544520Snw141292 	idmap_retcode	retcode;
17555731Sbaban 	char		*sidprefix = NULL;
17564520Snw141292 	idmap_rid_t	rid;
17574520Snw141292 	char		*name = NULL, *domain = NULL;
17584520Snw141292 
17595731Sbaban 	/* Done if we've both sid and winname */
17605731Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL && req->id1name != NULL)
17615731Sbaban 		return (IDMAP_SUCCESS);
17625731Sbaban 
17635731Sbaban 	/* Lookup sid to winname */
17645731Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
17655731Sbaban 		retcode = lookup_cache_sid2name(cache,
17665731Sbaban 		    req->id1.idmap_id_u.sid.prefix,
17675731Sbaban 		    req->id1.idmap_id_u.sid.rid, &name, &domain, &type);
17684864Sbaban 		goto out;
17695731Sbaban 	}
17705731Sbaban 
17715731Sbaban 	/* Lookup winame to sid */
17725731Sbaban 	retcode = lookup_cache_name2sid(cache, req->id1name, req->id1domain,
17735731Sbaban 	    &name, &sidprefix, &rid, &type);
17744520Snw141292 
17754520Snw141292 out:
17765731Sbaban 	if (retcode != IDMAP_SUCCESS) {
17775731Sbaban 		free(name);
17785731Sbaban 		free(domain);
17795731Sbaban 		free(sidprefix);
17805731Sbaban 		return (retcode);
17815731Sbaban 	}
17825731Sbaban 
17835731Sbaban 	if (res->id.idtype == IDMAP_POSIXID) {
17845731Sbaban 		res->id.idtype = (type == _IDMAP_T_USER) ?
17855731Sbaban 		    IDMAP_UID : IDMAP_GID;
17865731Sbaban 	}
17875731Sbaban 	req->id1.idtype = (type == _IDMAP_T_USER) ?
17885731Sbaban 	    IDMAP_USID : IDMAP_GSID;
17895731Sbaban 
17905731Sbaban 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
17915731Sbaban 	if (name != NULL) {
17925731Sbaban 		free(req->id1name);	/* Free existing winname */
17935731Sbaban 		req->id1name = name;	/* and use canonical name instead */
17945731Sbaban 	}
17955731Sbaban 	if (req->id1domain == NULL)
17965731Sbaban 		req->id1domain = domain;
17975731Sbaban 	if (req->id1.idmap_id_u.sid.prefix == NULL) {
17985731Sbaban 		req->id1.idmap_id_u.sid.prefix = sidprefix;
17995731Sbaban 		req->id1.idmap_id_u.sid.rid = rid;
18004520Snw141292 	}
18014520Snw141292 	return (retcode);
18024520Snw141292 }
18034520Snw141292 
18048361SJulian.Pullen@Sun.COM 
18058361SJulian.Pullen@Sun.COM 
18068361SJulian.Pullen@Sun.COM static int
18078361SJulian.Pullen@Sun.COM ad_lookup_batch_int(lookup_state_t *state, idmap_mapping_batch *batch,
18088361SJulian.Pullen@Sun.COM 		idmap_ids_res *result, int index, int *num_processed)
18095696Snw141292 {
18104520Snw141292 	idmap_retcode	retcode;
18118361SJulian.Pullen@Sun.COM 	int		i,  num_queued, type, is_wuser, is_user;
18128361SJulian.Pullen@Sun.COM 	int		next_request;
18135731Sbaban 	int		retries = 0, eunixtype;
18145731Sbaban 	char		**unixname;
18154520Snw141292 	idmap_mapping	*req;
18164520Snw141292 	idmap_id_res	*res;
18175731Sbaban 	idmap_query_state_t	*qs = NULL;
18186386Sjp151216 	idmap_how	*how;
18196616Sdm199847 	char		**dn, **attr, **value;
18205731Sbaban 
18218361SJulian.Pullen@Sun.COM 	*num_processed = 0;
18228361SJulian.Pullen@Sun.COM 
18235731Sbaban 	/*
18245731Sbaban 	 * Since req->id2.idtype is unused, we will use it here
18255731Sbaban 	 * to retrieve the value of sid_type. But it needs to be
18265731Sbaban 	 * reset to IDMAP_NONE before we return to prevent xdr
18275731Sbaban 	 * from mis-interpreting req->id2 when it tries to free
18285731Sbaban 	 * the input argument. Other option is to allocate an
18295731Sbaban 	 * array of integers and use it instead for the batched
18305731Sbaban 	 * call. But why un-necessarily allocate memory. That may
18315731Sbaban 	 * be an option if req->id2.idtype cannot be re-used in
18325731Sbaban 	 * future.
18335731Sbaban 	 */
18344520Snw141292 retry:
18358361SJulian.Pullen@Sun.COM 	retcode = idmap_lookup_batch_start(_idmapdstate.ads[index],
18368361SJulian.Pullen@Sun.COM 	    state->ad_nqueries, &qs);
18375731Sbaban 	if (retcode != IDMAP_SUCCESS) {
18388040SBaban.Kenkre@Sun.COM 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
18398040SBaban.Kenkre@Sun.COM 		    retries++ < ADUTILS_DEF_NUM_RETRIES)
18405968Snw141292 			goto retry;
18416097Snw141292 		degrade_svc(1, "failed to create batch for AD lookup");
18428361SJulian.Pullen@Sun.COM 			goto out;
18434520Snw141292 	}
18448361SJulian.Pullen@Sun.COM 	num_queued = 0;
18454520Snw141292 
18465317Sjp151216 	restore_svc();
18475317Sjp151216 
18488361SJulian.Pullen@Sun.COM 	if (index == 0) {
18498361SJulian.Pullen@Sun.COM 		/*
18508361SJulian.Pullen@Sun.COM 		 * Directory based name mapping is only performed within the
18518361SJulian.Pullen@Sun.COM 		 * joined forest (index == 0).  We don't trust other "trusted"
18528361SJulian.Pullen@Sun.COM 		 * forests to provide DS-based name mapping information because
18538361SJulian.Pullen@Sun.COM 		 * AD's definition of "cross-forest trust" does not encompass
18548361SJulian.Pullen@Sun.COM 		 * this sort of behavior.
18558361SJulian.Pullen@Sun.COM 		 */
18568361SJulian.Pullen@Sun.COM 		idmap_lookup_batch_set_unixattr(qs,
18578361SJulian.Pullen@Sun.COM 		    state->ad_unixuser_attr, state->ad_unixgroup_attr);
18588361SJulian.Pullen@Sun.COM 	}
18598361SJulian.Pullen@Sun.COM 
18608361SJulian.Pullen@Sun.COM 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
18614520Snw141292 		req = &batch->idmap_mapping_batch_val[i];
18624520Snw141292 		res = &result->ids.ids_val[i];
18636386Sjp151216 		how = &res->info.how;
18646386Sjp151216 
18655731Sbaban 		retcode = IDMAP_SUCCESS;
18665731Sbaban 		req->id2.idtype = IDMAP_NONE;
18675731Sbaban 
18688361SJulian.Pullen@Sun.COM 		/* Skip if not marked for this AD lookup */
18698361SJulian.Pullen@Sun.COM 		if (!(req->direction & _IDMAP_F_LOOKUP_AD) ||
18708361SJulian.Pullen@Sun.COM 		    (req->direction & _IDMAP_F_LOOKUP_OTHER_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 			}
18968361SJulian.Pullen@Sun.COM 
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);
19228361SJulian.Pullen@Sun.COM 				if (retcode == IDMAP_SUCCESS)
19238361SJulian.Pullen@Sun.COM 					num_queued++;
19246616Sdm199847 			} else {
19256616Sdm199847 				/* Lookup AD by winname */
19266616Sdm199847 				assert(req->id1name != NULL);
19276616Sdm199847 				retcode = idmap_name2sid_batch_add1(
19286616Sdm199847 				    qs, req->id1name, req->id1domain,
19296616Sdm199847 				    eunixtype,
19306616Sdm199847 				    dn, attr, value,
19316616Sdm199847 				    &req->id1name,
19326616Sdm199847 				    &req->id1.idmap_id_u.sid.prefix,
19336616Sdm199847 				    &req->id1.idmap_id_u.sid.rid,
19346616Sdm199847 				    (int *)&req->id2.idtype, unixname,
19356616Sdm199847 				    &res->retcode);
19368361SJulian.Pullen@Sun.COM 				if (retcode == IDMAP_SUCCESS)
19378361SJulian.Pullen@Sun.COM 					num_queued++;
19386616Sdm199847 			}
19395731Sbaban 
19405731Sbaban 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
19416616Sdm199847 
19426616Sdm199847 			/* unix2win request: */
19435731Sbaban 
19445731Sbaban 			if (res->id.idmap_id_u.sid.prefix != NULL &&
19455731Sbaban 			    req->id2name != NULL) {
19468361SJulian.Pullen@Sun.COM 				/* Already have SID and winname. done */
19475731Sbaban 				res->retcode = IDMAP_SUCCESS;
19485731Sbaban 				continue;
19495731Sbaban 			}
19505731Sbaban 
19515731Sbaban 			if (res->id.idmap_id_u.sid.prefix != NULL) {
19525731Sbaban 				/*
19535731Sbaban 				 * SID but no winname -- lookup AD by
19545731Sbaban 				 * SID to get winname.
19556616Sdm199847 				 * how info is not needed here because
19566616Sdm199847 				 * we are not retrieving unixname from
19576616Sdm199847 				 * AD.
19585731Sbaban 				 */
19598361SJulian.Pullen@Sun.COM 
19605731Sbaban 				retcode = idmap_sid2name_batch_add1(
19615731Sbaban 				    qs, res->id.idmap_id_u.sid.prefix,
19625731Sbaban 				    &res->id.idmap_id_u.sid.rid,
19636386Sjp151216 				    _IDMAP_T_UNDEF,
19646616Sdm199847 				    NULL, NULL, NULL,
19656386Sjp151216 				    &req->id2name,
19665731Sbaban 				    &req->id2domain, (int *)&req->id2.idtype,
19675731Sbaban 				    NULL, &res->retcode);
19688361SJulian.Pullen@Sun.COM 				if (retcode == IDMAP_SUCCESS)
19698361SJulian.Pullen@Sun.COM 					num_queued++;
19705731Sbaban 			} else if (req->id2name != NULL) {
19715731Sbaban 				/*
19725731Sbaban 				 * winname but no SID -- lookup AD by
19735731Sbaban 				 * winname to get SID.
19746616Sdm199847 				 * how info is not needed here because
19756616Sdm199847 				 * we are not retrieving unixname from
19766616Sdm199847 				 * AD.
19775731Sbaban 				 */
19785731Sbaban 				retcode = idmap_name2sid_batch_add1(
19795731Sbaban 				    qs, req->id2name, req->id2domain,
19806386Sjp151216 				    _IDMAP_T_UNDEF,
19816616Sdm199847 				    NULL, NULL, NULL, NULL,
19825731Sbaban 				    &res->id.idmap_id_u.sid.prefix,
19835731Sbaban 				    &res->id.idmap_id_u.sid.rid,
19845731Sbaban 				    (int *)&req->id2.idtype, NULL,
19855731Sbaban 				    &res->retcode);
19868361SJulian.Pullen@Sun.COM 				if (retcode == IDMAP_SUCCESS)
19878361SJulian.Pullen@Sun.COM 					num_queued++;
19885731Sbaban 			} else if (req->id1name != NULL) {
19895731Sbaban 				/*
19908361SJulian.Pullen@Sun.COM 				 * No SID and no winname but we've unixname.
19918361SJulian.Pullen@Sun.COM 				 * Lookup AD by unixname to get SID.
19925731Sbaban 				 */
19935731Sbaban 				is_user = (IS_REQUEST_UID(*req)) ? 1 : 0;
19945731Sbaban 				if (res->id.idtype == IDMAP_USID)
19955731Sbaban 					is_wuser = 1;
19965731Sbaban 				else if (res->id.idtype == IDMAP_GSID)
19975731Sbaban 					is_wuser = 0;
19985731Sbaban 				else
19995731Sbaban 					is_wuser = is_user;
20008361SJulian.Pullen@Sun.COM 
20016616Sdm199847 				idmap_info_free(&res->info);
20026386Sjp151216 				res->info.src = IDMAP_MAP_SRC_NEW;
20036386Sjp151216 				how->map_type = IDMAP_MAP_TYPE_DS_AD;
20045731Sbaban 				retcode = idmap_unixname2sid_batch_add1(
20055731Sbaban 				    qs, req->id1name, is_user, is_wuser,
20066386Sjp151216 				    &how->idmap_how_u.ad.dn,
20076386Sjp151216 				    &how->idmap_how_u.ad.attr,
20086386Sjp151216 				    &how->idmap_how_u.ad.value,
20095731Sbaban 				    &res->id.idmap_id_u.sid.prefix,
20105731Sbaban 				    &res->id.idmap_id_u.sid.rid,
20115731Sbaban 				    &req->id2name, &req->id2domain,
20125731Sbaban 				    (int *)&req->id2.idtype, &res->retcode);
20138361SJulian.Pullen@Sun.COM 				if (retcode == IDMAP_SUCCESS)
20148361SJulian.Pullen@Sun.COM 					num_queued++;
20155731Sbaban 			}
20165731Sbaban 		}
20178361SJulian.Pullen@Sun.COM 
20188361SJulian.Pullen@Sun.COM 		if (retcode == IDMAP_ERR_DOMAIN_NOTFOUND) {
20198361SJulian.Pullen@Sun.COM 			req->direction |= _IDMAP_F_LOOKUP_OTHER_AD;
20208361SJulian.Pullen@Sun.COM 			retcode = IDMAP_SUCCESS;
20218361SJulian.Pullen@Sun.COM 		} else if (retcode != IDMAP_SUCCESS) {
20225731Sbaban 			idmap_lookup_release_batch(&qs);
20238361SJulian.Pullen@Sun.COM 			num_queued = 0;
20248361SJulian.Pullen@Sun.COM 			next_request = i + 1;
20255731Sbaban 			break;
20264520Snw141292 		}
20278361SJulian.Pullen@Sun.COM 	} /* End of for loop */
20284520Snw141292 
20296963Sbaban 	if (retcode == IDMAP_SUCCESS) {
20306963Sbaban 		/* add keeps track if we added an entry to the batch */
20318361SJulian.Pullen@Sun.COM 		if (num_queued > 0)
20326963Sbaban 			retcode = idmap_lookup_batch_end(&qs);
20336963Sbaban 		else
20346963Sbaban 			idmap_lookup_release_batch(&qs);
20356963Sbaban 	}
20365696Snw141292 
20378040SBaban.Kenkre@Sun.COM 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
20388040SBaban.Kenkre@Sun.COM 	    retries++ < ADUTILS_DEF_NUM_RETRIES)
20394520Snw141292 		goto retry;
20405317Sjp151216 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
20416097Snw141292 		degrade_svc(1, "some AD lookups timed out repeatedly");
20424520Snw141292 
20438361SJulian.Pullen@Sun.COM 	if (retcode != IDMAP_SUCCESS) {
20448361SJulian.Pullen@Sun.COM 		/* Mark any unproccessed requests for an other AD */
20458361SJulian.Pullen@Sun.COM 		for (i = next_request; i < batch->idmap_mapping_batch_len;
20468361SJulian.Pullen@Sun.COM 		    i++) {
20478361SJulian.Pullen@Sun.COM 			req = &batch->idmap_mapping_batch_val[i];
20488361SJulian.Pullen@Sun.COM 			req->direction |= _IDMAP_F_LOOKUP_OTHER_AD;
20498361SJulian.Pullen@Sun.COM 
20508361SJulian.Pullen@Sun.COM 		}
20518361SJulian.Pullen@Sun.COM 	}
20528361SJulian.Pullen@Sun.COM 
20535731Sbaban 	if (retcode != IDMAP_SUCCESS)
20545731Sbaban 		idmapdlog(LOG_NOTICE, "Failed to batch AD lookup requests");
20554520Snw141292 
20564520Snw141292 out:
20575731Sbaban 	/*
20585731Sbaban 	 * This loop does the following:
20596616Sdm199847 	 * 1. Reset _IDMAP_F_LOOKUP_AD flag from the request.
20606616Sdm199847 	 * 2. Reset req->id2.idtype to IDMAP_NONE
20616616Sdm199847 	 * 3. If batch_start or batch_add failed then set the status
20626616Sdm199847 	 *    of each request marked for AD lookup to that error.
20638361SJulian.Pullen@Sun.COM 	 * 4. Evaluate the type of the AD object (i.e. user or group)
20648361SJulian.Pullen@Sun.COM 	 *    and update the idtype in request.
20655731Sbaban 	 */
20665731Sbaban 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
20675731Sbaban 		req = &batch->idmap_mapping_batch_val[i];
20685731Sbaban 		type = req->id2.idtype;
20695731Sbaban 		req->id2.idtype = IDMAP_NONE;
20705746Sbaban 		res = &result->ids.ids_val[i];
20716386Sjp151216 		how = &res->info.how;
20728361SJulian.Pullen@Sun.COM 		if (!(req->direction & _IDMAP_F_LOOKUP_AD) ||
20738361SJulian.Pullen@Sun.COM 		    (req->direction & _IDMAP_F_LOOKUP_OTHER_AD))
20745731Sbaban 			continue;
20755731Sbaban 
20768361SJulian.Pullen@Sun.COM 		/* Count number processed */
20778361SJulian.Pullen@Sun.COM 		(*num_processed)++;
20788361SJulian.Pullen@Sun.COM 
20796616Sdm199847 		/* Reset AD lookup flag */
20806616Sdm199847 		req->direction &= ~(_IDMAP_F_LOOKUP_AD);
20816616Sdm199847 
20826616Sdm199847 		/*
20838361SJulian.Pullen@Sun.COM 		 * If batch_start or batch_add failed then set the
20848361SJulian.Pullen@Sun.COM 		 * status of each request marked for AD lookup to
20858361SJulian.Pullen@Sun.COM 		 * that error.
20866616Sdm199847 		 */
20875731Sbaban 		if (retcode != IDMAP_SUCCESS) {
20885731Sbaban 			res->retcode = retcode;
20895731Sbaban 			continue;
20905731Sbaban 		}
20915731Sbaban 
20926386Sjp151216 		if (res->retcode == IDMAP_ERR_NOTFOUND) {
20936386Sjp151216 			/* Nothing found - remove the preset info */
20946616Sdm199847 			idmap_info_free(&res->info);
20956386Sjp151216 		}
20966386Sjp151216 
20975731Sbaban 		if (IS_REQUEST_SID(*req, 1)) {
20985731Sbaban 			if (res->retcode != IDMAP_SUCCESS)
20995731Sbaban 				continue;
21006616Sdm199847 			/* Evaluate result type */
21015731Sbaban 			switch (type) {
21025731Sbaban 			case _IDMAP_T_USER:
21035731Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
21045731Sbaban 					res->id.idtype = IDMAP_UID;
21055731Sbaban 				req->id1.idtype = IDMAP_USID;
21065731Sbaban 				break;
21078361SJulian.Pullen@Sun.COM 
21085731Sbaban 			case _IDMAP_T_GROUP:
21095731Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
21105731Sbaban 					res->id.idtype = IDMAP_GID;
21115731Sbaban 				req->id1.idtype = IDMAP_GSID;
21125731Sbaban 				break;
21138361SJulian.Pullen@Sun.COM 
21145731Sbaban 			default:
21155731Sbaban 				res->retcode = IDMAP_ERR_SID;
21165731Sbaban 				break;
21175731Sbaban 			}
21186616Sdm199847 			if (res->retcode == IDMAP_SUCCESS &&
21196616Sdm199847 			    req->id1name != NULL &&
21206616Sdm199847 			    (req->id2name == NULL ||
21216616Sdm199847 			    res->id.idmap_id_u.uid == SENTINEL_PID) &&
21226616Sdm199847 			    NLDAP_MODE(res->id.idtype, state)) {
21236616Sdm199847 				req->direction |= _IDMAP_F_LOOKUP_NLDAP;
21246616Sdm199847 				state->nldap_nqueries++;
21256616Sdm199847 			}
21265731Sbaban 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
21275731Sbaban 			if (res->retcode != IDMAP_SUCCESS) {
21285731Sbaban 				if ((!(IDMAP_FATAL_ERROR(res->retcode))) &&
21295731Sbaban 				    res->id.idmap_id_u.sid.prefix == NULL &&
21305731Sbaban 				    req->id2name == NULL && /* no winname */
21315731Sbaban 				    req->id1name != NULL) /* unixname */
21325731Sbaban 					/*
21338361SJulian.Pullen@Sun.COM 					 * If AD lookup by unixname
21348361SJulian.Pullen@Sun.COM 					 * failed with non fatal error
21358361SJulian.Pullen@Sun.COM 					 * then clear the error (ie set
21368361SJulian.Pullen@Sun.COM 					 * res->retcode to success).
21378361SJulian.Pullen@Sun.COM 					 * This allows the next pass to
21388361SJulian.Pullen@Sun.COM 					 * process other mapping
21396616Sdm199847 					 * mechanisms for this request.
21405731Sbaban 					 */
21415731Sbaban 					res->retcode = IDMAP_SUCCESS;
21425731Sbaban 				continue;
21435731Sbaban 			}
21446616Sdm199847 			/* Evaluate result type */
21455731Sbaban 			switch (type) {
21465731Sbaban 			case _IDMAP_T_USER:
21475731Sbaban 				if (res->id.idtype == IDMAP_SID)
21485731Sbaban 					res->id.idtype = IDMAP_USID;
21495731Sbaban 				break;
21508361SJulian.Pullen@Sun.COM 
21515731Sbaban 			case _IDMAP_T_GROUP:
21525731Sbaban 				if (res->id.idtype == IDMAP_SID)
21535731Sbaban 					res->id.idtype = IDMAP_GSID;
21545731Sbaban 				break;
21558361SJulian.Pullen@Sun.COM 
21565731Sbaban 			default:
21575731Sbaban 				res->retcode = IDMAP_ERR_SID;
21585731Sbaban 				break;
21595731Sbaban 			}
21605731Sbaban 		}
21615731Sbaban 	}
21625731Sbaban 
21638361SJulian.Pullen@Sun.COM 	return (retcode);
21648361SJulian.Pullen@Sun.COM }
21658361SJulian.Pullen@Sun.COM 
21668361SJulian.Pullen@Sun.COM 
21678361SJulian.Pullen@Sun.COM 
21688361SJulian.Pullen@Sun.COM /*
21698361SJulian.Pullen@Sun.COM  * Batch AD lookups
21708361SJulian.Pullen@Sun.COM  */
21718361SJulian.Pullen@Sun.COM idmap_retcode
21728361SJulian.Pullen@Sun.COM ad_lookup_batch(lookup_state_t *state, idmap_mapping_batch *batch,
21738361SJulian.Pullen@Sun.COM 		idmap_ids_res *result)
21748361SJulian.Pullen@Sun.COM {
21758361SJulian.Pullen@Sun.COM 	idmap_retcode	retcode;
21768361SJulian.Pullen@Sun.COM 	int		i, j;
21778361SJulian.Pullen@Sun.COM 	idmap_mapping	*req;
21788361SJulian.Pullen@Sun.COM 	idmap_id_res	*res;
21798361SJulian.Pullen@Sun.COM 	int		num_queries;
21808361SJulian.Pullen@Sun.COM 	int		num_processed;
21818361SJulian.Pullen@Sun.COM 
21828361SJulian.Pullen@Sun.COM 	if (state->ad_nqueries == 0)
21838361SJulian.Pullen@Sun.COM 		return (IDMAP_SUCCESS);
21848361SJulian.Pullen@Sun.COM 
21858361SJulian.Pullen@Sun.COM 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
21868361SJulian.Pullen@Sun.COM 		req = &batch->idmap_mapping_batch_val[i];
21878361SJulian.Pullen@Sun.COM 		res = &result->ids.ids_val[i];
21888361SJulian.Pullen@Sun.COM 
21898361SJulian.Pullen@Sun.COM 		/* Skip if not marked for AD lookup or already in error. */
21908361SJulian.Pullen@Sun.COM 		if (!(req->direction & _IDMAP_F_LOOKUP_AD) ||
21918361SJulian.Pullen@Sun.COM 		    res->retcode != IDMAP_SUCCESS)
21928361SJulian.Pullen@Sun.COM 			continue;
21938361SJulian.Pullen@Sun.COM 
21948361SJulian.Pullen@Sun.COM 		/* Init status */
21958361SJulian.Pullen@Sun.COM 		res->retcode = IDMAP_ERR_RETRIABLE_NET_ERR;
21968361SJulian.Pullen@Sun.COM 	}
21978361SJulian.Pullen@Sun.COM 
21988361SJulian.Pullen@Sun.COM 	RDLOCK_CONFIG();
21998361SJulian.Pullen@Sun.COM 	num_queries = state->ad_nqueries;
22008361SJulian.Pullen@Sun.COM 	if (_idmapdstate.num_ads > 0) {
22018361SJulian.Pullen@Sun.COM 		for (i = 0; i < _idmapdstate.num_ads && num_queries > 0; i++) {
22028361SJulian.Pullen@Sun.COM 
22038361SJulian.Pullen@Sun.COM 			retcode = ad_lookup_batch_int(state, batch, result, i,
22048361SJulian.Pullen@Sun.COM 			    &num_processed);
22058361SJulian.Pullen@Sun.COM 			num_queries -= num_processed;
22068361SJulian.Pullen@Sun.COM 
22078361SJulian.Pullen@Sun.COM 			if (num_queries > 0) {
22088361SJulian.Pullen@Sun.COM 				for (j = 0; j < batch->idmap_mapping_batch_len;
22098361SJulian.Pullen@Sun.COM 				    j++) {
22108361SJulian.Pullen@Sun.COM 					req =
22118361SJulian.Pullen@Sun.COM 					    &batch->idmap_mapping_batch_val[j];
22128361SJulian.Pullen@Sun.COM 					res = &result->ids.ids_val[j];
22138361SJulian.Pullen@Sun.COM 					if (!(req->direction &
22148361SJulian.Pullen@Sun.COM 					    _IDMAP_F_LOOKUP_AD))
22158361SJulian.Pullen@Sun.COM 						continue;
22168361SJulian.Pullen@Sun.COM 					/*
22178361SJulian.Pullen@Sun.COM 					 * Reset the other AD lookup flag so
22188361SJulian.Pullen@Sun.COM 					 * that we can try the next AD
22198361SJulian.Pullen@Sun.COM 					 */
22208361SJulian.Pullen@Sun.COM 					req->direction &=
22218361SJulian.Pullen@Sun.COM 					    ~(_IDMAP_F_LOOKUP_OTHER_AD);
22228361SJulian.Pullen@Sun.COM 
22238361SJulian.Pullen@Sun.COM 					if ((i + 1) >= _idmapdstate.num_ads) {
22248361SJulian.Pullen@Sun.COM 						/*
22258361SJulian.Pullen@Sun.COM 						 * There are no more ADs to try
22268361SJulian.Pullen@Sun.COM 						 */
22278361SJulian.Pullen@Sun.COM 						req->direction &=
22288361SJulian.Pullen@Sun.COM 						    ~(_IDMAP_F_LOOKUP_AD);
22298361SJulian.Pullen@Sun.COM 						res->retcode =
22308361SJulian.Pullen@Sun.COM 						    IDMAP_ERR_DOMAIN_NOTFOUND;
22318361SJulian.Pullen@Sun.COM 					}
22328361SJulian.Pullen@Sun.COM 				}
22338361SJulian.Pullen@Sun.COM 			}
22348361SJulian.Pullen@Sun.COM 		}
22358361SJulian.Pullen@Sun.COM 	} else {
22368361SJulian.Pullen@Sun.COM 		/* Case of no ADs */
22378361SJulian.Pullen@Sun.COM 		retcode = IDMAP_ERR_NO_ACTIVEDIRECTORY;
22388361SJulian.Pullen@Sun.COM 		for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
22398361SJulian.Pullen@Sun.COM 			req = &batch->idmap_mapping_batch_val[i];
22408361SJulian.Pullen@Sun.COM 			res = &result->ids.ids_val[i];
22418361SJulian.Pullen@Sun.COM 			if (!(req->direction & _IDMAP_F_LOOKUP_AD))
22428361SJulian.Pullen@Sun.COM 				continue;
22438361SJulian.Pullen@Sun.COM 			req->direction &= ~(_IDMAP_F_LOOKUP_AD);
22448361SJulian.Pullen@Sun.COM 			res->retcode = IDMAP_ERR_NO_ACTIVEDIRECTORY;
22458361SJulian.Pullen@Sun.COM 		}
22468361SJulian.Pullen@Sun.COM 	}
22478361SJulian.Pullen@Sun.COM 	UNLOCK_CONFIG();
22488361SJulian.Pullen@Sun.COM 
22495731Sbaban 	/* AD lookups done. Reset state->ad_nqueries and return */
22505731Sbaban 	state->ad_nqueries = 0;
22514520Snw141292 	return (retcode);
22524520Snw141292 }
22534520Snw141292 
22545696Snw141292 /*
22555696Snw141292  * Convention when processing win2unix requests:
22565696Snw141292  *
22575696Snw141292  * Windows identity:
22585696Snw141292  * req->id1name =
22595696Snw141292  *              winname if given otherwise winname found will be placed
22605696Snw141292  *              here.
22615696Snw141292  * req->id1domain =
22625696Snw141292  *              windomain if given otherwise windomain found will be
22635696Snw141292  *              placed here.
22645696Snw141292  * req->id1.idtype =
22655696Snw141292  *              Either IDMAP_SID/USID/GSID. If this is IDMAP_SID then it'll
22665696Snw141292  *              be set to IDMAP_USID/GSID depending upon whether the
22675696Snw141292  *              given SID is user or group respectively. The user/group-ness
22685696Snw141292  *              is determined either when looking up well-known SIDs table OR
22696616Sdm199847  *              if the SID is found in namecache OR by ad_lookup_one() OR by
22705696Snw141292  *              ad_lookup_batch().
22715696Snw141292  * req->id1..sid.[prefix, rid] =
22725696Snw141292  *              SID if given otherwise SID found will be placed here.
22735696Snw141292  *
22745696Snw141292  * Unix identity:
22755696Snw141292  * req->id2name =
22765696Snw141292  *              unixname found will be placed here.
22775696Snw141292  * req->id2domain =
22785696Snw141292  *              NOT USED
22795696Snw141292  * res->id.idtype =
22805696Snw141292  *              Target type initialized from req->id2.idtype. If
22815696Snw141292  *              it is IDMAP_POSIXID then actual type (IDMAP_UID/GID) found
22825696Snw141292  *              will be placed here.
22835696Snw141292  * res->id..[uid or gid] =
22845696Snw141292  *              UID/GID found will be placed here.
22855696Snw141292  *
22865696Snw141292  * Others:
22875696Snw141292  * res->retcode =
22885696Snw141292  *              Return status for this request will be placed here.
22895696Snw141292  * res->direction =
22905696Snw141292  *              Direction found will be placed here. Direction
22915696Snw141292  *              meaning whether the resultant mapping is valid
22925696Snw141292  *              only from win2unix or bi-directional.
22935696Snw141292  * req->direction =
22945696Snw141292  *              INTERNAL USE. Used by idmapd to set various
22955696Snw141292  *              flags (_IDMAP_F_xxxx) to aid in processing
22965696Snw141292  *              of the request.
22975696Snw141292  * req->id2.idtype =
22985696Snw141292  *              INTERNAL USE. Initially this is the requested target
22995696Snw141292  *              type and is used to initialize res->id.idtype.
23005696Snw141292  *              ad_lookup_batch() uses this field temporarily to store
23015696Snw141292  *              sid_type obtained by the batched AD lookups and after
23025696Snw141292  *              use resets it to IDMAP_NONE to prevent xdr from
23035696Snw141292  *              mis-interpreting the contents of req->id2.
23045696Snw141292  * req->id2..[uid or gid or sid] =
23055696Snw141292  *              NOT USED
23065696Snw141292  */
23075696Snw141292 
23085696Snw141292 /*
23095696Snw141292  * This function does the following:
23105696Snw141292  * 1. Lookup well-known SIDs table.
23115696Snw141292  * 2. Check if the given SID is a local-SID and if so extract UID/GID from it.
23125696Snw141292  * 3. Lookup cache.
23135696Snw141292  * 4. Check if the client does not want new mapping to be allocated
23145696Snw141292  *    in which case this pass is the final pass.
23155696Snw141292  * 5. Set AD lookup flag if it determines that the next stage needs
23165696Snw141292  *    to do AD lookup.
23175696Snw141292  */
23184520Snw141292 idmap_retcode
23196616Sdm199847 sid2pid_first_pass(lookup_state_t *state, idmap_mapping *req,
23205696Snw141292 		idmap_id_res *res)
23215696Snw141292 {
23224520Snw141292 	idmap_retcode	retcode;
23235731Sbaban 	int		wksid;
23245731Sbaban 
23255731Sbaban 	/* Initialize result */
23265731Sbaban 	res->id.idtype = req->id2.idtype;
23275731Sbaban 	res->id.idmap_id_u.uid = SENTINEL_PID;
23285731Sbaban 	res->direction = IDMAP_DIRECTION_UNDEF;
23295731Sbaban 	wksid = 0;
23304520Snw141292 
23315127Sdm199847 	if (EMPTY_STRING(req->id1.idmap_id_u.sid.prefix)) {
23325731Sbaban 		if (req->id1name == NULL) {
23335731Sbaban 			retcode = IDMAP_ERR_ARG;
23345731Sbaban 			goto out;
23355731Sbaban 		}
23365731Sbaban 		/* sanitize sidprefix */
23375731Sbaban 		free(req->id1.idmap_id_u.sid.prefix);
23385731Sbaban 		req->id1.idmap_id_u.sid.prefix = NULL;
23394520Snw141292 	}
23405731Sbaban 
23415731Sbaban 	/* Lookup well-known SIDs table */
23425731Sbaban 	retcode = lookup_wksids_sid2pid(req, res, &wksid);
23434520Snw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
23444520Snw141292 		goto out;
23454520Snw141292 
23465731Sbaban 	if (!wksid) {
23478040SBaban.Kenkre@Sun.COM 		/* Check if this is a localsid */
23485731Sbaban 		retcode = lookup_localsid2pid(req, res);
23495731Sbaban 		if (retcode != IDMAP_ERR_NOTFOUND)
23505731Sbaban 			goto out;
23518040SBaban.Kenkre@Sun.COM 
23528040SBaban.Kenkre@Sun.COM 		if (ALLOW_WK_OR_LOCAL_SIDS_ONLY(req)) {
23538361SJulian.Pullen@Sun.COM 			retcode = IDMAP_ERR_NONE_GENERATED;
23548040SBaban.Kenkre@Sun.COM 			goto out;
23558040SBaban.Kenkre@Sun.COM 		}
23565731Sbaban 	}
23575731Sbaban 
23585731Sbaban 	/* Lookup cache */
23596616Sdm199847 	retcode = lookup_cache_sid2pid(state->cache, req, res);
23604520Snw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
23614520Snw141292 		goto out;
23624520Snw141292 
23634520Snw141292 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req) || AVOID_NAMESERVICE(req)) {
23648361SJulian.Pullen@Sun.COM 		retcode = IDMAP_ERR_NONE_GENERATED;
23654520Snw141292 		goto out;
23664520Snw141292 	}
23674520Snw141292 
23684520Snw141292 	/*
23695731Sbaban 	 * Failed to find non-expired entry in cache. Next step is
23705731Sbaban 	 * to determine if this request needs to be batched for AD lookup.
23715731Sbaban 	 *
23725731Sbaban 	 * At this point we have either sid or winname or both. If we don't
23735731Sbaban 	 * have both then lookup name_cache for the sid or winname
23745731Sbaban 	 * whichever is missing. If not found then this request will be
23755731Sbaban 	 * batched for AD lookup.
23764520Snw141292 	 */
23776616Sdm199847 	retcode = lookup_name_cache(state->cache, req, res);
23785731Sbaban 	if (retcode != IDMAP_SUCCESS && retcode != IDMAP_ERR_NOTFOUND)
23795731Sbaban 		goto out;
23804520Snw141292 
23814520Snw141292 	/*
23825731Sbaban 	 * Set the flag to indicate that we are not done yet so that
23835731Sbaban 	 * subsequent passes considers this request for name-based
23845731Sbaban 	 * mapping and ephemeral mapping.
23854520Snw141292 	 */
23865731Sbaban 	state->sid2pid_done = FALSE;
23875731Sbaban 	req->direction |= _IDMAP_F_NOTDONE;
23885731Sbaban 
23895731Sbaban 	/*
23905731Sbaban 	 * Even if we have both sid and winname, we still may need to batch
23915731Sbaban 	 * this request for AD lookup if we don't have unixname and
23925731Sbaban 	 * directory-based name mapping (AD or mixed) is enabled.
23935731Sbaban 	 * We avoid AD lookup for well-known SIDs because they don't have
23945731Sbaban 	 * regular AD objects.
23955731Sbaban 	 */
23965731Sbaban 	if (retcode != IDMAP_SUCCESS ||
23975731Sbaban 	    (!wksid && req->id2name == NULL &&
23985731Sbaban 	    AD_OR_MIXED_MODE(res->id.idtype, state))) {
23994520Snw141292 		retcode = IDMAP_SUCCESS;
24005731Sbaban 		req->direction |= _IDMAP_F_LOOKUP_AD;
24014520Snw141292 		state->ad_nqueries++;
24026616Sdm199847 	} else if (NLDAP_MODE(res->id.idtype, state)) {
24036616Sdm199847 		req->direction |= _IDMAP_F_LOOKUP_NLDAP;
24046616Sdm199847 		state->nldap_nqueries++;
24054520Snw141292 	}
24064520Snw141292 
24074520Snw141292 
24084520Snw141292 out:
24094520Snw141292 	res->retcode = idmap_stat4prot(retcode);
24105731Sbaban 	/*
24115731Sbaban 	 * If we are done and there was an error then set fallback pid
24125731Sbaban 	 * in the result.
24135731Sbaban 	 */
24145731Sbaban 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
24155731Sbaban 		res->id.idmap_id_u.uid = UID_NOBODY;
24164520Snw141292 	return (retcode);
24174520Snw141292 }
24184520Snw141292 
24194520Snw141292 /*
24204520Snw141292  * Generate SID using the following convention
24214520Snw141292  * 	<machine-sid-prefix>-<1000 + uid>
24224520Snw141292  * 	<machine-sid-prefix>-<2^31 + gid>
24234520Snw141292  */
24245696Snw141292 static
24255696Snw141292 idmap_retcode
24266386Sjp151216 generate_localsid(idmap_mapping *req, idmap_id_res *res, int is_user,
24276386Sjp151216 		int fallback)
24285696Snw141292 {
24295731Sbaban 	free(res->id.idmap_id_u.sid.prefix);
24305731Sbaban 	res->id.idmap_id_u.sid.prefix = NULL;
24315731Sbaban 
24325731Sbaban 	/*
24335731Sbaban 	 * Diagonal mapping for localSIDs not supported because of the
24345731Sbaban 	 * way we generate localSIDs.
24355731Sbaban 	 */
24365731Sbaban 	if (is_user && res->id.idtype == IDMAP_GSID)
24375731Sbaban 		return (IDMAP_ERR_NOMAPPING);
24385731Sbaban 	if (!is_user && res->id.idtype == IDMAP_USID)
24395731Sbaban 		return (IDMAP_ERR_NOMAPPING);
24405731Sbaban 
24415731Sbaban 	/* Skip 1000 UIDs */
24425731Sbaban 	if (is_user && req->id1.idmap_id_u.uid >
24435731Sbaban 	    (INT32_MAX - LOCALRID_MIN))
24445731Sbaban 		return (IDMAP_ERR_NOMAPPING);
24455731Sbaban 
24465731Sbaban 	RDLOCK_CONFIG();
24475731Sbaban 	/*
24485731Sbaban 	 * machine_sid is never NULL because if it is we won't be here.
24495731Sbaban 	 * No need to assert because stdrup(NULL) will core anyways.
24505731Sbaban 	 */
24515731Sbaban 	res->id.idmap_id_u.sid.prefix =
24525731Sbaban 	    strdup(_idmapdstate.cfg->pgcfg.machine_sid);
24535731Sbaban 	if (res->id.idmap_id_u.sid.prefix == NULL) {
24544520Snw141292 		UNLOCK_CONFIG();
24555731Sbaban 		idmapdlog(LOG_ERR, "Out of memory");
24565731Sbaban 		return (IDMAP_ERR_MEMORY);
24574520Snw141292 	}
24585731Sbaban 	UNLOCK_CONFIG();
24595731Sbaban 	res->id.idmap_id_u.sid.rid =
24605731Sbaban 	    (is_user) ? req->id1.idmap_id_u.uid + LOCALRID_MIN :
24615731Sbaban 	    req->id1.idmap_id_u.gid + INT32_MAX + 1;
24625731Sbaban 	res->direction = IDMAP_DIRECTION_BI;
24635731Sbaban 	if (res->id.idtype == IDMAP_SID)
24645731Sbaban 		res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
24655731Sbaban 
24666386Sjp151216 	if (!fallback && req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
24676386Sjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_LOCAL_SID;
24686386Sjp151216 		res->info.src = IDMAP_MAP_SRC_ALGORITHMIC;
24696386Sjp151216 	}
24706386Sjp151216 
24715731Sbaban 	/*
24725731Sbaban 	 * Don't update name_cache because local sids don't have
24735731Sbaban 	 * valid windows names.
24745731Sbaban 	 */
24755731Sbaban 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
24765731Sbaban 	return (IDMAP_SUCCESS);
24774520Snw141292 }
24784520Snw141292 
24795696Snw141292 static
24805696Snw141292 idmap_retcode
24815696Snw141292 lookup_localsid2pid(idmap_mapping *req, idmap_id_res *res)
24825696Snw141292 {
24834520Snw141292 	char		*sidprefix;
24844520Snw141292 	uint32_t	rid;
24854520Snw141292 	int		s;
24864520Snw141292 
24874520Snw141292 	/*
24884520Snw141292 	 * If the sidprefix == localsid then UID = last RID - 1000 or
24894520Snw141292 	 * GID = last RID - 2^31.
24904520Snw141292 	 */
24915731Sbaban 	if ((sidprefix = req->id1.idmap_id_u.sid.prefix) == NULL)
24925731Sbaban 		/* This means we are looking up by winname */
24935731Sbaban 		return (IDMAP_ERR_NOTFOUND);
24944520Snw141292 	rid = req->id1.idmap_id_u.sid.rid;
24954520Snw141292 
24964520Snw141292 	RDLOCK_CONFIG();
24975696Snw141292 	s = (_idmapdstate.cfg->pgcfg.machine_sid) ?
24985696Snw141292 	    strcasecmp(sidprefix, _idmapdstate.cfg->pgcfg.machine_sid) : 1;
24994520Snw141292 	UNLOCK_CONFIG();
25004520Snw141292 
25015731Sbaban 	/*
25025731Sbaban 	 * If the given sidprefix does not match machine_sid then this is
25035731Sbaban 	 * not a local SID.
25045731Sbaban 	 */
25055731Sbaban 	if (s != 0)
25065731Sbaban 		return (IDMAP_ERR_NOTFOUND);
25075731Sbaban 
25085731Sbaban 	switch (res->id.idtype) {
25095731Sbaban 	case IDMAP_UID:
25105731Sbaban 		if (rid > INT32_MAX || rid < LOCALRID_MIN)
25115731Sbaban 			return (IDMAP_ERR_ARG);
25125731Sbaban 		res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
25135731Sbaban 		break;
25145731Sbaban 	case IDMAP_GID:
25155731Sbaban 		if (rid <= INT32_MAX)
25165731Sbaban 			return (IDMAP_ERR_ARG);
25175731Sbaban 		res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
25185731Sbaban 		break;
25195731Sbaban 	case IDMAP_POSIXID:
25205731Sbaban 		if (rid > INT32_MAX) {
25214520Snw141292 			res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
25224520Snw141292 			res->id.idtype = IDMAP_GID;
25235731Sbaban 		} else if (rid < LOCALRID_MIN) {
25245731Sbaban 			return (IDMAP_ERR_ARG);
25255731Sbaban 		} else {
25265731Sbaban 			res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
25275731Sbaban 			res->id.idtype = IDMAP_UID;
25284520Snw141292 		}
25295731Sbaban 		break;
25305731Sbaban 	default:
25315731Sbaban 		return (IDMAP_ERR_NOTSUPPORTED);
25324520Snw141292 	}
25336386Sjp151216 	if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
25346386Sjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_LOCAL_SID;
25356386Sjp151216 		res->info.src = IDMAP_MAP_SRC_ALGORITHMIC;
25366386Sjp151216 	}
25375731Sbaban 	return (IDMAP_SUCCESS);
25384520Snw141292 }
25394520Snw141292 
25405731Sbaban /*
25415731Sbaban  * Name service lookup by unixname to get pid
25425731Sbaban  */
25435696Snw141292 static
25445696Snw141292 idmap_retcode
25455731Sbaban ns_lookup_byname(const char *name, const char *lower_name, idmap_id *id)
25465696Snw141292 {
25475696Snw141292 	struct passwd	pwd, *pwdp;
25485696Snw141292 	struct group	grp, *grpp;
25494520Snw141292 	char		buf[1024];
25504520Snw141292 	int		errnum;
25514520Snw141292 	const char	*me = "ns_lookup_byname";
25524520Snw141292 
25535731Sbaban 	switch (id->idtype) {
25545731Sbaban 	case IDMAP_UID:
25555696Snw141292 		pwdp = getpwnam_r(name, &pwd, buf, sizeof (buf));
25565731Sbaban 		if (pwdp == NULL && errno == 0 && lower_name != NULL &&
25575696Snw141292 		    name != lower_name && strcmp(name, lower_name) != 0)
25585696Snw141292 			pwdp = getpwnam_r(lower_name, &pwd, buf, sizeof (buf));
25595696Snw141292 		if (pwdp == NULL) {
25604520Snw141292 			errnum = errno;
25614520Snw141292 			idmapdlog(LOG_WARNING,
25625696Snw141292 			    "%s: getpwnam_r(%s) failed (%s).",
25635696Snw141292 			    me, name, errnum ? strerror(errnum) : "not found");
25644520Snw141292 			if (errnum == 0)
25654520Snw141292 				return (IDMAP_ERR_NOTFOUND);
25664520Snw141292 			else
25674520Snw141292 				return (IDMAP_ERR_INTERNAL);
25684520Snw141292 		}
25695731Sbaban 		id->idmap_id_u.uid = pwd.pw_uid;
25705731Sbaban 		break;
25715731Sbaban 	case IDMAP_GID:
25725696Snw141292 		grpp = getgrnam_r(name, &grp, buf, sizeof (buf));
25735731Sbaban 		if (grpp == NULL && errno == 0 && lower_name != NULL &&
25745696Snw141292 		    name != lower_name && strcmp(name, lower_name) != 0)
25755696Snw141292 			grpp = getgrnam_r(lower_name, &grp, buf, sizeof (buf));
25765696Snw141292 		if (grpp == NULL) {
25774520Snw141292 			errnum = errno;
25784520Snw141292 			idmapdlog(LOG_WARNING,
25795696Snw141292 			    "%s: getgrnam_r(%s) failed (%s).",
25805696Snw141292 			    me, name, errnum ? strerror(errnum) : "not found");
25814520Snw141292 			if (errnum == 0)
25824520Snw141292 				return (IDMAP_ERR_NOTFOUND);
25834520Snw141292 			else
25844520Snw141292 				return (IDMAP_ERR_INTERNAL);
25854520Snw141292 		}
25865731Sbaban 		id->idmap_id_u.gid = grp.gr_gid;
25875731Sbaban 		break;
25885731Sbaban 	default:
25895731Sbaban 		return (IDMAP_ERR_ARG);
25904520Snw141292 	}
25914520Snw141292 	return (IDMAP_SUCCESS);
25924520Snw141292 }
25934520Snw141292 
25945731Sbaban 
25955731Sbaban /*
25965731Sbaban  * Name service lookup by pid to get unixname
25975731Sbaban  */
25985731Sbaban static
25995731Sbaban idmap_retcode
26005731Sbaban ns_lookup_bypid(uid_t pid, int is_user, char **unixname)
26015731Sbaban {
26025731Sbaban 	struct passwd	pwd;
26035731Sbaban 	struct group	grp;
26045731Sbaban 	char		buf[1024];
26055731Sbaban 	int		errnum;
26065731Sbaban 	const char	*me = "ns_lookup_bypid";
26075731Sbaban 
26085731Sbaban 	if (is_user) {
26095731Sbaban 		errno = 0;
26105731Sbaban 		if (getpwuid_r(pid, &pwd, buf, sizeof (buf)) == NULL) {
26115731Sbaban 			errnum = errno;
26125731Sbaban 			idmapdlog(LOG_WARNING,
26135731Sbaban 			    "%s: getpwuid_r(%u) failed (%s).",
26145731Sbaban 			    me, pid, errnum ? strerror(errnum) : "not found");
26155731Sbaban 			if (errnum == 0)
26165731Sbaban 				return (IDMAP_ERR_NOTFOUND);
26175731Sbaban 			else
26185731Sbaban 				return (IDMAP_ERR_INTERNAL);
26195731Sbaban 		}
26205731Sbaban 		*unixname = strdup(pwd.pw_name);
26215731Sbaban 	} else {
26225731Sbaban 		errno = 0;
26235731Sbaban 		if (getgrgid_r(pid, &grp, buf, sizeof (buf)) == NULL) {
26245731Sbaban 			errnum = errno;
26255731Sbaban 			idmapdlog(LOG_WARNING,
26265731Sbaban 			    "%s: getgrgid_r(%u) failed (%s).",
26275731Sbaban 			    me, pid, errnum ? strerror(errnum) : "not found");
26285731Sbaban 			if (errnum == 0)
26295731Sbaban 				return (IDMAP_ERR_NOTFOUND);
26305731Sbaban 			else
26315731Sbaban 				return (IDMAP_ERR_INTERNAL);
26325731Sbaban 		}
26335731Sbaban 		*unixname = strdup(grp.gr_name);
26345731Sbaban 	}
26355731Sbaban 	if (*unixname == NULL)
26365731Sbaban 		return (IDMAP_ERR_MEMORY);
26375731Sbaban 	return (IDMAP_SUCCESS);
26385731Sbaban }
26395731Sbaban 
26404520Snw141292 /*
26414520Snw141292  * Name-based mapping
26424520Snw141292  *
26434520Snw141292  * Case 1: If no rule matches do ephemeral
26444520Snw141292  *
26454520Snw141292  * Case 2: If rule matches and unixname is "" then return no mapping.
26464520Snw141292  *
26474520Snw141292  * Case 3: If rule matches and unixname is specified then lookup name
26484520Snw141292  *  service using the unixname. If unixname not found then return no mapping.
26494520Snw141292  *
26504520Snw141292  * Case 4: If rule matches and unixname is * then lookup name service
26514520Snw141292  *  using winname as the unixname. If unixname not found then process
26524520Snw141292  *  other rules using the lookup order. If no other rule matches then do
26534520Snw141292  *  ephemeral. Otherwise, based on the matched rule do Case 2 or 3 or 4.
26544520Snw141292  *  This allows us to specify a fallback unixname per _domain_ or no mapping
26554520Snw141292  *  instead of the default behaviour of doing ephemeral mapping.
26564520Snw141292  *
26574520Snw141292  * Example 1:
26584520Snw141292  * *@sfbay == *
26594520Snw141292  * If looking up windows users foo@sfbay and foo does not exists in
26604520Snw141292  * the name service then foo@sfbay will be mapped to an ephemeral id.
26614520Snw141292  *
26624520Snw141292  * Example 2:
26634520Snw141292  * *@sfbay == *
26644520Snw141292  * *@sfbay => guest
26654520Snw141292  * If looking up windows users foo@sfbay and foo does not exists in
26664520Snw141292  * the name service then foo@sfbay will be mapped to guest.
26674520Snw141292  *
26684520Snw141292  * Example 3:
26694520Snw141292  * *@sfbay == *
26704520Snw141292  * *@sfbay => ""
26714520Snw141292  * If looking up windows users foo@sfbay and foo does not exists in
26724520Snw141292  * the name service then we will return no mapping for foo@sfbay.
26734520Snw141292  *
26744520Snw141292  */
26755696Snw141292 static
26765696Snw141292 idmap_retcode
26776616Sdm199847 name_based_mapping_sid2pid(lookup_state_t *state,
26786616Sdm199847 		idmap_mapping *req, idmap_id_res *res)
26795696Snw141292 {
26805696Snw141292 	const char	*unixname, *windomain;
26815696Snw141292 	char		*sql = NULL, *errmsg = NULL, *lower_winname = NULL;
26824520Snw141292 	idmap_retcode	retcode;
26835696Snw141292 	char		*end, *lower_unixname, *winname;
26844520Snw141292 	const char	**values;
26854520Snw141292 	sqlite_vm	*vm = NULL;
26865696Snw141292 	int		ncol, r, i, is_user, is_wuser;
26876386Sjp151216 	idmap_namerule	*rule = &res->info.how.idmap_how_u.rule;
26886386Sjp151216 	int		direction;
26894520Snw141292 	const char	*me = "name_based_mapping_sid2pid";
26904520Snw141292 
26915731Sbaban 	assert(req->id1name != NULL); /* We have winname */
26925731Sbaban 	assert(req->id2name == NULL); /* We don't have unixname */
26935731Sbaban 
26945064Sdm199847 	winname = req->id1name;
26955064Sdm199847 	windomain = req->id1domain;
26965696Snw141292 
26975696Snw141292 	switch (req->id1.idtype) {
26985696Snw141292 	case IDMAP_USID:
26995696Snw141292 		is_wuser = 1;
27005696Snw141292 		break;
27015696Snw141292 	case IDMAP_GSID:
27025696Snw141292 		is_wuser = 0;
27035696Snw141292 		break;
27045696Snw141292 	default:
27055731Sbaban 		idmapdlog(LOG_ERR, "%s: Unable to determine if the "
27065731Sbaban 		    "given Windows id is user or group.", me);
27075696Snw141292 		return (IDMAP_ERR_INTERNAL);
27085696Snw141292 	}
27095696Snw141292 
27105731Sbaban 	switch (res->id.idtype) {
27115696Snw141292 	case IDMAP_UID:
27125696Snw141292 		is_user = 1;
27135696Snw141292 		break;
27145696Snw141292 	case IDMAP_GID:
27155696Snw141292 		is_user = 0;
27165696Snw141292 		break;
27175696Snw141292 	case IDMAP_POSIXID:
27185696Snw141292 		is_user = is_wuser;
27195696Snw141292 		res->id.idtype = is_user ? IDMAP_UID : IDMAP_GID;
27205696Snw141292 		break;
27215696Snw141292 	}
27224520Snw141292 
27234520Snw141292 	i = 0;
27246616Sdm199847 	if (windomain == NULL)
27254864Sbaban 		windomain = "";
27266950Sbaban 	else if (state->defdom != NULL &&
27276950Sbaban 	    strcasecmp(state->defdom, windomain) == 0)
27286616Sdm199847 		i = 1;
27294520Snw141292 
27305696Snw141292 	if ((lower_winname = tolower_u8(winname)) == NULL)
27315696Snw141292 		lower_winname = winname;    /* hope for the best */
27324520Snw141292 	sql = sqlite_mprintf(
27336386Sjp151216 	    "SELECT unixname, u2w_order, winname_display, windomain, is_nt4 "
27346386Sjp151216 	    "FROM namerules WHERE "
27355696Snw141292 	    "w2u_order > 0 AND is_user = %d AND is_wuser = %d AND "
27365696Snw141292 	    "(winname = %Q OR winname = '*') AND "
27375696Snw141292 	    "(windomain = %Q OR windomain = '*' %s) "
27385696Snw141292 	    "ORDER BY w2u_order ASC;",
27395696Snw141292 	    is_user, is_wuser, lower_winname, windomain,
27405696Snw141292 	    i ? "OR windomain ISNULL OR windomain = ''" : "");
27414520Snw141292 	if (sql == NULL) {
27424520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
27434520Snw141292 		retcode = IDMAP_ERR_MEMORY;
27444520Snw141292 		goto out;
27454520Snw141292 	}
27464520Snw141292 
27476616Sdm199847 	if (sqlite_compile(state->db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
27484520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
27495696Snw141292 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
27505696Snw141292 		    CHECK_NULL(errmsg));
27514520Snw141292 		sqlite_freemem(errmsg);
27524520Snw141292 		goto out;
27534520Snw141292 	}
27544520Snw141292 
27556386Sjp151216 	for (;;) {
27564520Snw141292 		r = sqlite_step(vm, &ncol, &values, NULL);
27574884Sjp151216 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
27584884Sjp151216 
27594884Sjp151216 		if (r == SQLITE_ROW) {
27606386Sjp151216 			if (ncol < 5) {
27614520Snw141292 				retcode = IDMAP_ERR_INTERNAL;
27624520Snw141292 				goto out;
27634520Snw141292 			}
27644520Snw141292 			if (values[0] == NULL) {
27654520Snw141292 				retcode = IDMAP_ERR_INTERNAL;
27664520Snw141292 				goto out;
27674520Snw141292 			}
27684520Snw141292 
27696386Sjp151216 			if (values[1] != NULL)
27706386Sjp151216 				direction =
27716386Sjp151216 				    (strtol(values[1], &end, 10) == 0)?
27726386Sjp151216 				    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
27736386Sjp151216 			else
27746386Sjp151216 				direction = IDMAP_DIRECTION_W2U;
27756386Sjp151216 
27764520Snw141292 			if (EMPTY_NAME(values[0])) {
27776386Sjp151216 				idmap_namerule_set(rule, values[3], values[2],
27786386Sjp151216 				    values[0], is_wuser, is_user,
27796386Sjp151216 				    strtol(values[4], &end, 10),
27806386Sjp151216 				    direction);
27814520Snw141292 				retcode = IDMAP_ERR_NOMAPPING;
27824520Snw141292 				goto out;
27834520Snw141292 			}
27846386Sjp151216 
27856386Sjp151216 			if (values[0][0] == '*') {
27866386Sjp151216 				unixname = winname;
27876386Sjp151216 				lower_unixname = lower_winname;
27886386Sjp151216 			} else {
27896386Sjp151216 				unixname = values[0];
27906386Sjp151216 				lower_unixname = NULL;
27916386Sjp151216 			}
27926386Sjp151216 
27935731Sbaban 			retcode = ns_lookup_byname(unixname, lower_unixname,
27945731Sbaban 			    &res->id);
27954520Snw141292 			if (retcode == IDMAP_ERR_NOTFOUND) {
27966386Sjp151216 				if (values[0][0] == '*')
27974520Snw141292 					/* Case 4 */
27984520Snw141292 					continue;
27996386Sjp151216 				else {
28004520Snw141292 					/* Case 3 */
28016386Sjp151216 					idmap_namerule_set(rule, values[3],
28026386Sjp151216 					    values[2], values[0], is_wuser,
28036386Sjp151216 					    is_user,
28046386Sjp151216 					    strtol(values[4], &end, 10),
28056386Sjp151216 					    direction);
28064520Snw141292 					retcode = IDMAP_ERR_NOMAPPING;
28076386Sjp151216 				}
28084520Snw141292 			}
28094520Snw141292 			goto out;
28104520Snw141292 		} else if (r == SQLITE_DONE) {
28114520Snw141292 			retcode = IDMAP_ERR_NOTFOUND;
28124520Snw141292 			goto out;
28134520Snw141292 		} else {
28144520Snw141292 			(void) sqlite_finalize(vm, &errmsg);
28154520Snw141292 			vm = NULL;
28165696Snw141292 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
28175696Snw141292 			    CHECK_NULL(errmsg));
28184520Snw141292 			sqlite_freemem(errmsg);
28194520Snw141292 			retcode = IDMAP_ERR_INTERNAL;
28204520Snw141292 			goto out;
28214520Snw141292 		}
28224520Snw141292 	}
28234520Snw141292 
28244520Snw141292 out:
28256386Sjp151216 	if (sql != NULL)
28266386Sjp151216 		sqlite_freemem(sql);
28276386Sjp151216 	res->info.how.map_type = IDMAP_MAP_TYPE_RULE_BASED;
28284520Snw141292 	if (retcode == IDMAP_SUCCESS) {
28294864Sbaban 		if (values[1] != NULL)
28304520Snw141292 			res->direction =
28314644Sbaban 			    (strtol(values[1], &end, 10) == 0)?
28324644Sbaban 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
28334520Snw141292 		else
28344644Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
28356386Sjp151216 
28365064Sdm199847 		req->id2name = strdup(unixname);
28376616Sdm199847 		if (req->id2name == NULL) {
28386616Sdm199847 			retcode = IDMAP_ERR_MEMORY;
28396616Sdm199847 		}
28406616Sdm199847 	}
28416616Sdm199847 
28426616Sdm199847 	if (retcode == IDMAP_SUCCESS) {
28436386Sjp151216 		idmap_namerule_set(rule, values[3], values[2],
28446386Sjp151216 		    values[0], is_wuser, is_user, strtol(values[4], &end, 10),
28456386Sjp151216 		    res->direction);
28466386Sjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
28474520Snw141292 	}
28486616Sdm199847 
28495696Snw141292 	if (lower_winname != NULL && lower_winname != winname)
28505696Snw141292 		free(lower_winname);
28514864Sbaban 	if (vm != NULL)
28524520Snw141292 		(void) sqlite_finalize(vm, NULL);
28534520Snw141292 	return (retcode);
28544520Snw141292 }
28554520Snw141292 
28564520Snw141292 static
28574520Snw141292 int
28584520Snw141292 get_next_eph_uid(uid_t *next_uid)
28594520Snw141292 {
28604520Snw141292 	uid_t uid;
28614520Snw141292 	gid_t gid;
28624520Snw141292 	int err;
28634520Snw141292 
28644520Snw141292 	*next_uid = (uid_t)-1;
28654520Snw141292 	uid = _idmapdstate.next_uid++;
28664520Snw141292 	if (uid >= _idmapdstate.limit_uid) {
28674520Snw141292 		if ((err = allocids(0, 8192, &uid, 0, &gid)) != 0)
28684520Snw141292 			return (err);
28694520Snw141292 
28704520Snw141292 		_idmapdstate.limit_uid = uid + 8192;
28714520Snw141292 		_idmapdstate.next_uid = uid;
28724520Snw141292 	}
28734520Snw141292 	*next_uid = uid;
28744520Snw141292 
28754520Snw141292 	return (0);
28764520Snw141292 }
28774520Snw141292 
28784520Snw141292 static
28794520Snw141292 int
28804520Snw141292 get_next_eph_gid(gid_t *next_gid)
28814520Snw141292 {
28824520Snw141292 	uid_t uid;
28834520Snw141292 	gid_t gid;
28844520Snw141292 	int err;
28854520Snw141292 
28864520Snw141292 	*next_gid = (uid_t)-1;
28874520Snw141292 	gid = _idmapdstate.next_gid++;
28884520Snw141292 	if (gid >= _idmapdstate.limit_gid) {
28894520Snw141292 		if ((err = allocids(0, 0, &uid, 8192, &gid)) != 0)
28904520Snw141292 			return (err);
28914520Snw141292 
28924520Snw141292 		_idmapdstate.limit_gid = gid + 8192;
28934520Snw141292 		_idmapdstate.next_gid = gid;
28944520Snw141292 	}
28954520Snw141292 	*next_gid = gid;
28964520Snw141292 
28974520Snw141292 	return (0);
28984520Snw141292 }
28994520Snw141292 
29004864Sbaban static
29014864Sbaban int
29025696Snw141292 gethash(const char *str, uint32_t num, uint_t htsize)
29035696Snw141292 {
29044864Sbaban 	uint_t  hval, i, len;
29054864Sbaban 
29064864Sbaban 	if (str == NULL)
29074864Sbaban 		return (0);
29084864Sbaban 	for (len = strlen(str), hval = 0, i = 0; i < len; i++) {
29094864Sbaban 		hval += str[i];
29104864Sbaban 		hval += (hval << 10);
29114864Sbaban 		hval ^= (hval >> 6);
29124864Sbaban 	}
29134864Sbaban 	for (str = (const char *)&num, i = 0; i < sizeof (num); i++) {
29144864Sbaban 		hval += str[i];
29154864Sbaban 		hval += (hval << 10);
29164864Sbaban 		hval ^= (hval >> 6);
29174864Sbaban 	}
29184864Sbaban 	hval += (hval << 3);
29194864Sbaban 	hval ^= (hval >> 11);
29204864Sbaban 	hval += (hval << 15);
29214864Sbaban 	return (hval % htsize);
29224864Sbaban }
29234864Sbaban 
29244864Sbaban static
29254864Sbaban int
29264864Sbaban get_from_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid,
29275696Snw141292 		uid_t *pid)
29285696Snw141292 {
29294864Sbaban 	uint_t		next, key;
29304864Sbaban 	uint_t		htsize = state->sid_history_size;
29314864Sbaban 	idmap_sid	*sid;
29324864Sbaban 
29334864Sbaban 	next = gethash(prefix, rid, htsize);
29344864Sbaban 	while (next != htsize) {
29354864Sbaban 		key = state->sid_history[next].key;
29364864Sbaban 		if (key == htsize)
29374864Sbaban 			return (0);
29384864Sbaban 		sid = &state->batch->idmap_mapping_batch_val[key].id1.
29394864Sbaban 		    idmap_id_u.sid;
29404864Sbaban 		if (sid->rid == rid && strcmp(sid->prefix, prefix) == 0) {
29414864Sbaban 			*pid = state->result->ids.ids_val[key].id.
29424864Sbaban 			    idmap_id_u.uid;
29434864Sbaban 			return (1);
29444864Sbaban 		}
29454864Sbaban 		next = state->sid_history[next].next;
29464864Sbaban 	}
29474864Sbaban 	return (0);
29484864Sbaban }
29494864Sbaban 
29504864Sbaban static
29514864Sbaban void
29525696Snw141292 add_to_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid)
29535696Snw141292 {
29544864Sbaban 	uint_t		hash, next;
29554864Sbaban 	uint_t		htsize = state->sid_history_size;
29564864Sbaban 
29574864Sbaban 	hash = next = gethash(prefix, rid, htsize);
29584864Sbaban 	while (state->sid_history[next].key != htsize) {
29594864Sbaban 		next++;
29604864Sbaban 		next %= htsize;
29614864Sbaban 	}
29624864Sbaban 	state->sid_history[next].key = state->curpos;
29634864Sbaban 	if (hash == next)
29644864Sbaban 		return;
29654864Sbaban 	state->sid_history[next].next = state->sid_history[hash].next;
29664864Sbaban 	state->sid_history[hash].next = next;
29674864Sbaban }
29684520Snw141292 
29695731Sbaban void
29705731Sbaban cleanup_lookup_state(lookup_state_t *state)
29715731Sbaban {
29725731Sbaban 	free(state->sid_history);
29735731Sbaban 	free(state->ad_unixuser_attr);
29745731Sbaban 	free(state->ad_unixgroup_attr);
29756616Sdm199847 	free(state->nldap_winname_attr);
29766616Sdm199847 	free(state->defdom);
29775731Sbaban }
29785731Sbaban 
29794520Snw141292 /* ARGSUSED */
29804520Snw141292 static
29814520Snw141292 idmap_retcode
29826616Sdm199847 dynamic_ephemeral_mapping(lookup_state_t *state,
29835696Snw141292 		idmap_mapping *req, idmap_id_res *res)
29845696Snw141292 {
29854520Snw141292 
29864520Snw141292 	uid_t		next_pid;
29874520Snw141292 
29884864Sbaban 	res->direction = IDMAP_DIRECTION_BI;
29894864Sbaban 
29906386Sjp151216 	if (IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
29916386Sjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
29926386Sjp151216 		res->info.src = IDMAP_MAP_SRC_CACHE;
29934864Sbaban 		return (IDMAP_SUCCESS);
29946386Sjp151216 	}
29954864Sbaban 
29964864Sbaban 	if (state->sid_history != NULL &&
29974864Sbaban 	    get_from_sid_history(state, req->id1.idmap_id_u.sid.prefix,
29984864Sbaban 	    req->id1.idmap_id_u.sid.rid, &next_pid)) {
29994864Sbaban 		res->id.idmap_id_u.uid = next_pid;
30006386Sjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
30016386Sjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
30024864Sbaban 		return (IDMAP_SUCCESS);
30034864Sbaban 	}
30044864Sbaban 
30054864Sbaban 	if (res->id.idtype == IDMAP_UID) {
30064520Snw141292 		if (get_next_eph_uid(&next_pid) != 0)
30074520Snw141292 			return (IDMAP_ERR_INTERNAL);
30084520Snw141292 		res->id.idmap_id_u.uid = next_pid;
30094520Snw141292 	} else {
30104520Snw141292 		if (get_next_eph_gid(&next_pid) != 0)
30114520Snw141292 			return (IDMAP_ERR_INTERNAL);
30124520Snw141292 		res->id.idmap_id_u.gid = next_pid;
30134520Snw141292 	}
30144520Snw141292 
30156386Sjp151216 	res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
30166386Sjp151216 	res->info.src = IDMAP_MAP_SRC_NEW;
30174864Sbaban 	if (state->sid_history != NULL)
30184864Sbaban 		add_to_sid_history(state, req->id1.idmap_id_u.sid.prefix,
30194864Sbaban 		    req->id1.idmap_id_u.sid.rid);
30204864Sbaban 
30214520Snw141292 	return (IDMAP_SUCCESS);
30224520Snw141292 }
30234520Snw141292 
30244520Snw141292 idmap_retcode
30256616Sdm199847 sid2pid_second_pass(lookup_state_t *state,
30265696Snw141292 		idmap_mapping *req, idmap_id_res *res)
30275696Snw141292 {
30284520Snw141292 	idmap_retcode	retcode;
30294520Snw141292 
30304520Snw141292 	/* Check if second pass is needed */
30315731Sbaban 	if (ARE_WE_DONE(req->direction))
30324520Snw141292 		return (res->retcode);
30334520Snw141292 
30344520Snw141292 	/* Get status from previous pass */
30355731Sbaban 	retcode = res->retcode;
30367031Snw141292 	if (retcode != IDMAP_SUCCESS && state->eph_map_unres_sids &&
30377031Snw141292 	    !EMPTY_STRING(req->id1.idmap_id_u.sid.prefix) &&
30387031Snw141292 	    EMPTY_STRING(req->id1name)) {
30397031Snw141292 		/*
30407031Snw141292 		 * We are asked to map an unresolvable SID to a UID or
30417031Snw141292 		 * GID, but, which?  We'll treat all unresolvable SIDs
30427031Snw141292 		 * as users unless the caller specified which of a UID
30437031Snw141292 		 * or GID they want.
30447031Snw141292 		 */
30457818SNicolas.Williams@Sun.COM 		if (req->id1.idtype == IDMAP_SID)
30467818SNicolas.Williams@Sun.COM 			req->id1.idtype = IDMAP_USID;
30477031Snw141292 		if (res->id.idtype == IDMAP_POSIXID)
30487031Snw141292 			res->id.idtype = IDMAP_UID;
30497031Snw141292 		goto do_eph;
30507031Snw141292 	}
30515731Sbaban 	if (retcode != IDMAP_SUCCESS)
30525731Sbaban 		goto out;
30535731Sbaban 
30545731Sbaban 	/*
30555731Sbaban 	 * If directory-based name mapping is enabled then the unixname
30565731Sbaban 	 * may already have been retrieved from the AD object (AD-mode or
30575731Sbaban 	 * mixed-mode) or from native LDAP object (nldap-mode) -- done.
30585731Sbaban 	 */
30595731Sbaban 	if (req->id2name != NULL) {
30605731Sbaban 		assert(res->id.idtype != IDMAP_POSIXID);
30615731Sbaban 		if (AD_MODE(res->id.idtype, state))
30625731Sbaban 			res->direction = IDMAP_DIRECTION_BI;
30635731Sbaban 		else if (NLDAP_MODE(res->id.idtype, state))
30645731Sbaban 			res->direction = IDMAP_DIRECTION_BI;
30655731Sbaban 		else if (MIXED_MODE(res->id.idtype, state))
30665731Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
30675731Sbaban 
30685731Sbaban 		/*
30695731Sbaban 		 * Special case: (1) If the ad_unixuser_attr and
30705731Sbaban 		 * ad_unixgroup_attr uses the same attribute
30715731Sbaban 		 * name and (2) if this is a diagonal mapping
30725731Sbaban 		 * request and (3) the unixname has been retrieved
30735731Sbaban 		 * from the AD object -- then we ignore it and fallback
30745731Sbaban 		 * to name-based mapping rules and ephemeral mapping
30755731Sbaban 		 *
30765731Sbaban 		 * Example:
30775731Sbaban 		 *  Properties:
30785731Sbaban 		 *    config/ad_unixuser_attr = "unixname"
30795731Sbaban 		 *    config/ad_unixgroup_attr = "unixname"
30805731Sbaban 		 *  AD user object:
30815731Sbaban 		 *    dn: cn=bob ...
30825731Sbaban 		 *    objectclass: user
30835731Sbaban 		 *    sam: bob
30845731Sbaban 		 *    unixname: bob1234
30855731Sbaban 		 *  AD group object:
30865731Sbaban 		 *    dn: cn=winadmins ...
30875731Sbaban 		 *    objectclass: group
30885731Sbaban 		 *    sam: winadmins
30895731Sbaban 		 *    unixname: unixadmins
30905731Sbaban 		 *
30915731Sbaban 		 *  In this example whether "unixname" refers to a unixuser
30925731Sbaban 		 *  or unixgroup depends upon the AD object.
30935731Sbaban 		 *
30945731Sbaban 		 * $idmap show -c winname:bob gid
30955731Sbaban 		 *    AD lookup by "samAccountName=bob" for
30965731Sbaban 		 *    "ad_unixgroup_attr (i.e unixname)" for directory-based
30975731Sbaban 		 *    mapping would get "bob1234" which is not what we want.
30985731Sbaban 		 *    Now why not getgrnam_r("bob1234") and use it if it
30995731Sbaban 		 *    is indeed a unixgroup? That's because Unix can have
31005731Sbaban 		 *    users and groups with the same name and we clearly
31015731Sbaban 		 *    don't know the intention of the admin here.
31025731Sbaban 		 *    Therefore we ignore this and fallback to name-based
31035731Sbaban 		 *    mapping rules or ephemeral mapping.
31045731Sbaban 		 */
31055731Sbaban 		if ((AD_MODE(res->id.idtype, state) ||
31065731Sbaban 		    MIXED_MODE(res->id.idtype, state)) &&
31075731Sbaban 		    state->ad_unixuser_attr != NULL &&
31085731Sbaban 		    state->ad_unixgroup_attr != NULL &&
31095731Sbaban 		    strcasecmp(state->ad_unixuser_attr,
31105731Sbaban 		    state->ad_unixgroup_attr) == 0 &&
31115731Sbaban 		    ((req->id1.idtype == IDMAP_USID &&
31125731Sbaban 		    res->id.idtype == IDMAP_GID) ||
31135731Sbaban 		    (req->id1.idtype == IDMAP_GSID &&
31145731Sbaban 		    res->id.idtype == IDMAP_UID))) {
31155731Sbaban 			free(req->id2name);
31165731Sbaban 			req->id2name = NULL;
31175731Sbaban 			res->id.idmap_id_u.uid = SENTINEL_PID;
31185731Sbaban 			/* fallback */
31195731Sbaban 		} else {
31205731Sbaban 			if (res->id.idmap_id_u.uid == SENTINEL_PID)
31215731Sbaban 				retcode = ns_lookup_byname(req->id2name,
31225731Sbaban 				    NULL, &res->id);
31235731Sbaban 			/*
31246616Sdm199847 			 * If ns_lookup_byname() fails that means the
31256616Sdm199847 			 * unixname (req->id2name), which was obtained
31266616Sdm199847 			 * from the AD object by directory-based mapping,
31276616Sdm199847 			 * is not a valid Unix user/group and therefore
31286616Sdm199847 			 * we return the error to the client instead of
31296616Sdm199847 			 * doing rule-based mapping or ephemeral mapping.
31306616Sdm199847 			 * This way the client can detect the issue.
31315731Sbaban 			 */
31325731Sbaban 			goto out;
31334520Snw141292 		}
31344520Snw141292 	}
31354520Snw141292 
31366386Sjp151216 	/* Free any mapping info from Directory based mapping */
31376386Sjp151216 	if (res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN)
31386386Sjp151216 		idmap_info_free(&res->info);
31396386Sjp151216 
31405731Sbaban 	/*
31415731Sbaban 	 * If we don't have unixname then evaluate local name-based
31425731Sbaban 	 * mapping rules.
31435731Sbaban 	 */
31446616Sdm199847 	retcode = name_based_mapping_sid2pid(state, req, res);
31455731Sbaban 	if (retcode != IDMAP_ERR_NOTFOUND)
31464520Snw141292 		goto out;
31474520Snw141292 
31487031Snw141292 do_eph:
31495731Sbaban 	/* If not found, do ephemeral mapping */
31506616Sdm199847 	retcode = dynamic_ephemeral_mapping(state, req, res);
31514520Snw141292 
31524520Snw141292 out:
31534520Snw141292 	res->retcode = idmap_stat4prot(retcode);
31545731Sbaban 	if (res->retcode != IDMAP_SUCCESS) {
31555731Sbaban 		req->direction = _IDMAP_F_DONE;
31565731Sbaban 		res->id.idmap_id_u.uid = UID_NOBODY;
31575731Sbaban 	}
31585731Sbaban 	if (!ARE_WE_DONE(req->direction))
31595731Sbaban 		state->sid2pid_done = FALSE;
31604520Snw141292 	return (retcode);
31614520Snw141292 }
31624520Snw141292 
31634520Snw141292 idmap_retcode
31646616Sdm199847 update_cache_pid2sid(lookup_state_t *state,
31655696Snw141292 		idmap_mapping *req, idmap_id_res *res)
31665696Snw141292 {
31674520Snw141292 	char		*sql = NULL;
31684520Snw141292 	idmap_retcode	retcode;
31696386Sjp151216 	char		*map_dn = NULL;
31706386Sjp151216 	char		*map_attr = NULL;
31716386Sjp151216 	char		*map_value = NULL;
31726386Sjp151216 	char 		*map_windomain = NULL;
31736386Sjp151216 	char		*map_winname = NULL;
31746386Sjp151216 	char		*map_unixname = NULL;
31756386Sjp151216 	int		map_is_nt4 = FALSE;
31764520Snw141292 
31774520Snw141292 	/* Check if we need to cache anything */
31785731Sbaban 	if (ARE_WE_DONE(req->direction))
31794520Snw141292 		return (IDMAP_SUCCESS);
31804520Snw141292 
31814520Snw141292 	/* We don't cache negative entries */
31824520Snw141292 	if (res->retcode != IDMAP_SUCCESS)
31834520Snw141292 		return (IDMAP_SUCCESS);
31844520Snw141292 
31855731Sbaban 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
31866386Sjp151216 	assert(req->id1.idmap_id_u.uid != SENTINEL_PID);
31876386Sjp151216 	assert(res->id.idtype != IDMAP_SID);
31886386Sjp151216 
31896386Sjp151216 	assert(res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN);
31906386Sjp151216 	switch (res->info.how.map_type) {
31916386Sjp151216 	case IDMAP_MAP_TYPE_DS_AD:
31926386Sjp151216 		map_dn = res->info.how.idmap_how_u.ad.dn;
31936386Sjp151216 		map_attr = res->info.how.idmap_how_u.ad.attr;
31946386Sjp151216 		map_value = res->info.how.idmap_how_u.ad.value;
31956386Sjp151216 		break;
31966386Sjp151216 
31976386Sjp151216 	case IDMAP_MAP_TYPE_DS_NLDAP:
31986386Sjp151216 		map_dn = res->info.how.idmap_how_u.nldap.dn;
31996386Sjp151216 		map_attr = res->info.how.idmap_how_u.nldap.attr;
32006386Sjp151216 		map_value = res->info.how.idmap_how_u.nldap.value;
32016386Sjp151216 		break;
32026386Sjp151216 
32036386Sjp151216 	case IDMAP_MAP_TYPE_RULE_BASED:
32046386Sjp151216 		map_windomain = res->info.how.idmap_how_u.rule.windomain;
32056386Sjp151216 		map_winname = res->info.how.idmap_how_u.rule.winname;
32066386Sjp151216 		map_unixname = res->info.how.idmap_how_u.rule.unixname;
32076386Sjp151216 		map_is_nt4 = res->info.how.idmap_how_u.rule.is_nt4;
32086386Sjp151216 		break;
32096386Sjp151216 
32106386Sjp151216 	case IDMAP_MAP_TYPE_EPHEMERAL:
32116386Sjp151216 		break;
32126386Sjp151216 
32136386Sjp151216 	case IDMAP_MAP_TYPE_LOCAL_SID:
32146386Sjp151216 		break;
32156386Sjp151216 
32166386Sjp151216 	default:
32176386Sjp151216 		/* Dont cache other mapping types */
32186386Sjp151216 		assert(FALSE);
32196386Sjp151216 	}
32205731Sbaban 
32214520Snw141292 	/*
32224520Snw141292 	 * Using NULL for u2w instead of 0 so that our trigger allows
32234520Snw141292 	 * the same pid to be the destination in multiple entries
32244520Snw141292 	 */
32254520Snw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
32265696Snw141292 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
32276386Sjp151216 	    "is_user, is_wuser, expiration, w2u, u2w, "
32286386Sjp151216 	    "map_type, map_dn, map_attr, map_value, map_windomain, "
32296386Sjp151216 	    "map_winname, map_unixname, map_is_nt4) "
32305696Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
32316386Sjp151216 	    "strftime('%%s','now') + 600, %q, 1, "
32326386Sjp151216 	    "%d, %Q, %Q, %Q, %Q, %Q, %Q, %d); ",
32335696Snw141292 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
32345696Snw141292 	    req->id2domain, req->id2name, req->id1.idmap_id_u.uid,
32355696Snw141292 	    req->id1name, (req->id1.idtype == IDMAP_UID) ? 1 : 0,
32365731Sbaban 	    (res->id.idtype == IDMAP_USID) ? 1 : 0,
32376386Sjp151216 	    (res->direction == 0) ? "1" : NULL,
32386386Sjp151216 	    res->info.how.map_type, map_dn, map_attr, map_value,
32396386Sjp151216 	    map_windomain, map_winname, map_unixname, map_is_nt4);
32404520Snw141292 
32414520Snw141292 	if (sql == NULL) {
32424520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
32434520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
32444520Snw141292 		goto out;
32454520Snw141292 	}
32464520Snw141292 
32476616Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
32484520Snw141292 	if (retcode != IDMAP_SUCCESS)
32494520Snw141292 		goto out;
32504520Snw141292 
32514520Snw141292 	state->pid2sid_done = FALSE;
32524520Snw141292 	sqlite_freemem(sql);
32534520Snw141292 	sql = NULL;
32544520Snw141292 
32555731Sbaban 	/* Check if we need to update namecache */
32565731Sbaban 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
32574520Snw141292 		goto out;
32584520Snw141292 
32595064Sdm199847 	if (req->id2name == NULL)
32604520Snw141292 		goto out;
32614520Snw141292 
32624520Snw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
32635696Snw141292 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
32645696Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
32655696Snw141292 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
32665696Snw141292 	    req->id2name, req->id2domain,
32675731Sbaban 	    (res->id.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
32684520Snw141292 
32694520Snw141292 	if (sql == NULL) {
32704520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
32714520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
32724520Snw141292 		goto out;
32734520Snw141292 	}
32744520Snw141292 
32756616Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
32764520Snw141292 
32774520Snw141292 out:
32786386Sjp151216 	if (!(req->flag & IDMAP_REQ_FLG_MAPPING_INFO))
32796386Sjp151216 		idmap_info_free(&res->info);
32804864Sbaban 	if (sql != NULL)
32814520Snw141292 		sqlite_freemem(sql);
32824520Snw141292 	return (retcode);
32834520Snw141292 }
32844520Snw141292 
32854520Snw141292 idmap_retcode
32866616Sdm199847 update_cache_sid2pid(lookup_state_t *state,
32875696Snw141292 		idmap_mapping *req, idmap_id_res *res)
32885696Snw141292 {
32894520Snw141292 	char		*sql = NULL;
32904520Snw141292 	idmap_retcode	retcode;
32914520Snw141292 	int		is_eph_user;
32926386Sjp151216 	char		*map_dn = NULL;
32936386Sjp151216 	char		*map_attr = NULL;
32946386Sjp151216 	char		*map_value = NULL;
32956386Sjp151216 	char 		*map_windomain = NULL;
32966386Sjp151216 	char		*map_winname = NULL;
32976386Sjp151216 	char		*map_unixname = NULL;
32986386Sjp151216 	int		map_is_nt4 = FALSE;
32994520Snw141292 
33004520Snw141292 	/* Check if we need to cache anything */
33015731Sbaban 	if (ARE_WE_DONE(req->direction))
33024520Snw141292 		return (IDMAP_SUCCESS);
33034520Snw141292 
33044520Snw141292 	/* We don't cache negative entries */
33054520Snw141292 	if (res->retcode != IDMAP_SUCCESS)
33064520Snw141292 		return (IDMAP_SUCCESS);
33074520Snw141292 
33084520Snw141292 	if (req->direction & _IDMAP_F_EXP_EPH_UID)
33094520Snw141292 		is_eph_user = 1;
33104520Snw141292 	else if (req->direction & _IDMAP_F_EXP_EPH_GID)
33114520Snw141292 		is_eph_user = 0;
33124520Snw141292 	else
33134520Snw141292 		is_eph_user = -1;
33144520Snw141292 
33154520Snw141292 	if (is_eph_user >= 0 && !IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
33164520Snw141292 		sql = sqlite_mprintf("UPDATE idmap_cache "
33175696Snw141292 		    "SET w2u = 0 WHERE "
33185696Snw141292 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
33195696Snw141292 		    "pid >= 2147483648 AND is_user = %d;",
33205696Snw141292 		    req->id1.idmap_id_u.sid.prefix,
33215696Snw141292 		    req->id1.idmap_id_u.sid.rid,
33225696Snw141292 		    is_eph_user);
33234520Snw141292 		if (sql == NULL) {
33244520Snw141292 			retcode = IDMAP_ERR_INTERNAL;
33254520Snw141292 			idmapdlog(LOG_ERR, "Out of memory");
33264520Snw141292 			goto out;
33274520Snw141292 		}
33284520Snw141292 
33296616Sdm199847 		retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
33304520Snw141292 		if (retcode != IDMAP_SUCCESS)
33314520Snw141292 			goto out;
33324520Snw141292 
33334520Snw141292 		sqlite_freemem(sql);
33344520Snw141292 		sql = NULL;
33354520Snw141292 	}
33364520Snw141292 
33375731Sbaban 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
33386386Sjp151216 	assert(res->id.idmap_id_u.uid != SENTINEL_PID);
33396386Sjp151216 
33406386Sjp151216 	switch (res->info.how.map_type) {
33416386Sjp151216 	case IDMAP_MAP_TYPE_DS_AD:
33426386Sjp151216 		map_dn = res->info.how.idmap_how_u.ad.dn;
33436386Sjp151216 		map_attr = res->info.how.idmap_how_u.ad.attr;
33446386Sjp151216 		map_value = res->info.how.idmap_how_u.ad.value;
33456386Sjp151216 		break;
33466386Sjp151216 
33476386Sjp151216 	case IDMAP_MAP_TYPE_DS_NLDAP:
33486386Sjp151216 		map_dn = res->info.how.idmap_how_u.nldap.dn;
33496386Sjp151216 		map_attr = res->info.how.idmap_how_u.ad.attr;
33506386Sjp151216 		map_value = res->info.how.idmap_how_u.nldap.value;
33516386Sjp151216 		break;
33526386Sjp151216 
33536386Sjp151216 	case IDMAP_MAP_TYPE_RULE_BASED:
33546386Sjp151216 		map_windomain = res->info.how.idmap_how_u.rule.windomain;
33556386Sjp151216 		map_winname = res->info.how.idmap_how_u.rule.winname;
33566386Sjp151216 		map_unixname = res->info.how.idmap_how_u.rule.unixname;
33576386Sjp151216 		map_is_nt4 = res->info.how.idmap_how_u.rule.is_nt4;
33586386Sjp151216 		break;
33596386Sjp151216 
33606386Sjp151216 	case IDMAP_MAP_TYPE_EPHEMERAL:
33616386Sjp151216 		break;
33626386Sjp151216 
33636386Sjp151216 	default:
33646386Sjp151216 		/* Dont cache other mapping types */
33656386Sjp151216 		assert(FALSE);
33666386Sjp151216 	}
33675696Snw141292 
33684520Snw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
33695696Snw141292 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
33706386Sjp151216 	    "is_user, is_wuser, expiration, w2u, u2w, "
33716386Sjp151216 	    "map_type, map_dn, map_attr, map_value, map_windomain, "
33726386Sjp151216 	    "map_winname, map_unixname, map_is_nt4) "
33735696Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
33746386Sjp151216 	    "strftime('%%s','now') + 600, 1, %q, "
33756386Sjp151216 	    "%d, %Q, %Q, %Q, %Q, %Q, %Q, %d);",
33765696Snw141292 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
33775731Sbaban 	    (req->id1domain != NULL) ? req->id1domain : "", req->id1name,
33785731Sbaban 	    res->id.idmap_id_u.uid, req->id2name,
33795731Sbaban 	    (res->id.idtype == IDMAP_UID) ? 1 : 0,
33805696Snw141292 	    (req->id1.idtype == IDMAP_USID) ? 1 : 0,
33816386Sjp151216 	    (res->direction == 0) ? "1" : NULL,
33826386Sjp151216 	    res->info.how.map_type, map_dn, map_attr, map_value,
33836386Sjp151216 	    map_windomain, map_winname, map_unixname, map_is_nt4);
33844520Snw141292 
33854520Snw141292 	if (sql == NULL) {
33864520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
33874520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
33884520Snw141292 		goto out;
33894520Snw141292 	}
33904520Snw141292 
33916616Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
33924520Snw141292 	if (retcode != IDMAP_SUCCESS)
33934520Snw141292 		goto out;
33944520Snw141292 
33954520Snw141292 	state->sid2pid_done = FALSE;
33964520Snw141292 	sqlite_freemem(sql);
33974520Snw141292 	sql = NULL;
33984520Snw141292 
33995731Sbaban 	/* Check if we need to update namecache */
34005731Sbaban 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
34014520Snw141292 		goto out;
34024520Snw141292 
34035127Sdm199847 	if (EMPTY_STRING(req->id1name))
34044520Snw141292 		goto out;
34054520Snw141292 
34064520Snw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
34075696Snw141292 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
34085696Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
34095696Snw141292 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
34105696Snw141292 	    req->id1name, req->id1domain,
34115696Snw141292 	    (req->id1.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
34124520Snw141292 
34134520Snw141292 	if (sql == NULL) {
34144520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
34154520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
34164520Snw141292 		goto out;
34174520Snw141292 	}
34184520Snw141292 
34196616Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
34204520Snw141292 
34214520Snw141292 out:
34226386Sjp151216 	if (!(req->flag & IDMAP_REQ_FLG_MAPPING_INFO))
34236386Sjp151216 		idmap_info_free(&res->info);
34246386Sjp151216 
34254864Sbaban 	if (sql != NULL)
34264520Snw141292 		sqlite_freemem(sql);
34274520Snw141292 	return (retcode);
34284520Snw141292 }
34294520Snw141292 
34305696Snw141292 static
34315696Snw141292 idmap_retcode
34324520Snw141292 lookup_cache_pid2sid(sqlite *cache, idmap_mapping *req, idmap_id_res *res,
34335696Snw141292 		int is_user, int getname)
34345696Snw141292 {
34354520Snw141292 	char		*end;
34364520Snw141292 	char		*sql = NULL;
34374520Snw141292 	const char	**values;
34384520Snw141292 	sqlite_vm	*vm = NULL;
34394520Snw141292 	int		ncol;
34404520Snw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
34414520Snw141292 	time_t		curtime;
34425731Sbaban 	idmap_id_type	idtype;
34434520Snw141292 
34444520Snw141292 	/* Current time */
34454520Snw141292 	errno = 0;
34464520Snw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
34475696Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
34485696Snw141292 		    strerror(errno));
34494520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
34504520Snw141292 		goto out;
34514520Snw141292 	}
34524520Snw141292 
34535731Sbaban 	/* SQL to lookup the cache by pid or by unixname */
34545731Sbaban 	if (req->id1.idmap_id_u.uid != SENTINEL_PID) {
34556386Sjp151216 		sql = sqlite_mprintf("SELECT sidprefix, rid, "
34566386Sjp151216 		    "canon_winname, windomain, w2u, is_wuser, "
34576386Sjp151216 		    "map_type, map_dn, map_attr, map_value, map_windomain, "
34586386Sjp151216 		    "map_winname, map_unixname, map_is_nt4 "
34595731Sbaban 		    "FROM idmap_cache WHERE "
34605731Sbaban 		    "pid = %u AND u2w = 1 AND is_user = %d AND "
34615731Sbaban 		    "(pid >= 2147483648 OR "
34625731Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
34635731Sbaban 		    "expiration > %d));",
34645731Sbaban 		    req->id1.idmap_id_u.uid, is_user, curtime);
34655731Sbaban 	} else if (req->id1name != NULL) {
34666386Sjp151216 		sql = sqlite_mprintf("SELECT sidprefix, rid, "
34676386Sjp151216 		    "canon_winname, windomain, w2u, is_wuser, "
34686386Sjp151216 		    "map_type, map_dn, map_attr, map_value, map_windomain, "
34696386Sjp151216 		    "map_winname, map_unixname, map_is_nt4 "
34705731Sbaban 		    "FROM idmap_cache WHERE "
34715731Sbaban 		    "unixname = %Q AND u2w = 1 AND is_user = %d AND "
34725731Sbaban 		    "(pid >= 2147483648 OR "
34735731Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
34745731Sbaban 		    "expiration > %d));",
34755731Sbaban 		    req->id1name, is_user, curtime);
34766386Sjp151216 	} else {
34776386Sjp151216 		retcode = IDMAP_ERR_ARG;
34786386Sjp151216 		goto out;
34795731Sbaban 	}
34805731Sbaban 
34814520Snw141292 	if (sql == NULL) {
34824520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
34834520Snw141292 		retcode = IDMAP_ERR_MEMORY;
34844520Snw141292 		goto out;
34854520Snw141292 	}
34866386Sjp151216 	retcode = sql_compile_n_step_once(
34876386Sjp151216 	    cache, sql, &vm, &ncol, 14, &values);
34884520Snw141292 	sqlite_freemem(sql);
34894520Snw141292 
34904520Snw141292 	if (retcode == IDMAP_ERR_NOTFOUND)
34914520Snw141292 		goto out;
34924520Snw141292 	else if (retcode == IDMAP_SUCCESS) {
34934520Snw141292 		/* sanity checks */
34944520Snw141292 		if (values[0] == NULL || values[1] == NULL) {
34954520Snw141292 			retcode = IDMAP_ERR_CACHE;
34964520Snw141292 			goto out;
34974520Snw141292 		}
34984520Snw141292 
34995731Sbaban 		switch (res->id.idtype) {
35004520Snw141292 		case IDMAP_SID:
35015696Snw141292 		case IDMAP_USID:
35025696Snw141292 		case IDMAP_GSID:
35035731Sbaban 			idtype = strtol(values[5], &end, 10) == 1
35045696Snw141292 			    ? IDMAP_USID : IDMAP_GSID;
35055696Snw141292 
35065731Sbaban 			if (res->id.idtype == IDMAP_USID &&
35075731Sbaban 			    idtype != IDMAP_USID) {
35085696Snw141292 				retcode = IDMAP_ERR_NOTUSER;
35095696Snw141292 				goto out;
35105731Sbaban 			} else if (res->id.idtype == IDMAP_GSID &&
35115731Sbaban 			    idtype != IDMAP_GSID) {
35125696Snw141292 				retcode = IDMAP_ERR_NOTGROUP;
35135696Snw141292 				goto out;
35145696Snw141292 			}
35155731Sbaban 			res->id.idtype = idtype;
35165696Snw141292 
35174520Snw141292 			res->id.idmap_id_u.sid.rid =
35185696Snw141292 			    strtoul(values[1], &end, 10);
35194520Snw141292 			res->id.idmap_id_u.sid.prefix = strdup(values[0]);
35204520Snw141292 			if (res->id.idmap_id_u.sid.prefix == NULL) {
35214520Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
35224520Snw141292 				retcode = IDMAP_ERR_MEMORY;
35234520Snw141292 				goto out;
35244520Snw141292 			}
35254520Snw141292 
35264864Sbaban 			if (values[4] != NULL)
35274520Snw141292 				res->direction =
35284644Sbaban 				    (strtol(values[4], &end, 10) == 0)?
35294644Sbaban 				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
35304520Snw141292 			else
35314644Sbaban 				res->direction = IDMAP_DIRECTION_U2W;
35324520Snw141292 
35334520Snw141292 			if (getname == 0 || values[2] == NULL)
35344520Snw141292 				break;
35355064Sdm199847 			req->id2name = strdup(values[2]);
35365064Sdm199847 			if (req->id2name == NULL) {
35374520Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
35384520Snw141292 				retcode = IDMAP_ERR_MEMORY;
35394520Snw141292 				goto out;
35404520Snw141292 			}
35414520Snw141292 
35424520Snw141292 			if (values[3] == NULL)
35434520Snw141292 				break;
35445064Sdm199847 			req->id2domain = strdup(values[3]);
35455064Sdm199847 			if (req->id2domain == NULL) {
35464520Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
35474520Snw141292 				retcode = IDMAP_ERR_MEMORY;
35484520Snw141292 				goto out;
35494520Snw141292 			}
35505696Snw141292 
35514520Snw141292 			break;
35524520Snw141292 		default:
35534520Snw141292 			retcode = IDMAP_ERR_NOTSUPPORTED;
35544520Snw141292 			break;
35554520Snw141292 		}
35566386Sjp151216 		if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
35576386Sjp151216 			res->info.src = IDMAP_MAP_SRC_CACHE;
35586386Sjp151216 			res->info.how.map_type = strtoul(values[6], &end, 10);
35596386Sjp151216 			switch (res->info.how.map_type) {
35606386Sjp151216 			case IDMAP_MAP_TYPE_DS_AD:
35616386Sjp151216 				res->info.how.idmap_how_u.ad.dn =
35626386Sjp151216 				    strdup(values[7]);
35636386Sjp151216 				res->info.how.idmap_how_u.ad.attr =
35646386Sjp151216 				    strdup(values[8]);
35656386Sjp151216 				res->info.how.idmap_how_u.ad.value =
35666386Sjp151216 				    strdup(values[9]);
35676386Sjp151216 				break;
35686386Sjp151216 
35696386Sjp151216 			case IDMAP_MAP_TYPE_DS_NLDAP:
35706386Sjp151216 				res->info.how.idmap_how_u.nldap.dn =
35716386Sjp151216 				    strdup(values[7]);
35726386Sjp151216 				res->info.how.idmap_how_u.nldap.attr =
35736386Sjp151216 				    strdup(values[8]);
35746386Sjp151216 				res->info.how.idmap_how_u.nldap.value =
35756386Sjp151216 				    strdup(values[9]);
35766386Sjp151216 				break;
35776386Sjp151216 
35786386Sjp151216 			case IDMAP_MAP_TYPE_RULE_BASED:
35796386Sjp151216 				res->info.how.idmap_how_u.rule.windomain =
35806386Sjp151216 				    strdup(values[10]);
35816386Sjp151216 				res->info.how.idmap_how_u.rule.winname =
35826386Sjp151216 				    strdup(values[11]);
35836386Sjp151216 				res->info.how.idmap_how_u.rule.unixname =
35846386Sjp151216 				    strdup(values[12]);
35856386Sjp151216 				res->info.how.idmap_how_u.rule.is_nt4 =
35866386Sjp151216 				    strtoul(values[13], &end, 10);
35876386Sjp151216 				res->info.how.idmap_how_u.rule.is_user =
35886386Sjp151216 				    is_user;
35896386Sjp151216 				res->info.how.idmap_how_u.rule.is_wuser =
35906386Sjp151216 				    strtol(values[5], &end, 10);
35916386Sjp151216 				break;
35926386Sjp151216 
35936386Sjp151216 			case IDMAP_MAP_TYPE_EPHEMERAL:
35946386Sjp151216 				break;
35956386Sjp151216 
35966386Sjp151216 			case IDMAP_MAP_TYPE_LOCAL_SID:
35976386Sjp151216 				break;
35986386Sjp151216 
35996386Sjp151216 			case IDMAP_MAP_TYPE_KNOWN_SID:
36006386Sjp151216 				break;
36016386Sjp151216 
36026386Sjp151216 			default:
36036386Sjp151216 				/* Unknow mapping type */
36046386Sjp151216 				assert(FALSE);
36056386Sjp151216 			}
36066386Sjp151216 		}
36074520Snw141292 	}
36084520Snw141292 
36094520Snw141292 out:
36104864Sbaban 	if (vm != NULL)
36114520Snw141292 		(void) sqlite_finalize(vm, NULL);
36124520Snw141292 	return (retcode);
36134520Snw141292 }
36144520Snw141292 
36155696Snw141292 static
36165696Snw141292 idmap_retcode
36174520Snw141292 lookup_cache_name2sid(sqlite *cache, const char *name, const char *domain,
36185696Snw141292 	char **canonname, char **sidprefix, idmap_rid_t *rid, int *type)
36195696Snw141292 {
36205696Snw141292 	char		*end, *lower_name;
36214520Snw141292 	char		*sql = NULL;
36224520Snw141292 	const char	**values;
36234520Snw141292 	sqlite_vm	*vm = NULL;
36244520Snw141292 	int		ncol;
36254520Snw141292 	time_t		curtime;
36264520Snw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
36274520Snw141292 
36284520Snw141292 	/* Get current time */
36294520Snw141292 	errno = 0;
36304520Snw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
36315696Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
36325696Snw141292 		    strerror(errno));
36334520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
36344520Snw141292 		goto out;
36354520Snw141292 	}
36364520Snw141292 
36374520Snw141292 	/* SQL to lookup the cache */
36385696Snw141292 	if ((lower_name = tolower_u8(name)) == NULL)
36395696Snw141292 		lower_name = (char *)name;
36405696Snw141292 	sql = sqlite_mprintf("SELECT sidprefix, rid, type, canon_name "
36415696Snw141292 	    "FROM name_cache WHERE name = %Q AND domain = %Q AND "
36425696Snw141292 	    "(expiration = 0 OR expiration ISNULL OR "
36435696Snw141292 	    "expiration > %d);", lower_name, domain, curtime);
36445696Snw141292 	if (lower_name != name)
36455696Snw141292 		free(lower_name);
36464520Snw141292 	if (sql == NULL) {
36474520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
36484520Snw141292 		retcode = IDMAP_ERR_MEMORY;
36494520Snw141292 		goto out;
36504520Snw141292 	}
36515696Snw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 4, &values);
36524520Snw141292 	sqlite_freemem(sql);
36534520Snw141292 
36544520Snw141292 	if (retcode == IDMAP_SUCCESS) {
36554864Sbaban 		if (type != NULL) {
36564520Snw141292 			if (values[2] == NULL) {
36574520Snw141292 				retcode = IDMAP_ERR_CACHE;
36584520Snw141292 				goto out;
36594520Snw141292 			}
36604520Snw141292 			*type = strtol(values[2], &end, 10);
36614520Snw141292 		}
36624520Snw141292 
36635731Sbaban 		if (values[0] == NULL || values[1] == NULL) {
36645731Sbaban 			retcode = IDMAP_ERR_CACHE;
36655731Sbaban 			goto out;
36665731Sbaban 		}
36675731Sbaban 
36685696Snw141292 		if (canonname != NULL) {
36695696Snw141292 			assert(values[3] != NULL);
36705696Snw141292 			if ((*canonname = strdup(values[3])) == NULL) {
36715696Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
36725696Snw141292 				retcode = IDMAP_ERR_MEMORY;
36735696Snw141292 				goto out;
36745696Snw141292 			}
36755696Snw141292 		}
36765696Snw141292 
36774520Snw141292 		if ((*sidprefix = strdup(values[0])) == NULL) {
36784520Snw141292 			idmapdlog(LOG_ERR, "Out of memory");
36794520Snw141292 			retcode = IDMAP_ERR_MEMORY;
36805731Sbaban 			if (canonname != NULL) {
36815731Sbaban 				free(*canonname);
36825731Sbaban 				*canonname = NULL;
36835731Sbaban 			}
36844520Snw141292 			goto out;
36854520Snw141292 		}
36864520Snw141292 		*rid = strtoul(values[1], &end, 10);
36874520Snw141292 	}
36884520Snw141292 
36894520Snw141292 out:
36904864Sbaban 	if (vm != NULL)
36914520Snw141292 		(void) sqlite_finalize(vm, NULL);
36924520Snw141292 	return (retcode);
36934520Snw141292 }
36944520Snw141292 
36955696Snw141292 static
36965696Snw141292 idmap_retcode
36975731Sbaban ad_lookup_by_winname(lookup_state_t *state,
36985731Sbaban 		const char *name, const char *domain, int eunixtype,
36996386Sjp151216 		char **dn, char **attr, char **value, char **canonname,
37006386Sjp151216 		char **sidprefix, idmap_rid_t *rid, int *wintype,
37016386Sjp151216 		char **unixname)
37025696Snw141292 {
37038361SJulian.Pullen@Sun.COM 	int			retries;
37044520Snw141292 	idmap_query_state_t	*qs = NULL;
37054520Snw141292 	idmap_retcode		rc, retcode;
37068361SJulian.Pullen@Sun.COM 	int			i;
37078361SJulian.Pullen@Sun.COM 	int			found_ad = 0;
37088361SJulian.Pullen@Sun.COM 
37098040SBaban.Kenkre@Sun.COM 	RDLOCK_CONFIG();
37108361SJulian.Pullen@Sun.COM 	if (_idmapdstate.num_ads > 0) {
37118361SJulian.Pullen@Sun.COM 		for (i = 0; i < _idmapdstate.num_ads && !found_ad; i++) {
37128361SJulian.Pullen@Sun.COM 			retries = 0;
37138361SJulian.Pullen@Sun.COM retry:
37148361SJulian.Pullen@Sun.COM 			retcode = idmap_lookup_batch_start(_idmapdstate.ads[i],
37158361SJulian.Pullen@Sun.COM 			    1, &qs);
37168361SJulian.Pullen@Sun.COM 			if (retcode != IDMAP_SUCCESS) {
37178361SJulian.Pullen@Sun.COM 				if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
37188361SJulian.Pullen@Sun.COM 				    retries++ < ADUTILS_DEF_NUM_RETRIES)
37198361SJulian.Pullen@Sun.COM 					goto retry;
37208361SJulian.Pullen@Sun.COM 				degrade_svc(1, "failed to create request for "
37218361SJulian.Pullen@Sun.COM 				    "AD lookup by winname");
37228361SJulian.Pullen@Sun.COM 				return (retcode);
37238361SJulian.Pullen@Sun.COM 			}
37248361SJulian.Pullen@Sun.COM 
37258361SJulian.Pullen@Sun.COM 			restore_svc();
37268361SJulian.Pullen@Sun.COM 
37278361SJulian.Pullen@Sun.COM 			if (state != NULL && i == 0) {
37288361SJulian.Pullen@Sun.COM 				/*
37298361SJulian.Pullen@Sun.COM 				 * Directory based name mapping is only
37308361SJulian.Pullen@Sun.COM 				 * performed within the joined forest (i == 0).
37318361SJulian.Pullen@Sun.COM 				 * We don't trust other "trusted" forests to
37328361SJulian.Pullen@Sun.COM 				 * provide DS-based name mapping information
37338361SJulian.Pullen@Sun.COM 				 * because AD's definition of "cross-forest
37348361SJulian.Pullen@Sun.COM 				 * trust" does not encompass this sort of
37358361SJulian.Pullen@Sun.COM 				 * behavior.
37368361SJulian.Pullen@Sun.COM 				 */
37378361SJulian.Pullen@Sun.COM 				idmap_lookup_batch_set_unixattr(qs,
37388361SJulian.Pullen@Sun.COM 				    state->ad_unixuser_attr,
37398361SJulian.Pullen@Sun.COM 				    state->ad_unixgroup_attr);
37408361SJulian.Pullen@Sun.COM 			}
37418361SJulian.Pullen@Sun.COM 
37428361SJulian.Pullen@Sun.COM 			retcode = idmap_name2sid_batch_add1(qs, name, domain,
37438361SJulian.Pullen@Sun.COM 			    eunixtype, dn, attr, value, canonname, sidprefix,
37448361SJulian.Pullen@Sun.COM 			    rid, wintype, unixname, &rc);
37458361SJulian.Pullen@Sun.COM 			if (retcode == IDMAP_ERR_DOMAIN_NOTFOUND) {
37468361SJulian.Pullen@Sun.COM 				idmap_lookup_release_batch(&qs);
37478361SJulian.Pullen@Sun.COM 				continue;
37488361SJulian.Pullen@Sun.COM 			}
37498361SJulian.Pullen@Sun.COM 			found_ad = 1;
37508361SJulian.Pullen@Sun.COM 			if (retcode != IDMAP_SUCCESS)
37518361SJulian.Pullen@Sun.COM 				idmap_lookup_release_batch(&qs);
37528361SJulian.Pullen@Sun.COM 			else
37538361SJulian.Pullen@Sun.COM 				retcode = idmap_lookup_batch_end(&qs);
37548361SJulian.Pullen@Sun.COM 
37558361SJulian.Pullen@Sun.COM 			if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
37568361SJulian.Pullen@Sun.COM 			    retries++ < ADUTILS_DEF_NUM_RETRIES)
37578361SJulian.Pullen@Sun.COM 				goto retry;
37588361SJulian.Pullen@Sun.COM 			else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
37598361SJulian.Pullen@Sun.COM 				degrade_svc(1,
37608361SJulian.Pullen@Sun.COM 				    "some AD lookups timed out repeatedly");
37618361SJulian.Pullen@Sun.COM 		}
37628361SJulian.Pullen@Sun.COM 	} else {
37638361SJulian.Pullen@Sun.COM 		/* No AD case */
37648361SJulian.Pullen@Sun.COM 		retcode = IDMAP_ERR_NO_ACTIVEDIRECTORY;
37654520Snw141292 	}
37668361SJulian.Pullen@Sun.COM 	UNLOCK_CONFIG();
37674520Snw141292 
37684520Snw141292 	if (retcode != IDMAP_SUCCESS) {
37695731Sbaban 		idmapdlog(LOG_NOTICE, "AD lookup by winname failed");
37704520Snw141292 		return (retcode);
37715731Sbaban 	}
37725731Sbaban 	return (rc);
37734520Snw141292 }
37744520Snw141292 
37755696Snw141292 idmap_retcode
37764520Snw141292 lookup_name2sid(sqlite *cache, const char *name, const char *domain,
37775696Snw141292 		int *is_wuser, char **canonname, char **sidprefix,
37786616Sdm199847 		idmap_rid_t *rid, idmap_mapping *req, int local_only)
37795696Snw141292 {
37804520Snw141292 	int		type;
37814520Snw141292 	idmap_retcode	retcode;
37824520Snw141292 
37835696Snw141292 	*sidprefix = NULL;
37845731Sbaban 	if (canonname != NULL)
37855731Sbaban 		*canonname = NULL;
37865731Sbaban 
37875731Sbaban 	/* Lookup well-known SIDs table */
37885696Snw141292 	retcode = lookup_wksids_name2sid(name, canonname, sidprefix, rid,
37895696Snw141292 	    &type);
37904864Sbaban 	if (retcode == IDMAP_SUCCESS) {
37915731Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
37924864Sbaban 		goto out;
37934864Sbaban 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
37944864Sbaban 		return (retcode);
37954864Sbaban 	}
37964864Sbaban 
37975731Sbaban 	/* Lookup cache */
37985696Snw141292 	retcode = lookup_cache_name2sid(cache, name, domain, canonname,
37995696Snw141292 	    sidprefix, rid, &type);
38005731Sbaban 	if (retcode == IDMAP_SUCCESS) {
38015731Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
38025731Sbaban 		goto out;
38035731Sbaban 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
38044520Snw141292 		return (retcode);
38054520Snw141292 	}
38064520Snw141292 
38076616Sdm199847 	/*
38086616Sdm199847 	 * The caller may be using this function to determine if this
38096616Sdm199847 	 * request needs to be marked for AD lookup or not
38106616Sdm199847 	 * (i.e. _IDMAP_F_LOOKUP_AD) and therefore may not want this
38116616Sdm199847 	 * function to AD lookup now.
38126616Sdm199847 	 */
38136616Sdm199847 	if (local_only)
38146616Sdm199847 		return (retcode);
38156616Sdm199847 
38165731Sbaban 	/* Lookup AD */
38175731Sbaban 	retcode = ad_lookup_by_winname(NULL, name, domain, _IDMAP_T_UNDEF,
38186386Sjp151216 	    NULL, NULL, NULL, canonname, sidprefix, rid, &type, NULL);
38195731Sbaban 	if (retcode != IDMAP_SUCCESS)
38205731Sbaban 		return (retcode);
38215731Sbaban 
38224864Sbaban out:
38234520Snw141292 	/*
38244520Snw141292 	 * Entry found (cache or Windows lookup)
38255696Snw141292 	 * is_wuser is both input as well as output parameter
38264520Snw141292 	 */
38275731Sbaban 	if (*is_wuser == 1 && type != _IDMAP_T_USER)
38285731Sbaban 		retcode = IDMAP_ERR_NOTUSER;
38295731Sbaban 	else if (*is_wuser == 0 && type != _IDMAP_T_GROUP)
38305731Sbaban 		retcode = IDMAP_ERR_NOTGROUP;
38315731Sbaban 	else if (*is_wuser == -1) {
38324520Snw141292 		/* Caller wants to know if its user or group */
38334520Snw141292 		if (type == _IDMAP_T_USER)
38345696Snw141292 			*is_wuser = 1;
38354520Snw141292 		else if (type == _IDMAP_T_GROUP)
38365696Snw141292 			*is_wuser = 0;
38375731Sbaban 		else
38385731Sbaban 			retcode = IDMAP_ERR_SID;
38395731Sbaban 	}
38405731Sbaban 
38415731Sbaban 	if (retcode != IDMAP_SUCCESS) {
38425731Sbaban 		free(*sidprefix);
38435731Sbaban 		*sidprefix = NULL;
38445731Sbaban 		if (canonname != NULL) {
38455731Sbaban 			free(*canonname);
38465731Sbaban 			*canonname = NULL;
38475696Snw141292 		}
38484520Snw141292 	}
38494520Snw141292 	return (retcode);
38504520Snw141292 }
38514520Snw141292 
38525696Snw141292 static
38535696Snw141292 idmap_retcode
38546616Sdm199847 name_based_mapping_pid2sid(lookup_state_t *state, const char *unixname,
38555696Snw141292 		int is_user, idmap_mapping *req, idmap_id_res *res)
38565696Snw141292 {
38574520Snw141292 	const char	*winname, *windomain;
38585696Snw141292 	char		*canonname;
38594520Snw141292 	char		*sql = NULL, *errmsg = NULL;
38604520Snw141292 	idmap_retcode	retcode;
38614520Snw141292 	char		*end;
38624520Snw141292 	const char	**values;
38634520Snw141292 	sqlite_vm	*vm = NULL;
38646386Sjp151216 	int		ncol, r;
38655731Sbaban 	int		is_wuser;
38664520Snw141292 	const char	*me = "name_based_mapping_pid2sid";
38676386Sjp151216 	int 		non_wild_match = FALSE;
38686386Sjp151216 	idmap_namerule	*rule = &res->info.how.idmap_how_u.rule;
38696386Sjp151216 	int direction;
38705731Sbaban 
38715731Sbaban 	assert(unixname != NULL); /* We have unixname */
38725731Sbaban 	assert(req->id2name == NULL); /* We don't have winname */
38735731Sbaban 	assert(res->id.idmap_id_u.sid.prefix == NULL); /* No SID either */
38744520Snw141292 
38754520Snw141292 	sql = sqlite_mprintf(
38766386Sjp151216 	    "SELECT winname_display, windomain, w2u_order, "
38776386Sjp151216 	    "is_wuser, unixname, is_nt4 "
38786386Sjp151216 	    "FROM namerules WHERE "
38795696Snw141292 	    "u2w_order > 0 AND is_user = %d AND "
38805696Snw141292 	    "(unixname = %Q OR unixname = '*') "
38815696Snw141292 	    "ORDER BY u2w_order ASC;", is_user, unixname);
38824520Snw141292 	if (sql == NULL) {
38834520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
38844520Snw141292 		retcode = IDMAP_ERR_MEMORY;
38854520Snw141292 		goto out;
38864520Snw141292 	}
38874520Snw141292 
38886616Sdm199847 	if (sqlite_compile(state->db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
38894520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
38905696Snw141292 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
38915696Snw141292 		    CHECK_NULL(errmsg));
38924520Snw141292 		sqlite_freemem(errmsg);
38934520Snw141292 		goto out;
38944520Snw141292 	}
38954520Snw141292 
38966386Sjp151216 	for (;;) {
38974520Snw141292 		r = sqlite_step(vm, &ncol, &values, NULL);
38984884Sjp151216 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
38994884Sjp151216 		if (r == SQLITE_ROW) {
39006386Sjp151216 			if (ncol < 6) {
39014520Snw141292 				retcode = IDMAP_ERR_INTERNAL;
39024520Snw141292 				goto out;
39034520Snw141292 			}
39044520Snw141292 			if (values[0] == NULL) {
39054520Snw141292 				/* values [1] and [2] can be null */
39064520Snw141292 				retcode = IDMAP_ERR_INTERNAL;
39074520Snw141292 				goto out;
39084520Snw141292 			}
39096386Sjp151216 
39106386Sjp151216 			if (values[2] != NULL)
39116386Sjp151216 				direction =
39126386Sjp151216 				    (strtol(values[2], &end, 10) == 0)?
39136386Sjp151216 				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
39146386Sjp151216 			else
39156386Sjp151216 				direction = IDMAP_DIRECTION_U2W;
39166386Sjp151216 
39174520Snw141292 			if (EMPTY_NAME(values[0])) {
39186386Sjp151216 				idmap_namerule_set(rule, values[1], values[0],
39196386Sjp151216 				    values[4], is_user,
39206386Sjp151216 				    strtol(values[3], &end, 10),
39216386Sjp151216 				    strtol(values[5], &end, 10),
39226386Sjp151216 				    direction);
39234520Snw141292 				retcode = IDMAP_ERR_NOMAPPING;
39244520Snw141292 				goto out;
39254520Snw141292 			}
39265696Snw141292 
39275696Snw141292 			if (values[0][0] == '*') {
39286386Sjp151216 				winname = unixname;
39296386Sjp151216 				if (non_wild_match) {
39305696Snw141292 					/*
39316386Sjp151216 					 * There were non-wildcard rules
39326386Sjp151216 					 * where the Windows identity doesn't
39336386Sjp151216 					 * exist. Return no mapping.
39345696Snw141292 					 */
39355696Snw141292 					retcode = IDMAP_ERR_NOMAPPING;
39365696Snw141292 					goto out;
39375696Snw141292 				}
39385696Snw141292 			} else {
39396386Sjp151216 				/* Save first non-wild match rule */
39406386Sjp151216 				if (!non_wild_match) {
39416386Sjp151216 					idmap_namerule_set(rule, values[1],
39426386Sjp151216 					    values[0], values[4],
39436386Sjp151216 					    is_user,
39446386Sjp151216 					    strtol(values[3], &end, 10),
39456386Sjp151216 					    strtol(values[5], &end, 10),
39466386Sjp151216 					    direction);
39476386Sjp151216 					non_wild_match = TRUE;
39486386Sjp151216 				}
39495696Snw141292 				winname = values[0];
39505696Snw141292 			}
39516386Sjp151216 			is_wuser = res->id.idtype == IDMAP_USID ? 1
39526386Sjp151216 			    : res->id.idtype == IDMAP_GSID ? 0
39536386Sjp151216 			    : -1;
39544864Sbaban 			if (values[1] != NULL)
39554520Snw141292 				windomain = values[1];
39566616Sdm199847 			else if (state->defdom != NULL)
39576616Sdm199847 				windomain = state->defdom;
39584520Snw141292 			else {
39595696Snw141292 				idmapdlog(LOG_ERR, "%s: no domain", me);
39604520Snw141292 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
39614520Snw141292 				goto out;
39624520Snw141292 			}
39635696Snw141292 
39646616Sdm199847 			retcode = lookup_name2sid(state->cache,
39656616Sdm199847 			    winname, windomain,
39665696Snw141292 			    &is_wuser, &canonname,
39675696Snw141292 			    &res->id.idmap_id_u.sid.prefix,
39686616Sdm199847 			    &res->id.idmap_id_u.sid.rid, req, 0);
39695731Sbaban 
39704520Snw141292 			if (retcode == IDMAP_ERR_NOTFOUND) {
39715696Snw141292 				continue;
39724520Snw141292 			}
39734520Snw141292 			goto out;
39746386Sjp151216 
39754520Snw141292 		} else if (r == SQLITE_DONE) {
39766386Sjp151216 			/*
39776386Sjp151216 			 * If there were non-wildcard rules where
39786386Sjp151216 			 * Windows identity doesn't exist
39796386Sjp151216 			 * return no mapping.
39806386Sjp151216 			 */
39816386Sjp151216 			if (non_wild_match)
39826386Sjp151216 				retcode = IDMAP_ERR_NOMAPPING;
39836386Sjp151216 			else
39846386Sjp151216 				retcode = IDMAP_ERR_NOTFOUND;
39854520Snw141292 			goto out;
39864520Snw141292 		} else {
39874520Snw141292 			(void) sqlite_finalize(vm, &errmsg);
39884520Snw141292 			vm = NULL;
39895696Snw141292 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
39905696Snw141292 			    CHECK_NULL(errmsg));
39914520Snw141292 			sqlite_freemem(errmsg);
39924520Snw141292 			retcode = IDMAP_ERR_INTERNAL;
39934520Snw141292 			goto out;
39944520Snw141292 		}
39954520Snw141292 	}
39964520Snw141292 
39974520Snw141292 out:
39984864Sbaban 	if (sql != NULL)
39994520Snw141292 		sqlite_freemem(sql);
40006386Sjp151216 	res->info.how.map_type = IDMAP_MAP_TYPE_RULE_BASED;
40014520Snw141292 	if (retcode == IDMAP_SUCCESS) {
40025696Snw141292 		res->id.idtype = is_wuser ? IDMAP_USID : IDMAP_GSID;
40035696Snw141292 
40044864Sbaban 		if (values[2] != NULL)
40054520Snw141292 			res->direction =
40064644Sbaban 			    (strtol(values[2], &end, 10) == 0)?
40074644Sbaban 			    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
40084520Snw141292 		else
40094644Sbaban 			res->direction = IDMAP_DIRECTION_U2W;
40105064Sdm199847 
40115696Snw141292 		req->id2name = canonname;
40125064Sdm199847 		if (req->id2name != NULL) {
40136616Sdm199847 			req->id2domain = strdup(windomain);
40146616Sdm199847 			if (req->id2domain == NULL)
40156616Sdm199847 				retcode = IDMAP_ERR_MEMORY;
40164520Snw141292 		}
40176616Sdm199847 	}
40186616Sdm199847 
40196616Sdm199847 	if (retcode == IDMAP_SUCCESS) {
40206386Sjp151216 		idmap_namerule_set(rule, values[1], values[0], values[4],
40216386Sjp151216 		    is_user, strtol(values[3], &end, 10),
40226386Sjp151216 		    strtol(values[5], &end, 10),
40236386Sjp151216 		    rule->direction);
40246386Sjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
40254520Snw141292 	}
40264864Sbaban 	if (vm != NULL)
40274520Snw141292 		(void) sqlite_finalize(vm, NULL);
40284520Snw141292 	return (retcode);
40294520Snw141292 }
40304520Snw141292 
40315696Snw141292 /*
40325696Snw141292  * Convention when processing unix2win requests:
40335696Snw141292  *
40345696Snw141292  * Unix identity:
40355696Snw141292  * req->id1name =
40365696Snw141292  *              unixname if given otherwise unixname found will be placed
40375696Snw141292  *              here.
40385696Snw141292  * req->id1domain =
40395696Snw141292  *              NOT USED
40405696Snw141292  * req->id1.idtype =
40415696Snw141292  *              Given type (IDMAP_UID or IDMAP_GID)
40425696Snw141292  * req->id1..[uid or gid] =
40435696Snw141292  *              UID/GID if given otherwise UID/GID found will be placed here.
40445696Snw141292  *
40455696Snw141292  * Windows identity:
40465696Snw141292  * req->id2name =
40475696Snw141292  *              winname found will be placed here.
40485696Snw141292  * req->id2domain =
40495696Snw141292  *              windomain found will be placed here.
40505696Snw141292  * res->id.idtype =
40515696Snw141292  *              Target type initialized from req->id2.idtype. If
40525696Snw141292  *              it is IDMAP_SID then actual type (IDMAP_USID/GSID) found
40535696Snw141292  *              will be placed here.
40545696Snw141292  * req->id..sid.[prefix, rid] =
40555696Snw141292  *              SID found will be placed here.
40565696Snw141292  *
40575696Snw141292  * Others:
40585696Snw141292  * res->retcode =
40595696Snw141292  *              Return status for this request will be placed here.
40605696Snw141292  * res->direction =
40615696Snw141292  *              Direction found will be placed here. Direction
40625696Snw141292  *              meaning whether the resultant mapping is valid
40635696Snw141292  *              only from unix2win or bi-directional.
40645696Snw141292  * req->direction =
40655696Snw141292  *              INTERNAL USE. Used by idmapd to set various
40665696Snw141292  *              flags (_IDMAP_F_xxxx) to aid in processing
40675696Snw141292  *              of the request.
40685696Snw141292  * req->id2.idtype =
40695696Snw141292  *              INTERNAL USE. Initially this is the requested target
40705696Snw141292  *              type and is used to initialize res->id.idtype.
40715696Snw141292  *              ad_lookup_batch() uses this field temporarily to store
40725696Snw141292  *              sid_type obtained by the batched AD lookups and after
40735696Snw141292  *              use resets it to IDMAP_NONE to prevent xdr from
40745696Snw141292  *              mis-interpreting the contents of req->id2.
40755696Snw141292  * req->id2..[uid or gid or sid] =
40765696Snw141292  *              NOT USED
40775696Snw141292  */
40785696Snw141292 
40795696Snw141292 /*
40805696Snw141292  * This function does the following:
40815696Snw141292  * 1. Lookup well-known SIDs table.
40825696Snw141292  * 2. Lookup cache.
40835696Snw141292  * 3. Check if the client does not want new mapping to be allocated
40845696Snw141292  *    in which case this pass is the final pass.
40855731Sbaban  * 4. Set AD/NLDAP lookup flags if it determines that the next stage needs
40865731Sbaban  *    to do AD/NLDAP lookup.
40875696Snw141292  */
40884520Snw141292 idmap_retcode
40896616Sdm199847 pid2sid_first_pass(lookup_state_t *state, idmap_mapping *req,
40906616Sdm199847 		idmap_id_res *res, int is_user, int getname)
40915696Snw141292 {
40925731Sbaban 	idmap_retcode	retcode;
40935731Sbaban 	bool_t		gen_localsid_on_err = FALSE;
40945731Sbaban 
40955731Sbaban 	/* Initialize result */
40964520Snw141292 	res->id.idtype = req->id2.idtype;
40975731Sbaban 	res->direction = IDMAP_DIRECTION_UNDEF;
40985731Sbaban 
40995731Sbaban 	if (req->id2.idmap_id_u.sid.prefix != NULL) {
41005731Sbaban 		/* sanitize sidprefix */
41015731Sbaban 		free(req->id2.idmap_id_u.sid.prefix);
41025731Sbaban 		req->id2.idmap_id_u.sid.prefix = NULL;
41035731Sbaban 	}
41045731Sbaban 
41056386Sjp151216 	/* Find pid */
41066386Sjp151216 	if (req->id1.idmap_id_u.uid == SENTINEL_PID) {
41076386Sjp151216 		if (ns_lookup_byname(req->id1name, NULL, &req->id1)
41086386Sjp151216 		    != IDMAP_SUCCESS) {
41096386Sjp151216 			retcode = IDMAP_ERR_NOMAPPING;
41106386Sjp151216 			goto out;
41116386Sjp151216 		}
41126386Sjp151216 	}
41136386Sjp151216 
41145731Sbaban 	/* Lookup well-known SIDs table */
41154520Snw141292 	retcode = lookup_wksids_pid2sid(req, res, is_user);
41164520Snw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
41174520Snw141292 		goto out;
41184520Snw141292 
41195731Sbaban 	/* Lookup cache */
41206616Sdm199847 	retcode = lookup_cache_pid2sid(state->cache, req, res, is_user,
41216616Sdm199847 	    getname);
41224520Snw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
41234520Snw141292 		goto out;
41244520Snw141292 
41254520Snw141292 	/* Ephemeral ids cannot be allocated during pid2sid */
41264520Snw141292 	if (IS_EPHEMERAL(req->id1.idmap_id_u.uid)) {
41274864Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
41284520Snw141292 		goto out;
41294520Snw141292 	}
41304520Snw141292 
41316386Sjp151216 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req)) {
41328361SJulian.Pullen@Sun.COM 		retcode = IDMAP_ERR_NONE_GENERATED;
41336386Sjp151216 		goto out;
41346386Sjp151216 	}
41356386Sjp151216 
41366386Sjp151216 	if (AVOID_NAMESERVICE(req)) {
41375731Sbaban 		gen_localsid_on_err = TRUE;
41384864Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
41394520Snw141292 		goto out;
41404520Snw141292 	}
41414520Snw141292 
41425731Sbaban 	/* Set flags for the next stage */
41435731Sbaban 	if (AD_MODE(req->id1.idtype, state)) {
41445731Sbaban 		/*
41455731Sbaban 		 * If AD-based name mapping is enabled then the next stage
41465731Sbaban 		 * will need to lookup AD using unixname to get the
41475731Sbaban 		 * corresponding winname.
41485731Sbaban 		 */
41495731Sbaban 		if (req->id1name == NULL) {
41505731Sbaban 			/* Get unixname if only pid is given. */
41515731Sbaban 			retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid,
41525731Sbaban 			    is_user, &req->id1name);
41536616Sdm199847 			if (retcode != IDMAP_SUCCESS) {
41546616Sdm199847 				gen_localsid_on_err = TRUE;
41555731Sbaban 				goto out;
41566616Sdm199847 			}
41574520Snw141292 		}
41585731Sbaban 		req->direction |= _IDMAP_F_LOOKUP_AD;
41595731Sbaban 		state->ad_nqueries++;
41605731Sbaban 	} else if (NLDAP_OR_MIXED_MODE(req->id1.idtype, state)) {
41615731Sbaban 		/*
41625731Sbaban 		 * If native LDAP or mixed mode is enabled for name mapping
41635731Sbaban 		 * then the next stage will need to lookup native LDAP using
41645731Sbaban 		 * unixname/pid to get the corresponding winname.
41655731Sbaban 		 */
41665731Sbaban 		req->direction |= _IDMAP_F_LOOKUP_NLDAP;
41675731Sbaban 		state->nldap_nqueries++;
41685731Sbaban 	}
41695731Sbaban 
41705731Sbaban 	/*
41715731Sbaban 	 * Failed to find non-expired entry in cache. Set the flag to
41725731Sbaban 	 * indicate that we are not done yet.
41735731Sbaban 	 */
41745731Sbaban 	state->pid2sid_done = FALSE;
41755731Sbaban 	req->direction |= _IDMAP_F_NOTDONE;
41765731Sbaban 	retcode = IDMAP_SUCCESS;
41775731Sbaban 
41785731Sbaban out:
41795731Sbaban 	res->retcode = idmap_stat4prot(retcode);
41805731Sbaban 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
41815731Sbaban 		if (gen_localsid_on_err == TRUE)
41826386Sjp151216 			(void) generate_localsid(req, res, is_user, TRUE);
41835731Sbaban 	return (retcode);
41845731Sbaban }
41855731Sbaban 
41865731Sbaban idmap_retcode
41876616Sdm199847 pid2sid_second_pass(lookup_state_t *state, idmap_mapping *req,
41886616Sdm199847 	idmap_id_res *res, int is_user)
41895731Sbaban {
41905731Sbaban 	bool_t		gen_localsid_on_err = TRUE;
41915731Sbaban 	idmap_retcode	retcode = IDMAP_SUCCESS;
41925731Sbaban 
41935731Sbaban 	/* Check if second pass is needed */
41945731Sbaban 	if (ARE_WE_DONE(req->direction))
41955731Sbaban 		return (res->retcode);
41965731Sbaban 
41975731Sbaban 	/* Get status from previous pass */
41985731Sbaban 	retcode = res->retcode;
41995731Sbaban 	if (retcode != IDMAP_SUCCESS)
42005731Sbaban 		goto out;
42015731Sbaban 
42025731Sbaban 	/*
42035731Sbaban 	 * If directory-based name mapping is enabled then the winname
42045731Sbaban 	 * may already have been retrieved from the AD object (AD-mode)
42056616Sdm199847 	 * or from native LDAP object (nldap-mode or mixed-mode).
42066616Sdm199847 	 * Note that if we have winname but no SID then it's an error
42076616Sdm199847 	 * because this implies that the Native LDAP entry contains
42086616Sdm199847 	 * winname which does not exist and it's better that we return
42096616Sdm199847 	 * an error instead of doing rule-based mapping so that the user
42106616Sdm199847 	 * can detect the issue and take appropriate action.
42115731Sbaban 	 */
42126616Sdm199847 	if (req->id2name != NULL) {
42136616Sdm199847 		/* Return notfound if we've winname but no SID. */
42146616Sdm199847 		if (res->id.idmap_id_u.sid.prefix == NULL) {
42156616Sdm199847 			retcode = IDMAP_ERR_NOTFOUND;
42166616Sdm199847 			goto out;
42176616Sdm199847 		}
42185731Sbaban 		if (AD_MODE(req->id1.idtype, state))
42195731Sbaban 			res->direction = IDMAP_DIRECTION_BI;
42205731Sbaban 		else if (NLDAP_MODE(req->id1.idtype, state))
42215731Sbaban 			res->direction = IDMAP_DIRECTION_BI;
42225731Sbaban 		else if (MIXED_MODE(req->id1.idtype, state))
42235731Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
42245731Sbaban 		goto out;
42256616Sdm199847 	} else if (res->id.idmap_id_u.sid.prefix != NULL) {
42266616Sdm199847 		/*
42276616Sdm199847 		 * We've SID but no winname. This is fine because
42286616Sdm199847 		 * the caller may have only requested SID.
42296616Sdm199847 		 */
42306616Sdm199847 		goto out;
42315731Sbaban 	}
42325731Sbaban 
42336616Sdm199847 	/* Free any mapping info from Directory based mapping */
42346616Sdm199847 	if (res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN)
42356616Sdm199847 		idmap_info_free(&res->info);
42366616Sdm199847 
42375731Sbaban 	if (req->id1name == NULL) {
42385731Sbaban 		/* Get unixname from name service */
42395731Sbaban 		retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid, is_user,
42405731Sbaban 		    &req->id1name);
42415731Sbaban 		if (retcode != IDMAP_SUCCESS)
42425731Sbaban 			goto out;
42435731Sbaban 	} else if (req->id1.idmap_id_u.uid == SENTINEL_PID) {
42445731Sbaban 		/* Get pid from name service */
42455731Sbaban 		retcode = ns_lookup_byname(req->id1name, NULL, &req->id1);
42465731Sbaban 		if (retcode != IDMAP_SUCCESS) {
42475731Sbaban 			gen_localsid_on_err = FALSE;
42485731Sbaban 			goto out;
42494520Snw141292 		}
42504520Snw141292 	}
42514520Snw141292 
42525731Sbaban 	/* Use unixname to evaluate local name-based mapping rules */
42536616Sdm199847 	retcode = name_based_mapping_pid2sid(state, req->id1name, is_user,
42545696Snw141292 	    req, res);
42554520Snw141292 	if (retcode == IDMAP_ERR_NOTFOUND) {
42566386Sjp151216 		retcode = generate_localsid(req, res, is_user, FALSE);
42575731Sbaban 		gen_localsid_on_err = FALSE;
42585731Sbaban 	}
42594520Snw141292 
42604520Snw141292 out:
42615731Sbaban 	res->retcode = idmap_stat4prot(retcode);
42625731Sbaban 	if (res->retcode != IDMAP_SUCCESS) {
42635731Sbaban 		req->direction = _IDMAP_F_DONE;
42646616Sdm199847 		free(req->id2name);
42656616Sdm199847 		req->id2name = NULL;
42666616Sdm199847 		free(req->id2domain);
42676616Sdm199847 		req->id2domain = NULL;
42685731Sbaban 		if (gen_localsid_on_err == TRUE)
42696386Sjp151216 			(void) generate_localsid(req, res, is_user, TRUE);
42706616Sdm199847 		else
42716616Sdm199847 			res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
42724520Snw141292 	}
42735731Sbaban 	if (!ARE_WE_DONE(req->direction))
42744520Snw141292 		state->pid2sid_done = FALSE;
42754520Snw141292 	return (retcode);
42764520Snw141292 }
42774520Snw141292 
42785696Snw141292 static
42795696Snw141292 int
42804644Sbaban copy_mapping_request(idmap_mapping *mapping, idmap_mapping *request)
42814520Snw141292 {
42824644Sbaban 	(void) memset(mapping, 0, sizeof (*mapping));
42834644Sbaban 
42844520Snw141292 	mapping->flag = request->flag;
42855731Sbaban 	mapping->direction = _IDMAP_F_DONE;
42864644Sbaban 	mapping->id2.idtype = request->id2.idtype;
42874520Snw141292 
42884520Snw141292 	mapping->id1.idtype = request->id1.idtype;
42895696Snw141292 	if (IS_REQUEST_SID(*request, 1)) {
42904520Snw141292 		mapping->id1.idmap_id_u.sid.rid =
42914520Snw141292 		    request->id1.idmap_id_u.sid.rid;
42924644Sbaban 		if (!EMPTY_STRING(request->id1.idmap_id_u.sid.prefix)) {
42934520Snw141292 			mapping->id1.idmap_id_u.sid.prefix =
42944520Snw141292 			    strdup(request->id1.idmap_id_u.sid.prefix);
42954644Sbaban 			if (mapping->id1.idmap_id_u.sid.prefix == NULL)
42965064Sdm199847 				goto errout;
42974644Sbaban 		}
42984520Snw141292 	} else {
42994520Snw141292 		mapping->id1.idmap_id_u.uid = request->id1.idmap_id_u.uid;
43004520Snw141292 	}
43014520Snw141292 
43025731Sbaban 	if (!EMPTY_STRING(request->id1domain)) {
43035731Sbaban 		mapping->id1domain = strdup(request->id1domain);
43045731Sbaban 		if (mapping->id1domain == NULL)
43055731Sbaban 			goto errout;
43065731Sbaban 	}
43075731Sbaban 
43085731Sbaban 	if (!EMPTY_STRING(request->id1name)) {
43095731Sbaban 		mapping->id1name = strdup(request->id1name);
43105731Sbaban 		if (mapping->id1name == NULL)
43115731Sbaban 			goto errout;
43125731Sbaban 	}
43134520Snw141292 
43144644Sbaban 	/* We don't need the rest of the request i.e request->id2 */
43154644Sbaban 	return (0);
43164644Sbaban 
43174644Sbaban errout:
43185064Sdm199847 	if (mapping->id1.idmap_id_u.sid.prefix != NULL)
43194644Sbaban 		free(mapping->id1.idmap_id_u.sid.prefix);
43205064Sdm199847 	if (mapping->id1domain != NULL)
43215064Sdm199847 		free(mapping->id1domain);
43225064Sdm199847 	if (mapping->id1name != NULL)
43235064Sdm199847 		free(mapping->id1name);
43244644Sbaban 
43254644Sbaban 	(void) memset(mapping, 0, sizeof (*mapping));
43264644Sbaban 	return (-1);
43274520Snw141292 }
43284520Snw141292 
43294520Snw141292 
43304520Snw141292 idmap_retcode
43314520Snw141292 get_w2u_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
43325696Snw141292 		idmap_mapping *mapping)
43335696Snw141292 {
43344520Snw141292 	idmap_id_res	idres;
43354520Snw141292 	lookup_state_t	state;
43365043Sbaban 	char		*cp;
43374520Snw141292 	idmap_retcode	retcode;
43384520Snw141292 	const char	*winname, *windomain;
43394520Snw141292 
43404520Snw141292 	(void) memset(&idres, 0, sizeof (idres));
43414520Snw141292 	(void) memset(&state, 0, sizeof (state));
43426616Sdm199847 	state.cache = cache;
43436616Sdm199847 	state.db = db;
43444520Snw141292 
43455731Sbaban 	/* Get directory-based name mapping info */
43466616Sdm199847 	retcode = load_cfg_in_state(&state);
43475731Sbaban 	if (retcode != IDMAP_SUCCESS)
43484520Snw141292 		goto out;
43495731Sbaban 
43505731Sbaban 	/*
43515731Sbaban 	 * Copy data from "request" to "mapping". Note that
43525731Sbaban 	 * empty strings are not copied from "request" to
43535731Sbaban 	 * "mapping" and therefore the coresponding strings in
43545731Sbaban 	 * "mapping" will be NULL. This eliminates having to
43555731Sbaban 	 * check for empty strings henceforth.
43565731Sbaban 	 */
43574644Sbaban 	if (copy_mapping_request(mapping, request) < 0) {
43584644Sbaban 		retcode = IDMAP_ERR_MEMORY;
43594644Sbaban 		goto out;
43604644Sbaban 	}
43614520Snw141292 
43625064Sdm199847 	winname = mapping->id1name;
43635064Sdm199847 	windomain = mapping->id1domain;
43644520Snw141292 
43655731Sbaban 	if (winname == NULL && windomain != NULL) {
43665731Sbaban 		retcode = IDMAP_ERR_ARG;
43675731Sbaban 		goto out;
43685731Sbaban 	}
43695731Sbaban 
43705731Sbaban 	/* Need atleast winname or sid to proceed */
43715731Sbaban 	if (winname == NULL && mapping->id1.idmap_id_u.sid.prefix == NULL) {
43724520Snw141292 		retcode = IDMAP_ERR_ARG;
43734520Snw141292 		goto out;
43744520Snw141292 	}
43754520Snw141292 
43765731Sbaban 	/*
43775731Sbaban 	 * If domainname is not given but we have a fully qualified
43785731Sbaban 	 * winname then extract the domainname from the winname,
43795731Sbaban 	 * otherwise use the default_domain from the config
43805731Sbaban 	 */
43815731Sbaban 	if (winname != NULL && windomain == NULL) {
43825064Sdm199847 		retcode = IDMAP_SUCCESS;
43835043Sbaban 		if ((cp = strchr(winname, '@')) != NULL) {
43845043Sbaban 			*cp = '\0';
43855064Sdm199847 			mapping->id1domain = strdup(cp + 1);
43865064Sdm199847 			if (mapping->id1domain == NULL)
43875064Sdm199847 				retcode = IDMAP_ERR_MEMORY;
43885731Sbaban 		} else if (lookup_wksids_name2sid(winname, NULL, NULL, NULL,
43895731Sbaban 		    NULL) != IDMAP_SUCCESS) {
43906950Sbaban 			if (state.defdom == NULL) {
43916950Sbaban 				/*
43926950Sbaban 				 * We have a non-qualified winname which is
43936950Sbaban 				 * neither the name of a well-known SID nor
43946950Sbaban 				 * there is a default domain with which we can
43956950Sbaban 				 * qualify it.
43966950Sbaban 				 */
43976950Sbaban 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
43986950Sbaban 			} else {
43996950Sbaban 				mapping->id1domain = strdup(state.defdom);
44006950Sbaban 				if (mapping->id1domain == NULL)
44016950Sbaban 					retcode = IDMAP_ERR_MEMORY;
44026950Sbaban 			}
44035064Sdm199847 		}
44044520Snw141292 		if (retcode != IDMAP_SUCCESS)
44054520Snw141292 			goto out;
44064520Snw141292 	}
44074520Snw141292 
44085731Sbaban 	/*
44095731Sbaban 	 * First pass looks up the well-known SIDs table and cache
44105731Sbaban 	 * and handles localSIDs
44115731Sbaban 	 */
44124520Snw141292 	state.sid2pid_done = TRUE;
44136616Sdm199847 	retcode = sid2pid_first_pass(&state, mapping, &idres);
44144520Snw141292 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
44154520Snw141292 		goto out;
44164520Snw141292 
44176616Sdm199847 	/* AD lookup */
44185731Sbaban 	if (state.ad_nqueries > 0) {
44196616Sdm199847 		retcode = ad_lookup_one(&state, mapping, &idres);
44205731Sbaban 		if (IDMAP_ERROR(retcode))
44215731Sbaban 			goto out;
44224520Snw141292 	}
44234520Snw141292 
44246616Sdm199847 	/* nldap lookup */
44256616Sdm199847 	if (state.nldap_nqueries > 0) {
44266616Sdm199847 		retcode = nldap_lookup_one(&state, mapping, &idres);
44276616Sdm199847 		if (IDMAP_FATAL_ERROR(retcode))
44285731Sbaban 			goto out;
44295731Sbaban 	}
44305731Sbaban 
44315731Sbaban 	/* Next pass performs name-based mapping and ephemeral mapping. */
44324520Snw141292 	state.sid2pid_done = TRUE;
44336616Sdm199847 	retcode = sid2pid_second_pass(&state, mapping, &idres);
44344520Snw141292 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
44354520Snw141292 		goto out;
44364520Snw141292 
44374520Snw141292 	/* Update cache */
44386616Sdm199847 	(void) update_cache_sid2pid(&state, mapping, &idres);
44394520Snw141292 
44404520Snw141292 out:
44415731Sbaban 	/*
44425731Sbaban 	 * Note that "mapping" is returned to the client. Therefore
44435731Sbaban 	 * copy whatever we have in "idres" to mapping->id2 and
44445731Sbaban 	 * free idres.
44455731Sbaban 	 */
44465731Sbaban 	mapping->direction = idres.direction;
44475731Sbaban 	mapping->id2 = idres.id;
44486386Sjp151216 	if (mapping->flag & IDMAP_REQ_FLG_MAPPING_INFO ||
44496386Sjp151216 	    retcode != IDMAP_SUCCESS)
44506386Sjp151216 		(void) idmap_info_mov(&mapping->info, &idres.info);
44516386Sjp151216 	else
44526386Sjp151216 		idmap_info_free(&idres.info);
44535731Sbaban 	(void) memset(&idres, 0, sizeof (idres));
44545731Sbaban 	if (retcode != IDMAP_SUCCESS)
44554864Sbaban 		mapping->id2.idmap_id_u.uid = UID_NOBODY;
44564520Snw141292 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
44575731Sbaban 	cleanup_lookup_state(&state);
44584520Snw141292 	return (retcode);
44594520Snw141292 }
44604520Snw141292 
44614520Snw141292 idmap_retcode
44624520Snw141292 get_u2w_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
44635696Snw141292 		idmap_mapping *mapping, int is_user)
44645696Snw141292 {
44654520Snw141292 	idmap_id_res	idres;
44664520Snw141292 	lookup_state_t	state;
44674520Snw141292 	idmap_retcode	retcode;
44684520Snw141292 
44694520Snw141292 	/*
44704520Snw141292 	 * In order to re-use the pid2sid code, we convert
44714520Snw141292 	 * our input data into structs that are expected by
44724520Snw141292 	 * pid2sid_first_pass.
44734520Snw141292 	 */
44744520Snw141292 
44754520Snw141292 	(void) memset(&idres, 0, sizeof (idres));
44764520Snw141292 	(void) memset(&state, 0, sizeof (state));
44776616Sdm199847 	state.cache = cache;
44786616Sdm199847 	state.db = db;
44794520Snw141292 
44805731Sbaban 	/* Get directory-based name mapping info */
44816616Sdm199847 	retcode = load_cfg_in_state(&state);
44825731Sbaban 	if (retcode != IDMAP_SUCCESS)
44835731Sbaban 		goto out;
44845731Sbaban 
44855731Sbaban 	/*
44865731Sbaban 	 * Copy data from "request" to "mapping". Note that
44875731Sbaban 	 * empty strings are not copied from "request" to
44885731Sbaban 	 * "mapping" and therefore the coresponding strings in
44895731Sbaban 	 * "mapping" will be NULL. This eliminates having to
44905731Sbaban 	 * check for empty strings henceforth.
44915731Sbaban 	 */
44924644Sbaban 	if (copy_mapping_request(mapping, request) < 0) {
44934644Sbaban 		retcode = IDMAP_ERR_MEMORY;
44944644Sbaban 		goto out;
44954644Sbaban 	}
44964520Snw141292 
44975731Sbaban 	/*
44985731Sbaban 	 * For unix to windows mapping request, we need atleast a
44995731Sbaban 	 * unixname or uid/gid to proceed
45005731Sbaban 	 */
45015731Sbaban 	if (mapping->id1name == NULL &&
45025127Sdm199847 	    mapping->id1.idmap_id_u.uid == SENTINEL_PID) {
45034520Snw141292 		retcode = IDMAP_ERR_ARG;
45044520Snw141292 		goto out;
45054520Snw141292 	}
45064520Snw141292 
45075731Sbaban 	/* First pass looks up cache and well-known SIDs */
45085731Sbaban 	state.pid2sid_done = TRUE;
45096616Sdm199847 	retcode = pid2sid_first_pass(&state, mapping, &idres, is_user, 1);
45105731Sbaban 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
45115731Sbaban 		goto out;
45125731Sbaban 
45136616Sdm199847 	/* nldap lookup */
45145731Sbaban 	if (state.nldap_nqueries > 0) {
45156616Sdm199847 		retcode = nldap_lookup_one(&state, mapping, &idres);
45165731Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
45175731Sbaban 			goto out;
45186616Sdm199847 	}
45196616Sdm199847 
45206616Sdm199847 	/* AD lookup */
45216616Sdm199847 	if (state.ad_nqueries > 0) {
45226616Sdm199847 		retcode = ad_lookup_one(&state, mapping, &idres);
45235731Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
45245731Sbaban 			goto out;
45254520Snw141292 	}
45264520Snw141292 
45275731Sbaban 	/*
45285731Sbaban 	 * Next pass processes the result of the preceding passes/lookups.
45295731Sbaban 	 * It returns if there's nothing more to be done otherwise it
45305731Sbaban 	 * evaluates local name-based mapping rules
45315731Sbaban 	 */
45324520Snw141292 	state.pid2sid_done = TRUE;
45336616Sdm199847 	retcode = pid2sid_second_pass(&state, mapping, &idres, is_user);
45344520Snw141292 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
45354520Snw141292 		goto out;
45364520Snw141292 
45374520Snw141292 	/* Update cache */
45386616Sdm199847 	(void) update_cache_pid2sid(&state, mapping, &idres);
45394520Snw141292 
45404520Snw141292 out:
45415731Sbaban 	/*
45425731Sbaban 	 * Note that "mapping" is returned to the client. Therefore
45435731Sbaban 	 * copy whatever we have in "idres" to mapping->id2 and
45445731Sbaban 	 * free idres.
45455731Sbaban 	 */
45464520Snw141292 	mapping->direction = idres.direction;
45474520Snw141292 	mapping->id2 = idres.id;
45486386Sjp151216 	if (mapping->flag & IDMAP_REQ_FLG_MAPPING_INFO ||
45496386Sjp151216 	    retcode != IDMAP_SUCCESS)
45506386Sjp151216 		(void) idmap_info_mov(&mapping->info, &idres.info);
45516386Sjp151216 	else
45526386Sjp151216 		idmap_info_free(&idres.info);
45534520Snw141292 	(void) memset(&idres, 0, sizeof (idres));
45544520Snw141292 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
45555731Sbaban 	cleanup_lookup_state(&state);
45564520Snw141292 	return (retcode);
45574520Snw141292 }
45585731Sbaban 
45596616Sdm199847 /*ARGSUSED*/
45605731Sbaban static
45615731Sbaban idmap_retcode
45626616Sdm199847 ad_lookup_one(lookup_state_t *state, idmap_mapping *req, idmap_id_res *res)
45635731Sbaban {
45646616Sdm199847 	idmap_mapping_batch	batch;
45656616Sdm199847 	idmap_ids_res		result;
45666616Sdm199847 
45676616Sdm199847 	batch.idmap_mapping_batch_len = 1;
45686616Sdm199847 	batch.idmap_mapping_batch_val = req;
45696616Sdm199847 	result.ids.ids_len = 1;
45706616Sdm199847 	result.ids.ids_val = res;
45716616Sdm199847 	return (ad_lookup_batch(state, &batch, &result));
45725731Sbaban }
4573