dbutils.c revision 11963:061945695ce1
1/*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21/*
22 * Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
23 * Use is subject to license terms.
24 */
25
26/*
27 * Database related utility routines
28 */
29
30#include <stdio.h>
31#include <stdlib.h>
32#include <string.h>
33#include <errno.h>
34#include <sys/types.h>
35#include <sys/stat.h>
36#include <rpc/rpc.h>
37#include <sys/sid.h>
38#include <time.h>
39#include <pwd.h>
40#include <grp.h>
41#include <pthread.h>
42#include <assert.h>
43#include <sys/u8_textprep.h>
44#include <alloca.h>
45
46#include "idmapd.h"
47#include "adutils.h"
48#include "string.h"
49#include "idmap_priv.h"
50#include "schema.h"
51#include "nldaputils.h"
52#include "miscutils.h"
53
54
55static idmap_retcode sql_compile_n_step_once(sqlite *, char *,
56		sqlite_vm **, int *, int, const char ***);
57static idmap_retcode lookup_localsid2pid(idmap_mapping *, idmap_id_res *);
58static idmap_retcode lookup_cache_name2sid(sqlite *, const char *,
59		const char *, char **, char **, idmap_rid_t *, int *);
60
61#define	NELEM(a)	(sizeof (a) / sizeof ((a)[0]))
62
63#define	EMPTY_NAME(name)	(*name == 0 || strcmp(name, "\"\"") == 0)
64
65#define	DO_NOT_ALLOC_NEW_ID_MAPPING(req)\
66		(req->flag & IDMAP_REQ_FLG_NO_NEW_ID_ALLOC)
67
68#define	AVOID_NAMESERVICE(req)\
69		(req->flag & IDMAP_REQ_FLG_NO_NAMESERVICE)
70
71#define	ALLOW_WK_OR_LOCAL_SIDS_ONLY(req)\
72		(req->flag & IDMAP_REQ_FLG_WK_OR_LOCAL_SIDS_ONLY)
73
74typedef enum init_db_option {
75	FAIL_IF_CORRUPT = 0,
76	REMOVE_IF_CORRUPT = 1
77} init_db_option_t;
78
79/*
80 * Thread specific data to hold the database handles so that the
81 * databases are not opened and closed for every request. It also
82 * contains the sqlite busy handler structure.
83 */
84
85struct idmap_busy {
86	const char *name;
87	const int *delays;
88	int delay_size;
89	int total;
90	int sec;
91};
92
93
94typedef struct idmap_tsd {
95	sqlite *db_db;
96	sqlite *cache_db;
97	struct idmap_busy cache_busy;
98	struct idmap_busy db_busy;
99} idmap_tsd_t;
100
101/*
102 * Flags to indicate how local the directory we're consulting is.
103 * If neither is set, it means the directory belongs to a remote forest.
104 */
105#define	DOMAIN_IS_LOCAL	0x01
106#define	FOREST_IS_LOCAL	0x02
107
108static const int cache_delay_table[] =
109		{ 1, 2, 5, 10, 15, 20, 25, 30,  35,  40,
110		50,  50, 60, 70, 80, 90, 100};
111
112static const int db_delay_table[] =
113		{ 5, 10, 15, 20, 30,  40,  55,  70, 100};
114
115
116static pthread_key_t	idmap_tsd_key;
117
118void
119idmap_tsd_destroy(void *key)
120{
121
122	idmap_tsd_t	*tsd = (idmap_tsd_t *)key;
123	if (tsd) {
124		if (tsd->db_db)
125			(void) sqlite_close(tsd->db_db);
126		if (tsd->cache_db)
127			(void) sqlite_close(tsd->cache_db);
128		free(tsd);
129	}
130}
131
132int
133idmap_init_tsd_key(void)
134{
135	return (pthread_key_create(&idmap_tsd_key, idmap_tsd_destroy));
136}
137
138
139
140idmap_tsd_t *
141idmap_get_tsd(void)
142{
143	idmap_tsd_t	*tsd;
144
145	if ((tsd = pthread_getspecific(idmap_tsd_key)) == NULL) {
146		/* No thread specific data so create it */
147		if ((tsd = malloc(sizeof (*tsd))) != NULL) {
148			/* Initialize thread specific data */
149			(void) memset(tsd, 0, sizeof (*tsd));
150			/* save the trhread specific data */
151			if (pthread_setspecific(idmap_tsd_key, tsd) != 0) {
152				/* Can't store key */
153				free(tsd);
154				tsd = NULL;
155			}
156		} else {
157			tsd = NULL;
158		}
159	}
160
161	return (tsd);
162}
163
164/*
165 * A simple wrapper around u8_textprep_str() that returns the Unicode
166 * lower-case version of some string.  The result must be freed.
167 */
168char *
169tolower_u8(const char *s)
170{
171	char *res = NULL;
172	char *outs;
173	size_t inlen, outlen, inbytesleft, outbytesleft;
174	int rc, err;
175
176	/*
177	 * u8_textprep_str() does not allocate memory.  The input and
178	 * output buffers may differ in size (though that would be more
179	 * likely when normalization is done).  We have to loop over it...
180	 *
181	 * To improve the chances that we can avoid looping we add 10
182	 * bytes of output buffer room the first go around.
183	 */
184	inlen = inbytesleft = strlen(s);
185	outlen = outbytesleft = inlen + 10;
186	if ((res = malloc(outlen)) == NULL)
187		return (NULL);
188	outs = res;
189
190	while ((rc = u8_textprep_str((char *)s, &inbytesleft, outs,
191	    &outbytesleft, U8_TEXTPREP_TOLOWER, U8_UNICODE_LATEST, &err)) < 0 &&
192	    err == E2BIG) {
193		if ((res = realloc(res, outlen + inbytesleft)) == NULL)
194			return (NULL);
195		/* adjust input/output buffer pointers */
196		s += (inlen - inbytesleft);
197		outs = res + outlen - outbytesleft;
198		/* adjust outbytesleft and outlen */
199		outlen += inbytesleft;
200		outbytesleft += inbytesleft;
201	}
202
203	if (rc < 0) {
204		free(res);
205		res = NULL;
206		return (NULL);
207	}
208
209	res[outlen - outbytesleft] = '\0';
210
211	return (res);
212}
213
214static int sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
215	const char *while_doing);
216
217
218/*
219 * Initialize 'dbname' using 'sql'
220 */
221static
222int
223init_db_instance(const char *dbname, int version,
224	const char *detect_version_sql, char * const *sql,
225	init_db_option_t opt, int *created, int *upgraded)
226{
227	int rc, curr_version;
228	int tries = 1;
229	int prio = LOG_NOTICE;
230	sqlite *db = NULL;
231	char *errmsg = NULL;
232
233	*created = 0;
234	*upgraded = 0;
235
236	if (opt == REMOVE_IF_CORRUPT)
237		tries = 3;
238
239rinse_repeat:
240	if (tries == 0) {
241		idmapdlog(LOG_ERR, "Failed to initialize db %s", dbname);
242		return (-1);
243	}
244	if (tries-- == 1)
245		/* Last try, log errors */
246		prio = LOG_ERR;
247
248	db = sqlite_open(dbname, 0600, &errmsg);
249	if (db == NULL) {
250		idmapdlog(prio, "Error creating database %s (%s)",
251		    dbname, CHECK_NULL(errmsg));
252		sqlite_freemem(errmsg);
253		if (opt == REMOVE_IF_CORRUPT)
254			(void) unlink(dbname);
255		goto rinse_repeat;
256	}
257
258	sqlite_busy_timeout(db, 3000);
259
260	/* Detect current version of schema in the db, if any */
261	curr_version = 0;
262	if (detect_version_sql != NULL) {
263		char *end, **results;
264		int nrow;
265
266#ifdef	IDMAPD_DEBUG
267		(void) fprintf(stderr, "Schema version detection SQL: %s\n",
268		    detect_version_sql);
269#endif	/* IDMAPD_DEBUG */
270		rc = sqlite_get_table(db, detect_version_sql, &results,
271		    &nrow, NULL, &errmsg);
272		if (rc != SQLITE_OK) {
273			idmapdlog(prio,
274			    "Error detecting schema version of db %s (%s)",
275			    dbname, errmsg);
276			sqlite_freemem(errmsg);
277			sqlite_free_table(results);
278			sqlite_close(db);
279			return (-1);
280		}
281		if (nrow != 1) {
282			idmapdlog(prio,
283			    "Error detecting schema version of db %s", dbname);
284			sqlite_close(db);
285			sqlite_free_table(results);
286			return (-1);
287		}
288		curr_version = strtol(results[1], &end, 10);
289		sqlite_free_table(results);
290	}
291
292	if (curr_version < 0) {
293		if (opt == REMOVE_IF_CORRUPT)
294			(void) unlink(dbname);
295		goto rinse_repeat;
296	}
297
298	if (curr_version == version)
299		goto done;
300
301	/* Install or upgrade schema */
302#ifdef	IDMAPD_DEBUG
303	(void) fprintf(stderr, "Schema init/upgrade SQL: %s\n",
304	    sql[curr_version]);
305#endif	/* IDMAPD_DEBUG */
306	rc = sql_exec_tran_no_cb(db, sql[curr_version], dbname,
307	    (curr_version == 0) ? "installing schema" : "upgrading schema");
308	if (rc != 0) {
309		idmapdlog(prio, "Error %s schema for db %s", dbname,
310		    (curr_version == 0) ? "installing schema" :
311		    "upgrading schema");
312		if (opt == REMOVE_IF_CORRUPT)
313			(void) unlink(dbname);
314		goto rinse_repeat;
315	}
316
317	*upgraded = (curr_version > 0);
318	*created = (curr_version == 0);
319
320done:
321	(void) sqlite_close(db);
322	return (0);
323}
324
325
326/*
327 * This is the SQLite database busy handler that retries the SQL
328 * operation until it is successful.
329 */
330int
331/* LINTED E_FUNC_ARG_UNUSED */
332idmap_sqlite_busy_handler(void *arg, const char *table_name, int count)
333{
334	struct idmap_busy	*busy = arg;
335	int			delay;
336	struct timespec		rqtp;
337
338	if (count == 1)  {
339		busy->total = 0;
340		busy->sec = 2;
341	}
342	if (busy->total > 1000 * busy->sec) {
343		idmapdlog(LOG_DEBUG,
344		    "Thread %d waited %d sec for the %s database",
345		    pthread_self(), busy->sec, busy->name);
346		busy->sec++;
347	}
348
349	if (count <= busy->delay_size) {
350		delay = busy->delays[count-1];
351	} else {
352		delay = busy->delays[busy->delay_size - 1];
353	}
354	busy->total += delay;
355	rqtp.tv_sec = 0;
356	rqtp.tv_nsec = delay * (NANOSEC / MILLISEC);
357	(void) nanosleep(&rqtp, NULL);
358	return (1);
359}
360
361
362/*
363 * Get the database handle
364 */
365idmap_retcode
366get_db_handle(sqlite **db)
367{
368	char		*errmsg;
369	idmap_tsd_t	*tsd;
370
371	/*
372	 * Retrieve the db handle from thread-specific storage
373	 * If none exists, open and store in thread-specific storage.
374	 */
375	if ((tsd = idmap_get_tsd()) == NULL) {
376		idmapdlog(LOG_ERR,
377		    "Error getting thread specific data for %s", IDMAP_DBNAME);
378		return (IDMAP_ERR_MEMORY);
379	}
380
381	if (tsd->db_db == NULL) {
382		tsd->db_db = sqlite_open(IDMAP_DBNAME, 0, &errmsg);
383		if (tsd->db_db == NULL) {
384			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
385			    IDMAP_DBNAME, CHECK_NULL(errmsg));
386			sqlite_freemem(errmsg);
387			return (IDMAP_ERR_DB);
388		}
389
390		tsd->db_busy.name = IDMAP_DBNAME;
391		tsd->db_busy.delays = db_delay_table;
392		tsd->db_busy.delay_size = sizeof (db_delay_table) /
393		    sizeof (int);
394		sqlite_busy_handler(tsd->db_db, idmap_sqlite_busy_handler,
395		    &tsd->db_busy);
396	}
397	*db = tsd->db_db;
398	return (IDMAP_SUCCESS);
399}
400
401/*
402 * Get the cache handle
403 */
404idmap_retcode
405get_cache_handle(sqlite **cache)
406{
407	char		*errmsg;
408	idmap_tsd_t	*tsd;
409
410	/*
411	 * Retrieve the db handle from thread-specific storage
412	 * If none exists, open and store in thread-specific storage.
413	 */
414	if ((tsd = idmap_get_tsd()) == NULL) {
415		idmapdlog(LOG_ERR, "Error getting thread specific data for %s",
416		    IDMAP_DBNAME);
417		return (IDMAP_ERR_MEMORY);
418	}
419
420	if (tsd->cache_db == NULL) {
421		tsd->cache_db = sqlite_open(IDMAP_CACHENAME, 0, &errmsg);
422		if (tsd->cache_db == NULL) {
423			idmapdlog(LOG_ERR, "Error opening database %s (%s)",
424			    IDMAP_CACHENAME, CHECK_NULL(errmsg));
425			sqlite_freemem(errmsg);
426			return (IDMAP_ERR_DB);
427		}
428
429		tsd->cache_busy.name = IDMAP_CACHENAME;
430		tsd->cache_busy.delays = cache_delay_table;
431		tsd->cache_busy.delay_size = sizeof (cache_delay_table) /
432		    sizeof (int);
433		sqlite_busy_handler(tsd->cache_db, idmap_sqlite_busy_handler,
434		    &tsd->cache_busy);
435	}
436	*cache = tsd->cache_db;
437	return (IDMAP_SUCCESS);
438}
439
440/*
441 * Initialize cache and db
442 */
443int
444init_dbs()
445{
446	char *sql[4];
447	int created, upgraded;
448
449	/* name-based mappings; probably OK to blow away in a pinch(?) */
450	sql[0] = DB_INSTALL_SQL;
451	sql[1] = DB_UPGRADE_FROM_v1_SQL;
452	sql[2] = NULL;
453
454	if (init_db_instance(IDMAP_DBNAME, DB_VERSION, DB_VERSION_SQL, sql,
455	    FAIL_IF_CORRUPT, &created, &upgraded) < 0)
456		return (-1);
457
458	/* mappings, name/SID lookup cache + ephemeral IDs; OK to blow away */
459	sql[0] = CACHE_INSTALL_SQL;
460	sql[1] = CACHE_UPGRADE_FROM_v1_SQL;
461	sql[2] = CACHE_UPGRADE_FROM_v2_SQL;
462	sql[3] = NULL;
463
464	if (init_db_instance(IDMAP_CACHENAME, CACHE_VERSION, CACHE_VERSION_SQL,
465	    sql, REMOVE_IF_CORRUPT, &created, &upgraded) < 0)
466		return (-1);
467
468	_idmapdstate.new_eph_db = (created || upgraded) ? 1 : 0;
469
470	return (0);
471}
472
473/*
474 * Finalize databases
475 */
476void
477fini_dbs()
478{
479}
480
481/*
482 * This table is a listing of status codes that will be returned to the
483 * client when a SQL command fails with the corresponding error message.
484 */
485static msg_table_t sqlmsgtable[] = {
486	{IDMAP_ERR_U2W_NAMERULE_CONFLICT,
487	"columns unixname, is_user, u2w_order are not unique"},
488	{IDMAP_ERR_W2U_NAMERULE_CONFLICT,
489	"columns winname, windomain, is_user, is_wuser, w2u_order are not"
490	" unique"},
491	{IDMAP_ERR_W2U_NAMERULE_CONFLICT, "Conflicting w2u namerules"},
492	{-1, NULL}
493};
494
495/*
496 * idmapd's version of string2stat to map SQLite messages to
497 * status codes
498 */
499idmap_retcode
500idmapd_string2stat(const char *msg)
501{
502	int i;
503	for (i = 0; sqlmsgtable[i].msg; i++) {
504		if (strcasecmp(sqlmsgtable[i].msg, msg) == 0)
505			return (sqlmsgtable[i].retcode);
506	}
507	return (IDMAP_ERR_OTHER);
508}
509
510/*
511 * Executes some SQL in a transaction.
512 *
513 * Returns 0 on success, -1 if it failed but the rollback succeeded, -2
514 * if the rollback failed.
515 */
516static
517int
518sql_exec_tran_no_cb(sqlite *db, char *sql, const char *dbname,
519	const char *while_doing)
520{
521	char		*errmsg = NULL;
522	int		rc;
523
524	rc = sqlite_exec(db, "BEGIN TRANSACTION;", NULL, NULL, &errmsg);
525	if (rc != SQLITE_OK) {
526		idmapdlog(LOG_ERR, "Begin transaction failed (%s) "
527		    "while %s (%s)", errmsg, while_doing, dbname);
528		sqlite_freemem(errmsg);
529		return (-1);
530	}
531
532	rc = sqlite_exec(db, sql, NULL, NULL, &errmsg);
533	if (rc != SQLITE_OK) {
534		idmapdlog(LOG_ERR, "Database error (%s) while %s (%s)", errmsg,
535		    while_doing, dbname);
536		sqlite_freemem(errmsg);
537		errmsg = NULL;
538		goto rollback;
539	}
540
541	rc = sqlite_exec(db, "COMMIT TRANSACTION", NULL, NULL, &errmsg);
542	if (rc == SQLITE_OK) {
543		sqlite_freemem(errmsg);
544		return (0);
545	}
546
547	idmapdlog(LOG_ERR, "Database commit error (%s) while s (%s)",
548	    errmsg, while_doing, dbname);
549	sqlite_freemem(errmsg);
550	errmsg = NULL;
551
552rollback:
553	rc = sqlite_exec(db, "ROLLBACK TRANSACTION", NULL, NULL, &errmsg);
554	if (rc != SQLITE_OK) {
555		idmapdlog(LOG_ERR, "Rollback failed (%s) while %s (%s)",
556		    errmsg, while_doing, dbname);
557		sqlite_freemem(errmsg);
558		return (-2);
559	}
560	sqlite_freemem(errmsg);
561
562	return (-1);
563}
564
565/*
566 * Execute the given SQL statment without using any callbacks
567 */
568idmap_retcode
569sql_exec_no_cb(sqlite *db, const char *dbname, char *sql)
570{
571	char		*errmsg = NULL;
572	int		r;
573	idmap_retcode	retcode;
574
575	r = sqlite_exec(db, sql, NULL, NULL, &errmsg);
576	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
577
578	if (r != SQLITE_OK) {
579		idmapdlog(LOG_ERR, "Database error on %s while executing %s "
580		    "(%s)", dbname, sql, CHECK_NULL(errmsg));
581		retcode = idmapd_string2stat(errmsg);
582		if (errmsg != NULL)
583			sqlite_freemem(errmsg);
584		return (retcode);
585	}
586
587	return (IDMAP_SUCCESS);
588}
589
590/*
591 * Generate expression that can be used in WHERE statements.
592 * Examples:
593 * <prefix> <col>      <op> <value>   <suffix>
594 * ""       "unixuser" "="  "foo" "AND"
595 */
596idmap_retcode
597gen_sql_expr_from_rule(idmap_namerule *rule, char **out)
598{
599	char	*s_windomain = NULL, *s_winname = NULL;
600	char	*s_unixname = NULL;
601	char	*dir;
602	char	*lower_winname;
603	int	retcode = IDMAP_SUCCESS;
604
605	if (out == NULL)
606		return (IDMAP_ERR_ARG);
607
608
609	if (!EMPTY_STRING(rule->windomain)) {
610		s_windomain =  sqlite_mprintf("AND windomain = %Q ",
611		    rule->windomain);
612		if (s_windomain == NULL) {
613			retcode = IDMAP_ERR_MEMORY;
614			goto out;
615		}
616	}
617
618	if (!EMPTY_STRING(rule->winname)) {
619		if ((lower_winname = tolower_u8(rule->winname)) == NULL)
620			lower_winname = rule->winname;
621		s_winname = sqlite_mprintf(
622		    "AND winname = %Q AND is_wuser = %d ",
623		    lower_winname, rule->is_wuser ? 1 : 0);
624		if (lower_winname != rule->winname)
625			free(lower_winname);
626		if (s_winname == NULL) {
627			retcode = IDMAP_ERR_MEMORY;
628			goto out;
629		}
630	}
631
632	if (!EMPTY_STRING(rule->unixname)) {
633		s_unixname = sqlite_mprintf(
634		    "AND unixname = %Q AND is_user = %d ",
635		    rule->unixname, rule->is_user ? 1 : 0);
636		if (s_unixname == NULL) {
637			retcode = IDMAP_ERR_MEMORY;
638			goto out;
639		}
640	}
641
642	switch (rule->direction) {
643	case IDMAP_DIRECTION_BI:
644		dir = "AND w2u_order > 0 AND u2w_order > 0";
645		break;
646	case IDMAP_DIRECTION_W2U:
647		dir = "AND w2u_order > 0"
648		    " AND (u2w_order = 0 OR u2w_order ISNULL)";
649		break;
650	case IDMAP_DIRECTION_U2W:
651		dir = "AND u2w_order > 0"
652		    " AND (w2u_order = 0 OR w2u_order ISNULL)";
653		break;
654	default:
655		dir = "";
656		break;
657	}
658
659	*out = sqlite_mprintf("%s %s %s %s",
660	    s_windomain ? s_windomain : "",
661	    s_winname ? s_winname : "",
662	    s_unixname ? s_unixname : "",
663	    dir);
664
665	if (*out == NULL) {
666		retcode = IDMAP_ERR_MEMORY;
667		idmapdlog(LOG_ERR, "Out of memory");
668		goto out;
669	}
670
671out:
672	if (s_windomain != NULL)
673		sqlite_freemem(s_windomain);
674	if (s_winname != NULL)
675		sqlite_freemem(s_winname);
676	if (s_unixname != NULL)
677		sqlite_freemem(s_unixname);
678
679	return (retcode);
680}
681
682
683
684/*
685 * Generate and execute SQL statement for LIST RPC calls
686 */
687idmap_retcode
688process_list_svc_sql(sqlite *db, const char *dbname, char *sql, uint64_t limit,
689		int flag, list_svc_cb cb, void *result)
690{
691	list_cb_data_t	cb_data;
692	char		*errmsg = NULL;
693	int		r;
694	idmap_retcode	retcode = IDMAP_ERR_INTERNAL;
695
696	(void) memset(&cb_data, 0, sizeof (cb_data));
697	cb_data.result = result;
698	cb_data.limit = limit;
699	cb_data.flag = flag;
700
701
702	r = sqlite_exec(db, sql, cb, &cb_data, &errmsg);
703	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
704	switch (r) {
705	case SQLITE_OK:
706		retcode = IDMAP_SUCCESS;
707		break;
708
709	default:
710		retcode = IDMAP_ERR_INTERNAL;
711		idmapdlog(LOG_ERR, "Database error on %s while executing "
712		    "%s (%s)", dbname, sql, CHECK_NULL(errmsg));
713		break;
714	}
715	if (errmsg != NULL)
716		sqlite_freemem(errmsg);
717	return (retcode);
718}
719
720/*
721 * This routine is called by callbacks that process the results of
722 * LIST RPC calls to validate data and to allocate memory for
723 * the result array.
724 */
725idmap_retcode
726validate_list_cb_data(list_cb_data_t *cb_data, int argc, char **argv,
727		int ncol, uchar_t **list, size_t valsize)
728{
729	size_t	nsize;
730	void	*tmplist;
731
732	if (cb_data->limit > 0 && cb_data->next == cb_data->limit)
733		return (IDMAP_NEXT);
734
735	if (argc < ncol || argv == NULL) {
736		idmapdlog(LOG_ERR, "Invalid data");
737		return (IDMAP_ERR_INTERNAL);
738	}
739
740	/* alloc in bulk to reduce number of reallocs */
741	if (cb_data->next >= cb_data->len) {
742		nsize = (cb_data->len + SIZE_INCR) * valsize;
743		tmplist = realloc(*list, nsize);
744		if (tmplist == NULL) {
745			idmapdlog(LOG_ERR, "Out of memory");
746			return (IDMAP_ERR_MEMORY);
747		}
748		*list = tmplist;
749		(void) memset(*list + (cb_data->len * valsize), 0,
750		    SIZE_INCR * valsize);
751		cb_data->len += SIZE_INCR;
752	}
753	return (IDMAP_SUCCESS);
754}
755
756static
757idmap_retcode
758get_namerule_order(char *winname, char *windomain, char *unixname,
759	int direction, int is_diagonal, int *w2u_order, int *u2w_order)
760{
761	*w2u_order = 0;
762	*u2w_order = 0;
763
764	/*
765	 * Windows to UNIX lookup order:
766	 *  1. winname@domain (or winname) to ""
767	 *  2. winname@domain (or winname) to unixname
768	 *  3. winname@* to ""
769	 *  4. winname@* to unixname
770	 *  5. *@domain (or *) to *
771	 *  6. *@domain (or *) to ""
772	 *  7. *@domain (or *) to unixname
773	 *  8. *@* to *
774	 *  9. *@* to ""
775	 * 10. *@* to unixname
776	 *
777	 * winname is a special case of winname@domain when domain is the
778	 * default domain. Similarly * is a special case of *@domain when
779	 * domain is the default domain.
780	 *
781	 * Note that "" has priority over specific names because "" inhibits
782	 * mappings and traditionally deny rules always had higher priority.
783	 */
784	if (direction != IDMAP_DIRECTION_U2W) {
785		/* bi-directional or from windows to unix */
786		if (winname == NULL)
787			return (IDMAP_ERR_W2U_NAMERULE);
788		else if (unixname == NULL)
789			return (IDMAP_ERR_W2U_NAMERULE);
790		else if (EMPTY_NAME(winname))
791			return (IDMAP_ERR_W2U_NAMERULE);
792		else if (*winname == '*' && windomain && *windomain == '*') {
793			if (*unixname == '*')
794				*w2u_order = 8;
795			else if (EMPTY_NAME(unixname))
796				*w2u_order = 9;
797			else /* unixname == name */
798				*w2u_order = 10;
799		} else if (*winname == '*') {
800			if (*unixname == '*')
801				*w2u_order = 5;
802			else if (EMPTY_NAME(unixname))
803				*w2u_order = 6;
804			else /* name */
805				*w2u_order = 7;
806		} else if (windomain != NULL && *windomain == '*') {
807			/* winname == name */
808			if (*unixname == '*')
809				return (IDMAP_ERR_W2U_NAMERULE);
810			else if (EMPTY_NAME(unixname))
811				*w2u_order = 3;
812			else /* name */
813				*w2u_order = 4;
814		} else  {
815			/* winname == name && windomain == null or name */
816			if (*unixname == '*')
817				return (IDMAP_ERR_W2U_NAMERULE);
818			else if (EMPTY_NAME(unixname))
819				*w2u_order = 1;
820			else /* name */
821				*w2u_order = 2;
822		}
823
824	}
825
826	/*
827	 * 1. unixname to "", non-diagonal
828	 * 2. unixname to winname@domain (or winname), non-diagonal
829	 * 3. unixname to "", diagonal
830	 * 4. unixname to winname@domain (or winname), diagonal
831	 * 5. * to *@domain (or *), non-diagonal
832	 * 5. * to *@domain (or *), diagonal
833	 * 7. * to ""
834	 * 8. * to winname@domain (or winname)
835	 * 9. * to "", non-diagonal
836	 * 10. * to winname@domain (or winname), diagonal
837	 */
838	if (direction != IDMAP_DIRECTION_W2U) {
839		int diagonal = is_diagonal ? 1 : 0;
840
841		/* bi-directional or from unix to windows */
842		if (unixname == NULL || EMPTY_NAME(unixname))
843			return (IDMAP_ERR_U2W_NAMERULE);
844		else if (winname == NULL)
845			return (IDMAP_ERR_U2W_NAMERULE);
846		else if (windomain != NULL && *windomain == '*')
847			return (IDMAP_ERR_U2W_NAMERULE);
848		else if (*unixname == '*') {
849			if (*winname == '*')
850				*u2w_order = 5 + diagonal;
851			else if (EMPTY_NAME(winname))
852				*u2w_order = 7 + 2 * diagonal;
853			else
854				*u2w_order = 8 + 2 * diagonal;
855		} else {
856			if (*winname == '*')
857				return (IDMAP_ERR_U2W_NAMERULE);
858			else if (EMPTY_NAME(winname))
859				*u2w_order = 1 + 2 * diagonal;
860			else
861				*u2w_order = 2 + 2 * diagonal;
862		}
863	}
864	return (IDMAP_SUCCESS);
865}
866
867/*
868 * Generate and execute SQL statement to add name-based mapping rule
869 */
870idmap_retcode
871add_namerule(sqlite *db, idmap_namerule *rule)
872{
873	char		*sql = NULL;
874	idmap_stat	retcode;
875	char		*dom = NULL;
876	char		*name;
877	int		w2u_order, u2w_order;
878	char		w2ubuf[11], u2wbuf[11];
879	char		*canonname = NULL;
880	char		*canondomain = NULL;
881
882	retcode = get_namerule_order(rule->winname, rule->windomain,
883	    rule->unixname, rule->direction,
884	    rule->is_user == rule->is_wuser ? 0 : 1, &w2u_order, &u2w_order);
885	if (retcode != IDMAP_SUCCESS)
886		goto out;
887
888	if (w2u_order)
889		(void) snprintf(w2ubuf, sizeof (w2ubuf), "%d", w2u_order);
890	if (u2w_order)
891		(void) snprintf(u2wbuf, sizeof (u2wbuf), "%d", u2w_order);
892
893	/*
894	 * For the triggers on namerules table to work correctly:
895	 * 1) Use NULL instead of 0 for w2u_order and u2w_order
896	 * 2) Use "" instead of NULL for "no domain"
897	 */
898
899	name = rule->winname;
900	dom = rule->windomain;
901
902	RDLOCK_CONFIG();
903	if (lookup_wksids_name2sid(name, dom,
904	    &canonname, &canondomain,
905	    NULL, NULL, NULL) == IDMAP_SUCCESS) {
906		name = canonname;
907		dom = canondomain;
908	} else if (EMPTY_STRING(dom)) {
909		if (_idmapdstate.cfg->pgcfg.default_domain)
910			dom = _idmapdstate.cfg->pgcfg.default_domain;
911		else
912			dom = "";
913	}
914	sql = sqlite_mprintf("INSERT into namerules "
915	    "(is_user, is_wuser, windomain, winname_display, is_nt4, "
916	    "unixname, w2u_order, u2w_order) "
917	    "VALUES(%d, %d, %Q, %Q, %d, %Q, %q, %q);",
918	    rule->is_user ? 1 : 0, rule->is_wuser ? 1 : 0, dom,
919	    name, rule->is_nt4 ? 1 : 0, rule->unixname,
920	    w2u_order ? w2ubuf : NULL, u2w_order ? u2wbuf : NULL);
921	UNLOCK_CONFIG();
922
923	if (sql == NULL) {
924		retcode = IDMAP_ERR_INTERNAL;
925		idmapdlog(LOG_ERR, "Out of memory");
926		goto out;
927	}
928
929	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, sql);
930
931	if (retcode == IDMAP_ERR_OTHER)
932		retcode = IDMAP_ERR_CFG;
933
934out:
935	free(canonname);
936	free(canondomain);
937	if (sql != NULL)
938		sqlite_freemem(sql);
939	return (retcode);
940}
941
942/*
943 * Flush name-based mapping rules
944 */
945idmap_retcode
946flush_namerules(sqlite *db)
947{
948	idmap_stat	retcode;
949
950	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, "DELETE FROM namerules;");
951
952	return (retcode);
953}
954
955/*
956 * Generate and execute SQL statement to remove a name-based mapping rule
957 */
958idmap_retcode
959rm_namerule(sqlite *db, idmap_namerule *rule)
960{
961	char		*sql = NULL;
962	idmap_stat	retcode;
963	char		*expr = NULL;
964
965	if (rule->direction < 0 && EMPTY_STRING(rule->windomain) &&
966	    EMPTY_STRING(rule->winname) && EMPTY_STRING(rule->unixname))
967		return (IDMAP_SUCCESS);
968
969	retcode = gen_sql_expr_from_rule(rule, &expr);
970	if (retcode != IDMAP_SUCCESS)
971		goto out;
972
973	sql = sqlite_mprintf("DELETE FROM namerules WHERE 1 %s;", expr);
974
975	if (sql == NULL) {
976		retcode = IDMAP_ERR_INTERNAL;
977		idmapdlog(LOG_ERR, "Out of memory");
978		goto out;
979	}
980
981
982	retcode = sql_exec_no_cb(db, IDMAP_DBNAME, sql);
983
984out:
985	if (expr != NULL)
986		sqlite_freemem(expr);
987	if (sql != NULL)
988		sqlite_freemem(sql);
989	return (retcode);
990}
991
992/*
993 * Compile the given SQL query and step just once.
994 *
995 * Input:
996 * db  - db handle
997 * sql - SQL statement
998 *
999 * Output:
1000 * vm     -  virtual SQL machine
1001 * ncol   - number of columns in the result
1002 * values - column values
1003 *
1004 * Return values:
1005 * IDMAP_SUCCESS
1006 * IDMAP_ERR_NOTFOUND
1007 * IDMAP_ERR_INTERNAL
1008 */
1009
1010static
1011idmap_retcode
1012sql_compile_n_step_once(sqlite *db, char *sql, sqlite_vm **vm, int *ncol,
1013		int reqcol, const char ***values)
1014{
1015	char		*errmsg = NULL;
1016	int		r;
1017
1018	if ((r = sqlite_compile(db, sql, NULL, vm, &errmsg)) != SQLITE_OK) {
1019		idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
1020		    CHECK_NULL(errmsg));
1021		sqlite_freemem(errmsg);
1022		return (IDMAP_ERR_INTERNAL);
1023	}
1024
1025	r = sqlite_step(*vm, ncol, values, NULL);
1026	assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
1027
1028	if (r == SQLITE_ROW) {
1029		if (ncol != NULL && *ncol < reqcol) {
1030			(void) sqlite_finalize(*vm, NULL);
1031			*vm = NULL;
1032			return (IDMAP_ERR_INTERNAL);
1033		}
1034		/* Caller will call finalize after using the results */
1035		return (IDMAP_SUCCESS);
1036	} else if (r == SQLITE_DONE) {
1037		(void) sqlite_finalize(*vm, NULL);
1038		*vm = NULL;
1039		return (IDMAP_ERR_NOTFOUND);
1040	}
1041
1042	(void) sqlite_finalize(*vm, &errmsg);
1043	*vm = NULL;
1044	idmapdlog(LOG_ERR, "Database error during %s (%s)", sql,
1045	    CHECK_NULL(errmsg));
1046	sqlite_freemem(errmsg);
1047	return (IDMAP_ERR_INTERNAL);
1048}
1049
1050/*
1051 * Load config in the state.
1052 *
1053 * nm_siduid and nm_sidgid fields:
1054 * state->nm_siduid represents mode used by sid2uid and uid2sid
1055 * requests for directory-based name mappings. Similarly,
1056 * state->nm_sidgid represents mode used by sid2gid and gid2sid
1057 * requests.
1058 *
1059 * sid2uid/uid2sid:
1060 * none       -> directory_based_mapping != DIRECTORY_MAPPING_NAME
1061 * AD-mode    -> !nldap_winname_attr && ad_unixuser_attr
1062 * nldap-mode -> nldap_winname_attr && !ad_unixuser_attr
1063 * mixed-mode -> nldap_winname_attr && ad_unixuser_attr
1064 *
1065 * sid2gid/gid2sid:
1066 * none       -> directory_based_mapping != DIRECTORY_MAPPING_NAME
1067 * AD-mode    -> !nldap_winname_attr && ad_unixgroup_attr
1068 * nldap-mode -> nldap_winname_attr && !ad_unixgroup_attr
1069 * mixed-mode -> nldap_winname_attr && ad_unixgroup_attr
1070 */
1071idmap_retcode
1072load_cfg_in_state(lookup_state_t *state)
1073{
1074	state->nm_siduid = IDMAP_NM_NONE;
1075	state->nm_sidgid = IDMAP_NM_NONE;
1076	RDLOCK_CONFIG();
1077
1078	state->eph_map_unres_sids = 0;
1079	if (_idmapdstate.cfg->pgcfg.eph_map_unres_sids)
1080		state->eph_map_unres_sids = 1;
1081
1082	state->directory_based_mapping =
1083	    _idmapdstate.cfg->pgcfg.directory_based_mapping;
1084
1085	if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
1086		state->defdom =
1087		    strdup(_idmapdstate.cfg->pgcfg.default_domain);
1088		if (state->defdom == NULL) {
1089			UNLOCK_CONFIG();
1090			return (IDMAP_ERR_MEMORY);
1091		}
1092	} else {
1093		UNLOCK_CONFIG();
1094		return (IDMAP_SUCCESS);
1095	}
1096
1097	if (_idmapdstate.cfg->pgcfg.directory_based_mapping !=
1098	    DIRECTORY_MAPPING_NAME) {
1099		UNLOCK_CONFIG();
1100		return (IDMAP_SUCCESS);
1101	}
1102
1103	if (_idmapdstate.cfg->pgcfg.nldap_winname_attr != NULL) {
1104		state->nm_siduid =
1105		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
1106		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
1107		state->nm_sidgid =
1108		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
1109		    ? IDMAP_NM_MIXED : IDMAP_NM_NLDAP;
1110	} else {
1111		state->nm_siduid =
1112		    (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL)
1113		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
1114		state->nm_sidgid =
1115		    (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL)
1116		    ? IDMAP_NM_AD : IDMAP_NM_NONE;
1117	}
1118	if (_idmapdstate.cfg->pgcfg.ad_unixuser_attr != NULL) {
1119		state->ad_unixuser_attr =
1120		    strdup(_idmapdstate.cfg->pgcfg.ad_unixuser_attr);
1121		if (state->ad_unixuser_attr == NULL) {
1122			UNLOCK_CONFIG();
1123			return (IDMAP_ERR_MEMORY);
1124		}
1125	}
1126	if (_idmapdstate.cfg->pgcfg.ad_unixgroup_attr != NULL) {
1127		state->ad_unixgroup_attr =
1128		    strdup(_idmapdstate.cfg->pgcfg.ad_unixgroup_attr);
1129		if (state->ad_unixgroup_attr == NULL) {
1130			UNLOCK_CONFIG();
1131			return (IDMAP_ERR_MEMORY);
1132		}
1133	}
1134	if (_idmapdstate.cfg->pgcfg.nldap_winname_attr != NULL) {
1135		state->nldap_winname_attr =
1136		    strdup(_idmapdstate.cfg->pgcfg.nldap_winname_attr);
1137		if (state->nldap_winname_attr == NULL) {
1138			UNLOCK_CONFIG();
1139			return (IDMAP_ERR_MEMORY);
1140		}
1141	}
1142	UNLOCK_CONFIG();
1143	return (IDMAP_SUCCESS);
1144}
1145
1146/*
1147 * Set the rule with specified values.
1148 * All the strings are copied.
1149 */
1150static void
1151idmap_namerule_set(idmap_namerule *rule, const char *windomain,
1152		const char *winname, const char *unixname, boolean_t is_user,
1153		boolean_t is_wuser, boolean_t is_nt4, int direction)
1154{
1155	/*
1156	 * Only update if they differ because we have to free
1157	 * and duplicate the strings
1158	 */
1159	if (rule->windomain == NULL || windomain == NULL ||
1160	    strcmp(rule->windomain, windomain) != 0) {
1161		if (rule->windomain != NULL) {
1162			free(rule->windomain);
1163			rule->windomain = NULL;
1164		}
1165		if (windomain != NULL)
1166			rule->windomain = strdup(windomain);
1167	}
1168
1169	if (rule->winname == NULL || winname == NULL ||
1170	    strcmp(rule->winname, winname) != 0) {
1171		if (rule->winname != NULL) {
1172			free(rule->winname);
1173			rule->winname = NULL;
1174		}
1175		if (winname != NULL)
1176			rule->winname = strdup(winname);
1177	}
1178
1179	if (rule->unixname == NULL || unixname == NULL ||
1180	    strcmp(rule->unixname, unixname) != 0) {
1181		if (rule->unixname != NULL) {
1182			free(rule->unixname);
1183			rule->unixname = NULL;
1184		}
1185		if (unixname != NULL)
1186			rule->unixname = strdup(unixname);
1187	}
1188
1189	rule->is_user = is_user;
1190	rule->is_wuser = is_wuser;
1191	rule->is_nt4 = is_nt4;
1192	rule->direction = direction;
1193}
1194
1195/*
1196 * Lookup well-known SIDs table either by winname or by SID.
1197 *
1198 * If the given winname or SID is a well-known SID then we set is_wksid
1199 * variable and then proceed to see if the SID has a hard mapping to
1200 * a particular UID/GID (Ex: Creator Owner/Creator Group mapped to
1201 * fixed ephemeral ids). The direction flag indicates whether we have
1202 * a mapping; UNDEF indicates that we do not.
1203 *
1204 * If we find a mapping then we return success, except for the
1205 * special case of IDMAP_SENTINEL_PID which indicates an inhibited mapping.
1206 *
1207 * If we find a matching entry, but no mapping, we supply SID, name, and type
1208 * information and return "not found".  Higher layers will probably
1209 * do ephemeral mapping.
1210 *
1211 * If we do not find a match, we return "not found" and leave the question
1212 * to higher layers.
1213 */
1214static
1215idmap_retcode
1216lookup_wksids_sid2pid(idmap_mapping *req, idmap_id_res *res, int *is_wksid)
1217{
1218	const wksids_table_t *wksid;
1219
1220	*is_wksid = 0;
1221
1222	assert(req->id1.idmap_id_u.sid.prefix != NULL ||
1223	    req->id1name != NULL);
1224
1225	if (req->id1.idmap_id_u.sid.prefix != NULL) {
1226		wksid = find_wksid_by_sid(req->id1.idmap_id_u.sid.prefix,
1227		    req->id1.idmap_id_u.sid.rid, res->id.idtype);
1228	} else {
1229		wksid = find_wksid_by_name(req->id1name, req->id1domain,
1230		    res->id.idtype);
1231	}
1232	if (wksid == NULL)
1233		return (IDMAP_ERR_NOTFOUND);
1234
1235	/* Found matching entry. */
1236
1237	/* Fill in name if it was not already there. */
1238	if (req->id1name == NULL) {
1239		req->id1name = strdup(wksid->winname);
1240		if (req->id1name == NULL)
1241			return (IDMAP_ERR_MEMORY);
1242	}
1243
1244	/* Fill in SID if it was not already there */
1245	if (req->id1.idmap_id_u.sid.prefix == NULL) {
1246		if (wksid->sidprefix != NULL) {
1247			req->id1.idmap_id_u.sid.prefix =
1248			    strdup(wksid->sidprefix);
1249		} else {
1250			RDLOCK_CONFIG();
1251			req->id1.idmap_id_u.sid.prefix =
1252			    strdup(_idmapdstate.cfg->pgcfg.machine_sid);
1253			UNLOCK_CONFIG();
1254		}
1255		if (req->id1.idmap_id_u.sid.prefix == NULL)
1256			return (IDMAP_ERR_MEMORY);
1257		req->id1.idmap_id_u.sid.rid = wksid->rid;
1258	}
1259
1260	/* Fill in the canonical domain if not already there */
1261	if (req->id1domain == NULL) {
1262		const char *dom;
1263
1264		RDLOCK_CONFIG();
1265		if (wksid->domain != NULL)
1266			dom = wksid->domain;
1267		else
1268			dom = _idmapdstate.hostname;
1269		req->id1domain = strdup(dom);
1270		UNLOCK_CONFIG();
1271		if (req->id1domain == NULL)
1272			return (IDMAP_ERR_MEMORY);
1273	}
1274
1275	*is_wksid = 1;
1276	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
1277
1278	req->id1.idtype = wksid->is_wuser ? IDMAP_USID : IDMAP_GSID;
1279
1280	if (res->id.idtype == IDMAP_POSIXID) {
1281		res->id.idtype = wksid->is_wuser ? IDMAP_UID : IDMAP_GID;
1282	}
1283
1284	if (wksid->direction == IDMAP_DIRECTION_UNDEF) {
1285		/*
1286		 * We don't have a mapping
1287		 * (But note that we may have supplied SID, name, or type
1288		 * information.)
1289		 */
1290		return (IDMAP_ERR_NOTFOUND);
1291	}
1292
1293	/*
1294	 * We have an explicit mapping.
1295	 */
1296	if (wksid->pid == IDMAP_SENTINEL_PID) {
1297		/*
1298		 * ... which is that mapping is inhibited.
1299		 */
1300		return (IDMAP_ERR_NOMAPPING);
1301	}
1302
1303	switch (res->id.idtype) {
1304	case IDMAP_UID:
1305		res->id.idmap_id_u.uid = wksid->pid;
1306		break;
1307	case IDMAP_GID:
1308		res->id.idmap_id_u.gid = wksid->pid;
1309		break;
1310	default:
1311		/* IDMAP_POSIXID is eliminated above */
1312		return (IDMAP_ERR_NOTSUPPORTED);
1313	}
1314
1315	res->direction = wksid->direction;
1316	res->info.how.map_type = IDMAP_MAP_TYPE_KNOWN_SID;
1317	res->info.src = IDMAP_MAP_SRC_HARD_CODED;
1318	return (IDMAP_SUCCESS);
1319}
1320
1321
1322/*
1323 * Look for an entry mapping a PID to a SID.
1324 *
1325 * Note that direction=UNDEF entries do not specify a mapping,
1326 * and that IDMAP_SENTINEL_PID entries represent either an inhibited
1327 * mapping or an ephemeral mapping.  We don't handle either here;
1328 * they are filtered out by find_wksid_by_pid.
1329 */
1330static
1331idmap_retcode
1332lookup_wksids_pid2sid(idmap_mapping *req, idmap_id_res *res, int is_user)
1333{
1334	const wksids_table_t *wksid;
1335
1336	wksid = find_wksid_by_pid(req->id1.idmap_id_u.uid, is_user);
1337	if (wksid == NULL)
1338		return (IDMAP_ERR_NOTFOUND);
1339
1340	if (res->id.idtype == IDMAP_SID) {
1341		res->id.idtype = wksid->is_wuser ? IDMAP_USID : IDMAP_GSID;
1342	}
1343	res->id.idmap_id_u.sid.rid = wksid->rid;
1344
1345	if (wksid->sidprefix != NULL) {
1346		res->id.idmap_id_u.sid.prefix =
1347		    strdup(wksid->sidprefix);
1348	} else {
1349		RDLOCK_CONFIG();
1350		res->id.idmap_id_u.sid.prefix =
1351		    strdup(_idmapdstate.cfg->pgcfg.machine_sid);
1352		UNLOCK_CONFIG();
1353	}
1354
1355	if (res->id.idmap_id_u.sid.prefix == NULL) {
1356		idmapdlog(LOG_ERR, "Out of memory");
1357		return (IDMAP_ERR_MEMORY);
1358	}
1359
1360	/* Fill in name if it was not already there. */
1361	if (req->id2name == NULL) {
1362		req->id2name = strdup(wksid->winname);
1363		if (req->id2name == NULL)
1364			return (IDMAP_ERR_MEMORY);
1365	}
1366
1367	/* Fill in the canonical domain if not already there */
1368	if (req->id2domain == NULL) {
1369		const char *dom;
1370
1371		RDLOCK_CONFIG();
1372		if (wksid->domain != NULL)
1373			dom = wksid->domain;
1374		else
1375			dom = _idmapdstate.hostname;
1376		req->id2domain = strdup(dom);
1377		UNLOCK_CONFIG();
1378		if (req->id2domain == NULL)
1379			return (IDMAP_ERR_MEMORY);
1380	}
1381
1382	res->direction = wksid->direction;
1383	res->info.how.map_type = IDMAP_MAP_TYPE_KNOWN_SID;
1384	res->info.src = IDMAP_MAP_SRC_HARD_CODED;
1385	return (IDMAP_SUCCESS);
1386}
1387
1388/*
1389 * Look up a name in the wksids list, matching name and, if supplied, domain,
1390 * and extract data.
1391 *
1392 * Given:
1393 * name		Windows user name
1394 * domain	Windows domain name (or NULL)
1395 *
1396 * Return:  Error code
1397 *
1398 * *canonname	canonical name (if canonname non-NULL) [1]
1399 * *canondomain	canonical domain (if canondomain non-NULL) [1]
1400 * *sidprefix	SID prefix (if sidprefix non-NULL) [1]
1401 * *rid		RID (if rid non-NULL) [2]
1402 * *type	Type (if type non-NULL) [2]
1403 *
1404 * [1] malloc'ed, NULL on error
1405 * [2] Undefined on error
1406 */
1407idmap_retcode
1408lookup_wksids_name2sid(
1409    const char *name,
1410    const char *domain,
1411    char **canonname,
1412    char **canondomain,
1413    char **sidprefix,
1414    idmap_rid_t *rid,
1415    int *type)
1416{
1417	const wksids_table_t *wksid;
1418
1419	if (sidprefix != NULL)
1420		*sidprefix = NULL;
1421	if (canonname != NULL)
1422		*canonname = NULL;
1423	if (canondomain != NULL)
1424		*canondomain = NULL;
1425
1426	wksid = find_wksid_by_name(name, domain, IDMAP_POSIXID);
1427	if (wksid == NULL)
1428		return (IDMAP_ERR_NOTFOUND);
1429
1430	if (sidprefix != NULL) {
1431		if (wksid->sidprefix != NULL) {
1432			*sidprefix = strdup(wksid->sidprefix);
1433		} else {
1434			RDLOCK_CONFIG();
1435			*sidprefix = strdup(
1436			    _idmapdstate.cfg->pgcfg.machine_sid);
1437			UNLOCK_CONFIG();
1438		}
1439		if (*sidprefix == NULL)
1440			goto nomem;
1441	}
1442
1443	if (rid != NULL)
1444		*rid = wksid->rid;
1445
1446	if (canonname != NULL) {
1447		*canonname = strdup(wksid->winname);
1448		if (*canonname == NULL)
1449			goto nomem;
1450	}
1451
1452	if (canondomain != NULL) {
1453		if (wksid->domain != NULL) {
1454			*canondomain = strdup(wksid->domain);
1455		} else {
1456			RDLOCK_CONFIG();
1457			*canondomain = strdup(_idmapdstate.hostname);
1458			UNLOCK_CONFIG();
1459		}
1460		if (*canondomain == NULL)
1461			goto nomem;
1462	}
1463
1464	if (type != NULL)
1465		*type = (wksid->is_wuser) ?
1466		    _IDMAP_T_USER : _IDMAP_T_GROUP;
1467
1468	return (IDMAP_SUCCESS);
1469
1470nomem:
1471	idmapdlog(LOG_ERR, "Out of memory");
1472
1473	if (sidprefix != NULL) {
1474		free(*sidprefix);
1475		*sidprefix = NULL;
1476	}
1477
1478	if (canonname != NULL) {
1479		free(*canonname);
1480		*canonname = NULL;
1481	}
1482
1483	if (canondomain != NULL) {
1484		free(*canondomain);
1485		*canondomain = NULL;
1486	}
1487
1488	return (IDMAP_ERR_MEMORY);
1489}
1490
1491static
1492idmap_retcode
1493lookup_cache_sid2pid(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
1494{
1495	char		*end;
1496	char		*sql = NULL;
1497	const char	**values;
1498	sqlite_vm	*vm = NULL;
1499	int		ncol, is_user;
1500	uid_t		pid;
1501	time_t		curtime, exp;
1502	idmap_retcode	retcode;
1503	char		*is_user_string, *lower_name;
1504
1505	/* Current time */
1506	errno = 0;
1507	if ((curtime = time(NULL)) == (time_t)-1) {
1508		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
1509		    strerror(errno));
1510		retcode = IDMAP_ERR_INTERNAL;
1511		goto out;
1512	}
1513
1514	switch (res->id.idtype) {
1515	case IDMAP_UID:
1516		is_user_string = "1";
1517		break;
1518	case IDMAP_GID:
1519		is_user_string = "0";
1520		break;
1521	case IDMAP_POSIXID:
1522		/* the non-diagonal mapping */
1523		is_user_string = "is_wuser";
1524		break;
1525	default:
1526		retcode = IDMAP_ERR_NOTSUPPORTED;
1527		goto out;
1528	}
1529
1530	/* SQL to lookup the cache */
1531
1532	if (req->id1.idmap_id_u.sid.prefix != NULL) {
1533		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
1534		    "unixname, u2w, is_wuser, "
1535		    "map_type, map_dn, map_attr, map_value, "
1536		    "map_windomain, map_winname, map_unixname, map_is_nt4 "
1537		    "FROM idmap_cache WHERE is_user = %s AND "
1538		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
1539		    "(pid >= 2147483648 OR "
1540		    "(expiration = 0 OR expiration ISNULL OR "
1541		    "expiration > %d));",
1542		    is_user_string, req->id1.idmap_id_u.sid.prefix,
1543		    req->id1.idmap_id_u.sid.rid, curtime);
1544	} else if (req->id1name != NULL) {
1545		if ((lower_name = tolower_u8(req->id1name)) == NULL)
1546			lower_name = req->id1name;
1547		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
1548		    "unixname, u2w, is_wuser, "
1549		    "map_type, map_dn, map_attr, map_value, "
1550		    "map_windomain, map_winname, map_unixname, map_is_nt4 "
1551		    "FROM idmap_cache WHERE is_user = %s AND "
1552		    "winname = %Q AND windomain = %Q AND w2u = 1 AND "
1553		    "(pid >= 2147483648 OR "
1554		    "(expiration = 0 OR expiration ISNULL OR "
1555		    "expiration > %d));",
1556		    is_user_string, lower_name, req->id1domain,
1557		    curtime);
1558		if (lower_name != req->id1name)
1559			free(lower_name);
1560	} else {
1561		retcode = IDMAP_ERR_ARG;
1562		goto out;
1563	}
1564	if (sql == NULL) {
1565		idmapdlog(LOG_ERR, "Out of memory");
1566		retcode = IDMAP_ERR_MEMORY;
1567		goto out;
1568	}
1569	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol,
1570	    14, &values);
1571	sqlite_freemem(sql);
1572
1573	if (retcode == IDMAP_ERR_NOTFOUND) {
1574		goto out;
1575	} else if (retcode == IDMAP_SUCCESS) {
1576		/* sanity checks */
1577		if (values[0] == NULL || values[1] == NULL) {
1578			retcode = IDMAP_ERR_CACHE;
1579			goto out;
1580		}
1581
1582		pid = strtoul(values[0], &end, 10);
1583		is_user = strncmp(values[1], "0", 2) ? 1 : 0;
1584
1585		if (is_user) {
1586			res->id.idtype = IDMAP_UID;
1587			res->id.idmap_id_u.uid = pid;
1588		} else {
1589			res->id.idtype = IDMAP_GID;
1590			res->id.idmap_id_u.gid = pid;
1591		}
1592
1593		/*
1594		 * We may have an expired ephemeral mapping. Consider
1595		 * the expired entry as valid if we are not going to
1596		 * perform name-based mapping. But do not renew the
1597		 * expiration.
1598		 * If we will be doing name-based mapping then store the
1599		 * ephemeral pid in the result so that we can use it
1600		 * if we end up doing dynamic mapping again.
1601		 */
1602		if (!DO_NOT_ALLOC_NEW_ID_MAPPING(req) &&
1603		    !AVOID_NAMESERVICE(req) &&
1604		    IDMAP_ID_IS_EPHEMERAL(pid) && values[2] != NULL) {
1605			exp = strtoll(values[2], &end, 10);
1606			if (exp && exp <= curtime) {
1607				/* Store the ephemeral pid */
1608				res->direction = IDMAP_DIRECTION_BI;
1609				req->direction |= is_user
1610				    ? _IDMAP_F_EXP_EPH_UID
1611				    : _IDMAP_F_EXP_EPH_GID;
1612				retcode = IDMAP_ERR_NOTFOUND;
1613			}
1614		}
1615	}
1616
1617out:
1618	if (retcode == IDMAP_SUCCESS) {
1619		if (values[4] != NULL)
1620			res->direction =
1621			    (strtol(values[4], &end, 10) == 0)?
1622			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
1623		else
1624			res->direction = IDMAP_DIRECTION_W2U;
1625
1626		if (values[3] != NULL) {
1627			if (req->id2name != NULL)
1628				free(req->id2name);
1629			req->id2name = strdup(values[3]);
1630			if (req->id2name == NULL) {
1631				idmapdlog(LOG_ERR, "Out of memory");
1632				retcode = IDMAP_ERR_MEMORY;
1633			}
1634		}
1635
1636		req->id1.idtype = strncmp(values[5], "0", 2) ?
1637		    IDMAP_USID : IDMAP_GSID;
1638
1639		if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
1640			res->info.src = IDMAP_MAP_SRC_CACHE;
1641			res->info.how.map_type = strtoul(values[6], &end, 10);
1642			switch (res->info.how.map_type) {
1643			case IDMAP_MAP_TYPE_DS_AD:
1644				res->info.how.idmap_how_u.ad.dn =
1645				    strdup(values[7]);
1646				res->info.how.idmap_how_u.ad.attr =
1647				    strdup(values[8]);
1648				res->info.how.idmap_how_u.ad.value =
1649				    strdup(values[9]);
1650				break;
1651
1652			case IDMAP_MAP_TYPE_DS_NLDAP:
1653				res->info.how.idmap_how_u.nldap.dn =
1654				    strdup(values[7]);
1655				res->info.how.idmap_how_u.nldap.attr =
1656				    strdup(values[8]);
1657				res->info.how.idmap_how_u.nldap.value =
1658				    strdup(values[9]);
1659				break;
1660
1661			case IDMAP_MAP_TYPE_RULE_BASED:
1662				res->info.how.idmap_how_u.rule.windomain =
1663				    strdup(values[10]);
1664				res->info.how.idmap_how_u.rule.winname =
1665				    strdup(values[11]);
1666				res->info.how.idmap_how_u.rule.unixname =
1667				    strdup(values[12]);
1668				res->info.how.idmap_how_u.rule.is_nt4 =
1669				    strtoul(values[13], &end, 1);
1670				res->info.how.idmap_how_u.rule.is_user =
1671				    is_user;
1672				res->info.how.idmap_how_u.rule.is_wuser =
1673				    strtoul(values[5], &end, 1);
1674				break;
1675
1676			case IDMAP_MAP_TYPE_EPHEMERAL:
1677				break;
1678
1679			case IDMAP_MAP_TYPE_LOCAL_SID:
1680				break;
1681
1682			case IDMAP_MAP_TYPE_KNOWN_SID:
1683				break;
1684
1685			case IDMAP_MAP_TYPE_IDMU:
1686				res->info.how.idmap_how_u.idmu.dn =
1687				    strdup(values[7]);
1688				res->info.how.idmap_how_u.idmu.attr =
1689				    strdup(values[8]);
1690				res->info.how.idmap_how_u.idmu.value =
1691				    strdup(values[9]);
1692				break;
1693
1694			default:
1695				/* Unknown mapping type */
1696				assert(FALSE);
1697			}
1698		}
1699	}
1700	if (vm != NULL)
1701		(void) sqlite_finalize(vm, NULL);
1702	return (retcode);
1703}
1704
1705static
1706idmap_retcode
1707lookup_cache_sid2name(sqlite *cache, const char *sidprefix, idmap_rid_t rid,
1708		char **canonname, char **canondomain, int *type)
1709{
1710	char		*end;
1711	char		*sql = NULL;
1712	const char	**values;
1713	sqlite_vm	*vm = NULL;
1714	int		ncol;
1715	time_t		curtime;
1716	idmap_retcode	retcode = IDMAP_SUCCESS;
1717
1718	/* Get current time */
1719	errno = 0;
1720	if ((curtime = time(NULL)) == (time_t)-1) {
1721		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
1722		    strerror(errno));
1723		retcode = IDMAP_ERR_INTERNAL;
1724		goto out;
1725	}
1726
1727	/* SQL to lookup the cache */
1728	sql = sqlite_mprintf("SELECT canon_name, domain, type "
1729	    "FROM name_cache WHERE "
1730	    "sidprefix = %Q AND rid = %u AND "
1731	    "(expiration = 0 OR expiration ISNULL OR "
1732	    "expiration > %d);",
1733	    sidprefix, rid, curtime);
1734	if (sql == NULL) {
1735		idmapdlog(LOG_ERR, "Out of memory");
1736		retcode = IDMAP_ERR_MEMORY;
1737		goto out;
1738	}
1739	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 3, &values);
1740	sqlite_freemem(sql);
1741
1742	if (retcode == IDMAP_SUCCESS) {
1743		if (type != NULL) {
1744			if (values[2] == NULL) {
1745				retcode = IDMAP_ERR_CACHE;
1746				goto out;
1747			}
1748			*type = strtol(values[2], &end, 10);
1749		}
1750
1751		if (canonname != NULL && values[0] != NULL) {
1752			if ((*canonname = strdup(values[0])) == NULL) {
1753				idmapdlog(LOG_ERR, "Out of memory");
1754				retcode = IDMAP_ERR_MEMORY;
1755				goto out;
1756			}
1757		}
1758
1759		if (canondomain != NULL && values[1] != NULL) {
1760			if ((*canondomain = strdup(values[1])) == NULL) {
1761				if (canonname != NULL) {
1762					free(*canonname);
1763					*canonname = NULL;
1764				}
1765				idmapdlog(LOG_ERR, "Out of memory");
1766				retcode = IDMAP_ERR_MEMORY;
1767				goto out;
1768			}
1769		}
1770	}
1771
1772out:
1773	if (vm != NULL)
1774		(void) sqlite_finalize(vm, NULL);
1775	return (retcode);
1776}
1777
1778/*
1779 * Given SID, find winname using name_cache OR
1780 * Given winname, find SID using name_cache.
1781 * Used when mapping win to unix i.e. req->id1 is windows id and
1782 * req->id2 is unix id
1783 */
1784static
1785idmap_retcode
1786lookup_name_cache(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
1787{
1788	int		type = -1;
1789	idmap_retcode	retcode;
1790	char		*sidprefix = NULL;
1791	idmap_rid_t	rid;
1792	char		*name = NULL, *domain = NULL;
1793
1794	/* Done if we've both sid and winname */
1795	if (req->id1.idmap_id_u.sid.prefix != NULL && req->id1name != NULL)
1796		return (IDMAP_SUCCESS);
1797
1798	if (req->id1.idmap_id_u.sid.prefix != NULL) {
1799		/* Lookup sid to winname */
1800		retcode = lookup_cache_sid2name(cache,
1801		    req->id1.idmap_id_u.sid.prefix,
1802		    req->id1.idmap_id_u.sid.rid, &name, &domain, &type);
1803	} else {
1804		/* Lookup winame to sid */
1805		retcode = lookup_cache_name2sid(cache, req->id1name,
1806		    req->id1domain, &name, &sidprefix, &rid, &type);
1807	}
1808
1809	if (retcode != IDMAP_SUCCESS) {
1810		free(name);
1811		free(domain);
1812		free(sidprefix);
1813		return (retcode);
1814	}
1815
1816	if (res->id.idtype == IDMAP_POSIXID) {
1817		res->id.idtype = (type == _IDMAP_T_USER) ?
1818		    IDMAP_UID : IDMAP_GID;
1819	}
1820	req->id1.idtype = (type == _IDMAP_T_USER) ?
1821	    IDMAP_USID : IDMAP_GSID;
1822
1823	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
1824
1825	/*
1826	 * If we found canonical names or domain, use them instead of
1827	 * the existing values.
1828	 */
1829	if (name != NULL) {
1830		free(req->id1name);
1831		req->id1name = name;
1832	}
1833	if (domain != NULL) {
1834		free(req->id1domain);
1835		req->id1domain = domain;
1836	}
1837
1838	if (req->id1.idmap_id_u.sid.prefix == NULL) {
1839		req->id1.idmap_id_u.sid.prefix = sidprefix;
1840		req->id1.idmap_id_u.sid.rid = rid;
1841	}
1842	return (retcode);
1843}
1844
1845
1846
1847static int
1848ad_lookup_batch_int(lookup_state_t *state, idmap_mapping_batch *batch,
1849		idmap_ids_res *result, adutils_ad_t *dir, int how_local,
1850		int *num_processed)
1851{
1852	idmap_retcode	retcode;
1853	int		i,  num_queued, is_wuser, is_user;
1854	int		next_request;
1855	int		retries = 0, eunixtype;
1856	char		**unixname;
1857	idmap_mapping	*req;
1858	idmap_id_res	*res;
1859	idmap_query_state_t	*qs = NULL;
1860	idmap_how	*how;
1861	char		**dn, **attr, **value;
1862
1863	*num_processed = 0;
1864
1865	/*
1866	 * Since req->id2.idtype is unused, we will use it here
1867	 * to retrieve the value of sid_type. But it needs to be
1868	 * reset to IDMAP_NONE before we return to prevent xdr
1869	 * from mis-interpreting req->id2 when it tries to free
1870	 * the input argument. Other option is to allocate an
1871	 * array of integers and use it instead for the batched
1872	 * call. But why un-necessarily allocate memory. That may
1873	 * be an option if req->id2.idtype cannot be re-used in
1874	 * future.
1875	 *
1876	 * Similarly, we use req->id2.idmap_id_u.uid to return
1877	 * uidNumber or gidNumber supplied by IDMU, and reset it
1878	 * back to IDMAP_SENTINEL_PID when we're done.  Note that
1879	 * the query always puts the result in req->id2.idmap_id_u.uid,
1880	 * not .gid.
1881	 */
1882retry:
1883	retcode = idmap_lookup_batch_start(dir, state->ad_nqueries,
1884	    state->directory_based_mapping,
1885	    state->defdom,
1886	    &qs);
1887	if (retcode != IDMAP_SUCCESS) {
1888		if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
1889		    retries++ < ADUTILS_DEF_NUM_RETRIES)
1890			goto retry;
1891		degrade_svc(1, "failed to create batch for AD lookup");
1892			goto out;
1893	}
1894	num_queued = 0;
1895
1896	restore_svc();
1897
1898	if (how_local & FOREST_IS_LOCAL) {
1899		/*
1900		 * Directory based name mapping is only performed within the
1901		 * joined forest.  We don't trust other "trusted"
1902		 * forests to provide DS-based name mapping information because
1903		 * AD's definition of "cross-forest trust" does not encompass
1904		 * this sort of behavior.
1905		 */
1906		idmap_lookup_batch_set_unixattr(qs,
1907		    state->ad_unixuser_attr, state->ad_unixgroup_attr);
1908	}
1909
1910	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
1911		req = &batch->idmap_mapping_batch_val[i];
1912		res = &result->ids.ids_val[i];
1913		how = &res->info.how;
1914
1915		retcode = IDMAP_SUCCESS;
1916		req->id2.idtype = IDMAP_NONE;
1917		req->id2.idmap_id_u.uid = IDMAP_SENTINEL_PID;
1918
1919		/* Skip if no AD lookup required */
1920		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
1921			continue;
1922
1923		/* Skip if we've already tried and gotten a "not found" */
1924		if (req->direction & _IDMAP_F_LOOKUP_OTHER_AD)
1925			continue;
1926
1927		/* Skip if we've already either succeeded or failed */
1928		if (res->retcode != IDMAP_ERR_RETRIABLE_NET_ERR)
1929			continue;
1930
1931		if (IS_REQUEST_SID(*req, 1)) {
1932
1933			/* win2unix request: */
1934
1935			posix_id_t *pid = NULL;
1936			unixname = dn = attr = value = NULL;
1937			eunixtype = _IDMAP_T_UNDEF;
1938			if (state->directory_based_mapping ==
1939			    DIRECTORY_MAPPING_NAME &&
1940			    req->id2name == NULL) {
1941				if (res->id.idtype == IDMAP_UID &&
1942				    AD_OR_MIXED(state->nm_siduid)) {
1943					eunixtype = _IDMAP_T_USER;
1944					unixname = &req->id2name;
1945				} else if (res->id.idtype == IDMAP_GID &&
1946				    AD_OR_MIXED(state->nm_sidgid)) {
1947					eunixtype = _IDMAP_T_GROUP;
1948					unixname = &req->id2name;
1949				} else if (AD_OR_MIXED(state->nm_siduid) ||
1950				    AD_OR_MIXED(state->nm_sidgid)) {
1951					unixname = &req->id2name;
1952				}
1953
1954				if (unixname != NULL) {
1955					/*
1956					 * Get how info for DS-based name
1957					 * mapping only if AD or MIXED
1958					 * mode is enabled.
1959					 */
1960					idmap_info_free(&res->info);
1961					res->info.src = IDMAP_MAP_SRC_NEW;
1962					how->map_type = IDMAP_MAP_TYPE_DS_AD;
1963					dn = &how->idmap_how_u.ad.dn;
1964					attr = &how->idmap_how_u.ad.attr;
1965					value = &how->idmap_how_u.ad.value;
1966				}
1967			} else if (state->directory_based_mapping ==
1968			    DIRECTORY_MAPPING_IDMU &&
1969			    (how_local & DOMAIN_IS_LOCAL)) {
1970				/*
1971				 * Ensure that we only do IDMU processing
1972				 * when querying the domain we've joined.
1973				 */
1974				pid = &req->id2.idmap_id_u.uid;
1975				/*
1976				 * Get how info for IDMU based mapping.
1977				 */
1978				idmap_info_free(&res->info);
1979				res->info.src = IDMAP_MAP_SRC_NEW;
1980				how->map_type = IDMAP_MAP_TYPE_IDMU;
1981				dn = &how->idmap_how_u.idmu.dn;
1982				attr = &how->idmap_how_u.idmu.attr;
1983				value = &how->idmap_how_u.idmu.value;
1984			}
1985
1986			if (req->id1.idmap_id_u.sid.prefix != NULL) {
1987				/* Lookup AD by SID */
1988				retcode = idmap_sid2name_batch_add1(
1989				    qs, req->id1.idmap_id_u.sid.prefix,
1990				    &req->id1.idmap_id_u.sid.rid, eunixtype,
1991				    dn, attr, value,
1992				    (req->id1name == NULL) ?
1993				    &req->id1name : NULL,
1994				    (req->id1domain == NULL) ?
1995				    &req->id1domain : NULL,
1996				    (int *)&req->id2.idtype, unixname,
1997				    pid,
1998				    &res->retcode);
1999				if (retcode == IDMAP_SUCCESS)
2000					num_queued++;
2001			} else {
2002				/* Lookup AD by winname */
2003				assert(req->id1name != NULL);
2004				retcode = idmap_name2sid_batch_add1(
2005				    qs, req->id1name, req->id1domain,
2006				    eunixtype,
2007				    dn, attr, value,
2008				    &req->id1name,
2009				    &req->id1.idmap_id_u.sid.prefix,
2010				    &req->id1.idmap_id_u.sid.rid,
2011				    (int *)&req->id2.idtype, unixname,
2012				    pid,
2013				    &res->retcode);
2014				if (retcode == IDMAP_SUCCESS)
2015					num_queued++;
2016			}
2017
2018		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
2019
2020			/* unix2win request: */
2021
2022			if (res->id.idmap_id_u.sid.prefix != NULL &&
2023			    req->id2name != NULL) {
2024				/* Already have SID and winname. done */
2025				res->retcode = IDMAP_SUCCESS;
2026				continue;
2027			}
2028
2029			if (res->id.idmap_id_u.sid.prefix != NULL) {
2030				/*
2031				 * SID but no winname -- lookup AD by
2032				 * SID to get winname.
2033				 * how info is not needed here because
2034				 * we are not retrieving unixname from
2035				 * AD.
2036				 */
2037
2038				retcode = idmap_sid2name_batch_add1(
2039				    qs, res->id.idmap_id_u.sid.prefix,
2040				    &res->id.idmap_id_u.sid.rid,
2041				    _IDMAP_T_UNDEF,
2042				    NULL, NULL, NULL,
2043				    &req->id2name,
2044				    &req->id2domain, (int *)&req->id2.idtype,
2045				    NULL, NULL, &res->retcode);
2046				if (retcode == IDMAP_SUCCESS)
2047					num_queued++;
2048			} else if (req->id2name != NULL) {
2049				/*
2050				 * winname but no SID -- lookup AD by
2051				 * winname to get SID.
2052				 * how info is not needed here because
2053				 * we are not retrieving unixname from
2054				 * AD.
2055				 */
2056				retcode = idmap_name2sid_batch_add1(
2057				    qs, req->id2name, req->id2domain,
2058				    _IDMAP_T_UNDEF,
2059				    NULL, NULL, NULL, NULL,
2060				    &res->id.idmap_id_u.sid.prefix,
2061				    &res->id.idmap_id_u.sid.rid,
2062				    (int *)&req->id2.idtype, NULL,
2063				    NULL,
2064				    &res->retcode);
2065				if (retcode == IDMAP_SUCCESS)
2066					num_queued++;
2067			} else if (state->directory_based_mapping ==
2068			    DIRECTORY_MAPPING_IDMU &&
2069			    (how_local & DOMAIN_IS_LOCAL)) {
2070				assert(req->id1.idmap_id_u.uid !=
2071				    IDMAP_SENTINEL_PID);
2072				is_user = IS_REQUEST_UID(*req);
2073				if (res->id.idtype == IDMAP_USID)
2074					is_wuser = 1;
2075				else if (res->id.idtype == IDMAP_GSID)
2076					is_wuser = 0;
2077				else
2078					is_wuser = is_user;
2079
2080				/* IDMU can't do diagonal mappings */
2081				if (is_user != is_wuser)
2082					continue;
2083
2084				idmap_info_free(&res->info);
2085				res->info.src = IDMAP_MAP_SRC_NEW;
2086				how->map_type = IDMAP_MAP_TYPE_IDMU;
2087				retcode = idmap_pid2sid_batch_add1(
2088				    qs, req->id1.idmap_id_u.uid, is_user,
2089				    &how->idmap_how_u.ad.dn,
2090				    &how->idmap_how_u.ad.attr,
2091				    &how->idmap_how_u.ad.value,
2092				    &res->id.idmap_id_u.sid.prefix,
2093				    &res->id.idmap_id_u.sid.rid,
2094				    &req->id2name, &req->id2domain,
2095				    (int *)&req->id2.idtype, &res->retcode);
2096				if (retcode == IDMAP_SUCCESS)
2097					num_queued++;
2098			} else if (req->id1name != NULL) {
2099				/*
2100				 * No SID and no winname but we've unixname.
2101				 * Lookup AD by unixname to get SID.
2102				 */
2103				is_user = (IS_REQUEST_UID(*req)) ? 1 : 0;
2104				if (res->id.idtype == IDMAP_USID)
2105					is_wuser = 1;
2106				else if (res->id.idtype == IDMAP_GSID)
2107					is_wuser = 0;
2108				else
2109					is_wuser = is_user;
2110
2111				idmap_info_free(&res->info);
2112				res->info.src = IDMAP_MAP_SRC_NEW;
2113				how->map_type = IDMAP_MAP_TYPE_DS_AD;
2114				retcode = idmap_unixname2sid_batch_add1(
2115				    qs, req->id1name, is_user, is_wuser,
2116				    &how->idmap_how_u.ad.dn,
2117				    &how->idmap_how_u.ad.attr,
2118				    &how->idmap_how_u.ad.value,
2119				    &res->id.idmap_id_u.sid.prefix,
2120				    &res->id.idmap_id_u.sid.rid,
2121				    &req->id2name, &req->id2domain,
2122				    (int *)&req->id2.idtype, &res->retcode);
2123				if (retcode == IDMAP_SUCCESS)
2124					num_queued++;
2125			}
2126		}
2127
2128		if (retcode == IDMAP_ERR_DOMAIN_NOTFOUND) {
2129			req->direction |= _IDMAP_F_LOOKUP_OTHER_AD;
2130			retcode = IDMAP_SUCCESS;
2131		} else if (retcode != IDMAP_SUCCESS) {
2132			break;
2133		}
2134	} /* End of for loop */
2135
2136	if (retcode == IDMAP_SUCCESS) {
2137		/* add keeps track if we added an entry to the batch */
2138		if (num_queued > 0)
2139			retcode = idmap_lookup_batch_end(&qs);
2140		else
2141			idmap_lookup_release_batch(&qs);
2142	} else {
2143		idmap_lookup_release_batch(&qs);
2144		num_queued = 0;
2145		next_request = i + 1;
2146	}
2147
2148	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
2149	    retries++ < ADUTILS_DEF_NUM_RETRIES)
2150		goto retry;
2151	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
2152		degrade_svc(1, "some AD lookups timed out repeatedly");
2153
2154	if (retcode != IDMAP_SUCCESS) {
2155		/* Mark any unproccessed requests for an other AD */
2156		for (i = next_request; i < batch->idmap_mapping_batch_len;
2157		    i++) {
2158			req = &batch->idmap_mapping_batch_val[i];
2159			req->direction |= _IDMAP_F_LOOKUP_OTHER_AD;
2160
2161		}
2162	}
2163
2164	if (retcode != IDMAP_SUCCESS)
2165		idmapdlog(LOG_NOTICE, "Failed to batch AD lookup requests");
2166
2167out:
2168	/*
2169	 * This loop does the following:
2170	 * 1. Reset _IDMAP_F_LOOKUP_AD flag from the request.
2171	 * 2. Reset req->id2.idtype to IDMAP_NONE
2172	 * 3. If batch_start or batch_add failed then set the status
2173	 *    of each request marked for AD lookup to that error.
2174	 * 4. Evaluate the type of the AD object (i.e. user or group)
2175	 *    and update the idtype in request.
2176	 */
2177	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
2178		int type;
2179		uid_t posix_id;
2180
2181		req = &batch->idmap_mapping_batch_val[i];
2182		type = req->id2.idtype;
2183		req->id2.idtype = IDMAP_NONE;
2184		posix_id = req->id2.idmap_id_u.uid;
2185		req->id2.idmap_id_u.uid = IDMAP_SENTINEL_PID;
2186		res = &result->ids.ids_val[i];
2187
2188		/*
2189		 * If it didn't need AD lookup, ignore it.
2190		 */
2191		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
2192			continue;
2193
2194		/*
2195		 * If we deferred it this time, reset for the next
2196		 * AD server.
2197		 */
2198		if (req->direction & _IDMAP_F_LOOKUP_OTHER_AD) {
2199			req->direction &= ~_IDMAP_F_LOOKUP_OTHER_AD;
2200			continue;
2201		}
2202
2203		/* Count number processed */
2204		(*num_processed)++;
2205
2206		/* Reset AD lookup flag */
2207		req->direction &= ~(_IDMAP_F_LOOKUP_AD);
2208
2209		/*
2210		 * If batch_start or batch_add failed then set the
2211		 * status of each request marked for AD lookup to
2212		 * that error.
2213		 */
2214		if (retcode != IDMAP_SUCCESS) {
2215			res->retcode = retcode;
2216			continue;
2217		}
2218
2219		if (res->retcode == IDMAP_ERR_NOTFOUND) {
2220			/* Nothing found - remove the preset info */
2221			idmap_info_free(&res->info);
2222		}
2223
2224		if (IS_REQUEST_SID(*req, 1)) {
2225			if (res->retcode != IDMAP_SUCCESS)
2226				continue;
2227			/* Evaluate result type */
2228			switch (type) {
2229			case _IDMAP_T_USER:
2230				if (res->id.idtype == IDMAP_POSIXID)
2231					res->id.idtype = IDMAP_UID;
2232				/*
2233				 * We found a user.  If we got information
2234				 * from IDMU and we were expecting a user,
2235				 * copy the id.
2236				 */
2237				if (posix_id != IDMAP_SENTINEL_PID &&
2238				    res->id.idtype == IDMAP_UID) {
2239					res->id.idmap_id_u.uid = posix_id;
2240					res->direction = IDMAP_DIRECTION_BI;
2241					res->info.how.map_type =
2242					    IDMAP_MAP_TYPE_IDMU;
2243					res->info.src = IDMAP_MAP_SRC_NEW;
2244				}
2245				req->id1.idtype = IDMAP_USID;
2246				break;
2247
2248			case _IDMAP_T_GROUP:
2249				if (res->id.idtype == IDMAP_POSIXID)
2250					res->id.idtype = IDMAP_GID;
2251				/*
2252				 * We found a group.  If we got information
2253				 * from IDMU and we were expecting a group,
2254				 * copy the id.
2255				 */
2256				if (posix_id != IDMAP_SENTINEL_PID &&
2257				    res->id.idtype == IDMAP_GID) {
2258					res->id.idmap_id_u.gid = posix_id;
2259					res->direction = IDMAP_DIRECTION_BI;
2260					res->info.how.map_type =
2261					    IDMAP_MAP_TYPE_IDMU;
2262					res->info.src = IDMAP_MAP_SRC_NEW;
2263				}
2264				req->id1.idtype = IDMAP_GSID;
2265				break;
2266
2267			default:
2268				res->retcode = IDMAP_ERR_SID;
2269				break;
2270			}
2271			if (res->retcode == IDMAP_SUCCESS &&
2272			    req->id1name != NULL &&
2273			    (req->id2name == NULL ||
2274			    res->id.idmap_id_u.uid == IDMAP_SENTINEL_PID) &&
2275			    NLDAP_MODE(res->id.idtype, state)) {
2276				req->direction |= _IDMAP_F_LOOKUP_NLDAP;
2277				state->nldap_nqueries++;
2278			}
2279		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
2280			if (res->retcode != IDMAP_SUCCESS) {
2281				if ((!(IDMAP_FATAL_ERROR(res->retcode))) &&
2282				    res->id.idmap_id_u.sid.prefix == NULL &&
2283				    req->id2name == NULL) /* no winname */
2284					/*
2285					 * If AD lookup by unixname or pid
2286					 * failed with non fatal error
2287					 * then clear the error (ie set
2288					 * res->retcode to success).
2289					 * This allows the next pass to
2290					 * process other mapping
2291					 * mechanisms for this request.
2292					 */
2293					res->retcode = IDMAP_SUCCESS;
2294				continue;
2295			}
2296			/* Evaluate result type */
2297			switch (type) {
2298			case _IDMAP_T_USER:
2299				if (res->id.idtype == IDMAP_SID)
2300					res->id.idtype = IDMAP_USID;
2301				break;
2302
2303			case _IDMAP_T_GROUP:
2304				if (res->id.idtype == IDMAP_SID)
2305					res->id.idtype = IDMAP_GSID;
2306				break;
2307
2308			default:
2309				res->retcode = IDMAP_ERR_SID;
2310				break;
2311			}
2312		}
2313	}
2314
2315	return (retcode);
2316}
2317
2318
2319
2320/*
2321 * Batch AD lookups
2322 */
2323idmap_retcode
2324ad_lookup_batch(lookup_state_t *state, idmap_mapping_batch *batch,
2325		idmap_ids_res *result)
2326{
2327	idmap_retcode	retcode;
2328	int		i, j;
2329	idmap_mapping	*req;
2330	idmap_id_res	*res;
2331	int		num_queries;
2332	int		num_processed;
2333
2334	if (state->ad_nqueries == 0)
2335		return (IDMAP_SUCCESS);
2336
2337	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
2338		req = &batch->idmap_mapping_batch_val[i];
2339		res = &result->ids.ids_val[i];
2340
2341		/* Skip if not marked for AD lookup or already in error. */
2342		if (!(req->direction & _IDMAP_F_LOOKUP_AD) ||
2343		    res->retcode != IDMAP_SUCCESS)
2344			continue;
2345
2346		/* Init status */
2347		res->retcode = IDMAP_ERR_RETRIABLE_NET_ERR;
2348	}
2349
2350	RDLOCK_CONFIG();
2351	num_queries = state->ad_nqueries;
2352
2353	if (_idmapdstate.num_gcs == 0 && _idmapdstate.num_dcs == 0) {
2354		/* Case of no ADs */
2355		retcode = IDMAP_ERR_NO_ACTIVEDIRECTORY;
2356		for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
2357			req = &batch->idmap_mapping_batch_val[i];
2358			res = &result->ids.ids_val[i];
2359			if (!(req->direction & _IDMAP_F_LOOKUP_AD))
2360				continue;
2361			req->direction &= ~(_IDMAP_F_LOOKUP_AD);
2362			res->retcode = IDMAP_ERR_NO_ACTIVEDIRECTORY;
2363		}
2364		goto out;
2365	}
2366
2367	if (state->directory_based_mapping == DIRECTORY_MAPPING_IDMU) {
2368		for (i = 0; i < _idmapdstate.num_dcs && num_queries > 0; i++) {
2369
2370			retcode = ad_lookup_batch_int(state, batch,
2371			    result, _idmapdstate.dcs[i],
2372			    i == 0 ? DOMAIN_IS_LOCAL|FOREST_IS_LOCAL : 0,
2373			    &num_processed);
2374			num_queries -= num_processed;
2375
2376		}
2377	}
2378
2379	for (i = 0; i < _idmapdstate.num_gcs && num_queries > 0; i++) {
2380
2381		retcode = ad_lookup_batch_int(state, batch, result,
2382		    _idmapdstate.gcs[i],
2383		    i == 0 ? FOREST_IS_LOCAL : 0,
2384		    &num_processed);
2385		num_queries -= num_processed;
2386
2387	}
2388
2389	/*
2390	 * There are no more ADs to try.  Return errors for any
2391	 * remaining requests.
2392	 */
2393	if (num_queries > 0) {
2394		for (j = 0; j < batch->idmap_mapping_batch_len; j++) {
2395			req = &batch->idmap_mapping_batch_val[j];
2396			res = &result->ids.ids_val[j];
2397			if (!(req->direction & _IDMAP_F_LOOKUP_AD))
2398				continue;
2399			req->direction &= ~(_IDMAP_F_LOOKUP_AD);
2400			res->retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
2401		}
2402	}
2403
2404out:
2405	UNLOCK_CONFIG();
2406
2407	/* AD lookups done. Reset state->ad_nqueries and return */
2408	state->ad_nqueries = 0;
2409	return (retcode);
2410}
2411
2412/*
2413 * Convention when processing win2unix requests:
2414 *
2415 * Windows identity:
2416 * req->id1name =
2417 *              winname if given otherwise winname found will be placed
2418 *              here.
2419 * req->id1domain =
2420 *              windomain if given otherwise windomain found will be
2421 *              placed here.
2422 * req->id1.idtype =
2423 *              Either IDMAP_SID/USID/GSID. If this is IDMAP_SID then it'll
2424 *              be set to IDMAP_USID/GSID depending upon whether the
2425 *              given SID is user or group respectively. The user/group-ness
2426 *              is determined either when looking up well-known SIDs table OR
2427 *              if the SID is found in namecache OR by ad_lookup_batch().
2428 * req->id1..sid.[prefix, rid] =
2429 *              SID if given otherwise SID found will be placed here.
2430 *
2431 * Unix identity:
2432 * req->id2name =
2433 *              unixname found will be placed here.
2434 * req->id2domain =
2435 *              NOT USED
2436 * res->id.idtype =
2437 *              Target type initialized from req->id2.idtype. If
2438 *              it is IDMAP_POSIXID then actual type (IDMAP_UID/GID) found
2439 *              will be placed here.
2440 * res->id..[uid or gid] =
2441 *              UID/GID found will be placed here.
2442 *
2443 * Others:
2444 * res->retcode =
2445 *              Return status for this request will be placed here.
2446 * res->direction =
2447 *              Direction found will be placed here. Direction
2448 *              meaning whether the resultant mapping is valid
2449 *              only from win2unix or bi-directional.
2450 * req->direction =
2451 *              INTERNAL USE. Used by idmapd to set various
2452 *              flags (_IDMAP_F_xxxx) to aid in processing
2453 *              of the request.
2454 * req->id2.idtype =
2455 *              INTERNAL USE. Initially this is the requested target
2456 *              type and is used to initialize res->id.idtype.
2457 *              ad_lookup_batch() uses this field temporarily to store
2458 *              sid_type obtained by the batched AD lookups and after
2459 *              use resets it to IDMAP_NONE to prevent xdr from
2460 *              mis-interpreting the contents of req->id2.
2461 * req->id2.idmap_id_u.uid =
2462 *              INTERNAL USE.  If the AD lookup finds IDMU data
2463 *		(uidNumber or gidNumber, depending on the type of
2464 *		the entry), it's left here.
2465 */
2466
2467/*
2468 * This function does the following:
2469 * 1. Lookup well-known SIDs table.
2470 * 2. Check if the given SID is a local-SID and if so extract UID/GID from it.
2471 * 3. Lookup cache.
2472 * 4. Check if the client does not want new mapping to be allocated
2473 *    in which case this pass is the final pass.
2474 * 5. Set AD lookup flag if it determines that the next stage needs
2475 *    to do AD lookup.
2476 */
2477idmap_retcode
2478sid2pid_first_pass(lookup_state_t *state, idmap_mapping *req,
2479		idmap_id_res *res)
2480{
2481	idmap_retcode	retcode;
2482	int		wksid;
2483
2484	/* Initialize result */
2485	res->id.idtype = req->id2.idtype;
2486	res->id.idmap_id_u.uid = IDMAP_SENTINEL_PID;
2487	res->direction = IDMAP_DIRECTION_UNDEF;
2488	wksid = 0;
2489
2490	if (EMPTY_STRING(req->id1.idmap_id_u.sid.prefix)) {
2491		/* They have to give us *something* to work with! */
2492		if (req->id1name == NULL) {
2493			retcode = IDMAP_ERR_ARG;
2494			goto out;
2495		}
2496
2497		/* sanitize sidprefix */
2498		free(req->id1.idmap_id_u.sid.prefix);
2499		req->id1.idmap_id_u.sid.prefix = NULL;
2500
2501		/* Allow for a fully-qualified name in the "name" parameter */
2502		if (req->id1domain == NULL) {
2503			char *p;
2504			p = strchr(req->id1name, '@');
2505			if (p != NULL) {
2506				char *q;
2507				q = req->id1name;
2508				req->id1name = strndup(q, p - req->id1name);
2509				req->id1domain = strdup(p+1);
2510				free(q);
2511				if (req->id1name == NULL ||
2512				    req->id1domain == NULL) {
2513					retcode = IDMAP_ERR_MEMORY;
2514					goto out;
2515				}
2516			}
2517		}
2518	}
2519
2520	/* Lookup well-known SIDs table */
2521	retcode = lookup_wksids_sid2pid(req, res, &wksid);
2522	/*
2523	 * Note that IDMAP_SUCCESS means that we found a hardwired mapping.
2524	 * If we found a well-known identity but no mapping, wksid==true and
2525	 * retcode==IDMAP_ERR_NOTFOUND.
2526	 */
2527	if (retcode != IDMAP_ERR_NOTFOUND)
2528		goto out;
2529
2530	if (!wksid) {
2531		/* Check if this is a localsid */
2532		retcode = lookup_localsid2pid(req, res);
2533		if (retcode != IDMAP_ERR_NOTFOUND)
2534			goto out;
2535
2536		if (ALLOW_WK_OR_LOCAL_SIDS_ONLY(req)) {
2537			retcode = IDMAP_ERR_NONE_GENERATED;
2538			goto out;
2539		}
2540	}
2541
2542	/*
2543	 * If this is a name-based request and we don't have a domain,
2544	 * use the default domain.  Note that the well-known identity
2545	 * cases will have supplied a SID prefix already, and that we
2546	 * don't (yet?) support looking up a local user through a Windows
2547	 * style name.
2548	 */
2549	if (req->id1.idmap_id_u.sid.prefix == NULL &&
2550	    req->id1name != NULL && req->id1domain == NULL) {
2551		if (state->defdom == NULL) {
2552			retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
2553			goto out;
2554		}
2555		req->id1domain = strdup(state->defdom);
2556		if (req->id1domain == NULL) {
2557			retcode = IDMAP_ERR_MEMORY;
2558			goto out;
2559		}
2560	}
2561
2562	/* Lookup cache */
2563	retcode = lookup_cache_sid2pid(state->cache, req, res);
2564	if (retcode != IDMAP_ERR_NOTFOUND)
2565		goto out;
2566
2567	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req) || AVOID_NAMESERVICE(req)) {
2568		retcode = IDMAP_ERR_NONE_GENERATED;
2569		goto out;
2570	}
2571
2572	/*
2573	 * Failed to find non-expired entry in cache. Next step is
2574	 * to determine if this request needs to be batched for AD lookup.
2575	 *
2576	 * At this point we have either sid or winname or both. If we don't
2577	 * have both then lookup name_cache for the sid or winname
2578	 * whichever is missing. If not found then this request will be
2579	 * batched for AD lookup.
2580	 */
2581	retcode = lookup_name_cache(state->cache, req, res);
2582	if (retcode != IDMAP_SUCCESS && retcode != IDMAP_ERR_NOTFOUND)
2583		goto out;
2584
2585	/*
2586	 * Set the flag to indicate that we are not done yet so that
2587	 * subsequent passes considers this request for name-based
2588	 * mapping and ephemeral mapping.
2589	 */
2590	state->sid2pid_done = FALSE;
2591	req->direction |= _IDMAP_F_NOTDONE;
2592
2593	/*
2594	 * Even if we have both sid and winname, we still may need to batch
2595	 * this request for AD lookup if we don't have unixname and
2596	 * directory-based name mapping (AD or mixed) is enabled.
2597	 * We avoid AD lookup for well-known SIDs because they don't have
2598	 * regular AD objects.
2599	 */
2600	if (retcode != IDMAP_SUCCESS ||
2601	    (!wksid && req->id2name == NULL &&
2602	    AD_OR_MIXED_MODE(res->id.idtype, state)) ||
2603	    (!wksid && res->id.idmap_id_u.uid == IDMAP_SENTINEL_PID &&
2604	    state->directory_based_mapping == DIRECTORY_MAPPING_IDMU)) {
2605		retcode = IDMAP_SUCCESS;
2606		req->direction |= _IDMAP_F_LOOKUP_AD;
2607		state->ad_nqueries++;
2608	} else if (NLDAP_MODE(res->id.idtype, state)) {
2609		req->direction |= _IDMAP_F_LOOKUP_NLDAP;
2610		state->nldap_nqueries++;
2611	}
2612
2613
2614out:
2615	res->retcode = idmap_stat4prot(retcode);
2616	/*
2617	 * If we are done and there was an error then set fallback pid
2618	 * in the result.
2619	 */
2620	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
2621		res->id.idmap_id_u.uid = UID_NOBODY;
2622	return (retcode);
2623}
2624
2625/*
2626 * Generate SID using the following convention
2627 * 	<machine-sid-prefix>-<1000 + uid>
2628 * 	<machine-sid-prefix>-<2^31 + gid>
2629 */
2630static
2631idmap_retcode
2632generate_localsid(idmap_mapping *req, idmap_id_res *res, int is_user,
2633		int fallback)
2634{
2635	free(res->id.idmap_id_u.sid.prefix);
2636	res->id.idmap_id_u.sid.prefix = NULL;
2637
2638	/*
2639	 * Diagonal mapping for localSIDs not supported because of the
2640	 * way we generate localSIDs.
2641	 */
2642	if (is_user && res->id.idtype == IDMAP_GSID)
2643		return (IDMAP_ERR_NOTGROUP);
2644	if (!is_user && res->id.idtype == IDMAP_USID)
2645		return (IDMAP_ERR_NOTUSER);
2646
2647	/* Skip 1000 UIDs */
2648	if (is_user &&
2649	    req->id1.idmap_id_u.uid + LOCALRID_UID_MIN > LOCALRID_UID_MAX)
2650		return (IDMAP_ERR_NOMAPPING);
2651
2652	RDLOCK_CONFIG();
2653	/*
2654	 * machine_sid is never NULL because if it is we won't be here.
2655	 * No need to assert because stdrup(NULL) will core anyways.
2656	 */
2657	res->id.idmap_id_u.sid.prefix =
2658	    strdup(_idmapdstate.cfg->pgcfg.machine_sid);
2659	if (res->id.idmap_id_u.sid.prefix == NULL) {
2660		UNLOCK_CONFIG();
2661		idmapdlog(LOG_ERR, "Out of memory");
2662		return (IDMAP_ERR_MEMORY);
2663	}
2664	UNLOCK_CONFIG();
2665	res->id.idmap_id_u.sid.rid =
2666	    (is_user) ? req->id1.idmap_id_u.uid + LOCALRID_UID_MIN :
2667	    req->id1.idmap_id_u.gid + LOCALRID_GID_MIN;
2668	res->direction = IDMAP_DIRECTION_BI;
2669	if (res->id.idtype == IDMAP_SID)
2670		res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
2671
2672	if (!fallback) {
2673		res->info.how.map_type = IDMAP_MAP_TYPE_LOCAL_SID;
2674		res->info.src = IDMAP_MAP_SRC_ALGORITHMIC;
2675	}
2676
2677	/*
2678	 * Don't update name_cache because local sids don't have
2679	 * valid windows names.
2680	 */
2681	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
2682	return (IDMAP_SUCCESS);
2683}
2684
2685static
2686idmap_retcode
2687lookup_localsid2pid(idmap_mapping *req, idmap_id_res *res)
2688{
2689	char		*sidprefix;
2690	uint32_t	rid;
2691	int		s;
2692
2693	/*
2694	 * If the sidprefix == localsid then UID = last RID - 1000 or
2695	 * GID = last RID - 2^31.
2696	 */
2697	if ((sidprefix = req->id1.idmap_id_u.sid.prefix) == NULL)
2698		/* This means we are looking up by winname */
2699		return (IDMAP_ERR_NOTFOUND);
2700	rid = req->id1.idmap_id_u.sid.rid;
2701
2702	RDLOCK_CONFIG();
2703	s = (_idmapdstate.cfg->pgcfg.machine_sid) ?
2704	    strcasecmp(sidprefix, _idmapdstate.cfg->pgcfg.machine_sid) : 1;
2705	UNLOCK_CONFIG();
2706
2707	/*
2708	 * If the given sidprefix does not match machine_sid then this is
2709	 * not a local SID.
2710	 */
2711	if (s != 0)
2712		return (IDMAP_ERR_NOTFOUND);
2713
2714	switch (res->id.idtype) {
2715	case IDMAP_UID:
2716		if (rid < LOCALRID_UID_MIN || rid > LOCALRID_UID_MAX)
2717			return (IDMAP_ERR_ARG);
2718		res->id.idmap_id_u.uid = rid - LOCALRID_UID_MIN;
2719		break;
2720	case IDMAP_GID:
2721		if (rid < LOCALRID_GID_MIN)
2722			return (IDMAP_ERR_ARG);
2723		res->id.idmap_id_u.gid = rid - LOCALRID_GID_MIN;
2724		break;
2725	case IDMAP_POSIXID:
2726		if (rid >= LOCALRID_GID_MIN) {
2727			res->id.idmap_id_u.gid = rid - LOCALRID_GID_MIN;
2728			res->id.idtype = IDMAP_GID;
2729		} else if (rid >= LOCALRID_UID_MIN) {
2730			res->id.idmap_id_u.uid = rid - LOCALRID_UID_MIN;
2731			res->id.idtype = IDMAP_UID;
2732		} else {
2733			return (IDMAP_ERR_ARG);
2734		}
2735		break;
2736	default:
2737		return (IDMAP_ERR_NOTSUPPORTED);
2738	}
2739	res->info.how.map_type = IDMAP_MAP_TYPE_LOCAL_SID;
2740	res->info.src = IDMAP_MAP_SRC_ALGORITHMIC;
2741	return (IDMAP_SUCCESS);
2742}
2743
2744/*
2745 * Name service lookup by unixname to get pid
2746 */
2747static
2748idmap_retcode
2749ns_lookup_byname(const char *name, const char *lower_name, idmap_id *id)
2750{
2751	struct passwd	pwd, *pwdp;
2752	struct group	grp, *grpp;
2753	char		*buf;
2754	static size_t	pwdbufsiz = 0;
2755	static size_t	grpbufsiz = 0;
2756
2757	switch (id->idtype) {
2758	case IDMAP_UID:
2759		if (pwdbufsiz == 0)
2760			pwdbufsiz = sysconf(_SC_GETPW_R_SIZE_MAX);
2761		buf = alloca(pwdbufsiz);
2762		pwdp = getpwnam_r(name, &pwd, buf, pwdbufsiz);
2763		if (pwdp == NULL && errno == 0 && lower_name != NULL &&
2764		    name != lower_name && strcmp(name, lower_name) != 0)
2765			pwdp = getpwnam_r(lower_name, &pwd, buf, pwdbufsiz);
2766		if (pwdp == NULL) {
2767			if (errno == 0)
2768				return (IDMAP_ERR_NOTFOUND);
2769			else
2770				return (IDMAP_ERR_INTERNAL);
2771		}
2772		id->idmap_id_u.uid = pwd.pw_uid;
2773		break;
2774	case IDMAP_GID:
2775		if (grpbufsiz == 0)
2776			grpbufsiz = sysconf(_SC_GETGR_R_SIZE_MAX);
2777		buf = alloca(grpbufsiz);
2778		grpp = getgrnam_r(name, &grp, buf, grpbufsiz);
2779		if (grpp == NULL && errno == 0 && lower_name != NULL &&
2780		    name != lower_name && strcmp(name, lower_name) != 0)
2781			grpp = getgrnam_r(lower_name, &grp, buf, grpbufsiz);
2782		if (grpp == NULL) {
2783			if (errno == 0)
2784				return (IDMAP_ERR_NOTFOUND);
2785			else
2786				return (IDMAP_ERR_INTERNAL);
2787		}
2788		id->idmap_id_u.gid = grp.gr_gid;
2789		break;
2790	default:
2791		return (IDMAP_ERR_ARG);
2792	}
2793	return (IDMAP_SUCCESS);
2794}
2795
2796
2797/*
2798 * Name service lookup by pid to get unixname
2799 */
2800static
2801idmap_retcode
2802ns_lookup_bypid(uid_t pid, int is_user, char **unixname)
2803{
2804	struct passwd	pwd;
2805	struct group	grp;
2806	char		*buf;
2807	static size_t	pwdbufsiz = 0;
2808	static size_t	grpbufsiz = 0;
2809
2810	if (is_user) {
2811		if (pwdbufsiz == 0)
2812			pwdbufsiz = sysconf(_SC_GETPW_R_SIZE_MAX);
2813		buf = alloca(pwdbufsiz);
2814		errno = 0;
2815		if (getpwuid_r(pid, &pwd, buf, pwdbufsiz) == NULL) {
2816			if (errno == 0)
2817				return (IDMAP_ERR_NOTFOUND);
2818			else
2819				return (IDMAP_ERR_INTERNAL);
2820		}
2821		*unixname = strdup(pwd.pw_name);
2822	} else {
2823		if (grpbufsiz == 0)
2824			grpbufsiz = sysconf(_SC_GETGR_R_SIZE_MAX);
2825		buf = alloca(grpbufsiz);
2826		errno = 0;
2827		if (getgrgid_r(pid, &grp, buf, grpbufsiz) == NULL) {
2828			if (errno == 0)
2829				return (IDMAP_ERR_NOTFOUND);
2830			else
2831				return (IDMAP_ERR_INTERNAL);
2832		}
2833		*unixname = strdup(grp.gr_name);
2834	}
2835	if (*unixname == NULL)
2836		return (IDMAP_ERR_MEMORY);
2837	return (IDMAP_SUCCESS);
2838}
2839
2840/*
2841 * Name-based mapping
2842 *
2843 * Case 1: If no rule matches do ephemeral
2844 *
2845 * Case 2: If rule matches and unixname is "" then return no mapping.
2846 *
2847 * Case 3: If rule matches and unixname is specified then lookup name
2848 *  service using the unixname. If unixname not found then return no mapping.
2849 *
2850 * Case 4: If rule matches and unixname is * then lookup name service
2851 *  using winname as the unixname. If unixname not found then process
2852 *  other rules using the lookup order. If no other rule matches then do
2853 *  ephemeral. Otherwise, based on the matched rule do Case 2 or 3 or 4.
2854 *  This allows us to specify a fallback unixname per _domain_ or no mapping
2855 *  instead of the default behaviour of doing ephemeral mapping.
2856 *
2857 * Example 1:
2858 * *@sfbay == *
2859 * If looking up windows users foo@sfbay and foo does not exists in
2860 * the name service then foo@sfbay will be mapped to an ephemeral id.
2861 *
2862 * Example 2:
2863 * *@sfbay == *
2864 * *@sfbay => guest
2865 * If looking up windows users foo@sfbay and foo does not exists in
2866 * the name service then foo@sfbay will be mapped to guest.
2867 *
2868 * Example 3:
2869 * *@sfbay == *
2870 * *@sfbay => ""
2871 * If looking up windows users foo@sfbay and foo does not exists in
2872 * the name service then we will return no mapping for foo@sfbay.
2873 *
2874 */
2875static
2876idmap_retcode
2877name_based_mapping_sid2pid(lookup_state_t *state,
2878		idmap_mapping *req, idmap_id_res *res)
2879{
2880	const char	*unixname, *windomain;
2881	char		*sql = NULL, *errmsg = NULL, *lower_winname = NULL;
2882	idmap_retcode	retcode;
2883	char		*end, *lower_unixname, *winname;
2884	const char	**values;
2885	sqlite_vm	*vm = NULL;
2886	int		ncol, r, is_user, is_wuser;
2887	idmap_namerule	*rule = &res->info.how.idmap_how_u.rule;
2888	int		direction;
2889	const char	*me = "name_based_mapping_sid2pid";
2890
2891	assert(req->id1name != NULL); /* We have winname */
2892	assert(req->id2name == NULL); /* We don't have unixname */
2893
2894	winname = req->id1name;
2895	windomain = req->id1domain;
2896
2897	switch (req->id1.idtype) {
2898	case IDMAP_USID:
2899		is_wuser = 1;
2900		break;
2901	case IDMAP_GSID:
2902		is_wuser = 0;
2903		break;
2904	default:
2905		idmapdlog(LOG_ERR, "%s: Unable to determine if the "
2906		    "given Windows id is user or group.", me);
2907		return (IDMAP_ERR_INTERNAL);
2908	}
2909
2910	switch (res->id.idtype) {
2911	case IDMAP_UID:
2912		is_user = 1;
2913		break;
2914	case IDMAP_GID:
2915		is_user = 0;
2916		break;
2917	case IDMAP_POSIXID:
2918		is_user = is_wuser;
2919		res->id.idtype = is_user ? IDMAP_UID : IDMAP_GID;
2920		break;
2921	}
2922
2923	if (windomain == NULL)
2924		windomain = "";
2925
2926	if ((lower_winname = tolower_u8(winname)) == NULL)
2927		lower_winname = winname;    /* hope for the best */
2928	sql = sqlite_mprintf(
2929	    "SELECT unixname, u2w_order, winname_display, windomain, is_nt4 "
2930	    "FROM namerules WHERE "
2931	    "w2u_order > 0 AND is_user = %d AND is_wuser = %d AND "
2932	    "(winname = %Q OR winname = '*') AND "
2933	    "(windomain = %Q OR windomain = '*') "
2934	    "ORDER BY w2u_order ASC;",
2935	    is_user, is_wuser, lower_winname, windomain);
2936	if (sql == NULL) {
2937		idmapdlog(LOG_ERR, "Out of memory");
2938		retcode = IDMAP_ERR_MEMORY;
2939		goto out;
2940	}
2941
2942	if (sqlite_compile(state->db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
2943		retcode = IDMAP_ERR_INTERNAL;
2944		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
2945		    CHECK_NULL(errmsg));
2946		sqlite_freemem(errmsg);
2947		goto out;
2948	}
2949
2950	for (;;) {
2951		r = sqlite_step(vm, &ncol, &values, NULL);
2952		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
2953
2954		if (r == SQLITE_ROW) {
2955			if (ncol < 5) {
2956				retcode = IDMAP_ERR_INTERNAL;
2957				goto out;
2958			}
2959			if (values[0] == NULL) {
2960				retcode = IDMAP_ERR_INTERNAL;
2961				goto out;
2962			}
2963
2964			if (values[1] != NULL)
2965				direction =
2966				    (strtol(values[1], &end, 10) == 0)?
2967				    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
2968			else
2969				direction = IDMAP_DIRECTION_W2U;
2970
2971			if (EMPTY_NAME(values[0])) {
2972				idmap_namerule_set(rule, values[3], values[2],
2973				    values[0], is_user, is_wuser,
2974				    strtol(values[4], &end, 10),
2975				    direction);
2976				retcode = IDMAP_ERR_NOMAPPING;
2977				goto out;
2978			}
2979
2980			if (values[0][0] == '*') {
2981				unixname = winname;
2982				lower_unixname = lower_winname;
2983			} else {
2984				unixname = values[0];
2985				lower_unixname = NULL;
2986			}
2987
2988			retcode = ns_lookup_byname(unixname, lower_unixname,
2989			    &res->id);
2990			if (retcode == IDMAP_ERR_NOTFOUND) {
2991				if (values[0][0] == '*')
2992					/* Case 4 */
2993					continue;
2994				else {
2995					/* Case 3 */
2996					idmap_namerule_set(rule, values[3],
2997					    values[2], values[0], is_user,
2998					    is_wuser,
2999					    strtol(values[4], &end, 10),
3000					    direction);
3001					retcode = IDMAP_ERR_NOMAPPING;
3002				}
3003			}
3004			goto out;
3005		} else if (r == SQLITE_DONE) {
3006			retcode = IDMAP_ERR_NOTFOUND;
3007			goto out;
3008		} else {
3009			(void) sqlite_finalize(vm, &errmsg);
3010			vm = NULL;
3011			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
3012			    CHECK_NULL(errmsg));
3013			sqlite_freemem(errmsg);
3014			retcode = IDMAP_ERR_INTERNAL;
3015			goto out;
3016		}
3017	}
3018
3019out:
3020	if (sql != NULL)
3021		sqlite_freemem(sql);
3022	if (retcode == IDMAP_SUCCESS) {
3023		if (values[1] != NULL)
3024			res->direction =
3025			    (strtol(values[1], &end, 10) == 0)?
3026			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
3027		else
3028			res->direction = IDMAP_DIRECTION_W2U;
3029
3030		req->id2name = strdup(unixname);
3031		if (req->id2name == NULL) {
3032			retcode = IDMAP_ERR_MEMORY;
3033		}
3034	}
3035
3036	if (retcode == IDMAP_SUCCESS) {
3037		idmap_namerule_set(rule, values[3], values[2],
3038		    values[0], is_user, is_wuser, strtol(values[4], &end, 10),
3039		    res->direction);
3040	}
3041
3042	if (retcode != IDMAP_ERR_NOTFOUND) {
3043		res->info.how.map_type = IDMAP_MAP_TYPE_RULE_BASED;
3044		res->info.src = IDMAP_MAP_SRC_NEW;
3045	}
3046
3047	if (lower_winname != NULL && lower_winname != winname)
3048		free(lower_winname);
3049	if (vm != NULL)
3050		(void) sqlite_finalize(vm, NULL);
3051	return (retcode);
3052}
3053
3054static
3055int
3056get_next_eph_uid(uid_t *next_uid)
3057{
3058	uid_t uid;
3059	gid_t gid;
3060	int err;
3061
3062	*next_uid = (uid_t)-1;
3063	uid = _idmapdstate.next_uid++;
3064	if (uid >= _idmapdstate.limit_uid) {
3065		if ((err = allocids(0, 8192, &uid, 0, &gid)) != 0)
3066			return (err);
3067
3068		_idmapdstate.limit_uid = uid + 8192;
3069		_idmapdstate.next_uid = uid;
3070	}
3071	*next_uid = uid;
3072
3073	return (0);
3074}
3075
3076static
3077int
3078get_next_eph_gid(gid_t *next_gid)
3079{
3080	uid_t uid;
3081	gid_t gid;
3082	int err;
3083
3084	*next_gid = (uid_t)-1;
3085	gid = _idmapdstate.next_gid++;
3086	if (gid >= _idmapdstate.limit_gid) {
3087		if ((err = allocids(0, 0, &uid, 8192, &gid)) != 0)
3088			return (err);
3089
3090		_idmapdstate.limit_gid = gid + 8192;
3091		_idmapdstate.next_gid = gid;
3092	}
3093	*next_gid = gid;
3094
3095	return (0);
3096}
3097
3098static
3099int
3100gethash(const char *str, uint32_t num, uint_t htsize)
3101{
3102	uint_t  hval, i, len;
3103
3104	if (str == NULL)
3105		return (0);
3106	for (len = strlen(str), hval = 0, i = 0; i < len; i++) {
3107		hval += str[i];
3108		hval += (hval << 10);
3109		hval ^= (hval >> 6);
3110	}
3111	for (str = (const char *)&num, i = 0; i < sizeof (num); i++) {
3112		hval += str[i];
3113		hval += (hval << 10);
3114		hval ^= (hval >> 6);
3115	}
3116	hval += (hval << 3);
3117	hval ^= (hval >> 11);
3118	hval += (hval << 15);
3119	return (hval % htsize);
3120}
3121
3122static
3123int
3124get_from_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid,
3125		uid_t *pid)
3126{
3127	uint_t		next, key;
3128	uint_t		htsize = state->sid_history_size;
3129	idmap_sid	*sid;
3130
3131	next = gethash(prefix, rid, htsize);
3132	while (next != htsize) {
3133		key = state->sid_history[next].key;
3134		if (key == htsize)
3135			return (0);
3136		sid = &state->batch->idmap_mapping_batch_val[key].id1.
3137		    idmap_id_u.sid;
3138		if (sid->rid == rid && strcmp(sid->prefix, prefix) == 0) {
3139			*pid = state->result->ids.ids_val[key].id.
3140			    idmap_id_u.uid;
3141			return (1);
3142		}
3143		next = state->sid_history[next].next;
3144	}
3145	return (0);
3146}
3147
3148static
3149void
3150add_to_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid)
3151{
3152	uint_t		hash, next;
3153	uint_t		htsize = state->sid_history_size;
3154
3155	hash = next = gethash(prefix, rid, htsize);
3156	while (state->sid_history[next].key != htsize) {
3157		next++;
3158		next %= htsize;
3159	}
3160	state->sid_history[next].key = state->curpos;
3161	if (hash == next)
3162		return;
3163	state->sid_history[next].next = state->sid_history[hash].next;
3164	state->sid_history[hash].next = next;
3165}
3166
3167void
3168cleanup_lookup_state(lookup_state_t *state)
3169{
3170	free(state->sid_history);
3171	free(state->ad_unixuser_attr);
3172	free(state->ad_unixgroup_attr);
3173	free(state->nldap_winname_attr);
3174	free(state->defdom);
3175}
3176
3177/* ARGSUSED */
3178static
3179idmap_retcode
3180dynamic_ephemeral_mapping(lookup_state_t *state,
3181		idmap_mapping *req, idmap_id_res *res)
3182{
3183
3184	uid_t		next_pid;
3185
3186	res->direction = IDMAP_DIRECTION_BI;
3187
3188	if (IDMAP_ID_IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
3189		res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
3190		res->info.src = IDMAP_MAP_SRC_CACHE;
3191		return (IDMAP_SUCCESS);
3192	}
3193
3194	if (state->sid_history != NULL &&
3195	    get_from_sid_history(state, req->id1.idmap_id_u.sid.prefix,
3196	    req->id1.idmap_id_u.sid.rid, &next_pid)) {
3197		res->id.idmap_id_u.uid = next_pid;
3198		res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
3199		res->info.src = IDMAP_MAP_SRC_NEW;
3200		return (IDMAP_SUCCESS);
3201	}
3202
3203	if (res->id.idtype == IDMAP_UID) {
3204		if (get_next_eph_uid(&next_pid) != 0)
3205			return (IDMAP_ERR_INTERNAL);
3206		res->id.idmap_id_u.uid = next_pid;
3207	} else {
3208		if (get_next_eph_gid(&next_pid) != 0)
3209			return (IDMAP_ERR_INTERNAL);
3210		res->id.idmap_id_u.gid = next_pid;
3211	}
3212
3213	res->info.how.map_type = IDMAP_MAP_TYPE_EPHEMERAL;
3214	res->info.src = IDMAP_MAP_SRC_NEW;
3215	if (state->sid_history != NULL)
3216		add_to_sid_history(state, req->id1.idmap_id_u.sid.prefix,
3217		    req->id1.idmap_id_u.sid.rid);
3218
3219	return (IDMAP_SUCCESS);
3220}
3221
3222idmap_retcode
3223sid2pid_second_pass(lookup_state_t *state,
3224		idmap_mapping *req, idmap_id_res *res)
3225{
3226	idmap_retcode	retcode;
3227
3228	/* Check if second pass is needed */
3229	if (ARE_WE_DONE(req->direction))
3230		return (res->retcode);
3231
3232	/* Get status from previous pass */
3233	retcode = res->retcode;
3234	if (retcode != IDMAP_SUCCESS && state->eph_map_unres_sids &&
3235	    !EMPTY_STRING(req->id1.idmap_id_u.sid.prefix) &&
3236	    EMPTY_STRING(req->id1name)) {
3237		/*
3238		 * We are asked to map an unresolvable SID to a UID or
3239		 * GID, but, which?  We'll treat all unresolvable SIDs
3240		 * as users unless the caller specified which of a UID
3241		 * or GID they want.
3242		 */
3243		if (req->id1.idtype == IDMAP_SID)
3244			req->id1.idtype = IDMAP_USID;
3245		if (res->id.idtype == IDMAP_POSIXID)
3246			res->id.idtype = IDMAP_UID;
3247		goto do_eph;
3248	}
3249	if (retcode != IDMAP_SUCCESS)
3250		goto out;
3251
3252	/*
3253	 * There are two ways we might get here with a Posix ID:
3254	 * - It could be from an expired ephemeral cache entry.
3255	 * - It could be from IDMU.
3256	 * If it's from IDMU, we need to look up the name, for name-based
3257	 * requests and the cache.
3258	 */
3259	if (!IDMAP_ID_IS_EPHEMERAL(res->id.idmap_id_u.uid) &&
3260	    res->id.idmap_id_u.uid != IDMAP_SENTINEL_PID) {
3261		if (req->id2name == NULL) {
3262			/*
3263			 * If the lookup fails, go ahead anyway.
3264			 * The general UNIX rule is that it's OK to
3265			 * have a UID or GID that isn't in the
3266			 * name service.
3267			 */
3268			(void) ns_lookup_bypid(res->id.idmap_id_u.uid,
3269			    res->id.idtype == IDMAP_UID, &req->id2name);
3270		}
3271		goto out;
3272	}
3273
3274	/*
3275	 * If directory-based name mapping is enabled then the unixname
3276	 * may already have been retrieved from the AD object (AD-mode or
3277	 * mixed-mode) or from native LDAP object (nldap-mode) -- done.
3278	 */
3279	if (req->id2name != NULL) {
3280		assert(res->id.idtype != IDMAP_POSIXID);
3281		if (AD_MODE(res->id.idtype, state))
3282			res->direction = IDMAP_DIRECTION_BI;
3283		else if (NLDAP_MODE(res->id.idtype, state))
3284			res->direction = IDMAP_DIRECTION_BI;
3285		else if (MIXED_MODE(res->id.idtype, state))
3286			res->direction = IDMAP_DIRECTION_W2U;
3287
3288		/*
3289		 * Special case: (1) If the ad_unixuser_attr and
3290		 * ad_unixgroup_attr uses the same attribute
3291		 * name and (2) if this is a diagonal mapping
3292		 * request and (3) the unixname has been retrieved
3293		 * from the AD object -- then we ignore it and fallback
3294		 * to name-based mapping rules and ephemeral mapping
3295		 *
3296		 * Example:
3297		 *  Properties:
3298		 *    config/ad_unixuser_attr = "unixname"
3299		 *    config/ad_unixgroup_attr = "unixname"
3300		 *  AD user object:
3301		 *    dn: cn=bob ...
3302		 *    objectclass: user
3303		 *    sam: bob
3304		 *    unixname: bob1234
3305		 *  AD group object:
3306		 *    dn: cn=winadmins ...
3307		 *    objectclass: group
3308		 *    sam: winadmins
3309		 *    unixname: unixadmins
3310		 *
3311		 *  In this example whether "unixname" refers to a unixuser
3312		 *  or unixgroup depends upon the AD object.
3313		 *
3314		 * $idmap show -c winname:bob gid
3315		 *    AD lookup by "samAccountName=bob" for
3316		 *    "ad_unixgroup_attr (i.e unixname)" for directory-based
3317		 *    mapping would get "bob1234" which is not what we want.
3318		 *    Now why not getgrnam_r("bob1234") and use it if it
3319		 *    is indeed a unixgroup? That's because Unix can have
3320		 *    users and groups with the same name and we clearly
3321		 *    don't know the intention of the admin here.
3322		 *    Therefore we ignore this and fallback to name-based
3323		 *    mapping rules or ephemeral mapping.
3324		 */
3325		if ((AD_MODE(res->id.idtype, state) ||
3326		    MIXED_MODE(res->id.idtype, state)) &&
3327		    state->ad_unixuser_attr != NULL &&
3328		    state->ad_unixgroup_attr != NULL &&
3329		    strcasecmp(state->ad_unixuser_attr,
3330		    state->ad_unixgroup_attr) == 0 &&
3331		    ((req->id1.idtype == IDMAP_USID &&
3332		    res->id.idtype == IDMAP_GID) ||
3333		    (req->id1.idtype == IDMAP_GSID &&
3334		    res->id.idtype == IDMAP_UID))) {
3335			free(req->id2name);
3336			req->id2name = NULL;
3337			res->id.idmap_id_u.uid = IDMAP_SENTINEL_PID;
3338			/* fallback */
3339		} else {
3340			if (res->id.idmap_id_u.uid == IDMAP_SENTINEL_PID)
3341				retcode = ns_lookup_byname(req->id2name,
3342				    NULL, &res->id);
3343			/*
3344			 * If ns_lookup_byname() fails that means the
3345			 * unixname (req->id2name), which was obtained
3346			 * from the AD object by directory-based mapping,
3347			 * is not a valid Unix user/group and therefore
3348			 * we return the error to the client instead of
3349			 * doing rule-based mapping or ephemeral mapping.
3350			 * This way the client can detect the issue.
3351			 */
3352			goto out;
3353		}
3354	}
3355
3356	/* Free any mapping info from Directory based mapping */
3357	if (res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN)
3358		idmap_info_free(&res->info);
3359
3360	/*
3361	 * If we don't have unixname then evaluate local name-based
3362	 * mapping rules.
3363	 */
3364	retcode = name_based_mapping_sid2pid(state, req, res);
3365	if (retcode != IDMAP_ERR_NOTFOUND)
3366		goto out;
3367
3368do_eph:
3369	/* If not found, do ephemeral mapping */
3370	retcode = dynamic_ephemeral_mapping(state, req, res);
3371
3372out:
3373	res->retcode = idmap_stat4prot(retcode);
3374	if (res->retcode != IDMAP_SUCCESS) {
3375		req->direction = _IDMAP_F_DONE;
3376		res->id.idmap_id_u.uid = UID_NOBODY;
3377	}
3378	if (!ARE_WE_DONE(req->direction))
3379		state->sid2pid_done = FALSE;
3380	return (retcode);
3381}
3382
3383idmap_retcode
3384update_cache_pid2sid(lookup_state_t *state,
3385		idmap_mapping *req, idmap_id_res *res)
3386{
3387	char		*sql = NULL;
3388	idmap_retcode	retcode;
3389	char		*map_dn = NULL;
3390	char		*map_attr = NULL;
3391	char		*map_value = NULL;
3392	char 		*map_windomain = NULL;
3393	char		*map_winname = NULL;
3394	char		*map_unixname = NULL;
3395	int		map_is_nt4 = FALSE;
3396
3397	/* Check if we need to cache anything */
3398	if (ARE_WE_DONE(req->direction))
3399		return (IDMAP_SUCCESS);
3400
3401	/* We don't cache negative entries */
3402	if (res->retcode != IDMAP_SUCCESS)
3403		return (IDMAP_SUCCESS);
3404
3405	assert(res->direction != IDMAP_DIRECTION_UNDEF);
3406	assert(req->id1.idmap_id_u.uid != IDMAP_SENTINEL_PID);
3407	assert(res->id.idtype != IDMAP_SID);
3408
3409	/*
3410	 * If we've gotten to this point and we *still* don't know the
3411	 * unixname, well, we'd like to have it now for the cache.
3412	 *
3413	 * If we truly always need it for the cache, we should probably
3414	 * look it up once at the beginning, rather than "at need" in
3415	 * several places as is now done.  However, it's not really clear
3416	 * that we *do* need it in the cache; there's a decent argument
3417	 * that the cache should contain only SIDs and PIDs, so we'll
3418	 * leave our options open by doing it "at need" here too.
3419	 *
3420	 * If we can't find it... c'est la vie.
3421	 */
3422	if (req->id1name == NULL) {
3423		(void) ns_lookup_bypid(req->id1.idmap_id_u.uid,
3424		    req->id1.idtype == IDMAP_UID, &req->id1name);
3425	}
3426
3427	assert(res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN);
3428	switch (res->info.how.map_type) {
3429	case IDMAP_MAP_TYPE_DS_AD:
3430		map_dn = res->info.how.idmap_how_u.ad.dn;
3431		map_attr = res->info.how.idmap_how_u.ad.attr;
3432		map_value = res->info.how.idmap_how_u.ad.value;
3433		break;
3434
3435	case IDMAP_MAP_TYPE_DS_NLDAP:
3436		map_dn = res->info.how.idmap_how_u.nldap.dn;
3437		map_attr = res->info.how.idmap_how_u.nldap.attr;
3438		map_value = res->info.how.idmap_how_u.nldap.value;
3439		break;
3440
3441	case IDMAP_MAP_TYPE_RULE_BASED:
3442		map_windomain = res->info.how.idmap_how_u.rule.windomain;
3443		map_winname = res->info.how.idmap_how_u.rule.winname;
3444		map_unixname = res->info.how.idmap_how_u.rule.unixname;
3445		map_is_nt4 = res->info.how.idmap_how_u.rule.is_nt4;
3446		break;
3447
3448	case IDMAP_MAP_TYPE_EPHEMERAL:
3449		break;
3450
3451	case IDMAP_MAP_TYPE_LOCAL_SID:
3452		break;
3453
3454	case IDMAP_MAP_TYPE_IDMU:
3455		map_dn = res->info.how.idmap_how_u.idmu.dn;
3456		map_attr = res->info.how.idmap_how_u.idmu.attr;
3457		map_value = res->info.how.idmap_how_u.idmu.value;
3458		break;
3459
3460	default:
3461		/* Dont cache other mapping types */
3462		assert(FALSE);
3463	}
3464
3465	/*
3466	 * Using NULL for u2w instead of 0 so that our trigger allows
3467	 * the same pid to be the destination in multiple entries
3468	 */
3469	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
3470	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
3471	    "is_user, is_wuser, expiration, w2u, u2w, "
3472	    "map_type, map_dn, map_attr, map_value, map_windomain, "
3473	    "map_winname, map_unixname, map_is_nt4) "
3474	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
3475	    "strftime('%%s','now') + 600, %q, 1, "
3476	    "%d, %Q, %Q, %Q, %Q, %Q, %Q, %d); ",
3477	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
3478	    req->id2domain, req->id2name, req->id1.idmap_id_u.uid,
3479	    req->id1name, (req->id1.idtype == IDMAP_UID) ? 1 : 0,
3480	    (res->id.idtype == IDMAP_USID) ? 1 : 0,
3481	    (res->direction == 0) ? "1" : NULL,
3482	    res->info.how.map_type, map_dn, map_attr, map_value,
3483	    map_windomain, map_winname, map_unixname, map_is_nt4);
3484
3485	if (sql == NULL) {
3486		retcode = IDMAP_ERR_INTERNAL;
3487		idmapdlog(LOG_ERR, "Out of memory");
3488		goto out;
3489	}
3490
3491	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
3492	if (retcode != IDMAP_SUCCESS)
3493		goto out;
3494
3495	state->pid2sid_done = FALSE;
3496	sqlite_freemem(sql);
3497	sql = NULL;
3498
3499	/* Check if we need to update namecache */
3500	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
3501		goto out;
3502
3503	if (req->id2name == NULL)
3504		goto out;
3505
3506	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
3507	    "(sidprefix, rid, canon_name, domain, type, expiration) "
3508	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
3509	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
3510	    req->id2name, req->id2domain,
3511	    (res->id.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
3512
3513	if (sql == NULL) {
3514		retcode = IDMAP_ERR_INTERNAL;
3515		idmapdlog(LOG_ERR, "Out of memory");
3516		goto out;
3517	}
3518
3519	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
3520
3521out:
3522	if (!(req->flag & IDMAP_REQ_FLG_MAPPING_INFO))
3523		idmap_info_free(&res->info);
3524	if (sql != NULL)
3525		sqlite_freemem(sql);
3526	return (retcode);
3527}
3528
3529idmap_retcode
3530update_cache_sid2pid(lookup_state_t *state,
3531		idmap_mapping *req, idmap_id_res *res)
3532{
3533	char		*sql = NULL;
3534	idmap_retcode	retcode;
3535	int		is_eph_user;
3536	char		*map_dn = NULL;
3537	char		*map_attr = NULL;
3538	char		*map_value = NULL;
3539	char 		*map_windomain = NULL;
3540	char		*map_winname = NULL;
3541	char		*map_unixname = NULL;
3542	int		map_is_nt4 = FALSE;
3543
3544	/* Check if we need to cache anything */
3545	if (ARE_WE_DONE(req->direction))
3546		return (IDMAP_SUCCESS);
3547
3548	/* We don't cache negative entries */
3549	if (res->retcode != IDMAP_SUCCESS)
3550		return (IDMAP_SUCCESS);
3551
3552	if (req->direction & _IDMAP_F_EXP_EPH_UID)
3553		is_eph_user = 1;
3554	else if (req->direction & _IDMAP_F_EXP_EPH_GID)
3555		is_eph_user = 0;
3556	else
3557		is_eph_user = -1;
3558
3559	if (is_eph_user >= 0 &&
3560	    !IDMAP_ID_IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
3561		sql = sqlite_mprintf("UPDATE idmap_cache "
3562		    "SET w2u = 0 WHERE "
3563		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
3564		    "pid >= 2147483648 AND is_user = %d;",
3565		    req->id1.idmap_id_u.sid.prefix,
3566		    req->id1.idmap_id_u.sid.rid,
3567		    is_eph_user);
3568		if (sql == NULL) {
3569			retcode = IDMAP_ERR_INTERNAL;
3570			idmapdlog(LOG_ERR, "Out of memory");
3571			goto out;
3572		}
3573
3574		retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
3575		if (retcode != IDMAP_SUCCESS)
3576			goto out;
3577
3578		sqlite_freemem(sql);
3579		sql = NULL;
3580	}
3581
3582	assert(res->direction != IDMAP_DIRECTION_UNDEF);
3583	assert(res->id.idmap_id_u.uid != IDMAP_SENTINEL_PID);
3584
3585	switch (res->info.how.map_type) {
3586	case IDMAP_MAP_TYPE_DS_AD:
3587		map_dn = res->info.how.idmap_how_u.ad.dn;
3588		map_attr = res->info.how.idmap_how_u.ad.attr;
3589		map_value = res->info.how.idmap_how_u.ad.value;
3590		break;
3591
3592	case IDMAP_MAP_TYPE_DS_NLDAP:
3593		map_dn = res->info.how.idmap_how_u.nldap.dn;
3594		map_attr = res->info.how.idmap_how_u.ad.attr;
3595		map_value = res->info.how.idmap_how_u.nldap.value;
3596		break;
3597
3598	case IDMAP_MAP_TYPE_RULE_BASED:
3599		map_windomain = res->info.how.idmap_how_u.rule.windomain;
3600		map_winname = res->info.how.idmap_how_u.rule.winname;
3601		map_unixname = res->info.how.idmap_how_u.rule.unixname;
3602		map_is_nt4 = res->info.how.idmap_how_u.rule.is_nt4;
3603		break;
3604
3605	case IDMAP_MAP_TYPE_EPHEMERAL:
3606		break;
3607
3608	case IDMAP_MAP_TYPE_IDMU:
3609		map_dn = res->info.how.idmap_how_u.idmu.dn;
3610		map_attr = res->info.how.idmap_how_u.idmu.attr;
3611		map_value = res->info.how.idmap_how_u.idmu.value;
3612		break;
3613
3614	default:
3615		/* Dont cache other mapping types */
3616		assert(FALSE);
3617	}
3618
3619	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
3620	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
3621	    "is_user, is_wuser, expiration, w2u, u2w, "
3622	    "map_type, map_dn, map_attr, map_value, map_windomain, "
3623	    "map_winname, map_unixname, map_is_nt4) "
3624	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
3625	    "strftime('%%s','now') + 600, 1, %q, "
3626	    "%d, %Q, %Q, %Q, %Q, %Q, %Q, %d);",
3627	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
3628	    (req->id1domain != NULL) ? req->id1domain : "", req->id1name,
3629	    res->id.idmap_id_u.uid, req->id2name,
3630	    (res->id.idtype == IDMAP_UID) ? 1 : 0,
3631	    (req->id1.idtype == IDMAP_USID) ? 1 : 0,
3632	    (res->direction == 0) ? "1" : NULL,
3633	    res->info.how.map_type, map_dn, map_attr, map_value,
3634	    map_windomain, map_winname, map_unixname, map_is_nt4);
3635
3636	if (sql == NULL) {
3637		retcode = IDMAP_ERR_INTERNAL;
3638		idmapdlog(LOG_ERR, "Out of memory");
3639		goto out;
3640	}
3641
3642	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
3643	if (retcode != IDMAP_SUCCESS)
3644		goto out;
3645
3646	state->sid2pid_done = FALSE;
3647	sqlite_freemem(sql);
3648	sql = NULL;
3649
3650	/* Check if we need to update namecache */
3651	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
3652		goto out;
3653
3654	if (EMPTY_STRING(req->id1name))
3655		goto out;
3656
3657	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
3658	    "(sidprefix, rid, canon_name, domain, type, expiration) "
3659	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
3660	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
3661	    req->id1name, req->id1domain,
3662	    (req->id1.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
3663
3664	if (sql == NULL) {
3665		retcode = IDMAP_ERR_INTERNAL;
3666		idmapdlog(LOG_ERR, "Out of memory");
3667		goto out;
3668	}
3669
3670	retcode = sql_exec_no_cb(state->cache, IDMAP_CACHENAME, sql);
3671
3672out:
3673	if (!(req->flag & IDMAP_REQ_FLG_MAPPING_INFO))
3674		idmap_info_free(&res->info);
3675
3676	if (sql != NULL)
3677		sqlite_freemem(sql);
3678	return (retcode);
3679}
3680
3681static
3682idmap_retcode
3683lookup_cache_pid2sid(sqlite *cache, idmap_mapping *req, idmap_id_res *res,
3684		int is_user)
3685{
3686	char		*end;
3687	char		*sql = NULL;
3688	const char	**values;
3689	sqlite_vm	*vm = NULL;
3690	int		ncol;
3691	idmap_retcode	retcode = IDMAP_SUCCESS;
3692	time_t		curtime;
3693	idmap_id_type	idtype;
3694
3695	/* Current time */
3696	errno = 0;
3697	if ((curtime = time(NULL)) == (time_t)-1) {
3698		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
3699		    strerror(errno));
3700		retcode = IDMAP_ERR_INTERNAL;
3701		goto out;
3702	}
3703
3704	/* SQL to lookup the cache by pid or by unixname */
3705	if (req->id1.idmap_id_u.uid != IDMAP_SENTINEL_PID) {
3706		sql = sqlite_mprintf("SELECT sidprefix, rid, "
3707		    "canon_winname, windomain, w2u, is_wuser, "
3708		    "map_type, map_dn, map_attr, map_value, map_windomain, "
3709		    "map_winname, map_unixname, map_is_nt4 "
3710		    "FROM idmap_cache WHERE "
3711		    "pid = %u AND u2w = 1 AND is_user = %d AND "
3712		    "(pid >= 2147483648 OR "
3713		    "(expiration = 0 OR expiration ISNULL OR "
3714		    "expiration > %d));",
3715		    req->id1.idmap_id_u.uid, is_user, curtime);
3716	} else if (req->id1name != NULL) {
3717		sql = sqlite_mprintf("SELECT sidprefix, rid, "
3718		    "canon_winname, windomain, w2u, is_wuser, "
3719		    "map_type, map_dn, map_attr, map_value, map_windomain, "
3720		    "map_winname, map_unixname, map_is_nt4 "
3721		    "FROM idmap_cache WHERE "
3722		    "unixname = %Q AND u2w = 1 AND is_user = %d AND "
3723		    "(pid >= 2147483648 OR "
3724		    "(expiration = 0 OR expiration ISNULL OR "
3725		    "expiration > %d));",
3726		    req->id1name, is_user, curtime);
3727	} else {
3728		retcode = IDMAP_ERR_ARG;
3729		goto out;
3730	}
3731
3732	if (sql == NULL) {
3733		idmapdlog(LOG_ERR, "Out of memory");
3734		retcode = IDMAP_ERR_MEMORY;
3735		goto out;
3736	}
3737	retcode = sql_compile_n_step_once(
3738	    cache, sql, &vm, &ncol, 14, &values);
3739	sqlite_freemem(sql);
3740
3741	if (retcode == IDMAP_ERR_NOTFOUND)
3742		goto out;
3743	else if (retcode == IDMAP_SUCCESS) {
3744		/* sanity checks */
3745		if (values[0] == NULL || values[1] == NULL) {
3746			retcode = IDMAP_ERR_CACHE;
3747			goto out;
3748		}
3749
3750		switch (res->id.idtype) {
3751		case IDMAP_SID:
3752		case IDMAP_USID:
3753		case IDMAP_GSID:
3754			idtype = strtol(values[5], &end, 10) == 1
3755			    ? IDMAP_USID : IDMAP_GSID;
3756
3757			if (res->id.idtype == IDMAP_USID &&
3758			    idtype != IDMAP_USID) {
3759				retcode = IDMAP_ERR_NOTUSER;
3760				goto out;
3761			} else if (res->id.idtype == IDMAP_GSID &&
3762			    idtype != IDMAP_GSID) {
3763				retcode = IDMAP_ERR_NOTGROUP;
3764				goto out;
3765			}
3766			res->id.idtype = idtype;
3767
3768			res->id.idmap_id_u.sid.rid =
3769			    strtoul(values[1], &end, 10);
3770			res->id.idmap_id_u.sid.prefix = strdup(values[0]);
3771			if (res->id.idmap_id_u.sid.prefix == NULL) {
3772				idmapdlog(LOG_ERR, "Out of memory");
3773				retcode = IDMAP_ERR_MEMORY;
3774				goto out;
3775			}
3776
3777			if (values[4] != NULL)
3778				res->direction =
3779				    (strtol(values[4], &end, 10) == 0)?
3780				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
3781			else
3782				res->direction = IDMAP_DIRECTION_U2W;
3783
3784			if (values[2] == NULL)
3785				break;
3786			req->id2name = strdup(values[2]);
3787			if (req->id2name == NULL) {
3788				idmapdlog(LOG_ERR, "Out of memory");
3789				retcode = IDMAP_ERR_MEMORY;
3790				goto out;
3791			}
3792
3793			if (values[3] == NULL)
3794				break;
3795			req->id2domain = strdup(values[3]);
3796			if (req->id2domain == NULL) {
3797				idmapdlog(LOG_ERR, "Out of memory");
3798				retcode = IDMAP_ERR_MEMORY;
3799				goto out;
3800			}
3801
3802			break;
3803		default:
3804			retcode = IDMAP_ERR_NOTSUPPORTED;
3805			break;
3806		}
3807		if (req->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
3808			res->info.src = IDMAP_MAP_SRC_CACHE;
3809			res->info.how.map_type = strtoul(values[6], &end, 10);
3810			switch (res->info.how.map_type) {
3811			case IDMAP_MAP_TYPE_DS_AD:
3812				res->info.how.idmap_how_u.ad.dn =
3813				    strdup(values[7]);
3814				res->info.how.idmap_how_u.ad.attr =
3815				    strdup(values[8]);
3816				res->info.how.idmap_how_u.ad.value =
3817				    strdup(values[9]);
3818				break;
3819
3820			case IDMAP_MAP_TYPE_DS_NLDAP:
3821				res->info.how.idmap_how_u.nldap.dn =
3822				    strdup(values[7]);
3823				res->info.how.idmap_how_u.nldap.attr =
3824				    strdup(values[8]);
3825				res->info.how.idmap_how_u.nldap.value =
3826				    strdup(values[9]);
3827				break;
3828
3829			case IDMAP_MAP_TYPE_RULE_BASED:
3830				res->info.how.idmap_how_u.rule.windomain =
3831				    strdup(values[10]);
3832				res->info.how.idmap_how_u.rule.winname =
3833				    strdup(values[11]);
3834				res->info.how.idmap_how_u.rule.unixname =
3835				    strdup(values[12]);
3836				res->info.how.idmap_how_u.rule.is_nt4 =
3837				    strtoul(values[13], &end, 10);
3838				res->info.how.idmap_how_u.rule.is_user =
3839				    is_user;
3840				res->info.how.idmap_how_u.rule.is_wuser =
3841				    strtol(values[5], &end, 10);
3842				break;
3843
3844			case IDMAP_MAP_TYPE_EPHEMERAL:
3845				break;
3846
3847			case IDMAP_MAP_TYPE_LOCAL_SID:
3848				break;
3849
3850			case IDMAP_MAP_TYPE_KNOWN_SID:
3851				break;
3852
3853			case IDMAP_MAP_TYPE_IDMU:
3854				res->info.how.idmap_how_u.idmu.dn =
3855				    strdup(values[7]);
3856				res->info.how.idmap_how_u.idmu.attr =
3857				    strdup(values[8]);
3858				res->info.how.idmap_how_u.idmu.value =
3859				    strdup(values[9]);
3860				break;
3861
3862			default:
3863				/* Unknown mapping type */
3864				assert(FALSE);
3865			}
3866		}
3867	}
3868
3869out:
3870	if (vm != NULL)
3871		(void) sqlite_finalize(vm, NULL);
3872	return (retcode);
3873}
3874
3875/*
3876 * Given:
3877 * cache	sqlite handle
3878 * name		Windows user name
3879 * domain	Windows domain name
3880 *
3881 * Return:  Error code
3882 *
3883 * *canonname	Canonical name (if canonname is non-NULL) [1]
3884 * *sidprefix	SID prefix [1]
3885 * *rid		RID
3886 * *type	Type of name
3887 *
3888 * [1] malloc'ed, NULL on error
3889 */
3890static
3891idmap_retcode
3892lookup_cache_name2sid(sqlite *cache, const char *name, const char *domain,
3893	char **canonname, char **sidprefix, idmap_rid_t *rid, int *type)
3894{
3895	char		*end, *lower_name;
3896	char		*sql;
3897	const char	**values;
3898	sqlite_vm	*vm = NULL;
3899	int		ncol;
3900	time_t		curtime;
3901	idmap_retcode	retcode;
3902
3903	*sidprefix = NULL;
3904	if (canonname != NULL)
3905		*canonname = NULL;
3906
3907	/* Get current time */
3908	errno = 0;
3909	if ((curtime = time(NULL)) == (time_t)-1) {
3910		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
3911		    strerror(errno));
3912		retcode = IDMAP_ERR_INTERNAL;
3913		goto out;
3914	}
3915
3916	/* SQL to lookup the cache */
3917	if ((lower_name = tolower_u8(name)) == NULL)
3918		lower_name = (char *)name;
3919	sql = sqlite_mprintf("SELECT sidprefix, rid, type, canon_name "
3920	    "FROM name_cache WHERE name = %Q AND domain = %Q AND "
3921	    "(expiration = 0 OR expiration ISNULL OR "
3922	    "expiration > %d);", lower_name, domain, curtime);
3923	if (lower_name != name)
3924		free(lower_name);
3925	if (sql == NULL) {
3926		idmapdlog(LOG_ERR, "Out of memory");
3927		retcode = IDMAP_ERR_MEMORY;
3928		goto out;
3929	}
3930	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 4, &values);
3931
3932	sqlite_freemem(sql);
3933
3934	if (retcode != IDMAP_SUCCESS)
3935		goto out;
3936
3937	if (type != NULL) {
3938		if (values[2] == NULL) {
3939			retcode = IDMAP_ERR_CACHE;
3940			goto out;
3941		}
3942		*type = strtol(values[2], &end, 10);
3943	}
3944
3945	if (values[0] == NULL || values[1] == NULL) {
3946		retcode = IDMAP_ERR_CACHE;
3947		goto out;
3948	}
3949
3950	if (canonname != NULL) {
3951		assert(values[3] != NULL);
3952		*canonname = strdup(values[3]);
3953		if (*canonname == NULL) {
3954			idmapdlog(LOG_ERR, "Out of memory");
3955			retcode = IDMAP_ERR_MEMORY;
3956			goto out;
3957		}
3958	}
3959
3960	*sidprefix = strdup(values[0]);
3961	if (*sidprefix == NULL) {
3962		idmapdlog(LOG_ERR, "Out of memory");
3963		retcode = IDMAP_ERR_MEMORY;
3964		goto out;
3965	}
3966	*rid = strtoul(values[1], &end, 10);
3967
3968	retcode = IDMAP_SUCCESS;
3969
3970out:
3971	if (vm != NULL)
3972		(void) sqlite_finalize(vm, NULL);
3973
3974	if (retcode != IDMAP_SUCCESS) {
3975		free(*sidprefix);
3976		*sidprefix = NULL;
3977		if (canonname != NULL) {
3978			free(*canonname);
3979			*canonname = NULL;
3980		}
3981	}
3982	return (retcode);
3983}
3984
3985static
3986idmap_retcode
3987ad_lookup_by_winname(lookup_state_t *state,
3988		const char *name, const char *domain, int eunixtype,
3989		char **dn, char **attr, char **value, char **canonname,
3990		char **sidprefix, idmap_rid_t *rid, int *wintype,
3991		char **unixname)
3992{
3993	int			retries;
3994	idmap_query_state_t	*qs = NULL;
3995	idmap_retcode		rc, retcode;
3996	int			i;
3997	int			found_ad = 0;
3998
3999	RDLOCK_CONFIG();
4000	if (_idmapdstate.num_gcs > 0) {
4001		for (i = 0; i < _idmapdstate.num_gcs && !found_ad; i++) {
4002			retries = 0;
4003retry:
4004			retcode = idmap_lookup_batch_start(
4005			    _idmapdstate.gcs[i],
4006			    1,
4007			    _idmapdstate.cfg->pgcfg.directory_based_mapping,
4008			    _idmapdstate.cfg->pgcfg.default_domain,
4009			    &qs);
4010			if (retcode != IDMAP_SUCCESS) {
4011				if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
4012				    retries++ < ADUTILS_DEF_NUM_RETRIES)
4013					goto retry;
4014				degrade_svc(1, "failed to create request for "
4015				    "AD lookup by winname");
4016				return (retcode);
4017			}
4018
4019			restore_svc();
4020
4021			if (state != NULL && i == 0) {
4022				/*
4023				 * Directory based name mapping is only
4024				 * performed within the joined forest (i == 0).
4025				 * We don't trust other "trusted" forests to
4026				 * provide DS-based name mapping information
4027				 * because AD's definition of "cross-forest
4028				 * trust" does not encompass this sort of
4029				 * behavior.
4030				 */
4031				idmap_lookup_batch_set_unixattr(qs,
4032				    state->ad_unixuser_attr,
4033				    state->ad_unixgroup_attr);
4034			}
4035
4036			retcode = idmap_name2sid_batch_add1(qs, name, domain,
4037			    eunixtype, dn, attr, value, canonname, sidprefix,
4038			    rid, wintype, unixname, NULL, &rc);
4039			if (retcode == IDMAP_ERR_DOMAIN_NOTFOUND) {
4040				idmap_lookup_release_batch(&qs);
4041				continue;
4042			}
4043			found_ad = 1;
4044			if (retcode != IDMAP_SUCCESS)
4045				idmap_lookup_release_batch(&qs);
4046			else
4047				retcode = idmap_lookup_batch_end(&qs);
4048
4049			if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR &&
4050			    retries++ < ADUTILS_DEF_NUM_RETRIES)
4051				goto retry;
4052			else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
4053				degrade_svc(1,
4054				    "some AD lookups timed out repeatedly");
4055		}
4056	} else {
4057		/* No AD case */
4058		retcode = IDMAP_ERR_NO_ACTIVEDIRECTORY;
4059	}
4060	UNLOCK_CONFIG();
4061
4062	if (retcode != IDMAP_SUCCESS) {
4063		idmapdlog(LOG_NOTICE,
4064		    "AD lookup of winname %s@%s failed, error code %d",
4065		    name == NULL ? "(null)" : name,
4066		    domain == NULL ? "(null)" : domain,
4067		    retcode);
4068		return (retcode);
4069	}
4070	return (rc);
4071}
4072
4073/*
4074 * Given:
4075 * cache	sqlite handle to cache
4076 * name		Windows user name
4077 * domain	Windows domain name
4078 * local_only	if true, don't try AD lookups
4079 *
4080 * Returns: Error code
4081 *
4082 * *canonname	Canonical name (if non-NULL) [1]
4083 * *canondomain	Canonical domain (if non-NULL) [1]
4084 * *sidprefix	SID prefix [1]
4085 * *rid		RID
4086 * *req		Request (direction is updated)
4087 *
4088 * [1] malloc'ed, NULL on error
4089 */
4090idmap_retcode
4091lookup_name2sid(
4092    sqlite *cache,
4093    const char *name,
4094    const char *domain,
4095    int *is_wuser,
4096    char **canonname,
4097    char **canondomain,
4098    char **sidprefix,
4099    idmap_rid_t *rid,
4100    idmap_mapping *req,
4101    int local_only)
4102{
4103	int		type;
4104	idmap_retcode	retcode;
4105
4106	*sidprefix = NULL;
4107	if (canonname != NULL)
4108		*canonname = NULL;
4109	if (canondomain != NULL)
4110		*canondomain = NULL;
4111
4112	/* Lookup well-known SIDs table */
4113	retcode = lookup_wksids_name2sid(name, domain, canonname, canondomain,
4114	    sidprefix, rid, &type);
4115	if (retcode == IDMAP_SUCCESS) {
4116		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
4117		goto out;
4118	} else if (retcode != IDMAP_ERR_NOTFOUND) {
4119		return (retcode);
4120	}
4121
4122	/* Lookup cache */
4123	retcode = lookup_cache_name2sid(cache, name, domain, canonname,
4124	    sidprefix, rid, &type);
4125	if (retcode == IDMAP_SUCCESS) {
4126		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
4127		goto out;
4128	} else if (retcode != IDMAP_ERR_NOTFOUND) {
4129		return (retcode);
4130	}
4131
4132	/*
4133	 * The caller may be using this function to determine if this
4134	 * request needs to be marked for AD lookup or not
4135	 * (i.e. _IDMAP_F_LOOKUP_AD) and therefore may not want this
4136	 * function to AD lookup now.
4137	 */
4138	if (local_only)
4139		return (retcode);
4140
4141	/* Lookup AD */
4142	retcode = ad_lookup_by_winname(NULL, name, domain, _IDMAP_T_UNDEF,
4143	    NULL, NULL, NULL, canonname, sidprefix, rid, &type, NULL);
4144	if (retcode != IDMAP_SUCCESS)
4145		return (retcode);
4146
4147out:
4148	/*
4149	 * Entry found (cache or Windows lookup)
4150	 * is_wuser is both input as well as output parameter
4151	 */
4152	if (*is_wuser == 1 && type != _IDMAP_T_USER)
4153		retcode = IDMAP_ERR_NOTUSER;
4154	else if (*is_wuser == 0 && type != _IDMAP_T_GROUP)
4155		retcode = IDMAP_ERR_NOTGROUP;
4156	else if (*is_wuser == -1) {
4157		/* Caller wants to know if its user or group */
4158		if (type == _IDMAP_T_USER)
4159			*is_wuser = 1;
4160		else if (type == _IDMAP_T_GROUP)
4161			*is_wuser = 0;
4162		else
4163			retcode = IDMAP_ERR_SID;
4164	}
4165
4166	if (retcode == IDMAP_SUCCESS) {
4167		/*
4168		 * If we were asked for a canonical domain and none
4169		 * of the searches have provided one, assume it's the
4170		 * supplied domain.
4171		 */
4172		if (canondomain != NULL && *canondomain == NULL) {
4173			*canondomain = strdup(domain);
4174			if (*canondomain == NULL)
4175				retcode = IDMAP_ERR_MEMORY;
4176		}
4177	}
4178	if (retcode != IDMAP_SUCCESS) {
4179		free(*sidprefix);
4180		*sidprefix = NULL;
4181		if (canonname != NULL) {
4182			free(*canonname);
4183			*canonname = NULL;
4184		}
4185		if (canondomain != NULL) {
4186			free(*canondomain);
4187			*canondomain = NULL;
4188		}
4189	}
4190	return (retcode);
4191}
4192
4193static
4194idmap_retcode
4195name_based_mapping_pid2sid(lookup_state_t *state, const char *unixname,
4196		int is_user, idmap_mapping *req, idmap_id_res *res)
4197{
4198	const char	*winname, *windomain;
4199	char		*canonname;
4200	char		*canondomain;
4201	char		*sql = NULL, *errmsg = NULL;
4202	idmap_retcode	retcode;
4203	char		*end;
4204	const char	**values;
4205	sqlite_vm	*vm = NULL;
4206	int		ncol, r;
4207	int		is_wuser;
4208	const char	*me = "name_based_mapping_pid2sid";
4209	int 		non_wild_match = FALSE;
4210	idmap_namerule	*rule = &res->info.how.idmap_how_u.rule;
4211	int direction;
4212
4213	assert(unixname != NULL); /* We have unixname */
4214	assert(req->id2name == NULL); /* We don't have winname */
4215	assert(res->id.idmap_id_u.sid.prefix == NULL); /* No SID either */
4216
4217	sql = sqlite_mprintf(
4218	    "SELECT winname_display, windomain, w2u_order, "
4219	    "is_wuser, unixname, is_nt4 "
4220	    "FROM namerules WHERE "
4221	    "u2w_order > 0 AND is_user = %d AND "
4222	    "(unixname = %Q OR unixname = '*') "
4223	    "ORDER BY u2w_order ASC;", is_user, unixname);
4224	if (sql == NULL) {
4225		idmapdlog(LOG_ERR, "Out of memory");
4226		retcode = IDMAP_ERR_MEMORY;
4227		goto out;
4228	}
4229
4230	if (sqlite_compile(state->db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
4231		retcode = IDMAP_ERR_INTERNAL;
4232		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
4233		    CHECK_NULL(errmsg));
4234		sqlite_freemem(errmsg);
4235		goto out;
4236	}
4237
4238	for (;;) {
4239		r = sqlite_step(vm, &ncol, &values, NULL);
4240		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
4241		if (r == SQLITE_ROW) {
4242			if (ncol < 6) {
4243				retcode = IDMAP_ERR_INTERNAL;
4244				goto out;
4245			}
4246			if (values[0] == NULL) {
4247				/* values [1] and [2] can be null */
4248				retcode = IDMAP_ERR_INTERNAL;
4249				goto out;
4250			}
4251
4252			if (values[2] != NULL)
4253				direction =
4254				    (strtol(values[2], &end, 10) == 0)?
4255				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
4256			else
4257				direction = IDMAP_DIRECTION_U2W;
4258
4259			if (EMPTY_NAME(values[0])) {
4260				idmap_namerule_set(rule, values[1], values[0],
4261				    values[4], is_user,
4262				    strtol(values[3], &end, 10),
4263				    strtol(values[5], &end, 10),
4264				    direction);
4265				retcode = IDMAP_ERR_NOMAPPING;
4266				goto out;
4267			}
4268
4269			if (values[0][0] == '*') {
4270				winname = unixname;
4271				if (non_wild_match) {
4272					/*
4273					 * There were non-wildcard rules
4274					 * where the Windows identity doesn't
4275					 * exist. Return no mapping.
4276					 */
4277					retcode = IDMAP_ERR_NOMAPPING;
4278					goto out;
4279				}
4280			} else {
4281				/* Save first non-wild match rule */
4282				if (!non_wild_match) {
4283					idmap_namerule_set(rule, values[1],
4284					    values[0], values[4],
4285					    is_user,
4286					    strtol(values[3], &end, 10),
4287					    strtol(values[5], &end, 10),
4288					    direction);
4289					non_wild_match = TRUE;
4290				}
4291				winname = values[0];
4292			}
4293			is_wuser = res->id.idtype == IDMAP_USID ? 1
4294			    : res->id.idtype == IDMAP_GSID ? 0
4295			    : -1;
4296			if (values[1] != NULL)
4297				windomain = values[1];
4298			else if (state->defdom != NULL)
4299				windomain = state->defdom;
4300			else {
4301				idmapdlog(LOG_ERR, "%s: no domain", me);
4302				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
4303				goto out;
4304			}
4305
4306			retcode = lookup_name2sid(state->cache,
4307			    winname, windomain,
4308			    &is_wuser, &canonname, &canondomain,
4309			    &res->id.idmap_id_u.sid.prefix,
4310			    &res->id.idmap_id_u.sid.rid, req, 0);
4311
4312			if (retcode == IDMAP_ERR_NOTFOUND) {
4313				continue;
4314			}
4315			goto out;
4316
4317		} else if (r == SQLITE_DONE) {
4318			/*
4319			 * If there were non-wildcard rules where
4320			 * Windows identity doesn't exist
4321			 * return no mapping.
4322			 */
4323			if (non_wild_match)
4324				retcode = IDMAP_ERR_NOMAPPING;
4325			else
4326				retcode = IDMAP_ERR_NOTFOUND;
4327			goto out;
4328		} else {
4329			(void) sqlite_finalize(vm, &errmsg);
4330			vm = NULL;
4331			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
4332			    CHECK_NULL(errmsg));
4333			sqlite_freemem(errmsg);
4334			retcode = IDMAP_ERR_INTERNAL;
4335			goto out;
4336		}
4337	}
4338
4339out:
4340	if (sql != NULL)
4341		sqlite_freemem(sql);
4342	if (retcode == IDMAP_SUCCESS) {
4343		res->id.idtype = is_wuser ? IDMAP_USID : IDMAP_GSID;
4344
4345		if (values[2] != NULL)
4346			res->direction =
4347			    (strtol(values[2], &end, 10) == 0)?
4348			    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
4349		else
4350			res->direction = IDMAP_DIRECTION_U2W;
4351
4352		req->id2name = canonname;
4353		req->id2domain = canondomain;
4354	}
4355
4356	if (retcode == IDMAP_SUCCESS) {
4357		idmap_namerule_set(rule, values[1], values[0], values[4],
4358		    is_user, strtol(values[3], &end, 10),
4359		    strtol(values[5], &end, 10),
4360		    rule->direction);
4361	}
4362
4363	if (retcode != IDMAP_ERR_NOTFOUND) {
4364		res->info.how.map_type = IDMAP_MAP_TYPE_RULE_BASED;
4365		res->info.src = IDMAP_MAP_SRC_NEW;
4366	}
4367
4368	if (vm != NULL)
4369		(void) sqlite_finalize(vm, NULL);
4370	return (retcode);
4371}
4372
4373/*
4374 * Convention when processing unix2win requests:
4375 *
4376 * Unix identity:
4377 * req->id1name =
4378 *              unixname if given otherwise unixname found will be placed
4379 *              here.
4380 * req->id1domain =
4381 *              NOT USED
4382 * req->id1.idtype =
4383 *              Given type (IDMAP_UID or IDMAP_GID)
4384 * req->id1..[uid or gid] =
4385 *              UID/GID if given otherwise UID/GID found will be placed here.
4386 *
4387 * Windows identity:
4388 * req->id2name =
4389 *              winname found will be placed here.
4390 * req->id2domain =
4391 *              windomain found will be placed here.
4392 * res->id.idtype =
4393 *              Target type initialized from req->id2.idtype. If
4394 *              it is IDMAP_SID then actual type (IDMAP_USID/GSID) found
4395 *              will be placed here.
4396 * req->id..sid.[prefix, rid] =
4397 *              SID found will be placed here.
4398 *
4399 * Others:
4400 * res->retcode =
4401 *              Return status for this request will be placed here.
4402 * res->direction =
4403 *              Direction found will be placed here. Direction
4404 *              meaning whether the resultant mapping is valid
4405 *              only from unix2win or bi-directional.
4406 * req->direction =
4407 *              INTERNAL USE. Used by idmapd to set various
4408 *              flags (_IDMAP_F_xxxx) to aid in processing
4409 *              of the request.
4410 * req->id2.idtype =
4411 *              INTERNAL USE. Initially this is the requested target
4412 *              type and is used to initialize res->id.idtype.
4413 *              ad_lookup_batch() uses this field temporarily to store
4414 *              sid_type obtained by the batched AD lookups and after
4415 *              use resets it to IDMAP_NONE to prevent xdr from
4416 *              mis-interpreting the contents of req->id2.
4417 * req->id2..[uid or gid or sid] =
4418 *              NOT USED
4419 */
4420
4421/*
4422 * This function does the following:
4423 * 1. Lookup well-known SIDs table.
4424 * 2. Lookup cache.
4425 * 3. Check if the client does not want new mapping to be allocated
4426 *    in which case this pass is the final pass.
4427 * 4. Set AD/NLDAP lookup flags if it determines that the next stage needs
4428 *    to do AD/NLDAP lookup.
4429 */
4430idmap_retcode
4431pid2sid_first_pass(lookup_state_t *state, idmap_mapping *req,
4432		idmap_id_res *res, int is_user)
4433{
4434	idmap_retcode	retcode;
4435	bool_t		gen_localsid_on_err = FALSE;
4436
4437	/* Initialize result */
4438	res->id.idtype = req->id2.idtype;
4439	res->direction = IDMAP_DIRECTION_UNDEF;
4440
4441	if (req->id2.idmap_id_u.sid.prefix != NULL) {
4442		/* sanitize sidprefix */
4443		free(req->id2.idmap_id_u.sid.prefix);
4444		req->id2.idmap_id_u.sid.prefix = NULL;
4445	}
4446
4447	/* Find pid */
4448	if (req->id1.idmap_id_u.uid == IDMAP_SENTINEL_PID) {
4449		if (req->id1name == NULL) {
4450			retcode = IDMAP_ERR_ARG;
4451			goto out;
4452		}
4453
4454		if (ns_lookup_byname(req->id1name, NULL, &req->id1)
4455		    != IDMAP_SUCCESS) {
4456			retcode = IDMAP_ERR_NOMAPPING;
4457			goto out;
4458		}
4459	}
4460
4461	/* Lookup in well-known SIDs table */
4462	retcode = lookup_wksids_pid2sid(req, res, is_user);
4463	if (retcode != IDMAP_ERR_NOTFOUND)
4464		goto out;
4465
4466	/* Lookup in cache */
4467	retcode = lookup_cache_pid2sid(state->cache, req, res, is_user);
4468	if (retcode != IDMAP_ERR_NOTFOUND)
4469		goto out;
4470
4471	/* Ephemeral ids cannot be allocated during pid2sid */
4472	if (IDMAP_ID_IS_EPHEMERAL(req->id1.idmap_id_u.uid)) {
4473		retcode = IDMAP_ERR_NOMAPPING;
4474		goto out;
4475	}
4476
4477	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req)) {
4478		retcode = IDMAP_ERR_NONE_GENERATED;
4479		goto out;
4480	}
4481
4482	if (AVOID_NAMESERVICE(req)) {
4483		gen_localsid_on_err = TRUE;
4484		retcode = IDMAP_ERR_NOMAPPING;
4485		goto out;
4486	}
4487
4488	/* Set flags for the next stage */
4489	if (state->directory_based_mapping == DIRECTORY_MAPPING_IDMU) {
4490		req->direction |= _IDMAP_F_LOOKUP_AD;
4491		state->ad_nqueries++;
4492	} else if (AD_MODE(req->id1.idtype, state)) {
4493		/*
4494		 * If AD-based name mapping is enabled then the next stage
4495		 * will need to lookup AD using unixname to get the
4496		 * corresponding winname.
4497		 */
4498		if (req->id1name == NULL) {
4499			/* Get unixname if only pid is given. */
4500			retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid,
4501			    is_user, &req->id1name);
4502			if (retcode != IDMAP_SUCCESS) {
4503				gen_localsid_on_err = TRUE;
4504				goto out;
4505			}
4506		}
4507		req->direction |= _IDMAP_F_LOOKUP_AD;
4508		state->ad_nqueries++;
4509	} else if (NLDAP_OR_MIXED_MODE(req->id1.idtype, state)) {
4510		/*
4511		 * If native LDAP or mixed mode is enabled for name mapping
4512		 * then the next stage will need to lookup native LDAP using
4513		 * unixname/pid to get the corresponding winname.
4514		 */
4515		req->direction |= _IDMAP_F_LOOKUP_NLDAP;
4516		state->nldap_nqueries++;
4517	}
4518
4519	/*
4520	 * Failed to find non-expired entry in cache. Set the flag to
4521	 * indicate that we are not done yet.
4522	 */
4523	state->pid2sid_done = FALSE;
4524	req->direction |= _IDMAP_F_NOTDONE;
4525	retcode = IDMAP_SUCCESS;
4526
4527out:
4528	res->retcode = idmap_stat4prot(retcode);
4529	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
4530		if (gen_localsid_on_err == TRUE)
4531			(void) generate_localsid(req, res, is_user, TRUE);
4532	return (retcode);
4533}
4534
4535idmap_retcode
4536pid2sid_second_pass(lookup_state_t *state, idmap_mapping *req,
4537	idmap_id_res *res, int is_user)
4538{
4539	bool_t		gen_localsid_on_err = TRUE;
4540	idmap_retcode	retcode = IDMAP_SUCCESS;
4541
4542	/* Check if second pass is needed */
4543	if (ARE_WE_DONE(req->direction))
4544		return (res->retcode);
4545
4546	/* Get status from previous pass */
4547	retcode = res->retcode;
4548	if (retcode != IDMAP_SUCCESS)
4549		goto out;
4550
4551	/*
4552	 * If directory-based name mapping is enabled then the winname
4553	 * may already have been retrieved from the AD object (AD-mode)
4554	 * or from native LDAP object (nldap-mode or mixed-mode).
4555	 * Note that if we have winname but no SID then it's an error
4556	 * because this implies that the Native LDAP entry contains
4557	 * winname which does not exist and it's better that we return
4558	 * an error instead of doing rule-based mapping so that the user
4559	 * can detect the issue and take appropriate action.
4560	 */
4561	if (req->id2name != NULL) {
4562		/* Return notfound if we've winname but no SID. */
4563		if (res->id.idmap_id_u.sid.prefix == NULL) {
4564			retcode = IDMAP_ERR_NOTFOUND;
4565			goto out;
4566		}
4567		if (state->directory_based_mapping == DIRECTORY_MAPPING_IDMU)
4568			res->direction = IDMAP_DIRECTION_BI;
4569		else if (AD_MODE(req->id1.idtype, state))
4570			res->direction = IDMAP_DIRECTION_BI;
4571		else if (NLDAP_MODE(req->id1.idtype, state))
4572			res->direction = IDMAP_DIRECTION_BI;
4573		else if (MIXED_MODE(req->id1.idtype, state))
4574			res->direction = IDMAP_DIRECTION_W2U;
4575		goto out;
4576	} else if (res->id.idmap_id_u.sid.prefix != NULL) {
4577		/*
4578		 * We've SID but no winname. This is fine because
4579		 * the caller may have only requested SID.
4580		 */
4581		goto out;
4582	}
4583
4584	/* Free any mapping info from Directory based mapping */
4585	if (res->info.how.map_type != IDMAP_MAP_TYPE_UNKNOWN)
4586		idmap_info_free(&res->info);
4587
4588	if (req->id1name == NULL) {
4589		/* Get unixname from name service */
4590		retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid, is_user,
4591		    &req->id1name);
4592		if (retcode != IDMAP_SUCCESS)
4593			goto out;
4594	} else if (req->id1.idmap_id_u.uid == IDMAP_SENTINEL_PID) {
4595		/* Get pid from name service */
4596		retcode = ns_lookup_byname(req->id1name, NULL, &req->id1);
4597		if (retcode != IDMAP_SUCCESS) {
4598			gen_localsid_on_err = FALSE;
4599			goto out;
4600		}
4601	}
4602
4603	/* Use unixname to evaluate local name-based mapping rules */
4604	retcode = name_based_mapping_pid2sid(state, req->id1name, is_user,
4605	    req, res);
4606	if (retcode == IDMAP_ERR_NOTFOUND) {
4607		retcode = generate_localsid(req, res, is_user, FALSE);
4608		gen_localsid_on_err = FALSE;
4609	}
4610
4611out:
4612	res->retcode = idmap_stat4prot(retcode);
4613	if (res->retcode != IDMAP_SUCCESS) {
4614		req->direction = _IDMAP_F_DONE;
4615		free(req->id2name);
4616		req->id2name = NULL;
4617		free(req->id2domain);
4618		req->id2domain = NULL;
4619		if (gen_localsid_on_err == TRUE)
4620			(void) generate_localsid(req, res, is_user, TRUE);
4621		else
4622			res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
4623	}
4624	if (!ARE_WE_DONE(req->direction))
4625		state->pid2sid_done = FALSE;
4626	return (retcode);
4627}
4628
4629idmap_retcode
4630idmap_cache_flush(idmap_flush_op op)
4631{
4632	idmap_retcode	rc;
4633	sqlite *cache = NULL;
4634	char *sql1;
4635	char *sql2;
4636
4637	switch (op) {
4638	case IDMAP_FLUSH_EXPIRE:
4639		sql1 =
4640		    "UPDATE idmap_cache SET expiration=1 WHERE expiration>0;";
4641		sql2 =
4642		    "UPDATE name_cache SET expiration=1 WHERE expiration>0;";
4643		break;
4644
4645	case IDMAP_FLUSH_DELETE:
4646		sql1 = "DELETE FROM idmap_cache;";
4647		sql2 = "DELETE FROM name_cache;";
4648		break;
4649
4650	default:
4651		return (IDMAP_ERR_INTERNAL);
4652	}
4653
4654	rc = get_cache_handle(&cache);
4655	if (rc != IDMAP_SUCCESS)
4656		return (rc);
4657
4658	/*
4659	 * Note that we flush the idmapd cache first, before the kernel
4660	 * cache.  If we did it the other way 'round, a request could come
4661	 * in after the kernel cache flush and pull a soon-to-be-flushed
4662	 * idmapd cache entry back into the kernel cache.  This way the
4663	 * worst that will happen is that a new entry will be added to
4664	 * the kernel cache and then immediately flushed.
4665	 */
4666
4667	rc = sql_exec_no_cb(cache, IDMAP_CACHENAME, sql1);
4668	if (rc != IDMAP_SUCCESS)
4669		return (rc);
4670
4671	rc = sql_exec_no_cb(cache, IDMAP_CACHENAME, sql2);
4672
4673	(void) __idmap_flush_kcache();
4674	return (rc);
4675}
4676