xref: /onnv-gate/usr/src/cmd/idmap/idmapd/dbutils.c (revision 7031:2738a61b5fd9)
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 #pragma ident	"%Z%%M%	%I%	%E% SMI"
274520Snw141292 
284520Snw141292 /*
294520Snw141292  * Database related utility routines
304520Snw141292  */
314520Snw141292 
324520Snw141292 #include <stdio.h>
334520Snw141292 #include <stdlib.h>
344520Snw141292 #include <string.h>
354520Snw141292 #include <errno.h>
364520Snw141292 #include <sys/types.h>
374520Snw141292 #include <sys/stat.h>
384520Snw141292 #include <rpc/rpc.h>
394520Snw141292 #include <sys/sid.h>
404520Snw141292 #include <time.h>
414520Snw141292 #include <pwd.h>
424520Snw141292 #include <grp.h>
434884Sjp151216 #include <pthread.h>
444884Sjp151216 #include <assert.h>
455696Snw141292 #include <sys/u8_textprep.h>
464520Snw141292 
474520Snw141292 #include "idmapd.h"
484520Snw141292 #include "adutils.h"
494520Snw141292 #include "string.h"
504520Snw141292 #include "idmap_priv.h"
515696Snw141292 #include "schema.h"
525731Sbaban #include "nldaputils.h"
534520Snw141292 
544884Sjp151216 
554520Snw141292 static idmap_retcode sql_compile_n_step_once(sqlite *, char *,
564520Snw141292 		sqlite_vm **, int *, int, const char ***);
576616Sdm199847 static idmap_retcode ad_lookup_one(lookup_state_t *, idmap_mapping *,
586616Sdm199847 		idmap_id_res *);
595731Sbaban static idmap_retcode lookup_localsid2pid(idmap_mapping *, idmap_id_res *);
605731Sbaban static idmap_retcode lookup_cache_name2sid(sqlite *, const char *,
615731Sbaban 		const char *, char **, char **, idmap_rid_t *, int *);
625731Sbaban 
634520Snw141292 
644520Snw141292 #define	EMPTY_NAME(name)	(*name == 0 || strcmp(name, "\"\"") == 0)
654520Snw141292 
664520Snw141292 #define	DO_NOT_ALLOC_NEW_ID_MAPPING(req)\
674520Snw141292 		(req->flag & IDMAP_REQ_FLG_NO_NEW_ID_ALLOC)
684520Snw141292 
694520Snw141292 #define	AVOID_NAMESERVICE(req)\
704520Snw141292 		(req->flag & IDMAP_REQ_FLG_NO_NAMESERVICE)
714520Snw141292 
725731Sbaban #define	IS_EPHEMERAL(pid)	(pid > INT32_MAX && pid != SENTINEL_PID)
734520Snw141292 
744520Snw141292 #define	LOCALRID_MIN	1000
754520Snw141292 
764520Snw141292 
774520Snw141292 typedef enum init_db_option {
784520Snw141292 	FAIL_IF_CORRUPT = 0,
794520Snw141292 	REMOVE_IF_CORRUPT = 1
804520Snw141292 } init_db_option_t;
814520Snw141292 
824884Sjp151216 /*
835731Sbaban  * Data structure to store well-known SIDs and
845731Sbaban  * associated mappings (if any)
855731Sbaban  */
865731Sbaban typedef struct wksids_table {
875731Sbaban 	const char	*sidprefix;
885731Sbaban 	uint32_t	rid;
895731Sbaban 	const char	*winname;
905731Sbaban 	int		is_wuser;
915731Sbaban 	uid_t		pid;
925731Sbaban 	int		is_user;
935731Sbaban 	int		direction;
945731Sbaban } wksids_table_t;
955731Sbaban 
965731Sbaban /*
974884Sjp151216  * Thread specfic data to hold the database handles so that the
984884Sjp151216  * databaes are not opened and closed for every request. It also
994884Sjp151216  * contains the sqlite busy handler structure.
1004884Sjp151216  */
1014884Sjp151216 
1024884Sjp151216 struct idmap_busy {
1034884Sjp151216 	const char *name;
1044884Sjp151216 	const int *delays;
1054884Sjp151216 	int delay_size;
1064884Sjp151216 	int total;
1074884Sjp151216 	int sec;
1084884Sjp151216 };
1094884Sjp151216 
1104884Sjp151216 
1114884Sjp151216 typedef struct idmap_tsd {
1124884Sjp151216 	sqlite *db_db;
1134884Sjp151216 	sqlite *cache_db;
1144884Sjp151216 	struct idmap_busy cache_busy;
1154884Sjp151216 	struct idmap_busy db_busy;
1164884Sjp151216 } idmap_tsd_t;
1174884Sjp151216 
1184884Sjp151216 
1194884Sjp151216 
1204884Sjp151216 static const int cache_delay_table[] =
1214884Sjp151216 		{ 1, 2, 5, 10, 15, 20, 25, 30,  35,  40,
1224884Sjp151216 		50,  50, 60, 70, 80, 90, 100};
1234884Sjp151216 
1244884Sjp151216 static const int db_delay_table[] =
1254884Sjp151216 		{ 5, 10, 15, 20, 30,  40,  55,  70, 100};
1264884Sjp151216 
1274884Sjp151216 
1284884Sjp151216 static pthread_key_t	idmap_tsd_key;
1294884Sjp151216 
1304884Sjp151216 void
1314884Sjp151216 idmap_tsd_destroy(void *key)
1324884Sjp151216 {
1334884Sjp151216 
1344884Sjp151216 	idmap_tsd_t	*tsd = (idmap_tsd_t *)key;
1354884Sjp151216 	if (tsd) {
1364884Sjp151216 		if (tsd->db_db)
1374884Sjp151216 			(void) sqlite_close(tsd->db_db);
1384884Sjp151216 		if (tsd->cache_db)
1394884Sjp151216 			(void) sqlite_close(tsd->cache_db);
1404884Sjp151216 		free(tsd);
1414884Sjp151216 	}
1424884Sjp151216 }
1434884Sjp151216 
1444884Sjp151216 int
1455696Snw141292 idmap_init_tsd_key(void)
1465696Snw141292 {
1474884Sjp151216 	return (pthread_key_create(&idmap_tsd_key, idmap_tsd_destroy));
1484884Sjp151216 }
1494884Sjp151216 
1504884Sjp151216 
1514884Sjp151216 
1524884Sjp151216 idmap_tsd_t *
1534884Sjp151216 idmap_get_tsd(void)
1544884Sjp151216 {
1554884Sjp151216 	idmap_tsd_t	*tsd;
1564884Sjp151216 
1574884Sjp151216 	if ((tsd = pthread_getspecific(idmap_tsd_key)) == NULL) {
1584884Sjp151216 		/* No thread specific data so create it */
1594884Sjp151216 		if ((tsd = malloc(sizeof (*tsd))) != NULL) {
1604884Sjp151216 			/* Initialize thread specific data */
1614884Sjp151216 			(void) memset(tsd, 0, sizeof (*tsd));
1624884Sjp151216 			/* save the trhread specific data */
1634884Sjp151216 			if (pthread_setspecific(idmap_tsd_key, tsd) != 0) {
1644884Sjp151216 				/* Can't store key */
1654884Sjp151216 				free(tsd);
1664884Sjp151216 				tsd = NULL;
1674884Sjp151216 			}
1684884Sjp151216 		} else {
1694884Sjp151216 			tsd = NULL;
1704884Sjp151216 		}
1714884Sjp151216 	}
1724884Sjp151216 
1734884Sjp151216 	return (tsd);
1744884Sjp151216 }
1754884Sjp151216 
1765696Snw141292 /*
1775696Snw141292  * A simple wrapper around u8_textprep_str() that returns the Unicode
1785696Snw141292  * lower-case version of some string.  The result must be freed.
1795696Snw141292  */
1805696Snw141292 char *
1815696Snw141292 tolower_u8(const char *s)
1825696Snw141292 {
1835696Snw141292 	char *res = NULL;
1845696Snw141292 	char *outs;
1855696Snw141292 	size_t inlen, outlen, inbytesleft, outbytesleft;
1865696Snw141292 	int rc, err;
1875696Snw141292 
1885696Snw141292 	/*
1895696Snw141292 	 * u8_textprep_str() does not allocate memory.  The input and
1905696Snw141292 	 * output buffers may differ in size (though that would be more
1915696Snw141292 	 * likely when normalization is done).  We have to loop over it...
1925696Snw141292 	 *
1935696Snw141292 	 * To improve the chances that we can avoid looping we add 10
1945696Snw141292 	 * bytes of output buffer room the first go around.
1955696Snw141292 	 */
1965696Snw141292 	inlen = inbytesleft = strlen(s);
1975696Snw141292 	outlen = outbytesleft = inlen + 10;
1985696Snw141292 	if ((res = malloc(outlen)) == NULL)
1995696Snw141292 		return (NULL);
2005696Snw141292 	outs = res;
2015696Snw141292 
2025696Snw141292 	while ((rc = u8_textprep_str((char *)s, &inbytesleft, outs,
2035696Snw141292 	    &outbytesleft, U8_TEXTPREP_TOLOWER, U8_UNICODE_LATEST, &err)) < 0 &&
2045696Snw141292 	    err == E2BIG) {
2055696Snw141292 		if ((res = realloc(res, outlen + inbytesleft)) == NULL)
2065696Snw141292 			return (NULL);
2075696Snw141292 		/* adjust input/output buffer pointers */
2085696Snw141292 		s += (inlen - inbytesleft);
2095696Snw141292 		outs = res + outlen - outbytesleft;
2105696Snw141292 		/* adjust outbytesleft and outlen */
2115696Snw141292 		outlen += inbytesleft;
2125696Snw141292 		outbytesleft += inbytesleft;
2135696Snw141292 	}
2145696Snw141292 
2155696Snw141292 	if (rc < 0) {
2165696Snw141292 		free(res);
2175696Snw141292 		res = NULL;
2185696Snw141292 		return (NULL);
2195696Snw141292 	}
2205696Snw141292 
2215696Snw141292 	res[outlen - outbytesleft] = '\0';
2225696Snw141292 
2235696Snw141292 	return (res);
2245696Snw141292 }
2255696Snw141292 
2265696Snw141292 static int sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
2275696Snw141292 	const char *while_doing);
2285696Snw141292 
2294520Snw141292 
2304520Snw141292 /*
2314520Snw141292  * Initialize 'dbname' using 'sql'
2324520Snw141292  */
2335696Snw141292 static
2345696Snw141292 int
2355696Snw141292 init_db_instance(const char *dbname, int version,
2365696Snw141292 	const char *detect_version_sql, char * const *sql,
2375696Snw141292 	init_db_option_t opt, int *created, int *upgraded)
2384520Snw141292 {
2395696Snw141292 	int rc, curr_version;
2405696Snw141292 	int tries = 1;
2415696Snw141292 	int prio = LOG_NOTICE;
2424520Snw141292 	sqlite *db = NULL;
2435696Snw141292 	char *errmsg = NULL;
2445696Snw141292 
2455696Snw141292 	*created = 0;
2465696Snw141292 	*upgraded = 0;
2475696Snw141292 
2485696Snw141292 	if (opt == REMOVE_IF_CORRUPT)
2495696Snw141292 		tries = 3;
2505696Snw141292 
2515696Snw141292 rinse_repeat:
2525696Snw141292 	if (tries == 0) {
2535696Snw141292 		idmapdlog(LOG_ERR, "Failed to initialize db %s", dbname);
2545696Snw141292 		return (-1);
2555696Snw141292 	}
2565696Snw141292 	if (tries-- == 1)
2575696Snw141292 		/* Last try, log errors */
2585696Snw141292 		prio = LOG_ERR;
2595696Snw141292 
2605696Snw141292 	db = sqlite_open(dbname, 0600, &errmsg);
2615696Snw141292 	if (db == NULL) {
2625696Snw141292 		idmapdlog(prio, "Error creating database %s (%s)",
2635696Snw141292 		    dbname, CHECK_NULL(errmsg));
2645696Snw141292 		sqlite_freemem(errmsg);
2655696Snw141292 		if (opt == REMOVE_IF_CORRUPT)
2665696Snw141292 			(void) unlink(dbname);
2675696Snw141292 		goto rinse_repeat;
2684520Snw141292 	}
2694520Snw141292 
2704520Snw141292 	sqlite_busy_timeout(db, 3000);
2715696Snw141292 
2725696Snw141292 	/* Detect current version of schema in the db, if any */
2735696Snw141292 	curr_version = 0;
2745696Snw141292 	if (detect_version_sql != NULL) {
2755696Snw141292 		char *end, **results;
2765696Snw141292 		int nrow;
2775696Snw141292 
2785696Snw141292 #ifdef	IDMAPD_DEBUG
2795696Snw141292 		(void) fprintf(stderr, "Schema version detection SQL: %s\n",
2805696Snw141292 		    detect_version_sql);
2815696Snw141292 #endif	/* IDMAPD_DEBUG */
2825696Snw141292 		rc = sqlite_get_table(db, detect_version_sql, &results,
2835696Snw141292 		    &nrow, NULL, &errmsg);
2845696Snw141292 		if (rc != SQLITE_OK) {
2855696Snw141292 			idmapdlog(prio,
2865696Snw141292 			    "Error detecting schema version of db %s (%s)",
2875696Snw141292 			    dbname, errmsg);
2885696Snw141292 			sqlite_freemem(errmsg);
2895696Snw141292 			sqlite_free_table(results);
2905696Snw141292 			sqlite_close(db);
2915696Snw141292 			return (-1);
2925696Snw141292 		}
2935696Snw141292 		if (nrow != 1) {
2945696Snw141292 			idmapdlog(prio,
2955696Snw141292 			    "Error detecting schema version of db %s", dbname);
2965696Snw141292 			sqlite_close(db);
2975696Snw141292 			sqlite_free_table(results);
2985696Snw141292 			return (-1);
2995696Snw141292 		}
3005696Snw141292 		curr_version = strtol(results[1], &end, 10);
3015696Snw141292 		sqlite_free_table(results);
3024520Snw141292 	}
3034520Snw141292 
3045696Snw141292 	if (curr_version < 0) {
3055696Snw141292 		if (opt == REMOVE_IF_CORRUPT)
3065696Snw141292 			(void) unlink(dbname);
3075696Snw141292 		goto rinse_repeat;
3084520Snw141292 	}
3094520Snw141292 
3105696Snw141292 	if (curr_version == version)
3115696Snw141292 		goto done;
3125696Snw141292 
3135696Snw141292 	/* Install or upgrade schema */
3145696Snw141292 #ifdef	IDMAPD_DEBUG
3155696Snw141292 	(void) fprintf(stderr, "Schema init/upgrade SQL: %s\n",
3165696Snw141292 	    sql[curr_version]);
3175696Snw141292 #endif	/* IDMAPD_DEBUG */
3185696Snw141292 	rc = sql_exec_tran_no_cb(db, sql[curr_version], dbname,
3195696Snw141292 	    (curr_version == 0) ? "installing schema" : "upgrading schema");
3205696Snw141292 	if (rc != 0) {
3215696Snw141292 		idmapdlog(prio, "Error %s schema for db %s", dbname,
3225696Snw141292 		    (curr_version == 0) ? "installing schema" :
3235696Snw141292 		    "upgrading schema");
3245696Snw141292 		if (opt == REMOVE_IF_CORRUPT)
3255696Snw141292 			(void) unlink(dbname);
3265696Snw141292 		goto rinse_repeat;
3274520Snw141292 	}
3284520Snw141292 
3295696Snw141292 	*upgraded = (curr_version > 0);
3305696Snw141292 	*created = (curr_version == 0);
3315696Snw141292 
3325696Snw141292 done:
3334520Snw141292 	(void) sqlite_close(db);
3345696Snw141292 	return (0);
3354520Snw141292 }
3364520Snw141292 
3374884Sjp151216 
3384884Sjp151216 /*
3394884Sjp151216  * This is the SQLite database busy handler that retries the SQL
3404884Sjp151216  * operation until it is successful.
3414884Sjp151216  */
3424884Sjp151216 int
3434884Sjp151216 /* LINTED E_FUNC_ARG_UNUSED */
3444884Sjp151216 idmap_sqlite_busy_handler(void *arg, const char *table_name, int count)
3454884Sjp151216 {
3464884Sjp151216 	struct idmap_busy	*busy = arg;
3474884Sjp151216 	int			delay;
3484884Sjp151216 	struct timespec		rqtp;
3494884Sjp151216 
3504884Sjp151216 	if (count == 1)  {
3514884Sjp151216 		busy->total = 0;
3524884Sjp151216 		busy->sec = 2;
3534884Sjp151216 	}
3544884Sjp151216 	if (busy->total > 1000 * busy->sec) {
3556414Sjp151216 		idmapdlog(LOG_DEBUG,
3564884Sjp151216 		    "Thread %d waited %d sec for the %s database",
3574884Sjp151216 		    pthread_self(), busy->sec, busy->name);
3584884Sjp151216 		busy->sec++;
3594884Sjp151216 	}
3604884Sjp151216 
3614884Sjp151216 	if (count <= busy->delay_size) {
3624884Sjp151216 		delay = busy->delays[count-1];
3634884Sjp151216 	} else {
3644884Sjp151216 		delay = busy->delays[busy->delay_size - 1];
3654884Sjp151216 	}
3664884Sjp151216 	busy->total += delay;
3674884Sjp151216 	rqtp.tv_sec = 0;
3684884Sjp151216 	rqtp.tv_nsec = delay * (NANOSEC / MILLISEC);
3694884Sjp151216 	(void) nanosleep(&rqtp, NULL);
3704884Sjp151216 	return (1);
3714884Sjp151216 }
3724884Sjp151216 
3734884Sjp151216 
3744520Snw141292 /*
3754520Snw141292  * Get the database handle
3764520Snw141292  */
3774520Snw141292 idmap_retcode
3785696Snw141292 get_db_handle(sqlite **db)
3795696Snw141292 {
3805696Snw141292 	char		*errmsg;
3815696Snw141292 	idmap_tsd_t	*tsd;
3824520Snw141292 
3834520Snw141292 	/*
3844884Sjp151216 	 * Retrieve the db handle from thread-specific storage
3854520Snw141292 	 * If none exists, open and store in thread-specific storage.
3864520Snw141292 	 */
3874884Sjp151216 	if ((tsd = idmap_get_tsd()) == NULL) {
3884520Snw141292 		idmapdlog(LOG_ERR,
3895696Snw141292 		    "Error getting thread specific data for %s", IDMAP_DBNAME);
3904884Sjp151216 		return (IDMAP_ERR_MEMORY);
3914520Snw141292 	}
3924884Sjp151216 
3934884Sjp151216 	if (tsd->db_db == NULL) {
3944884Sjp151216 		tsd->db_db = sqlite_open(IDMAP_DBNAME, 0, &errmsg);
3954884Sjp151216 		if (tsd->db_db == NULL) {
3965696Snw141292 			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
3975696Snw141292 			    IDMAP_DBNAME, CHECK_NULL(errmsg));
3984884Sjp151216 			sqlite_freemem(errmsg);
3995696Snw141292 			return (IDMAP_ERR_DB);
4004884Sjp151216 		}
4015696Snw141292 
4024884Sjp151216 		tsd->db_busy.name = IDMAP_DBNAME;
4034884Sjp151216 		tsd->db_busy.delays = db_delay_table;
4044884Sjp151216 		tsd->db_busy.delay_size = sizeof (db_delay_table) /
4054884Sjp151216 		    sizeof (int);
4064884Sjp151216 		sqlite_busy_handler(tsd->db_db, idmap_sqlite_busy_handler,
4074884Sjp151216 		    &tsd->db_busy);
4084884Sjp151216 	}
4094884Sjp151216 	*db = tsd->db_db;
4104520Snw141292 	return (IDMAP_SUCCESS);
4114520Snw141292 }
4124520Snw141292 
4134520Snw141292 /*
4144520Snw141292  * Get the cache handle
4154520Snw141292  */
4164520Snw141292 idmap_retcode
4175696Snw141292 get_cache_handle(sqlite **cache)
4185696Snw141292 {
4195696Snw141292 	char		*errmsg;
4205696Snw141292 	idmap_tsd_t	*tsd;
4214520Snw141292 
4224520Snw141292 	/*
4234884Sjp151216 	 * Retrieve the db handle from thread-specific storage
4244520Snw141292 	 * If none exists, open and store in thread-specific storage.
4254520Snw141292 	 */
4264884Sjp151216 	if ((tsd = idmap_get_tsd()) == NULL) {
4275696Snw141292 		idmapdlog(LOG_ERR, "Error getting thread specific data for %s",
4285696Snw141292 		    IDMAP_DBNAME);
4294884Sjp151216 		return (IDMAP_ERR_MEMORY);
4304520Snw141292 	}
4314884Sjp151216 
4324884Sjp151216 	if (tsd->cache_db == NULL) {
4334884Sjp151216 		tsd->cache_db = sqlite_open(IDMAP_CACHENAME, 0, &errmsg);
4344884Sjp151216 		if (tsd->cache_db == NULL) {
4355696Snw141292 			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
4365696Snw141292 			    IDMAP_CACHENAME, CHECK_NULL(errmsg));
4374884Sjp151216 			sqlite_freemem(errmsg);
4385696Snw141292 			return (IDMAP_ERR_DB);
4394884Sjp151216 		}
4405696Snw141292 
4414884Sjp151216 		tsd->cache_busy.name = IDMAP_CACHENAME;
4424884Sjp151216 		tsd->cache_busy.delays = cache_delay_table;
4434884Sjp151216 		tsd->cache_busy.delay_size = sizeof (cache_delay_table) /
4444884Sjp151216 		    sizeof (int);
4454884Sjp151216 		sqlite_busy_handler(tsd->cache_db, idmap_sqlite_busy_handler,
4464884Sjp151216 		    &tsd->cache_busy);
4474884Sjp151216 	}
4484884Sjp151216 	*cache = tsd->cache_db;
4494520Snw141292 	return (IDMAP_SUCCESS);
4504520Snw141292 }
4514520Snw141292 
4524520Snw141292 /*
4534520Snw141292  * Initialize cache and db
4544520Snw141292  */
4554520Snw141292 int
4565696Snw141292 init_dbs()
4575696Snw141292 {
4586386Sjp151216 	char *sql[4];
4595696Snw141292 	int created, upgraded;
4605696Snw141292 
4614520Snw141292 	/* name-based mappings; probably OK to blow away in a pinch(?) */
4625696Snw141292 	sql[0] = DB_INSTALL_SQL;
4635696Snw141292 	sql[1] = DB_UPGRADE_FROM_v1_SQL;
4646386Sjp151216 	sql[2] = NULL;
4655696Snw141292 
4665696Snw141292 	if (init_db_instance(IDMAP_DBNAME, DB_VERSION, DB_VERSION_SQL, sql,
4675696Snw141292 	    FAIL_IF_CORRUPT, &created, &upgraded) < 0)
4684520Snw141292 		return (-1);
4694520Snw141292 
4704520Snw141292 	/* mappings, name/SID lookup cache + ephemeral IDs; OK to blow away */
4715696Snw141292 	sql[0] = CACHE_INSTALL_SQL;
4725696Snw141292 	sql[1] = CACHE_UPGRADE_FROM_v1_SQL;
4736386Sjp151216 	sql[2] = CACHE_UPGRADE_FROM_v2_SQL;
4746386Sjp151216 	sql[3] = NULL;
4756386Sjp151216 
4765696Snw141292 	if (init_db_instance(IDMAP_CACHENAME, CACHE_VERSION, CACHE_VERSION_SQL,
4775696Snw141292 	    sql, REMOVE_IF_CORRUPT, &created, &upgraded) < 0)
4784520Snw141292 		return (-1);
4794520Snw141292 
4805696Snw141292 	_idmapdstate.new_eph_db = (created || upgraded) ? 1 : 0;
4815696Snw141292 
4824520Snw141292 	return (0);
4834520Snw141292 }
4844520Snw141292 
4854520Snw141292 /*
4864520Snw141292  * Finalize databases
4874520Snw141292  */
4884520Snw141292 void
4895696Snw141292 fini_dbs()
4905696Snw141292 {
4914520Snw141292 }
4924520Snw141292 
4934520Snw141292 /*
4945731Sbaban  * This table is a listing of status codes that will be returned to the
4954520Snw141292  * client when a SQL command fails with the corresponding error message.
4964520Snw141292  */
4974520Snw141292 static msg_table_t sqlmsgtable[] = {
4984864Sbaban 	{IDMAP_ERR_U2W_NAMERULE_CONFLICT,
4994520Snw141292 	"columns unixname, is_user, u2w_order are not unique"},
5004864Sbaban 	{IDMAP_ERR_W2U_NAMERULE_CONFLICT,
5015696Snw141292 	"columns winname, windomain, is_user, is_wuser, w2u_order are not"
5025696Snw141292 	" unique"},
5035696Snw141292 	{IDMAP_ERR_W2U_NAMERULE_CONFLICT, "Conflicting w2u namerules"},
5044520Snw141292 	{-1, NULL}
5054520Snw141292 };
5064520Snw141292 
5074520Snw141292 /*
5084520Snw141292  * idmapd's version of string2stat to map SQLite messages to
5094520Snw141292  * status codes
5104520Snw141292  */
5114520Snw141292 idmap_retcode
5125696Snw141292 idmapd_string2stat(const char *msg)
5135696Snw141292 {
5144520Snw141292 	int i;
5154520Snw141292 	for (i = 0; sqlmsgtable[i].msg; i++) {
5164520Snw141292 		if (strcasecmp(sqlmsgtable[i].msg, msg) == 0)
5174520Snw141292 			return (sqlmsgtable[i].retcode);
5184520Snw141292 	}
5194520Snw141292 	return (IDMAP_ERR_OTHER);
5204520Snw141292 }
5214520Snw141292 
5224520Snw141292 /*
5235696Snw141292  * Executes some SQL in a transaction.
5245696Snw141292  *
5255696Snw141292  * Returns 0 on success, -1 if it failed but the rollback succeeded, -2
5265696Snw141292  * if the rollback failed.
5275696Snw141292  */
5285696Snw141292 static
5295696Snw141292 int
5305696Snw141292 sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
5315696Snw141292 	const char *while_doing)
5325696Snw141292 {
5335696Snw141292 	char		*errmsg = NULL;
5345696Snw141292 	int		rc;
5355696Snw141292 
5365696Snw141292 	rc = sqlite_exec(db, "BEGIN TRANSACTION;", NULL, NULL, &errmsg);
5375696Snw141292 	if (rc != SQLITE_OK) {
5385696Snw141292 		idmapdlog(LOG_ERR, "Begin transaction failed (%s) "
5395696Snw141292 		    "while %s (%s)", errmsg, while_doing, dbname);
5405696Snw141292 		sqlite_freemem(errmsg);
5415696Snw141292 		return (-1);
5425696Snw141292 	}
5435696Snw141292 
5445696Snw141292 	rc = sqlite_exec(db, sql, NULL, NULL, &errmsg);
5455696Snw141292 	if (rc != SQLITE_OK) {
5465696Snw141292 		idmapdlog(LOG_ERR, "Database error (%s) while %s (%s)", errmsg,
5475696Snw141292 		    while_doing, dbname);
5485696Snw141292 		sqlite_freemem(errmsg);
5495696Snw141292 		errmsg = NULL;
5505696Snw141292 		goto rollback;
5515696Snw141292 	}
5525696Snw141292 
5535696Snw141292 	rc = sqlite_exec(db, "COMMIT TRANSACTION", NULL, NULL, &errmsg);
5545696Snw141292 	if (rc == SQLITE_OK) {
5555696Snw141292 		sqlite_freemem(errmsg);
5565696Snw141292 		return (0);
5575696Snw141292 	}
5585696Snw141292 
5595696Snw141292 	idmapdlog(LOG_ERR, "Database commit error (%s) while s (%s)",
5605696Snw141292 	    errmsg, while_doing, dbname);
5615696Snw141292 	sqlite_freemem(errmsg);
5625696Snw141292 	errmsg = NULL;
5635696Snw141292 
5645696Snw141292 rollback:
5655696Snw141292 	rc = sqlite_exec(db, "ROLLBACK TRANSACTION", NULL, NULL, &errmsg);
5665696Snw141292 	if (rc != SQLITE_OK) {
5675696Snw141292 		idmapdlog(LOG_ERR, "Rollback failed (%s) while %s (%s)",
5685696Snw141292 		    errmsg, while_doing, dbname);
5695696Snw141292 		sqlite_freemem(errmsg);
5705696Snw141292 		return (-2);
5715696Snw141292 	}
5725696Snw141292 	sqlite_freemem(errmsg);
5735696Snw141292 
5745696Snw141292 	return (-1);
5755696Snw141292 }
5765696Snw141292 
5775696Snw141292 /*
5784520Snw141292  * Execute the given SQL statment without using any callbacks
5794520Snw141292  */
5804520Snw141292 idmap_retcode
5816017Snw141292 sql_exec_no_cb(sqlite *db, const char *dbname, char *sql)
5825696Snw141292 {
5834520Snw141292 	char		*errmsg = NULL;
5844884Sjp151216 	int		r;
5854520Snw141292 	idmap_retcode	retcode;
5864520Snw141292 
5874884Sjp151216 	r = sqlite_exec(db, sql, NULL, NULL, &errmsg);
5884884Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
5894520Snw141292 
5904520Snw141292 	if (r != SQLITE_OK) {
5916017Snw141292 		idmapdlog(LOG_ERR, "Database error on %s while executing %s "
5926017Snw141292 		    "(%s)", dbname, sql, CHECK_NULL(errmsg));
5934884Sjp151216 		retcode = idmapd_string2stat(errmsg);
5944864Sbaban 		if (errmsg != NULL)
5954520Snw141292 			sqlite_freemem(errmsg);
5964520Snw141292 		return (retcode);
5974520Snw141292 	}
5984520Snw141292 
5994520Snw141292 	return (IDMAP_SUCCESS);
6004520Snw141292 }
6014520Snw141292 
6024520Snw141292 /*
6034520Snw141292  * Generate expression that can be used in WHERE statements.
6044520Snw141292  * Examples:
6054520Snw141292  * <prefix> <col>      <op> <value>   <suffix>
6064520Snw141292  * ""       "unixuser" "="  "foo" "AND"
6074520Snw141292  */
6084520Snw141292 idmap_retcode
6095696Snw141292 gen_sql_expr_from_rule(idmap_namerule *rule, char **out)
6105696Snw141292 {
6115696Snw141292 	char	*s_windomain = NULL, *s_winname = NULL;
6125696Snw141292 	char	*s_unixname = NULL;
6135696Snw141292 	char	*lower_winname;
6145696Snw141292 	int	retcode = IDMAP_SUCCESS;
6155696Snw141292 
6164520Snw141292 	if (out == NULL)
6174520Snw141292 		return (IDMAP_ERR_ARG);
6184520Snw141292 
6195696Snw141292 
6205696Snw141292 	if (!EMPTY_STRING(rule->windomain)) {
6215696Snw141292 		s_windomain =  sqlite_mprintf("AND windomain = %Q ",
6225696Snw141292 		    rule->windomain);
6235696Snw141292 		if (s_windomain == NULL) {
6245696Snw141292 			retcode = IDMAP_ERR_MEMORY;
6255696Snw141292 			goto out;
6265696Snw141292 		}
6275696Snw141292 	}
6285696Snw141292 
6295696Snw141292 	if (!EMPTY_STRING(rule->winname)) {
6305696Snw141292 		if ((lower_winname = tolower_u8(rule->winname)) == NULL)
6315696Snw141292 			lower_winname = rule->winname;
6325696Snw141292 		s_winname = sqlite_mprintf(
6335696Snw141292 		    "AND winname = %Q AND is_wuser = %d ",
6345696Snw141292 		    lower_winname, rule->is_wuser ? 1 : 0);
6355696Snw141292 		if (lower_winname != rule->winname)
6365696Snw141292 			free(lower_winname);
6375696Snw141292 		if (s_winname == NULL) {
6385696Snw141292 			retcode = IDMAP_ERR_MEMORY;
6395696Snw141292 			goto out;
6405696Snw141292 		}
6415696Snw141292 	}
6425696Snw141292 
6435696Snw141292 	if (!EMPTY_STRING(rule->unixname)) {
6445696Snw141292 		s_unixname = sqlite_mprintf(
6455696Snw141292 		    "AND unixname = %Q AND is_user = %d ",
6465696Snw141292 		    rule->unixname, rule->is_user ? 1 : 0);
6475696Snw141292 		if (s_unixname == NULL) {
6485696Snw141292 			retcode = IDMAP_ERR_MEMORY;
6495696Snw141292 			goto out;
6505696Snw141292 		}
6515696Snw141292 	}
6525696Snw141292 
6535696Snw141292 	*out = sqlite_mprintf("%s %s %s",
6545696Snw141292 	    s_windomain ? s_windomain : "",
6555696Snw141292 	    s_winname ? s_winname : "",
6565696Snw141292 	    s_unixname ? s_unixname : "");
6575696Snw141292 
6585696Snw141292 	if (*out == NULL) {
6595696Snw141292 		retcode = IDMAP_ERR_MEMORY;
6605696Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
6615696Snw141292 		goto out;
6625696Snw141292 	}
6635696Snw141292 
6645696Snw141292 out:
6655696Snw141292 	if (s_windomain != NULL)
6665696Snw141292 		sqlite_freemem(s_windomain);
6675696Snw141292 	if (s_winname != NULL)
6685696Snw141292 		sqlite_freemem(s_winname);
6695696Snw141292 	if (s_unixname != NULL)
6705696Snw141292 		sqlite_freemem(s_unixname);
6715696Snw141292 
6725696Snw141292 	return (retcode);
6734520Snw141292 }
6744520Snw141292 
6755696Snw141292 
6765696Snw141292 
6774520Snw141292 /*
6784520Snw141292  * Generate and execute SQL statement for LIST RPC calls
6794520Snw141292  */
6804520Snw141292 idmap_retcode
6816017Snw141292 process_list_svc_sql(sqlite *db, const char *dbname, char *sql, uint64_t limit,
6826386Sjp151216 		int flag, list_svc_cb cb, void *result)
6835696Snw141292 {
6844520Snw141292 	list_cb_data_t	cb_data;
6854520Snw141292 	char		*errmsg = NULL;
6864884Sjp151216 	int		r;
6874520Snw141292 	idmap_retcode	retcode = IDMAP_ERR_INTERNAL;
6884520Snw141292 
6894520Snw141292 	(void) memset(&cb_data, 0, sizeof (cb_data));
6904520Snw141292 	cb_data.result = result;
6914520Snw141292 	cb_data.limit = limit;
6926386Sjp151216 	cb_data.flag = flag;
6934520Snw141292 
6944884Sjp151216 
6954884Sjp151216 	r = sqlite_exec(db, sql, cb, &cb_data, &errmsg);
6964884Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
6974884Sjp151216 	switch (r) {
6984884Sjp151216 	case SQLITE_OK:
6994884Sjp151216 		retcode = IDMAP_SUCCESS;
7004884Sjp151216 		break;
7014884Sjp151216 
7024884Sjp151216 	default:
7034884Sjp151216 		retcode = IDMAP_ERR_INTERNAL;
7046017Snw141292 		idmapdlog(LOG_ERR, "Database error on %s while executing "
7056017Snw141292 		    "%s (%s)", dbname, sql, CHECK_NULL(errmsg));
7064884Sjp151216 		break;
7074520Snw141292 	}
7084864Sbaban 	if (errmsg != NULL)
7094520Snw141292 		sqlite_freemem(errmsg);
7104520Snw141292 	return (retcode);
7114520Snw141292 }
7124520Snw141292 
7134520Snw141292 /*
7144520Snw141292  * This routine is called by callbacks that process the results of
7154520Snw141292  * LIST RPC calls to validate data and to allocate memory for
7164520Snw141292  * the result array.
7174520Snw141292  */
7184520Snw141292 idmap_retcode
7194520Snw141292 validate_list_cb_data(list_cb_data_t *cb_data, int argc, char **argv,
7205696Snw141292 		int ncol, uchar_t **list, size_t valsize)
7215696Snw141292 {
7224520Snw141292 	size_t	nsize;
7234520Snw141292 	void	*tmplist;
7244520Snw141292 
7254520Snw141292 	if (cb_data->limit > 0 && cb_data->next == cb_data->limit)
7264520Snw141292 		return (IDMAP_NEXT);
7274520Snw141292 
7284520Snw141292 	if (argc < ncol || argv == NULL) {
7294520Snw141292 		idmapdlog(LOG_ERR, "Invalid data");
7304520Snw141292 		return (IDMAP_ERR_INTERNAL);
7314520Snw141292 	}
7324520Snw141292 
7334520Snw141292 	/* alloc in bulk to reduce number of reallocs */
7344520Snw141292 	if (cb_data->next >= cb_data->len) {
7354520Snw141292 		nsize = (cb_data->len + SIZE_INCR) * valsize;
7364520Snw141292 		tmplist = realloc(*list, nsize);
7374520Snw141292 		if (tmplist == NULL) {
7384520Snw141292 			idmapdlog(LOG_ERR, "Out of memory");
7394520Snw141292 			return (IDMAP_ERR_MEMORY);
7404520Snw141292 		}
7414520Snw141292 		*list = tmplist;
7424520Snw141292 		(void) memset(*list + (cb_data->len * valsize), 0,
7435696Snw141292 		    SIZE_INCR * valsize);
7444520Snw141292 		cb_data->len += SIZE_INCR;
7454520Snw141292 	}
7464520Snw141292 	return (IDMAP_SUCCESS);
7474520Snw141292 }
7484520Snw141292 
7495696Snw141292 static
7505696Snw141292 idmap_retcode
7514520Snw141292 get_namerule_order(char *winname, char *windomain, char *unixname,
7525696Snw141292 	int direction, int is_diagonal, int *w2u_order, int *u2w_order)
7535696Snw141292 {
7544520Snw141292 	*w2u_order = 0;
7554520Snw141292 	*u2w_order = 0;
7564520Snw141292 
7574520Snw141292 	/*
7584520Snw141292 	 * Windows to UNIX lookup order:
7594520Snw141292 	 *  1. winname@domain (or winname) to ""
7604520Snw141292 	 *  2. winname@domain (or winname) to unixname
7614520Snw141292 	 *  3. winname@* to ""
7624520Snw141292 	 *  4. winname@* to unixname
7634520Snw141292 	 *  5. *@domain (or *) to *
7644520Snw141292 	 *  6. *@domain (or *) to ""
7654520Snw141292 	 *  7. *@domain (or *) to unixname
7664520Snw141292 	 *  8. *@* to *
7674520Snw141292 	 *  9. *@* to ""
7684520Snw141292 	 * 10. *@* to unixname
7694520Snw141292 	 *
7704520Snw141292 	 * winname is a special case of winname@domain when domain is the
7714520Snw141292 	 * default domain. Similarly * is a special case of *@domain when
7724520Snw141292 	 * domain is the default domain.
7734520Snw141292 	 *
7744520Snw141292 	 * Note that "" has priority over specific names because "" inhibits
7754520Snw141292 	 * mappings and traditionally deny rules always had higher priority.
7764520Snw141292 	 */
7774644Sbaban 	if (direction != IDMAP_DIRECTION_U2W) {
7784644Sbaban 		/* bi-directional or from windows to unix */
7794520Snw141292 		if (winname == NULL)
7804520Snw141292 			return (IDMAP_ERR_W2U_NAMERULE);
7814520Snw141292 		else if (unixname == NULL)
7824520Snw141292 			return (IDMAP_ERR_W2U_NAMERULE);
7834520Snw141292 		else if (EMPTY_NAME(winname))
7844520Snw141292 			return (IDMAP_ERR_W2U_NAMERULE);
7854520Snw141292 		else if (*winname == '*' && windomain && *windomain == '*') {
7864520Snw141292 			if (*unixname == '*')
7874520Snw141292 				*w2u_order = 8;
7884520Snw141292 			else if (EMPTY_NAME(unixname))
7894520Snw141292 				*w2u_order = 9;
7904520Snw141292 			else /* unixname == name */
7914520Snw141292 				*w2u_order = 10;
7924520Snw141292 		} else if (*winname == '*') {
7934520Snw141292 			if (*unixname == '*')
7944520Snw141292 				*w2u_order = 5;
7954520Snw141292 			else if (EMPTY_NAME(unixname))
7964520Snw141292 				*w2u_order = 6;
7974520Snw141292 			else /* name */
7984520Snw141292 				*w2u_order = 7;
7994864Sbaban 		} else if (windomain != NULL && *windomain == '*') {
8004520Snw141292 			/* winname == name */
8014520Snw141292 			if (*unixname == '*')
8024520Snw141292 				return (IDMAP_ERR_W2U_NAMERULE);
8034520Snw141292 			else if (EMPTY_NAME(unixname))
8044520Snw141292 				*w2u_order = 3;
8054520Snw141292 			else /* name */
8064520Snw141292 				*w2u_order = 4;
8074520Snw141292 		} else  {
8084520Snw141292 			/* winname == name && windomain == null or name */
8094520Snw141292 			if (*unixname == '*')
8104520Snw141292 				return (IDMAP_ERR_W2U_NAMERULE);
8114520Snw141292 			else if (EMPTY_NAME(unixname))
8124520Snw141292 				*w2u_order = 1;
8134520Snw141292 			else /* name */
8144520Snw141292 				*w2u_order = 2;
8154520Snw141292 		}
8165696Snw141292 
8174520Snw141292 	}
8184520Snw141292 
8194520Snw141292 	/*
8205696Snw141292 	 * 1. unixname to "", non-diagonal
8215696Snw141292 	 * 2. unixname to winname@domain (or winname), non-diagonal
8225696Snw141292 	 * 3. unixname to "", diagonal
8235696Snw141292 	 * 4. unixname to winname@domain (or winname), diagonal
8245696Snw141292 	 * 5. * to *@domain (or *), non-diagonal
8255696Snw141292 	 * 5. * to *@domain (or *), diagonal
8265696Snw141292 	 * 7. * to ""
8275696Snw141292 	 * 8. * to winname@domain (or winname)
8285696Snw141292 	 * 9. * to "", non-diagonal
8295696Snw141292 	 * 10. * to winname@domain (or winname), diagonal
8304520Snw141292 	 */
8314644Sbaban 	if (direction != IDMAP_DIRECTION_W2U) {
8325696Snw141292 		int diagonal = is_diagonal ? 1 : 0;
8335696Snw141292 
8344644Sbaban 		/* bi-directional or from unix to windows */
8354520Snw141292 		if (unixname == NULL || EMPTY_NAME(unixname))
8364520Snw141292 			return (IDMAP_ERR_U2W_NAMERULE);
8374520Snw141292 		else if (winname == NULL)
8384520Snw141292 			return (IDMAP_ERR_U2W_NAMERULE);
8394864Sbaban 		else if (windomain != NULL && *windomain == '*')
8404644Sbaban 			return (IDMAP_ERR_U2W_NAMERULE);
8414520Snw141292 		else if (*unixname == '*') {
8424520Snw141292 			if (*winname == '*')
8435696Snw141292 				*u2w_order = 5 + diagonal;
8444520Snw141292 			else if (EMPTY_NAME(winname))
8455696Snw141292 				*u2w_order = 7 + 2 * diagonal;
8464520Snw141292 			else
8475696Snw141292 				*u2w_order = 8 + 2 * diagonal;
8484520Snw141292 		} else {
8494520Snw141292 			if (*winname == '*')
8504520Snw141292 				return (IDMAP_ERR_U2W_NAMERULE);
8514520Snw141292 			else if (EMPTY_NAME(winname))
8525696Snw141292 				*u2w_order = 1 + 2 * diagonal;
8534520Snw141292 			else
8545696Snw141292 				*u2w_order = 2 + 2 * diagonal;
8554520Snw141292 		}
8564520Snw141292 	}
8574520Snw141292 	return (IDMAP_SUCCESS);
8584520Snw141292 }
8594520Snw141292 
8604520Snw141292 /*
8614520Snw141292  * Generate and execute SQL statement to add name-based mapping rule
8624520Snw141292  */
8634520Snw141292 idmap_retcode
8645696Snw141292 add_namerule(sqlite *db, idmap_namerule *rule)
8655696Snw141292 {
8664520Snw141292 	char		*sql = NULL;
8674520Snw141292 	idmap_stat	retcode;
8685064Sdm199847 	char		*dom = NULL;
8694520Snw141292 	int		w2u_order, u2w_order;
8704520Snw141292 	char		w2ubuf[11], u2wbuf[11];
8714520Snw141292 
8725064Sdm199847 	retcode = get_namerule_order(rule->winname, rule->windomain,
8735696Snw141292 	    rule->unixname, rule->direction,
8745696Snw141292 	    rule->is_user == rule->is_wuser ? 0 : 1, &w2u_order, &u2w_order);
8754520Snw141292 	if (retcode != IDMAP_SUCCESS)
8764520Snw141292 		goto out;
8774520Snw141292 
8784520Snw141292 	if (w2u_order)
8794520Snw141292 		(void) snprintf(w2ubuf, sizeof (w2ubuf), "%d", w2u_order);
8804520Snw141292 	if (u2w_order)
8814520Snw141292 		(void) snprintf(u2wbuf, sizeof (u2wbuf), "%d", u2w_order);
8824520Snw141292 
8834864Sbaban 	/*
8844864Sbaban 	 * For the triggers on namerules table to work correctly:
8854864Sbaban 	 * 1) Use NULL instead of 0 for w2u_order and u2w_order
8864864Sbaban 	 * 2) Use "" instead of NULL for "no domain"
8874864Sbaban 	 */
8884864Sbaban 
8895731Sbaban 	if (!EMPTY_STRING(rule->windomain))
8905064Sdm199847 		dom = rule->windomain;
8915696Snw141292 	else if (lookup_wksids_name2sid(rule->winname, NULL, NULL, NULL, NULL)
8924864Sbaban 	    == IDMAP_SUCCESS) {
8934864Sbaban 		/* well-known SIDs don't need domain */
8944864Sbaban 		dom = "";
8954864Sbaban 	}
8964520Snw141292 
8974520Snw141292 	RDLOCK_CONFIG();
8984864Sbaban 	if (dom == NULL) {
8995317Sjp151216 		if (_idmapdstate.cfg->pgcfg.default_domain)
9005317Sjp151216 			dom = _idmapdstate.cfg->pgcfg.default_domain;
9014864Sbaban 		else
9024864Sbaban 			dom = "";
9034864Sbaban 	}
9044884Sjp151216 	sql = sqlite_mprintf("INSERT into namerules "
9055696Snw141292 	    "(is_user, is_wuser, windomain, winname_display, is_nt4, "
9065696Snw141292 	    "unixname, w2u_order, u2w_order) "
9075696Snw141292 	    "VALUES(%d, %d, %Q, %Q, %d, %Q, %q, %q);",
9085696Snw141292 	    rule->is_user ? 1 : 0, rule->is_wuser ? 1 : 0, dom,
9095696Snw141292 	    rule->winname, rule->is_nt4 ? 1 : 0, rule->unixname,
9105696Snw141292 	    w2u_order ? w2ubuf : NULL, u2w_order ? u2wbuf : NULL);
9114520Snw141292 	UNLOCK_CONFIG();
9124520Snw141292 
9134520Snw141292 	if (sql == NULL) {
9144520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
9154520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
9164520Snw141292 		goto out;
9174520Snw141292 	}
9184520Snw141292 
9196017Snw141292 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, sql);
9204520Snw141292 
9214520Snw141292 	if (retcode == IDMAP_ERR_OTHER)
9224520Snw141292 		retcode = IDMAP_ERR_CFG;
9234520Snw141292 
9244520Snw141292 out:
9254864Sbaban 	if (sql != NULL)
9264520Snw141292 		sqlite_freemem(sql);
9274520Snw141292 	return (retcode);
9284520Snw141292 }
9294520Snw141292 
9304520Snw141292 /*
9314520Snw141292  * Flush name-based mapping rules
9324520Snw141292  */
9334520Snw141292 idmap_retcode
9345696Snw141292 flush_namerules(sqlite *db)
9355696Snw141292 {
9364520Snw141292 	idmap_stat	retcode;
9374520Snw141292 
9386017Snw141292 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, "DELETE FROM namerules;");
9395696Snw141292 
9404520Snw141292 	return (retcode);
9414520Snw141292 }
9424520Snw141292 
9434520Snw141292 /*
9444520Snw141292  * Generate and execute SQL statement to remove a name-based mapping rule
9454520Snw141292  */
9464520Snw141292 idmap_retcode
9475696Snw141292 rm_namerule(sqlite *db, idmap_namerule *rule)
9485696Snw141292 {
9494520Snw141292 	char		*sql = NULL;
9504520Snw141292 	idmap_stat	retcode;
9514520Snw141292 	char		buf[80];
9525696Snw141292 	char		*expr = NULL;
9534520Snw141292 
9545064Sdm199847 	if (rule->direction < 0 && EMPTY_STRING(rule->windomain) &&
9555064Sdm199847 	    EMPTY_STRING(rule->winname) && EMPTY_STRING(rule->unixname))
9564520Snw141292 		return (IDMAP_SUCCESS);
9574520Snw141292 
9585696Snw141292 	buf[0] = 0;
9595696Snw141292 
9605696Snw141292 	if (rule->direction == IDMAP_DIRECTION_BI)
9614520Snw141292 		(void) snprintf(buf, sizeof (buf), "AND w2u_order > 0"
9625696Snw141292 		    " AND u2w_order > 0");
9635696Snw141292 	else if (rule->direction == IDMAP_DIRECTION_W2U)
9644520Snw141292 		(void) snprintf(buf, sizeof (buf), "AND w2u_order > 0"
9655696Snw141292 		    " AND (u2w_order = 0 OR u2w_order ISNULL)");
9665696Snw141292 	else if (rule->direction == IDMAP_DIRECTION_U2W)
9674520Snw141292 		(void) snprintf(buf, sizeof (buf), "AND u2w_order > 0"
9685696Snw141292 		    " AND (w2u_order = 0 OR w2u_order ISNULL)");
9695696Snw141292 
9705696Snw141292 	retcode = gen_sql_expr_from_rule(rule, &expr);
9715696Snw141292 	if (retcode != IDMAP_SUCCESS)
9725696Snw141292 		goto out;
9735696Snw141292 
9745696Snw141292 	sql = sqlite_mprintf("DELETE FROM namerules WHERE 1 %s %s;", expr,
9755696Snw141292 	    buf);
9764520Snw141292 
9774520Snw141292 	if (sql == NULL) {
9784520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
9794520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
9804520Snw141292 		goto out;
9814520Snw141292 	}
9824520Snw141292 
9835696Snw141292 
9846017Snw141292 	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, sql);
9854520Snw141292 
9864520Snw141292 out:
9875696Snw141292 	if (expr != NULL)
9885696Snw141292 		sqlite_freemem(expr);
9894864Sbaban 	if (sql != NULL)
9904520Snw141292 		sqlite_freemem(sql);
9914520Snw141292 	return (retcode);
9924520Snw141292 }
9934520Snw141292 
9944520Snw141292 /*
9954520Snw141292  * Compile the given SQL query and step just once.
9964520Snw141292  *
9974520Snw141292  * Input:
9984520Snw141292  * db  - db handle
9994520Snw141292  * sql - SQL statement
10004520Snw141292  *
10014520Snw141292  * Output:
10024520Snw141292  * vm     -  virtual SQL machine
10034520Snw141292  * ncol   - number of columns in the result
10044520Snw141292  * values - column values
10054520Snw141292  *
10064520Snw141292  * Return values:
10074520Snw141292  * IDMAP_SUCCESS
10084520Snw141292  * IDMAP_ERR_NOTFOUND
10094520Snw141292  * IDMAP_ERR_INTERNAL
10104520Snw141292  */
10114520Snw141292 
10125696Snw141292 static
10135696Snw141292 idmap_retcode
10144520Snw141292 sql_compile_n_step_once(sqlite *db, char *sql, sqlite_vm **vm, int *ncol,
10155696Snw141292 		int reqcol, const char ***values)
10165696Snw141292 {
10174520Snw141292 	char		*errmsg = NULL;
10184884Sjp151216 	int		r;
10194884Sjp151216 
10204884Sjp151216 	if ((r = sqlite_compile(db, sql, NULL, vm, &errmsg)) != SQLITE_OK) {
10215696Snw141292 		idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
10225696Snw141292 		    CHECK_NULL(errmsg));
10234520Snw141292 		sqlite_freemem(errmsg);
10244520Snw141292 		return (IDMAP_ERR_INTERNAL);
10254520Snw141292 	}
10264520Snw141292 
10274884Sjp151216 	r = sqlite_step(*vm, ncol, values, NULL);
10284884Sjp151216 	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
10294884Sjp151216 
10304884Sjp151216 	if (r == SQLITE_ROW) {
10314864Sbaban 		if (ncol != NULL && *ncol < reqcol) {
10324520Snw141292 			(void) sqlite_finalize(*vm, NULL);
10334520Snw141292 			*vm = NULL;
10344520Snw141292 			return (IDMAP_ERR_INTERNAL);
10354520Snw141292 		}
10364520Snw141292 		/* Caller will call finalize after using the results */
10374520Snw141292 		return (IDMAP_SUCCESS);
10384520Snw141292 	} else if (r == SQLITE_DONE) {
10394520Snw141292 		(void) sqlite_finalize(*vm, NULL);
10404520Snw141292 		*vm = NULL;
10414520Snw141292 		return (IDMAP_ERR_NOTFOUND);
10424520Snw141292 	}
10434520Snw141292 
10444520Snw141292 	(void) sqlite_finalize(*vm, &errmsg);
10454520Snw141292 	*vm = NULL;
10465696Snw141292 	idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
10475696Snw141292 	    CHECK_NULL(errmsg));
10484520Snw141292 	sqlite_freemem(errmsg);
10494520Snw141292 	return (IDMAP_ERR_INTERNAL);
10504520Snw141292 }
10514520Snw141292 
10524864Sbaban /*
10536616Sdm199847  * Load config in the state.
10545731Sbaban  *
10556616Sdm199847  * nm_siduid and nm_sidgid fields:
10565731Sbaban  * state->nm_siduid represents mode used by sid2uid and uid2sid
10575731Sbaban  * requests for directory-based name mappings. Similarly,
10585731Sbaban  * state->nm_sidgid represents mode used by sid2gid and gid2sid
10595731Sbaban  * requests.
10605731Sbaban  *
10615731Sbaban  * sid2uid/uid2sid:
10625731Sbaban  * none       -> ds_name_mapping_enabled != true
10635731Sbaban  * AD-mode    -> !nldap_winname_attr && ad_unixuser_attr
10645731Sbaban  * nldap-mode -> nldap_winname_attr && !ad_unixuser_attr
10655731Sbaban  * mixed-mode -> nldap_winname_attr && ad_unixuser_attr
10665731Sbaban  *
10675731Sbaban  * sid2gid/gid2sid:
10685731Sbaban  * none       -> ds_name_mapping_enabled != true
10695731Sbaban  * AD-mode    -> !nldap_winname_attr && ad_unixgroup_attr
10705731Sbaban  * nldap-mode -> nldap_winname_attr && !ad_unixgroup_attr
10715731Sbaban  * mixed-mode -> nldap_winname_attr && ad_unixgroup_attr
10725731Sbaban  */
10735731Sbaban idmap_retcode
10746616Sdm199847 load_cfg_in_state(lookup_state_t *state)
10755731Sbaban {
10765731Sbaban 	state->nm_siduid = IDMAP_NM_NONE;
10775731Sbaban 	state->nm_sidgid = IDMAP_NM_NONE;
10785731Sbaban 	RDLOCK_CONFIG();
10796616Sdm199847 
1080*7031Snw141292 	state->eph_map_unres_sids = 0;
1081*7031Snw141292 	if (_idmapdstate.cfg->pgcfg.eph_map_unres_sids)
1082*7031Snw141292 		state->eph_map_unres_sids = 1;
1083*7031Snw141292 
10846616Sdm199847 	if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
10856616Sdm199847 		state->defdom =
10866616Sdm199847 		    strdup(_idmapdstate.cfg->pgcfg.default_domain);
10876616Sdm199847 		if (state->defdom == NULL) {
10886616Sdm199847 			UNLOCK_CONFIG();
10896616Sdm199847 			return (IDMAP_ERR_MEMORY);
10906616Sdm199847 		}
10916616Sdm199847 	} else {
10926616Sdm199847 		UNLOCK_CONFIG();
10936813Sdm199847 		return (IDMAP_SUCCESS);
10946616Sdm199847 	}
10955731Sbaban 	if (_idmapdstate.cfg->pgcfg.ds_name_mapping_enabled == FALSE) {
10965731Sbaban 		UNLOCK_CONFIG();
10975731Sbaban 		return (IDMAP_SUCCESS);
10985731Sbaban 	}
10995731Sbaban 	if (_idmapdstate.cfg->pgcfg.nldap_winname_attr != NULL) {
11005731Sbaban 		state->nm_siduid =
11015731Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
11025731Sbaban 		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
11035731Sbaban 		state->nm_sidgid =
11045731Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
11055731Sbaban 		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
11065731Sbaban 	} else {
11075731Sbaban 		state->nm_siduid =
11085731Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
11095731Sbaban 		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
11105731Sbaban 		state->nm_sidgid =
11115731Sbaban 		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
11125731Sbaban 		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
11135731Sbaban 	}
11145731Sbaban 	if (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL) {
11155731Sbaban 		state->ad_unixuser_attr =
11165731Sbaban 		    strdup(_idmapdstate.cfg->pgcfg.ad_unixuser_attr);
11175731Sbaban 		if (state->ad_unixuser_attr == NULL) {
11185731Sbaban 			UNLOCK_CONFIG();
11195731Sbaban 			return (IDMAP_ERR_MEMORY);
11205731Sbaban 		}
11215731Sbaban 	}
11225731Sbaban 	if (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL) {
11235731Sbaban 		state->ad_unixgroup_attr =
11245731Sbaban 		    strdup(_idmapdstate.cfg->pgcfg.ad_unixgroup_attr);
11255731Sbaban 		if (state->ad_unixgroup_attr == NULL) {
11265731Sbaban 			UNLOCK_CONFIG();
11275731Sbaban 			return (IDMAP_ERR_MEMORY);
11285731Sbaban 		}
11295731Sbaban 	}
11306616Sdm199847 	if (_idmapdstate.cfg->pgcfg.nldap_winname_attr != NULL) {
11316616Sdm199847 		state->nldap_winname_attr =
11326616Sdm199847 		    strdup(_idmapdstate.cfg->pgcfg.nldap_winname_attr);
11336616Sdm199847 		if (state->nldap_winname_attr == NULL) {
11346616Sdm199847 			UNLOCK_CONFIG();
11356616Sdm199847 			return (IDMAP_ERR_MEMORY);
11366616Sdm199847 		}
11376616Sdm199847 	}
11385731Sbaban 	UNLOCK_CONFIG();
11395731Sbaban 	return (IDMAP_SUCCESS);
11405731Sbaban }
11415731Sbaban 
11425731Sbaban /*
11436386Sjp151216  * Set the rule with sepecified values.
11446386Sjp151216  * All the strings are copied.
11456386Sjp151216  */
11466386Sjp151216 static void
11476386Sjp151216 idmap_namerule_set(idmap_namerule *rule, const char *windomain,
11486386Sjp151216 		const char *winname, const char *unixname, boolean_t is_user,
11496386Sjp151216 		boolean_t is_wuser, boolean_t is_nt4, int direction)
11506386Sjp151216 {
11516386Sjp151216 	/*
11526386Sjp151216 	 * Only update if they differ because we have to free
11536386Sjp151216 	 * and duplicate the strings
11546386Sjp151216 	 */
11556386Sjp151216 	if (rule->windomain == NULL || windomain == NULL ||
11566386Sjp151216 	    strcmp(rule->windomain, windomain) != 0) {
11576386Sjp151216 		if (rule->windomain != NULL) {
11586386Sjp151216 			free(rule->windomain);
11596386Sjp151216 			rule->windomain = NULL;
11606386Sjp151216 		}
11616386Sjp151216 		if (windomain != NULL)
11626386Sjp151216 			rule->windomain = strdup(windomain);
11636386Sjp151216 	}
11646386Sjp151216 
11656386Sjp151216 	if (rule->winname == NULL || winname == NULL ||
11666386Sjp151216 	    strcmp(rule->winname, winname) != 0) {
11676386Sjp151216 		if (rule->winname != NULL) {
11686386Sjp151216 			free(rule->winname);
11696386Sjp151216 			rule->winname = NULL;
11706386Sjp151216 		}
11716386Sjp151216 		if (winname != NULL)
11726386Sjp151216 			rule->winname = strdup(winname);
11736386Sjp151216 	}
11746386Sjp151216 
11756386Sjp151216 	if (rule->unixname == NULL || unixname == NULL ||
11766386Sjp151216 	    strcmp(rule->unixname, unixname) != 0) {
11776386Sjp151216 		if (rule->unixname != NULL) {
11786386Sjp151216 			free(rule->unixname);
11796386Sjp151216 			rule->unixname = NULL;
11806386Sjp151216 		}
11816386Sjp151216 		if (unixname != NULL)
11826386Sjp151216 			rule->unixname = strdup(unixname);
11836386Sjp151216 	}
11846386Sjp151216 
11856386Sjp151216 	rule->is_user = is_user;
11866386Sjp151216 	rule->is_wuser = is_wuser;
11876386Sjp151216 	rule->is_nt4 = is_nt4;
11886386Sjp151216 	rule->direction = direction;
11896386Sjp151216 }
11906386Sjp151216 
11916386Sjp151216 
11926386Sjp151216 /*
11934864Sbaban  * Table for well-known SIDs.
11944864Sbaban  *
11954864Sbaban  * Background:
11964864Sbaban  *
11975191Sbaban  * Some of the well-known principals are stored under:
11984864Sbaban  * cn=WellKnown Security Principals, cn=Configuration, dc=<forestRootDomain>
11994864Sbaban  * They belong to objectClass "foreignSecurityPrincipal". They don't have
12004864Sbaban  * "samAccountName" nor "userPrincipalName" attributes. Their names are
12014864Sbaban  * available in "cn" and "name" attributes. Some of these principals have a
12024864Sbaban  * second entry under CN=ForeignSecurityPrincipals,dc=<forestRootDomain> and
12034864Sbaban  * these duplicate entries have the stringified SID in the "name" and "cn"
12044864Sbaban  * attributes instead of the actual name.
12054864Sbaban  *
12065191Sbaban  * Those of the form S-1-5-32-X are Builtin groups and are stored in the
12075191Sbaban  * cn=builtin container (except, Power Users which is not stored in AD)
12084864Sbaban  *
12095191Sbaban  * These principals are and will remain constant. Therefore doing AD lookups
12105191Sbaban  * provides no benefit. Also, using hard-coded table (and thus avoiding AD
12115191Sbaban  * lookup) improves performance and avoids additional complexity in the
12125191Sbaban  * adutils.c code. Moreover these SIDs can be used when no Active Directory
12135191Sbaban  * is available (such as the CIFS server's "workgroup" mode).
12145191Sbaban  *
12155191Sbaban  * Notes:
12165191Sbaban  * 1. Currently we don't support localization of well-known SID names,
12174864Sbaban  * unlike Windows.
12184864Sbaban  *
12195191Sbaban  * 2. Other well-known SIDs i.e. S-1-5-<domain>-<w-k RID> are not stored
12205191Sbaban  * here. AD does have normal user/group objects for these objects and
12215191Sbaban  * can be looked up using the existing AD lookup code.
12225731Sbaban  *
12235731Sbaban  * 3. See comments above lookup_wksids_sid2pid() for more information
12245731Sbaban  * on how we lookup the wksids table.
12254864Sbaban  */
12264864Sbaban static wksids_table_t wksids[] = {
12275731Sbaban 	{"S-1-0", 0, "Nobody", 0, SENTINEL_PID, -1, 1},
12285731Sbaban 	{"S-1-1", 0, "Everyone", 0, SENTINEL_PID, -1, -1},
12295731Sbaban 	{"S-1-3", 0, "Creator Owner", 1, IDMAP_WK_CREATOR_OWNER_UID, 1, 0},
12305731Sbaban 	{"S-1-3", 1, "Creator Group", 0, IDMAP_WK_CREATOR_GROUP_GID, 0, 0},
12315731Sbaban 	{"S-1-3", 2, "Creator Owner Server", 1, SENTINEL_PID, -1, -1},
12325731Sbaban 	{"S-1-3", 3, "Creator Group Server", 0, SENTINEL_PID, -1, 1},
12335731Sbaban 	{"S-1-3", 4, "Owner Rights", 0, SENTINEL_PID, -1, -1},
12345731Sbaban 	{"S-1-5", 1, "Dialup", 0, SENTINEL_PID, -1, -1},
12355731Sbaban 	{"S-1-5", 2, "Network", 0, SENTINEL_PID, -1, -1},
12365731Sbaban 	{"S-1-5", 3, "Batch", 0, SENTINEL_PID, -1, -1},
12375731Sbaban 	{"S-1-5", 4, "Interactive", 0, SENTINEL_PID, -1, -1},
12385731Sbaban 	{"S-1-5", 6, "Service", 0, SENTINEL_PID, -1, -1},
12395731Sbaban 	{"S-1-5", 7, "Anonymous Logon", 0, GID_NOBODY, 0, 0},
12405731Sbaban 	{"S-1-5", 7, "Anonymous Logon", 0, UID_NOBODY, 1, 0},
12415731Sbaban 	{"S-1-5", 8, "Proxy", 0, SENTINEL_PID, -1, -1},
12425731Sbaban 	{"S-1-5", 9, "Enterprise Domain Controllers", 0, SENTINEL_PID, -1, -1},
12435731Sbaban 	{"S-1-5", 10, "Self", 0, SENTINEL_PID, -1, -1},
12445731Sbaban 	{"S-1-5", 11, "Authenticated Users", 0, SENTINEL_PID, -1, -1},
12455731Sbaban 	{"S-1-5", 12, "Restricted Code", 0, SENTINEL_PID, -1, -1},
12465731Sbaban 	{"S-1-5", 13, "Terminal Server User", 0, SENTINEL_PID, -1, -1},
12475731Sbaban 	{"S-1-5", 14, "Remote Interactive Logon", 0, SENTINEL_PID, -1, -1},
12485731Sbaban 	{"S-1-5", 15, "This Organization", 0, SENTINEL_PID, -1, -1},
12495731Sbaban 	{"S-1-5", 17, "IUSR", 0, SENTINEL_PID, -1, -1},
12505731Sbaban 	{"S-1-5", 18, "Local System", 0, IDMAP_WK_LOCAL_SYSTEM_GID, 0, 0},
12515731Sbaban 	{"S-1-5", 19, "Local Service", 0, SENTINEL_PID, -1, -1},
12525731Sbaban 	{"S-1-5", 20, "Network Service", 0, SENTINEL_PID, -1, -1},
12535731Sbaban 	{"S-1-5", 1000, "Other Organization", 0, SENTINEL_PID, -1, -1},
12545731Sbaban 	{"S-1-5-32", 544, "Administrators", 0, SENTINEL_PID, -1, -1},
12555731Sbaban 	{"S-1-5-32", 545, "Users", 0, SENTINEL_PID, -1, -1},
12565731Sbaban 	{"S-1-5-32", 546, "Guests", 0, SENTINEL_PID, -1, -1},
12575731Sbaban 	{"S-1-5-32", 547, "Power Users", 0, SENTINEL_PID, -1, -1},
12585731Sbaban 	{"S-1-5-32", 548, "Account Operators", 0, SENTINEL_PID, -1, -1},
12595731Sbaban 	{"S-1-5-32", 549, "Server Operators", 0, SENTINEL_PID, -1, -1},
12605731Sbaban 	{"S-1-5-32", 550, "Print Operators", 0, SENTINEL_PID, -1, -1},
12615731Sbaban 	{"S-1-5-32", 551, "Backup Operators", 0, SENTINEL_PID, -1, -1},
12625731Sbaban 	{"S-1-5-32", 552, "Replicator", 0, SENTINEL_PID, -1, -1},
12635191Sbaban 	{"S-1-5-32", 554, "Pre-Windows 2000 Compatible Access", 0,
12645731Sbaban 	    SENTINEL_PID, -1, -1},
12655731Sbaban 	{"S-1-5-32", 555, "Remote Desktop Users", 0, SENTINEL_PID, -1, -1},
12665191Sbaban 	{"S-1-5-32", 556, "Network Configuration Operators", 0,
12675731Sbaban 	    SENTINEL_PID, -1, -1},
12685191Sbaban 	{"S-1-5-32", 557, "Incoming Forest Trust Builders", 0,
12695731Sbaban 	    SENTINEL_PID, -1, -1},
12705731Sbaban 	{"S-1-5-32", 558, "Performance Monitor Users", 0, SENTINEL_PID, -1, -1},
12715731Sbaban 	{"S-1-5-32", 559, "Performance Log Users", 0, SENTINEL_PID, -1, -1},
12725191Sbaban 	{"S-1-5-32", 560, "Windows Authorization Access Group", 0,
12735731Sbaban 	    SENTINEL_PID, -1, -1},
12745191Sbaban 	{"S-1-5-32", 561, "Terminal Server License Servers", 0,
12755731Sbaban 	    SENTINEL_PID, -1, -1},
12765731Sbaban 	{"S-1-5-32", 561, "Distributed COM Users", 0, SENTINEL_PID, -1, -1},
12775731Sbaban 	{"S-1-5-32", 568, "IIS_IUSRS", 0, SENTINEL_PID, -1, -1},
12785731Sbaban 	{"S-1-5-32", 569, "Cryptographic Operators", 0, SENTINEL_PID, -1, -1},
12795731Sbaban 	{"S-1-5-32", 573, "Event Log Readers", 0, SENTINEL_PID, -1, -1},
12805191Sbaban 	{"S-1-5-32", 574, "Certificate Service DCOM Access", 0,
12815731Sbaban 	    SENTINEL_PID, -1, -1},
12825731Sbaban 	{"S-1-5-64", 21, "Digest Authentication", 0, SENTINEL_PID, -1, -1},
12835731Sbaban 	{"S-1-5-64", 10, "NTLM Authentication", 0, SENTINEL_PID, -1, -1},
12845731Sbaban 	{"S-1-5-64", 14, "SChannel Authentication", 0, SENTINEL_PID, -1, -1},
12855731Sbaban 	{NULL, UINT32_MAX, NULL, -1, SENTINEL_PID, -1, -1}
12864520Snw141292 };
12874520Snw141292 
12885731Sbaban /*
12895731Sbaban  * Lookup well-known SIDs table either by winname or by SID.
12905731Sbaban  * If the given winname or SID is a well-known SID then we set wksid
12915731Sbaban  * variable and then proceed to see if the SID has a hard mapping to
12925731Sbaban  * a particular UID/GID (Ex: Creator Owner/Creator Group mapped to
12935731Sbaban  * fixed ephemeral ids). If we find such mapping then we return
12945731Sbaban  * success otherwise notfound. If a well-known SID is mapped to
12955731Sbaban  * SENTINEL_PID and the direction field is set (bi-directional or
12965731Sbaban  * win2unix) then we treat it as inhibited mapping and return no
12975731Sbaban  * mapping (Ex. S-1-0-0).
12985731Sbaban  */
12995696Snw141292 static
13005696Snw141292 idmap_retcode
13015731Sbaban lookup_wksids_sid2pid(idmap_mapping *req, idmap_id_res *res, int *wksid)
13025696Snw141292 {
13034520Snw141292 	int i;
13045731Sbaban 
13055731Sbaban 	*wksid = 0;
13065731Sbaban 
13074864Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
13085731Sbaban 		if (req->id1.idmap_id_u.sid.prefix != NULL) {
13095731Sbaban 			if ((strcasecmp(wksids[i].sidprefix,
13105731Sbaban 			    req->id1.idmap_id_u.sid.prefix) != 0) ||
13115731Sbaban 			    wksids[i].rid != req->id1.idmap_id_u.sid.rid)
13125731Sbaban 				/* this is not our SID */
13135731Sbaban 				continue;
13145731Sbaban 			if (req->id1name == NULL) {
13155731Sbaban 				req->id1name = strdup(wksids[i].winname);
13165731Sbaban 				if (req->id1name == NULL)
13175731Sbaban 					return (IDMAP_ERR_MEMORY);
13185731Sbaban 			}
13195731Sbaban 		} else if (req->id1name != NULL) {
13205731Sbaban 			if (strcasecmp(wksids[i].winname, req->id1name) != 0)
13215731Sbaban 				/* this is not our winname */
13224864Sbaban 				continue;
13235731Sbaban 			req->id1.idmap_id_u.sid.prefix =
13245731Sbaban 			    strdup(wksids[i].sidprefix);
13255731Sbaban 			if (req->id1.idmap_id_u.sid.prefix == NULL)
13265731Sbaban 				return (IDMAP_ERR_MEMORY);
13275731Sbaban 			req->id1.idmap_id_u.sid.rid = wksids[i].rid;
13285731Sbaban 		}
13295731Sbaban 
13305731Sbaban 		*wksid = 1;
13315731Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
13325731Sbaban 
13335731Sbaban 		req->id1.idtype = (wksids[i].is_wuser) ?
13345731Sbaban 		    IDMAP_USID : IDMAP_GSID;
13355731Sbaban 
13365731Sbaban 		if (wksids[i].pid == SENTINEL_PID) {
13375731Sbaban 			if (wksids[i].direction == IDMAP_DIRECTION_BI ||
13385731Sbaban 			    wksids[i].direction == IDMAP_DIRECTION_W2U)
13395731Sbaban 				/* Inhibited */
13405731Sbaban 				return (IDMAP_ERR_NOMAPPING);
13415731Sbaban 			/* Not mapped */
13426616Sdm199847 			if (res->id.idtype == IDMAP_POSIXID) {
13436616Sdm199847 				res->id.idtype =
13446616Sdm199847 				    (wksids[i].is_wuser) ?
13456616Sdm199847 				    IDMAP_UID : IDMAP_GID;
13466616Sdm199847 			}
13475731Sbaban 			return (IDMAP_ERR_NOTFOUND);
13485731Sbaban 		} else if (wksids[i].direction == IDMAP_DIRECTION_U2W)
13495731Sbaban 			continue;
13505731Sbaban 
13515731Sbaban 		switch (res->id.idtype) {
13525731Sbaban 		case IDMAP_UID:
13535731Sbaban 			if (wksids[i].is_user == 0)
13545731Sbaban 				continue;
13555731Sbaban 			res->id.idmap_id_u.uid = wksids[i].pid;
13565731Sbaban 			res->direction = wksids[i].direction;
13576386Sjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
13586386Sjp151216 				res->info.how.map_type =
13596386Sjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
13606386Sjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
13616386Sjp151216 			}
13625731Sbaban 			return (IDMAP_SUCCESS);
13635731Sbaban 		case IDMAP_GID:
13645731Sbaban 			if (wksids[i].is_user == 1)
13655731Sbaban 				continue;
13665731Sbaban 			res->id.idmap_id_u.gid = wksids[i].pid;
13675731Sbaban 			res->direction = wksids[i].direction;
13686386Sjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
13696386Sjp151216 				res->info.how.map_type =
13706386Sjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
13716386Sjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
13726386Sjp151216 			}
13735731Sbaban 			return (IDMAP_SUCCESS);
13745731Sbaban 		case IDMAP_POSIXID:
13755731Sbaban 			res->id.idmap_id_u.uid = wksids[i].pid;
13765731Sbaban 			res->id.idtype = (!wksids[i].is_user) ?
13775731Sbaban 			    IDMAP_GID : IDMAP_UID;
13785731Sbaban 			res->direction = wksids[i].direction;
13796386Sjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
13806386Sjp151216 				res->info.how.map_type =
13816386Sjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
13826386Sjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
13836386Sjp151216 			}
13845731Sbaban 			return (IDMAP_SUCCESS);
13855731Sbaban 		default:
13865731Sbaban 			return (IDMAP_ERR_NOTSUPPORTED);
13874520Snw141292 		}
13884520Snw141292 	}
13894520Snw141292 	return (IDMAP_ERR_NOTFOUND);
13904520Snw141292 }
13914520Snw141292 
13925696Snw141292 
13935696Snw141292 static
13945696Snw141292 idmap_retcode
13955696Snw141292 lookup_wksids_pid2sid(idmap_mapping *req, idmap_id_res *res, int is_user)
13965696Snw141292 {
13974520Snw141292 	int i;
13985731Sbaban 	if (req->id1.idmap_id_u.uid == SENTINEL_PID)
13995731Sbaban 		return (IDMAP_ERR_NOTFOUND);
14004864Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
14014864Sbaban 		if (wksids[i].pid == req->id1.idmap_id_u.uid &&
14024864Sbaban 		    wksids[i].is_user == is_user &&
14034864Sbaban 		    wksids[i].direction != IDMAP_DIRECTION_W2U) {
14045731Sbaban 			if (res->id.idtype == IDMAP_SID) {
14055731Sbaban 				res->id.idtype = (wksids[i].is_wuser) ?
14065731Sbaban 				    IDMAP_USID : IDMAP_GSID;
14075731Sbaban 			}
14084864Sbaban 			res->id.idmap_id_u.sid.rid = wksids[i].rid;
14094864Sbaban 			res->id.idmap_id_u.sid.prefix =
14105696Snw141292 			    strdup(wksids[i].sidprefix);
14114864Sbaban 			if (res->id.idmap_id_u.sid.prefix == NULL) {
14124864Sbaban 				idmapdlog(LOG_ERR, "Out of memory");
14134864Sbaban 				return (IDMAP_ERR_MEMORY);
14144520Snw141292 			}
14154864Sbaban 			res->direction = wksids[i].direction;
14166386Sjp151216 			if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
14176386Sjp151216 				res->info.how.map_type =
14186386Sjp151216 				    IDMAP_MAP_TYPE_KNOWN_SID;
14196386Sjp151216 				res->info.src = IDMAP_MAP_SRC_HARD_CODED;
14206386Sjp151216 			}
14214864Sbaban 			return (IDMAP_SUCCESS);
14224864Sbaban 		}
14234864Sbaban 	}
14244864Sbaban 	return (IDMAP_ERR_NOTFOUND);
14254864Sbaban }
14264864Sbaban 
14275696Snw141292 idmap_retcode
14285696Snw141292 lookup_wksids_name2sid(const char *name, char **canonname, char **sidprefix,
14295696Snw141292 	idmap_rid_t *rid, int *type)
14305696Snw141292 {
14316616Sdm199847 	int	i;
14326616Sdm199847 
14336616Sdm199847 	if ((strncasecmp(name, "BUILTIN\\", 8) == 0) ||
14346616Sdm199847 	    (strncasecmp(name, "BUILTIN/", 8) == 0))
14356616Sdm199847 		name += 8;
14366616Sdm199847 
14374864Sbaban 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
14385731Sbaban 		if (strcasecmp(wksids[i].winname, name) != 0)
14395731Sbaban 			continue;
14405731Sbaban 		if (sidprefix != NULL &&
14415731Sbaban 		    (*sidprefix = strdup(wksids[i].sidprefix)) == NULL) {
14425731Sbaban 			idmapdlog(LOG_ERR, "Out of memory");
14435731Sbaban 			return (IDMAP_ERR_MEMORY);
14445731Sbaban 		}
14455731Sbaban 		if (canonname != NULL &&
14465731Sbaban 		    (*canonname = strdup(wksids[i].winname)) == NULL) {
14475731Sbaban 			idmapdlog(LOG_ERR, "Out of memory");
14485731Sbaban 			if (sidprefix != NULL) {
14495731Sbaban 				free(*sidprefix);
14505731Sbaban 				*sidprefix = NULL;
14514864Sbaban 			}
14525731Sbaban 			return (IDMAP_ERR_MEMORY);
14534520Snw141292 		}
14545731Sbaban 		if (type != NULL)
14555731Sbaban 			*type = (wksids[i].is_wuser) ?
14565731Sbaban 			    _IDMAP_T_USER : _IDMAP_T_GROUP;
14575731Sbaban 		if (rid != NULL)
14585731Sbaban 			*rid = wksids[i].rid;
14595731Sbaban 		return (IDMAP_SUCCESS);
14604520Snw141292 	}
14614520Snw141292 	return (IDMAP_ERR_NOTFOUND);
14624520Snw141292 }
14634520Snw141292 
14645696Snw141292 static
14655696Snw141292 idmap_retcode
14665696Snw141292 lookup_cache_sid2pid(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
14675696Snw141292 {
14684520Snw141292 	char		*end;
14694520Snw141292 	char		*sql = NULL;
14704520Snw141292 	const char	**values;
14714520Snw141292 	sqlite_vm	*vm = NULL;
14724520Snw141292 	int		ncol, is_user;
14734520Snw141292 	uid_t		pid;
14744520Snw141292 	time_t		curtime, exp;
14754520Snw141292 	idmap_retcode	retcode;
14765932Sbaban 	char		*is_user_string, *lower_name;
14774520Snw141292 
14784520Snw141292 	/* Current time */
14794520Snw141292 	errno = 0;
14804520Snw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
14815696Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
14825696Snw141292 		    strerror(errno));
14834520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
14844520Snw141292 		goto out;
14854520Snw141292 	}
14864520Snw141292 
14875731Sbaban 	switch (res->id.idtype) {
14885696Snw141292 	case IDMAP_UID:
14895696Snw141292 		is_user_string = "1";
14905696Snw141292 		break;
14915696Snw141292 	case IDMAP_GID:
14925696Snw141292 		is_user_string = "0";
14935696Snw141292 		break;
14945696Snw141292 	case IDMAP_POSIXID:
14955696Snw141292 		/* the non-diagonal mapping */
14965696Snw141292 		is_user_string = "is_wuser";
14975696Snw141292 		break;
14985696Snw141292 	default:
14995696Snw141292 		retcode = IDMAP_ERR_NOTSUPPORTED;
15005696Snw141292 		goto out;
15015696Snw141292 	}
15025696Snw141292 
15034520Snw141292 	/* SQL to lookup the cache */
15046386Sjp151216 
15055731Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
15065731Sbaban 		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
15076386Sjp151216 		    "unixname, u2w, is_wuser, "
15086386Sjp151216 		    "map_type, map_dn, map_attr, map_value, "
15096386Sjp151216 		    "map_windomain, map_winname, map_unixname, map_is_nt4 "
15105731Sbaban 		    "FROM idmap_cache WHERE is_user = %s AND "
15115731Sbaban 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
15125731Sbaban 		    "(pid >= 2147483648 OR "
15135731Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
15145731Sbaban 		    "expiration > %d));",
15155731Sbaban 		    is_user_string, req->id1.idmap_id_u.sid.prefix,
15165731Sbaban 		    req->id1.idmap_id_u.sid.rid, curtime);
15175731Sbaban 	} else if (req->id1name != NULL) {
15185932Sbaban 		if ((lower_name = tolower_u8(req->id1name)) == NULL)
15195932Sbaban 			lower_name = req->id1name;
15205731Sbaban 		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
15216386Sjp151216 		    "unixname, u2w, is_wuser, "
15226386Sjp151216 		    "map_type, map_dn, map_attr, map_value, "
15236386Sjp151216 		    "map_windomain, map_winname, map_unixname, map_is_nt4 "
15245731Sbaban 		    "FROM idmap_cache WHERE is_user = %s AND "
15255731Sbaban 		    "winname = %Q AND windomain = %Q AND w2u = 1 AND "
15265731Sbaban 		    "(pid >= 2147483648 OR "
15275731Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
15285731Sbaban 		    "expiration > %d));",
15296386Sjp151216 		    is_user_string, lower_name, req->id1domain,
15306386Sjp151216 		    curtime);
15315932Sbaban 		if (lower_name != req->id1name)
15325932Sbaban 			free(lower_name);
15335731Sbaban 	} else {
15345731Sbaban 		retcode = IDMAP_ERR_ARG;
15355731Sbaban 		goto out;
15365731Sbaban 	}
15374520Snw141292 	if (sql == NULL) {
15384520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
15394520Snw141292 		retcode = IDMAP_ERR_MEMORY;
15404520Snw141292 		goto out;
15414520Snw141292 	}
15426386Sjp151216 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol,
15436386Sjp151216 	    14, &values);
15444520Snw141292 	sqlite_freemem(sql);
15454520Snw141292 
15464520Snw141292 	if (retcode == IDMAP_ERR_NOTFOUND) {
15474520Snw141292 		goto out;
15484520Snw141292 	} else if (retcode == IDMAP_SUCCESS) {
15494520Snw141292 		/* sanity checks */
15504520Snw141292 		if (values[0] == NULL || values[1] == NULL) {
15514520Snw141292 			retcode = IDMAP_ERR_CACHE;
15524520Snw141292 			goto out;
15534520Snw141292 		}
15544520Snw141292 
15554520Snw141292 		pid = strtoul(values[0], &end, 10);
15565731Sbaban 		is_user = strncmp(values[1], "0", 2) ? 1 : 0;
15574520Snw141292 
15585696Snw141292 		if (is_user) {
15595696Snw141292 			res->id.idtype = IDMAP_UID;
15605696Snw141292 			res->id.idmap_id_u.uid = pid;
15615696Snw141292 		} else {
15625696Snw141292 			res->id.idtype = IDMAP_GID;
15635696Snw141292 			res->id.idmap_id_u.gid = pid;
15645696Snw141292 		}
15655696Snw141292 
15664520Snw141292 		/*
15674520Snw141292 		 * We may have an expired ephemeral mapping. Consider
15684520Snw141292 		 * the expired entry as valid if we are not going to
15694520Snw141292 		 * perform name-based mapping. But do not renew the
15704520Snw141292 		 * expiration.
15714520Snw141292 		 * If we will be doing name-based mapping then store the
15724520Snw141292 		 * ephemeral pid in the result so that we can use it
15734520Snw141292 		 * if we end up doing dynamic mapping again.
15744520Snw141292 		 */
15754520Snw141292 		if (!DO_NOT_ALLOC_NEW_ID_MAPPING(req) &&
15765696Snw141292 		    !AVOID_NAMESERVICE(req) &&
15775696Snw141292 		    IS_EPHEMERAL(pid) && values[2] != NULL) {
15785696Snw141292 			exp = strtoll(values[2], &end, 10);
15795696Snw141292 			if (exp && exp <= curtime) {
15805696Snw141292 				/* Store the ephemeral pid */
15815696Snw141292 				res->direction = IDMAP_DIRECTION_BI;
15825696Snw141292 				req->direction |= is_user
15835696Snw141292 				    ? _IDMAP_F_EXP_EPH_UID
15845696Snw141292 				    : _IDMAP_F_EXP_EPH_GID;
15855696Snw141292 				retcode = IDMAP_ERR_NOTFOUND;
15864520Snw141292 			}
15874520Snw141292 		}
15884520Snw141292 	}
15894520Snw141292 
15904520Snw141292 out:
15914520Snw141292 	if (retcode == IDMAP_SUCCESS) {
15924864Sbaban 		if (values[4] != NULL)
15934520Snw141292 			res->direction =
15944644Sbaban 			    (strtol(values[4], &end, 10) == 0)?
15954644Sbaban 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
15964520Snw141292 		else
15974644Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
15984520Snw141292 
15994864Sbaban 		if (values[3] != NULL) {
16005731Sbaban 			if (req->id2name != NULL)
16015731Sbaban 				free(req->id2name);
16025064Sdm199847 			req->id2name = strdup(values[3]);
16035064Sdm199847 			if (req->id2name == NULL) {
16044520Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
16054520Snw141292 				retcode = IDMAP_ERR_MEMORY;
16064520Snw141292 			}
16074520Snw141292 		}
16085731Sbaban 
16095731Sbaban 		req->id1.idtype = strncmp(values[5], "0", 2) ?
16105731Sbaban 		    IDMAP_USID : IDMAP_GSID;
16116386Sjp151216 
16126386Sjp151216 		if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
16136386Sjp151216 			res->info.src = IDMAP_MAP_SRC_CACHE;
16146386Sjp151216 			res->info.how.map_type = strtoul(values[6], &end, 10);
16156386Sjp151216 			switch (res->info.how.map_type) {
16166386Sjp151216 			case IDMAP_MAP_TYPE_DS_AD:
16176386Sjp151216 				res->info.how.idmap_how_u.ad.dn =
16186386Sjp151216 				    strdup(values[7]);
16196386Sjp151216 				res->info.how.idmap_how_u.ad.attr =
16206386Sjp151216 				    strdup(values[8]);
16216386Sjp151216 				res->info.how.idmap_how_u.ad.value =
16226386Sjp151216 				    strdup(values[9]);
16236386Sjp151216 				break;
16246386Sjp151216 
16256386Sjp151216 			case IDMAP_MAP_TYPE_DS_NLDAP:
16266386Sjp151216 				res->info.how.idmap_how_u.nldap.dn =
16276386Sjp151216 				    strdup(values[7]);
16286386Sjp151216 				res->info.how.idmap_how_u.nldap.attr =
16296386Sjp151216 				    strdup(values[8]);
16306386Sjp151216 				res->info.how.idmap_how_u.nldap.value =
16316386Sjp151216 				    strdup(values[9]);
16326386Sjp151216 				break;
16336386Sjp151216 
16346386Sjp151216 			case IDMAP_MAP_TYPE_RULE_BASED:
16356386Sjp151216 				res->info.how.idmap_how_u.rule.windomain =
16366386Sjp151216 				    strdup(values[10]);
16376386Sjp151216 				res->info.how.idmap_how_u.rule.winname =
16386386Sjp151216 				    strdup(values[11]);
16396386Sjp151216 				res->info.how.idmap_how_u.rule.unixname =
16406386Sjp151216 				    strdup(values[12]);
16416386Sjp151216 				res->info.how.idmap_how_u.rule.is_nt4 =
16426386Sjp151216 				    strtoul(values[13], &end, 1);
16436386Sjp151216 				res->info.how.idmap_how_u.rule.is_user =
16446386Sjp151216 				    is_user;
16456386Sjp151216 				res->info.how.idmap_how_u.rule.is_wuser =
16466386Sjp151216 				    strtoul(values[5], &end, 1);
16476386Sjp151216 				break;
16486386Sjp151216 
16496386Sjp151216 			case IDMAP_MAP_TYPE_EPHEMERAL:
16506386Sjp151216 				break;
16516386Sjp151216 
16526386Sjp151216 			case IDMAP_MAP_TYPE_LOCAL_SID:
16536386Sjp151216 				break;
16546386Sjp151216 
16556386Sjp151216 			case IDMAP_MAP_TYPE_KNOWN_SID:
16566386Sjp151216 				break;
16576386Sjp151216 
16586386Sjp151216 			default:
16596386Sjp151216 				/* Unknow mapping type */
16606386Sjp151216 				assert(FALSE);
16616386Sjp151216 			}
16626386Sjp151216 		}
16634520Snw141292 	}
16644864Sbaban 	if (vm != NULL)
16654520Snw141292 		(void) sqlite_finalize(vm, NULL);
16664520Snw141292 	return (retcode);
16674520Snw141292 }
16684520Snw141292 
16695696Snw141292 static
16705696Snw141292 idmap_retcode
16714864Sbaban lookup_cache_sid2name(sqlite *cache, const char *sidprefix, idmap_rid_t rid,
16725696Snw141292 		char **name, char **domain, int *type)
16735696Snw141292 {
16744520Snw141292 	char		*end;
16754520Snw141292 	char		*sql = NULL;
16764520Snw141292 	const char	**values;
16774520Snw141292 	sqlite_vm	*vm = NULL;
16784520Snw141292 	int		ncol;
16794520Snw141292 	time_t		curtime;
16804520Snw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
16814520Snw141292 
16824520Snw141292 	/* Get current time */
16834520Snw141292 	errno = 0;
16844520Snw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
16855696Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
16865696Snw141292 		    strerror(errno));
16874520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
16884520Snw141292 		goto out;
16894520Snw141292 	}
16904520Snw141292 
16914520Snw141292 	/* SQL to lookup the cache */
16925696Snw141292 	sql = sqlite_mprintf("SELECT canon_name, domain, type "
16935696Snw141292 	    "FROM name_cache WHERE "
16945696Snw141292 	    "sidprefix = %Q AND rid = %u AND "
16955696Snw141292 	    "(expiration = 0 OR expiration ISNULL OR "
16965696Snw141292 	    "expiration > %d);",
16975696Snw141292 	    sidprefix, rid, curtime);
16984520Snw141292 	if (sql == NULL) {
16994520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
17004520Snw141292 		retcode = IDMAP_ERR_MEMORY;
17014520Snw141292 		goto out;
17024520Snw141292 	}
17034520Snw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 3, &values);
17044520Snw141292 	sqlite_freemem(sql);
17054520Snw141292 
17064520Snw141292 	if (retcode == IDMAP_SUCCESS) {
17074864Sbaban 		if (type != NULL) {
17084520Snw141292 			if (values[2] == NULL) {
17094520Snw141292 				retcode = IDMAP_ERR_CACHE;
17104520Snw141292 				goto out;
17114520Snw141292 			}
17124520Snw141292 			*type = strtol(values[2], &end, 10);
17134520Snw141292 		}
17144520Snw141292 
17154864Sbaban 		if (name != NULL && values[0] != NULL) {
17164520Snw141292 			if ((*name = strdup(values[0])) == NULL) {
17174520Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
17184520Snw141292 				retcode = IDMAP_ERR_MEMORY;
17194520Snw141292 				goto out;
17204520Snw141292 			}
17214520Snw141292 		}
17224520Snw141292 
17234864Sbaban 		if (domain != NULL && values[1] != NULL) {
17244520Snw141292 			if ((*domain = strdup(values[1])) == NULL) {
17254864Sbaban 				if (name != NULL && *name) {
17264520Snw141292 					free(*name);
17274520Snw141292 					*name = NULL;
17284520Snw141292 				}
17294520Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
17304520Snw141292 				retcode = IDMAP_ERR_MEMORY;
17314520Snw141292 				goto out;
17324520Snw141292 			}
17334520Snw141292 		}
17344520Snw141292 	}
17354520Snw141292 
17364520Snw141292 out:
17374864Sbaban 	if (vm != NULL)
17384520Snw141292 		(void) sqlite_finalize(vm, NULL);
17394520Snw141292 	return (retcode);
17404520Snw141292 }
17414520Snw141292 
17424520Snw141292 /*
17435731Sbaban  * Given SID, find winname using name_cache OR
17445731Sbaban  * Given winname, find SID using name_cache.
17455731Sbaban  * Used when mapping win to unix i.e. req->id1 is windows id and
17465731Sbaban  * req->id2 is unix id
17474520Snw141292  */
17485696Snw141292 static
17495696Snw141292 idmap_retcode
17505731Sbaban lookup_name_cache(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
17515696Snw141292 {
17524520Snw141292 	int		type = -1;
17534520Snw141292 	idmap_retcode	retcode;
17545731Sbaban 	char		*sidprefix = NULL;
17554520Snw141292 	idmap_rid_t	rid;
17564520Snw141292 	char		*name = NULL, *domain = NULL;
17574520Snw141292 
17585731Sbaban 	/* Done if we've both sid and winname */
17595731Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL && req->id1name != NULL)
17605731Sbaban 		return (IDMAP_SUCCESS);
17615731Sbaban 
17625731Sbaban 	/* Lookup sid to winname */
17635731Sbaban 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
17645731Sbaban 		retcode = lookup_cache_sid2name(cache,
17655731Sbaban 		    req->id1.idmap_id_u.sid.prefix,
17665731Sbaban 		    req->id1.idmap_id_u.sid.rid, &name, &domain, &type);
17674864Sbaban 		goto out;
17685731Sbaban 	}
17695731Sbaban 
17705731Sbaban 	/* Lookup winame to sid */
17715731Sbaban 	retcode = lookup_cache_name2sid(cache, req->id1name, req->id1domain,
17725731Sbaban 	    &name, &sidprefix, &rid, &type);
17734520Snw141292 
17744520Snw141292 out:
17755731Sbaban 	if (retcode != IDMAP_SUCCESS) {
17765731Sbaban 		free(name);
17775731Sbaban 		free(domain);
17785731Sbaban 		free(sidprefix);
17795731Sbaban 		return (retcode);
17805731Sbaban 	}
17815731Sbaban 
17825731Sbaban 	if (res->id.idtype == IDMAP_POSIXID) {
17835731Sbaban 		res->id.idtype = (type == _IDMAP_T_USER) ?
17845731Sbaban 		    IDMAP_UID : IDMAP_GID;
17855731Sbaban 	}
17865731Sbaban 	req->id1.idtype = (type == _IDMAP_T_USER) ?
17875731Sbaban 	    IDMAP_USID : IDMAP_GSID;
17885731Sbaban 
17895731Sbaban 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
17905731Sbaban 	if (name != NULL) {
17915731Sbaban 		free(req->id1name);	/* Free existing winname */
17925731Sbaban 		req->id1name = name;	/* and use canonical name instead */
17935731Sbaban 	}
17945731Sbaban 	if (req->id1domain == NULL)
17955731Sbaban 		req->id1domain = domain;
17965731Sbaban 	if (req->id1.idmap_id_u.sid.prefix == NULL) {
17975731Sbaban 		req->id1.idmap_id_u.sid.prefix = sidprefix;
17985731Sbaban 		req->id1.idmap_id_u.sid.rid = rid;
17994520Snw141292 	}
18004520Snw141292 	return (retcode);
18014520Snw141292 }
18024520Snw141292 
18035731Sbaban /*
18045731Sbaban  * Batch AD lookups
18055731Sbaban  */
18064520Snw141292 idmap_retcode
18075731Sbaban ad_lookup_batch(lookup_state_t *state, idmap_mapping_batch *batch,
18085696Snw141292 		idmap_ids_res *result)
18095696Snw141292 {
18104520Snw141292 	idmap_retcode	retcode;
18115731Sbaban 	int		i, add, type, is_wuser, is_user;
18125731Sbaban 	int		retries = 0, eunixtype;
18135731Sbaban 	char		**unixname;
18144520Snw141292 	idmap_mapping	*req;
18154520Snw141292 	idmap_id_res	*res;
18165731Sbaban 	idmap_query_state_t	*qs = NULL;
18176386Sjp151216 	idmap_how	*how;
18186616Sdm199847 	char		**dn, **attr, **value;
18195731Sbaban 
18205731Sbaban 	/*
18215731Sbaban 	 * Since req->id2.idtype is unused, we will use it here
18225731Sbaban 	 * to retrieve the value of sid_type. But it needs to be
18235731Sbaban 	 * reset to IDMAP_NONE before we return to prevent xdr
18245731Sbaban 	 * from mis-interpreting req->id2 when it tries to free
18255731Sbaban 	 * the input argument. Other option is to allocate an
18265731Sbaban 	 * array of integers and use it instead for the batched
18275731Sbaban 	 * call. But why un-necessarily allocate memory. That may
18285731Sbaban 	 * be an option if req->id2.idtype cannot be re-used in
18295731Sbaban 	 * future.
18305731Sbaban 	 */
18314520Snw141292 
18324520Snw141292 	if (state->ad_nqueries == 0)
18334520Snw141292 		return (IDMAP_SUCCESS);
18344520Snw141292 
18356963Sbaban 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
18366963Sbaban 		req = &batch->idmap_mapping_batch_val[i];
18376963Sbaban 		res = &result->ids.ids_val[i];
18386963Sbaban 
18396963Sbaban 		/* Skip if not marked for AD lookup or already in error. */
18406963Sbaban 		if (!(req->direction & _IDMAP_F_LOOKUP_AD) ||
18416963Sbaban 		    res->retcode != IDMAP_SUCCESS)
18426963Sbaban 			continue;
18436963Sbaban 
18446963Sbaban 		/* Init status */
18456963Sbaban 		res->retcode = IDMAP_ERR_RETRIABLE_NET_ERR;
18466963Sbaban 	}
18476963Sbaban 
18484520Snw141292 retry:
18495731Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, state->ad_nqueries,
18505731Sbaban 	    &qs);
18515731Sbaban 	if (retcode != IDMAP_SUCCESS) {
18525968Snw141292 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
18535968Snw141292 			goto retry;
18546097Snw141292 		degrade_svc(1, "failed to create batch for AD lookup");
18555731Sbaban 		goto out;
18564520Snw141292 	}
18574520Snw141292 
18585317Sjp151216 	restore_svc();
18595317Sjp151216 
18605731Sbaban 	idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
18615731Sbaban 	    state->ad_unixgroup_attr);
18625731Sbaban 
18635731Sbaban 	for (i = 0, add = 0; i < batch->idmap_mapping_batch_len; i++) {
18644520Snw141292 		req = &batch->idmap_mapping_batch_val[i];
18654520Snw141292 		res = &result->ids.ids_val[i];
18666386Sjp151216 		how = &res->info.how;
18676386Sjp151216 
18685731Sbaban 		retcode = IDMAP_SUCCESS;
18695731Sbaban 		req->id2.idtype = IDMAP_NONE;
18705731Sbaban 
18715731Sbaban 		/* Skip if not marked for AD lookup */
18725731Sbaban 		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
18735731Sbaban 			continue;
18745731Sbaban 
18756963Sbaban 		if (res->retcode != IDMAP_ERR_RETRIABLE_NET_ERR)
18765731Sbaban 			continue;
18775731Sbaban 
18785731Sbaban 		if (IS_REQUEST_SID(*req, 1)) {
18796616Sdm199847 
18806616Sdm199847 			/* win2unix request: */
18816616Sdm199847 
18826616Sdm199847 			unixname = dn = attr = value = NULL;
18835731Sbaban 			eunixtype = _IDMAP_T_UNDEF;
18845731Sbaban 			if (req->id2name == NULL) {
18855731Sbaban 				if (res->id.idtype == IDMAP_UID &&
18865731Sbaban 				    AD_OR_MIXED(state->nm_siduid)) {
18875731Sbaban 					eunixtype = _IDMAP_T_USER;
18885731Sbaban 					unixname = &req->id2name;
18895731Sbaban 				} else if (res->id.idtype == IDMAP_GID &&
18905731Sbaban 				    AD_OR_MIXED(state->nm_sidgid)) {
18915731Sbaban 					eunixtype = _IDMAP_T_GROUP;
18925731Sbaban 					unixname = &req->id2name;
18935731Sbaban 				} else if (AD_OR_MIXED(state->nm_siduid) ||
18945731Sbaban 				    AD_OR_MIXED(state->nm_sidgid)) {
18955731Sbaban 					unixname = &req->id2name;
18965731Sbaban 				}
18975731Sbaban 			}
18985731Sbaban 			add = 1;
18996616Sdm199847 			if (unixname != NULL) {
19006616Sdm199847 				/*
19016616Sdm199847 				 * Get how info for DS-based name
19026616Sdm199847 				 * mapping only if AD or MIXED
19036616Sdm199847 				 * mode is enabled.
19046616Sdm199847 				 */
19056616Sdm199847 				idmap_info_free(&res->info);
19066616Sdm199847 				res->info.src = IDMAP_MAP_SRC_NEW;
19076616Sdm199847 				how->map_type = IDMAP_MAP_TYPE_DS_AD;
19086616Sdm199847 				dn = &how->idmap_how_u.ad.dn;
19096616Sdm199847 				attr = &how->idmap_how_u.ad.attr;
19106616Sdm199847 				value = &how->idmap_how_u.ad.value;
19116616Sdm199847 			}
19126616Sdm199847 			if (req->id1.idmap_id_u.sid.prefix != NULL) {
19136616Sdm199847 				/* Lookup AD by SID */
19146616Sdm199847 				retcode = idmap_sid2name_batch_add1(
19156616Sdm199847 				    qs, req->id1.idmap_id_u.sid.prefix,
19166616Sdm199847 				    &req->id1.idmap_id_u.sid.rid, eunixtype,
19176616Sdm199847 				    dn, attr, value,
19186616Sdm199847 				    (req->id1name == NULL) ?
19196616Sdm199847 				    &req->id1name : NULL,
19206616Sdm199847 				    (req->id1domain == NULL) ?
19216616Sdm199847 				    &req->id1domain : NULL,
19226616Sdm199847 				    (int *)&req->id2.idtype, unixname,
19236616Sdm199847 				    &res->retcode);
19246616Sdm199847 			} else {
19256616Sdm199847 				/* Lookup AD by winname */
19266616Sdm199847 				assert(req->id1name != NULL);
19276616Sdm199847 				retcode = idmap_name2sid_batch_add1(
19286616Sdm199847 				    qs, req->id1name, req->id1domain,
19296616Sdm199847 				    eunixtype,
19306616Sdm199847 				    dn, attr, value,
19316616Sdm199847 				    &req->id1name,
19326616Sdm199847 				    &req->id1.idmap_id_u.sid.prefix,
19336616Sdm199847 				    &req->id1.idmap_id_u.sid.rid,
19346616Sdm199847 				    (int *)&req->id2.idtype, unixname,
19356616Sdm199847 				    &res->retcode);
19366616Sdm199847 			}
19375731Sbaban 
19385731Sbaban 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
19396616Sdm199847 
19406616Sdm199847 			/* unix2win request: */
19415731Sbaban 
19425731Sbaban 			if (res->id.idmap_id_u.sid.prefix != NULL &&
19435731Sbaban 			    req->id2name != NULL) {
19445731Sbaban 				/* Already have SID and winname -- done */
19455731Sbaban 				res->retcode = IDMAP_SUCCESS;
19465731Sbaban 				continue;
19475731Sbaban 			}
19485731Sbaban 
19495731Sbaban 			if (res->id.idmap_id_u.sid.prefix != NULL) {
19505731Sbaban 				/*
19515731Sbaban 				 * SID but no winname -- lookup AD by
19525731Sbaban 				 * SID to get winname.
19536616Sdm199847 				 * how info is not needed here because
19546616Sdm199847 				 * we are not retrieving unixname from
19556616Sdm199847 				 * AD.
19565731Sbaban 				 */
19575731Sbaban 				add = 1;
19585731Sbaban 				retcode = idmap_sid2name_batch_add1(
19595731Sbaban 				    qs, res->id.idmap_id_u.sid.prefix,
19605731Sbaban 				    &res->id.idmap_id_u.sid.rid,
19616386Sjp151216 				    _IDMAP_T_UNDEF,
19626616Sdm199847 				    NULL, NULL, NULL,
19636386Sjp151216 				    &req->id2name,
19645731Sbaban 				    &req->id2domain, (int *)&req->id2.idtype,
19655731Sbaban 				    NULL, &res->retcode);
19665731Sbaban 			} else if (req->id2name != NULL) {
19675731Sbaban 				/*
19685731Sbaban 				 * winname but no SID -- lookup AD by
19695731Sbaban 				 * winname to get SID.
19706616Sdm199847 				 * how info is not needed here because
19716616Sdm199847 				 * we are not retrieving unixname from
19726616Sdm199847 				 * AD.
19735731Sbaban 				 */
19745731Sbaban 				add = 1;
19755731Sbaban 				retcode = idmap_name2sid_batch_add1(
19765731Sbaban 				    qs, req->id2name, req->id2domain,
19776386Sjp151216 				    _IDMAP_T_UNDEF,
19786616Sdm199847 				    NULL, NULL, NULL, NULL,
19795731Sbaban 				    &res->id.idmap_id_u.sid.prefix,
19805731Sbaban 				    &res->id.idmap_id_u.sid.rid,
19815731Sbaban 				    (int *)&req->id2.idtype, NULL,
19825731Sbaban 				    &res->retcode);
19835731Sbaban 			} else if (req->id1name != NULL) {
19845731Sbaban 				/*
19855731Sbaban 				 * No SID and no winname but we've unixname --
19865731Sbaban 				 * lookup AD by unixname to get SID.
19875731Sbaban 				 */
19885731Sbaban 				is_user = (IS_REQUEST_UID(*req)) ? 1 : 0;
19895731Sbaban 				if (res->id.idtype == IDMAP_USID)
19905731Sbaban 					is_wuser = 1;
19915731Sbaban 				else if (res->id.idtype == IDMAP_GSID)
19925731Sbaban 					is_wuser = 0;
19935731Sbaban 				else
19945731Sbaban 					is_wuser = is_user;
19955731Sbaban 				add = 1;
19966616Sdm199847 				idmap_info_free(&res->info);
19976386Sjp151216 				res->info.src = IDMAP_MAP_SRC_NEW;
19986386Sjp151216 				how->map_type = IDMAP_MAP_TYPE_DS_AD;
19995731Sbaban 				retcode = idmap_unixname2sid_batch_add1(
20005731Sbaban 				    qs, req->id1name, is_user, is_wuser,
20016386Sjp151216 				    &how->idmap_how_u.ad.dn,
20026386Sjp151216 				    &how->idmap_how_u.ad.attr,
20036386Sjp151216 				    &how->idmap_how_u.ad.value,
20045731Sbaban 				    &res->id.idmap_id_u.sid.prefix,
20055731Sbaban 				    &res->id.idmap_id_u.sid.rid,
20065731Sbaban 				    &req->id2name, &req->id2domain,
20075731Sbaban 				    (int *)&req->id2.idtype, &res->retcode);
20085731Sbaban 			}
20095731Sbaban 		}
20105731Sbaban 		if (retcode != IDMAP_SUCCESS) {
20115731Sbaban 			idmap_lookup_release_batch(&qs);
20125731Sbaban 			break;
20134520Snw141292 		}
20144520Snw141292 	}
20154520Snw141292 
20166963Sbaban 	if (retcode == IDMAP_SUCCESS) {
20176963Sbaban 		/* add keeps track if we added an entry to the batch */
20186963Sbaban 		if (add)
20196963Sbaban 			retcode = idmap_lookup_batch_end(&qs);
20206963Sbaban 		else
20216963Sbaban 			idmap_lookup_release_batch(&qs);
20226963Sbaban 	}
20235696Snw141292 
20244520Snw141292 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
20254520Snw141292 		goto retry;
20265317Sjp151216 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
20276097Snw141292 		degrade_svc(1, "some AD lookups timed out repeatedly");
20284520Snw141292 
20295731Sbaban 	if (retcode != IDMAP_SUCCESS)
20305731Sbaban 		idmapdlog(LOG_NOTICE, "Failed to batch AD lookup requests");
20314520Snw141292 
20324520Snw141292 out:
20335731Sbaban 	/*
20345731Sbaban 	 * This loop does the following:
20356616Sdm199847 	 * 1. Reset _IDMAP_F_LOOKUP_AD flag from the request.
20366616Sdm199847 	 * 2. Reset req->id2.idtype to IDMAP_NONE
20376616Sdm199847 	 * 3. If batch_start or batch_add failed then set the status
20386616Sdm199847 	 *    of each request marked for AD lookup to that error.
20396616Sdm199847 	 * 4. Evaluate the type of the AD object (i.e. user or group) and
20406616Sdm199847 	 *    update the idtype in request.
20415731Sbaban 	 */
20425731Sbaban 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
20435731Sbaban 		req = &batch->idmap_mapping_batch_val[i];
20445731Sbaban 		type = req->id2.idtype;
20455731Sbaban 		req->id2.idtype = IDMAP_NONE;
20465746Sbaban 		res = &result->ids.ids_val[i];
20476386Sjp151216 		how = &res->info.how;
20485731Sbaban 		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
20495731Sbaban 			continue;
20505731Sbaban 
20516616Sdm199847 		/* Reset AD lookup flag */
20526616Sdm199847 		req->direction &= ~(_IDMAP_F_LOOKUP_AD);
20536616Sdm199847 
20546616Sdm199847 		/*
20556616Sdm199847 		 * If batch_start or batch_add failed then set the status
20566616Sdm199847 		 * of each request marked for AD lookup to that error.
20576616Sdm199847 		 */
20585731Sbaban 		if (retcode != IDMAP_SUCCESS) {
20595731Sbaban 			res->retcode = retcode;
20605731Sbaban 			continue;
20615731Sbaban 		}
20625731Sbaban 
20635731Sbaban 		if (!add)
20645731Sbaban 			continue;
20655731Sbaban 
20666386Sjp151216 		if (res->retcode == IDMAP_ERR_NOTFOUND) {
20676386Sjp151216 			/* Nothing found - remove the preset info */
20686616Sdm199847 			idmap_info_free(&res->info);
20696386Sjp151216 		}
20706386Sjp151216 
20715731Sbaban 		if (IS_REQUEST_SID(*req, 1)) {
20725731Sbaban 			if (res->retcode != IDMAP_SUCCESS)
20735731Sbaban 				continue;
20746616Sdm199847 			/* Evaluate result type */
20755731Sbaban 			switch (type) {
20765731Sbaban 			case _IDMAP_T_USER:
20775731Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
20785731Sbaban 					res->id.idtype = IDMAP_UID;
20795731Sbaban 				req->id1.idtype = IDMAP_USID;
20805731Sbaban 				break;
20815731Sbaban 			case _IDMAP_T_GROUP:
20825731Sbaban 				if (res->id.idtype == IDMAP_POSIXID)
20835731Sbaban 					res->id.idtype = IDMAP_GID;
20845731Sbaban 				req->id1.idtype = IDMAP_GSID;
20855731Sbaban 				break;
20865731Sbaban 			default:
20875731Sbaban 				res->retcode = IDMAP_ERR_SID;
20885731Sbaban 				break;
20895731Sbaban 			}
20906616Sdm199847 			if (res->retcode == IDMAP_SUCCESS &&
20916616Sdm199847 			    req->id1name != NULL &&
20926616Sdm199847 			    (req->id2name == NULL ||
20936616Sdm199847 			    res->id.idmap_id_u.uid == SENTINEL_PID) &&
20946616Sdm199847 			    NLDAP_MODE(res->id.idtype, state)) {
20956616Sdm199847 				req->direction |= _IDMAP_F_LOOKUP_NLDAP;
20966616Sdm199847 				state->nldap_nqueries++;
20976616Sdm199847 			}
20985731Sbaban 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
20995731Sbaban 			if (res->retcode != IDMAP_SUCCESS) {
21005731Sbaban 				if ((!(IDMAP_FATAL_ERROR(res->retcode))) &&
21015731Sbaban 				    res->id.idmap_id_u.sid.prefix == NULL &&
21025731Sbaban 				    req->id2name == NULL && /* no winname */
21035731Sbaban 				    req->id1name != NULL) /* unixname */
21045731Sbaban 					/*
21056616Sdm199847 					 * If AD lookup by unixname failed
21066616Sdm199847 					 * with non fatal error then clear
21076616Sdm199847 					 * the error (i.e set res->retcode
21086616Sdm199847 					 * to success). This allows the next
21096616Sdm199847 					 * pass to process other mapping
21106616Sdm199847 					 * mechanisms for this request.
21115731Sbaban 					 */
21125731Sbaban 					res->retcode = IDMAP_SUCCESS;
21135731Sbaban 				continue;
21145731Sbaban 			}
21156616Sdm199847 			/* Evaluate result type */
21165731Sbaban 			switch (type) {
21175731Sbaban 			case _IDMAP_T_USER:
21185731Sbaban 				if (res->id.idtype == IDMAP_SID)
21195731Sbaban 					res->id.idtype = IDMAP_USID;
21205731Sbaban 				break;
21215731Sbaban 			case _IDMAP_T_GROUP:
21225731Sbaban 				if (res->id.idtype == IDMAP_SID)
21235731Sbaban 					res->id.idtype = IDMAP_GSID;
21245731Sbaban 				break;
21255731Sbaban 			default:
21265731Sbaban 				res->retcode = IDMAP_ERR_SID;
21275731Sbaban 				break;
21285731Sbaban 			}
21295731Sbaban 		}
21305731Sbaban 	}
21315731Sbaban 
21325731Sbaban 	/* AD lookups done. Reset state->ad_nqueries and return */
21335731Sbaban 	state->ad_nqueries = 0;
21344520Snw141292 	return (retcode);
21354520Snw141292 }
21364520Snw141292 
21375696Snw141292 /*
21385696Snw141292  * Convention when processing win2unix requests:
21395696Snw141292  *
21405696Snw141292  * Windows identity:
21415696Snw141292  * req->id1name =
21425696Snw141292  *              winname if given otherwise winname found will be placed
21435696Snw141292  *              here.
21445696Snw141292  * req->id1domain =
21455696Snw141292  *              windomain if given otherwise windomain found will be
21465696Snw141292  *              placed here.
21475696Snw141292  * req->id1.idtype =
21485696Snw141292  *              Either IDMAP_SID/USID/GSID. If this is IDMAP_SID then it'll
21495696Snw141292  *              be set to IDMAP_USID/GSID depending upon whether the
21505696Snw141292  *              given SID is user or group respectively. The user/group-ness
21515696Snw141292  *              is determined either when looking up well-known SIDs table OR
21526616Sdm199847  *              if the SID is found in namecache OR by ad_lookup_one() OR by
21535696Snw141292  *              ad_lookup_batch().
21545696Snw141292  * req->id1..sid.[prefix, rid] =
21555696Snw141292  *              SID if given otherwise SID found will be placed here.
21565696Snw141292  *
21575696Snw141292  * Unix identity:
21585696Snw141292  * req->id2name =
21595696Snw141292  *              unixname found will be placed here.
21605696Snw141292  * req->id2domain =
21615696Snw141292  *              NOT USED
21625696Snw141292  * res->id.idtype =
21635696Snw141292  *              Target type initialized from req->id2.idtype. If
21645696Snw141292  *              it is IDMAP_POSIXID then actual type (IDMAP_UID/GID) found
21655696Snw141292  *              will be placed here.
21665696Snw141292  * res->id..[uid or gid] =
21675696Snw141292  *              UID/GID found will be placed here.
21685696Snw141292  *
21695696Snw141292  * Others:
21705696Snw141292  * res->retcode =
21715696Snw141292  *              Return status for this request will be placed here.
21725696Snw141292  * res->direction =
21735696Snw141292  *              Direction found will be placed here. Direction
21745696Snw141292  *              meaning whether the resultant mapping is valid
21755696Snw141292  *              only from win2unix or bi-directional.
21765696Snw141292  * req->direction =
21775696Snw141292  *              INTERNAL USE. Used by idmapd to set various
21785696Snw141292  *              flags (_IDMAP_F_xxxx) to aid in processing
21795696Snw141292  *              of the request.
21805696Snw141292  * req->id2.idtype =
21815696Snw141292  *              INTERNAL USE. Initially this is the requested target
21825696Snw141292  *              type and is used to initialize res->id.idtype.
21835696Snw141292  *              ad_lookup_batch() uses this field temporarily to store
21845696Snw141292  *              sid_type obtained by the batched AD lookups and after
21855696Snw141292  *              use resets it to IDMAP_NONE to prevent xdr from
21865696Snw141292  *              mis-interpreting the contents of req->id2.
21875696Snw141292  * req->id2..[uid or gid or sid] =
21885696Snw141292  *              NOT USED
21895696Snw141292  */
21905696Snw141292 
21915696Snw141292 /*
21925696Snw141292  * This function does the following:
21935696Snw141292  * 1. Lookup well-known SIDs table.
21945696Snw141292  * 2. Check if the given SID is a local-SID and if so extract UID/GID from it.
21955696Snw141292  * 3. Lookup cache.
21965696Snw141292  * 4. Check if the client does not want new mapping to be allocated
21975696Snw141292  *    in which case this pass is the final pass.
21985696Snw141292  * 5. Set AD lookup flag if it determines that the next stage needs
21995696Snw141292  *    to do AD lookup.
22005696Snw141292  */
22014520Snw141292 idmap_retcode
22026616Sdm199847 sid2pid_first_pass(lookup_state_t *state, idmap_mapping *req,
22035696Snw141292 		idmap_id_res *res)
22045696Snw141292 {
22054520Snw141292 	idmap_retcode	retcode;
22065731Sbaban 	int		wksid;
22075731Sbaban 
22085731Sbaban 	/* Initialize result */
22095731Sbaban 	res->id.idtype = req->id2.idtype;
22105731Sbaban 	res->id.idmap_id_u.uid = SENTINEL_PID;
22115731Sbaban 	res->direction = IDMAP_DIRECTION_UNDEF;
22125731Sbaban 	wksid = 0;
22134520Snw141292 
22145127Sdm199847 	if (EMPTY_STRING(req->id1.idmap_id_u.sid.prefix)) {
22155731Sbaban 		if (req->id1name == NULL) {
22165731Sbaban 			retcode = IDMAP_ERR_ARG;
22175731Sbaban 			goto out;
22185731Sbaban 		}
22195731Sbaban 		/* sanitize sidprefix */
22205731Sbaban 		free(req->id1.idmap_id_u.sid.prefix);
22215731Sbaban 		req->id1.idmap_id_u.sid.prefix = NULL;
22224520Snw141292 	}
22235731Sbaban 
22245731Sbaban 	/* Lookup well-known SIDs table */
22255731Sbaban 	retcode = lookup_wksids_sid2pid(req, res, &wksid);
22264520Snw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
22274520Snw141292 		goto out;
22284520Snw141292 
22295731Sbaban 	/* Check if this is a localsid */
22305731Sbaban 	if (!wksid) {
22315731Sbaban 		retcode = lookup_localsid2pid(req, res);
22325731Sbaban 		if (retcode != IDMAP_ERR_NOTFOUND)
22335731Sbaban 			goto out;
22345731Sbaban 	}
22355731Sbaban 
22365731Sbaban 	/* Lookup cache */
22376616Sdm199847 	retcode = lookup_cache_sid2pid(state->cache, req, res);
22384520Snw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
22394520Snw141292 		goto out;
22404520Snw141292 
22414520Snw141292 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req) || AVOID_NAMESERVICE(req)) {
22426386Sjp151216 		retcode = IDMAP_ERR_NONEGENERATED;
22434520Snw141292 		goto out;
22444520Snw141292 	}
22454520Snw141292 
22464520Snw141292 	/*
22475731Sbaban 	 * Failed to find non-expired entry in cache. Next step is
22485731Sbaban 	 * to determine if this request needs to be batched for AD lookup.
22495731Sbaban 	 *
22505731Sbaban 	 * At this point we have either sid or winname or both. If we don't
22515731Sbaban 	 * have both then lookup name_cache for the sid or winname
22525731Sbaban 	 * whichever is missing. If not found then this request will be
22535731Sbaban 	 * batched for AD lookup.
22544520Snw141292 	 */
22556616Sdm199847 	retcode = lookup_name_cache(state->cache, req, res);
22565731Sbaban 	if (retcode != IDMAP_SUCCESS && retcode != IDMAP_ERR_NOTFOUND)
22575731Sbaban 		goto out;
22584520Snw141292 
22594520Snw141292 	/*
22605731Sbaban 	 * Set the flag to indicate that we are not done yet so that
22615731Sbaban 	 * subsequent passes considers this request for name-based
22625731Sbaban 	 * mapping and ephemeral mapping.
22634520Snw141292 	 */
22645731Sbaban 	state->sid2pid_done = FALSE;
22655731Sbaban 	req->direction |= _IDMAP_F_NOTDONE;
22665731Sbaban 
22675731Sbaban 	/*
22685731Sbaban 	 * Even if we have both sid and winname, we still may need to batch
22695731Sbaban 	 * this request for AD lookup if we don't have unixname and
22705731Sbaban 	 * directory-based name mapping (AD or mixed) is enabled.
22715731Sbaban 	 * We avoid AD lookup for well-known SIDs because they don't have
22725731Sbaban 	 * regular AD objects.
22735731Sbaban 	 */
22745731Sbaban 	if (retcode != IDMAP_SUCCESS ||
22755731Sbaban 	    (!wksid && req->id2name == NULL &&
22765731Sbaban 	    AD_OR_MIXED_MODE(res->id.idtype, state))) {
22774520Snw141292 		retcode = IDMAP_SUCCESS;
22785731Sbaban 		req->direction |= _IDMAP_F_LOOKUP_AD;
22794520Snw141292 		state->ad_nqueries++;
22806616Sdm199847 	} else if (NLDAP_MODE(res->id.idtype, state)) {
22816616Sdm199847 		req->direction |= _IDMAP_F_LOOKUP_NLDAP;
22826616Sdm199847 		state->nldap_nqueries++;
22834520Snw141292 	}
22844520Snw141292 
22854520Snw141292 
22864520Snw141292 out:
22874520Snw141292 	res->retcode = idmap_stat4prot(retcode);
22885731Sbaban 	/*
22895731Sbaban 	 * If we are done and there was an error then set fallback pid
22905731Sbaban 	 * in the result.
22915731Sbaban 	 */
22925731Sbaban 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
22935731Sbaban 		res->id.idmap_id_u.uid = UID_NOBODY;
22944520Snw141292 	return (retcode);
22954520Snw141292 }
22964520Snw141292 
22974520Snw141292 /*
22984520Snw141292  * Generate SID using the following convention
22994520Snw141292  * 	<machine-sid-prefix>-<1000 + uid>
23004520Snw141292  * 	<machine-sid-prefix>-<2^31 + gid>
23014520Snw141292  */
23025696Snw141292 static
23035696Snw141292 idmap_retcode
23046386Sjp151216 generate_localsid(idmap_mapping *req, idmap_id_res *res, int is_user,
23056386Sjp151216 		int fallback)
23065696Snw141292 {
23075731Sbaban 	free(res->id.idmap_id_u.sid.prefix);
23085731Sbaban 	res->id.idmap_id_u.sid.prefix = NULL;
23095731Sbaban 
23105731Sbaban 	/*
23115731Sbaban 	 * Diagonal mapping for localSIDs not supported because of the
23125731Sbaban 	 * way we generate localSIDs.
23135731Sbaban 	 */
23145731Sbaban 	if (is_user && res->id.idtype == IDMAP_GSID)
23155731Sbaban 		return (IDMAP_ERR_NOMAPPING);
23165731Sbaban 	if (!is_user && res->id.idtype == IDMAP_USID)
23175731Sbaban 		return (IDMAP_ERR_NOMAPPING);
23185731Sbaban 
23195731Sbaban 	/* Skip 1000 UIDs */
23205731Sbaban 	if (is_user && req->id1.idmap_id_u.uid >
23215731Sbaban 	    (INT32_MAX - LOCALRID_MIN))
23225731Sbaban 		return (IDMAP_ERR_NOMAPPING);
23235731Sbaban 
23245731Sbaban 	RDLOCK_CONFIG();
23255731Sbaban 	/*
23265731Sbaban 	 * machine_sid is never NULL because if it is we won't be here.
23275731Sbaban 	 * No need to assert because stdrup(NULL) will core anyways.
23285731Sbaban 	 */
23295731Sbaban 	res->id.idmap_id_u.sid.prefix =
23305731Sbaban 	    strdup(_idmapdstate.cfg->pgcfg.machine_sid);
23315731Sbaban 	if (res->id.idmap_id_u.sid.prefix == NULL) {
23324520Snw141292 		UNLOCK_CONFIG();
23335731Sbaban 		idmapdlog(LOG_ERR, "Out of memory");
23345731Sbaban 		return (IDMAP_ERR_MEMORY);
23354520Snw141292 	}
23365731Sbaban 	UNLOCK_CONFIG();
23375731Sbaban 	res->id.idmap_id_u.sid.rid =
23385731Sbaban 	    (is_user) ? req->id1.idmap_id_u.uid + LOCALRID_MIN :
23395731Sbaban 	    req->id1.idmap_id_u.gid + INT32_MAX + 1;
23405731Sbaban 	res->direction = IDMAP_DIRECTION_BI;
23415731Sbaban 	if (res->id.idtype == IDMAP_SID)
23425731Sbaban 		res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
23435731Sbaban 
23446386Sjp151216 	if (!fallback && req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
23456386Sjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_LOCAL_SID;
23466386Sjp151216 		res->info.src = IDMAP_MAP_SRC_ALGORITHMIC;
23476386Sjp151216 	}
23486386Sjp151216 
23495731Sbaban 	/*
23505731Sbaban 	 * Don't update name_cache because local sids don't have
23515731Sbaban 	 * valid windows names.
23525731Sbaban 	 */
23535731Sbaban 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
23545731Sbaban 	return (IDMAP_SUCCESS);
23554520Snw141292 }
23564520Snw141292 
23575696Snw141292 static
23585696Snw141292 idmap_retcode
23595696Snw141292 lookup_localsid2pid(idmap_mapping *req, idmap_id_res *res)
23605696Snw141292 {
23614520Snw141292 	char		*sidprefix;
23624520Snw141292 	uint32_t	rid;
23634520Snw141292 	int		s;
23644520Snw141292 
23654520Snw141292 	/*
23664520Snw141292 	 * If the sidprefix == localsid then UID = last RID - 1000 or
23674520Snw141292 	 * GID = last RID - 2^31.
23684520Snw141292 	 */
23695731Sbaban 	if ((sidprefix = req->id1.idmap_id_u.sid.prefix) == NULL)
23705731Sbaban 		/* This means we are looking up by winname */
23715731Sbaban 		return (IDMAP_ERR_NOTFOUND);
23724520Snw141292 	rid = req->id1.idmap_id_u.sid.rid;
23734520Snw141292 
23744520Snw141292 	RDLOCK_CONFIG();
23755696Snw141292 	s = (_idmapdstate.cfg->pgcfg.machine_sid) ?
23765696Snw141292 	    strcasecmp(sidprefix, _idmapdstate.cfg->pgcfg.machine_sid) : 1;
23774520Snw141292 	UNLOCK_CONFIG();
23784520Snw141292 
23795731Sbaban 	/*
23805731Sbaban 	 * If the given sidprefix does not match machine_sid then this is
23815731Sbaban 	 * not a local SID.
23825731Sbaban 	 */
23835731Sbaban 	if (s != 0)
23845731Sbaban 		return (IDMAP_ERR_NOTFOUND);
23855731Sbaban 
23865731Sbaban 	switch (res->id.idtype) {
23875731Sbaban 	case IDMAP_UID:
23885731Sbaban 		if (rid > INT32_MAX || rid < LOCALRID_MIN)
23895731Sbaban 			return (IDMAP_ERR_ARG);
23905731Sbaban 		res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
23915731Sbaban 		break;
23925731Sbaban 	case IDMAP_GID:
23935731Sbaban 		if (rid <= INT32_MAX)
23945731Sbaban 			return (IDMAP_ERR_ARG);
23955731Sbaban 		res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
23965731Sbaban 		break;
23975731Sbaban 	case IDMAP_POSIXID:
23985731Sbaban 		if (rid > INT32_MAX) {
23994520Snw141292 			res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
24004520Snw141292 			res->id.idtype = IDMAP_GID;
24015731Sbaban 		} else if (rid < LOCALRID_MIN) {
24025731Sbaban 			return (IDMAP_ERR_ARG);
24035731Sbaban 		} else {
24045731Sbaban 			res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
24055731Sbaban 			res->id.idtype = IDMAP_UID;
24064520Snw141292 		}
24075731Sbaban 		break;
24085731Sbaban 	default:
24095731Sbaban 		return (IDMAP_ERR_NOTSUPPORTED);
24104520Snw141292 	}
24116386Sjp151216 	if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
24126386Sjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_LOCAL_SID;
24136386Sjp151216 		res->info.src = IDMAP_MAP_SRC_ALGORITHMIC;
24146386Sjp151216 	}
24155731Sbaban 	return (IDMAP_SUCCESS);
24164520Snw141292 }
24174520Snw141292 
24185731Sbaban /*
24195731Sbaban  * Name service lookup by unixname to get pid
24205731Sbaban  */
24215696Snw141292 static
24225696Snw141292 idmap_retcode
24235731Sbaban ns_lookup_byname(const char *name, const char *lower_name, idmap_id *id)
24245696Snw141292 {
24255696Snw141292 	struct passwd	pwd, *pwdp;
24265696Snw141292 	struct group	grp, *grpp;
24274520Snw141292 	char		buf[1024];
24284520Snw141292 	int		errnum;
24294520Snw141292 	const char	*me = "ns_lookup_byname";
24304520Snw141292 
24315731Sbaban 	switch (id->idtype) {
24325731Sbaban 	case IDMAP_UID:
24335696Snw141292 		pwdp = getpwnam_r(name, &pwd, buf, sizeof (buf));
24345731Sbaban 		if (pwdp == NULL && errno == 0 && lower_name != NULL &&
24355696Snw141292 		    name != lower_name && strcmp(name, lower_name) != 0)
24365696Snw141292 			pwdp = getpwnam_r(lower_name, &pwd, buf, sizeof (buf));
24375696Snw141292 		if (pwdp == NULL) {
24384520Snw141292 			errnum = errno;
24394520Snw141292 			idmapdlog(LOG_WARNING,
24405696Snw141292 			    "%s: getpwnam_r(%s) failed (%s).",
24415696Snw141292 			    me, name, errnum ? strerror(errnum) : "not found");
24424520Snw141292 			if (errnum == 0)
24434520Snw141292 				return (IDMAP_ERR_NOTFOUND);
24444520Snw141292 			else
24454520Snw141292 				return (IDMAP_ERR_INTERNAL);
24464520Snw141292 		}
24475731Sbaban 		id->idmap_id_u.uid = pwd.pw_uid;
24485731Sbaban 		break;
24495731Sbaban 	case IDMAP_GID:
24505696Snw141292 		grpp = getgrnam_r(name, &grp, buf, sizeof (buf));
24515731Sbaban 		if (grpp == NULL && errno == 0 && lower_name != NULL &&
24525696Snw141292 		    name != lower_name && strcmp(name, lower_name) != 0)
24535696Snw141292 			grpp = getgrnam_r(lower_name, &grp, buf, sizeof (buf));
24545696Snw141292 		if (grpp == NULL) {
24554520Snw141292 			errnum = errno;
24564520Snw141292 			idmapdlog(LOG_WARNING,
24575696Snw141292 			    "%s: getgrnam_r(%s) failed (%s).",
24585696Snw141292 			    me, name, errnum ? strerror(errnum) : "not found");
24594520Snw141292 			if (errnum == 0)
24604520Snw141292 				return (IDMAP_ERR_NOTFOUND);
24614520Snw141292 			else
24624520Snw141292 				return (IDMAP_ERR_INTERNAL);
24634520Snw141292 		}
24645731Sbaban 		id->idmap_id_u.gid = grp.gr_gid;
24655731Sbaban 		break;
24665731Sbaban 	default:
24675731Sbaban 		return (IDMAP_ERR_ARG);
24684520Snw141292 	}
24694520Snw141292 	return (IDMAP_SUCCESS);
24704520Snw141292 }
24714520Snw141292 
24725731Sbaban 
24735731Sbaban /*
24745731Sbaban  * Name service lookup by pid to get unixname
24755731Sbaban  */
24765731Sbaban static
24775731Sbaban idmap_retcode
24785731Sbaban ns_lookup_bypid(uid_t pid, int is_user, char **unixname)
24795731Sbaban {
24805731Sbaban 	struct passwd	pwd;
24815731Sbaban 	struct group	grp;
24825731Sbaban 	char		buf[1024];
24835731Sbaban 	int		errnum;
24845731Sbaban 	const char	*me = "ns_lookup_bypid";
24855731Sbaban 
24865731Sbaban 	if (is_user) {
24875731Sbaban 		errno = 0;
24885731Sbaban 		if (getpwuid_r(pid, &pwd, buf, sizeof (buf)) == NULL) {
24895731Sbaban 			errnum = errno;
24905731Sbaban 			idmapdlog(LOG_WARNING,
24915731Sbaban 			    "%s: getpwuid_r(%u) failed (%s).",
24925731Sbaban 			    me, pid, errnum ? strerror(errnum) : "not found");
24935731Sbaban 			if (errnum == 0)
24945731Sbaban 				return (IDMAP_ERR_NOTFOUND);
24955731Sbaban 			else
24965731Sbaban 				return (IDMAP_ERR_INTERNAL);
24975731Sbaban 		}
24985731Sbaban 		*unixname = strdup(pwd.pw_name);
24995731Sbaban 	} else {
25005731Sbaban 		errno = 0;
25015731Sbaban 		if (getgrgid_r(pid, &grp, buf, sizeof (buf)) == NULL) {
25025731Sbaban 			errnum = errno;
25035731Sbaban 			idmapdlog(LOG_WARNING,
25045731Sbaban 			    "%s: getgrgid_r(%u) failed (%s).",
25055731Sbaban 			    me, pid, errnum ? strerror(errnum) : "not found");
25065731Sbaban 			if (errnum == 0)
25075731Sbaban 				return (IDMAP_ERR_NOTFOUND);
25085731Sbaban 			else
25095731Sbaban 				return (IDMAP_ERR_INTERNAL);
25105731Sbaban 		}
25115731Sbaban 		*unixname = strdup(grp.gr_name);
25125731Sbaban 	}
25135731Sbaban 	if (*unixname == NULL)
25145731Sbaban 		return (IDMAP_ERR_MEMORY);
25155731Sbaban 	return (IDMAP_SUCCESS);
25165731Sbaban }
25175731Sbaban 
25184520Snw141292 /*
25194520Snw141292  * Name-based mapping
25204520Snw141292  *
25214520Snw141292  * Case 1: If no rule matches do ephemeral
25224520Snw141292  *
25234520Snw141292  * Case 2: If rule matches and unixname is "" then return no mapping.
25244520Snw141292  *
25254520Snw141292  * Case 3: If rule matches and unixname is specified then lookup name
25264520Snw141292  *  service using the unixname. If unixname not found then return no mapping.
25274520Snw141292  *
25284520Snw141292  * Case 4: If rule matches and unixname is * then lookup name service
25294520Snw141292  *  using winname as the unixname. If unixname not found then process
25304520Snw141292  *  other rules using the lookup order. If no other rule matches then do
25314520Snw141292  *  ephemeral. Otherwise, based on the matched rule do Case 2 or 3 or 4.
25324520Snw141292  *  This allows us to specify a fallback unixname per _domain_ or no mapping
25334520Snw141292  *  instead of the default behaviour of doing ephemeral mapping.
25344520Snw141292  *
25354520Snw141292  * Example 1:
25364520Snw141292  * *@sfbay == *
25374520Snw141292  * If looking up windows users foo@sfbay and foo does not exists in
25384520Snw141292  * the name service then foo@sfbay will be mapped to an ephemeral id.
25394520Snw141292  *
25404520Snw141292  * Example 2:
25414520Snw141292  * *@sfbay == *
25424520Snw141292  * *@sfbay => guest
25434520Snw141292  * If looking up windows users foo@sfbay and foo does not exists in
25444520Snw141292  * the name service then foo@sfbay will be mapped to guest.
25454520Snw141292  *
25464520Snw141292  * Example 3:
25474520Snw141292  * *@sfbay == *
25484520Snw141292  * *@sfbay => ""
25494520Snw141292  * If looking up windows users foo@sfbay and foo does not exists in
25504520Snw141292  * the name service then we will return no mapping for foo@sfbay.
25514520Snw141292  *
25524520Snw141292  */
25535696Snw141292 static
25545696Snw141292 idmap_retcode
25556616Sdm199847 name_based_mapping_sid2pid(lookup_state_t *state,
25566616Sdm199847 		idmap_mapping *req, idmap_id_res *res)
25575696Snw141292 {
25585696Snw141292 	const char	*unixname, *windomain;
25595696Snw141292 	char		*sql = NULL, *errmsg = NULL, *lower_winname = NULL;
25604520Snw141292 	idmap_retcode	retcode;
25615696Snw141292 	char		*end, *lower_unixname, *winname;
25624520Snw141292 	const char	**values;
25634520Snw141292 	sqlite_vm	*vm = NULL;
25645696Snw141292 	int		ncol, r, i, is_user, is_wuser;
25656386Sjp151216 	idmap_namerule	*rule = &res->info.how.idmap_how_u.rule;
25666386Sjp151216 	int		direction;
25674520Snw141292 	const char	*me = "name_based_mapping_sid2pid";
25684520Snw141292 
25695731Sbaban 	assert(req->id1name != NULL); /* We have winname */
25705731Sbaban 	assert(req->id2name == NULL); /* We don't have unixname */
25715731Sbaban 
25725064Sdm199847 	winname = req->id1name;
25735064Sdm199847 	windomain = req->id1domain;
25745696Snw141292 
25755696Snw141292 	switch (req->id1.idtype) {
25765696Snw141292 	case IDMAP_USID:
25775696Snw141292 		is_wuser = 1;
25785696Snw141292 		break;
25795696Snw141292 	case IDMAP_GSID:
25805696Snw141292 		is_wuser = 0;
25815696Snw141292 		break;
25825696Snw141292 	default:
25835731Sbaban 		idmapdlog(LOG_ERR, "%s: Unable to determine if the "
25845731Sbaban 		    "given Windows id is user or group.", me);
25855696Snw141292 		return (IDMAP_ERR_INTERNAL);
25865696Snw141292 	}
25875696Snw141292 
25885731Sbaban 	switch (res->id.idtype) {
25895696Snw141292 	case IDMAP_UID:
25905696Snw141292 		is_user = 1;
25915696Snw141292 		break;
25925696Snw141292 	case IDMAP_GID:
25935696Snw141292 		is_user = 0;
25945696Snw141292 		break;
25955696Snw141292 	case IDMAP_POSIXID:
25965696Snw141292 		is_user = is_wuser;
25975696Snw141292 		res->id.idtype = is_user ? IDMAP_UID : IDMAP_GID;
25985696Snw141292 		break;
25995696Snw141292 	}
26004520Snw141292 
26014520Snw141292 	i = 0;
26026616Sdm199847 	if (windomain == NULL)
26034864Sbaban 		windomain = "";
26046950Sbaban 	else if (state->defdom != NULL &&
26056950Sbaban 	    strcasecmp(state->defdom, windomain) == 0)
26066616Sdm199847 		i = 1;
26074520Snw141292 
26085696Snw141292 	if ((lower_winname = tolower_u8(winname)) == NULL)
26095696Snw141292 		lower_winname = winname;    /* hope for the best */
26104520Snw141292 	sql = sqlite_mprintf(
26116386Sjp151216 	    "SELECT unixname, u2w_order, winname_display, windomain, is_nt4 "
26126386Sjp151216 	    "FROM namerules WHERE "
26135696Snw141292 	    "w2u_order > 0 AND is_user = %d AND is_wuser = %d AND "
26145696Snw141292 	    "(winname = %Q OR winname = '*') AND "
26155696Snw141292 	    "(windomain = %Q OR windomain = '*' %s) "
26165696Snw141292 	    "ORDER BY w2u_order ASC;",
26175696Snw141292 	    is_user, is_wuser, lower_winname, windomain,
26185696Snw141292 	    i ? "OR windomain ISNULL OR windomain = ''" : "");
26194520Snw141292 	if (sql == NULL) {
26204520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
26214520Snw141292 		retcode = IDMAP_ERR_MEMORY;
26224520Snw141292 		goto out;
26234520Snw141292 	}
26244520Snw141292 
26256616Sdm199847 	if (sqlite_compile(state->db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
26264520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
26275696Snw141292 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
26285696Snw141292 		    CHECK_NULL(errmsg));
26294520Snw141292 		sqlite_freemem(errmsg);
26304520Snw141292 		goto out;
26314520Snw141292 	}
26324520Snw141292 
26336386Sjp151216 	for (;;) {
26344520Snw141292 		r = sqlite_step(vm, &ncol, &values, NULL);
26354884Sjp151216 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
26364884Sjp151216 
26374884Sjp151216 		if (r == SQLITE_ROW) {
26386386Sjp151216 			if (ncol < 5) {
26394520Snw141292 				retcode = IDMAP_ERR_INTERNAL;
26404520Snw141292 				goto out;
26414520Snw141292 			}
26424520Snw141292 			if (values[0] == NULL) {
26434520Snw141292 				retcode = IDMAP_ERR_INTERNAL;
26444520Snw141292 				goto out;
26454520Snw141292 			}
26464520Snw141292 
26476386Sjp151216 			if (values[1] != NULL)
26486386Sjp151216 				direction =
26496386Sjp151216 				    (strtol(values[1], &end, 10) == 0)?
26506386Sjp151216 				    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
26516386Sjp151216 			else
26526386Sjp151216 				direction = IDMAP_DIRECTION_W2U;
26536386Sjp151216 
26544520Snw141292 			if (EMPTY_NAME(values[0])) {
26556386Sjp151216 				idmap_namerule_set(rule, values[3], values[2],
26566386Sjp151216 				    values[0], is_wuser, is_user,
26576386Sjp151216 				    strtol(values[4], &end, 10),
26586386Sjp151216 				    direction);
26594520Snw141292 				retcode = IDMAP_ERR_NOMAPPING;
26604520Snw141292 				goto out;
26614520Snw141292 			}
26626386Sjp151216 
26636386Sjp151216 			if (values[0][0] == '*') {
26646386Sjp151216 				unixname = winname;
26656386Sjp151216 				lower_unixname = lower_winname;
26666386Sjp151216 			} else {
26676386Sjp151216 				unixname = values[0];
26686386Sjp151216 				lower_unixname = NULL;
26696386Sjp151216 			}
26706386Sjp151216 
26715731Sbaban 			retcode = ns_lookup_byname(unixname, lower_unixname,
26725731Sbaban 			    &res->id);
26734520Snw141292 			if (retcode == IDMAP_ERR_NOTFOUND) {
26746386Sjp151216 				if (values[0][0] == '*')
26754520Snw141292 					/* Case 4 */
26764520Snw141292 					continue;
26776386Sjp151216 				else {
26784520Snw141292 					/* Case 3 */
26796386Sjp151216 					idmap_namerule_set(rule, values[3],
26806386Sjp151216 					    values[2], values[0], is_wuser,
26816386Sjp151216 					    is_user,
26826386Sjp151216 					    strtol(values[4], &end, 10),
26836386Sjp151216 					    direction);
26844520Snw141292 					retcode = IDMAP_ERR_NOMAPPING;
26856386Sjp151216 				}
26864520Snw141292 			}
26874520Snw141292 			goto out;
26884520Snw141292 		} else if (r == SQLITE_DONE) {
26894520Snw141292 			retcode = IDMAP_ERR_NOTFOUND;
26904520Snw141292 			goto out;
26914520Snw141292 		} else {
26924520Snw141292 			(void) sqlite_finalize(vm, &errmsg);
26934520Snw141292 			vm = NULL;
26945696Snw141292 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
26955696Snw141292 			    CHECK_NULL(errmsg));
26964520Snw141292 			sqlite_freemem(errmsg);
26974520Snw141292 			retcode = IDMAP_ERR_INTERNAL;
26984520Snw141292 			goto out;
26994520Snw141292 		}
27004520Snw141292 	}
27014520Snw141292 
27024520Snw141292 out:
27036386Sjp151216 	if (sql != NULL)
27046386Sjp151216 		sqlite_freemem(sql);
27056386Sjp151216 	res->info.how.map_type = IDMAP_MAP_TYPE_RULE_BASED;
27064520Snw141292 	if (retcode == IDMAP_SUCCESS) {
27074864Sbaban 		if (values[1] != NULL)
27084520Snw141292 			res->direction =
27094644Sbaban 			    (strtol(values[1], &end, 10) == 0)?
27104644Sbaban 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
27114520Snw141292 		else
27124644Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
27136386Sjp151216 
27145064Sdm199847 		req->id2name = strdup(unixname);
27156616Sdm199847 		if (req->id2name == NULL) {
27166616Sdm199847 			retcode = IDMAP_ERR_MEMORY;
27176616Sdm199847 		}
27186616Sdm199847 	}
27196616Sdm199847 
27206616Sdm199847 	if (retcode == IDMAP_SUCCESS) {
27216386Sjp151216 		idmap_namerule_set(rule, values[3], values[2],
27226386Sjp151216 		    values[0], is_wuser, is_user, strtol(values[4], &end, 10),
27236386Sjp151216 		    res->direction);
27246386Sjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
27254520Snw141292 	}
27266616Sdm199847 
27275696Snw141292 	if (lower_winname != NULL && lower_winname != winname)
27285696Snw141292 		free(lower_winname);
27294864Sbaban 	if (vm != NULL)
27304520Snw141292 		(void) sqlite_finalize(vm, NULL);
27314520Snw141292 	return (retcode);
27324520Snw141292 }
27334520Snw141292 
27344520Snw141292 static
27354520Snw141292 int
27364520Snw141292 get_next_eph_uid(uid_t *next_uid)
27374520Snw141292 {
27384520Snw141292 	uid_t uid;
27394520Snw141292 	gid_t gid;
27404520Snw141292 	int err;
27414520Snw141292 
27424520Snw141292 	*next_uid = (uid_t)-1;
27434520Snw141292 	uid = _idmapdstate.next_uid++;
27444520Snw141292 	if (uid >= _idmapdstate.limit_uid) {
27454520Snw141292 		if ((err = allocids(0, 8192, &uid, 0, &gid)) != 0)
27464520Snw141292 			return (err);
27474520Snw141292 
27484520Snw141292 		_idmapdstate.limit_uid = uid + 8192;
27494520Snw141292 		_idmapdstate.next_uid = uid;
27504520Snw141292 	}
27514520Snw141292 	*next_uid = uid;
27524520Snw141292 
27534520Snw141292 	return (0);
27544520Snw141292 }
27554520Snw141292 
27564520Snw141292 static
27574520Snw141292 int
27584520Snw141292 get_next_eph_gid(gid_t *next_gid)
27594520Snw141292 {
27604520Snw141292 	uid_t uid;
27614520Snw141292 	gid_t gid;
27624520Snw141292 	int err;
27634520Snw141292 
27644520Snw141292 	*next_gid = (uid_t)-1;
27654520Snw141292 	gid = _idmapdstate.next_gid++;
27664520Snw141292 	if (gid >= _idmapdstate.limit_gid) {
27674520Snw141292 		if ((err = allocids(0, 0, &uid, 8192, &gid)) != 0)
27684520Snw141292 			return (err);
27694520Snw141292 
27704520Snw141292 		_idmapdstate.limit_gid = gid + 8192;
27714520Snw141292 		_idmapdstate.next_gid = gid;
27724520Snw141292 	}
27734520Snw141292 	*next_gid = gid;
27744520Snw141292 
27754520Snw141292 	return (0);
27764520Snw141292 }
27774520Snw141292 
27784864Sbaban static
27794864Sbaban int
27805696Snw141292 gethash(const char *str, uint32_t num, uint_t htsize)
27815696Snw141292 {
27824864Sbaban 	uint_t  hval, i, len;
27834864Sbaban 
27844864Sbaban 	if (str == NULL)
27854864Sbaban 		return (0);
27864864Sbaban 	for (len = strlen(str), hval = 0, i = 0; i < len; i++) {
27874864Sbaban 		hval += str[i];
27884864Sbaban 		hval += (hval << 10);
27894864Sbaban 		hval ^= (hval >> 6);
27904864Sbaban 	}
27914864Sbaban 	for (str = (const char *)&num, i = 0; i < sizeof (num); i++) {
27924864Sbaban 		hval += str[i];
27934864Sbaban 		hval += (hval << 10);
27944864Sbaban 		hval ^= (hval >> 6);
27954864Sbaban 	}
27964864Sbaban 	hval += (hval << 3);
27974864Sbaban 	hval ^= (hval >> 11);
27984864Sbaban 	hval += (hval << 15);
27994864Sbaban 	return (hval % htsize);
28004864Sbaban }
28014864Sbaban 
28024864Sbaban static
28034864Sbaban int
28044864Sbaban get_from_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid,
28055696Snw141292 		uid_t *pid)
28065696Snw141292 {
28074864Sbaban 	uint_t		next, key;
28084864Sbaban 	uint_t		htsize = state->sid_history_size;
28094864Sbaban 	idmap_sid	*sid;
28104864Sbaban 
28114864Sbaban 	next = gethash(prefix, rid, htsize);
28124864Sbaban 	while (next != htsize) {
28134864Sbaban 		key = state->sid_history[next].key;
28144864Sbaban 		if (key == htsize)
28154864Sbaban 			return (0);
28164864Sbaban 		sid = &state->batch->idmap_mapping_batch_val[key].id1.
28174864Sbaban 		    idmap_id_u.sid;
28184864Sbaban 		if (sid->rid == rid && strcmp(sid->prefix, prefix) == 0) {
28194864Sbaban 			*pid = state->result->ids.ids_val[key].id.
28204864Sbaban 			    idmap_id_u.uid;
28214864Sbaban 			return (1);
28224864Sbaban 		}
28234864Sbaban 		next = state->sid_history[next].next;
28244864Sbaban 	}
28254864Sbaban 	return (0);
28264864Sbaban }
28274864Sbaban 
28284864Sbaban static
28294864Sbaban void
28305696Snw141292 add_to_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid)
28315696Snw141292 {
28324864Sbaban 	uint_t		hash, next;
28334864Sbaban 	uint_t		htsize = state->sid_history_size;
28344864Sbaban 
28354864Sbaban 	hash = next = gethash(prefix, rid, htsize);
28364864Sbaban 	while (state->sid_history[next].key != htsize) {
28374864Sbaban 		next++;
28384864Sbaban 		next %= htsize;
28394864Sbaban 	}
28404864Sbaban 	state->sid_history[next].key = state->curpos;
28414864Sbaban 	if (hash == next)
28424864Sbaban 		return;
28434864Sbaban 	state->sid_history[next].next = state->sid_history[hash].next;
28444864Sbaban 	state->sid_history[hash].next = next;
28454864Sbaban }
28464520Snw141292 
28475731Sbaban void
28485731Sbaban cleanup_lookup_state(lookup_state_t *state)
28495731Sbaban {
28505731Sbaban 	free(state->sid_history);
28515731Sbaban 	free(state->ad_unixuser_attr);
28525731Sbaban 	free(state->ad_unixgroup_attr);
28536616Sdm199847 	free(state->nldap_winname_attr);
28546616Sdm199847 	free(state->defdom);
28555731Sbaban }
28565731Sbaban 
28574520Snw141292 /* ARGSUSED */
28584520Snw141292 static
28594520Snw141292 idmap_retcode
28606616Sdm199847 dynamic_ephemeral_mapping(lookup_state_t *state,
28615696Snw141292 		idmap_mapping *req, idmap_id_res *res)
28625696Snw141292 {
28634520Snw141292 
28644520Snw141292 	uid_t		next_pid;
28654520Snw141292 
28664864Sbaban 	res->direction = IDMAP_DIRECTION_BI;
28674864Sbaban 
28686386Sjp151216 	if (IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
28696386Sjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
28706386Sjp151216 		res->info.src = IDMAP_MAP_SRC_CACHE;
28714864Sbaban 		return (IDMAP_SUCCESS);
28726386Sjp151216 	}
28734864Sbaban 
28744864Sbaban 	if (state->sid_history != NULL &&
28754864Sbaban 	    get_from_sid_history(state, req->id1.idmap_id_u.sid.prefix,
28764864Sbaban 	    req->id1.idmap_id_u.sid.rid, &next_pid)) {
28774864Sbaban 		res->id.idmap_id_u.uid = next_pid;
28786386Sjp151216 		res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
28796386Sjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
28804864Sbaban 		return (IDMAP_SUCCESS);
28814864Sbaban 	}
28824864Sbaban 
28834864Sbaban 	if (res->id.idtype == IDMAP_UID) {
28844520Snw141292 		if (get_next_eph_uid(&next_pid) != 0)
28854520Snw141292 			return (IDMAP_ERR_INTERNAL);
28864520Snw141292 		res->id.idmap_id_u.uid = next_pid;
28874520Snw141292 	} else {
28884520Snw141292 		if (get_next_eph_gid(&next_pid) != 0)
28894520Snw141292 			return (IDMAP_ERR_INTERNAL);
28904520Snw141292 		res->id.idmap_id_u.gid = next_pid;
28914520Snw141292 	}
28924520Snw141292 
28936386Sjp151216 	res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
28946386Sjp151216 	res->info.src = IDMAP_MAP_SRC_NEW;
28954864Sbaban 	if (state->sid_history != NULL)
28964864Sbaban 		add_to_sid_history(state, req->id1.idmap_id_u.sid.prefix,
28974864Sbaban 		    req->id1.idmap_id_u.sid.rid);
28984864Sbaban 
28994520Snw141292 	return (IDMAP_SUCCESS);
29004520Snw141292 }
29014520Snw141292 
29024520Snw141292 idmap_retcode
29036616Sdm199847 sid2pid_second_pass(lookup_state_t *state,
29045696Snw141292 		idmap_mapping *req, idmap_id_res *res)
29055696Snw141292 {
29064520Snw141292 	idmap_retcode	retcode;
29074520Snw141292 
29084520Snw141292 	/* Check if second pass is needed */
29095731Sbaban 	if (ARE_WE_DONE(req->direction))
29104520Snw141292 		return (res->retcode);
29114520Snw141292 
29124520Snw141292 	/* Get status from previous pass */
29135731Sbaban 	retcode = res->retcode;
2914*7031Snw141292 	if (retcode != IDMAP_SUCCESS && state->eph_map_unres_sids &&
2915*7031Snw141292 	    !EMPTY_STRING(req->id1.idmap_id_u.sid.prefix) &&
2916*7031Snw141292 	    EMPTY_STRING(req->id1name)) {
2917*7031Snw141292 		/*
2918*7031Snw141292 		 * We are asked to map an unresolvable SID to a UID or
2919*7031Snw141292 		 * GID, but, which?  We'll treat all unresolvable SIDs
2920*7031Snw141292 		 * as users unless the caller specified which of a UID
2921*7031Snw141292 		 * or GID they want.
2922*7031Snw141292 		 */
2923*7031Snw141292 		if (res->id.idtype == IDMAP_POSIXID)
2924*7031Snw141292 			res->id.idtype = IDMAP_UID;
2925*7031Snw141292 		goto do_eph;
2926*7031Snw141292 	}
29275731Sbaban 	if (retcode != IDMAP_SUCCESS)
29285731Sbaban 		goto out;
29295731Sbaban 
29305731Sbaban 	/*
29315731Sbaban 	 * If directory-based name mapping is enabled then the unixname
29325731Sbaban 	 * may already have been retrieved from the AD object (AD-mode or
29335731Sbaban 	 * mixed-mode) or from native LDAP object (nldap-mode) -- done.
29345731Sbaban 	 */
29355731Sbaban 	if (req->id2name != NULL) {
29365731Sbaban 		assert(res->id.idtype != IDMAP_POSIXID);
29375731Sbaban 		if (AD_MODE(res->id.idtype, state))
29385731Sbaban 			res->direction = IDMAP_DIRECTION_BI;
29395731Sbaban 		else if (NLDAP_MODE(res->id.idtype, state))
29405731Sbaban 			res->direction = IDMAP_DIRECTION_BI;
29415731Sbaban 		else if (MIXED_MODE(res->id.idtype, state))
29425731Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
29435731Sbaban 
29445731Sbaban 		/*
29455731Sbaban 		 * Special case: (1) If the ad_unixuser_attr and
29465731Sbaban 		 * ad_unixgroup_attr uses the same attribute
29475731Sbaban 		 * name and (2) if this is a diagonal mapping
29485731Sbaban 		 * request and (3) the unixname has been retrieved
29495731Sbaban 		 * from the AD object -- then we ignore it and fallback
29505731Sbaban 		 * to name-based mapping rules and ephemeral mapping
29515731Sbaban 		 *
29525731Sbaban 		 * Example:
29535731Sbaban 		 *  Properties:
29545731Sbaban 		 *    config/ad_unixuser_attr = "unixname"
29555731Sbaban 		 *    config/ad_unixgroup_attr = "unixname"
29565731Sbaban 		 *  AD user object:
29575731Sbaban 		 *    dn: cn=bob ...
29585731Sbaban 		 *    objectclass: user
29595731Sbaban 		 *    sam: bob
29605731Sbaban 		 *    unixname: bob1234
29615731Sbaban 		 *  AD group object:
29625731Sbaban 		 *    dn: cn=winadmins ...
29635731Sbaban 		 *    objectclass: group
29645731Sbaban 		 *    sam: winadmins
29655731Sbaban 		 *    unixname: unixadmins
29665731Sbaban 		 *
29675731Sbaban 		 *  In this example whether "unixname" refers to a unixuser
29685731Sbaban 		 *  or unixgroup depends upon the AD object.
29695731Sbaban 		 *
29705731Sbaban 		 * $idmap show -c winname:bob gid
29715731Sbaban 		 *    AD lookup by "samAccountName=bob" for
29725731Sbaban 		 *    "ad_unixgroup_attr (i.e unixname)" for directory-based
29735731Sbaban 		 *    mapping would get "bob1234" which is not what we want.
29745731Sbaban 		 *    Now why not getgrnam_r("bob1234") and use it if it
29755731Sbaban 		 *    is indeed a unixgroup? That's because Unix can have
29765731Sbaban 		 *    users and groups with the same name and we clearly
29775731Sbaban 		 *    don't know the intention of the admin here.
29785731Sbaban 		 *    Therefore we ignore this and fallback to name-based
29795731Sbaban 		 *    mapping rules or ephemeral mapping.
29805731Sbaban 		 */
29815731Sbaban 		if ((AD_MODE(res->id.idtype, state) ||
29825731Sbaban 		    MIXED_MODE(res->id.idtype, state)) &&
29835731Sbaban 		    state->ad_unixuser_attr != NULL &&
29845731Sbaban 		    state->ad_unixgroup_attr != NULL &&
29855731Sbaban 		    strcasecmp(state->ad_unixuser_attr,
29865731Sbaban 		    state->ad_unixgroup_attr) == 0 &&
29875731Sbaban 		    ((req->id1.idtype == IDMAP_USID &&
29885731Sbaban 		    res->id.idtype == IDMAP_GID) ||
29895731Sbaban 		    (req->id1.idtype == IDMAP_GSID &&
29905731Sbaban 		    res->id.idtype == IDMAP_UID))) {
29915731Sbaban 			free(req->id2name);
29925731Sbaban 			req->id2name = NULL;
29935731Sbaban 			res->id.idmap_id_u.uid = SENTINEL_PID;
29945731Sbaban 			/* fallback */
29955731Sbaban 		} else {
29965731Sbaban 			if (res->id.idmap_id_u.uid == SENTINEL_PID)
29975731Sbaban 				retcode = ns_lookup_byname(req->id2name,
29985731Sbaban 				    NULL, &res->id);
29995731Sbaban 			/*
30006616Sdm199847 			 * If ns_lookup_byname() fails that means the
30016616Sdm199847 			 * unixname (req->id2name), which was obtained
30026616Sdm199847 			 * from the AD object by directory-based mapping,
30036616Sdm199847 			 * is not a valid Unix user/group and therefore
30046616Sdm199847 			 * we return the error to the client instead of
30056616Sdm199847 			 * doing rule-based mapping or ephemeral mapping.
30066616Sdm199847 			 * This way the client can detect the issue.
30075731Sbaban 			 */
30085731Sbaban 			goto out;
30094520Snw141292 		}
30104520Snw141292 	}
30114520Snw141292 
30126386Sjp151216 	/* Free any mapping info from Directory based mapping */
30136386Sjp151216 	if (res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN)
30146386Sjp151216 		idmap_info_free(&res->info);
30156386Sjp151216 
30165731Sbaban 	/*
30175731Sbaban 	 * If we don't have unixname then evaluate local name-based
30185731Sbaban 	 * mapping rules.
30195731Sbaban 	 */
30206616Sdm199847 	retcode = name_based_mapping_sid2pid(state, req, res);
30215731Sbaban 	if (retcode != IDMAP_ERR_NOTFOUND)
30224520Snw141292 		goto out;
30234520Snw141292 
3024*7031Snw141292 do_eph:
30255731Sbaban 	/* If not found, do ephemeral mapping */
30266616Sdm199847 	retcode = dynamic_ephemeral_mapping(state, req, res);
30274520Snw141292 
30284520Snw141292 out:
30294520Snw141292 	res->retcode = idmap_stat4prot(retcode);
30305731Sbaban 	if (res->retcode != IDMAP_SUCCESS) {
30315731Sbaban 		req->direction = _IDMAP_F_DONE;
30325731Sbaban 		res->id.idmap_id_u.uid = UID_NOBODY;
30335731Sbaban 	}
30345731Sbaban 	if (!ARE_WE_DONE(req->direction))
30355731Sbaban 		state->sid2pid_done = FALSE;
30364520Snw141292 	return (retcode);
30374520Snw141292 }
30384520Snw141292 
30394520Snw141292 idmap_retcode
30406616Sdm199847 update_cache_pid2sid(lookup_state_t *state,
30415696Snw141292 		idmap_mapping *req, idmap_id_res *res)
30425696Snw141292 {
30434520Snw141292 	char		*sql = NULL;
30444520Snw141292 	idmap_retcode	retcode;
30456386Sjp151216 	char		*map_dn = NULL;
30466386Sjp151216 	char		*map_attr = NULL;
30476386Sjp151216 	char		*map_value = NULL;
30486386Sjp151216 	char 		*map_windomain = NULL;
30496386Sjp151216 	char		*map_winname = NULL;
30506386Sjp151216 	char		*map_unixname = NULL;
30516386Sjp151216 	int		map_is_nt4 = FALSE;
30524520Snw141292 
30534520Snw141292 	/* Check if we need to cache anything */
30545731Sbaban 	if (ARE_WE_DONE(req->direction))
30554520Snw141292 		return (IDMAP_SUCCESS);
30564520Snw141292 
30574520Snw141292 	/* We don't cache negative entries */
30584520Snw141292 	if (res->retcode != IDMAP_SUCCESS)
30594520Snw141292 		return (IDMAP_SUCCESS);
30604520Snw141292 
30615731Sbaban 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
30626386Sjp151216 	assert(req->id1.idmap_id_u.uid != SENTINEL_PID);
30636386Sjp151216 	assert(res->id.idtype != IDMAP_SID);
30646386Sjp151216 
30656386Sjp151216 	assert(res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN);
30666386Sjp151216 	switch (res->info.how.map_type) {
30676386Sjp151216 	case IDMAP_MAP_TYPE_DS_AD:
30686386Sjp151216 		map_dn = res->info.how.idmap_how_u.ad.dn;
30696386Sjp151216 		map_attr = res->info.how.idmap_how_u.ad.attr;
30706386Sjp151216 		map_value = res->info.how.idmap_how_u.ad.value;
30716386Sjp151216 		break;
30726386Sjp151216 
30736386Sjp151216 	case IDMAP_MAP_TYPE_DS_NLDAP:
30746386Sjp151216 		map_dn = res->info.how.idmap_how_u.nldap.dn;
30756386Sjp151216 		map_attr = res->info.how.idmap_how_u.nldap.attr;
30766386Sjp151216 		map_value = res->info.how.idmap_how_u.nldap.value;
30776386Sjp151216 		break;
30786386Sjp151216 
30796386Sjp151216 	case IDMAP_MAP_TYPE_RULE_BASED:
30806386Sjp151216 		map_windomain = res->info.how.idmap_how_u.rule.windomain;
30816386Sjp151216 		map_winname = res->info.how.idmap_how_u.rule.winname;
30826386Sjp151216 		map_unixname = res->info.how.idmap_how_u.rule.unixname;
30836386Sjp151216 		map_is_nt4 = res->info.how.idmap_how_u.rule.is_nt4;
30846386Sjp151216 		break;
30856386Sjp151216 
30866386Sjp151216 	case IDMAP_MAP_TYPE_EPHEMERAL:
30876386Sjp151216 		break;
30886386Sjp151216 
30896386Sjp151216 	case IDMAP_MAP_TYPE_LOCAL_SID:
30906386Sjp151216 		break;
30916386Sjp151216 
30926386Sjp151216 	default:
30936386Sjp151216 		/* Dont cache other mapping types */
30946386Sjp151216 		assert(FALSE);
30956386Sjp151216 	}
30965731Sbaban 
30974520Snw141292 	/*
30984520Snw141292 	 * Using NULL for u2w instead of 0 so that our trigger allows
30994520Snw141292 	 * the same pid to be the destination in multiple entries
31004520Snw141292 	 */
31014520Snw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
31025696Snw141292 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
31036386Sjp151216 	    "is_user, is_wuser, expiration, w2u, u2w, "
31046386Sjp151216 	    "map_type, map_dn, map_attr, map_value, map_windomain, "
31056386Sjp151216 	    "map_winname, map_unixname, map_is_nt4) "
31065696Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
31076386Sjp151216 	    "strftime('%%s','now') + 600, %q, 1, "
31086386Sjp151216 	    "%d, %Q, %Q, %Q, %Q, %Q, %Q, %d); ",
31095696Snw141292 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
31105696Snw141292 	    req->id2domain, req->id2name, req->id1.idmap_id_u.uid,
31115696Snw141292 	    req->id1name, (req->id1.idtype == IDMAP_UID) ? 1 : 0,
31125731Sbaban 	    (res->id.idtype == IDMAP_USID) ? 1 : 0,
31136386Sjp151216 	    (res->direction == 0) ? "1" : NULL,
31146386Sjp151216 	    res->info.how.map_type, map_dn, map_attr, map_value,
31156386Sjp151216 	    map_windomain, map_winname, map_unixname, map_is_nt4);
31164520Snw141292 
31174520Snw141292 	if (sql == NULL) {
31184520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
31194520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
31204520Snw141292 		goto out;
31214520Snw141292 	}
31224520Snw141292 
31236616Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
31244520Snw141292 	if (retcode != IDMAP_SUCCESS)
31254520Snw141292 		goto out;
31264520Snw141292 
31274520Snw141292 	state->pid2sid_done = FALSE;
31284520Snw141292 	sqlite_freemem(sql);
31294520Snw141292 	sql = NULL;
31304520Snw141292 
31315731Sbaban 	/* Check if we need to update namecache */
31325731Sbaban 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
31334520Snw141292 		goto out;
31344520Snw141292 
31355064Sdm199847 	if (req->id2name == NULL)
31364520Snw141292 		goto out;
31374520Snw141292 
31384520Snw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
31395696Snw141292 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
31405696Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
31415696Snw141292 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
31425696Snw141292 	    req->id2name, req->id2domain,
31435731Sbaban 	    (res->id.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
31444520Snw141292 
31454520Snw141292 	if (sql == NULL) {
31464520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
31474520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
31484520Snw141292 		goto out;
31494520Snw141292 	}
31504520Snw141292 
31516616Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
31524520Snw141292 
31534520Snw141292 out:
31546386Sjp151216 	if (!(req->flag & IDMAP_REQ_FLG_MAPPING_INFO))
31556386Sjp151216 		idmap_info_free(&res->info);
31564864Sbaban 	if (sql != NULL)
31574520Snw141292 		sqlite_freemem(sql);
31584520Snw141292 	return (retcode);
31594520Snw141292 }
31604520Snw141292 
31614520Snw141292 idmap_retcode
31626616Sdm199847 update_cache_sid2pid(lookup_state_t *state,
31635696Snw141292 		idmap_mapping *req, idmap_id_res *res)
31645696Snw141292 {
31654520Snw141292 	char		*sql = NULL;
31664520Snw141292 	idmap_retcode	retcode;
31674520Snw141292 	int		is_eph_user;
31686386Sjp151216 	char		*map_dn = NULL;
31696386Sjp151216 	char		*map_attr = NULL;
31706386Sjp151216 	char		*map_value = NULL;
31716386Sjp151216 	char 		*map_windomain = NULL;
31726386Sjp151216 	char		*map_winname = NULL;
31736386Sjp151216 	char		*map_unixname = NULL;
31746386Sjp151216 	int		map_is_nt4 = FALSE;
31754520Snw141292 
31764520Snw141292 	/* Check if we need to cache anything */
31775731Sbaban 	if (ARE_WE_DONE(req->direction))
31784520Snw141292 		return (IDMAP_SUCCESS);
31794520Snw141292 
31804520Snw141292 	/* We don't cache negative entries */
31814520Snw141292 	if (res->retcode != IDMAP_SUCCESS)
31824520Snw141292 		return (IDMAP_SUCCESS);
31834520Snw141292 
31844520Snw141292 	if (req->direction & _IDMAP_F_EXP_EPH_UID)
31854520Snw141292 		is_eph_user = 1;
31864520Snw141292 	else if (req->direction & _IDMAP_F_EXP_EPH_GID)
31874520Snw141292 		is_eph_user = 0;
31884520Snw141292 	else
31894520Snw141292 		is_eph_user = -1;
31904520Snw141292 
31914520Snw141292 	if (is_eph_user >= 0 && !IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
31924520Snw141292 		sql = sqlite_mprintf("UPDATE idmap_cache "
31935696Snw141292 		    "SET w2u = 0 WHERE "
31945696Snw141292 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
31955696Snw141292 		    "pid >= 2147483648 AND is_user = %d;",
31965696Snw141292 		    req->id1.idmap_id_u.sid.prefix,
31975696Snw141292 		    req->id1.idmap_id_u.sid.rid,
31985696Snw141292 		    is_eph_user);
31994520Snw141292 		if (sql == NULL) {
32004520Snw141292 			retcode = IDMAP_ERR_INTERNAL;
32014520Snw141292 			idmapdlog(LOG_ERR, "Out of memory");
32024520Snw141292 			goto out;
32034520Snw141292 		}
32044520Snw141292 
32056616Sdm199847 		retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
32064520Snw141292 		if (retcode != IDMAP_SUCCESS)
32074520Snw141292 			goto out;
32084520Snw141292 
32094520Snw141292 		sqlite_freemem(sql);
32104520Snw141292 		sql = NULL;
32114520Snw141292 	}
32124520Snw141292 
32135731Sbaban 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
32146386Sjp151216 	assert(res->id.idmap_id_u.uid != SENTINEL_PID);
32156386Sjp151216 
32166386Sjp151216 	switch (res->info.how.map_type) {
32176386Sjp151216 	case IDMAP_MAP_TYPE_DS_AD:
32186386Sjp151216 		map_dn = res->info.how.idmap_how_u.ad.dn;
32196386Sjp151216 		map_attr = res->info.how.idmap_how_u.ad.attr;
32206386Sjp151216 		map_value = res->info.how.idmap_how_u.ad.value;
32216386Sjp151216 		break;
32226386Sjp151216 
32236386Sjp151216 	case IDMAP_MAP_TYPE_DS_NLDAP:
32246386Sjp151216 		map_dn = res->info.how.idmap_how_u.nldap.dn;
32256386Sjp151216 		map_attr = res->info.how.idmap_how_u.ad.attr;
32266386Sjp151216 		map_value = res->info.how.idmap_how_u.nldap.value;
32276386Sjp151216 		break;
32286386Sjp151216 
32296386Sjp151216 	case IDMAP_MAP_TYPE_RULE_BASED:
32306386Sjp151216 		map_windomain = res->info.how.idmap_how_u.rule.windomain;
32316386Sjp151216 		map_winname = res->info.how.idmap_how_u.rule.winname;
32326386Sjp151216 		map_unixname = res->info.how.idmap_how_u.rule.unixname;
32336386Sjp151216 		map_is_nt4 = res->info.how.idmap_how_u.rule.is_nt4;
32346386Sjp151216 		break;
32356386Sjp151216 
32366386Sjp151216 	case IDMAP_MAP_TYPE_EPHEMERAL:
32376386Sjp151216 		break;
32386386Sjp151216 
32396386Sjp151216 	default:
32406386Sjp151216 		/* Dont cache other mapping types */
32416386Sjp151216 		assert(FALSE);
32426386Sjp151216 	}
32435696Snw141292 
32444520Snw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
32455696Snw141292 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
32466386Sjp151216 	    "is_user, is_wuser, expiration, w2u, u2w, "
32476386Sjp151216 	    "map_type, map_dn, map_attr, map_value, map_windomain, "
32486386Sjp151216 	    "map_winname, map_unixname, map_is_nt4) "
32495696Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
32506386Sjp151216 	    "strftime('%%s','now') + 600, 1, %q, "
32516386Sjp151216 	    "%d, %Q, %Q, %Q, %Q, %Q, %Q, %d);",
32525696Snw141292 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
32535731Sbaban 	    (req->id1domain != NULL) ? req->id1domain : "", req->id1name,
32545731Sbaban 	    res->id.idmap_id_u.uid, req->id2name,
32555731Sbaban 	    (res->id.idtype == IDMAP_UID) ? 1 : 0,
32565696Snw141292 	    (req->id1.idtype == IDMAP_USID) ? 1 : 0,
32576386Sjp151216 	    (res->direction == 0) ? "1" : NULL,
32586386Sjp151216 	    res->info.how.map_type, map_dn, map_attr, map_value,
32596386Sjp151216 	    map_windomain, map_winname, map_unixname, map_is_nt4);
32604520Snw141292 
32614520Snw141292 	if (sql == NULL) {
32624520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
32634520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
32644520Snw141292 		goto out;
32654520Snw141292 	}
32664520Snw141292 
32676616Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
32684520Snw141292 	if (retcode != IDMAP_SUCCESS)
32694520Snw141292 		goto out;
32704520Snw141292 
32714520Snw141292 	state->sid2pid_done = FALSE;
32724520Snw141292 	sqlite_freemem(sql);
32734520Snw141292 	sql = NULL;
32744520Snw141292 
32755731Sbaban 	/* Check if we need to update namecache */
32765731Sbaban 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
32774520Snw141292 		goto out;
32784520Snw141292 
32795127Sdm199847 	if (EMPTY_STRING(req->id1name))
32804520Snw141292 		goto out;
32814520Snw141292 
32824520Snw141292 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
32835696Snw141292 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
32845696Snw141292 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
32855696Snw141292 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
32865696Snw141292 	    req->id1name, req->id1domain,
32875696Snw141292 	    (req->id1.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
32884520Snw141292 
32894520Snw141292 	if (sql == NULL) {
32904520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
32914520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
32924520Snw141292 		goto out;
32934520Snw141292 	}
32944520Snw141292 
32956616Sdm199847 	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
32964520Snw141292 
32974520Snw141292 out:
32986386Sjp151216 	if (!(req->flag & IDMAP_REQ_FLG_MAPPING_INFO))
32996386Sjp151216 		idmap_info_free(&res->info);
33006386Sjp151216 
33014864Sbaban 	if (sql != NULL)
33024520Snw141292 		sqlite_freemem(sql);
33034520Snw141292 	return (retcode);
33044520Snw141292 }
33054520Snw141292 
33065696Snw141292 static
33075696Snw141292 idmap_retcode
33084520Snw141292 lookup_cache_pid2sid(sqlite *cache, idmap_mapping *req, idmap_id_res *res,
33095696Snw141292 		int is_user, int getname)
33105696Snw141292 {
33114520Snw141292 	char		*end;
33124520Snw141292 	char		*sql = NULL;
33134520Snw141292 	const char	**values;
33144520Snw141292 	sqlite_vm	*vm = NULL;
33154520Snw141292 	int		ncol;
33164520Snw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
33174520Snw141292 	time_t		curtime;
33185731Sbaban 	idmap_id_type	idtype;
33194520Snw141292 
33204520Snw141292 	/* Current time */
33214520Snw141292 	errno = 0;
33224520Snw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
33235696Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
33245696Snw141292 		    strerror(errno));
33254520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
33264520Snw141292 		goto out;
33274520Snw141292 	}
33284520Snw141292 
33295731Sbaban 	/* SQL to lookup the cache by pid or by unixname */
33305731Sbaban 	if (req->id1.idmap_id_u.uid != SENTINEL_PID) {
33316386Sjp151216 		sql = sqlite_mprintf("SELECT sidprefix, rid, "
33326386Sjp151216 		    "canon_winname, windomain, w2u, is_wuser, "
33336386Sjp151216 		    "map_type, map_dn, map_attr, map_value, map_windomain, "
33346386Sjp151216 		    "map_winname, map_unixname, map_is_nt4 "
33355731Sbaban 		    "FROM idmap_cache WHERE "
33365731Sbaban 		    "pid = %u AND u2w = 1 AND is_user = %d AND "
33375731Sbaban 		    "(pid >= 2147483648 OR "
33385731Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
33395731Sbaban 		    "expiration > %d));",
33405731Sbaban 		    req->id1.idmap_id_u.uid, is_user, curtime);
33415731Sbaban 	} else if (req->id1name != NULL) {
33426386Sjp151216 		sql = sqlite_mprintf("SELECT sidprefix, rid, "
33436386Sjp151216 		    "canon_winname, windomain, w2u, is_wuser, "
33446386Sjp151216 		    "map_type, map_dn, map_attr, map_value, map_windomain, "
33456386Sjp151216 		    "map_winname, map_unixname, map_is_nt4 "
33465731Sbaban 		    "FROM idmap_cache WHERE "
33475731Sbaban 		    "unixname = %Q AND u2w = 1 AND is_user = %d AND "
33485731Sbaban 		    "(pid >= 2147483648 OR "
33495731Sbaban 		    "(expiration = 0 OR expiration ISNULL OR "
33505731Sbaban 		    "expiration > %d));",
33515731Sbaban 		    req->id1name, is_user, curtime);
33526386Sjp151216 	} else {
33536386Sjp151216 		retcode = IDMAP_ERR_ARG;
33546386Sjp151216 		goto out;
33555731Sbaban 	}
33565731Sbaban 
33574520Snw141292 	if (sql == NULL) {
33584520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
33594520Snw141292 		retcode = IDMAP_ERR_MEMORY;
33604520Snw141292 		goto out;
33614520Snw141292 	}
33626386Sjp151216 	retcode = sql_compile_n_step_once(
33636386Sjp151216 	    cache, sql, &vm, &ncol, 14, &values);
33644520Snw141292 	sqlite_freemem(sql);
33654520Snw141292 
33664520Snw141292 	if (retcode == IDMAP_ERR_NOTFOUND)
33674520Snw141292 		goto out;
33684520Snw141292 	else if (retcode == IDMAP_SUCCESS) {
33694520Snw141292 		/* sanity checks */
33704520Snw141292 		if (values[0] == NULL || values[1] == NULL) {
33714520Snw141292 			retcode = IDMAP_ERR_CACHE;
33724520Snw141292 			goto out;
33734520Snw141292 		}
33744520Snw141292 
33755731Sbaban 		switch (res->id.idtype) {
33764520Snw141292 		case IDMAP_SID:
33775696Snw141292 		case IDMAP_USID:
33785696Snw141292 		case IDMAP_GSID:
33795731Sbaban 			idtype = strtol(values[5], &end, 10) == 1
33805696Snw141292 			    ? IDMAP_USID : IDMAP_GSID;
33815696Snw141292 
33825731Sbaban 			if (res->id.idtype == IDMAP_USID &&
33835731Sbaban 			    idtype != IDMAP_USID) {
33845696Snw141292 				retcode = IDMAP_ERR_NOTUSER;
33855696Snw141292 				goto out;
33865731Sbaban 			} else if (res->id.idtype == IDMAP_GSID &&
33875731Sbaban 			    idtype != IDMAP_GSID) {
33885696Snw141292 				retcode = IDMAP_ERR_NOTGROUP;
33895696Snw141292 				goto out;
33905696Snw141292 			}
33915731Sbaban 			res->id.idtype = idtype;
33925696Snw141292 
33934520Snw141292 			res->id.idmap_id_u.sid.rid =
33945696Snw141292 			    strtoul(values[1], &end, 10);
33954520Snw141292 			res->id.idmap_id_u.sid.prefix = strdup(values[0]);
33964520Snw141292 			if (res->id.idmap_id_u.sid.prefix == NULL) {
33974520Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
33984520Snw141292 				retcode = IDMAP_ERR_MEMORY;
33994520Snw141292 				goto out;
34004520Snw141292 			}
34014520Snw141292 
34024864Sbaban 			if (values[4] != NULL)
34034520Snw141292 				res->direction =
34044644Sbaban 				    (strtol(values[4], &end, 10) == 0)?
34054644Sbaban 				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
34064520Snw141292 			else
34074644Sbaban 				res->direction = IDMAP_DIRECTION_U2W;
34084520Snw141292 
34094520Snw141292 			if (getname == 0 || values[2] == NULL)
34104520Snw141292 				break;
34115064Sdm199847 			req->id2name = strdup(values[2]);
34125064Sdm199847 			if (req->id2name == NULL) {
34134520Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
34144520Snw141292 				retcode = IDMAP_ERR_MEMORY;
34154520Snw141292 				goto out;
34164520Snw141292 			}
34174520Snw141292 
34184520Snw141292 			if (values[3] == NULL)
34194520Snw141292 				break;
34205064Sdm199847 			req->id2domain = strdup(values[3]);
34215064Sdm199847 			if (req->id2domain == NULL) {
34224520Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
34234520Snw141292 				retcode = IDMAP_ERR_MEMORY;
34244520Snw141292 				goto out;
34254520Snw141292 			}
34265696Snw141292 
34274520Snw141292 			break;
34284520Snw141292 		default:
34294520Snw141292 			retcode = IDMAP_ERR_NOTSUPPORTED;
34304520Snw141292 			break;
34314520Snw141292 		}
34326386Sjp151216 		if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
34336386Sjp151216 			res->info.src = IDMAP_MAP_SRC_CACHE;
34346386Sjp151216 			res->info.how.map_type = strtoul(values[6], &end, 10);
34356386Sjp151216 			switch (res->info.how.map_type) {
34366386Sjp151216 			case IDMAP_MAP_TYPE_DS_AD:
34376386Sjp151216 				res->info.how.idmap_how_u.ad.dn =
34386386Sjp151216 				    strdup(values[7]);
34396386Sjp151216 				res->info.how.idmap_how_u.ad.attr =
34406386Sjp151216 				    strdup(values[8]);
34416386Sjp151216 				res->info.how.idmap_how_u.ad.value =
34426386Sjp151216 				    strdup(values[9]);
34436386Sjp151216 				break;
34446386Sjp151216 
34456386Sjp151216 			case IDMAP_MAP_TYPE_DS_NLDAP:
34466386Sjp151216 				res->info.how.idmap_how_u.nldap.dn =
34476386Sjp151216 				    strdup(values[7]);
34486386Sjp151216 				res->info.how.idmap_how_u.nldap.attr =
34496386Sjp151216 				    strdup(values[8]);
34506386Sjp151216 				res->info.how.idmap_how_u.nldap.value =
34516386Sjp151216 				    strdup(values[9]);
34526386Sjp151216 				break;
34536386Sjp151216 
34546386Sjp151216 			case IDMAP_MAP_TYPE_RULE_BASED:
34556386Sjp151216 				res->info.how.idmap_how_u.rule.windomain =
34566386Sjp151216 				    strdup(values[10]);
34576386Sjp151216 				res->info.how.idmap_how_u.rule.winname =
34586386Sjp151216 				    strdup(values[11]);
34596386Sjp151216 				res->info.how.idmap_how_u.rule.unixname =
34606386Sjp151216 				    strdup(values[12]);
34616386Sjp151216 				res->info.how.idmap_how_u.rule.is_nt4 =
34626386Sjp151216 				    strtoul(values[13], &end, 10);
34636386Sjp151216 				res->info.how.idmap_how_u.rule.is_user =
34646386Sjp151216 				    is_user;
34656386Sjp151216 				res->info.how.idmap_how_u.rule.is_wuser =
34666386Sjp151216 				    strtol(values[5], &end, 10);
34676386Sjp151216 				break;
34686386Sjp151216 
34696386Sjp151216 			case IDMAP_MAP_TYPE_EPHEMERAL:
34706386Sjp151216 				break;
34716386Sjp151216 
34726386Sjp151216 			case IDMAP_MAP_TYPE_LOCAL_SID:
34736386Sjp151216 				break;
34746386Sjp151216 
34756386Sjp151216 			case IDMAP_MAP_TYPE_KNOWN_SID:
34766386Sjp151216 				break;
34776386Sjp151216 
34786386Sjp151216 			default:
34796386Sjp151216 				/* Unknow mapping type */
34806386Sjp151216 				assert(FALSE);
34816386Sjp151216 			}
34826386Sjp151216 		}
34834520Snw141292 	}
34844520Snw141292 
34854520Snw141292 out:
34864864Sbaban 	if (vm != NULL)
34874520Snw141292 		(void) sqlite_finalize(vm, NULL);
34884520Snw141292 	return (retcode);
34894520Snw141292 }
34904520Snw141292 
34915696Snw141292 static
34925696Snw141292 idmap_retcode
34934520Snw141292 lookup_cache_name2sid(sqlite *cache, const char *name, const char *domain,
34945696Snw141292 	char **canonname, char **sidprefix, idmap_rid_t *rid, int *type)
34955696Snw141292 {
34965696Snw141292 	char		*end, *lower_name;
34974520Snw141292 	char		*sql = NULL;
34984520Snw141292 	const char	**values;
34994520Snw141292 	sqlite_vm	*vm = NULL;
35004520Snw141292 	int		ncol;
35014520Snw141292 	time_t		curtime;
35024520Snw141292 	idmap_retcode	retcode = IDMAP_SUCCESS;
35034520Snw141292 
35044520Snw141292 	/* Get current time */
35054520Snw141292 	errno = 0;
35064520Snw141292 	if ((curtime = time(NULL)) == (time_t)-1) {
35075696Snw141292 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
35085696Snw141292 		    strerror(errno));
35094520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
35104520Snw141292 		goto out;
35114520Snw141292 	}
35124520Snw141292 
35134520Snw141292 	/* SQL to lookup the cache */
35145696Snw141292 	if ((lower_name = tolower_u8(name)) == NULL)
35155696Snw141292 		lower_name = (char *)name;
35165696Snw141292 	sql = sqlite_mprintf("SELECT sidprefix, rid, type, canon_name "
35175696Snw141292 	    "FROM name_cache WHERE name = %Q AND domain = %Q AND "
35185696Snw141292 	    "(expiration = 0 OR expiration ISNULL OR "
35195696Snw141292 	    "expiration > %d);", lower_name, domain, curtime);
35205696Snw141292 	if (lower_name != name)
35215696Snw141292 		free(lower_name);
35224520Snw141292 	if (sql == NULL) {
35234520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
35244520Snw141292 		retcode = IDMAP_ERR_MEMORY;
35254520Snw141292 		goto out;
35264520Snw141292 	}
35275696Snw141292 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 4, &values);
35284520Snw141292 	sqlite_freemem(sql);
35294520Snw141292 
35304520Snw141292 	if (retcode == IDMAP_SUCCESS) {
35314864Sbaban 		if (type != NULL) {
35324520Snw141292 			if (values[2] == NULL) {
35334520Snw141292 				retcode = IDMAP_ERR_CACHE;
35344520Snw141292 				goto out;
35354520Snw141292 			}
35364520Snw141292 			*type = strtol(values[2], &end, 10);
35374520Snw141292 		}
35384520Snw141292 
35395731Sbaban 		if (values[0] == NULL || values[1] == NULL) {
35405731Sbaban 			retcode = IDMAP_ERR_CACHE;
35415731Sbaban 			goto out;
35425731Sbaban 		}
35435731Sbaban 
35445696Snw141292 		if (canonname != NULL) {
35455696Snw141292 			assert(values[3] != NULL);
35465696Snw141292 			if ((*canonname = strdup(values[3])) == NULL) {
35475696Snw141292 				idmapdlog(LOG_ERR, "Out of memory");
35485696Snw141292 				retcode = IDMAP_ERR_MEMORY;
35495696Snw141292 				goto out;
35505696Snw141292 			}
35515696Snw141292 		}
35525696Snw141292 
35534520Snw141292 		if ((*sidprefix = strdup(values[0])) == NULL) {
35544520Snw141292 			idmapdlog(LOG_ERR, "Out of memory");
35554520Snw141292 			retcode = IDMAP_ERR_MEMORY;
35565731Sbaban 			if (canonname != NULL) {
35575731Sbaban 				free(*canonname);
35585731Sbaban 				*canonname = NULL;
35595731Sbaban 			}
35604520Snw141292 			goto out;
35614520Snw141292 		}
35624520Snw141292 		*rid = strtoul(values[1], &end, 10);
35634520Snw141292 	}
35644520Snw141292 
35654520Snw141292 out:
35664864Sbaban 	if (vm != NULL)
35674520Snw141292 		(void) sqlite_finalize(vm, NULL);
35684520Snw141292 	return (retcode);
35694520Snw141292 }
35704520Snw141292 
35715696Snw141292 static
35725696Snw141292 idmap_retcode
35735731Sbaban ad_lookup_by_winname(lookup_state_t *state,
35745731Sbaban 		const char *name, const char *domain, int eunixtype,
35756386Sjp151216 		char **dn, char **attr, char **value, char **canonname,
35766386Sjp151216 		char **sidprefix, idmap_rid_t *rid, int *wintype,
35776386Sjp151216 		char **unixname)
35785696Snw141292 {
35794520Snw141292 	int			retries = 0;
35804520Snw141292 	idmap_query_state_t	*qs = NULL;
35814520Snw141292 	idmap_retcode		rc, retcode;
35824520Snw141292 
35834520Snw141292 retry:
35845731Sbaban 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, 1, &qs);
35855731Sbaban 	if (retcode != IDMAP_SUCCESS) {
35865968Snw141292 		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
35875968Snw141292 			goto retry;
35886097Snw141292 		degrade_svc(1, "failed to create request for AD lookup "
35895968Snw141292 		    "by winname");
35905731Sbaban 		return (retcode);
35914520Snw141292 	}
35924520Snw141292 
35935317Sjp151216 	restore_svc();
35945317Sjp151216 
35955731Sbaban 	if (state != NULL)
35965731Sbaban 		idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
35975731Sbaban 		    state->ad_unixgroup_attr);
35985731Sbaban 
35995731Sbaban 	retcode = idmap_name2sid_batch_add1(qs, name, domain, eunixtype,
36006386Sjp151216 	    dn, attr, value, canonname, sidprefix, rid, wintype, unixname, &rc);
36015731Sbaban 
36025731Sbaban 	if (retcode != IDMAP_SUCCESS)
36034884Sjp151216 		idmap_lookup_release_batch(&qs);
36044520Snw141292 	else
36055968Snw141292 		retcode = idmap_lookup_batch_end(&qs);
36064520Snw141292 
36074520Snw141292 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
36084520Snw141292 		goto retry;
36095317Sjp151216 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
36106097Snw141292 		degrade_svc(1, "some AD lookups timed out repeatedly");
36114520Snw141292 
36124520Snw141292 	if (retcode != IDMAP_SUCCESS) {
36135731Sbaban 		idmapdlog(LOG_NOTICE, "AD lookup by winname failed");
36144520Snw141292 		return (retcode);
36155731Sbaban 	}
36165731Sbaban 	return (rc);
36174520Snw141292 }
36184520Snw141292 
36195696Snw141292 idmap_retcode
36204520Snw141292 lookup_name2sid(sqlite *cache, const char *name, const char *domain,
36215696Snw141292 		int *is_wuser, char **canonname, char **sidprefix,
36226616Sdm199847 		idmap_rid_t *rid, idmap_mapping *req, int local_only)
36235696Snw141292 {
36244520Snw141292 	int		type;
36254520Snw141292 	idmap_retcode	retcode;
36264520Snw141292 
36275696Snw141292 	*sidprefix = NULL;
36285731Sbaban 	if (canonname != NULL)
36295731Sbaban 		*canonname = NULL;
36305731Sbaban 
36315731Sbaban 	/* Lookup well-known SIDs table */
36325696Snw141292 	retcode = lookup_wksids_name2sid(name, canonname, sidprefix, rid,
36335696Snw141292 	    &type);
36344864Sbaban 	if (retcode == IDMAP_SUCCESS) {
36355731Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
36364864Sbaban 		goto out;
36374864Sbaban 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
36384864Sbaban 		return (retcode);
36394864Sbaban 	}
36404864Sbaban 
36415731Sbaban 	/* Lookup cache */
36425696Snw141292 	retcode = lookup_cache_name2sid(cache, name, domain, canonname,
36435696Snw141292 	    sidprefix, rid, &type);
36445731Sbaban 	if (retcode == IDMAP_SUCCESS) {
36455731Sbaban 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
36465731Sbaban 		goto out;
36475731Sbaban 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
36484520Snw141292 		return (retcode);
36494520Snw141292 	}
36504520Snw141292 
36516616Sdm199847 	/*
36526616Sdm199847 	 * The caller may be using this function to determine if this
36536616Sdm199847 	 * request needs to be marked for AD lookup or not
36546616Sdm199847 	 * (i.e. _IDMAP_F_LOOKUP_AD) and therefore may not want this
36556616Sdm199847 	 * function to AD lookup now.
36566616Sdm199847 	 */
36576616Sdm199847 	if (local_only)
36586616Sdm199847 		return (retcode);
36596616Sdm199847 
36605731Sbaban 	/* Lookup AD */
36615731Sbaban 	retcode = ad_lookup_by_winname(NULL, name, domain, _IDMAP_T_UNDEF,
36626386Sjp151216 	    NULL, NULL, NULL, canonname, sidprefix, rid, &type, NULL);
36635731Sbaban 	if (retcode != IDMAP_SUCCESS)
36645731Sbaban 		return (retcode);
36655731Sbaban 
36664864Sbaban out:
36674520Snw141292 	/*
36684520Snw141292 	 * Entry found (cache or Windows lookup)
36695696Snw141292 	 * is_wuser is both input as well as output parameter
36704520Snw141292 	 */
36715731Sbaban 	if (*is_wuser == 1 && type != _IDMAP_T_USER)
36725731Sbaban 		retcode = IDMAP_ERR_NOTUSER;
36735731Sbaban 	else if (*is_wuser == 0 && type != _IDMAP_T_GROUP)
36745731Sbaban 		retcode = IDMAP_ERR_NOTGROUP;
36755731Sbaban 	else if (*is_wuser == -1) {
36764520Snw141292 		/* Caller wants to know if its user or group */
36774520Snw141292 		if (type == _IDMAP_T_USER)
36785696Snw141292 			*is_wuser = 1;
36794520Snw141292 		else if (type == _IDMAP_T_GROUP)
36805696Snw141292 			*is_wuser = 0;
36815731Sbaban 		else
36825731Sbaban 			retcode = IDMAP_ERR_SID;
36835731Sbaban 	}
36845731Sbaban 
36855731Sbaban 	if (retcode != IDMAP_SUCCESS) {
36865731Sbaban 		free(*sidprefix);
36875731Sbaban 		*sidprefix = NULL;
36885731Sbaban 		if (canonname != NULL) {
36895731Sbaban 			free(*canonname);
36905731Sbaban 			*canonname = NULL;
36915696Snw141292 		}
36924520Snw141292 	}
36934520Snw141292 	return (retcode);
36944520Snw141292 }
36954520Snw141292 
36965696Snw141292 static
36975696Snw141292 idmap_retcode
36986616Sdm199847 name_based_mapping_pid2sid(lookup_state_t *state, const char *unixname,
36995696Snw141292 		int is_user, idmap_mapping *req, idmap_id_res *res)
37005696Snw141292 {
37014520Snw141292 	const char	*winname, *windomain;
37025696Snw141292 	char		*canonname;
37034520Snw141292 	char		*sql = NULL, *errmsg = NULL;
37044520Snw141292 	idmap_retcode	retcode;
37054520Snw141292 	char		*end;
37064520Snw141292 	const char	**values;
37074520Snw141292 	sqlite_vm	*vm = NULL;
37086386Sjp151216 	int		ncol, r;
37095731Sbaban 	int		is_wuser;
37104520Snw141292 	const char	*me = "name_based_mapping_pid2sid";
37116386Sjp151216 	int 		non_wild_match = FALSE;
37126386Sjp151216 	idmap_namerule	*rule = &res->info.how.idmap_how_u.rule;
37136386Sjp151216 	int direction;
37145731Sbaban 
37155731Sbaban 	assert(unixname != NULL); /* We have unixname */
37165731Sbaban 	assert(req->id2name == NULL); /* We don't have winname */
37175731Sbaban 	assert(res->id.idmap_id_u.sid.prefix == NULL); /* No SID either */
37184520Snw141292 
37194520Snw141292 	sql = sqlite_mprintf(
37206386Sjp151216 	    "SELECT winname_display, windomain, w2u_order, "
37216386Sjp151216 	    "is_wuser, unixname, is_nt4 "
37226386Sjp151216 	    "FROM namerules WHERE "
37235696Snw141292 	    "u2w_order > 0 AND is_user = %d AND "
37245696Snw141292 	    "(unixname = %Q OR unixname = '*') "
37255696Snw141292 	    "ORDER BY u2w_order ASC;", is_user, unixname);
37264520Snw141292 	if (sql == NULL) {
37274520Snw141292 		idmapdlog(LOG_ERR, "Out of memory");
37284520Snw141292 		retcode = IDMAP_ERR_MEMORY;
37294520Snw141292 		goto out;
37304520Snw141292 	}
37314520Snw141292 
37326616Sdm199847 	if (sqlite_compile(state->db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
37334520Snw141292 		retcode = IDMAP_ERR_INTERNAL;
37345696Snw141292 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
37355696Snw141292 		    CHECK_NULL(errmsg));
37364520Snw141292 		sqlite_freemem(errmsg);
37374520Snw141292 		goto out;
37384520Snw141292 	}
37394520Snw141292 
37406386Sjp151216 	for (;;) {
37414520Snw141292 		r = sqlite_step(vm, &ncol, &values, NULL);
37424884Sjp151216 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
37434884Sjp151216 		if (r == SQLITE_ROW) {
37446386Sjp151216 			if (ncol < 6) {
37454520Snw141292 				retcode = IDMAP_ERR_INTERNAL;
37464520Snw141292 				goto out;
37474520Snw141292 			}
37484520Snw141292 			if (values[0] == NULL) {
37494520Snw141292 				/* values [1] and [2] can be null */
37504520Snw141292 				retcode = IDMAP_ERR_INTERNAL;
37514520Snw141292 				goto out;
37524520Snw141292 			}
37536386Sjp151216 
37546386Sjp151216 			if (values[2] != NULL)
37556386Sjp151216 				direction =
37566386Sjp151216 				    (strtol(values[2], &end, 10) == 0)?
37576386Sjp151216 				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
37586386Sjp151216 			else
37596386Sjp151216 				direction = IDMAP_DIRECTION_U2W;
37606386Sjp151216 
37614520Snw141292 			if (EMPTY_NAME(values[0])) {
37626386Sjp151216 				idmap_namerule_set(rule, values[1], values[0],
37636386Sjp151216 				    values[4], is_user,
37646386Sjp151216 				    strtol(values[3], &end, 10),
37656386Sjp151216 				    strtol(values[5], &end, 10),
37666386Sjp151216 				    direction);
37674520Snw141292 				retcode = IDMAP_ERR_NOMAPPING;
37684520Snw141292 				goto out;
37694520Snw141292 			}
37705696Snw141292 
37715696Snw141292 			if (values[0][0] == '*') {
37726386Sjp151216 				winname = unixname;
37736386Sjp151216 				if (non_wild_match) {
37745696Snw141292 					/*
37756386Sjp151216 					 * There were non-wildcard rules
37766386Sjp151216 					 * where the Windows identity doesn't
37776386Sjp151216 					 * exist. Return no mapping.
37785696Snw141292 					 */
37795696Snw141292 					retcode = IDMAP_ERR_NOMAPPING;
37805696Snw141292 					goto out;
37815696Snw141292 				}
37825696Snw141292 			} else {
37836386Sjp151216 				/* Save first non-wild match rule */
37846386Sjp151216 				if (!non_wild_match) {
37856386Sjp151216 					idmap_namerule_set(rule, values[1],
37866386Sjp151216 					    values[0], values[4],
37876386Sjp151216 					    is_user,
37886386Sjp151216 					    strtol(values[3], &end, 10),
37896386Sjp151216 					    strtol(values[5], &end, 10),
37906386Sjp151216 					    direction);
37916386Sjp151216 					non_wild_match = TRUE;
37926386Sjp151216 				}
37935696Snw141292 				winname = values[0];
37945696Snw141292 			}
37956386Sjp151216 			is_wuser = res->id.idtype == IDMAP_USID ? 1
37966386Sjp151216 			    : res->id.idtype == IDMAP_GSID ? 0
37976386Sjp151216 			    : -1;
37984864Sbaban 			if (values[1] != NULL)
37994520Snw141292 				windomain = values[1];
38006616Sdm199847 			else if (state->defdom != NULL)
38016616Sdm199847 				windomain = state->defdom;
38024520Snw141292 			else {
38035696Snw141292 				idmapdlog(LOG_ERR, "%s: no domain", me);
38044520Snw141292 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
38054520Snw141292 				goto out;
38064520Snw141292 			}
38075696Snw141292 
38086616Sdm199847 			retcode = lookup_name2sid(state->cache,
38096616Sdm199847 			    winname, windomain,
38105696Snw141292 			    &is_wuser, &canonname,
38115696Snw141292 			    &res->id.idmap_id_u.sid.prefix,
38126616Sdm199847 			    &res->id.idmap_id_u.sid.rid, req, 0);
38135731Sbaban 
38144520Snw141292 			if (retcode == IDMAP_ERR_NOTFOUND) {
38155696Snw141292 				continue;
38164520Snw141292 			}
38174520Snw141292 			goto out;
38186386Sjp151216 
38194520Snw141292 		} else if (r == SQLITE_DONE) {
38206386Sjp151216 			/*
38216386Sjp151216 			 * If there were non-wildcard rules where
38226386Sjp151216 			 * Windows identity doesn't exist
38236386Sjp151216 			 * return no mapping.
38246386Sjp151216 			 */
38256386Sjp151216 			if (non_wild_match)
38266386Sjp151216 				retcode = IDMAP_ERR_NOMAPPING;
38276386Sjp151216 			else
38286386Sjp151216 				retcode = IDMAP_ERR_NOTFOUND;
38294520Snw141292 			goto out;
38304520Snw141292 		} else {
38314520Snw141292 			(void) sqlite_finalize(vm, &errmsg);
38324520Snw141292 			vm = NULL;
38335696Snw141292 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
38345696Snw141292 			    CHECK_NULL(errmsg));
38354520Snw141292 			sqlite_freemem(errmsg);
38364520Snw141292 			retcode = IDMAP_ERR_INTERNAL;
38374520Snw141292 			goto out;
38384520Snw141292 		}
38394520Snw141292 	}
38404520Snw141292 
38414520Snw141292 out:
38424864Sbaban 	if (sql != NULL)
38434520Snw141292 		sqlite_freemem(sql);
38446386Sjp151216 	res->info.how.map_type = IDMAP_MAP_TYPE_RULE_BASED;
38454520Snw141292 	if (retcode == IDMAP_SUCCESS) {
38465696Snw141292 		res->id.idtype = is_wuser ? IDMAP_USID : IDMAP_GSID;
38475696Snw141292 
38484864Sbaban 		if (values[2] != NULL)
38494520Snw141292 			res->direction =
38504644Sbaban 			    (strtol(values[2], &end, 10) == 0)?
38514644Sbaban 			    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
38524520Snw141292 		else
38534644Sbaban 			res->direction = IDMAP_DIRECTION_U2W;
38545064Sdm199847 
38555696Snw141292 		req->id2name = canonname;
38565064Sdm199847 		if (req->id2name != NULL) {
38576616Sdm199847 			req->id2domain = strdup(windomain);
38586616Sdm199847 			if (req->id2domain == NULL)
38596616Sdm199847 				retcode = IDMAP_ERR_MEMORY;
38604520Snw141292 		}
38616616Sdm199847 	}
38626616Sdm199847 
38636616Sdm199847 	if (retcode == IDMAP_SUCCESS) {
38646386Sjp151216 		idmap_namerule_set(rule, values[1], values[0], values[4],
38656386Sjp151216 		    is_user, strtol(values[3], &end, 10),
38666386Sjp151216 		    strtol(values[5], &end, 10),
38676386Sjp151216 		    rule->direction);
38686386Sjp151216 		res->info.src = IDMAP_MAP_SRC_NEW;
38694520Snw141292 	}
38704864Sbaban 	if (vm != NULL)
38714520Snw141292 		(void) sqlite_finalize(vm, NULL);
38724520Snw141292 	return (retcode);
38734520Snw141292 }
38744520Snw141292 
38755696Snw141292 /*
38765696Snw141292  * Convention when processing unix2win requests:
38775696Snw141292  *
38785696Snw141292  * Unix identity:
38795696Snw141292  * req->id1name =
38805696Snw141292  *              unixname if given otherwise unixname found will be placed
38815696Snw141292  *              here.
38825696Snw141292  * req->id1domain =
38835696Snw141292  *              NOT USED
38845696Snw141292  * req->id1.idtype =
38855696Snw141292  *              Given type (IDMAP_UID or IDMAP_GID)
38865696Snw141292  * req->id1..[uid or gid] =
38875696Snw141292  *              UID/GID if given otherwise UID/GID found will be placed here.
38885696Snw141292  *
38895696Snw141292  * Windows identity:
38905696Snw141292  * req->id2name =
38915696Snw141292  *              winname found will be placed here.
38925696Snw141292  * req->id2domain =
38935696Snw141292  *              windomain found will be placed here.
38945696Snw141292  * res->id.idtype =
38955696Snw141292  *              Target type initialized from req->id2.idtype. If
38965696Snw141292  *              it is IDMAP_SID then actual type (IDMAP_USID/GSID) found
38975696Snw141292  *              will be placed here.
38985696Snw141292  * req->id..sid.[prefix, rid] =
38995696Snw141292  *              SID found will be placed here.
39005696Snw141292  *
39015696Snw141292  * Others:
39025696Snw141292  * res->retcode =
39035696Snw141292  *              Return status for this request will be placed here.
39045696Snw141292  * res->direction =
39055696Snw141292  *              Direction found will be placed here. Direction
39065696Snw141292  *              meaning whether the resultant mapping is valid
39075696Snw141292  *              only from unix2win or bi-directional.
39085696Snw141292  * req->direction =
39095696Snw141292  *              INTERNAL USE. Used by idmapd to set various
39105696Snw141292  *              flags (_IDMAP_F_xxxx) to aid in processing
39115696Snw141292  *              of the request.
39125696Snw141292  * req->id2.idtype =
39135696Snw141292  *              INTERNAL USE. Initially this is the requested target
39145696Snw141292  *              type and is used to initialize res->id.idtype.
39155696Snw141292  *              ad_lookup_batch() uses this field temporarily to store
39165696Snw141292  *              sid_type obtained by the batched AD lookups and after
39175696Snw141292  *              use resets it to IDMAP_NONE to prevent xdr from
39185696Snw141292  *              mis-interpreting the contents of req->id2.
39195696Snw141292  * req->id2..[uid or gid or sid] =
39205696Snw141292  *              NOT USED
39215696Snw141292  */
39225696Snw141292 
39235696Snw141292 /*
39245696Snw141292  * This function does the following:
39255696Snw141292  * 1. Lookup well-known SIDs table.
39265696Snw141292  * 2. Lookup cache.
39275696Snw141292  * 3. Check if the client does not want new mapping to be allocated
39285696Snw141292  *    in which case this pass is the final pass.
39295731Sbaban  * 4. Set AD/NLDAP lookup flags if it determines that the next stage needs
39305731Sbaban  *    to do AD/NLDAP lookup.
39315696Snw141292  */
39324520Snw141292 idmap_retcode
39336616Sdm199847 pid2sid_first_pass(lookup_state_t *state, idmap_mapping *req,
39346616Sdm199847 		idmap_id_res *res, int is_user, int getname)
39355696Snw141292 {
39365731Sbaban 	idmap_retcode	retcode;
39375731Sbaban 	bool_t		gen_localsid_on_err = FALSE;
39385731Sbaban 
39395731Sbaban 	/* Initialize result */
39404520Snw141292 	res->id.idtype = req->id2.idtype;
39415731Sbaban 	res->direction = IDMAP_DIRECTION_UNDEF;
39425731Sbaban 
39435731Sbaban 	if (req->id2.idmap_id_u.sid.prefix != NULL) {
39445731Sbaban 		/* sanitize sidprefix */
39455731Sbaban 		free(req->id2.idmap_id_u.sid.prefix);
39465731Sbaban 		req->id2.idmap_id_u.sid.prefix = NULL;
39475731Sbaban 	}
39485731Sbaban 
39496386Sjp151216 	/* Find pid */
39506386Sjp151216 	if (req->id1.idmap_id_u.uid == SENTINEL_PID) {
39516386Sjp151216 		if (ns_lookup_byname(req->id1name, NULL, &req->id1)
39526386Sjp151216 		    != IDMAP_SUCCESS) {
39536386Sjp151216 			retcode = IDMAP_ERR_NOMAPPING;
39546386Sjp151216 			goto out;
39556386Sjp151216 		}
39566386Sjp151216 	}
39576386Sjp151216 
39585731Sbaban 	/* Lookup well-known SIDs table */
39594520Snw141292 	retcode = lookup_wksids_pid2sid(req, res, is_user);
39604520Snw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
39614520Snw141292 		goto out;
39624520Snw141292 
39635731Sbaban 	/* Lookup cache */
39646616Sdm199847 	retcode = lookup_cache_pid2sid(state->cache, req, res, is_user,
39656616Sdm199847 	    getname);
39664520Snw141292 	if (retcode != IDMAP_ERR_NOTFOUND)
39674520Snw141292 		goto out;
39684520Snw141292 
39694520Snw141292 	/* Ephemeral ids cannot be allocated during pid2sid */
39704520Snw141292 	if (IS_EPHEMERAL(req->id1.idmap_id_u.uid)) {
39714864Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
39724520Snw141292 		goto out;
39734520Snw141292 	}
39744520Snw141292 
39756386Sjp151216 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req)) {
39766386Sjp151216 		retcode = IDMAP_ERR_NONEGENERATED;
39776386Sjp151216 		goto out;
39786386Sjp151216 	}
39796386Sjp151216 
39806386Sjp151216 	if (AVOID_NAMESERVICE(req)) {
39815731Sbaban 		gen_localsid_on_err = TRUE;
39824864Sbaban 		retcode = IDMAP_ERR_NOMAPPING;
39834520Snw141292 		goto out;
39844520Snw141292 	}
39854520Snw141292 
39865731Sbaban 	/* Set flags for the next stage */
39875731Sbaban 	if (AD_MODE(req->id1.idtype, state)) {
39885731Sbaban 		/*
39895731Sbaban 		 * If AD-based name mapping is enabled then the next stage
39905731Sbaban 		 * will need to lookup AD using unixname to get the
39915731Sbaban 		 * corresponding winname.
39925731Sbaban 		 */
39935731Sbaban 		if (req->id1name == NULL) {
39945731Sbaban 			/* Get unixname if only pid is given. */
39955731Sbaban 			retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid,
39965731Sbaban 			    is_user, &req->id1name);
39976616Sdm199847 			if (retcode != IDMAP_SUCCESS) {
39986616Sdm199847 				gen_localsid_on_err = TRUE;
39995731Sbaban 				goto out;
40006616Sdm199847 			}
40014520Snw141292 		}
40025731Sbaban 		req->direction |= _IDMAP_F_LOOKUP_AD;
40035731Sbaban 		state->ad_nqueries++;
40045731Sbaban 	} else if (NLDAP_OR_MIXED_MODE(req->id1.idtype, state)) {
40055731Sbaban 		/*
40065731Sbaban 		 * If native LDAP or mixed mode is enabled for name mapping
40075731Sbaban 		 * then the next stage will need to lookup native LDAP using
40085731Sbaban 		 * unixname/pid to get the corresponding winname.
40095731Sbaban 		 */
40105731Sbaban 		req->direction |= _IDMAP_F_LOOKUP_NLDAP;
40115731Sbaban 		state->nldap_nqueries++;
40125731Sbaban 	}
40135731Sbaban 
40145731Sbaban 	/*
40155731Sbaban 	 * Failed to find non-expired entry in cache. Set the flag to
40165731Sbaban 	 * indicate that we are not done yet.
40175731Sbaban 	 */
40185731Sbaban 	state->pid2sid_done = FALSE;
40195731Sbaban 	req->direction |= _IDMAP_F_NOTDONE;
40205731Sbaban 	retcode = IDMAP_SUCCESS;
40215731Sbaban 
40225731Sbaban out:
40235731Sbaban 	res->retcode = idmap_stat4prot(retcode);
40245731Sbaban 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
40255731Sbaban 		if (gen_localsid_on_err == TRUE)
40266386Sjp151216 			(void) generate_localsid(req, res, is_user, TRUE);
40275731Sbaban 	return (retcode);
40285731Sbaban }
40295731Sbaban 
40305731Sbaban idmap_retcode
40316616Sdm199847 pid2sid_second_pass(lookup_state_t *state, idmap_mapping *req,
40326616Sdm199847 	idmap_id_res *res, int is_user)
40335731Sbaban {
40345731Sbaban 	bool_t		gen_localsid_on_err = TRUE;
40355731Sbaban 	idmap_retcode	retcode = IDMAP_SUCCESS;
40365731Sbaban 
40375731Sbaban 	/* Check if second pass is needed */
40385731Sbaban 	if (ARE_WE_DONE(req->direction))
40395731Sbaban 		return (res->retcode);
40405731Sbaban 
40415731Sbaban 	/* Get status from previous pass */
40425731Sbaban 	retcode = res->retcode;
40435731Sbaban 	if (retcode != IDMAP_SUCCESS)
40445731Sbaban 		goto out;
40455731Sbaban 
40465731Sbaban 	/*
40475731Sbaban 	 * If directory-based name mapping is enabled then the winname
40485731Sbaban 	 * may already have been retrieved from the AD object (AD-mode)
40496616Sdm199847 	 * or from native LDAP object (nldap-mode or mixed-mode).
40506616Sdm199847 	 * Note that if we have winname but no SID then it's an error
40516616Sdm199847 	 * because this implies that the Native LDAP entry contains
40526616Sdm199847 	 * winname which does not exist and it's better that we return
40536616Sdm199847 	 * an error instead of doing rule-based mapping so that the user
40546616Sdm199847 	 * can detect the issue and take appropriate action.
40555731Sbaban 	 */
40566616Sdm199847 	if (req->id2name != NULL) {
40576616Sdm199847 		/* Return notfound if we've winname but no SID. */
40586616Sdm199847 		if (res->id.idmap_id_u.sid.prefix == NULL) {
40596616Sdm199847 			retcode = IDMAP_ERR_NOTFOUND;
40606616Sdm199847 			goto out;
40616616Sdm199847 		}
40625731Sbaban 		if (AD_MODE(req->id1.idtype, state))
40635731Sbaban 			res->direction = IDMAP_DIRECTION_BI;
40645731Sbaban 		else if (NLDAP_MODE(req->id1.idtype, state))
40655731Sbaban 			res->direction = IDMAP_DIRECTION_BI;
40665731Sbaban 		else if (MIXED_MODE(req->id1.idtype, state))
40675731Sbaban 			res->direction = IDMAP_DIRECTION_W2U;
40685731Sbaban 		goto out;
40696616Sdm199847 	} else if (res->id.idmap_id_u.sid.prefix != NULL) {
40706616Sdm199847 		/*
40716616Sdm199847 		 * We've SID but no winname. This is fine because
40726616Sdm199847 		 * the caller may have only requested SID.
40736616Sdm199847 		 */
40746616Sdm199847 		goto out;
40755731Sbaban 	}
40765731Sbaban 
40776616Sdm199847 	/* Free any mapping info from Directory based mapping */
40786616Sdm199847 	if (res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN)
40796616Sdm199847 		idmap_info_free(&res->info);
40806616Sdm199847 
40815731Sbaban 	if (req->id1name == NULL) {
40825731Sbaban 		/* Get unixname from name service */
40835731Sbaban 		retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid, is_user,
40845731Sbaban 		    &req->id1name);
40855731Sbaban 		if (retcode != IDMAP_SUCCESS)
40865731Sbaban 			goto out;
40875731Sbaban 	} else if (req->id1.idmap_id_u.uid == SENTINEL_PID) {
40885731Sbaban 		/* Get pid from name service */
40895731Sbaban 		retcode = ns_lookup_byname(req->id1name, NULL, &req->id1);
40905731Sbaban 		if (retcode != IDMAP_SUCCESS) {
40915731Sbaban 			gen_localsid_on_err = FALSE;
40925731Sbaban 			goto out;
40934520Snw141292 		}
40944520Snw141292 	}
40954520Snw141292 
40965731Sbaban 	/* Use unixname to evaluate local name-based mapping rules */
40976616Sdm199847 	retcode = name_based_mapping_pid2sid(state, req->id1name, is_user,
40985696Snw141292 	    req, res);
40994520Snw141292 	if (retcode == IDMAP_ERR_NOTFOUND) {
41006386Sjp151216 		retcode = generate_localsid(req, res, is_user, FALSE);
41015731Sbaban 		gen_localsid_on_err = FALSE;
41025731Sbaban 	}
41034520Snw141292 
41044520Snw141292 out:
41055731Sbaban 	res->retcode = idmap_stat4prot(retcode);
41065731Sbaban 	if (res->retcode != IDMAP_SUCCESS) {
41075731Sbaban 		req->direction = _IDMAP_F_DONE;
41086616Sdm199847 		free(req->id2name);
41096616Sdm199847 		req->id2name = NULL;
41106616Sdm199847 		free(req->id2domain);
41116616Sdm199847 		req->id2domain = NULL;
41125731Sbaban 		if (gen_localsid_on_err == TRUE)
41136386Sjp151216 			(void) generate_localsid(req, res, is_user, TRUE);
41146616Sdm199847 		else
41156616Sdm199847 			res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
41164520Snw141292 	}
41175731Sbaban 	if (!ARE_WE_DONE(req->direction))
41184520Snw141292 		state->pid2sid_done = FALSE;
41194520Snw141292 	return (retcode);
41204520Snw141292 }
41214520Snw141292 
41225696Snw141292 static
41235696Snw141292 int
41244644Sbaban copy_mapping_request(idmap_mapping *mapping, idmap_mapping *request)
41254520Snw141292 {
41264644Sbaban 	(void) memset(mapping, 0, sizeof (*mapping));
41274644Sbaban 
41284520Snw141292 	mapping->flag = request->flag;
41295731Sbaban 	mapping->direction = _IDMAP_F_DONE;
41304644Sbaban 	mapping->id2.idtype = request->id2.idtype;
41314520Snw141292 
41324520Snw141292 	mapping->id1.idtype = request->id1.idtype;
41335696Snw141292 	if (IS_REQUEST_SID(*request, 1)) {
41344520Snw141292 		mapping->id1.idmap_id_u.sid.rid =
41354520Snw141292 		    request->id1.idmap_id_u.sid.rid;
41364644Sbaban 		if (!EMPTY_STRING(request->id1.idmap_id_u.sid.prefix)) {
41374520Snw141292 			mapping->id1.idmap_id_u.sid.prefix =
41384520Snw141292 			    strdup(request->id1.idmap_id_u.sid.prefix);
41394644Sbaban 			if (mapping->id1.idmap_id_u.sid.prefix == NULL)
41405064Sdm199847 				goto errout;
41414644Sbaban 		}
41424520Snw141292 	} else {
41434520Snw141292 		mapping->id1.idmap_id_u.uid = request->id1.idmap_id_u.uid;
41444520Snw141292 	}
41454520Snw141292 
41465731Sbaban 	if (!EMPTY_STRING(request->id1domain)) {
41475731Sbaban 		mapping->id1domain = strdup(request->id1domain);
41485731Sbaban 		if (mapping->id1domain == NULL)
41495731Sbaban 			goto errout;
41505731Sbaban 	}
41515731Sbaban 
41525731Sbaban 	if (!EMPTY_STRING(request->id1name)) {
41535731Sbaban 		mapping->id1name = strdup(request->id1name);
41545731Sbaban 		if (mapping->id1name == NULL)
41555731Sbaban 			goto errout;
41565731Sbaban 	}
41574520Snw141292 
41584644Sbaban 	/* We don't need the rest of the request i.e request->id2 */
41594644Sbaban 	return (0);
41604644Sbaban 
41614644Sbaban errout:
41625064Sdm199847 	if (mapping->id1.idmap_id_u.sid.prefix != NULL)
41634644Sbaban 		free(mapping->id1.idmap_id_u.sid.prefix);
41645064Sdm199847 	if (mapping->id1domain != NULL)
41655064Sdm199847 		free(mapping->id1domain);
41665064Sdm199847 	if (mapping->id1name != NULL)
41675064Sdm199847 		free(mapping->id1name);
41684644Sbaban 
41694644Sbaban 	(void) memset(mapping, 0, sizeof (*mapping));
41704644Sbaban 	return (-1);
41714520Snw141292 }
41724520Snw141292 
41734520Snw141292 
41744520Snw141292 idmap_retcode
41754520Snw141292 get_w2u_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
41765696Snw141292 		idmap_mapping *mapping)
41775696Snw141292 {
41784520Snw141292 	idmap_id_res	idres;
41794520Snw141292 	lookup_state_t	state;
41805043Sbaban 	char		*cp;
41814520Snw141292 	idmap_retcode	retcode;
41824520Snw141292 	const char	*winname, *windomain;
41834520Snw141292 
41844520Snw141292 	(void) memset(&idres, 0, sizeof (idres));
41854520Snw141292 	(void) memset(&state, 0, sizeof (state));
41866616Sdm199847 	state.cache = cache;
41876616Sdm199847 	state.db = db;
41884520Snw141292 
41895731Sbaban 	/* Get directory-based name mapping info */
41906616Sdm199847 	retcode = load_cfg_in_state(&state);
41915731Sbaban 	if (retcode != IDMAP_SUCCESS)
41924520Snw141292 		goto out;
41935731Sbaban 
41945731Sbaban 	/*
41955731Sbaban 	 * Copy data from "request" to "mapping". Note that
41965731Sbaban 	 * empty strings are not copied from "request" to
41975731Sbaban 	 * "mapping" and therefore the coresponding strings in
41985731Sbaban 	 * "mapping" will be NULL. This eliminates having to
41995731Sbaban 	 * check for empty strings henceforth.
42005731Sbaban 	 */
42014644Sbaban 	if (copy_mapping_request(mapping, request) < 0) {
42024644Sbaban 		retcode = IDMAP_ERR_MEMORY;
42034644Sbaban 		goto out;
42044644Sbaban 	}
42054520Snw141292 
42065064Sdm199847 	winname = mapping->id1name;
42075064Sdm199847 	windomain = mapping->id1domain;
42084520Snw141292 
42095731Sbaban 	if (winname == NULL && windomain != NULL) {
42105731Sbaban 		retcode = IDMAP_ERR_ARG;
42115731Sbaban 		goto out;
42125731Sbaban 	}
42135731Sbaban 
42145731Sbaban 	/* Need atleast winname or sid to proceed */
42155731Sbaban 	if (winname == NULL && mapping->id1.idmap_id_u.sid.prefix == NULL) {
42164520Snw141292 		retcode = IDMAP_ERR_ARG;
42174520Snw141292 		goto out;
42184520Snw141292 	}
42194520Snw141292 
42205731Sbaban 	/*
42215731Sbaban 	 * If domainname is not given but we have a fully qualified
42225731Sbaban 	 * winname then extract the domainname from the winname,
42235731Sbaban 	 * otherwise use the default_domain from the config
42245731Sbaban 	 */
42255731Sbaban 	if (winname != NULL && windomain == NULL) {
42265064Sdm199847 		retcode = IDMAP_SUCCESS;
42275043Sbaban 		if ((cp = strchr(winname, '@')) != NULL) {
42285043Sbaban 			*cp = '\0';
42295064Sdm199847 			mapping->id1domain = strdup(cp + 1);
42305064Sdm199847 			if (mapping->id1domain == NULL)
42315064Sdm199847 				retcode = IDMAP_ERR_MEMORY;
42325731Sbaban 		} else if (lookup_wksids_name2sid(winname, NULL, NULL, NULL,
42335731Sbaban 		    NULL) != IDMAP_SUCCESS) {
42346950Sbaban 			if (state.defdom == NULL) {
42356950Sbaban 				/*
42366950Sbaban 				 * We have a non-qualified winname which is
42376950Sbaban 				 * neither the name of a well-known SID nor
42386950Sbaban 				 * there is a default domain with which we can
42396950Sbaban 				 * qualify it.
42406950Sbaban 				 */
42416950Sbaban 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
42426950Sbaban 			} else {
42436950Sbaban 				mapping->id1domain = strdup(state.defdom);
42446950Sbaban 				if (mapping->id1domain == NULL)
42456950Sbaban 					retcode = IDMAP_ERR_MEMORY;
42466950Sbaban 			}
42475064Sdm199847 		}
42484520Snw141292 		if (retcode != IDMAP_SUCCESS)
42494520Snw141292 			goto out;
42504520Snw141292 	}
42514520Snw141292 
42525731Sbaban 	/*
42535731Sbaban 	 * First pass looks up the well-known SIDs table and cache
42545731Sbaban 	 * and handles localSIDs
42555731Sbaban 	 */
42564520Snw141292 	state.sid2pid_done = TRUE;
42576616Sdm199847 	retcode = sid2pid_first_pass(&state, mapping, &idres);
42584520Snw141292 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
42594520Snw141292 		goto out;
42604520Snw141292 
42616616Sdm199847 	/* AD lookup */
42625731Sbaban 	if (state.ad_nqueries > 0) {
42636616Sdm199847 		retcode = ad_lookup_one(&state, mapping, &idres);
42645731Sbaban 		if (IDMAP_ERROR(retcode))
42655731Sbaban 			goto out;
42664520Snw141292 	}
42674520Snw141292 
42686616Sdm199847 	/* nldap lookup */
42696616Sdm199847 	if (state.nldap_nqueries > 0) {
42706616Sdm199847 		retcode = nldap_lookup_one(&state, mapping, &idres);
42716616Sdm199847 		if (IDMAP_FATAL_ERROR(retcode))
42725731Sbaban 			goto out;
42735731Sbaban 	}
42745731Sbaban 
42755731Sbaban 	/* Next pass performs name-based mapping and ephemeral mapping. */
42764520Snw141292 	state.sid2pid_done = TRUE;
42776616Sdm199847 	retcode = sid2pid_second_pass(&state, mapping, &idres);
42784520Snw141292 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
42794520Snw141292 		goto out;
42804520Snw141292 
42814520Snw141292 	/* Update cache */
42826616Sdm199847 	(void) update_cache_sid2pid(&state, mapping, &idres);
42834520Snw141292 
42844520Snw141292 out:
42855731Sbaban 	/*
42865731Sbaban 	 * Note that "mapping" is returned to the client. Therefore
42875731Sbaban 	 * copy whatever we have in "idres" to mapping->id2 and
42885731Sbaban 	 * free idres.
42895731Sbaban 	 */
42905731Sbaban 	mapping->direction = idres.direction;
42915731Sbaban 	mapping->id2 = idres.id;
42926386Sjp151216 	if (mapping->flag & IDMAP_REQ_FLG_MAPPING_INFO ||
42936386Sjp151216 	    retcode != IDMAP_SUCCESS)
42946386Sjp151216 		(void) idmap_info_mov(&mapping->info, &idres.info);
42956386Sjp151216 	else
42966386Sjp151216 		idmap_info_free(&idres.info);
42975731Sbaban 	(void) memset(&idres, 0, sizeof (idres));
42985731Sbaban 	if (retcode != IDMAP_SUCCESS)
42994864Sbaban 		mapping->id2.idmap_id_u.uid = UID_NOBODY;
43004520Snw141292 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
43015731Sbaban 	cleanup_lookup_state(&state);
43024520Snw141292 	return (retcode);
43034520Snw141292 }
43044520Snw141292 
43054520Snw141292 idmap_retcode
43064520Snw141292 get_u2w_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
43075696Snw141292 		idmap_mapping *mapping, int is_user)
43085696Snw141292 {
43094520Snw141292 	idmap_id_res	idres;
43104520Snw141292 	lookup_state_t	state;
43114520Snw141292 	idmap_retcode	retcode;
43124520Snw141292 
43134520Snw141292 	/*
43144520Snw141292 	 * In order to re-use the pid2sid code, we convert
43154520Snw141292 	 * our input data into structs that are expected by
43164520Snw141292 	 * pid2sid_first_pass.
43174520Snw141292 	 */
43184520Snw141292 
43194520Snw141292 	(void) memset(&idres, 0, sizeof (idres));
43204520Snw141292 	(void) memset(&state, 0, sizeof (state));
43216616Sdm199847 	state.cache = cache;
43226616Sdm199847 	state.db = db;
43234520Snw141292 
43245731Sbaban 	/* Get directory-based name mapping info */
43256616Sdm199847 	retcode = load_cfg_in_state(&state);
43265731Sbaban 	if (retcode != IDMAP_SUCCESS)
43275731Sbaban 		goto out;
43285731Sbaban 
43295731Sbaban 	/*
43305731Sbaban 	 * Copy data from "request" to "mapping". Note that
43315731Sbaban 	 * empty strings are not copied from "request" to
43325731Sbaban 	 * "mapping" and therefore the coresponding strings in
43335731Sbaban 	 * "mapping" will be NULL. This eliminates having to
43345731Sbaban 	 * check for empty strings henceforth.
43355731Sbaban 	 */
43364644Sbaban 	if (copy_mapping_request(mapping, request) < 0) {
43374644Sbaban 		retcode = IDMAP_ERR_MEMORY;
43384644Sbaban 		goto out;
43394644Sbaban 	}
43404520Snw141292 
43415731Sbaban 	/*
43425731Sbaban 	 * For unix to windows mapping request, we need atleast a
43435731Sbaban 	 * unixname or uid/gid to proceed
43445731Sbaban 	 */
43455731Sbaban 	if (mapping->id1name == NULL &&
43465127Sdm199847 	    mapping->id1.idmap_id_u.uid == SENTINEL_PID) {
43474520Snw141292 		retcode = IDMAP_ERR_ARG;
43484520Snw141292 		goto out;
43494520Snw141292 	}
43504520Snw141292 
43515731Sbaban 	/* First pass looks up cache and well-known SIDs */
43525731Sbaban 	state.pid2sid_done = TRUE;
43536616Sdm199847 	retcode = pid2sid_first_pass(&state, mapping, &idres, is_user, 1);
43545731Sbaban 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
43555731Sbaban 		goto out;
43565731Sbaban 
43576616Sdm199847 	/* nldap lookup */
43585731Sbaban 	if (state.nldap_nqueries > 0) {
43596616Sdm199847 		retcode = nldap_lookup_one(&state, mapping, &idres);
43605731Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
43615731Sbaban 			goto out;
43626616Sdm199847 	}
43636616Sdm199847 
43646616Sdm199847 	/* AD lookup */
43656616Sdm199847 	if (state.ad_nqueries > 0) {
43666616Sdm199847 		retcode = ad_lookup_one(&state, mapping, &idres);
43675731Sbaban 		if (IDMAP_FATAL_ERROR(retcode))
43685731Sbaban 			goto out;
43694520Snw141292 	}
43704520Snw141292 
43715731Sbaban 	/*
43725731Sbaban 	 * Next pass processes the result of the preceding passes/lookups.
43735731Sbaban 	 * It returns if there's nothing more to be done otherwise it
43745731Sbaban 	 * evaluates local name-based mapping rules
43755731Sbaban 	 */
43764520Snw141292 	state.pid2sid_done = TRUE;
43776616Sdm199847 	retcode = pid2sid_second_pass(&state, mapping, &idres, is_user);
43784520Snw141292 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
43794520Snw141292 		goto out;
43804520Snw141292 
43814520Snw141292 	/* Update cache */
43826616Sdm199847 	(void) update_cache_pid2sid(&state, mapping, &idres);
43834520Snw141292 
43844520Snw141292 out:
43855731Sbaban 	/*
43865731Sbaban 	 * Note that "mapping" is returned to the client. Therefore
43875731Sbaban 	 * copy whatever we have in "idres" to mapping->id2 and
43885731Sbaban 	 * free idres.
43895731Sbaban 	 */
43904520Snw141292 	mapping->direction = idres.direction;
43914520Snw141292 	mapping->id2 = idres.id;
43926386Sjp151216 	if (mapping->flag & IDMAP_REQ_FLG_MAPPING_INFO ||
43936386Sjp151216 	    retcode != IDMAP_SUCCESS)
43946386Sjp151216 		(void) idmap_info_mov(&mapping->info, &idres.info);
43956386Sjp151216 	else
43966386Sjp151216 		idmap_info_free(&idres.info);
43974520Snw141292 	(void) memset(&idres, 0, sizeof (idres));
43984520Snw141292 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
43995731Sbaban 	cleanup_lookup_state(&state);
44004520Snw141292 	return (retcode);
44014520Snw141292 }
44025731Sbaban 
44036616Sdm199847 /*ARGSUSED*/
44045731Sbaban static
44055731Sbaban idmap_retcode
44066616Sdm199847 ad_lookup_one(lookup_state_t *state, idmap_mapping *req, idmap_id_res *res)
44075731Sbaban {
44086616Sdm199847 	idmap_mapping_batch	batch;
44096616Sdm199847 	idmap_ids_res		result;
44106616Sdm199847 
44116616Sdm199847 	batch.idmap_mapping_batch_len = 1;
44126616Sdm199847 	batch.idmap_mapping_batch_val = req;
44136616Sdm199847 	result.ids.ids_len = 1;
44146616Sdm199847 	result.ids.ids_val = res;
44156616Sdm199847 	return (ad_lookup_batch(state, &batch, &result));
44165731Sbaban }
4417