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