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