xref: /onnv-gate/usr/src/cmd/idmap/idmapd/dbutils.c (revision 8040:42abce45ef67)
14520Snw141292 /*
24520Snw141292  * CDDL HEADER START
34520Snw141292  *
44520Snw141292  * The contents of this file are subject to the terms of the
54520Snw141292  * Common Development and Distribution License (the "License").
64520Snw141292  * You may not use this file except in compliance with the License.
74520Snw141292  *
84520Snw141292  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
94520Snw141292  * or http://www.opensolaris.org/os/licensing.
104520Snw141292  * See the License for the specific language governing permissions
114520Snw141292  * and limitations under the License.
124520Snw141292  *
134520Snw141292  * When distributing Covered Code, include this CDDL HEADER in each
144520Snw141292  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
154520Snw141292  * If applicable, add the following below this CDDL HEADER, with the
164520Snw141292  * fields enclosed by brackets "[]" replaced with your own identifying
174520Snw141292  * information: Portions Copyright [yyyy] [name of copyright owner]
184520Snw141292  *
194520Snw141292  * CDDL HEADER END
204520Snw141292  */
214520Snw141292 /*
225932Sbaban  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
234520Snw141292  * Use is subject to license terms.
244520Snw141292  */
254520Snw141292 
264520Snw141292 /*
274520Snw141292  * Database related utility routines
284520Snw141292  */
294520Snw141292 
304520Snw141292 #include <stdio.h>
314520Snw141292 #include <stdlib.h>
324520Snw141292 #include <string.h>
334520Snw141292 #include <errno.h>
344520Snw141292 #include <sys/types.h>
354520Snw141292 #include <sys/stat.h>
364520Snw141292 #include <rpc/rpc.h>
374520Snw141292 #include <sys/sid.h>
384520Snw141292 #include <time.h>
394520Snw141292 #include <pwd.h>
404520Snw141292 #include <grp.h>
414884Sjp151216 #include <pthread.h>
424884Sjp151216 #include <assert.h>
435696Snw141292 #include <sys/u8_textprep.h>
444520Snw141292 
454520Snw141292 #include "idmapd.h"
464520Snw141292 #include "adutils.h"
474520Snw141292 #include "string.h"
484520Snw141292 #include "idmap_priv.h"
495696Snw141292 #include "schema.h"
505731Sbaban #include "nldaputils.h"
514520Snw141292 
524884Sjp151216 
534520Snw141292 static idmap_retcode sql_compile_n_step_once(sqlite *, char *,
544520Snw141292 		sqlite_vm **, int *, int, const char ***);
556616Sdm199847 static idmap_retcode ad_lookup_one(lookup_state_t *, idmap_mapping *,
566616Sdm199847 		idmap_id_res *);
575731Sbaban static idmap_retcode lookup_localsid2pid(idmap_mapping *, idmap_id_res *);
585731Sbaban static idmap_retcode lookup_cache_name2sid(sqlite *, const char *,
595731Sbaban 		const char *, char **, char **, idmap_rid_t *, int *);
605731Sbaban 
614520Snw141292 
624520Snw141292 #define	EMPTY_NAME(name)	(*name == 0 || strcmp(name, "\"\"") == 0)
634520Snw141292 
644520Snw141292 #define	DO_NOT_ALLOC_NEW_ID_MAPPING(req)\
654520Snw141292 		(req->flag & IDMAP_REQ_FLG_NO_NEW_ID_ALLOC)
664520Snw141292 
674520Snw141292 #define	AVOID_NAMESERVICE(req)\
684520Snw141292 		(req->flag & IDMAP_REQ_FLG_NO_NAMESERVICE)
694520Snw141292 
70*8040SBaban.Kenkre@Sun.COM #define	ALLOW_WK_OR_LOCAL_SIDS_ONLY(req)\
71*8040SBaban.Kenkre@Sun.COM 		(req->flag & IDMAP_REQ_FLG_WK_OR_LOCAL_SIDS_ONLY)
72*8040SBaban.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 	}
10965731Sbaban 	if (_idmapdstate.cfg->pgcfg.ds_name_mapping_enabled == FALSE) {
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 
18045731Sbaban /*
18055731Sbaban  * Batch AD lookups
18065731Sbaban  */
18074520Snw141292 idmap_retcode
18085731Sbaban ad_lookup_batch(lookup_state_t *state, idmap_mapping_batch *batch,
18095696Snw141292 		idmap_ids_res *result)
18105696Snw141292 {
18114520Snw141292 	idmap_retcode	retcode;
18125731Sbaban 	int		i, add, type, is_wuser, is_user;
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 
18215731Sbaban 	/*
18225731Sbaban 	 * Since req->id2.idtype is unused, we will use it here
18235731Sbaban 	 * to retrieve the value of sid_type. But it needs to be
18245731Sbaban 	 * reset to IDMAP_NONE before we return to prevent xdr
18255731Sbaban 	 * from mis-interpreting req->id2 when it tries to free
18265731Sbaban 	 * the input argument. Other option is to allocate an
18275731Sbaban 	 * array of integers and use it instead for the batched
18285731Sbaban 	 * call. But why un-necessarily allocate memory. That may
18295731Sbaban 	 * be an option if req->id2.idtype cannot be re-used in
18305731Sbaban 	 * future.
18315731Sbaban 	 */
18324520Snw141292 
18334520Snw141292 	if (state->ad_nqueries == 0)
18344520Snw141292 		return (IDMAP_SUCCESS);
18354520Snw141292 
18366963Sbaban 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
18376963Sbaban 		req = &batch->idmap_mapping_batch_val[i];
18386963Sbaban 		res = &result->ids.ids_val[i];
18396963Sbaban 
18406963Sbaban 		/* Skip if not marked for AD lookup or already in error. */
18416963Sbaban 		if (!(req->direction & _IDMAP_F_LOOKUP_AD) ||
18426963Sbaban 		    res->retcode != IDMAP_SUCCESS)
18436963Sbaban 			continue;
18446963Sbaban 
18456963Sbaban 		/* Init status */
18466963Sbaban 		res->retcode = IDMAP_ERR_RETRIABLE_NET_ERR;
18476963Sbaban 	}
18486963Sbaban 
18494520Snw141292 retry:
1850*8040SBaban.Kenkre@Sun.COM 	RDLOCK_CONFIG();
18515731Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, state->ad_nqueries,
18525731Sbaban 	    &qs);
1853*8040SBaban.Kenkre@Sun.COM 	UNLOCK_CONFIG();
18545731Sbaban 	if (retcode != IDMAP_SUCCESS) {
1855*8040SBaban.Kenkre@Sun.COM 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
1856*8040SBaban.Kenkre@Sun.COM 		    retries++ < ADUTILS_DEF_NUM_RETRIES)
18575968Snw141292 			goto retry;
18586097Snw141292 		degrade_svc(1, "failed to create batch for AD lookup");
18595731Sbaban 		goto out;
18604520Snw141292 	}
18614520Snw141292 
18625317Sjp151216 	restore_svc();
18635317Sjp151216 
18645731Sbaban 	idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
18655731Sbaban 	    state->ad_unixgroup_attr);
18665731Sbaban 
18675731Sbaban 	for (i = 0, add = 0; i < batch->idmap_mapping_batch_len; i++) {
18684520Snw141292 		req = &batch->idmap_mapping_batch_val[i];
18694520Snw141292 		res = &result->ids.ids_val[i];
18706386Sjp151216 		how = &res->info.how;
18716386Sjp151216 
18725731Sbaban 		retcode = IDMAP_SUCCESS;
18735731Sbaban 		req->id2.idtype = IDMAP_NONE;
18745731Sbaban 
18755731Sbaban 		/* Skip if not marked for AD lookup */
18765731Sbaban 		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
18775731Sbaban 			continue;
18785731Sbaban 
18796963Sbaban 		if (res->retcode != IDMAP_ERR_RETRIABLE_NET_ERR)
18805731Sbaban 			continue;
18815731Sbaban 
18825731Sbaban 		if (IS_REQUEST_SID(*req, 1)) {
18836616Sdm199847 
18846616Sdm199847 			/* win2unix request: */
18856616Sdm199847 
18866616Sdm199847 			unixname = dn = attr = value = NULL;
18875731Sbaban 			eunixtype = _IDMAP_T_UNDEF;
18885731Sbaban 			if (req->id2name == NULL) {
18895731Sbaban 				if (res->id.idtype == IDMAP_UID &&
18905731Sbaban 				    AD_OR_MIXED(state->nm_siduid)) {
18915731Sbaban 					eunixtype = _IDMAP_T_USER;
18925731Sbaban 					unixname = &req->id2name;
18935731Sbaban 				} else if (res->id.idtype == IDMAP_GID &&
18945731Sbaban 				    AD_OR_MIXED(state->nm_sidgid)) {
18955731Sbaban 					eunixtype = _IDMAP_T_GROUP;
18965731Sbaban 					unixname = &req->id2name;
18975731Sbaban 				} else if (AD_OR_MIXED(state->nm_siduid) ||
18985731Sbaban 				    AD_OR_MIXED(state->nm_sidgid)) {
18995731Sbaban 					unixname = &req->id2name;
19005731Sbaban 				}
19015731Sbaban 			}
19025731Sbaban 			add = 1;
19036616Sdm199847 			if (unixname != NULL) {
19046616Sdm199847 				/*
19056616Sdm199847 				 * Get how info for DS-based name
19066616Sdm199847 				 * mapping only if AD or MIXED
19076616Sdm199847 				 * mode is enabled.
19086616Sdm199847 				 */
19096616Sdm199847 				idmap_info_free(&res->info);
19106616Sdm199847 				res->info.src = IDMAP_MAP_SRC_NEW;
19116616Sdm199847 				how->map_type = IDMAP_MAP_TYPE_DS_AD;
19126616Sdm199847 				dn = &how->idmap_how_u.ad.dn;
19136616Sdm199847 				attr = &how->idmap_how_u.ad.attr;
19146616Sdm199847 				value = &how->idmap_how_u.ad.value;
19156616Sdm199847 			}
19166616Sdm199847 			if (req->id1.idmap_id_u.sid.prefix != NULL) {
19176616Sdm199847 				/* Lookup AD by SID */
19186616Sdm199847 				retcode = idmap_sid2name_batch_add1(
19196616Sdm199847 				    qs, req->id1.idmap_id_u.sid.prefix,
19206616Sdm199847 				    &req->id1.idmap_id_u.sid.rid, eunixtype,
19216616Sdm199847 				    dn, attr, value,
19226616Sdm199847 				    (req->id1name == NULL) ?
19236616Sdm199847 				    &req->id1name : NULL,
19246616Sdm199847 				    (req->id1domain == NULL) ?
19256616Sdm199847 				    &req->id1domain : NULL,
19266616Sdm199847 				    (int *)&req->id2.idtype, unixname,
19276616Sdm199847 				    &res->retcode);
19286616Sdm199847 			} else {
19296616Sdm199847 				/* Lookup AD by winname */
19306616Sdm199847 				assert(req->id1name != NULL);
19316616Sdm199847 				retcode = idmap_name2sid_batch_add1(
19326616Sdm199847 				    qs, req->id1name, req->id1domain,
19336616Sdm199847 				    eunixtype,
19346616Sdm199847 				    dn, attr, value,
19356616Sdm199847 				    &req->id1name,
19366616Sdm199847 				    &req->id1.idmap_id_u.sid.prefix,
19376616Sdm199847 				    &req->id1.idmap_id_u.sid.rid,
19386616Sdm199847 				    (int *)&req->id2.idtype, unixname,
19396616Sdm199847 				    &res->retcode);
19406616Sdm199847 			}
19415731Sbaban 
19425731Sbaban 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
19436616Sdm199847 
19446616Sdm199847 			/* unix2win request: */
19455731Sbaban 
19465731Sbaban 			if (res->id.idmap_id_u.sid.prefix != NULL &&
19475731Sbaban 			    req->id2name != NULL) {
19485731Sbaban 				/* Already have SID and winname -- done */
19495731Sbaban 				res->retcode = IDMAP_SUCCESS;
19505731Sbaban 				continue;
19515731Sbaban 			}
19525731Sbaban 
19535731Sbaban 			if (res->id.idmap_id_u.sid.prefix != NULL) {
19545731Sbaban 				/*
19555731Sbaban 				 * SID but no winname -- lookup AD by
19565731Sbaban 				 * SID to get winname.
19576616Sdm199847 				 * how info is not needed here because
19586616Sdm199847 				 * we are not retrieving unixname from
19596616Sdm199847 				 * AD.
19605731Sbaban 				 */
19615731Sbaban 				add = 1;
19625731Sbaban 				retcode = idmap_sid2name_batch_add1(
19635731Sbaban 				    qs, res->id.idmap_id_u.sid.prefix,
19645731Sbaban 				    &res->id.idmap_id_u.sid.rid,
19656386Sjp151216 				    _IDMAP_T_UNDEF,
19666616Sdm199847 				    NULL, NULL, NULL,
19676386Sjp151216 				    &req->id2name,
19685731Sbaban 				    &req->id2domain, (int *)&req->id2.idtype,
19695731Sbaban 				    NULL, &res->retcode);
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 				add = 1;
19795731Sbaban 				retcode = idmap_name2sid_batch_add1(
19805731Sbaban 				    qs, req->id2name, req->id2domain,
19816386Sjp151216 				    _IDMAP_T_UNDEF,
19826616Sdm199847 				    NULL, NULL, NULL, NULL,
19835731Sbaban 				    &res->id.idmap_id_u.sid.prefix,
19845731Sbaban 				    &res->id.idmap_id_u.sid.rid,
19855731Sbaban 				    (int *)&req->id2.idtype, NULL,
19865731Sbaban 				    &res->retcode);
19875731Sbaban 			} else if (req->id1name != NULL) {
19885731Sbaban 				/*
19895731Sbaban 				 * No SID and no winname but we've unixname --
19905731Sbaban 				 * lookup AD by unixname to get SID.
19915731Sbaban 				 */
19925731Sbaban 				is_user = (IS_REQUEST_UID(*req)) ? 1 : 0;
19935731Sbaban 				if (res->id.idtype == IDMAP_USID)
19945731Sbaban 					is_wuser = 1;
19955731Sbaban 				else if (res->id.idtype == IDMAP_GSID)
19965731Sbaban 					is_wuser = 0;
19975731Sbaban 				else
19985731Sbaban 					is_wuser = is_user;
19995731Sbaban 				add = 1;
20006616Sdm199847 				idmap_info_free(&res->info);
20016386Sjp151216 				res->info.src = IDMAP_MAP_SRC_NEW;
20026386Sjp151216 				how->map_type = IDMAP_MAP_TYPE_DS_AD;
20035731Sbaban 				retcode = idmap_unixname2sid_batch_add1(
20045731Sbaban 				    qs, req->id1name, is_user, is_wuser,
20056386Sjp151216 				    &how->idmap_how_u.ad.dn,
20066386Sjp151216 				    &how->idmap_how_u.ad.attr,
20076386Sjp151216 				    &how->idmap_how_u.ad.value,
20085731Sbaban 				    &res->id.idmap_id_u.sid.prefix,
20095731Sbaban 				    &res->id.idmap_id_u.sid.rid,
20105731Sbaban 				    &req->id2name, &req->id2domain,
20115731Sbaban 				    (int *)&req->id2.idtype, &res->retcode);
20125731Sbaban 			}
20135731Sbaban 		}
20145731Sbaban 		if (retcode != IDMAP_SUCCESS) {
20155731Sbaban 			idmap_lookup_release_batch(&qs);
20165731Sbaban 			break;
20174520Snw141292 		}
20184520Snw141292 	}
20194520Snw141292 
20206963Sbaban 	if (retcode == IDMAP_SUCCESS) {
20216963Sbaban 		/* add keeps track if we added an entry to the batch */
20226963Sbaban 		if (add)
20236963Sbaban 			retcode = idmap_lookup_batch_end(&qs);
20246963Sbaban 		else
20256963Sbaban 			idmap_lookup_release_batch(&qs);
20266963Sbaban 	}
20275696Snw141292 
2028*8040SBaban.Kenkre@Sun.COM 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
2029*8040SBaban.Kenkre@Sun.COM 	    retries++ < ADUTILS_DEF_NUM_RETRIES)
20304520Snw141292 		goto retry;
20315317Sjp151216 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
20326097Snw141292 		degrade_svc(1, "some AD lookups timed out repeatedly");
20334520Snw141292 
20345731Sbaban 	if (retcode != IDMAP_SUCCESS)
20355731Sbaban 		idmapdlog(LOG_NOTICE, "Failed to batch AD lookup requests");
20364520Snw141292 
20374520Snw141292 out:
20385731Sbaban 	/*
20395731Sbaban 	 * This loop does the following:
20406616Sdm199847 	 * 1. Reset _IDMAP_F_LOOKUP_AD flag from the request.
20416616Sdm199847 	 * 2. Reset req->id2.idtype to IDMAP_NONE
20426616Sdm199847 	 * 3. If batch_start or batch_add failed then set the status
20436616Sdm199847 	 *    of each request marked for AD lookup to that error.
20446616Sdm199847 	 * 4. Evaluate the type of the AD object (i.e. user or group) and
20456616Sdm199847 	 *    update the idtype in request.
20465731Sbaban 	 */
20475731Sbaban 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
20485731Sbaban 		req = &batch->idmap_mapping_batch_val[i];
20495731Sbaban 		type = req->id2.idtype;
20505731Sbaban 		req->id2.idtype = IDMAP_NONE;
20515746Sbaban 		res = &result->ids.ids_val[i];
20526386Sjp151216 		how = &res->info.how;
20535731Sbaban 		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
20545731Sbaban 			continue;
20555731Sbaban 
20566616Sdm199847 		/* Reset AD lookup flag */
20576616Sdm199847 		req->direction &= ~(_IDMAP_F_LOOKUP_AD);
20586616Sdm199847 
20596616Sdm199847 		/*
20606616Sdm199847 		 * If batch_start or batch_add failed then set the status
20616616Sdm199847 		 * of each request marked for AD lookup to that error.
20626616Sdm199847 		 */
20635731Sbaban 		if (retcode != IDMAP_SUCCESS) {
20645731Sbaban 			res->retcode = retcode;
20655731Sbaban 			continue;
20665731Sbaban 		}
20675731Sbaban 
20685731Sbaban 		if (!add)
20695731Sbaban 			continue;
20705731Sbaban 
20716386Sjp151216 		if (res->retcode == IDMAP_ERR_NOTFOUND) {
20726386Sjp151216 			/* Nothing found - remove the preset info */
20736616Sdm199847 			idmap_info_free(&res->info);
20746386Sjp151216 		}
20756386Sjp151216 
20765731Sbaban 		if (IS_REQUEST_SID(*req, 1)) {
20775731Sbaban 			if (res->retcode != IDMAP_SUCCESS)
20785731Sbaban 				continue;
20796616Sdm199847 			/* Evaluate result type */
20805731Sbaban 			switch (type) {
20815731Sbaban 			case _IDMAP_T_USER:
20825731Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
20835731Sbaban 					res->id.idtype = IDMAP_UID;
20845731Sbaban 				req->id1.idtype = IDMAP_USID;
20855731Sbaban 				break;
20865731Sbaban 			case _IDMAP_T_GROUP:
20875731Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
20885731Sbaban 					res->id.idtype = IDMAP_GID;
20895731Sbaban 				req->id1.idtype = IDMAP_GSID;
20905731Sbaban 				break;
20915731Sbaban 			default:
20925731Sbaban 				res->retcode = IDMAP_ERR_SID;
20935731Sbaban 				break;
20945731Sbaban 			}
20956616Sdm199847 			if (res->retcode == IDMAP_SUCCESS &&
20966616Sdm199847 			    req->id1name != NULL &&
20976616Sdm199847 			    (req->id2name == NULL ||
20986616Sdm199847 			    res->id.idmap_id_u.uid == SENTINEL_PID) &&
20996616Sdm199847 			    NLDAP_MODE(res->id.idtype, state)) {
21006616Sdm199847 				req->direction |= _IDMAP_F_LOOKUP_NLDAP;
21016616Sdm199847 				state->nldap_nqueries++;
21026616Sdm199847 			}
21035731Sbaban 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
21045731Sbaban 			if (res->retcode != IDMAP_SUCCESS) {
21055731Sbaban 				if ((!(IDMAP_FATAL_ERROR(res->retcode))) &&
21065731Sbaban 				    res->id.idmap_id_u.sid.prefix == NULL &&
21075731Sbaban 				    req->id2name == NULL && /* no winname */
21085731Sbaban 				    req->id1name != NULL) /* unixname */
21095731Sbaban 					/*
21106616Sdm199847 					 * If AD lookup by unixname failed
21116616Sdm199847 					 * with non fatal error then clear
21126616Sdm199847 					 * the error (i.e set res->retcode
21136616Sdm199847 					 * to success). This allows the next
21146616Sdm199847 					 * pass to process other mapping
21156616Sdm199847 					 * mechanisms for this request.
21165731Sbaban 					 */
21175731Sbaban 					res->retcode = IDMAP_SUCCESS;
21185731Sbaban 				continue;
21195731Sbaban 			}
21206616Sdm199847 			/* Evaluate result type */
21215731Sbaban 			switch (type) {
21225731Sbaban 			case _IDMAP_T_USER:
21235731Sbaban 				if (res->id.idtype == IDMAP_SID)
21245731Sbaban 					res->id.idtype = IDMAP_USID;
21255731Sbaban 				break;
21265731Sbaban 			case _IDMAP_T_GROUP:
21275731Sbaban 				if (res->id.idtype == IDMAP_SID)
21285731Sbaban 					res->id.idtype = IDMAP_GSID;
21295731Sbaban 				break;
21305731Sbaban 			default:
21315731Sbaban 				res->retcode = IDMAP_ERR_SID;
21325731Sbaban 				break;
21335731Sbaban 			}
21345731Sbaban 		}
21355731Sbaban 	}
21365731Sbaban 
21375731Sbaban 	/* AD lookups done. Reset state->ad_nqueries and return */
21385731Sbaban 	state->ad_nqueries = 0;
21394520Snw141292 	return (retcode);
21404520Snw141292 }
21414520Snw141292 
21425696Snw141292 /*
21435696Snw141292  * Convention when processing win2unix requests:
21445696Snw141292  *
21455696Snw141292  * Windows identity:
21465696Snw141292  * req->id1name =
21475696Snw141292  *              winname if given otherwise winname found will be placed
21485696Snw141292  *              here.
21495696Snw141292  * req->id1domain =
21505696Snw141292  *              windomain if given otherwise windomain found will be
21515696Snw141292  *              placed here.
21525696Snw141292  * req->id1.idtype =
21535696Snw141292  *              Either IDMAP_SID/USID/GSID. If this is IDMAP_SID then it'll
21545696Snw141292  *              be set to IDMAP_USID/GSID depending upon whether the
21555696Snw141292  *              given SID is user or group respectively. The user/group-ness
21565696Snw141292  *              is determined either when looking up well-known SIDs table OR
21576616Sdm199847  *              if the SID is found in namecache OR by ad_lookup_one() OR by
21585696Snw141292  *              ad_lookup_batch().
21595696Snw141292  * req->id1..sid.[prefix, rid] =
21605696Snw141292  *              SID if given otherwise SID found will be placed here.
21615696Snw141292  *
21625696Snw141292  * Unix identity:
21635696Snw141292  * req->id2name =
21645696Snw141292  *              unixname found will be placed here.
21655696Snw141292  * req->id2domain =
21665696Snw141292  *              NOT USED
21675696Snw141292  * res->id.idtype =
21685696Snw141292  *              Target type initialized from req->id2.idtype. If
21695696Snw141292  *              it is IDMAP_POSIXID then actual type (IDMAP_UID/GID) found
21705696Snw141292  *              will be placed here.
21715696Snw141292  * res->id..[uid or gid] =
21725696Snw141292  *              UID/GID found will be placed here.
21735696Snw141292  *
21745696Snw141292  * Others:
21755696Snw141292  * res->retcode =
21765696Snw141292  *              Return status for this request will be placed here.
21775696Snw141292  * res->direction =
21785696Snw141292  *              Direction found will be placed here. Direction
21795696Snw141292  *              meaning whether the resultant mapping is valid
21805696Snw141292  *              only from win2unix or bi-directional.
21815696Snw141292  * req->direction =
21825696Snw141292  *              INTERNAL USE. Used by idmapd to set various
21835696Snw141292  *              flags (_IDMAP_F_xxxx) to aid in processing
21845696Snw141292  *              of the request.
21855696Snw141292  * req->id2.idtype =
21865696Snw141292  *              INTERNAL USE. Initially this is the requested target
21875696Snw141292  *              type and is used to initialize res->id.idtype.
21885696Snw141292  *              ad_lookup_batch() uses this field temporarily to store
21895696Snw141292  *              sid_type obtained by the batched AD lookups and after
21905696Snw141292  *              use resets it to IDMAP_NONE to prevent xdr from
21915696Snw141292  *              mis-interpreting the contents of req->id2.
21925696Snw141292  * req->id2..[uid or gid or sid] =
21935696Snw141292  *              NOT USED
21945696Snw141292  */
21955696Snw141292 
21965696Snw141292 /*
21975696Snw141292  * This function does the following:
21985696Snw141292  * 1. Lookup well-known SIDs table.
21995696Snw141292  * 2. Check if the given SID is a local-SID and if so extract UID/GID from it.
22005696Snw141292  * 3. Lookup cache.
22015696Snw141292  * 4. Check if the client does not want new mapping to be allocated
22025696Snw141292  *    in which case this pass is the final pass.
22035696Snw141292  * 5. Set AD lookup flag if it determines that the next stage needs
22045696Snw141292  *    to do AD lookup.
22055696Snw141292  */
22064520Snw141292 idmap_retcode
22076616Sdm199847 sid2pid_first_pass(lookup_state_t *state, idmap_mapping *req,
22085696Snw141292 		idmap_id_res *res)
22095696Snw141292 {
22104520Snw141292 	idmap_retcode	retcode;
22115731Sbaban 	int		wksid;
22125731Sbaban 
22135731Sbaban 	/* Initialize result */
22145731Sbaban 	res->id.idtype = req->id2.idtype;
22155731Sbaban 	res->id.idmap_id_u.uid = SENTINEL_PID;
22165731Sbaban 	res->direction = IDMAP_DIRECTION_UNDEF;
22175731Sbaban 	wksid = 0;
22184520Snw141292 
22195127Sdm199847 	if (EMPTY_STRING(req->id1.idmap_id_u.sid.prefix)) {
22205731Sbaban 		if (req->id1name == NULL) {
22215731Sbaban 			retcode = IDMAP_ERR_ARG;
22225731Sbaban 			goto out;
22235731Sbaban 		}
22245731Sbaban 		/* sanitize sidprefix */
22255731Sbaban 		free(req->id1.idmap_id_u.sid.prefix);
22265731Sbaban 		req->id1.idmap_id_u.sid.prefix = NULL;
22274520Snw141292 	}
22285731Sbaban 
22295731Sbaban 	/* Lookup well-known SIDs table */
22305731Sbaban 	retcode = lookup_wksids_sid2pid(req, res, &wksid);
22314520Snw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
22324520Snw141292 		goto out;
22334520Snw141292 
22345731Sbaban 	if (!wksid) {
2235*8040SBaban.Kenkre@Sun.COM 		/* Check if this is a localsid */
22365731Sbaban 		retcode = lookup_localsid2pid(req, res);
22375731Sbaban 		if (retcode != IDMAP_ERR_NOTFOUND)
22385731Sbaban 			goto out;
2239*8040SBaban.Kenkre@Sun.COM 
2240*8040SBaban.Kenkre@Sun.COM 		if (ALLOW_WK_OR_LOCAL_SIDS_ONLY(req)) {
2241*8040SBaban.Kenkre@Sun.COM 			retcode = IDMAP_ERR_NONEGENERATED;
2242*8040SBaban.Kenkre@Sun.COM 			goto out;
2243*8040SBaban.Kenkre@Sun.COM 		}
22445731Sbaban 	}
22455731Sbaban 
22465731Sbaban 	/* Lookup cache */
22476616Sdm199847 	retcode = lookup_cache_sid2pid(state->cache, req, res);
22484520Snw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
22494520Snw141292 		goto out;
22504520Snw141292 
22514520Snw141292 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req) || AVOID_NAMESERVICE(req)) {
22526386Sjp151216 		retcode = IDMAP_ERR_NONEGENERATED;
22534520Snw141292 		goto out;
22544520Snw141292 	}
22554520Snw141292 
22564520Snw141292 	/*
22575731Sbaban 	 * Failed to find non-expired entry in cache. Next step is
22585731Sbaban 	 * to determine if this request needs to be batched for AD lookup.
22595731Sbaban 	 *
22605731Sbaban 	 * At this point we have either sid or winname or both. If we don't
22615731Sbaban 	 * have both then lookup name_cache for the sid or winname
22625731Sbaban 	 * whichever is missing. If not found then this request will be
22635731Sbaban 	 * batched for AD lookup.
22644520Snw141292 	 */
22656616Sdm199847 	retcode = lookup_name_cache(state->cache, req, res);
22665731Sbaban 	if (retcode != IDMAP_SUCCESS && retcode != IDMAP_ERR_NOTFOUND)
22675731Sbaban 		goto out;
22684520Snw141292 
22694520Snw141292 	/*
22705731Sbaban 	 * Set the flag to indicate that we are not done yet so that
22715731Sbaban 	 * subsequent passes considers this request for name-based
22725731Sbaban 	 * mapping and ephemeral mapping.
22734520Snw141292 	 */
22745731Sbaban 	state->sid2pid_done = FALSE;
22755731Sbaban 	req->direction |= _IDMAP_F_NOTDONE;
22765731Sbaban 
22775731Sbaban 	/*
22785731Sbaban 	 * Even if we have both sid and winname, we still may need to batch
22795731Sbaban 	 * this request for AD lookup if we don't have unixname and
22805731Sbaban 	 * directory-based name mapping (AD or mixed) is enabled.
22815731Sbaban 	 * We avoid AD lookup for well-known SIDs because they don't have
22825731Sbaban 	 * regular AD objects.
22835731Sbaban 	 */
22845731Sbaban 	if (retcode != IDMAP_SUCCESS ||
22855731Sbaban 	    (!wksid && req->id2name == NULL &&
22865731Sbaban 	    AD_OR_MIXED_MODE(res->id.idtype, state))) {
22874520Snw141292 		retcode = IDMAP_SUCCESS;
22885731Sbaban 		req->direction |= _IDMAP_F_LOOKUP_AD;
22894520Snw141292 		state->ad_nqueries++;
22906616Sdm199847 	} else if (NLDAP_MODE(res->id.idtype, state)) {
22916616Sdm199847 		req->direction |= _IDMAP_F_LOOKUP_NLDAP;
22926616Sdm199847 		state->nldap_nqueries++;
22934520Snw141292 	}
22944520Snw141292 
22954520Snw141292 
22964520Snw141292 out:
22974520Snw141292 	res->retcode = idmap_stat4prot(retcode);
22985731Sbaban 	/*
22995731Sbaban 	 * If we are done and there was an error then set fallback pid
23005731Sbaban 	 * in the result.
23015731Sbaban 	 */
23025731Sbaban 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
23035731Sbaban 		res->id.idmap_id_u.uid = UID_NOBODY;
23044520Snw141292 	return (retcode);
23054520Snw141292 }
23064520Snw141292 
23074520Snw141292 /*
23084520Snw141292  * Generate SID using the following convention
23094520Snw141292  * 	<machine-sid-prefix>-<1000 + uid>
23104520Snw141292  * 	<machine-sid-prefix>-<2^31 + gid>
23114520Snw141292  */
23125696Snw141292 static
23135696Snw141292 idmap_retcode
23146386Sjp151216 generate_localsid(idmap_mapping *req, idmap_id_res *res, int is_user,
23156386Sjp151216 		int fallback)
23165696Snw141292 {
23175731Sbaban 	free(res->id.idmap_id_u.sid.prefix);
23185731Sbaban 	res->id.idmap_id_u.sid.prefix = NULL;
23195731Sbaban 
23205731Sbaban 	/*
23215731Sbaban 	 * Diagonal mapping for localSIDs not supported because of the
23225731Sbaban 	 * way we generate localSIDs.
23235731Sbaban 	 */
23245731Sbaban 	if (is_user && res->id.idtype == IDMAP_GSID)
23255731Sbaban 		return (IDMAP_ERR_NOMAPPING);
23265731Sbaban 	if (!is_user && res->id.idtype == IDMAP_USID)
23275731Sbaban 		return (IDMAP_ERR_NOMAPPING);
23285731Sbaban 
23295731Sbaban 	/* Skip 1000 UIDs */
23305731Sbaban 	if (is_user && req->id1.idmap_id_u.uid >
23315731Sbaban 	    (INT32_MAX - LOCALRID_MIN))
23325731Sbaban 		return (IDMAP_ERR_NOMAPPING);
23335731Sbaban 
23345731Sbaban 	RDLOCK_CONFIG();
23355731Sbaban 	/*
23365731Sbaban 	 * machine_sid is never NULL because if it is we won't be here.
23375731Sbaban 	 * No need to assert because stdrup(NULL) will core anyways.
23385731Sbaban 	 */
23395731Sbaban 	res->id.idmap_id_u.sid.prefix =
23405731Sbaban 	    strdup(_idmapdstate.cfg->pgcfg.machine_sid);
23415731Sbaban 	if (res->id.idmap_id_u.sid.prefix == NULL) {
23424520Snw141292 		UNLOCK_CONFIG();
23435731Sbaban 		idmapdlog(LOG_ERR, "Out of memory");
23445731Sbaban 		return (IDMAP_ERR_MEMORY);
23454520Snw141292 	}
23465731Sbaban 	UNLOCK_CONFIG();
23475731Sbaban 	res->id.idmap_id_u.sid.rid =
23485731Sbaban 	    (is_user) ? req->id1.idmap_id_u.uid + LOCALRID_MIN :
23495731Sbaban 	    req->id1.idmap_id_u.gid + INT32_MAX + 1;
23505731Sbaban 	res->direction = IDMAP_DIRECTION_BI;
23515731Sbaban 	if (res->id.idtype == IDMAP_SID)
23525731Sbaban 		res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
23535731Sbaban 
23546386Sjp151216 	if (!fallback && req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
23556386Sjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_LOCAL_SID;
23566386Sjp151216 		res->info.src = IDMAP_MAP_SRC_ALGORITHMIC;
23576386Sjp151216 	}
23586386Sjp151216 
23595731Sbaban 	/*
23605731Sbaban 	 * Don't update name_cache because local sids don't have
23615731Sbaban 	 * valid windows names.
23625731Sbaban 	 */
23635731Sbaban 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
23645731Sbaban 	return (IDMAP_SUCCESS);
23654520Snw141292 }
23664520Snw141292 
23675696Snw141292 static
23685696Snw141292 idmap_retcode
23695696Snw141292 lookup_localsid2pid(idmap_mapping *req, idmap_id_res *res)
23705696Snw141292 {
23714520Snw141292 	char		*sidprefix;
23724520Snw141292 	uint32_t	rid;
23734520Snw141292 	int		s;
23744520Snw141292 
23754520Snw141292 	/*
23764520Snw141292 	 * If the sidprefix == localsid then UID = last RID - 1000 or
23774520Snw141292 	 * GID = last RID - 2^31.
23784520Snw141292 	 */
23795731Sbaban 	if ((sidprefix = req->id1.idmap_id_u.sid.prefix) == NULL)
23805731Sbaban 		/* This means we are looking up by winname */
23815731Sbaban 		return (IDMAP_ERR_NOTFOUND);
23824520Snw141292 	rid = req->id1.idmap_id_u.sid.rid;
23834520Snw141292 
23844520Snw141292 	RDLOCK_CONFIG();
23855696Snw141292 	s = (_idmapdstate.cfg->pgcfg.machine_sid) ?
23865696Snw141292 	    strcasecmp(sidprefix, _idmapdstate.cfg->pgcfg.machine_sid) : 1;
23874520Snw141292 	UNLOCK_CONFIG();
23884520Snw141292 
23895731Sbaban 	/*
23905731Sbaban 	 * If the given sidprefix does not match machine_sid then this is
23915731Sbaban 	 * not a local SID.
23925731Sbaban 	 */
23935731Sbaban 	if (s != 0)
23945731Sbaban 		return (IDMAP_ERR_NOTFOUND);
23955731Sbaban 
23965731Sbaban 	switch (res->id.idtype) {
23975731Sbaban 	case IDMAP_UID:
23985731Sbaban 		if (rid > INT32_MAX || rid < LOCALRID_MIN)
23995731Sbaban 			return (IDMAP_ERR_ARG);
24005731Sbaban 		res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
24015731Sbaban 		break;
24025731Sbaban 	case IDMAP_GID:
24035731Sbaban 		if (rid <= INT32_MAX)
24045731Sbaban 			return (IDMAP_ERR_ARG);
24055731Sbaban 		res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
24065731Sbaban 		break;
24075731Sbaban 	case IDMAP_POSIXID:
24085731Sbaban 		if (rid > INT32_MAX) {
24094520Snw141292 			res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
24104520Snw141292 			res->id.idtype = IDMAP_GID;
24115731Sbaban 		} else if (rid < LOCALRID_MIN) {
24125731Sbaban 			return (IDMAP_ERR_ARG);
24135731Sbaban 		} else {
24145731Sbaban 			res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
24155731Sbaban 			res->id.idtype = IDMAP_UID;
24164520Snw141292 		}
24175731Sbaban 		break;
24185731Sbaban 	default:
24195731Sbaban 		return (IDMAP_ERR_NOTSUPPORTED);
24204520Snw141292 	}
24216386Sjp151216 	if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
24226386Sjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_LOCAL_SID;
24236386Sjp151216 		res->info.src = IDMAP_MAP_SRC_ALGORITHMIC;
24246386Sjp151216 	}
24255731Sbaban 	return (IDMAP_SUCCESS);
24264520Snw141292 }
24274520Snw141292 
24285731Sbaban /*
24295731Sbaban  * Name service lookup by unixname to get pid
24305731Sbaban  */
24315696Snw141292 static
24325696Snw141292 idmap_retcode
24335731Sbaban ns_lookup_byname(const char *name, const char *lower_name, idmap_id *id)
24345696Snw141292 {
24355696Snw141292 	struct passwd	pwd, *pwdp;
24365696Snw141292 	struct group	grp, *grpp;
24374520Snw141292 	char		buf[1024];
24384520Snw141292 	int		errnum;
24394520Snw141292 	const char	*me = "ns_lookup_byname";
24404520Snw141292 
24415731Sbaban 	switch (id->idtype) {
24425731Sbaban 	case IDMAP_UID:
24435696Snw141292 		pwdp = getpwnam_r(name, &pwd, buf, sizeof (buf));
24445731Sbaban 		if (pwdp == NULL && errno == 0 && lower_name != NULL &&
24455696Snw141292 		    name != lower_name && strcmp(name, lower_name) != 0)
24465696Snw141292 			pwdp = getpwnam_r(lower_name, &pwd, buf, sizeof (buf));
24475696Snw141292 		if (pwdp == NULL) {
24484520Snw141292 			errnum = errno;
24494520Snw141292 			idmapdlog(LOG_WARNING,
24505696Snw141292 			    "%s: getpwnam_r(%s) failed (%s).",
24515696Snw141292 			    me, name, errnum ? strerror(errnum) : "not found");
24524520Snw141292 			if (errnum == 0)
24534520Snw141292 				return (IDMAP_ERR_NOTFOUND);
24544520Snw141292 			else
24554520Snw141292 				return (IDMAP_ERR_INTERNAL);
24564520Snw141292 		}
24575731Sbaban 		id->idmap_id_u.uid = pwd.pw_uid;
24585731Sbaban 		break;
24595731Sbaban 	case IDMAP_GID:
24605696Snw141292 		grpp = getgrnam_r(name, &grp, buf, sizeof (buf));
24615731Sbaban 		if (grpp == NULL && errno == 0 && lower_name != NULL &&
24625696Snw141292 		    name != lower_name && strcmp(name, lower_name) != 0)
24635696Snw141292 			grpp = getgrnam_r(lower_name, &grp, buf, sizeof (buf));
24645696Snw141292 		if (grpp == NULL) {
24654520Snw141292 			errnum = errno;
24664520Snw141292 			idmapdlog(LOG_WARNING,
24675696Snw141292 			    "%s: getgrnam_r(%s) failed (%s).",
24685696Snw141292 			    me, name, errnum ? strerror(errnum) : "not found");
24694520Snw141292 			if (errnum == 0)
24704520Snw141292 				return (IDMAP_ERR_NOTFOUND);
24714520Snw141292 			else
24724520Snw141292 				return (IDMAP_ERR_INTERNAL);
24734520Snw141292 		}
24745731Sbaban 		id->idmap_id_u.gid = grp.gr_gid;
24755731Sbaban 		break;
24765731Sbaban 	default:
24775731Sbaban 		return (IDMAP_ERR_ARG);
24784520Snw141292 	}
24794520Snw141292 	return (IDMAP_SUCCESS);
24804520Snw141292 }
24814520Snw141292 
24825731Sbaban 
24835731Sbaban /*
24845731Sbaban  * Name service lookup by pid to get unixname
24855731Sbaban  */
24865731Sbaban static
24875731Sbaban idmap_retcode
24885731Sbaban ns_lookup_bypid(uid_t pid, int is_user, char **unixname)
24895731Sbaban {
24905731Sbaban 	struct passwd	pwd;
24915731Sbaban 	struct group	grp;
24925731Sbaban 	char		buf[1024];
24935731Sbaban 	int		errnum;
24945731Sbaban 	const char	*me = "ns_lookup_bypid";
24955731Sbaban 
24965731Sbaban 	if (is_user) {
24975731Sbaban 		errno = 0;
24985731Sbaban 		if (getpwuid_r(pid, &pwd, buf, sizeof (buf)) == NULL) {
24995731Sbaban 			errnum = errno;
25005731Sbaban 			idmapdlog(LOG_WARNING,
25015731Sbaban 			    "%s: getpwuid_r(%u) failed (%s).",
25025731Sbaban 			    me, pid, errnum ? strerror(errnum) : "not found");
25035731Sbaban 			if (errnum == 0)
25045731Sbaban 				return (IDMAP_ERR_NOTFOUND);
25055731Sbaban 			else
25065731Sbaban 				return (IDMAP_ERR_INTERNAL);
25075731Sbaban 		}
25085731Sbaban 		*unixname = strdup(pwd.pw_name);
25095731Sbaban 	} else {
25105731Sbaban 		errno = 0;
25115731Sbaban 		if (getgrgid_r(pid, &grp, buf, sizeof (buf)) == NULL) {
25125731Sbaban 			errnum = errno;
25135731Sbaban 			idmapdlog(LOG_WARNING,
25145731Sbaban 			    "%s: getgrgid_r(%u) failed (%s).",
25155731Sbaban 			    me, pid, errnum ? strerror(errnum) : "not found");
25165731Sbaban 			if (errnum == 0)
25175731Sbaban 				return (IDMAP_ERR_NOTFOUND);
25185731Sbaban 			else
25195731Sbaban 				return (IDMAP_ERR_INTERNAL);
25205731Sbaban 		}
25215731Sbaban 		*unixname = strdup(grp.gr_name);
25225731Sbaban 	}
25235731Sbaban 	if (*unixname == NULL)
25245731Sbaban 		return (IDMAP_ERR_MEMORY);
25255731Sbaban 	return (IDMAP_SUCCESS);
25265731Sbaban }
25275731Sbaban 
25284520Snw141292 /*
25294520Snw141292  * Name-based mapping
25304520Snw141292  *
25314520Snw141292  * Case 1: If no rule matches do ephemeral
25324520Snw141292  *
25334520Snw141292  * Case 2: If rule matches and unixname is "" then return no mapping.
25344520Snw141292  *
25354520Snw141292  * Case 3: If rule matches and unixname is specified then lookup name
25364520Snw141292  *  service using the unixname. If unixname not found then return no mapping.
25374520Snw141292  *
25384520Snw141292  * Case 4: If rule matches and unixname is * then lookup name service
25394520Snw141292  *  using winname as the unixname. If unixname not found then process
25404520Snw141292  *  other rules using the lookup order. If no other rule matches then do
25414520Snw141292  *  ephemeral. Otherwise, based on the matched rule do Case 2 or 3 or 4.
25424520Snw141292  *  This allows us to specify a fallback unixname per _domain_ or no mapping
25434520Snw141292  *  instead of the default behaviour of doing ephemeral mapping.
25444520Snw141292  *
25454520Snw141292  * Example 1:
25464520Snw141292  * *@sfbay == *
25474520Snw141292  * If looking up windows users foo@sfbay and foo does not exists in
25484520Snw141292  * the name service then foo@sfbay will be mapped to an ephemeral id.
25494520Snw141292  *
25504520Snw141292  * Example 2:
25514520Snw141292  * *@sfbay == *
25524520Snw141292  * *@sfbay => guest
25534520Snw141292  * If looking up windows users foo@sfbay and foo does not exists in
25544520Snw141292  * the name service then foo@sfbay will be mapped to guest.
25554520Snw141292  *
25564520Snw141292  * Example 3:
25574520Snw141292  * *@sfbay == *
25584520Snw141292  * *@sfbay => ""
25594520Snw141292  * If looking up windows users foo@sfbay and foo does not exists in
25604520Snw141292  * the name service then we will return no mapping for foo@sfbay.
25614520Snw141292  *
25624520Snw141292  */
25635696Snw141292 static
25645696Snw141292 idmap_retcode
25656616Sdm199847 name_based_mapping_sid2pid(lookup_state_t *state,
25666616Sdm199847 		idmap_mapping *req, idmap_id_res *res)
25675696Snw141292 {
25685696Snw141292 	const char	*unixname, *windomain;
25695696Snw141292 	char		*sql = NULL, *errmsg = NULL, *lower_winname = NULL;
25704520Snw141292 	idmap_retcode	retcode;
25715696Snw141292 	char		*end, *lower_unixname, *winname;
25724520Snw141292 	const char	**values;
25734520Snw141292 	sqlite_vm	*vm = NULL;
25745696Snw141292 	int		ncol, r, i, is_user, is_wuser;
25756386Sjp151216 	idmap_namerule	*rule = &res->info.how.idmap_how_u.rule;
25766386Sjp151216 	int		direction;
25774520Snw141292 	const char	*me = "name_based_mapping_sid2pid";
25784520Snw141292 
25795731Sbaban 	assert(req->id1name != NULL); /* We have winname */
25805731Sbaban 	assert(req->id2name == NULL); /* We don't have unixname */
25815731Sbaban 
25825064Sdm199847 	winname = req->id1name;
25835064Sdm199847 	windomain = req->id1domain;
25845696Snw141292 
25855696Snw141292 	switch (req->id1.idtype) {
25865696Snw141292 	case IDMAP_USID:
25875696Snw141292 		is_wuser = 1;
25885696Snw141292 		break;
25895696Snw141292 	case IDMAP_GSID:
25905696Snw141292 		is_wuser = 0;
25915696Snw141292 		break;
25925696Snw141292 	default:
25935731Sbaban 		idmapdlog(LOG_ERR, "%s: Unable to determine if the "
25945731Sbaban 		    "given Windows id is user or group.", me);
25955696Snw141292 		return (IDMAP_ERR_INTERNAL);
25965696Snw141292 	}
25975696Snw141292 
25985731Sbaban 	switch (res->id.idtype) {
25995696Snw141292 	case IDMAP_UID:
26005696Snw141292 		is_user = 1;
26015696Snw141292 		break;
26025696Snw141292 	case IDMAP_GID:
26035696Snw141292 		is_user = 0;
26045696Snw141292 		break;
26055696Snw141292 	case IDMAP_POSIXID:
26065696Snw141292 		is_user = is_wuser;
26075696Snw141292 		res->id.idtype = is_user ? IDMAP_UID : IDMAP_GID;
26085696Snw141292 		break;
26095696Snw141292 	}
26104520Snw141292 
26114520Snw141292 	i = 0;
26126616Sdm199847 	if (windomain == NULL)
26134864Sbaban 		windomain = "";
26146950Sbaban 	else if (state->defdom != NULL &&
26156950Sbaban 	    strcasecmp(state->defdom, windomain) == 0)
26166616Sdm199847 		i = 1;
26174520Snw141292 
26185696Snw141292 	if ((lower_winname = tolower_u8(winname)) == NULL)
26195696Snw141292 		lower_winname = winname;    /* hope for the best */
26204520Snw141292 	sql = sqlite_mprintf(
26216386Sjp151216 	    "SELECT unixname, u2w_order, winname_display, windomain, is_nt4 "
26226386Sjp151216 	    "FROM namerules WHERE "
26235696Snw141292 	    "w2u_order > 0 AND is_user = %d AND is_wuser = %d AND "
26245696Snw141292 	    "(winname = %Q OR winname = '*') AND "
26255696Snw141292 	    "(windomain = %Q OR windomain = '*' %s) "
26265696Snw141292 	    "ORDER BY w2u_order ASC;",
26275696Snw141292 	    is_user, is_wuser, lower_winname, windomain,
26285696Snw141292 	    i ? "OR windomain ISNULL OR windomain = ''" : "");
26294520Snw141292 	if (sql == NULL) {
26304520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
26314520Snw141292 		retcode = IDMAP_ERR_MEMORY;
26324520Snw141292 		goto out;
26334520Snw141292 	}
26344520Snw141292 
26356616Sdm199847 	if (sqlite_compile(state->db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
26364520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
26375696Snw141292 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
26385696Snw141292 		    CHECK_NULL(errmsg));
26394520Snw141292 		sqlite_freemem(errmsg);
26404520Snw141292 		goto out;
26414520Snw141292 	}
26424520Snw141292 
26436386Sjp151216 	for (;;) {
26444520Snw141292 		r = sqlite_step(vm, &ncol, &values, NULL);
26454884Sjp151216 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
26464884Sjp151216 
26474884Sjp151216 		if (r == SQLITE_ROW) {
26486386Sjp151216 			if (ncol < 5) {
26494520Snw141292 				retcode = IDMAP_ERR_INTERNAL;
26504520Snw141292 				goto out;
26514520Snw141292 			}
26524520Snw141292 			if (values[0] == NULL) {
26534520Snw141292 				retcode = IDMAP_ERR_INTERNAL;
26544520Snw141292 				goto out;
26554520Snw141292 			}
26564520Snw141292 
26576386Sjp151216 			if (values[1] != NULL)
26586386Sjp151216 				direction =
26596386Sjp151216 				    (strtol(values[1], &end, 10) == 0)?
26606386Sjp151216 				    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
26616386Sjp151216 			else
26626386Sjp151216 				direction = IDMAP_DIRECTION_W2U;
26636386Sjp151216 
26644520Snw141292 			if (EMPTY_NAME(values[0])) {
26656386Sjp151216 				idmap_namerule_set(rule, values[3], values[2],
26666386Sjp151216 				    values[0], is_wuser, is_user,
26676386Sjp151216 				    strtol(values[4], &end, 10),
26686386Sjp151216 				    direction);
26694520Snw141292 				retcode = IDMAP_ERR_NOMAPPING;
26704520Snw141292 				goto out;
26714520Snw141292 			}
26726386Sjp151216 
26736386Sjp151216 			if (values[0][0] == '*') {
26746386Sjp151216 				unixname = winname;
26756386Sjp151216 				lower_unixname = lower_winname;
26766386Sjp151216 			} else {
26776386Sjp151216 				unixname = values[0];
26786386Sjp151216 				lower_unixname = NULL;
26796386Sjp151216 			}
26806386Sjp151216 
26815731Sbaban 			retcode = ns_lookup_byname(unixname, lower_unixname,
26825731Sbaban 			    &res->id);
26834520Snw141292 			if (retcode == IDMAP_ERR_NOTFOUND) {
26846386Sjp151216 				if (values[0][0] == '*')
26854520Snw141292 					/* Case 4 */
26864520Snw141292 					continue;
26876386Sjp151216 				else {
26884520Snw141292 					/* Case 3 */
26896386Sjp151216 					idmap_namerule_set(rule, values[3],
26906386Sjp151216 					    values[2], values[0], is_wuser,
26916386Sjp151216 					    is_user,
26926386Sjp151216 					    strtol(values[4], &end, 10),
26936386Sjp151216 					    direction);
26944520Snw141292 					retcode = IDMAP_ERR_NOMAPPING;
26956386Sjp151216 				}
26964520Snw141292 			}
26974520Snw141292 			goto out;
26984520Snw141292 		} else if (r == SQLITE_DONE) {
26994520Snw141292 			retcode = IDMAP_ERR_NOTFOUND;
27004520Snw141292 			goto out;
27014520Snw141292 		} else {
27024520Snw141292 			(void) sqlite_finalize(vm, &errmsg);
27034520Snw141292 			vm = NULL;
27045696Snw141292 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
27055696Snw141292 			    CHECK_NULL(errmsg));
27064520Snw141292 			sqlite_freemem(errmsg);
27074520Snw141292 			retcode = IDMAP_ERR_INTERNAL;
27084520Snw141292 			goto out;
27094520Snw141292 		}
27104520Snw141292 	}
27114520Snw141292 
27124520Snw141292 out:
27136386Sjp151216 	if (sql != NULL)
27146386Sjp151216 		sqlite_freemem(sql);
27156386Sjp151216 	res->info.how.map_type = IDMAP_MAP_TYPE_RULE_BASED;
27164520Snw141292 	if (retcode == IDMAP_SUCCESS) {
27174864Sbaban 		if (values[1] != NULL)
27184520Snw141292 			res->direction =
27194644Sbaban 			    (strtol(values[1], &end, 10) == 0)?
27204644Sbaban 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
27214520Snw141292 		else
27224644Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
27236386Sjp151216 
27245064Sdm199847 		req->id2name = strdup(unixname);
27256616Sdm199847 		if (req->id2name == NULL) {
27266616Sdm199847 			retcode = IDMAP_ERR_MEMORY;
27276616Sdm199847 		}
27286616Sdm199847 	}
27296616Sdm199847 
27306616Sdm199847 	if (retcode == IDMAP_SUCCESS) {
27316386Sjp151216 		idmap_namerule_set(rule, values[3], values[2],
27326386Sjp151216 		    values[0], is_wuser, is_user, strtol(values[4], &end, 10),
27336386Sjp151216 		    res->direction);
27346386Sjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
27354520Snw141292 	}
27366616Sdm199847 
27375696Snw141292 	if (lower_winname != NULL && lower_winname != winname)
27385696Snw141292 		free(lower_winname);
27394864Sbaban 	if (vm != NULL)
27404520Snw141292 		(void) sqlite_finalize(vm, NULL);
27414520Snw141292 	return (retcode);
27424520Snw141292 }
27434520Snw141292 
27444520Snw141292 static
27454520Snw141292 int
27464520Snw141292 get_next_eph_uid(uid_t *next_uid)
27474520Snw141292 {
27484520Snw141292 	uid_t uid;
27494520Snw141292 	gid_t gid;
27504520Snw141292 	int err;
27514520Snw141292 
27524520Snw141292 	*next_uid = (uid_t)-1;
27534520Snw141292 	uid = _idmapdstate.next_uid++;
27544520Snw141292 	if (uid >= _idmapdstate.limit_uid) {
27554520Snw141292 		if ((err = allocids(0, 8192, &uid, 0, &gid)) != 0)
27564520Snw141292 			return (err);
27574520Snw141292 
27584520Snw141292 		_idmapdstate.limit_uid = uid + 8192;
27594520Snw141292 		_idmapdstate.next_uid = uid;
27604520Snw141292 	}
27614520Snw141292 	*next_uid = uid;
27624520Snw141292 
27634520Snw141292 	return (0);
27644520Snw141292 }
27654520Snw141292 
27664520Snw141292 static
27674520Snw141292 int
27684520Snw141292 get_next_eph_gid(gid_t *next_gid)
27694520Snw141292 {
27704520Snw141292 	uid_t uid;
27714520Snw141292 	gid_t gid;
27724520Snw141292 	int err;
27734520Snw141292 
27744520Snw141292 	*next_gid = (uid_t)-1;
27754520Snw141292 	gid = _idmapdstate.next_gid++;
27764520Snw141292 	if (gid >= _idmapdstate.limit_gid) {
27774520Snw141292 		if ((err = allocids(0, 0, &uid, 8192, &gid)) != 0)
27784520Snw141292 			return (err);
27794520Snw141292 
27804520Snw141292 		_idmapdstate.limit_gid = gid + 8192;
27814520Snw141292 		_idmapdstate.next_gid = gid;
27824520Snw141292 	}
27834520Snw141292 	*next_gid = gid;
27844520Snw141292 
27854520Snw141292 	return (0);
27864520Snw141292 }
27874520Snw141292 
27884864Sbaban static
27894864Sbaban int
27905696Snw141292 gethash(const char *str, uint32_t num, uint_t htsize)
27915696Snw141292 {
27924864Sbaban 	uint_t  hval, i, len;
27934864Sbaban 
27944864Sbaban 	if (str == NULL)
27954864Sbaban 		return (0);
27964864Sbaban 	for (len = strlen(str), hval = 0, i = 0; i < len; i++) {
27974864Sbaban 		hval += str[i];
27984864Sbaban 		hval += (hval << 10);
27994864Sbaban 		hval ^= (hval >> 6);
28004864Sbaban 	}
28014864Sbaban 	for (str = (const char *)&num, i = 0; i < sizeof (num); i++) {
28024864Sbaban 		hval += str[i];
28034864Sbaban 		hval += (hval << 10);
28044864Sbaban 		hval ^= (hval >> 6);
28054864Sbaban 	}
28064864Sbaban 	hval += (hval << 3);
28074864Sbaban 	hval ^= (hval >> 11);
28084864Sbaban 	hval += (hval << 15);
28094864Sbaban 	return (hval % htsize);
28104864Sbaban }
28114864Sbaban 
28124864Sbaban static
28134864Sbaban int
28144864Sbaban get_from_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid,
28155696Snw141292 		uid_t *pid)
28165696Snw141292 {
28174864Sbaban 	uint_t		next, key;
28184864Sbaban 	uint_t		htsize = state->sid_history_size;
28194864Sbaban 	idmap_sid	*sid;
28204864Sbaban 
28214864Sbaban 	next = gethash(prefix, rid, htsize);
28224864Sbaban 	while (next != htsize) {
28234864Sbaban 		key = state->sid_history[next].key;
28244864Sbaban 		if (key == htsize)
28254864Sbaban 			return (0);
28264864Sbaban 		sid = &state->batch->idmap_mapping_batch_val[key].id1.
28274864Sbaban 		    idmap_id_u.sid;
28284864Sbaban 		if (sid->rid == rid && strcmp(sid->prefix, prefix) == 0) {
28294864Sbaban 			*pid = state->result->ids.ids_val[key].id.
28304864Sbaban 			    idmap_id_u.uid;
28314864Sbaban 			return (1);
28324864Sbaban 		}
28334864Sbaban 		next = state->sid_history[next].next;
28344864Sbaban 	}
28354864Sbaban 	return (0);
28364864Sbaban }
28374864Sbaban 
28384864Sbaban static
28394864Sbaban void
28405696Snw141292 add_to_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid)
28415696Snw141292 {
28424864Sbaban 	uint_t		hash, next;
28434864Sbaban 	uint_t		htsize = state->sid_history_size;
28444864Sbaban 
28454864Sbaban 	hash = next = gethash(prefix, rid, htsize);
28464864Sbaban 	while (state->sid_history[next].key != htsize) {
28474864Sbaban 		next++;
28484864Sbaban 		next %= htsize;
28494864Sbaban 	}
28504864Sbaban 	state->sid_history[next].key = state->curpos;
28514864Sbaban 	if (hash == next)
28524864Sbaban 		return;
28534864Sbaban 	state->sid_history[next].next = state->sid_history[hash].next;
28544864Sbaban 	state->sid_history[hash].next = next;
28554864Sbaban }
28564520Snw141292 
28575731Sbaban void
28585731Sbaban cleanup_lookup_state(lookup_state_t *state)
28595731Sbaban {
28605731Sbaban 	free(state->sid_history);
28615731Sbaban 	free(state->ad_unixuser_attr);
28625731Sbaban 	free(state->ad_unixgroup_attr);
28636616Sdm199847 	free(state->nldap_winname_attr);
28646616Sdm199847 	free(state->defdom);
28655731Sbaban }
28665731Sbaban 
28674520Snw141292 /* ARGSUSED */
28684520Snw141292 static
28694520Snw141292 idmap_retcode
28706616Sdm199847 dynamic_ephemeral_mapping(lookup_state_t *state,
28715696Snw141292 		idmap_mapping *req, idmap_id_res *res)
28725696Snw141292 {
28734520Snw141292 
28744520Snw141292 	uid_t		next_pid;
28754520Snw141292 
28764864Sbaban 	res->direction = IDMAP_DIRECTION_BI;
28774864Sbaban 
28786386Sjp151216 	if (IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
28796386Sjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
28806386Sjp151216 		res->info.src = IDMAP_MAP_SRC_CACHE;
28814864Sbaban 		return (IDMAP_SUCCESS);
28826386Sjp151216 	}
28834864Sbaban 
28844864Sbaban 	if (state->sid_history != NULL &&
28854864Sbaban 	    get_from_sid_history(state, req->id1.idmap_id_u.sid.prefix,
28864864Sbaban 	    req->id1.idmap_id_u.sid.rid, &next_pid)) {
28874864Sbaban 		res->id.idmap_id_u.uid = next_pid;
28886386Sjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
28896386Sjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
28904864Sbaban 		return (IDMAP_SUCCESS);
28914864Sbaban 	}
28924864Sbaban 
28934864Sbaban 	if (res->id.idtype == IDMAP_UID) {
28944520Snw141292 		if (get_next_eph_uid(&next_pid) != 0)
28954520Snw141292 			return (IDMAP_ERR_INTERNAL);
28964520Snw141292 		res->id.idmap_id_u.uid = next_pid;
28974520Snw141292 	} else {
28984520Snw141292 		if (get_next_eph_gid(&next_pid) != 0)
28994520Snw141292 			return (IDMAP_ERR_INTERNAL);
29004520Snw141292 		res->id.idmap_id_u.gid = next_pid;
29014520Snw141292 	}
29024520Snw141292 
29036386Sjp151216 	res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
29046386Sjp151216 	res->info.src = IDMAP_MAP_SRC_NEW;
29054864Sbaban 	if (state->sid_history != NULL)
29064864Sbaban 		add_to_sid_history(state, req->id1.idmap_id_u.sid.prefix,
29074864Sbaban 		    req->id1.idmap_id_u.sid.rid);
29084864Sbaban 
29094520Snw141292 	return (IDMAP_SUCCESS);
29104520Snw141292 }
29114520Snw141292 
29124520Snw141292 idmap_retcode
29136616Sdm199847 sid2pid_second_pass(lookup_state_t *state,
29145696Snw141292 		idmap_mapping *req, idmap_id_res *res)
29155696Snw141292 {
29164520Snw141292 	idmap_retcode	retcode;
29174520Snw141292 
29184520Snw141292 	/* Check if second pass is needed */
29195731Sbaban 	if (ARE_WE_DONE(req->direction))
29204520Snw141292 		return (res->retcode);
29214520Snw141292 
29224520Snw141292 	/* Get status from previous pass */
29235731Sbaban 	retcode = res->retcode;
29247031Snw141292 	if (retcode != IDMAP_SUCCESS && state->eph_map_unres_sids &&
29257031Snw141292 	    !EMPTY_STRING(req->id1.idmap_id_u.sid.prefix) &&
29267031Snw141292 	    EMPTY_STRING(req->id1name)) {
29277031Snw141292 		/*
29287031Snw141292 		 * We are asked to map an unresolvable SID to a UID or
29297031Snw141292 		 * GID, but, which?  We'll treat all unresolvable SIDs
29307031Snw141292 		 * as users unless the caller specified which of a UID
29317031Snw141292 		 * or GID they want.
29327031Snw141292 		 */
29337818SNicolas.Williams@Sun.COM 		if (req->id1.idtype == IDMAP_SID)
29347818SNicolas.Williams@Sun.COM 			req->id1.idtype = IDMAP_USID;
29357031Snw141292 		if (res->id.idtype == IDMAP_POSIXID)
29367031Snw141292 			res->id.idtype = IDMAP_UID;
29377031Snw141292 		goto do_eph;
29387031Snw141292 	}
29395731Sbaban 	if (retcode != IDMAP_SUCCESS)
29405731Sbaban 		goto out;
29415731Sbaban 
29425731Sbaban 	/*
29435731Sbaban 	 * If directory-based name mapping is enabled then the unixname
29445731Sbaban 	 * may already have been retrieved from the AD object (AD-mode or
29455731Sbaban 	 * mixed-mode) or from native LDAP object (nldap-mode) -- done.
29465731Sbaban 	 */
29475731Sbaban 	if (req->id2name != NULL) {
29485731Sbaban 		assert(res->id.idtype != IDMAP_POSIXID);
29495731Sbaban 		if (AD_MODE(res->id.idtype, state))
29505731Sbaban 			res->direction = IDMAP_DIRECTION_BI;
29515731Sbaban 		else if (NLDAP_MODE(res->id.idtype, state))
29525731Sbaban 			res->direction = IDMAP_DIRECTION_BI;
29535731Sbaban 		else if (MIXED_MODE(res->id.idtype, state))
29545731Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
29555731Sbaban 
29565731Sbaban 		/*
29575731Sbaban 		 * Special case: (1) If the ad_unixuser_attr and
29585731Sbaban 		 * ad_unixgroup_attr uses the same attribute
29595731Sbaban 		 * name and (2) if this is a diagonal mapping
29605731Sbaban 		 * request and (3) the unixname has been retrieved
29615731Sbaban 		 * from the AD object -- then we ignore it and fallback
29625731Sbaban 		 * to name-based mapping rules and ephemeral mapping
29635731Sbaban 		 *
29645731Sbaban 		 * Example:
29655731Sbaban 		 *  Properties:
29665731Sbaban 		 *    config/ad_unixuser_attr = "unixname"
29675731Sbaban 		 *    config/ad_unixgroup_attr = "unixname"
29685731Sbaban 		 *  AD user object:
29695731Sbaban 		 *    dn: cn=bob ...
29705731Sbaban 		 *    objectclass: user
29715731Sbaban 		 *    sam: bob
29725731Sbaban 		 *    unixname: bob1234
29735731Sbaban 		 *  AD group object:
29745731Sbaban 		 *    dn: cn=winadmins ...
29755731Sbaban 		 *    objectclass: group
29765731Sbaban 		 *    sam: winadmins
29775731Sbaban 		 *    unixname: unixadmins
29785731Sbaban 		 *
29795731Sbaban 		 *  In this example whether "unixname" refers to a unixuser
29805731Sbaban 		 *  or unixgroup depends upon the AD object.
29815731Sbaban 		 *
29825731Sbaban 		 * $idmap show -c winname:bob gid
29835731Sbaban 		 *    AD lookup by "samAccountName=bob" for
29845731Sbaban 		 *    "ad_unixgroup_attr (i.e unixname)" for directory-based
29855731Sbaban 		 *    mapping would get "bob1234" which is not what we want.
29865731Sbaban 		 *    Now why not getgrnam_r("bob1234") and use it if it
29875731Sbaban 		 *    is indeed a unixgroup? That's because Unix can have
29885731Sbaban 		 *    users and groups with the same name and we clearly
29895731Sbaban 		 *    don't know the intention of the admin here.
29905731Sbaban 		 *    Therefore we ignore this and fallback to name-based
29915731Sbaban 		 *    mapping rules or ephemeral mapping.
29925731Sbaban 		 */
29935731Sbaban 		if ((AD_MODE(res->id.idtype, state) ||
29945731Sbaban 		    MIXED_MODE(res->id.idtype, state)) &&
29955731Sbaban 		    state->ad_unixuser_attr != NULL &&
29965731Sbaban 		    state->ad_unixgroup_attr != NULL &&
29975731Sbaban 		    strcasecmp(state->ad_unixuser_attr,
29985731Sbaban 		    state->ad_unixgroup_attr) == 0 &&
29995731Sbaban 		    ((req->id1.idtype == IDMAP_USID &&
30005731Sbaban 		    res->id.idtype == IDMAP_GID) ||
30015731Sbaban 		    (req->id1.idtype == IDMAP_GSID &&
30025731Sbaban 		    res->id.idtype == IDMAP_UID))) {
30035731Sbaban 			free(req->id2name);
30045731Sbaban 			req->id2name = NULL;
30055731Sbaban 			res->id.idmap_id_u.uid = SENTINEL_PID;
30065731Sbaban 			/* fallback */
30075731Sbaban 		} else {
30085731Sbaban 			if (res->id.idmap_id_u.uid == SENTINEL_PID)
30095731Sbaban 				retcode = ns_lookup_byname(req->id2name,
30105731Sbaban 				    NULL, &res->id);
30115731Sbaban 			/*
30126616Sdm199847 			 * If ns_lookup_byname() fails that means the
30136616Sdm199847 			 * unixname (req->id2name), which was obtained
30146616Sdm199847 			 * from the AD object by directory-based mapping,
30156616Sdm199847 			 * is not a valid Unix user/group and therefore
30166616Sdm199847 			 * we return the error to the client instead of
30176616Sdm199847 			 * doing rule-based mapping or ephemeral mapping.
30186616Sdm199847 			 * This way the client can detect the issue.
30195731Sbaban 			 */
30205731Sbaban 			goto out;
30214520Snw141292 		}
30224520Snw141292 	}
30234520Snw141292 
30246386Sjp151216 	/* Free any mapping info from Directory based mapping */
30256386Sjp151216 	if (res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN)
30266386Sjp151216 		idmap_info_free(&res->info);
30276386Sjp151216 
30285731Sbaban 	/*
30295731Sbaban 	 * If we don't have unixname then evaluate local name-based
30305731Sbaban 	 * mapping rules.
30315731Sbaban 	 */
30326616Sdm199847 	retcode = name_based_mapping_sid2pid(state, req, res);
30335731Sbaban 	if (retcode != IDMAP_ERR_NOTFOUND)
30344520Snw141292 		goto out;
30354520Snw141292 
30367031Snw141292 do_eph:
30375731Sbaban 	/* If not found, do ephemeral mapping */
30386616Sdm199847 	retcode = dynamic_ephemeral_mapping(state, req, res);
30394520Snw141292 
30404520Snw141292 out:
30414520Snw141292 	res->retcode = idmap_stat4prot(retcode);
30425731Sbaban 	if (res->retcode != IDMAP_SUCCESS) {
30435731Sbaban 		req->direction = _IDMAP_F_DONE;
30445731Sbaban 		res->id.idmap_id_u.uid = UID_NOBODY;
30455731Sbaban 	}
30465731Sbaban 	if (!ARE_WE_DONE(req->direction))
30475731Sbaban 		state->sid2pid_done = FALSE;
30484520Snw141292 	return (retcode);
30494520Snw141292 }
30504520Snw141292 
30514520Snw141292 idmap_retcode
30526616Sdm199847 update_cache_pid2sid(lookup_state_t *state,
30535696Snw141292 		idmap_mapping *req, idmap_id_res *res)
30545696Snw141292 {
30554520Snw141292 	char		*sql = NULL;
30564520Snw141292 	idmap_retcode	retcode;
30576386Sjp151216 	char		*map_dn = NULL;
30586386Sjp151216 	char		*map_attr = NULL;
30596386Sjp151216 	char		*map_value = NULL;
30606386Sjp151216 	char 		*map_windomain = NULL;
30616386Sjp151216 	char		*map_winname = NULL;
30626386Sjp151216 	char		*map_unixname = NULL;
30636386Sjp151216 	int		map_is_nt4 = FALSE;
30644520Snw141292 
30654520Snw141292 	/* Check if we need to cache anything */
30665731Sbaban 	if (ARE_WE_DONE(req->direction))
30674520Snw141292 		return (IDMAP_SUCCESS);
30684520Snw141292 
30694520Snw141292 	/* We don't cache negative entries */
30704520Snw141292 	if (res->retcode != IDMAP_SUCCESS)
30714520Snw141292 		return (IDMAP_SUCCESS);
30724520Snw141292 
30735731Sbaban 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
30746386Sjp151216 	assert(req->id1.idmap_id_u.uid != SENTINEL_PID);
30756386Sjp151216 	assert(res->id.idtype != IDMAP_SID);
30766386Sjp151216 
30776386Sjp151216 	assert(res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN);
30786386Sjp151216 	switch (res->info.how.map_type) {
30796386Sjp151216 	case IDMAP_MAP_TYPE_DS_AD:
30806386Sjp151216 		map_dn = res->info.how.idmap_how_u.ad.dn;
30816386Sjp151216 		map_attr = res->info.how.idmap_how_u.ad.attr;
30826386Sjp151216 		map_value = res->info.how.idmap_how_u.ad.value;
30836386Sjp151216 		break;
30846386Sjp151216 
30856386Sjp151216 	case IDMAP_MAP_TYPE_DS_NLDAP:
30866386Sjp151216 		map_dn = res->info.how.idmap_how_u.nldap.dn;
30876386Sjp151216 		map_attr = res->info.how.idmap_how_u.nldap.attr;
30886386Sjp151216 		map_value = res->info.how.idmap_how_u.nldap.value;
30896386Sjp151216 		break;
30906386Sjp151216 
30916386Sjp151216 	case IDMAP_MAP_TYPE_RULE_BASED:
30926386Sjp151216 		map_windomain = res->info.how.idmap_how_u.rule.windomain;
30936386Sjp151216 		map_winname = res->info.how.idmap_how_u.rule.winname;
30946386Sjp151216 		map_unixname = res->info.how.idmap_how_u.rule.unixname;
30956386Sjp151216 		map_is_nt4 = res->info.how.idmap_how_u.rule.is_nt4;
30966386Sjp151216 		break;
30976386Sjp151216 
30986386Sjp151216 	case IDMAP_MAP_TYPE_EPHEMERAL:
30996386Sjp151216 		break;
31006386Sjp151216 
31016386Sjp151216 	case IDMAP_MAP_TYPE_LOCAL_SID:
31026386Sjp151216 		break;
31036386Sjp151216 
31046386Sjp151216 	default:
31056386Sjp151216 		/* Dont cache other mapping types */
31066386Sjp151216 		assert(FALSE);
31076386Sjp151216 	}
31085731Sbaban 
31094520Snw141292 	/*
31104520Snw141292 	 * Using NULL for u2w instead of 0 so that our trigger allows
31114520Snw141292 	 * the same pid to be the destination in multiple entries
31124520Snw141292 	 */
31134520Snw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
31145696Snw141292 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
31156386Sjp151216 	    "is_user, is_wuser, expiration, w2u, u2w, "
31166386Sjp151216 	    "map_type, map_dn, map_attr, map_value, map_windomain, "
31176386Sjp151216 	    "map_winname, map_unixname, map_is_nt4) "
31185696Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
31196386Sjp151216 	    "strftime('%%s','now') + 600, %q, 1, "
31206386Sjp151216 	    "%d, %Q, %Q, %Q, %Q, %Q, %Q, %d); ",
31215696Snw141292 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
31225696Snw141292 	    req->id2domain, req->id2name, req->id1.idmap_id_u.uid,
31235696Snw141292 	    req->id1name, (req->id1.idtype == IDMAP_UID) ? 1 : 0,
31245731Sbaban 	    (res->id.idtype == IDMAP_USID) ? 1 : 0,
31256386Sjp151216 	    (res->direction == 0) ? "1" : NULL,
31266386Sjp151216 	    res->info.how.map_type, map_dn, map_attr, map_value,
31276386Sjp151216 	    map_windomain, map_winname, map_unixname, map_is_nt4);
31284520Snw141292 
31294520Snw141292 	if (sql == NULL) {
31304520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
31314520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
31324520Snw141292 		goto out;
31334520Snw141292 	}
31344520Snw141292 
31356616Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
31364520Snw141292 	if (retcode != IDMAP_SUCCESS)
31374520Snw141292 		goto out;
31384520Snw141292 
31394520Snw141292 	state->pid2sid_done = FALSE;
31404520Snw141292 	sqlite_freemem(sql);
31414520Snw141292 	sql = NULL;
31424520Snw141292 
31435731Sbaban 	/* Check if we need to update namecache */
31445731Sbaban 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
31454520Snw141292 		goto out;
31464520Snw141292 
31475064Sdm199847 	if (req->id2name == NULL)
31484520Snw141292 		goto out;
31494520Snw141292 
31504520Snw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
31515696Snw141292 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
31525696Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
31535696Snw141292 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
31545696Snw141292 	    req->id2name, req->id2domain,
31555731Sbaban 	    (res->id.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
31564520Snw141292 
31574520Snw141292 	if (sql == NULL) {
31584520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
31594520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
31604520Snw141292 		goto out;
31614520Snw141292 	}
31624520Snw141292 
31636616Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
31644520Snw141292 
31654520Snw141292 out:
31666386Sjp151216 	if (!(req->flag & IDMAP_REQ_FLG_MAPPING_INFO))
31676386Sjp151216 		idmap_info_free(&res->info);
31684864Sbaban 	if (sql != NULL)
31694520Snw141292 		sqlite_freemem(sql);
31704520Snw141292 	return (retcode);
31714520Snw141292 }
31724520Snw141292 
31734520Snw141292 idmap_retcode
31746616Sdm199847 update_cache_sid2pid(lookup_state_t *state,
31755696Snw141292 		idmap_mapping *req, idmap_id_res *res)
31765696Snw141292 {
31774520Snw141292 	char		*sql = NULL;
31784520Snw141292 	idmap_retcode	retcode;
31794520Snw141292 	int		is_eph_user;
31806386Sjp151216 	char		*map_dn = NULL;
31816386Sjp151216 	char		*map_attr = NULL;
31826386Sjp151216 	char		*map_value = NULL;
31836386Sjp151216 	char 		*map_windomain = NULL;
31846386Sjp151216 	char		*map_winname = NULL;
31856386Sjp151216 	char		*map_unixname = NULL;
31866386Sjp151216 	int		map_is_nt4 = FALSE;
31874520Snw141292 
31884520Snw141292 	/* Check if we need to cache anything */
31895731Sbaban 	if (ARE_WE_DONE(req->direction))
31904520Snw141292 		return (IDMAP_SUCCESS);
31914520Snw141292 
31924520Snw141292 	/* We don't cache negative entries */
31934520Snw141292 	if (res->retcode != IDMAP_SUCCESS)
31944520Snw141292 		return (IDMAP_SUCCESS);
31954520Snw141292 
31964520Snw141292 	if (req->direction & _IDMAP_F_EXP_EPH_UID)
31974520Snw141292 		is_eph_user = 1;
31984520Snw141292 	else if (req->direction & _IDMAP_F_EXP_EPH_GID)
31994520Snw141292 		is_eph_user = 0;
32004520Snw141292 	else
32014520Snw141292 		is_eph_user = -1;
32024520Snw141292 
32034520Snw141292 	if (is_eph_user >= 0 && !IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
32044520Snw141292 		sql = sqlite_mprintf("UPDATE idmap_cache "
32055696Snw141292 		    "SET w2u = 0 WHERE "
32065696Snw141292 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
32075696Snw141292 		    "pid >= 2147483648 AND is_user = %d;",
32085696Snw141292 		    req->id1.idmap_id_u.sid.prefix,
32095696Snw141292 		    req->id1.idmap_id_u.sid.rid,
32105696Snw141292 		    is_eph_user);
32114520Snw141292 		if (sql == NULL) {
32124520Snw141292 			retcode = IDMAP_ERR_INTERNAL;
32134520Snw141292 			idmapdlog(LOG_ERR, "Out of memory");
32144520Snw141292 			goto out;
32154520Snw141292 		}
32164520Snw141292 
32176616Sdm199847 		retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
32184520Snw141292 		if (retcode != IDMAP_SUCCESS)
32194520Snw141292 			goto out;
32204520Snw141292 
32214520Snw141292 		sqlite_freemem(sql);
32224520Snw141292 		sql = NULL;
32234520Snw141292 	}
32244520Snw141292 
32255731Sbaban 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
32266386Sjp151216 	assert(res->id.idmap_id_u.uid != SENTINEL_PID);
32276386Sjp151216 
32286386Sjp151216 	switch (res->info.how.map_type) {
32296386Sjp151216 	case IDMAP_MAP_TYPE_DS_AD:
32306386Sjp151216 		map_dn = res->info.how.idmap_how_u.ad.dn;
32316386Sjp151216 		map_attr = res->info.how.idmap_how_u.ad.attr;
32326386Sjp151216 		map_value = res->info.how.idmap_how_u.ad.value;
32336386Sjp151216 		break;
32346386Sjp151216 
32356386Sjp151216 	case IDMAP_MAP_TYPE_DS_NLDAP:
32366386Sjp151216 		map_dn = res->info.how.idmap_how_u.nldap.dn;
32376386Sjp151216 		map_attr = res->info.how.idmap_how_u.ad.attr;
32386386Sjp151216 		map_value = res->info.how.idmap_how_u.nldap.value;
32396386Sjp151216 		break;
32406386Sjp151216 
32416386Sjp151216 	case IDMAP_MAP_TYPE_RULE_BASED:
32426386Sjp151216 		map_windomain = res->info.how.idmap_how_u.rule.windomain;
32436386Sjp151216 		map_winname = res->info.how.idmap_how_u.rule.winname;
32446386Sjp151216 		map_unixname = res->info.how.idmap_how_u.rule.unixname;
32456386Sjp151216 		map_is_nt4 = res->info.how.idmap_how_u.rule.is_nt4;
32466386Sjp151216 		break;
32476386Sjp151216 
32486386Sjp151216 	case IDMAP_MAP_TYPE_EPHEMERAL:
32496386Sjp151216 		break;
32506386Sjp151216 
32516386Sjp151216 	default:
32526386Sjp151216 		/* Dont cache other mapping types */
32536386Sjp151216 		assert(FALSE);
32546386Sjp151216 	}
32555696Snw141292 
32564520Snw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
32575696Snw141292 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
32586386Sjp151216 	    "is_user, is_wuser, expiration, w2u, u2w, "
32596386Sjp151216 	    "map_type, map_dn, map_attr, map_value, map_windomain, "
32606386Sjp151216 	    "map_winname, map_unixname, map_is_nt4) "
32615696Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
32626386Sjp151216 	    "strftime('%%s','now') + 600, 1, %q, "
32636386Sjp151216 	    "%d, %Q, %Q, %Q, %Q, %Q, %Q, %d);",
32645696Snw141292 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
32655731Sbaban 	    (req->id1domain != NULL) ? req->id1domain : "", req->id1name,
32665731Sbaban 	    res->id.idmap_id_u.uid, req->id2name,
32675731Sbaban 	    (res->id.idtype == IDMAP_UID) ? 1 : 0,
32685696Snw141292 	    (req->id1.idtype == IDMAP_USID) ? 1 : 0,
32696386Sjp151216 	    (res->direction == 0) ? "1" : NULL,
32706386Sjp151216 	    res->info.how.map_type, map_dn, map_attr, map_value,
32716386Sjp151216 	    map_windomain, map_winname, map_unixname, map_is_nt4);
32724520Snw141292 
32734520Snw141292 	if (sql == NULL) {
32744520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
32754520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
32764520Snw141292 		goto out;
32774520Snw141292 	}
32784520Snw141292 
32796616Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
32804520Snw141292 	if (retcode != IDMAP_SUCCESS)
32814520Snw141292 		goto out;
32824520Snw141292 
32834520Snw141292 	state->sid2pid_done = FALSE;
32844520Snw141292 	sqlite_freemem(sql);
32854520Snw141292 	sql = NULL;
32864520Snw141292 
32875731Sbaban 	/* Check if we need to update namecache */
32885731Sbaban 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
32894520Snw141292 		goto out;
32904520Snw141292 
32915127Sdm199847 	if (EMPTY_STRING(req->id1name))
32924520Snw141292 		goto out;
32934520Snw141292 
32944520Snw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
32955696Snw141292 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
32965696Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
32975696Snw141292 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
32985696Snw141292 	    req->id1name, req->id1domain,
32995696Snw141292 	    (req->id1.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
33004520Snw141292 
33014520Snw141292 	if (sql == NULL) {
33024520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
33034520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
33044520Snw141292 		goto out;
33054520Snw141292 	}
33064520Snw141292 
33076616Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
33084520Snw141292 
33094520Snw141292 out:
33106386Sjp151216 	if (!(req->flag & IDMAP_REQ_FLG_MAPPING_INFO))
33116386Sjp151216 		idmap_info_free(&res->info);
33126386Sjp151216 
33134864Sbaban 	if (sql != NULL)
33144520Snw141292 		sqlite_freemem(sql);
33154520Snw141292 	return (retcode);
33164520Snw141292 }
33174520Snw141292 
33185696Snw141292 static
33195696Snw141292 idmap_retcode
33204520Snw141292 lookup_cache_pid2sid(sqlite *cache, idmap_mapping *req, idmap_id_res *res,
33215696Snw141292 		int is_user, int getname)
33225696Snw141292 {
33234520Snw141292 	char		*end;
33244520Snw141292 	char		*sql = NULL;
33254520Snw141292 	const char	**values;
33264520Snw141292 	sqlite_vm	*vm = NULL;
33274520Snw141292 	int		ncol;
33284520Snw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
33294520Snw141292 	time_t		curtime;
33305731Sbaban 	idmap_id_type	idtype;
33314520Snw141292 
33324520Snw141292 	/* Current time */
33334520Snw141292 	errno = 0;
33344520Snw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
33355696Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
33365696Snw141292 		    strerror(errno));
33374520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
33384520Snw141292 		goto out;
33394520Snw141292 	}
33404520Snw141292 
33415731Sbaban 	/* SQL to lookup the cache by pid or by unixname */
33425731Sbaban 	if (req->id1.idmap_id_u.uid != SENTINEL_PID) {
33436386Sjp151216 		sql = sqlite_mprintf("SELECT sidprefix, rid, "
33446386Sjp151216 		    "canon_winname, windomain, w2u, is_wuser, "
33456386Sjp151216 		    "map_type, map_dn, map_attr, map_value, map_windomain, "
33466386Sjp151216 		    "map_winname, map_unixname, map_is_nt4 "
33475731Sbaban 		    "FROM idmap_cache WHERE "
33485731Sbaban 		    "pid = %u AND u2w = 1 AND is_user = %d AND "
33495731Sbaban 		    "(pid >= 2147483648 OR "
33505731Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
33515731Sbaban 		    "expiration > %d));",
33525731Sbaban 		    req->id1.idmap_id_u.uid, is_user, curtime);
33535731Sbaban 	} else if (req->id1name != NULL) {
33546386Sjp151216 		sql = sqlite_mprintf("SELECT sidprefix, rid, "
33556386Sjp151216 		    "canon_winname, windomain, w2u, is_wuser, "
33566386Sjp151216 		    "map_type, map_dn, map_attr, map_value, map_windomain, "
33576386Sjp151216 		    "map_winname, map_unixname, map_is_nt4 "
33585731Sbaban 		    "FROM idmap_cache WHERE "
33595731Sbaban 		    "unixname = %Q AND u2w = 1 AND is_user = %d AND "
33605731Sbaban 		    "(pid >= 2147483648 OR "
33615731Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
33625731Sbaban 		    "expiration > %d));",
33635731Sbaban 		    req->id1name, is_user, curtime);
33646386Sjp151216 	} else {
33656386Sjp151216 		retcode = IDMAP_ERR_ARG;
33666386Sjp151216 		goto out;
33675731Sbaban 	}
33685731Sbaban 
33694520Snw141292 	if (sql == NULL) {
33704520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
33714520Snw141292 		retcode = IDMAP_ERR_MEMORY;
33724520Snw141292 		goto out;
33734520Snw141292 	}
33746386Sjp151216 	retcode = sql_compile_n_step_once(
33756386Sjp151216 	    cache, sql, &vm, &ncol, 14, &values);
33764520Snw141292 	sqlite_freemem(sql);
33774520Snw141292 
33784520Snw141292 	if (retcode == IDMAP_ERR_NOTFOUND)
33794520Snw141292 		goto out;
33804520Snw141292 	else if (retcode == IDMAP_SUCCESS) {
33814520Snw141292 		/* sanity checks */
33824520Snw141292 		if (values[0] == NULL || values[1] == NULL) {
33834520Snw141292 			retcode = IDMAP_ERR_CACHE;
33844520Snw141292 			goto out;
33854520Snw141292 		}
33864520Snw141292 
33875731Sbaban 		switch (res->id.idtype) {
33884520Snw141292 		case IDMAP_SID:
33895696Snw141292 		case IDMAP_USID:
33905696Snw141292 		case IDMAP_GSID:
33915731Sbaban 			idtype = strtol(values[5], &end, 10) == 1
33925696Snw141292 			    ? IDMAP_USID : IDMAP_GSID;
33935696Snw141292 
33945731Sbaban 			if (res->id.idtype == IDMAP_USID &&
33955731Sbaban 			    idtype != IDMAP_USID) {
33965696Snw141292 				retcode = IDMAP_ERR_NOTUSER;
33975696Snw141292 				goto out;
33985731Sbaban 			} else if (res->id.idtype == IDMAP_GSID &&
33995731Sbaban 			    idtype != IDMAP_GSID) {
34005696Snw141292 				retcode = IDMAP_ERR_NOTGROUP;
34015696Snw141292 				goto out;
34025696Snw141292 			}
34035731Sbaban 			res->id.idtype = idtype;
34045696Snw141292 
34054520Snw141292 			res->id.idmap_id_u.sid.rid =
34065696Snw141292 			    strtoul(values[1], &end, 10);
34074520Snw141292 			res->id.idmap_id_u.sid.prefix = strdup(values[0]);
34084520Snw141292 			if (res->id.idmap_id_u.sid.prefix == NULL) {
34094520Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
34104520Snw141292 				retcode = IDMAP_ERR_MEMORY;
34114520Snw141292 				goto out;
34124520Snw141292 			}
34134520Snw141292 
34144864Sbaban 			if (values[4] != NULL)
34154520Snw141292 				res->direction =
34164644Sbaban 				    (strtol(values[4], &end, 10) == 0)?
34174644Sbaban 				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
34184520Snw141292 			else
34194644Sbaban 				res->direction = IDMAP_DIRECTION_U2W;
34204520Snw141292 
34214520Snw141292 			if (getname == 0 || values[2] == NULL)
34224520Snw141292 				break;
34235064Sdm199847 			req->id2name = strdup(values[2]);
34245064Sdm199847 			if (req->id2name == NULL) {
34254520Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
34264520Snw141292 				retcode = IDMAP_ERR_MEMORY;
34274520Snw141292 				goto out;
34284520Snw141292 			}
34294520Snw141292 
34304520Snw141292 			if (values[3] == NULL)
34314520Snw141292 				break;
34325064Sdm199847 			req->id2domain = strdup(values[3]);
34335064Sdm199847 			if (req->id2domain == NULL) {
34344520Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
34354520Snw141292 				retcode = IDMAP_ERR_MEMORY;
34364520Snw141292 				goto out;
34374520Snw141292 			}
34385696Snw141292 
34394520Snw141292 			break;
34404520Snw141292 		default:
34414520Snw141292 			retcode = IDMAP_ERR_NOTSUPPORTED;
34424520Snw141292 			break;
34434520Snw141292 		}
34446386Sjp151216 		if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
34456386Sjp151216 			res->info.src = IDMAP_MAP_SRC_CACHE;
34466386Sjp151216 			res->info.how.map_type = strtoul(values[6], &end, 10);
34476386Sjp151216 			switch (res->info.how.map_type) {
34486386Sjp151216 			case IDMAP_MAP_TYPE_DS_AD:
34496386Sjp151216 				res->info.how.idmap_how_u.ad.dn =
34506386Sjp151216 				    strdup(values[7]);
34516386Sjp151216 				res->info.how.idmap_how_u.ad.attr =
34526386Sjp151216 				    strdup(values[8]);
34536386Sjp151216 				res->info.how.idmap_how_u.ad.value =
34546386Sjp151216 				    strdup(values[9]);
34556386Sjp151216 				break;
34566386Sjp151216 
34576386Sjp151216 			case IDMAP_MAP_TYPE_DS_NLDAP:
34586386Sjp151216 				res->info.how.idmap_how_u.nldap.dn =
34596386Sjp151216 				    strdup(values[7]);
34606386Sjp151216 				res->info.how.idmap_how_u.nldap.attr =
34616386Sjp151216 				    strdup(values[8]);
34626386Sjp151216 				res->info.how.idmap_how_u.nldap.value =
34636386Sjp151216 				    strdup(values[9]);
34646386Sjp151216 				break;
34656386Sjp151216 
34666386Sjp151216 			case IDMAP_MAP_TYPE_RULE_BASED:
34676386Sjp151216 				res->info.how.idmap_how_u.rule.windomain =
34686386Sjp151216 				    strdup(values[10]);
34696386Sjp151216 				res->info.how.idmap_how_u.rule.winname =
34706386Sjp151216 				    strdup(values[11]);
34716386Sjp151216 				res->info.how.idmap_how_u.rule.unixname =
34726386Sjp151216 				    strdup(values[12]);
34736386Sjp151216 				res->info.how.idmap_how_u.rule.is_nt4 =
34746386Sjp151216 				    strtoul(values[13], &end, 10);
34756386Sjp151216 				res->info.how.idmap_how_u.rule.is_user =
34766386Sjp151216 				    is_user;
34776386Sjp151216 				res->info.how.idmap_how_u.rule.is_wuser =
34786386Sjp151216 				    strtol(values[5], &end, 10);
34796386Sjp151216 				break;
34806386Sjp151216 
34816386Sjp151216 			case IDMAP_MAP_TYPE_EPHEMERAL:
34826386Sjp151216 				break;
34836386Sjp151216 
34846386Sjp151216 			case IDMAP_MAP_TYPE_LOCAL_SID:
34856386Sjp151216 				break;
34866386Sjp151216 
34876386Sjp151216 			case IDMAP_MAP_TYPE_KNOWN_SID:
34886386Sjp151216 				break;
34896386Sjp151216 
34906386Sjp151216 			default:
34916386Sjp151216 				/* Unknow mapping type */
34926386Sjp151216 				assert(FALSE);
34936386Sjp151216 			}
34946386Sjp151216 		}
34954520Snw141292 	}
34964520Snw141292 
34974520Snw141292 out:
34984864Sbaban 	if (vm != NULL)
34994520Snw141292 		(void) sqlite_finalize(vm, NULL);
35004520Snw141292 	return (retcode);
35014520Snw141292 }
35024520Snw141292 
35035696Snw141292 static
35045696Snw141292 idmap_retcode
35054520Snw141292 lookup_cache_name2sid(sqlite *cache, const char *name, const char *domain,
35065696Snw141292 	char **canonname, char **sidprefix, idmap_rid_t *rid, int *type)
35075696Snw141292 {
35085696Snw141292 	char		*end, *lower_name;
35094520Snw141292 	char		*sql = NULL;
35104520Snw141292 	const char	**values;
35114520Snw141292 	sqlite_vm	*vm = NULL;
35124520Snw141292 	int		ncol;
35134520Snw141292 	time_t		curtime;
35144520Snw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
35154520Snw141292 
35164520Snw141292 	/* Get current time */
35174520Snw141292 	errno = 0;
35184520Snw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
35195696Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
35205696Snw141292 		    strerror(errno));
35214520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
35224520Snw141292 		goto out;
35234520Snw141292 	}
35244520Snw141292 
35254520Snw141292 	/* SQL to lookup the cache */
35265696Snw141292 	if ((lower_name = tolower_u8(name)) == NULL)
35275696Snw141292 		lower_name = (char *)name;
35285696Snw141292 	sql = sqlite_mprintf("SELECT sidprefix, rid, type, canon_name "
35295696Snw141292 	    "FROM name_cache WHERE name = %Q AND domain = %Q AND "
35305696Snw141292 	    "(expiration = 0 OR expiration ISNULL OR "
35315696Snw141292 	    "expiration > %d);", lower_name, domain, curtime);
35325696Snw141292 	if (lower_name != name)
35335696Snw141292 		free(lower_name);
35344520Snw141292 	if (sql == NULL) {
35354520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
35364520Snw141292 		retcode = IDMAP_ERR_MEMORY;
35374520Snw141292 		goto out;
35384520Snw141292 	}
35395696Snw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 4, &values);
35404520Snw141292 	sqlite_freemem(sql);
35414520Snw141292 
35424520Snw141292 	if (retcode == IDMAP_SUCCESS) {
35434864Sbaban 		if (type != NULL) {
35444520Snw141292 			if (values[2] == NULL) {
35454520Snw141292 				retcode = IDMAP_ERR_CACHE;
35464520Snw141292 				goto out;
35474520Snw141292 			}
35484520Snw141292 			*type = strtol(values[2], &end, 10);
35494520Snw141292 		}
35504520Snw141292 
35515731Sbaban 		if (values[0] == NULL || values[1] == NULL) {
35525731Sbaban 			retcode = IDMAP_ERR_CACHE;
35535731Sbaban 			goto out;
35545731Sbaban 		}
35555731Sbaban 
35565696Snw141292 		if (canonname != NULL) {
35575696Snw141292 			assert(values[3] != NULL);
35585696Snw141292 			if ((*canonname = strdup(values[3])) == NULL) {
35595696Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
35605696Snw141292 				retcode = IDMAP_ERR_MEMORY;
35615696Snw141292 				goto out;
35625696Snw141292 			}
35635696Snw141292 		}
35645696Snw141292 
35654520Snw141292 		if ((*sidprefix = strdup(values[0])) == NULL) {
35664520Snw141292 			idmapdlog(LOG_ERR, "Out of memory");
35674520Snw141292 			retcode = IDMAP_ERR_MEMORY;
35685731Sbaban 			if (canonname != NULL) {
35695731Sbaban 				free(*canonname);
35705731Sbaban 				*canonname = NULL;
35715731Sbaban 			}
35724520Snw141292 			goto out;
35734520Snw141292 		}
35744520Snw141292 		*rid = strtoul(values[1], &end, 10);
35754520Snw141292 	}
35764520Snw141292 
35774520Snw141292 out:
35784864Sbaban 	if (vm != NULL)
35794520Snw141292 		(void) sqlite_finalize(vm, NULL);
35804520Snw141292 	return (retcode);
35814520Snw141292 }
35824520Snw141292 
35835696Snw141292 static
35845696Snw141292 idmap_retcode
35855731Sbaban ad_lookup_by_winname(lookup_state_t *state,
35865731Sbaban 		const char *name, const char *domain, int eunixtype,
35876386Sjp151216 		char **dn, char **attr, char **value, char **canonname,
35886386Sjp151216 		char **sidprefix, idmap_rid_t *rid, int *wintype,
35896386Sjp151216 		char **unixname)
35905696Snw141292 {
35914520Snw141292 	int			retries = 0;
35924520Snw141292 	idmap_query_state_t	*qs = NULL;
35934520Snw141292 	idmap_retcode		rc, retcode;
35944520Snw141292 
35954520Snw141292 retry:
3596*8040SBaban.Kenkre@Sun.COM 	RDLOCK_CONFIG();
35975731Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, 1, &qs);
3598*8040SBaban.Kenkre@Sun.COM 	UNLOCK_CONFIG();
35995731Sbaban 	if (retcode != IDMAP_SUCCESS) {
3600*8040SBaban.Kenkre@Sun.COM 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
3601*8040SBaban.Kenkre@Sun.COM 		    retries++ < ADUTILS_DEF_NUM_RETRIES)
36025968Snw141292 			goto retry;
36036097Snw141292 		degrade_svc(1, "failed to create request for AD lookup "
36045968Snw141292 		    "by winname");
36055731Sbaban 		return (retcode);
36064520Snw141292 	}
36074520Snw141292 
36085317Sjp151216 	restore_svc();
36095317Sjp151216 
36105731Sbaban 	if (state != NULL)
36115731Sbaban 		idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
36125731Sbaban 		    state->ad_unixgroup_attr);
36135731Sbaban 
36145731Sbaban 	retcode = idmap_name2sid_batch_add1(qs, name, domain, eunixtype,
36156386Sjp151216 	    dn, attr, value, canonname, sidprefix, rid, wintype, unixname, &rc);
36165731Sbaban 
36175731Sbaban 	if (retcode != IDMAP_SUCCESS)
36184884Sjp151216 		idmap_lookup_release_batch(&qs);
36194520Snw141292 	else
36205968Snw141292 		retcode = idmap_lookup_batch_end(&qs);
36214520Snw141292 
3622*8040SBaban.Kenkre@Sun.COM 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
3623*8040SBaban.Kenkre@Sun.COM 	    retries++ < ADUTILS_DEF_NUM_RETRIES)
36244520Snw141292 		goto retry;
36255317Sjp151216 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
36266097Snw141292 		degrade_svc(1, "some AD lookups timed out repeatedly");
36274520Snw141292 
36284520Snw141292 	if (retcode != IDMAP_SUCCESS) {
36295731Sbaban 		idmapdlog(LOG_NOTICE, "AD lookup by winname failed");
36304520Snw141292 		return (retcode);
36315731Sbaban 	}
36325731Sbaban 	return (rc);
36334520Snw141292 }
36344520Snw141292 
36355696Snw141292 idmap_retcode
36364520Snw141292 lookup_name2sid(sqlite *cache, const char *name, const char *domain,
36375696Snw141292 		int *is_wuser, char **canonname, char **sidprefix,
36386616Sdm199847 		idmap_rid_t *rid, idmap_mapping *req, int local_only)
36395696Snw141292 {
36404520Snw141292 	int		type;
36414520Snw141292 	idmap_retcode	retcode;
36424520Snw141292 
36435696Snw141292 	*sidprefix = NULL;
36445731Sbaban 	if (canonname != NULL)
36455731Sbaban 		*canonname = NULL;
36465731Sbaban 
36475731Sbaban 	/* Lookup well-known SIDs table */
36485696Snw141292 	retcode = lookup_wksids_name2sid(name, canonname, sidprefix, rid,
36495696Snw141292 	    &type);
36504864Sbaban 	if (retcode == IDMAP_SUCCESS) {
36515731Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
36524864Sbaban 		goto out;
36534864Sbaban 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
36544864Sbaban 		return (retcode);
36554864Sbaban 	}
36564864Sbaban 
36575731Sbaban 	/* Lookup cache */
36585696Snw141292 	retcode = lookup_cache_name2sid(cache, name, domain, canonname,
36595696Snw141292 	    sidprefix, rid, &type);
36605731Sbaban 	if (retcode == IDMAP_SUCCESS) {
36615731Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
36625731Sbaban 		goto out;
36635731Sbaban 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
36644520Snw141292 		return (retcode);
36654520Snw141292 	}
36664520Snw141292 
36676616Sdm199847 	/*
36686616Sdm199847 	 * The caller may be using this function to determine if this
36696616Sdm199847 	 * request needs to be marked for AD lookup or not
36706616Sdm199847 	 * (i.e. _IDMAP_F_LOOKUP_AD) and therefore may not want this
36716616Sdm199847 	 * function to AD lookup now.
36726616Sdm199847 	 */
36736616Sdm199847 	if (local_only)
36746616Sdm199847 		return (retcode);
36756616Sdm199847 
36765731Sbaban 	/* Lookup AD */
36775731Sbaban 	retcode = ad_lookup_by_winname(NULL, name, domain, _IDMAP_T_UNDEF,
36786386Sjp151216 	    NULL, NULL, NULL, canonname, sidprefix, rid, &type, NULL);
36795731Sbaban 	if (retcode != IDMAP_SUCCESS)
36805731Sbaban 		return (retcode);
36815731Sbaban 
36824864Sbaban out:
36834520Snw141292 	/*
36844520Snw141292 	 * Entry found (cache or Windows lookup)
36855696Snw141292 	 * is_wuser is both input as well as output parameter
36864520Snw141292 	 */
36875731Sbaban 	if (*is_wuser == 1 && type != _IDMAP_T_USER)
36885731Sbaban 		retcode = IDMAP_ERR_NOTUSER;
36895731Sbaban 	else if (*is_wuser == 0 && type != _IDMAP_T_GROUP)
36905731Sbaban 		retcode = IDMAP_ERR_NOTGROUP;
36915731Sbaban 	else if (*is_wuser == -1) {
36924520Snw141292 		/* Caller wants to know if its user or group */
36934520Snw141292 		if (type == _IDMAP_T_USER)
36945696Snw141292 			*is_wuser = 1;
36954520Snw141292 		else if (type == _IDMAP_T_GROUP)
36965696Snw141292 			*is_wuser = 0;
36975731Sbaban 		else
36985731Sbaban 			retcode = IDMAP_ERR_SID;
36995731Sbaban 	}
37005731Sbaban 
37015731Sbaban 	if (retcode != IDMAP_SUCCESS) {
37025731Sbaban 		free(*sidprefix);
37035731Sbaban 		*sidprefix = NULL;
37045731Sbaban 		if (canonname != NULL) {
37055731Sbaban 			free(*canonname);
37065731Sbaban 			*canonname = NULL;
37075696Snw141292 		}
37084520Snw141292 	}
37094520Snw141292 	return (retcode);
37104520Snw141292 }
37114520Snw141292 
37125696Snw141292 static
37135696Snw141292 idmap_retcode
37146616Sdm199847 name_based_mapping_pid2sid(lookup_state_t *state, const char *unixname,
37155696Snw141292 		int is_user, idmap_mapping *req, idmap_id_res *res)
37165696Snw141292 {
37174520Snw141292 	const char	*winname, *windomain;
37185696Snw141292 	char		*canonname;
37194520Snw141292 	char		*sql = NULL, *errmsg = NULL;
37204520Snw141292 	idmap_retcode	retcode;
37214520Snw141292 	char		*end;
37224520Snw141292 	const char	**values;
37234520Snw141292 	sqlite_vm	*vm = NULL;
37246386Sjp151216 	int		ncol, r;
37255731Sbaban 	int		is_wuser;
37264520Snw141292 	const char	*me = "name_based_mapping_pid2sid";
37276386Sjp151216 	int 		non_wild_match = FALSE;
37286386Sjp151216 	idmap_namerule	*rule = &res->info.how.idmap_how_u.rule;
37296386Sjp151216 	int direction;
37305731Sbaban 
37315731Sbaban 	assert(unixname != NULL); /* We have unixname */
37325731Sbaban 	assert(req->id2name == NULL); /* We don't have winname */
37335731Sbaban 	assert(res->id.idmap_id_u.sid.prefix == NULL); /* No SID either */
37344520Snw141292 
37354520Snw141292 	sql = sqlite_mprintf(
37366386Sjp151216 	    "SELECT winname_display, windomain, w2u_order, "
37376386Sjp151216 	    "is_wuser, unixname, is_nt4 "
37386386Sjp151216 	    "FROM namerules WHERE "
37395696Snw141292 	    "u2w_order > 0 AND is_user = %d AND "
37405696Snw141292 	    "(unixname = %Q OR unixname = '*') "
37415696Snw141292 	    "ORDER BY u2w_order ASC;", is_user, unixname);
37424520Snw141292 	if (sql == NULL) {
37434520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
37444520Snw141292 		retcode = IDMAP_ERR_MEMORY;
37454520Snw141292 		goto out;
37464520Snw141292 	}
37474520Snw141292 
37486616Sdm199847 	if (sqlite_compile(state->db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
37494520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
37505696Snw141292 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
37515696Snw141292 		    CHECK_NULL(errmsg));
37524520Snw141292 		sqlite_freemem(errmsg);
37534520Snw141292 		goto out;
37544520Snw141292 	}
37554520Snw141292 
37566386Sjp151216 	for (;;) {
37574520Snw141292 		r = sqlite_step(vm, &ncol, &values, NULL);
37584884Sjp151216 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
37594884Sjp151216 		if (r == SQLITE_ROW) {
37606386Sjp151216 			if (ncol < 6) {
37614520Snw141292 				retcode = IDMAP_ERR_INTERNAL;
37624520Snw141292 				goto out;
37634520Snw141292 			}
37644520Snw141292 			if (values[0] == NULL) {
37654520Snw141292 				/* values [1] and [2] can be null */
37664520Snw141292 				retcode = IDMAP_ERR_INTERNAL;
37674520Snw141292 				goto out;
37684520Snw141292 			}
37696386Sjp151216 
37706386Sjp151216 			if (values[2] != NULL)
37716386Sjp151216 				direction =
37726386Sjp151216 				    (strtol(values[2], &end, 10) == 0)?
37736386Sjp151216 				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
37746386Sjp151216 			else
37756386Sjp151216 				direction = IDMAP_DIRECTION_U2W;
37766386Sjp151216 
37774520Snw141292 			if (EMPTY_NAME(values[0])) {
37786386Sjp151216 				idmap_namerule_set(rule, values[1], values[0],
37796386Sjp151216 				    values[4], is_user,
37806386Sjp151216 				    strtol(values[3], &end, 10),
37816386Sjp151216 				    strtol(values[5], &end, 10),
37826386Sjp151216 				    direction);
37834520Snw141292 				retcode = IDMAP_ERR_NOMAPPING;
37844520Snw141292 				goto out;
37854520Snw141292 			}
37865696Snw141292 
37875696Snw141292 			if (values[0][0] == '*') {
37886386Sjp151216 				winname = unixname;
37896386Sjp151216 				if (non_wild_match) {
37905696Snw141292 					/*
37916386Sjp151216 					 * There were non-wildcard rules
37926386Sjp151216 					 * where the Windows identity doesn't
37936386Sjp151216 					 * exist. Return no mapping.
37945696Snw141292 					 */
37955696Snw141292 					retcode = IDMAP_ERR_NOMAPPING;
37965696Snw141292 					goto out;
37975696Snw141292 				}
37985696Snw141292 			} else {
37996386Sjp151216 				/* Save first non-wild match rule */
38006386Sjp151216 				if (!non_wild_match) {
38016386Sjp151216 					idmap_namerule_set(rule, values[1],
38026386Sjp151216 					    values[0], values[4],
38036386Sjp151216 					    is_user,
38046386Sjp151216 					    strtol(values[3], &end, 10),
38056386Sjp151216 					    strtol(values[5], &end, 10),
38066386Sjp151216 					    direction);
38076386Sjp151216 					non_wild_match = TRUE;
38086386Sjp151216 				}
38095696Snw141292 				winname = values[0];
38105696Snw141292 			}
38116386Sjp151216 			is_wuser = res->id.idtype == IDMAP_USID ? 1
38126386Sjp151216 			    : res->id.idtype == IDMAP_GSID ? 0
38136386Sjp151216 			    : -1;
38144864Sbaban 			if (values[1] != NULL)
38154520Snw141292 				windomain = values[1];
38166616Sdm199847 			else if (state->defdom != NULL)
38176616Sdm199847 				windomain = state->defdom;
38184520Snw141292 			else {
38195696Snw141292 				idmapdlog(LOG_ERR, "%s: no domain", me);
38204520Snw141292 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
38214520Snw141292 				goto out;
38224520Snw141292 			}
38235696Snw141292 
38246616Sdm199847 			retcode = lookup_name2sid(state->cache,
38256616Sdm199847 			    winname, windomain,
38265696Snw141292 			    &is_wuser, &canonname,
38275696Snw141292 			    &res->id.idmap_id_u.sid.prefix,
38286616Sdm199847 			    &res->id.idmap_id_u.sid.rid, req, 0);
38295731Sbaban 
38304520Snw141292 			if (retcode == IDMAP_ERR_NOTFOUND) {
38315696Snw141292 				continue;
38324520Snw141292 			}
38334520Snw141292 			goto out;
38346386Sjp151216 
38354520Snw141292 		} else if (r == SQLITE_DONE) {
38366386Sjp151216 			/*
38376386Sjp151216 			 * If there were non-wildcard rules where
38386386Sjp151216 			 * Windows identity doesn't exist
38396386Sjp151216 			 * return no mapping.
38406386Sjp151216 			 */
38416386Sjp151216 			if (non_wild_match)
38426386Sjp151216 				retcode = IDMAP_ERR_NOMAPPING;
38436386Sjp151216 			else
38446386Sjp151216 				retcode = IDMAP_ERR_NOTFOUND;
38454520Snw141292 			goto out;
38464520Snw141292 		} else {
38474520Snw141292 			(void) sqlite_finalize(vm, &errmsg);
38484520Snw141292 			vm = NULL;
38495696Snw141292 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
38505696Snw141292 			    CHECK_NULL(errmsg));
38514520Snw141292 			sqlite_freemem(errmsg);
38524520Snw141292 			retcode = IDMAP_ERR_INTERNAL;
38534520Snw141292 			goto out;
38544520Snw141292 		}
38554520Snw141292 	}
38564520Snw141292 
38574520Snw141292 out:
38584864Sbaban 	if (sql != NULL)
38594520Snw141292 		sqlite_freemem(sql);
38606386Sjp151216 	res->info.how.map_type = IDMAP_MAP_TYPE_RULE_BASED;
38614520Snw141292 	if (retcode == IDMAP_SUCCESS) {
38625696Snw141292 		res->id.idtype = is_wuser ? IDMAP_USID : IDMAP_GSID;
38635696Snw141292 
38644864Sbaban 		if (values[2] != NULL)
38654520Snw141292 			res->direction =
38664644Sbaban 			    (strtol(values[2], &end, 10) == 0)?
38674644Sbaban 			    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
38684520Snw141292 		else
38694644Sbaban 			res->direction = IDMAP_DIRECTION_U2W;
38705064Sdm199847 
38715696Snw141292 		req->id2name = canonname;
38725064Sdm199847 		if (req->id2name != NULL) {
38736616Sdm199847 			req->id2domain = strdup(windomain);
38746616Sdm199847 			if (req->id2domain == NULL)
38756616Sdm199847 				retcode = IDMAP_ERR_MEMORY;
38764520Snw141292 		}
38776616Sdm199847 	}
38786616Sdm199847 
38796616Sdm199847 	if (retcode == IDMAP_SUCCESS) {
38806386Sjp151216 		idmap_namerule_set(rule, values[1], values[0], values[4],
38816386Sjp151216 		    is_user, strtol(values[3], &end, 10),
38826386Sjp151216 		    strtol(values[5], &end, 10),
38836386Sjp151216 		    rule->direction);
38846386Sjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
38854520Snw141292 	}
38864864Sbaban 	if (vm != NULL)
38874520Snw141292 		(void) sqlite_finalize(vm, NULL);
38884520Snw141292 	return (retcode);
38894520Snw141292 }
38904520Snw141292 
38915696Snw141292 /*
38925696Snw141292  * Convention when processing unix2win requests:
38935696Snw141292  *
38945696Snw141292  * Unix identity:
38955696Snw141292  * req->id1name =
38965696Snw141292  *              unixname if given otherwise unixname found will be placed
38975696Snw141292  *              here.
38985696Snw141292  * req->id1domain =
38995696Snw141292  *              NOT USED
39005696Snw141292  * req->id1.idtype =
39015696Snw141292  *              Given type (IDMAP_UID or IDMAP_GID)
39025696Snw141292  * req->id1..[uid or gid] =
39035696Snw141292  *              UID/GID if given otherwise UID/GID found will be placed here.
39045696Snw141292  *
39055696Snw141292  * Windows identity:
39065696Snw141292  * req->id2name =
39075696Snw141292  *              winname found will be placed here.
39085696Snw141292  * req->id2domain =
39095696Snw141292  *              windomain found will be placed here.
39105696Snw141292  * res->id.idtype =
39115696Snw141292  *              Target type initialized from req->id2.idtype. If
39125696Snw141292  *              it is IDMAP_SID then actual type (IDMAP_USID/GSID) found
39135696Snw141292  *              will be placed here.
39145696Snw141292  * req->id..sid.[prefix, rid] =
39155696Snw141292  *              SID found will be placed here.
39165696Snw141292  *
39175696Snw141292  * Others:
39185696Snw141292  * res->retcode =
39195696Snw141292  *              Return status for this request will be placed here.
39205696Snw141292  * res->direction =
39215696Snw141292  *              Direction found will be placed here. Direction
39225696Snw141292  *              meaning whether the resultant mapping is valid
39235696Snw141292  *              only from unix2win or bi-directional.
39245696Snw141292  * req->direction =
39255696Snw141292  *              INTERNAL USE. Used by idmapd to set various
39265696Snw141292  *              flags (_IDMAP_F_xxxx) to aid in processing
39275696Snw141292  *              of the request.
39285696Snw141292  * req->id2.idtype =
39295696Snw141292  *              INTERNAL USE. Initially this is the requested target
39305696Snw141292  *              type and is used to initialize res->id.idtype.
39315696Snw141292  *              ad_lookup_batch() uses this field temporarily to store
39325696Snw141292  *              sid_type obtained by the batched AD lookups and after
39335696Snw141292  *              use resets it to IDMAP_NONE to prevent xdr from
39345696Snw141292  *              mis-interpreting the contents of req->id2.
39355696Snw141292  * req->id2..[uid or gid or sid] =
39365696Snw141292  *              NOT USED
39375696Snw141292  */
39385696Snw141292 
39395696Snw141292 /*
39405696Snw141292  * This function does the following:
39415696Snw141292  * 1. Lookup well-known SIDs table.
39425696Snw141292  * 2. Lookup cache.
39435696Snw141292  * 3. Check if the client does not want new mapping to be allocated
39445696Snw141292  *    in which case this pass is the final pass.
39455731Sbaban  * 4. Set AD/NLDAP lookup flags if it determines that the next stage needs
39465731Sbaban  *    to do AD/NLDAP lookup.
39475696Snw141292  */
39484520Snw141292 idmap_retcode
39496616Sdm199847 pid2sid_first_pass(lookup_state_t *state, idmap_mapping *req,
39506616Sdm199847 		idmap_id_res *res, int is_user, int getname)
39515696Snw141292 {
39525731Sbaban 	idmap_retcode	retcode;
39535731Sbaban 	bool_t		gen_localsid_on_err = FALSE;
39545731Sbaban 
39555731Sbaban 	/* Initialize result */
39564520Snw141292 	res->id.idtype = req->id2.idtype;
39575731Sbaban 	res->direction = IDMAP_DIRECTION_UNDEF;
39585731Sbaban 
39595731Sbaban 	if (req->id2.idmap_id_u.sid.prefix != NULL) {
39605731Sbaban 		/* sanitize sidprefix */
39615731Sbaban 		free(req->id2.idmap_id_u.sid.prefix);
39625731Sbaban 		req->id2.idmap_id_u.sid.prefix = NULL;
39635731Sbaban 	}
39645731Sbaban 
39656386Sjp151216 	/* Find pid */
39666386Sjp151216 	if (req->id1.idmap_id_u.uid == SENTINEL_PID) {
39676386Sjp151216 		if (ns_lookup_byname(req->id1name, NULL, &req->id1)
39686386Sjp151216 		    != IDMAP_SUCCESS) {
39696386Sjp151216 			retcode = IDMAP_ERR_NOMAPPING;
39706386Sjp151216 			goto out;
39716386Sjp151216 		}
39726386Sjp151216 	}
39736386Sjp151216 
39745731Sbaban 	/* Lookup well-known SIDs table */
39754520Snw141292 	retcode = lookup_wksids_pid2sid(req, res, is_user);
39764520Snw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
39774520Snw141292 		goto out;
39784520Snw141292 
39795731Sbaban 	/* Lookup cache */
39806616Sdm199847 	retcode = lookup_cache_pid2sid(state->cache, req, res, is_user,
39816616Sdm199847 	    getname);
39824520Snw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
39834520Snw141292 		goto out;
39844520Snw141292 
39854520Snw141292 	/* Ephemeral ids cannot be allocated during pid2sid */
39864520Snw141292 	if (IS_EPHEMERAL(req->id1.idmap_id_u.uid)) {
39874864Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
39884520Snw141292 		goto out;
39894520Snw141292 	}
39904520Snw141292 
39916386Sjp151216 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req)) {
39926386Sjp151216 		retcode = IDMAP_ERR_NONEGENERATED;
39936386Sjp151216 		goto out;
39946386Sjp151216 	}
39956386Sjp151216 
39966386Sjp151216 	if (AVOID_NAMESERVICE(req)) {
39975731Sbaban 		gen_localsid_on_err = TRUE;
39984864Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
39994520Snw141292 		goto out;
40004520Snw141292 	}
40014520Snw141292 
40025731Sbaban 	/* Set flags for the next stage */
40035731Sbaban 	if (AD_MODE(req->id1.idtype, state)) {
40045731Sbaban 		/*
40055731Sbaban 		 * If AD-based name mapping is enabled then the next stage
40065731Sbaban 		 * will need to lookup AD using unixname to get the
40075731Sbaban 		 * corresponding winname.
40085731Sbaban 		 */
40095731Sbaban 		if (req->id1name == NULL) {
40105731Sbaban 			/* Get unixname if only pid is given. */
40115731Sbaban 			retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid,
40125731Sbaban 			    is_user, &req->id1name);
40136616Sdm199847 			if (retcode != IDMAP_SUCCESS) {
40146616Sdm199847 				gen_localsid_on_err = TRUE;
40155731Sbaban 				goto out;
40166616Sdm199847 			}
40174520Snw141292 		}
40185731Sbaban 		req->direction |= _IDMAP_F_LOOKUP_AD;
40195731Sbaban 		state->ad_nqueries++;
40205731Sbaban 	} else if (NLDAP_OR_MIXED_MODE(req->id1.idtype, state)) {
40215731Sbaban 		/*
40225731Sbaban 		 * If native LDAP or mixed mode is enabled for name mapping
40235731Sbaban 		 * then the next stage will need to lookup native LDAP using
40245731Sbaban 		 * unixname/pid to get the corresponding winname.
40255731Sbaban 		 */
40265731Sbaban 		req->direction |= _IDMAP_F_LOOKUP_NLDAP;
40275731Sbaban 		state->nldap_nqueries++;
40285731Sbaban 	}
40295731Sbaban 
40305731Sbaban 	/*
40315731Sbaban 	 * Failed to find non-expired entry in cache. Set the flag to
40325731Sbaban 	 * indicate that we are not done yet.
40335731Sbaban 	 */
40345731Sbaban 	state->pid2sid_done = FALSE;
40355731Sbaban 	req->direction |= _IDMAP_F_NOTDONE;
40365731Sbaban 	retcode = IDMAP_SUCCESS;
40375731Sbaban 
40385731Sbaban out:
40395731Sbaban 	res->retcode = idmap_stat4prot(retcode);
40405731Sbaban 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
40415731Sbaban 		if (gen_localsid_on_err == TRUE)
40426386Sjp151216 			(void) generate_localsid(req, res, is_user, TRUE);
40435731Sbaban 	return (retcode);
40445731Sbaban }
40455731Sbaban 
40465731Sbaban idmap_retcode
40476616Sdm199847 pid2sid_second_pass(lookup_state_t *state, idmap_mapping *req,
40486616Sdm199847 	idmap_id_res *res, int is_user)
40495731Sbaban {
40505731Sbaban 	bool_t		gen_localsid_on_err = TRUE;
40515731Sbaban 	idmap_retcode	retcode = IDMAP_SUCCESS;
40525731Sbaban 
40535731Sbaban 	/* Check if second pass is needed */
40545731Sbaban 	if (ARE_WE_DONE(req->direction))
40555731Sbaban 		return (res->retcode);
40565731Sbaban 
40575731Sbaban 	/* Get status from previous pass */
40585731Sbaban 	retcode = res->retcode;
40595731Sbaban 	if (retcode != IDMAP_SUCCESS)
40605731Sbaban 		goto out;
40615731Sbaban 
40625731Sbaban 	/*
40635731Sbaban 	 * If directory-based name mapping is enabled then the winname
40645731Sbaban 	 * may already have been retrieved from the AD object (AD-mode)
40656616Sdm199847 	 * or from native LDAP object (nldap-mode or mixed-mode).
40666616Sdm199847 	 * Note that if we have winname but no SID then it's an error
40676616Sdm199847 	 * because this implies that the Native LDAP entry contains
40686616Sdm199847 	 * winname which does not exist and it's better that we return
40696616Sdm199847 	 * an error instead of doing rule-based mapping so that the user
40706616Sdm199847 	 * can detect the issue and take appropriate action.
40715731Sbaban 	 */
40726616Sdm199847 	if (req->id2name != NULL) {
40736616Sdm199847 		/* Return notfound if we've winname but no SID. */
40746616Sdm199847 		if (res->id.idmap_id_u.sid.prefix == NULL) {
40756616Sdm199847 			retcode = IDMAP_ERR_NOTFOUND;
40766616Sdm199847 			goto out;
40776616Sdm199847 		}
40785731Sbaban 		if (AD_MODE(req->id1.idtype, state))
40795731Sbaban 			res->direction = IDMAP_DIRECTION_BI;
40805731Sbaban 		else if (NLDAP_MODE(req->id1.idtype, state))
40815731Sbaban 			res->direction = IDMAP_DIRECTION_BI;
40825731Sbaban 		else if (MIXED_MODE(req->id1.idtype, state))
40835731Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
40845731Sbaban 		goto out;
40856616Sdm199847 	} else if (res->id.idmap_id_u.sid.prefix != NULL) {
40866616Sdm199847 		/*
40876616Sdm199847 		 * We've SID but no winname. This is fine because
40886616Sdm199847 		 * the caller may have only requested SID.
40896616Sdm199847 		 */
40906616Sdm199847 		goto out;
40915731Sbaban 	}
40925731Sbaban 
40936616Sdm199847 	/* Free any mapping info from Directory based mapping */
40946616Sdm199847 	if (res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN)
40956616Sdm199847 		idmap_info_free(&res->info);
40966616Sdm199847 
40975731Sbaban 	if (req->id1name == NULL) {
40985731Sbaban 		/* Get unixname from name service */
40995731Sbaban 		retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid, is_user,
41005731Sbaban 		    &req->id1name);
41015731Sbaban 		if (retcode != IDMAP_SUCCESS)
41025731Sbaban 			goto out;
41035731Sbaban 	} else if (req->id1.idmap_id_u.uid == SENTINEL_PID) {
41045731Sbaban 		/* Get pid from name service */
41055731Sbaban 		retcode = ns_lookup_byname(req->id1name, NULL, &req->id1);
41065731Sbaban 		if (retcode != IDMAP_SUCCESS) {
41075731Sbaban 			gen_localsid_on_err = FALSE;
41085731Sbaban 			goto out;
41094520Snw141292 		}
41104520Snw141292 	}
41114520Snw141292 
41125731Sbaban 	/* Use unixname to evaluate local name-based mapping rules */
41136616Sdm199847 	retcode = name_based_mapping_pid2sid(state, req->id1name, is_user,
41145696Snw141292 	    req, res);
41154520Snw141292 	if (retcode == IDMAP_ERR_NOTFOUND) {
41166386Sjp151216 		retcode = generate_localsid(req, res, is_user, FALSE);
41175731Sbaban 		gen_localsid_on_err = FALSE;
41185731Sbaban 	}
41194520Snw141292 
41204520Snw141292 out:
41215731Sbaban 	res->retcode = idmap_stat4prot(retcode);
41225731Sbaban 	if (res->retcode != IDMAP_SUCCESS) {
41235731Sbaban 		req->direction = _IDMAP_F_DONE;
41246616Sdm199847 		free(req->id2name);
41256616Sdm199847 		req->id2name = NULL;
41266616Sdm199847 		free(req->id2domain);
41276616Sdm199847 		req->id2domain = NULL;
41285731Sbaban 		if (gen_localsid_on_err == TRUE)
41296386Sjp151216 			(void) generate_localsid(req, res, is_user, TRUE);
41306616Sdm199847 		else
41316616Sdm199847 			res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
41324520Snw141292 	}
41335731Sbaban 	if (!ARE_WE_DONE(req->direction))
41344520Snw141292 		state->pid2sid_done = FALSE;
41354520Snw141292 	return (retcode);
41364520Snw141292 }
41374520Snw141292 
41385696Snw141292 static
41395696Snw141292 int
41404644Sbaban copy_mapping_request(idmap_mapping *mapping, idmap_mapping *request)
41414520Snw141292 {
41424644Sbaban 	(void) memset(mapping, 0, sizeof (*mapping));
41434644Sbaban 
41444520Snw141292 	mapping->flag = request->flag;
41455731Sbaban 	mapping->direction = _IDMAP_F_DONE;
41464644Sbaban 	mapping->id2.idtype = request->id2.idtype;
41474520Snw141292 
41484520Snw141292 	mapping->id1.idtype = request->id1.idtype;
41495696Snw141292 	if (IS_REQUEST_SID(*request, 1)) {
41504520Snw141292 		mapping->id1.idmap_id_u.sid.rid =
41514520Snw141292 		    request->id1.idmap_id_u.sid.rid;
41524644Sbaban 		if (!EMPTY_STRING(request->id1.idmap_id_u.sid.prefix)) {
41534520Snw141292 			mapping->id1.idmap_id_u.sid.prefix =
41544520Snw141292 			    strdup(request->id1.idmap_id_u.sid.prefix);
41554644Sbaban 			if (mapping->id1.idmap_id_u.sid.prefix == NULL)
41565064Sdm199847 				goto errout;
41574644Sbaban 		}
41584520Snw141292 	} else {
41594520Snw141292 		mapping->id1.idmap_id_u.uid = request->id1.idmap_id_u.uid;
41604520Snw141292 	}
41614520Snw141292 
41625731Sbaban 	if (!EMPTY_STRING(request->id1domain)) {
41635731Sbaban 		mapping->id1domain = strdup(request->id1domain);
41645731Sbaban 		if (mapping->id1domain == NULL)
41655731Sbaban 			goto errout;
41665731Sbaban 	}
41675731Sbaban 
41685731Sbaban 	if (!EMPTY_STRING(request->id1name)) {
41695731Sbaban 		mapping->id1name = strdup(request->id1name);
41705731Sbaban 		if (mapping->id1name == NULL)
41715731Sbaban 			goto errout;
41725731Sbaban 	}
41734520Snw141292 
41744644Sbaban 	/* We don't need the rest of the request i.e request->id2 */
41754644Sbaban 	return (0);
41764644Sbaban 
41774644Sbaban errout:
41785064Sdm199847 	if (mapping->id1.idmap_id_u.sid.prefix != NULL)
41794644Sbaban 		free(mapping->id1.idmap_id_u.sid.prefix);
41805064Sdm199847 	if (mapping->id1domain != NULL)
41815064Sdm199847 		free(mapping->id1domain);
41825064Sdm199847 	if (mapping->id1name != NULL)
41835064Sdm199847 		free(mapping->id1name);
41844644Sbaban 
41854644Sbaban 	(void) memset(mapping, 0, sizeof (*mapping));
41864644Sbaban 	return (-1);
41874520Snw141292 }
41884520Snw141292 
41894520Snw141292 
41904520Snw141292 idmap_retcode
41914520Snw141292 get_w2u_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
41925696Snw141292 		idmap_mapping *mapping)
41935696Snw141292 {
41944520Snw141292 	idmap_id_res	idres;
41954520Snw141292 	lookup_state_t	state;
41965043Sbaban 	char		*cp;
41974520Snw141292 	idmap_retcode	retcode;
41984520Snw141292 	const char	*winname, *windomain;
41994520Snw141292 
42004520Snw141292 	(void) memset(&idres, 0, sizeof (idres));
42014520Snw141292 	(void) memset(&state, 0, sizeof (state));
42026616Sdm199847 	state.cache = cache;
42036616Sdm199847 	state.db = db;
42044520Snw141292 
42055731Sbaban 	/* Get directory-based name mapping info */
42066616Sdm199847 	retcode = load_cfg_in_state(&state);
42075731Sbaban 	if (retcode != IDMAP_SUCCESS)
42084520Snw141292 		goto out;
42095731Sbaban 
42105731Sbaban 	/*
42115731Sbaban 	 * Copy data from "request" to "mapping". Note that
42125731Sbaban 	 * empty strings are not copied from "request" to
42135731Sbaban 	 * "mapping" and therefore the coresponding strings in
42145731Sbaban 	 * "mapping" will be NULL. This eliminates having to
42155731Sbaban 	 * check for empty strings henceforth.
42165731Sbaban 	 */
42174644Sbaban 	if (copy_mapping_request(mapping, request) < 0) {
42184644Sbaban 		retcode = IDMAP_ERR_MEMORY;
42194644Sbaban 		goto out;
42204644Sbaban 	}
42214520Snw141292 
42225064Sdm199847 	winname = mapping->id1name;
42235064Sdm199847 	windomain = mapping->id1domain;
42244520Snw141292 
42255731Sbaban 	if (winname == NULL && windomain != NULL) {
42265731Sbaban 		retcode = IDMAP_ERR_ARG;
42275731Sbaban 		goto out;
42285731Sbaban 	}
42295731Sbaban 
42305731Sbaban 	/* Need atleast winname or sid to proceed */
42315731Sbaban 	if (winname == NULL && mapping->id1.idmap_id_u.sid.prefix == NULL) {
42324520Snw141292 		retcode = IDMAP_ERR_ARG;
42334520Snw141292 		goto out;
42344520Snw141292 	}
42354520Snw141292 
42365731Sbaban 	/*
42375731Sbaban 	 * If domainname is not given but we have a fully qualified
42385731Sbaban 	 * winname then extract the domainname from the winname,
42395731Sbaban 	 * otherwise use the default_domain from the config
42405731Sbaban 	 */
42415731Sbaban 	if (winname != NULL && windomain == NULL) {
42425064Sdm199847 		retcode = IDMAP_SUCCESS;
42435043Sbaban 		if ((cp = strchr(winname, '@')) != NULL) {
42445043Sbaban 			*cp = '\0';
42455064Sdm199847 			mapping->id1domain = strdup(cp + 1);
42465064Sdm199847 			if (mapping->id1domain == NULL)
42475064Sdm199847 				retcode = IDMAP_ERR_MEMORY;
42485731Sbaban 		} else if (lookup_wksids_name2sid(winname, NULL, NULL, NULL,
42495731Sbaban 		    NULL) != IDMAP_SUCCESS) {
42506950Sbaban 			if (state.defdom == NULL) {
42516950Sbaban 				/*
42526950Sbaban 				 * We have a non-qualified winname which is
42536950Sbaban 				 * neither the name of a well-known SID nor
42546950Sbaban 				 * there is a default domain with which we can
42556950Sbaban 				 * qualify it.
42566950Sbaban 				 */
42576950Sbaban 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
42586950Sbaban 			} else {
42596950Sbaban 				mapping->id1domain = strdup(state.defdom);
42606950Sbaban 				if (mapping->id1domain == NULL)
42616950Sbaban 					retcode = IDMAP_ERR_MEMORY;
42626950Sbaban 			}
42635064Sdm199847 		}
42644520Snw141292 		if (retcode != IDMAP_SUCCESS)
42654520Snw141292 			goto out;
42664520Snw141292 	}
42674520Snw141292 
42685731Sbaban 	/*
42695731Sbaban 	 * First pass looks up the well-known SIDs table and cache
42705731Sbaban 	 * and handles localSIDs
42715731Sbaban 	 */
42724520Snw141292 	state.sid2pid_done = TRUE;
42736616Sdm199847 	retcode = sid2pid_first_pass(&state, mapping, &idres);
42744520Snw141292 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
42754520Snw141292 		goto out;
42764520Snw141292 
42776616Sdm199847 	/* AD lookup */
42785731Sbaban 	if (state.ad_nqueries > 0) {
42796616Sdm199847 		retcode = ad_lookup_one(&state, mapping, &idres);
42805731Sbaban 		if (IDMAP_ERROR(retcode))
42815731Sbaban 			goto out;
42824520Snw141292 	}
42834520Snw141292 
42846616Sdm199847 	/* nldap lookup */
42856616Sdm199847 	if (state.nldap_nqueries > 0) {
42866616Sdm199847 		retcode = nldap_lookup_one(&state, mapping, &idres);
42876616Sdm199847 		if (IDMAP_FATAL_ERROR(retcode))
42885731Sbaban 			goto out;
42895731Sbaban 	}
42905731Sbaban 
42915731Sbaban 	/* Next pass performs name-based mapping and ephemeral mapping. */
42924520Snw141292 	state.sid2pid_done = TRUE;
42936616Sdm199847 	retcode = sid2pid_second_pass(&state, mapping, &idres);
42944520Snw141292 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
42954520Snw141292 		goto out;
42964520Snw141292 
42974520Snw141292 	/* Update cache */
42986616Sdm199847 	(void) update_cache_sid2pid(&state, mapping, &idres);
42994520Snw141292 
43004520Snw141292 out:
43015731Sbaban 	/*
43025731Sbaban 	 * Note that "mapping" is returned to the client. Therefore
43035731Sbaban 	 * copy whatever we have in "idres" to mapping->id2 and
43045731Sbaban 	 * free idres.
43055731Sbaban 	 */
43065731Sbaban 	mapping->direction = idres.direction;
43075731Sbaban 	mapping->id2 = idres.id;
43086386Sjp151216 	if (mapping->flag & IDMAP_REQ_FLG_MAPPING_INFO ||
43096386Sjp151216 	    retcode != IDMAP_SUCCESS)
43106386Sjp151216 		(void) idmap_info_mov(&mapping->info, &idres.info);
43116386Sjp151216 	else
43126386Sjp151216 		idmap_info_free(&idres.info);
43135731Sbaban 	(void) memset(&idres, 0, sizeof (idres));
43145731Sbaban 	if (retcode != IDMAP_SUCCESS)
43154864Sbaban 		mapping->id2.idmap_id_u.uid = UID_NOBODY;
43164520Snw141292 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
43175731Sbaban 	cleanup_lookup_state(&state);
43184520Snw141292 	return (retcode);
43194520Snw141292 }
43204520Snw141292 
43214520Snw141292 idmap_retcode
43224520Snw141292 get_u2w_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
43235696Snw141292 		idmap_mapping *mapping, int is_user)
43245696Snw141292 {
43254520Snw141292 	idmap_id_res	idres;
43264520Snw141292 	lookup_state_t	state;
43274520Snw141292 	idmap_retcode	retcode;
43284520Snw141292 
43294520Snw141292 	/*
43304520Snw141292 	 * In order to re-use the pid2sid code, we convert
43314520Snw141292 	 * our input data into structs that are expected by
43324520Snw141292 	 * pid2sid_first_pass.
43334520Snw141292 	 */
43344520Snw141292 
43354520Snw141292 	(void) memset(&idres, 0, sizeof (idres));
43364520Snw141292 	(void) memset(&state, 0, sizeof (state));
43376616Sdm199847 	state.cache = cache;
43386616Sdm199847 	state.db = db;
43394520Snw141292 
43405731Sbaban 	/* Get directory-based name mapping info */
43416616Sdm199847 	retcode = load_cfg_in_state(&state);
43425731Sbaban 	if (retcode != IDMAP_SUCCESS)
43435731Sbaban 		goto out;
43445731Sbaban 
43455731Sbaban 	/*
43465731Sbaban 	 * Copy data from "request" to "mapping". Note that
43475731Sbaban 	 * empty strings are not copied from "request" to
43485731Sbaban 	 * "mapping" and therefore the coresponding strings in
43495731Sbaban 	 * "mapping" will be NULL. This eliminates having to
43505731Sbaban 	 * check for empty strings henceforth.
43515731Sbaban 	 */
43524644Sbaban 	if (copy_mapping_request(mapping, request) < 0) {
43534644Sbaban 		retcode = IDMAP_ERR_MEMORY;
43544644Sbaban 		goto out;
43554644Sbaban 	}
43564520Snw141292 
43575731Sbaban 	/*
43585731Sbaban 	 * For unix to windows mapping request, we need atleast a
43595731Sbaban 	 * unixname or uid/gid to proceed
43605731Sbaban 	 */
43615731Sbaban 	if (mapping->id1name == NULL &&
43625127Sdm199847 	    mapping->id1.idmap_id_u.uid == SENTINEL_PID) {
43634520Snw141292 		retcode = IDMAP_ERR_ARG;
43644520Snw141292 		goto out;
43654520Snw141292 	}
43664520Snw141292 
43675731Sbaban 	/* First pass looks up cache and well-known SIDs */
43685731Sbaban 	state.pid2sid_done = TRUE;
43696616Sdm199847 	retcode = pid2sid_first_pass(&state, mapping, &idres, is_user, 1);
43705731Sbaban 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
43715731Sbaban 		goto out;
43725731Sbaban 
43736616Sdm199847 	/* nldap lookup */
43745731Sbaban 	if (state.nldap_nqueries > 0) {
43756616Sdm199847 		retcode = nldap_lookup_one(&state, mapping, &idres);
43765731Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
43775731Sbaban 			goto out;
43786616Sdm199847 	}
43796616Sdm199847 
43806616Sdm199847 	/* AD lookup */
43816616Sdm199847 	if (state.ad_nqueries > 0) {
43826616Sdm199847 		retcode = ad_lookup_one(&state, mapping, &idres);
43835731Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
43845731Sbaban 			goto out;
43854520Snw141292 	}
43864520Snw141292 
43875731Sbaban 	/*
43885731Sbaban 	 * Next pass processes the result of the preceding passes/lookups.
43895731Sbaban 	 * It returns if there's nothing more to be done otherwise it
43905731Sbaban 	 * evaluates local name-based mapping rules
43915731Sbaban 	 */
43924520Snw141292 	state.pid2sid_done = TRUE;
43936616Sdm199847 	retcode = pid2sid_second_pass(&state, mapping, &idres, is_user);
43944520Snw141292 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
43954520Snw141292 		goto out;
43964520Snw141292 
43974520Snw141292 	/* Update cache */
43986616Sdm199847 	(void) update_cache_pid2sid(&state, mapping, &idres);
43994520Snw141292 
44004520Snw141292 out:
44015731Sbaban 	/*
44025731Sbaban 	 * Note that "mapping" is returned to the client. Therefore
44035731Sbaban 	 * copy whatever we have in "idres" to mapping->id2 and
44045731Sbaban 	 * free idres.
44055731Sbaban 	 */
44064520Snw141292 	mapping->direction = idres.direction;
44074520Snw141292 	mapping->id2 = idres.id;
44086386Sjp151216 	if (mapping->flag & IDMAP_REQ_FLG_MAPPING_INFO ||
44096386Sjp151216 	    retcode != IDMAP_SUCCESS)
44106386Sjp151216 		(void) idmap_info_mov(&mapping->info, &idres.info);
44116386Sjp151216 	else
44126386Sjp151216 		idmap_info_free(&idres.info);
44134520Snw141292 	(void) memset(&idres, 0, sizeof (idres));
44144520Snw141292 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
44155731Sbaban 	cleanup_lookup_state(&state);
44164520Snw141292 	return (retcode);
44174520Snw141292 }
44185731Sbaban 
44196616Sdm199847 /*ARGSUSED*/
44205731Sbaban static
44215731Sbaban idmap_retcode
44226616Sdm199847 ad_lookup_one(lookup_state_t *state, idmap_mapping *req, idmap_id_res *res)
44235731Sbaban {
44246616Sdm199847 	idmap_mapping_batch	batch;
44256616Sdm199847 	idmap_ids_res		result;
44266616Sdm199847 
44276616Sdm199847 	batch.idmap_mapping_batch_len = 1;
44286616Sdm199847 	batch.idmap_mapping_batch_val = req;
44296616Sdm199847 	result.ids.ids_len = 1;
44306616Sdm199847 	result.ids.ids_val = res;
44316616Sdm199847 	return (ad_lookup_batch(state, &batch, &result));
44325731Sbaban }
4433