xref: /illumos-gate/usr/src/cmd/idmap/idmapd/dbutils.c (revision 5e0794bc)
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 2007 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;
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 		sql = sqlite_mprintf("SELECT pid, is_user, expiration, "
1477 		    "unixname, u2w, is_wuser "
1478 		    "FROM idmap_cache WHERE is_user = %s AND "
1479 		    "winname = %Q AND windomain = %Q AND w2u = 1 AND "
1480 		    "(pid >= 2147483648 OR "
1481 		    "(expiration = 0 OR expiration ISNULL OR "
1482 		    "expiration > %d));",
1483 		    is_user_string, req->id1name, req->id1domain, curtime);
1484 	} else {
1485 		retcode = IDMAP_ERR_ARG;
1486 		goto out;
1487 	}
1488 
1489 	if (sql == NULL) {
1490 		idmapdlog(LOG_ERR, "Out of memory");
1491 		retcode = IDMAP_ERR_MEMORY;
1492 		goto out;
1493 	}
1494 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 6, &values);
1495 	sqlite_freemem(sql);
1496 
1497 	if (retcode == IDMAP_ERR_NOTFOUND) {
1498 		goto out;
1499 	} else if (retcode == IDMAP_SUCCESS) {
1500 		/* sanity checks */
1501 		if (values[0] == NULL || values[1] == NULL) {
1502 			retcode = IDMAP_ERR_CACHE;
1503 			goto out;
1504 		}
1505 
1506 		pid = strtoul(values[0], &end, 10);
1507 		is_user = strncmp(values[1], "0", 2) ? 1 : 0;
1508 
1509 		if (is_user) {
1510 			res->id.idtype = IDMAP_UID;
1511 			res->id.idmap_id_u.uid = pid;
1512 		} else {
1513 			res->id.idtype = IDMAP_GID;
1514 			res->id.idmap_id_u.gid = pid;
1515 		}
1516 
1517 		/*
1518 		 * We may have an expired ephemeral mapping. Consider
1519 		 * the expired entry as valid if we are not going to
1520 		 * perform name-based mapping. But do not renew the
1521 		 * expiration.
1522 		 * If we will be doing name-based mapping then store the
1523 		 * ephemeral pid in the result so that we can use it
1524 		 * if we end up doing dynamic mapping again.
1525 		 */
1526 		if (!DO_NOT_ALLOC_NEW_ID_MAPPING(req) &&
1527 		    !AVOID_NAMESERVICE(req) &&
1528 		    IS_EPHEMERAL(pid) && values[2] != NULL) {
1529 			exp = strtoll(values[2], &end, 10);
1530 			if (exp && exp <= curtime) {
1531 				/* Store the ephemeral pid */
1532 				res->direction = IDMAP_DIRECTION_BI;
1533 				req->direction |= is_user
1534 				    ? _IDMAP_F_EXP_EPH_UID
1535 				    : _IDMAP_F_EXP_EPH_GID;
1536 				retcode = IDMAP_ERR_NOTFOUND;
1537 			}
1538 		}
1539 	}
1540 
1541 out:
1542 	if (retcode == IDMAP_SUCCESS) {
1543 		if (values[4] != NULL)
1544 			res->direction =
1545 			    (strtol(values[4], &end, 10) == 0)?
1546 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
1547 		else
1548 			res->direction = IDMAP_DIRECTION_W2U;
1549 
1550 		if (values[3] != NULL) {
1551 			if (req->id2name != NULL)
1552 				free(req->id2name);
1553 			req->id2name = strdup(values[3]);
1554 			if (req->id2name == NULL) {
1555 				idmapdlog(LOG_ERR, "Out of memory");
1556 				retcode = IDMAP_ERR_MEMORY;
1557 			}
1558 		}
1559 
1560 		req->id1.idtype = strncmp(values[5], "0", 2) ?
1561 		    IDMAP_USID : IDMAP_GSID;
1562 	}
1563 	if (vm != NULL)
1564 		(void) sqlite_finalize(vm, NULL);
1565 	return (retcode);
1566 }
1567 
1568 static
1569 idmap_retcode
1570 lookup_cache_sid2name(sqlite *cache, const char *sidprefix, idmap_rid_t rid,
1571 		char **name, char **domain, int *type)
1572 {
1573 	char		*end;
1574 	char		*sql = NULL;
1575 	const char	**values;
1576 	sqlite_vm	*vm = NULL;
1577 	int		ncol;
1578 	time_t		curtime;
1579 	idmap_retcode	retcode = IDMAP_SUCCESS;
1580 
1581 	/* Get current time */
1582 	errno = 0;
1583 	if ((curtime = time(NULL)) == (time_t)-1) {
1584 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
1585 		    strerror(errno));
1586 		retcode = IDMAP_ERR_INTERNAL;
1587 		goto out;
1588 	}
1589 
1590 	/* SQL to lookup the cache */
1591 	sql = sqlite_mprintf("SELECT canon_name, domain, type "
1592 	    "FROM name_cache WHERE "
1593 	    "sidprefix = %Q AND rid = %u AND "
1594 	    "(expiration = 0 OR expiration ISNULL OR "
1595 	    "expiration > %d);",
1596 	    sidprefix, rid, curtime);
1597 	if (sql == NULL) {
1598 		idmapdlog(LOG_ERR, "Out of memory");
1599 		retcode = IDMAP_ERR_MEMORY;
1600 		goto out;
1601 	}
1602 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 3, &values);
1603 	sqlite_freemem(sql);
1604 
1605 	if (retcode == IDMAP_SUCCESS) {
1606 		if (type != NULL) {
1607 			if (values[2] == NULL) {
1608 				retcode = IDMAP_ERR_CACHE;
1609 				goto out;
1610 			}
1611 			*type = strtol(values[2], &end, 10);
1612 		}
1613 
1614 		if (name != NULL && values[0] != NULL) {
1615 			if ((*name = strdup(values[0])) == NULL) {
1616 				idmapdlog(LOG_ERR, "Out of memory");
1617 				retcode = IDMAP_ERR_MEMORY;
1618 				goto out;
1619 			}
1620 		}
1621 
1622 		if (domain != NULL && values[1] != NULL) {
1623 			if ((*domain = strdup(values[1])) == NULL) {
1624 				if (name != NULL && *name) {
1625 					free(*name);
1626 					*name = NULL;
1627 				}
1628 				idmapdlog(LOG_ERR, "Out of memory");
1629 				retcode = IDMAP_ERR_MEMORY;
1630 				goto out;
1631 			}
1632 		}
1633 	}
1634 
1635 out:
1636 	if (vm != NULL)
1637 		(void) sqlite_finalize(vm, NULL);
1638 	return (retcode);
1639 }
1640 
1641 /*
1642  * Given SID, find winname using name_cache OR
1643  * Given winname, find SID using name_cache.
1644  * Used when mapping win to unix i.e. req->id1 is windows id and
1645  * req->id2 is unix id
1646  */
1647 static
1648 idmap_retcode
1649 lookup_name_cache(sqlite *cache, idmap_mapping *req, idmap_id_res *res)
1650 {
1651 	int		type = -1;
1652 	idmap_retcode	retcode;
1653 	char		*sidprefix = NULL;
1654 	idmap_rid_t	rid;
1655 	char		*name = NULL, *domain = NULL;
1656 
1657 	/* Done if we've both sid and winname */
1658 	if (req->id1.idmap_id_u.sid.prefix != NULL && req->id1name != NULL)
1659 		return (IDMAP_SUCCESS);
1660 
1661 	/* Lookup sid to winname */
1662 	if (req->id1.idmap_id_u.sid.prefix != NULL) {
1663 		retcode = lookup_cache_sid2name(cache,
1664 		    req->id1.idmap_id_u.sid.prefix,
1665 		    req->id1.idmap_id_u.sid.rid, &name, &domain, &type);
1666 		goto out;
1667 	}
1668 
1669 	/* Lookup winame to sid */
1670 	retcode = lookup_cache_name2sid(cache, req->id1name, req->id1domain,
1671 	    &name, &sidprefix, &rid, &type);
1672 
1673 out:
1674 	if (retcode != IDMAP_SUCCESS) {
1675 		free(name);
1676 		free(domain);
1677 		free(sidprefix);
1678 		return (retcode);
1679 	}
1680 
1681 	if (res->id.idtype == IDMAP_POSIXID) {
1682 		res->id.idtype = (type == _IDMAP_T_USER) ?
1683 		    IDMAP_UID : IDMAP_GID;
1684 	}
1685 	req->id1.idtype = (type == _IDMAP_T_USER) ?
1686 	    IDMAP_USID : IDMAP_GSID;
1687 
1688 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
1689 	if (name != NULL) {
1690 		free(req->id1name);	/* Free existing winname */
1691 		req->id1name = name;	/* and use canonical name instead */
1692 	}
1693 	if (req->id1domain == NULL)
1694 		req->id1domain = domain;
1695 	if (req->id1.idmap_id_u.sid.prefix == NULL) {
1696 		req->id1.idmap_id_u.sid.prefix = sidprefix;
1697 		req->id1.idmap_id_u.sid.rid = rid;
1698 	}
1699 	return (retcode);
1700 }
1701 
1702 /*
1703  * Batch AD lookups
1704  */
1705 idmap_retcode
1706 ad_lookup_batch(lookup_state_t *state, idmap_mapping_batch *batch,
1707 		idmap_ids_res *result)
1708 {
1709 	idmap_retcode	retcode;
1710 	int		i, add, type, is_wuser, is_user;
1711 	int		retries = 0, eunixtype;
1712 	char		**unixname;
1713 	idmap_mapping	*req;
1714 	idmap_id_res	*res;
1715 	idmap_query_state_t	*qs = NULL;
1716 
1717 	/*
1718 	 * Since req->id2.idtype is unused, we will use it here
1719 	 * to retrieve the value of sid_type. But it needs to be
1720 	 * reset to IDMAP_NONE before we return to prevent xdr
1721 	 * from mis-interpreting req->id2 when it tries to free
1722 	 * the input argument. Other option is to allocate an
1723 	 * array of integers and use it instead for the batched
1724 	 * call. But why un-necessarily allocate memory. That may
1725 	 * be an option if req->id2.idtype cannot be re-used in
1726 	 * future.
1727 	 */
1728 
1729 	if (state->ad_nqueries == 0)
1730 		return (IDMAP_SUCCESS);
1731 
1732 retry:
1733 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, state->ad_nqueries,
1734 	    &qs);
1735 	if (retcode != IDMAP_SUCCESS) {
1736 		degrade_svc();
1737 		idmapdlog(LOG_ERR,
1738 		    "Failed to create batch for AD lookup");
1739 		goto out;
1740 	}
1741 
1742 	restore_svc();
1743 
1744 	idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
1745 	    state->ad_unixgroup_attr);
1746 
1747 	for (i = 0, add = 0; i < batch->idmap_mapping_batch_len; i++) {
1748 		req = &batch->idmap_mapping_batch_val[i];
1749 		res = &result->ids.ids_val[i];
1750 		retcode = IDMAP_SUCCESS;
1751 		req->id2.idtype = IDMAP_NONE;
1752 
1753 		/* Skip if not marked for AD lookup */
1754 		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
1755 			continue;
1756 
1757 		if (retries == 0)
1758 			res->retcode = IDMAP_ERR_RETRIABLE_NET_ERR;
1759 		else if (res->retcode != IDMAP_ERR_RETRIABLE_NET_ERR)
1760 			continue;
1761 
1762 		if (IS_REQUEST_SID(*req, 1)) {
1763 			/* win to unix */
1764 
1765 			assert(req->id1.idmap_id_u.sid.prefix != NULL);
1766 
1767 			/* Lookup AD by SID */
1768 			unixname = NULL;
1769 			eunixtype = _IDMAP_T_UNDEF;
1770 			if (req->id2name == NULL) {
1771 				if (res->id.idtype == IDMAP_UID &&
1772 				    AD_OR_MIXED(state->nm_siduid)) {
1773 					eunixtype = _IDMAP_T_USER;
1774 					unixname = &req->id2name;
1775 				} else if (res->id.idtype == IDMAP_GID &&
1776 				    AD_OR_MIXED(state->nm_sidgid)) {
1777 					eunixtype = _IDMAP_T_GROUP;
1778 					unixname = &req->id2name;
1779 				} else if (AD_OR_MIXED(state->nm_siduid) ||
1780 				    AD_OR_MIXED(state->nm_sidgid)) {
1781 					unixname = &req->id2name;
1782 				}
1783 			}
1784 			add = 1;
1785 			retcode = idmap_sid2name_batch_add1(
1786 			    qs, req->id1.idmap_id_u.sid.prefix,
1787 			    &req->id1.idmap_id_u.sid.rid, eunixtype,
1788 			    (req->id1name == NULL) ? &req->id1name : NULL,
1789 			    (req->id1domain == NULL) ? &req->id1domain : NULL,
1790 			    (int *)&req->id2.idtype, unixname, &res->retcode);
1791 
1792 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
1793 			/* unix to win */
1794 
1795 			if (res->id.idmap_id_u.sid.prefix != NULL &&
1796 			    req->id2name != NULL) {
1797 				/* Already have SID and winname -- done */
1798 				res->retcode = IDMAP_SUCCESS;
1799 				continue;
1800 			}
1801 
1802 			if (res->id.idmap_id_u.sid.prefix != NULL) {
1803 				/*
1804 				 * SID but no winname -- lookup AD by
1805 				 * SID to get winname.
1806 				 */
1807 				add = 1;
1808 				retcode = idmap_sid2name_batch_add1(
1809 				    qs, res->id.idmap_id_u.sid.prefix,
1810 				    &res->id.idmap_id_u.sid.rid,
1811 				    _IDMAP_T_UNDEF, &req->id2name,
1812 				    &req->id2domain, (int *)&req->id2.idtype,
1813 				    NULL, &res->retcode);
1814 			} else if (req->id2name != NULL) {
1815 				/*
1816 				 * winname but no SID -- lookup AD by
1817 				 * winname to get SID.
1818 				 */
1819 				add = 1;
1820 				retcode = idmap_name2sid_batch_add1(
1821 				    qs, req->id2name, req->id2domain,
1822 				    _IDMAP_T_UNDEF, NULL,
1823 				    &res->id.idmap_id_u.sid.prefix,
1824 				    &res->id.idmap_id_u.sid.rid,
1825 				    (int *)&req->id2.idtype, NULL,
1826 				    &res->retcode);
1827 			} else if (req->id1name != NULL) {
1828 				/*
1829 				 * No SID and no winname but we've unixname --
1830 				 * lookup AD by unixname to get SID.
1831 				 */
1832 				is_user = (IS_REQUEST_UID(*req)) ? 1 : 0;
1833 				if (res->id.idtype == IDMAP_USID)
1834 					is_wuser = 1;
1835 				else if (res->id.idtype == IDMAP_GSID)
1836 					is_wuser = 0;
1837 				else
1838 					is_wuser = is_user;
1839 				add = 1;
1840 				retcode = idmap_unixname2sid_batch_add1(
1841 				    qs, req->id1name, is_user, is_wuser,
1842 				    &res->id.idmap_id_u.sid.prefix,
1843 				    &res->id.idmap_id_u.sid.rid,
1844 				    &req->id2name, &req->id2domain,
1845 				    (int *)&req->id2.idtype, &res->retcode);
1846 			}
1847 		}
1848 		if (retcode != IDMAP_SUCCESS) {
1849 			idmap_lookup_release_batch(&qs);
1850 			break;
1851 		}
1852 	}
1853 
1854 	if (retcode == IDMAP_SUCCESS && add)
1855 		retcode = idmap_lookup_batch_end(&qs, NULL);
1856 
1857 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
1858 		goto retry;
1859 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
1860 		degrade_svc();
1861 
1862 	if (retcode != IDMAP_SUCCESS)
1863 		idmapdlog(LOG_NOTICE, "Failed to batch AD lookup requests");
1864 
1865 out:
1866 	/*
1867 	 * This loop does the following:
1868 	 * 1) If there are errors in creating or submitting the batch then
1869 	 *    we set the retcode for each request (res->retcode) that's part
1870 	 *    of the batch to that error. If there were no such errors then
1871 	 *    res->retcode for each request will reflect the status of AD
1872 	 *    lookup for that particular request. Initial value of
1873 	 *    res->retcode is IDMAP_ERR_RETRIABLE_NET_ERR.
1874 	 * 2) If AD lookup for a given request succeeds then evaluate the
1875 	 *    type of the AD object (i.e user or group) and update the
1876 	 *    idtype in res and req.
1877 	 * 3) Reset req->id2.idtype to IDMAP_NONE.
1878 	 */
1879 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
1880 		req = &batch->idmap_mapping_batch_val[i];
1881 		type = req->id2.idtype;
1882 		req->id2.idtype = IDMAP_NONE;
1883 		res = &result->ids.ids_val[i];
1884 
1885 		if (!(req->direction & _IDMAP_F_LOOKUP_AD))
1886 			/* Entry that wasn't marked for AD lookup - skip */
1887 			continue;
1888 
1889 		if (retcode != IDMAP_SUCCESS) {
1890 			res->retcode = retcode;
1891 			continue;
1892 		}
1893 
1894 		if (!add)
1895 			continue;
1896 
1897 
1898 		if (IS_REQUEST_SID(*req, 1)) {
1899 			if (res->retcode != IDMAP_SUCCESS)
1900 				continue;
1901 			switch (type) {
1902 			case _IDMAP_T_USER:
1903 				if (res->id.idtype == IDMAP_POSIXID)
1904 					res->id.idtype = IDMAP_UID;
1905 				req->id1.idtype = IDMAP_USID;
1906 				break;
1907 			case _IDMAP_T_GROUP:
1908 				if (res->id.idtype == IDMAP_POSIXID)
1909 					res->id.idtype = IDMAP_GID;
1910 				req->id1.idtype = IDMAP_GSID;
1911 				break;
1912 			default:
1913 				res->retcode = IDMAP_ERR_SID;
1914 				break;
1915 			}
1916 		} else if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req)) {
1917 			if (res->retcode != IDMAP_SUCCESS) {
1918 				if ((!(IDMAP_FATAL_ERROR(res->retcode))) &&
1919 				    res->id.idmap_id_u.sid.prefix == NULL &&
1920 				    req->id2name == NULL && /* no winname */
1921 				    req->id1name != NULL) /* unixname */
1922 					/*
1923 					 * Here we have a pid2sid request
1924 					 * that was marked for AD lookup
1925 					 * with no SID, no winname but with
1926 					 * unixname. This request was
1927 					 * added to the batch to do AD lookup
1928 					 * by unixname but it failed with non
1929 					 * fatal error. In such case we
1930 					 * ignore the error (i.e set
1931 					 * res->retcode to success) so that
1932 					 * next pass considers it for name
1933 					 * based mapping rules or ephemeral
1934 					 * mapping.
1935 					 */
1936 					res->retcode = IDMAP_SUCCESS;
1937 				continue;
1938 			}
1939 			switch (type) {
1940 			case _IDMAP_T_USER:
1941 				if (res->id.idtype == IDMAP_SID)
1942 					res->id.idtype = IDMAP_USID;
1943 				break;
1944 			case _IDMAP_T_GROUP:
1945 				if (res->id.idtype == IDMAP_SID)
1946 					res->id.idtype = IDMAP_GSID;
1947 				break;
1948 			default:
1949 				res->retcode = IDMAP_ERR_SID;
1950 				break;
1951 			}
1952 		}
1953 	}
1954 
1955 	/* AD lookups done. Reset state->ad_nqueries and return */
1956 	state->ad_nqueries = 0;
1957 	return (retcode);
1958 }
1959 
1960 /*
1961  * Convention when processing win2unix requests:
1962  *
1963  * Windows identity:
1964  * req->id1name =
1965  *              winname if given otherwise winname found will be placed
1966  *              here.
1967  * req->id1domain =
1968  *              windomain if given otherwise windomain found will be
1969  *              placed here.
1970  * req->id1.idtype =
1971  *              Either IDMAP_SID/USID/GSID. If this is IDMAP_SID then it'll
1972  *              be set to IDMAP_USID/GSID depending upon whether the
1973  *              given SID is user or group respectively. The user/group-ness
1974  *              is determined either when looking up well-known SIDs table OR
1975  *              if the SID is found in namecache OR by ad_lookup() OR by
1976  *              ad_lookup_batch().
1977  * req->id1..sid.[prefix, rid] =
1978  *              SID if given otherwise SID found will be placed here.
1979  *
1980  * Unix identity:
1981  * req->id2name =
1982  *              unixname found will be placed here.
1983  * req->id2domain =
1984  *              NOT USED
1985  * res->id.idtype =
1986  *              Target type initialized from req->id2.idtype. If
1987  *              it is IDMAP_POSIXID then actual type (IDMAP_UID/GID) found
1988  *              will be placed here.
1989  * res->id..[uid or gid] =
1990  *              UID/GID found will be placed here.
1991  *
1992  * Others:
1993  * res->retcode =
1994  *              Return status for this request will be placed here.
1995  * res->direction =
1996  *              Direction found will be placed here. Direction
1997  *              meaning whether the resultant mapping is valid
1998  *              only from win2unix or bi-directional.
1999  * req->direction =
2000  *              INTERNAL USE. Used by idmapd to set various
2001  *              flags (_IDMAP_F_xxxx) to aid in processing
2002  *              of the request.
2003  * req->id2.idtype =
2004  *              INTERNAL USE. Initially this is the requested target
2005  *              type and is used to initialize res->id.idtype.
2006  *              ad_lookup_batch() uses this field temporarily to store
2007  *              sid_type obtained by the batched AD lookups and after
2008  *              use resets it to IDMAP_NONE to prevent xdr from
2009  *              mis-interpreting the contents of req->id2.
2010  * req->id2..[uid or gid or sid] =
2011  *              NOT USED
2012  */
2013 
2014 /*
2015  * This function does the following:
2016  * 1. Lookup well-known SIDs table.
2017  * 2. Check if the given SID is a local-SID and if so extract UID/GID from it.
2018  * 3. Lookup cache.
2019  * 4. Check if the client does not want new mapping to be allocated
2020  *    in which case this pass is the final pass.
2021  * 5. Set AD lookup flag if it determines that the next stage needs
2022  *    to do AD lookup.
2023  */
2024 idmap_retcode
2025 sid2pid_first_pass(lookup_state_t *state, sqlite *cache, idmap_mapping *req,
2026 		idmap_id_res *res)
2027 {
2028 	idmap_retcode	retcode;
2029 	int		wksid;
2030 
2031 	/* Initialize result */
2032 	res->id.idtype = req->id2.idtype;
2033 	res->id.idmap_id_u.uid = SENTINEL_PID;
2034 	res->direction = IDMAP_DIRECTION_UNDEF;
2035 	wksid = 0;
2036 
2037 	if (EMPTY_STRING(req->id1.idmap_id_u.sid.prefix)) {
2038 		if (req->id1name == NULL) {
2039 			retcode = IDMAP_ERR_ARG;
2040 			goto out;
2041 		}
2042 		/* sanitize sidprefix */
2043 		free(req->id1.idmap_id_u.sid.prefix);
2044 		req->id1.idmap_id_u.sid.prefix = NULL;
2045 	}
2046 
2047 	/* Lookup well-known SIDs table */
2048 	retcode = lookup_wksids_sid2pid(req, res, &wksid);
2049 	if (retcode != IDMAP_ERR_NOTFOUND)
2050 		goto out;
2051 
2052 	/* Check if this is a localsid */
2053 	if (!wksid) {
2054 		retcode = lookup_localsid2pid(req, res);
2055 		if (retcode != IDMAP_ERR_NOTFOUND)
2056 			goto out;
2057 	}
2058 
2059 	/* Lookup cache */
2060 	retcode = lookup_cache_sid2pid(cache, req, res);
2061 	if (retcode != IDMAP_ERR_NOTFOUND)
2062 		goto out;
2063 
2064 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req) || AVOID_NAMESERVICE(req)) {
2065 		retcode = IDMAP_ERR_NOMAPPING;
2066 		goto out;
2067 	}
2068 
2069 	/*
2070 	 * Failed to find non-expired entry in cache. Next step is
2071 	 * to determine if this request needs to be batched for AD lookup.
2072 	 *
2073 	 * At this point we have either sid or winname or both. If we don't
2074 	 * have both then lookup name_cache for the sid or winname
2075 	 * whichever is missing. If not found then this request will be
2076 	 * batched for AD lookup.
2077 	 */
2078 	retcode = lookup_name_cache(cache, req, res);
2079 	if (retcode != IDMAP_SUCCESS && retcode != IDMAP_ERR_NOTFOUND)
2080 		goto out;
2081 
2082 	/*
2083 	 * Set the flag to indicate that we are not done yet so that
2084 	 * subsequent passes considers this request for name-based
2085 	 * mapping and ephemeral mapping.
2086 	 */
2087 	state->sid2pid_done = FALSE;
2088 	req->direction |= _IDMAP_F_NOTDONE;
2089 
2090 	/*
2091 	 * Even if we have both sid and winname, we still may need to batch
2092 	 * this request for AD lookup if we don't have unixname and
2093 	 * directory-based name mapping (AD or mixed) is enabled.
2094 	 * We avoid AD lookup for well-known SIDs because they don't have
2095 	 * regular AD objects.
2096 	 */
2097 	if (retcode != IDMAP_SUCCESS ||
2098 	    (!wksid && req->id2name == NULL &&
2099 	    AD_OR_MIXED_MODE(res->id.idtype, state))) {
2100 		retcode = IDMAP_SUCCESS;
2101 		req->direction |= _IDMAP_F_LOOKUP_AD;
2102 		state->ad_nqueries++;
2103 	}
2104 
2105 
2106 out:
2107 	res->retcode = idmap_stat4prot(retcode);
2108 	/*
2109 	 * If we are done and there was an error then set fallback pid
2110 	 * in the result.
2111 	 */
2112 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
2113 		res->id.idmap_id_u.uid = UID_NOBODY;
2114 	return (retcode);
2115 }
2116 
2117 /*
2118  * Generate SID using the following convention
2119  * 	<machine-sid-prefix>-<1000 + uid>
2120  * 	<machine-sid-prefix>-<2^31 + gid>
2121  */
2122 static
2123 idmap_retcode
2124 generate_localsid(idmap_mapping *req, idmap_id_res *res, int is_user)
2125 {
2126 	free(res->id.idmap_id_u.sid.prefix);
2127 	res->id.idmap_id_u.sid.prefix = NULL;
2128 
2129 	/*
2130 	 * Diagonal mapping for localSIDs not supported because of the
2131 	 * way we generate localSIDs.
2132 	 */
2133 	if (is_user && res->id.idtype == IDMAP_GSID)
2134 		return (IDMAP_ERR_NOMAPPING);
2135 	if (!is_user && res->id.idtype == IDMAP_USID)
2136 		return (IDMAP_ERR_NOMAPPING);
2137 
2138 	/* Skip 1000 UIDs */
2139 	if (is_user && req->id1.idmap_id_u.uid >
2140 	    (INT32_MAX - LOCALRID_MIN))
2141 		return (IDMAP_ERR_NOMAPPING);
2142 
2143 	RDLOCK_CONFIG();
2144 	/*
2145 	 * machine_sid is never NULL because if it is we won't be here.
2146 	 * No need to assert because stdrup(NULL) will core anyways.
2147 	 */
2148 	res->id.idmap_id_u.sid.prefix =
2149 	    strdup(_idmapdstate.cfg->pgcfg.machine_sid);
2150 	if (res->id.idmap_id_u.sid.prefix == NULL) {
2151 		UNLOCK_CONFIG();
2152 		idmapdlog(LOG_ERR, "Out of memory");
2153 		return (IDMAP_ERR_MEMORY);
2154 	}
2155 	UNLOCK_CONFIG();
2156 	res->id.idmap_id_u.sid.rid =
2157 	    (is_user) ? req->id1.idmap_id_u.uid + LOCALRID_MIN :
2158 	    req->id1.idmap_id_u.gid + INT32_MAX + 1;
2159 	res->direction = IDMAP_DIRECTION_BI;
2160 	if (res->id.idtype == IDMAP_SID)
2161 		res->id.idtype = is_user ? IDMAP_USID : IDMAP_GSID;
2162 
2163 	/*
2164 	 * Don't update name_cache because local sids don't have
2165 	 * valid windows names.
2166 	 */
2167 	req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
2168 	return (IDMAP_SUCCESS);
2169 }
2170 
2171 static
2172 idmap_retcode
2173 lookup_localsid2pid(idmap_mapping *req, idmap_id_res *res)
2174 {
2175 	char		*sidprefix;
2176 	uint32_t	rid;
2177 	int		s;
2178 
2179 	/*
2180 	 * If the sidprefix == localsid then UID = last RID - 1000 or
2181 	 * GID = last RID - 2^31.
2182 	 */
2183 	if ((sidprefix = req->id1.idmap_id_u.sid.prefix) == NULL)
2184 		/* This means we are looking up by winname */
2185 		return (IDMAP_ERR_NOTFOUND);
2186 	rid = req->id1.idmap_id_u.sid.rid;
2187 
2188 	RDLOCK_CONFIG();
2189 	s = (_idmapdstate.cfg->pgcfg.machine_sid) ?
2190 	    strcasecmp(sidprefix, _idmapdstate.cfg->pgcfg.machine_sid) : 1;
2191 	UNLOCK_CONFIG();
2192 
2193 	/*
2194 	 * If the given sidprefix does not match machine_sid then this is
2195 	 * not a local SID.
2196 	 */
2197 	if (s != 0)
2198 		return (IDMAP_ERR_NOTFOUND);
2199 
2200 	switch (res->id.idtype) {
2201 	case IDMAP_UID:
2202 		if (rid > INT32_MAX || rid < LOCALRID_MIN)
2203 			return (IDMAP_ERR_ARG);
2204 		res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
2205 		break;
2206 	case IDMAP_GID:
2207 		if (rid <= INT32_MAX)
2208 			return (IDMAP_ERR_ARG);
2209 		res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
2210 		break;
2211 	case IDMAP_POSIXID:
2212 		if (rid > INT32_MAX) {
2213 			res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
2214 			res->id.idtype = IDMAP_GID;
2215 		} else if (rid < LOCALRID_MIN) {
2216 			return (IDMAP_ERR_ARG);
2217 		} else {
2218 			res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
2219 			res->id.idtype = IDMAP_UID;
2220 		}
2221 		break;
2222 	default:
2223 		return (IDMAP_ERR_NOTSUPPORTED);
2224 	}
2225 	return (IDMAP_SUCCESS);
2226 }
2227 
2228 /*
2229  * Name service lookup by unixname to get pid
2230  */
2231 static
2232 idmap_retcode
2233 ns_lookup_byname(const char *name, const char *lower_name, idmap_id *id)
2234 {
2235 	struct passwd	pwd, *pwdp;
2236 	struct group	grp, *grpp;
2237 	char		buf[1024];
2238 	int		errnum;
2239 	const char	*me = "ns_lookup_byname";
2240 
2241 	switch (id->idtype) {
2242 	case IDMAP_UID:
2243 		pwdp = getpwnam_r(name, &pwd, buf, sizeof (buf));
2244 		if (pwdp == NULL && errno == 0 && lower_name != NULL &&
2245 		    name != lower_name && strcmp(name, lower_name) != 0)
2246 			pwdp = getpwnam_r(lower_name, &pwd, buf, sizeof (buf));
2247 		if (pwdp == NULL) {
2248 			errnum = errno;
2249 			idmapdlog(LOG_WARNING,
2250 			    "%s: getpwnam_r(%s) failed (%s).",
2251 			    me, name, errnum ? strerror(errnum) : "not found");
2252 			if (errnum == 0)
2253 				return (IDMAP_ERR_NOTFOUND);
2254 			else
2255 				return (IDMAP_ERR_INTERNAL);
2256 		}
2257 		id->idmap_id_u.uid = pwd.pw_uid;
2258 		break;
2259 	case IDMAP_GID:
2260 		grpp = getgrnam_r(name, &grp, buf, sizeof (buf));
2261 		if (grpp == NULL && errno == 0 && lower_name != NULL &&
2262 		    name != lower_name && strcmp(name, lower_name) != 0)
2263 			grpp = getgrnam_r(lower_name, &grp, buf, sizeof (buf));
2264 		if (grpp == NULL) {
2265 			errnum = errno;
2266 			idmapdlog(LOG_WARNING,
2267 			    "%s: getgrnam_r(%s) failed (%s).",
2268 			    me, name, errnum ? strerror(errnum) : "not found");
2269 			if (errnum == 0)
2270 				return (IDMAP_ERR_NOTFOUND);
2271 			else
2272 				return (IDMAP_ERR_INTERNAL);
2273 		}
2274 		id->idmap_id_u.gid = grp.gr_gid;
2275 		break;
2276 	default:
2277 		return (IDMAP_ERR_ARG);
2278 	}
2279 	return (IDMAP_SUCCESS);
2280 }
2281 
2282 
2283 /*
2284  * Name service lookup by pid to get unixname
2285  */
2286 static
2287 idmap_retcode
2288 ns_lookup_bypid(uid_t pid, int is_user, char **unixname)
2289 {
2290 	struct passwd	pwd;
2291 	struct group	grp;
2292 	char		buf[1024];
2293 	int		errnum;
2294 	const char	*me = "ns_lookup_bypid";
2295 
2296 	if (is_user) {
2297 		errno = 0;
2298 		if (getpwuid_r(pid, &pwd, buf, sizeof (buf)) == NULL) {
2299 			errnum = errno;
2300 			idmapdlog(LOG_WARNING,
2301 			    "%s: getpwuid_r(%u) failed (%s).",
2302 			    me, pid, errnum ? strerror(errnum) : "not found");
2303 			if (errnum == 0)
2304 				return (IDMAP_ERR_NOTFOUND);
2305 			else
2306 				return (IDMAP_ERR_INTERNAL);
2307 		}
2308 		*unixname = strdup(pwd.pw_name);
2309 	} else {
2310 		errno = 0;
2311 		if (getgrgid_r(pid, &grp, buf, sizeof (buf)) == NULL) {
2312 			errnum = errno;
2313 			idmapdlog(LOG_WARNING,
2314 			    "%s: getgrgid_r(%u) failed (%s).",
2315 			    me, pid, errnum ? strerror(errnum) : "not found");
2316 			if (errnum == 0)
2317 				return (IDMAP_ERR_NOTFOUND);
2318 			else
2319 				return (IDMAP_ERR_INTERNAL);
2320 		}
2321 		*unixname = strdup(grp.gr_name);
2322 	}
2323 	if (*unixname == NULL)
2324 		return (IDMAP_ERR_MEMORY);
2325 	return (IDMAP_SUCCESS);
2326 }
2327 
2328 /*
2329  * Name-based mapping
2330  *
2331  * Case 1: If no rule matches do ephemeral
2332  *
2333  * Case 2: If rule matches and unixname is "" then return no mapping.
2334  *
2335  * Case 3: If rule matches and unixname is specified then lookup name
2336  *  service using the unixname. If unixname not found then return no mapping.
2337  *
2338  * Case 4: If rule matches and unixname is * then lookup name service
2339  *  using winname as the unixname. If unixname not found then process
2340  *  other rules using the lookup order. If no other rule matches then do
2341  *  ephemeral. Otherwise, based on the matched rule do Case 2 or 3 or 4.
2342  *  This allows us to specify a fallback unixname per _domain_ or no mapping
2343  *  instead of the default behaviour of doing ephemeral mapping.
2344  *
2345  * Example 1:
2346  * *@sfbay == *
2347  * If looking up windows users foo@sfbay and foo does not exists in
2348  * the name service then foo@sfbay will be mapped to an ephemeral id.
2349  *
2350  * Example 2:
2351  * *@sfbay == *
2352  * *@sfbay => guest
2353  * If looking up windows users foo@sfbay and foo does not exists in
2354  * the name service then foo@sfbay will be mapped to guest.
2355  *
2356  * Example 3:
2357  * *@sfbay == *
2358  * *@sfbay => ""
2359  * If looking up windows users foo@sfbay and foo does not exists in
2360  * the name service then we will return no mapping for foo@sfbay.
2361  *
2362  */
2363 static
2364 idmap_retcode
2365 name_based_mapping_sid2pid(sqlite *db, idmap_mapping *req, idmap_id_res *res)
2366 {
2367 	const char	*unixname, *windomain;
2368 	char		*sql = NULL, *errmsg = NULL, *lower_winname = NULL;
2369 	idmap_retcode	retcode;
2370 	char		*end, *lower_unixname, *winname;
2371 	const char	**values;
2372 	sqlite_vm	*vm = NULL;
2373 	int		ncol, r, i, is_user, is_wuser;
2374 	const char	*me = "name_based_mapping_sid2pid";
2375 
2376 	assert(req->id1name != NULL); /* We have winname */
2377 	assert(req->id2name == NULL); /* We don't have unixname */
2378 
2379 	winname = req->id1name;
2380 	windomain = req->id1domain;
2381 
2382 	switch (req->id1.idtype) {
2383 	case IDMAP_USID:
2384 		is_wuser = 1;
2385 		break;
2386 	case IDMAP_GSID:
2387 		is_wuser = 0;
2388 		break;
2389 	default:
2390 		idmapdlog(LOG_ERR, "%s: Unable to determine if the "
2391 		    "given Windows id is user or group.", me);
2392 		return (IDMAP_ERR_INTERNAL);
2393 	}
2394 
2395 	switch (res->id.idtype) {
2396 	case IDMAP_UID:
2397 		is_user = 1;
2398 		break;
2399 	case IDMAP_GID:
2400 		is_user = 0;
2401 		break;
2402 	case IDMAP_POSIXID:
2403 		is_user = is_wuser;
2404 		res->id.idtype = is_user ? IDMAP_UID : IDMAP_GID;
2405 		break;
2406 	}
2407 
2408 	i = 0;
2409 	if (windomain == NULL) {
2410 		windomain = "";
2411 	} else {
2412 		RDLOCK_CONFIG();
2413 		if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
2414 			if (strcasecmp(_idmapdstate.cfg->pgcfg.default_domain,
2415 			    windomain) == 0)
2416 				i = 1;
2417 		}
2418 		UNLOCK_CONFIG();
2419 	}
2420 
2421 	if ((lower_winname = tolower_u8(winname)) == NULL)
2422 		lower_winname = winname;    /* hope for the best */
2423 	sql = sqlite_mprintf(
2424 	    "SELECT unixname, u2w_order FROM namerules WHERE "
2425 	    "w2u_order > 0 AND is_user = %d AND is_wuser = %d AND "
2426 	    "(winname = %Q OR winname = '*') AND "
2427 	    "(windomain = %Q OR windomain = '*' %s) "
2428 	    "ORDER BY w2u_order ASC;",
2429 	    is_user, is_wuser, lower_winname, windomain,
2430 	    i ? "OR windomain ISNULL OR windomain = ''" : "");
2431 	if (sql == NULL) {
2432 		idmapdlog(LOG_ERR, "Out of memory");
2433 		retcode = IDMAP_ERR_MEMORY;
2434 		goto out;
2435 	}
2436 
2437 	if (sqlite_compile(db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
2438 		retcode = IDMAP_ERR_INTERNAL;
2439 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
2440 		    CHECK_NULL(errmsg));
2441 		sqlite_freemem(errmsg);
2442 		goto out;
2443 	}
2444 
2445 	for (; ; ) {
2446 		r = sqlite_step(vm, &ncol, &values, NULL);
2447 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
2448 
2449 		if (r == SQLITE_ROW) {
2450 			if (ncol < 2) {
2451 				retcode = IDMAP_ERR_INTERNAL;
2452 				goto out;
2453 			}
2454 			if (values[0] == NULL) {
2455 				retcode = IDMAP_ERR_INTERNAL;
2456 				goto out;
2457 			}
2458 
2459 			if (EMPTY_NAME(values[0])) {
2460 				retcode = IDMAP_ERR_NOMAPPING;
2461 				goto out;
2462 			}
2463 			unixname = (values[0][0] == '*') ? winname : values[0];
2464 			lower_unixname = (values[0][0] == '*') ?
2465 			    lower_winname : NULL;
2466 			retcode = ns_lookup_byname(unixname, lower_unixname,
2467 			    &res->id);
2468 			if (retcode == IDMAP_ERR_NOTFOUND) {
2469 				if (unixname == winname)
2470 					/* Case 4 */
2471 					continue;
2472 				else
2473 					/* Case 3 */
2474 					retcode = IDMAP_ERR_NOMAPPING;
2475 			}
2476 			goto out;
2477 		} else if (r == SQLITE_DONE) {
2478 			retcode = IDMAP_ERR_NOTFOUND;
2479 			goto out;
2480 		} else {
2481 			(void) sqlite_finalize(vm, &errmsg);
2482 			vm = NULL;
2483 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
2484 			    CHECK_NULL(errmsg));
2485 			sqlite_freemem(errmsg);
2486 			retcode = IDMAP_ERR_INTERNAL;
2487 			goto out;
2488 		}
2489 	}
2490 
2491 out:
2492 	sqlite_freemem(sql);
2493 	if (retcode == IDMAP_SUCCESS) {
2494 		if (values[1] != NULL)
2495 			res->direction =
2496 			    (strtol(values[1], &end, 10) == 0)?
2497 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
2498 		else
2499 			res->direction = IDMAP_DIRECTION_W2U;
2500 		req->id2name = strdup(unixname);
2501 	}
2502 	if (lower_winname != NULL && lower_winname != winname)
2503 		free(lower_winname);
2504 	if (vm != NULL)
2505 		(void) sqlite_finalize(vm, NULL);
2506 	return (retcode);
2507 }
2508 
2509 static
2510 int
2511 get_next_eph_uid(uid_t *next_uid)
2512 {
2513 	uid_t uid;
2514 	gid_t gid;
2515 	int err;
2516 
2517 	*next_uid = (uid_t)-1;
2518 	uid = _idmapdstate.next_uid++;
2519 	if (uid >= _idmapdstate.limit_uid) {
2520 		if ((err = allocids(0, 8192, &uid, 0, &gid)) != 0)
2521 			return (err);
2522 
2523 		_idmapdstate.limit_uid = uid + 8192;
2524 		_idmapdstate.next_uid = uid;
2525 	}
2526 	*next_uid = uid;
2527 
2528 	return (0);
2529 }
2530 
2531 static
2532 int
2533 get_next_eph_gid(gid_t *next_gid)
2534 {
2535 	uid_t uid;
2536 	gid_t gid;
2537 	int err;
2538 
2539 	*next_gid = (uid_t)-1;
2540 	gid = _idmapdstate.next_gid++;
2541 	if (gid >= _idmapdstate.limit_gid) {
2542 		if ((err = allocids(0, 0, &uid, 8192, &gid)) != 0)
2543 			return (err);
2544 
2545 		_idmapdstate.limit_gid = gid + 8192;
2546 		_idmapdstate.next_gid = gid;
2547 	}
2548 	*next_gid = gid;
2549 
2550 	return (0);
2551 }
2552 
2553 static
2554 int
2555 gethash(const char *str, uint32_t num, uint_t htsize)
2556 {
2557 	uint_t  hval, i, len;
2558 
2559 	if (str == NULL)
2560 		return (0);
2561 	for (len = strlen(str), hval = 0, i = 0; i < len; i++) {
2562 		hval += str[i];
2563 		hval += (hval << 10);
2564 		hval ^= (hval >> 6);
2565 	}
2566 	for (str = (const char *)&num, i = 0; i < sizeof (num); i++) {
2567 		hval += str[i];
2568 		hval += (hval << 10);
2569 		hval ^= (hval >> 6);
2570 	}
2571 	hval += (hval << 3);
2572 	hval ^= (hval >> 11);
2573 	hval += (hval << 15);
2574 	return (hval % htsize);
2575 }
2576 
2577 static
2578 int
2579 get_from_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid,
2580 		uid_t *pid)
2581 {
2582 	uint_t		next, key;
2583 	uint_t		htsize = state->sid_history_size;
2584 	idmap_sid	*sid;
2585 
2586 	next = gethash(prefix, rid, htsize);
2587 	while (next != htsize) {
2588 		key = state->sid_history[next].key;
2589 		if (key == htsize)
2590 			return (0);
2591 		sid = &state->batch->idmap_mapping_batch_val[key].id1.
2592 		    idmap_id_u.sid;
2593 		if (sid->rid == rid && strcmp(sid->prefix, prefix) == 0) {
2594 			*pid = state->result->ids.ids_val[key].id.
2595 			    idmap_id_u.uid;
2596 			return (1);
2597 		}
2598 		next = state->sid_history[next].next;
2599 	}
2600 	return (0);
2601 }
2602 
2603 static
2604 void
2605 add_to_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid)
2606 {
2607 	uint_t		hash, next;
2608 	uint_t		htsize = state->sid_history_size;
2609 
2610 	hash = next = gethash(prefix, rid, htsize);
2611 	while (state->sid_history[next].key != htsize) {
2612 		next++;
2613 		next %= htsize;
2614 	}
2615 	state->sid_history[next].key = state->curpos;
2616 	if (hash == next)
2617 		return;
2618 	state->sid_history[next].next = state->sid_history[hash].next;
2619 	state->sid_history[hash].next = next;
2620 }
2621 
2622 void
2623 cleanup_lookup_state(lookup_state_t *state)
2624 {
2625 	free(state->sid_history);
2626 	free(state->ad_unixuser_attr);
2627 	free(state->ad_unixgroup_attr);
2628 }
2629 
2630 /* ARGSUSED */
2631 static
2632 idmap_retcode
2633 dynamic_ephemeral_mapping(lookup_state_t *state, sqlite *cache,
2634 		idmap_mapping *req, idmap_id_res *res)
2635 {
2636 
2637 	uid_t		next_pid;
2638 
2639 	res->direction = IDMAP_DIRECTION_BI;
2640 
2641 	if (IS_EPHEMERAL(res->id.idmap_id_u.uid))
2642 		return (IDMAP_SUCCESS);
2643 
2644 	if (state->sid_history != NULL &&
2645 	    get_from_sid_history(state, req->id1.idmap_id_u.sid.prefix,
2646 	    req->id1.idmap_id_u.sid.rid, &next_pid)) {
2647 		res->id.idmap_id_u.uid = next_pid;
2648 		return (IDMAP_SUCCESS);
2649 	}
2650 
2651 	if (res->id.idtype == IDMAP_UID) {
2652 		if (get_next_eph_uid(&next_pid) != 0)
2653 			return (IDMAP_ERR_INTERNAL);
2654 		res->id.idmap_id_u.uid = next_pid;
2655 	} else {
2656 		if (get_next_eph_gid(&next_pid) != 0)
2657 			return (IDMAP_ERR_INTERNAL);
2658 		res->id.idmap_id_u.gid = next_pid;
2659 	}
2660 
2661 	if (state->sid_history != NULL)
2662 		add_to_sid_history(state, req->id1.idmap_id_u.sid.prefix,
2663 		    req->id1.idmap_id_u.sid.rid);
2664 
2665 	return (IDMAP_SUCCESS);
2666 }
2667 
2668 idmap_retcode
2669 sid2pid_second_pass(lookup_state_t *state, sqlite *cache, sqlite *db,
2670 		idmap_mapping *req, idmap_id_res *res)
2671 {
2672 	idmap_retcode	retcode;
2673 
2674 	/* Check if second pass is needed */
2675 	if (ARE_WE_DONE(req->direction))
2676 		return (res->retcode);
2677 
2678 	/* Get status from previous pass */
2679 	retcode = res->retcode;
2680 	if (retcode != IDMAP_SUCCESS)
2681 		goto out;
2682 
2683 	/*
2684 	 * If directory-based name mapping is enabled then the unixname
2685 	 * may already have been retrieved from the AD object (AD-mode or
2686 	 * mixed-mode) or from native LDAP object (nldap-mode) -- done.
2687 	 */
2688 	if (req->id2name != NULL) {
2689 		assert(res->id.idtype != IDMAP_POSIXID);
2690 		if (AD_MODE(res->id.idtype, state))
2691 			res->direction = IDMAP_DIRECTION_BI;
2692 		else if (NLDAP_MODE(res->id.idtype, state))
2693 			res->direction = IDMAP_DIRECTION_BI;
2694 		else if (MIXED_MODE(res->id.idtype, state))
2695 			res->direction = IDMAP_DIRECTION_W2U;
2696 
2697 		/*
2698 		 * Special case: (1) If the ad_unixuser_attr and
2699 		 * ad_unixgroup_attr uses the same attribute
2700 		 * name and (2) if this is a diagonal mapping
2701 		 * request and (3) the unixname has been retrieved
2702 		 * from the AD object -- then we ignore it and fallback
2703 		 * to name-based mapping rules and ephemeral mapping
2704 		 *
2705 		 * Example:
2706 		 *  Properties:
2707 		 *    config/ad_unixuser_attr = "unixname"
2708 		 *    config/ad_unixgroup_attr = "unixname"
2709 		 *  AD user object:
2710 		 *    dn: cn=bob ...
2711 		 *    objectclass: user
2712 		 *    sam: bob
2713 		 *    unixname: bob1234
2714 		 *  AD group object:
2715 		 *    dn: cn=winadmins ...
2716 		 *    objectclass: group
2717 		 *    sam: winadmins
2718 		 *    unixname: unixadmins
2719 		 *
2720 		 *  In this example whether "unixname" refers to a unixuser
2721 		 *  or unixgroup depends upon the AD object.
2722 		 *
2723 		 * $idmap show -c winname:bob gid
2724 		 *    AD lookup by "samAccountName=bob" for
2725 		 *    "ad_unixgroup_attr (i.e unixname)" for directory-based
2726 		 *    mapping would get "bob1234" which is not what we want.
2727 		 *    Now why not getgrnam_r("bob1234") and use it if it
2728 		 *    is indeed a unixgroup? That's because Unix can have
2729 		 *    users and groups with the same name and we clearly
2730 		 *    don't know the intention of the admin here.
2731 		 *    Therefore we ignore this and fallback to name-based
2732 		 *    mapping rules or ephemeral mapping.
2733 		 */
2734 		if ((AD_MODE(res->id.idtype, state) ||
2735 		    MIXED_MODE(res->id.idtype, state)) &&
2736 		    state->ad_unixuser_attr != NULL &&
2737 		    state->ad_unixgroup_attr != NULL &&
2738 		    strcasecmp(state->ad_unixuser_attr,
2739 		    state->ad_unixgroup_attr) == 0 &&
2740 		    ((req->id1.idtype == IDMAP_USID &&
2741 		    res->id.idtype == IDMAP_GID) ||
2742 		    (req->id1.idtype == IDMAP_GSID &&
2743 		    res->id.idtype == IDMAP_UID))) {
2744 			free(req->id2name);
2745 			req->id2name = NULL;
2746 			res->id.idmap_id_u.uid = SENTINEL_PID;
2747 			/* fallback */
2748 		} else {
2749 			if (res->id.idmap_id_u.uid == SENTINEL_PID)
2750 				retcode = ns_lookup_byname(req->id2name,
2751 				    NULL, &res->id);
2752 			/*
2753 			 * We don't fallback to name-based mapping rules
2754 			 * or ephemeral mapping.
2755 			 */
2756 			goto out;
2757 		}
2758 	}
2759 
2760 	/*
2761 	 * If we don't have unixname then evaluate local name-based
2762 	 * mapping rules.
2763 	 */
2764 	retcode = name_based_mapping_sid2pid(db, req, res);
2765 	if (retcode != IDMAP_ERR_NOTFOUND)
2766 		goto out;
2767 
2768 	/* If not found, do ephemeral mapping */
2769 	retcode = dynamic_ephemeral_mapping(state, cache, req, res);
2770 
2771 out:
2772 	res->retcode = idmap_stat4prot(retcode);
2773 	if (res->retcode != IDMAP_SUCCESS) {
2774 		req->direction = _IDMAP_F_DONE;
2775 		res->id.idmap_id_u.uid = UID_NOBODY;
2776 	}
2777 	if (!ARE_WE_DONE(req->direction))
2778 		state->sid2pid_done = FALSE;
2779 	return (retcode);
2780 }
2781 
2782 idmap_retcode
2783 update_cache_pid2sid(lookup_state_t *state, sqlite *cache,
2784 		idmap_mapping *req, idmap_id_res *res)
2785 {
2786 	char		*sql = NULL;
2787 	idmap_retcode	retcode;
2788 
2789 	/* Check if we need to cache anything */
2790 	if (ARE_WE_DONE(req->direction))
2791 		return (IDMAP_SUCCESS);
2792 
2793 	/* We don't cache negative entries */
2794 	if (res->retcode != IDMAP_SUCCESS)
2795 		return (IDMAP_SUCCESS);
2796 
2797 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
2798 
2799 	/*
2800 	 * Using NULL for u2w instead of 0 so that our trigger allows
2801 	 * the same pid to be the destination in multiple entries
2802 	 */
2803 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
2804 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
2805 	    "is_user, is_wuser, expiration, w2u, u2w) "
2806 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
2807 	    "strftime('%%s','now') + 600, %q, 1); ",
2808 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
2809 	    req->id2domain, req->id2name, req->id1.idmap_id_u.uid,
2810 	    req->id1name, (req->id1.idtype == IDMAP_UID) ? 1 : 0,
2811 	    (res->id.idtype == IDMAP_USID) ? 1 : 0,
2812 	    (res->direction == 0) ? "1" : NULL);
2813 
2814 	if (sql == NULL) {
2815 		retcode = IDMAP_ERR_INTERNAL;
2816 		idmapdlog(LOG_ERR, "Out of memory");
2817 		goto out;
2818 	}
2819 
2820 	retcode = sql_exec_no_cb(cache, sql);
2821 	if (retcode != IDMAP_SUCCESS)
2822 		goto out;
2823 
2824 	state->pid2sid_done = FALSE;
2825 	sqlite_freemem(sql);
2826 	sql = NULL;
2827 
2828 	/* Check if we need to update namecache */
2829 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
2830 		goto out;
2831 
2832 	if (req->id2name == NULL)
2833 		goto out;
2834 
2835 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
2836 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
2837 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
2838 	    res->id.idmap_id_u.sid.prefix, res->id.idmap_id_u.sid.rid,
2839 	    req->id2name, req->id2domain,
2840 	    (res->id.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
2841 
2842 	if (sql == NULL) {
2843 		retcode = IDMAP_ERR_INTERNAL;
2844 		idmapdlog(LOG_ERR, "Out of memory");
2845 		goto out;
2846 	}
2847 
2848 	retcode = sql_exec_no_cb(cache, sql);
2849 
2850 out:
2851 	if (sql != NULL)
2852 		sqlite_freemem(sql);
2853 	return (retcode);
2854 }
2855 
2856 idmap_retcode
2857 update_cache_sid2pid(lookup_state_t *state, sqlite *cache,
2858 		idmap_mapping *req, idmap_id_res *res)
2859 {
2860 	char		*sql = NULL;
2861 	idmap_retcode	retcode;
2862 	int		is_eph_user;
2863 
2864 	/* Check if we need to cache anything */
2865 	if (ARE_WE_DONE(req->direction))
2866 		return (IDMAP_SUCCESS);
2867 
2868 	/* We don't cache negative entries */
2869 	if (res->retcode != IDMAP_SUCCESS)
2870 		return (IDMAP_SUCCESS);
2871 
2872 	if (req->direction & _IDMAP_F_EXP_EPH_UID)
2873 		is_eph_user = 1;
2874 	else if (req->direction & _IDMAP_F_EXP_EPH_GID)
2875 		is_eph_user = 0;
2876 	else
2877 		is_eph_user = -1;
2878 
2879 	if (is_eph_user >= 0 && !IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
2880 		sql = sqlite_mprintf("UPDATE idmap_cache "
2881 		    "SET w2u = 0 WHERE "
2882 		    "sidprefix = %Q AND rid = %u AND w2u = 1 AND "
2883 		    "pid >= 2147483648 AND is_user = %d;",
2884 		    req->id1.idmap_id_u.sid.prefix,
2885 		    req->id1.idmap_id_u.sid.rid,
2886 		    is_eph_user);
2887 		if (sql == NULL) {
2888 			retcode = IDMAP_ERR_INTERNAL;
2889 			idmapdlog(LOG_ERR, "Out of memory");
2890 			goto out;
2891 		}
2892 
2893 		retcode = sql_exec_no_cb(cache, sql);
2894 		if (retcode != IDMAP_SUCCESS)
2895 			goto out;
2896 
2897 		sqlite_freemem(sql);
2898 		sql = NULL;
2899 	}
2900 
2901 	assert(res->direction != IDMAP_DIRECTION_UNDEF);
2902 
2903 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
2904 	    "(sidprefix, rid, windomain, canon_winname, pid, unixname, "
2905 	    "is_user, is_wuser, expiration, w2u, u2w) "
2906 	    "VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, %d, "
2907 	    "strftime('%%s','now') + 600, 1, %q); ",
2908 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
2909 	    (req->id1domain != NULL) ? req->id1domain : "", req->id1name,
2910 	    res->id.idmap_id_u.uid, req->id2name,
2911 	    (res->id.idtype == IDMAP_UID) ? 1 : 0,
2912 	    (req->id1.idtype == IDMAP_USID) ? 1 : 0,
2913 	    (res->direction == 0) ? "1" : NULL);
2914 
2915 	if (sql == NULL) {
2916 		retcode = IDMAP_ERR_INTERNAL;
2917 		idmapdlog(LOG_ERR, "Out of memory");
2918 		goto out;
2919 	}
2920 
2921 	retcode = sql_exec_no_cb(cache, sql);
2922 	if (retcode != IDMAP_SUCCESS)
2923 		goto out;
2924 
2925 	state->sid2pid_done = FALSE;
2926 	sqlite_freemem(sql);
2927 	sql = NULL;
2928 
2929 	/* Check if we need to update namecache */
2930 	if (req->direction & _IDMAP_F_DONT_UPDATE_NAMECACHE)
2931 		goto out;
2932 
2933 	if (EMPTY_STRING(req->id1name))
2934 		goto out;
2935 
2936 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
2937 	    "(sidprefix, rid, canon_name, domain, type, expiration) "
2938 	    "VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
2939 	    req->id1.idmap_id_u.sid.prefix, req->id1.idmap_id_u.sid.rid,
2940 	    req->id1name, req->id1domain,
2941 	    (req->id1.idtype == IDMAP_USID) ? _IDMAP_T_USER : _IDMAP_T_GROUP);
2942 
2943 	if (sql == NULL) {
2944 		retcode = IDMAP_ERR_INTERNAL;
2945 		idmapdlog(LOG_ERR, "Out of memory");
2946 		goto out;
2947 	}
2948 
2949 	retcode = sql_exec_no_cb(cache, sql);
2950 
2951 out:
2952 	if (sql != NULL)
2953 		sqlite_freemem(sql);
2954 	return (retcode);
2955 }
2956 
2957 static
2958 idmap_retcode
2959 lookup_cache_pid2sid(sqlite *cache, idmap_mapping *req, idmap_id_res *res,
2960 		int is_user, int getname)
2961 {
2962 	char		*end;
2963 	char		*sql = NULL;
2964 	const char	**values;
2965 	sqlite_vm	*vm = NULL;
2966 	int		ncol;
2967 	idmap_retcode	retcode = IDMAP_SUCCESS;
2968 	time_t		curtime;
2969 	idmap_id_type	idtype;
2970 
2971 	/* Current time */
2972 	errno = 0;
2973 	if ((curtime = time(NULL)) == (time_t)-1) {
2974 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
2975 		    strerror(errno));
2976 		retcode = IDMAP_ERR_INTERNAL;
2977 		goto out;
2978 	}
2979 
2980 	/* SQL to lookup the cache by pid or by unixname */
2981 	if (req->id1.idmap_id_u.uid != SENTINEL_PID) {
2982 		sql = sqlite_mprintf("SELECT sidprefix, rid, canon_winname, "
2983 		    "windomain, w2u, is_wuser "
2984 		    "FROM idmap_cache WHERE "
2985 		    "pid = %u AND u2w = 1 AND is_user = %d AND "
2986 		    "(pid >= 2147483648 OR "
2987 		    "(expiration = 0 OR expiration ISNULL OR "
2988 		    "expiration > %d));",
2989 		    req->id1.idmap_id_u.uid, is_user, curtime);
2990 	} else if (req->id1name != NULL) {
2991 		sql = sqlite_mprintf("SELECT sidprefix, rid, canon_winname, "
2992 		    "windomain, w2u, is_wuser "
2993 		    "FROM idmap_cache WHERE "
2994 		    "unixname = %Q AND u2w = 1 AND is_user = %d AND "
2995 		    "(pid >= 2147483648 OR "
2996 		    "(expiration = 0 OR expiration ISNULL OR "
2997 		    "expiration > %d));",
2998 		    req->id1name, is_user, curtime);
2999 	}
3000 
3001 	if (sql == NULL) {
3002 		idmapdlog(LOG_ERR, "Out of memory");
3003 		retcode = IDMAP_ERR_MEMORY;
3004 		goto out;
3005 	}
3006 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 5, &values);
3007 	sqlite_freemem(sql);
3008 
3009 	if (retcode == IDMAP_ERR_NOTFOUND)
3010 		goto out;
3011 	else if (retcode == IDMAP_SUCCESS) {
3012 		/* sanity checks */
3013 		if (values[0] == NULL || values[1] == NULL) {
3014 			retcode = IDMAP_ERR_CACHE;
3015 			goto out;
3016 		}
3017 
3018 		switch (res->id.idtype) {
3019 		case IDMAP_SID:
3020 		case IDMAP_USID:
3021 		case IDMAP_GSID:
3022 			idtype = strtol(values[5], &end, 10) == 1
3023 			    ? IDMAP_USID : IDMAP_GSID;
3024 
3025 			if (res->id.idtype == IDMAP_USID &&
3026 			    idtype != IDMAP_USID) {
3027 				retcode = IDMAP_ERR_NOTUSER;
3028 				goto out;
3029 			} else if (res->id.idtype == IDMAP_GSID &&
3030 			    idtype != IDMAP_GSID) {
3031 				retcode = IDMAP_ERR_NOTGROUP;
3032 				goto out;
3033 			}
3034 			res->id.idtype = idtype;
3035 
3036 			res->id.idmap_id_u.sid.rid =
3037 			    strtoul(values[1], &end, 10);
3038 			res->id.idmap_id_u.sid.prefix = strdup(values[0]);
3039 			if (res->id.idmap_id_u.sid.prefix == NULL) {
3040 				idmapdlog(LOG_ERR, "Out of memory");
3041 				retcode = IDMAP_ERR_MEMORY;
3042 				goto out;
3043 			}
3044 
3045 			if (values[4] != NULL)
3046 				res->direction =
3047 				    (strtol(values[4], &end, 10) == 0)?
3048 				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
3049 			else
3050 				res->direction = IDMAP_DIRECTION_U2W;
3051 
3052 			if (getname == 0 || values[2] == NULL)
3053 				break;
3054 			req->id2name = strdup(values[2]);
3055 			if (req->id2name == NULL) {
3056 				idmapdlog(LOG_ERR, "Out of memory");
3057 				retcode = IDMAP_ERR_MEMORY;
3058 				goto out;
3059 			}
3060 
3061 			if (values[3] == NULL)
3062 				break;
3063 			req->id2domain = strdup(values[3]);
3064 			if (req->id2domain == NULL) {
3065 				idmapdlog(LOG_ERR, "Out of memory");
3066 				retcode = IDMAP_ERR_MEMORY;
3067 				goto out;
3068 			}
3069 
3070 			break;
3071 		default:
3072 			retcode = IDMAP_ERR_NOTSUPPORTED;
3073 			break;
3074 		}
3075 	}
3076 
3077 out:
3078 	if (vm != NULL)
3079 		(void) sqlite_finalize(vm, NULL);
3080 	return (retcode);
3081 }
3082 
3083 static
3084 idmap_retcode
3085 lookup_cache_name2sid(sqlite *cache, const char *name, const char *domain,
3086 	char **canonname, char **sidprefix, idmap_rid_t *rid, int *type)
3087 {
3088 	char		*end, *lower_name;
3089 	char		*sql = NULL;
3090 	const char	**values;
3091 	sqlite_vm	*vm = NULL;
3092 	int		ncol;
3093 	time_t		curtime;
3094 	idmap_retcode	retcode = IDMAP_SUCCESS;
3095 
3096 	/* Get current time */
3097 	errno = 0;
3098 	if ((curtime = time(NULL)) == (time_t)-1) {
3099 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
3100 		    strerror(errno));
3101 		retcode = IDMAP_ERR_INTERNAL;
3102 		goto out;
3103 	}
3104 
3105 	/* SQL to lookup the cache */
3106 	if ((lower_name = tolower_u8(name)) == NULL)
3107 		lower_name = (char *)name;
3108 	sql = sqlite_mprintf("SELECT sidprefix, rid, type, canon_name "
3109 	    "FROM name_cache WHERE name = %Q AND domain = %Q AND "
3110 	    "(expiration = 0 OR expiration ISNULL OR "
3111 	    "expiration > %d);", lower_name, domain, curtime);
3112 	if (lower_name != name)
3113 		free(lower_name);
3114 	if (sql == NULL) {
3115 		idmapdlog(LOG_ERR, "Out of memory");
3116 		retcode = IDMAP_ERR_MEMORY;
3117 		goto out;
3118 	}
3119 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 4, &values);
3120 	sqlite_freemem(sql);
3121 
3122 	if (retcode == IDMAP_SUCCESS) {
3123 		if (type != NULL) {
3124 			if (values[2] == NULL) {
3125 				retcode = IDMAP_ERR_CACHE;
3126 				goto out;
3127 			}
3128 			*type = strtol(values[2], &end, 10);
3129 		}
3130 
3131 		if (values[0] == NULL || values[1] == NULL) {
3132 			retcode = IDMAP_ERR_CACHE;
3133 			goto out;
3134 		}
3135 
3136 		if (canonname != NULL) {
3137 			assert(values[3] != NULL);
3138 			if ((*canonname = strdup(values[3])) == NULL) {
3139 				idmapdlog(LOG_ERR, "Out of memory");
3140 				retcode = IDMAP_ERR_MEMORY;
3141 				goto out;
3142 			}
3143 		}
3144 
3145 		if ((*sidprefix = strdup(values[0])) == NULL) {
3146 			idmapdlog(LOG_ERR, "Out of memory");
3147 			retcode = IDMAP_ERR_MEMORY;
3148 			if (canonname != NULL) {
3149 				free(*canonname);
3150 				*canonname = NULL;
3151 			}
3152 			goto out;
3153 		}
3154 		*rid = strtoul(values[1], &end, 10);
3155 	}
3156 
3157 out:
3158 	if (vm != NULL)
3159 		(void) sqlite_finalize(vm, NULL);
3160 	return (retcode);
3161 }
3162 
3163 static
3164 idmap_retcode
3165 ad_lookup_by_winname(lookup_state_t *state,
3166 		const char *name, const char *domain, int eunixtype,
3167 		char **canonname, char **sidprefix,
3168 		idmap_rid_t *rid, int *wintype, char **unixname)
3169 {
3170 	int			retries = 0;
3171 	idmap_query_state_t	*qs = NULL;
3172 	idmap_retcode		rc, retcode;
3173 
3174 retry:
3175 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, 1, &qs);
3176 	if (retcode != IDMAP_SUCCESS) {
3177 		degrade_svc();
3178 		idmapdlog(LOG_ERR,
3179 		    "Failed to create request for AD lookup by winname");
3180 		return (retcode);
3181 	}
3182 
3183 	restore_svc();
3184 
3185 	if (state != NULL)
3186 		idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
3187 		    state->ad_unixgroup_attr);
3188 
3189 	retcode = idmap_name2sid_batch_add1(qs, name, domain, eunixtype,
3190 	    canonname, sidprefix, rid, wintype, unixname, &rc);
3191 
3192 	if (retcode != IDMAP_SUCCESS)
3193 		idmap_lookup_release_batch(&qs);
3194 	else
3195 		retcode = idmap_lookup_batch_end(&qs, NULL);
3196 
3197 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
3198 		goto retry;
3199 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
3200 		degrade_svc();
3201 
3202 	if (retcode != IDMAP_SUCCESS) {
3203 		idmapdlog(LOG_NOTICE, "AD lookup by winname failed");
3204 		return (retcode);
3205 	}
3206 	return (rc);
3207 }
3208 
3209 static
3210 idmap_retcode
3211 lookup_name2sid(sqlite *cache, const char *name, const char *domain,
3212 		int *is_wuser, char **canonname, char **sidprefix,
3213 		idmap_rid_t *rid, idmap_mapping *req)
3214 {
3215 	int		type;
3216 	idmap_retcode	retcode;
3217 
3218 	*sidprefix = NULL;
3219 	if (canonname != NULL)
3220 		*canonname = NULL;
3221 
3222 	/* Lookup well-known SIDs table */
3223 	retcode = lookup_wksids_name2sid(name, canonname, sidprefix, rid,
3224 	    &type);
3225 	if (retcode == IDMAP_SUCCESS) {
3226 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
3227 		goto out;
3228 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
3229 		return (retcode);
3230 	}
3231 
3232 	/* Lookup cache */
3233 	retcode = lookup_cache_name2sid(cache, name, domain, canonname,
3234 	    sidprefix, rid, &type);
3235 	if (retcode == IDMAP_SUCCESS) {
3236 		req->direction |= _IDMAP_F_DONT_UPDATE_NAMECACHE;
3237 		goto out;
3238 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
3239 		return (retcode);
3240 	}
3241 
3242 	/* Lookup AD */
3243 	retcode = ad_lookup_by_winname(NULL, name, domain, _IDMAP_T_UNDEF,
3244 	    canonname, sidprefix, rid, &type, NULL);
3245 	if (retcode != IDMAP_SUCCESS)
3246 		return (retcode);
3247 	/* Don't need to set req->direction |= _IDMAP_F_LOOKUP_AD; */
3248 
3249 out:
3250 	/*
3251 	 * Entry found (cache or Windows lookup)
3252 	 * is_wuser is both input as well as output parameter
3253 	 */
3254 	if (*is_wuser == 1 && type != _IDMAP_T_USER)
3255 		retcode = IDMAP_ERR_NOTUSER;
3256 	else if (*is_wuser == 0 && type != _IDMAP_T_GROUP)
3257 		retcode = IDMAP_ERR_NOTGROUP;
3258 	else if (*is_wuser == -1) {
3259 		/* Caller wants to know if its user or group */
3260 		if (type == _IDMAP_T_USER)
3261 			*is_wuser = 1;
3262 		else if (type == _IDMAP_T_GROUP)
3263 			*is_wuser = 0;
3264 		else
3265 			retcode = IDMAP_ERR_SID;
3266 	}
3267 
3268 	if (retcode != IDMAP_SUCCESS) {
3269 		free(*sidprefix);
3270 		*sidprefix = NULL;
3271 		if (canonname != NULL) {
3272 			free(*canonname);
3273 			*canonname = NULL;
3274 		}
3275 	}
3276 	return (retcode);
3277 }
3278 
3279 static
3280 idmap_retcode
3281 name_based_mapping_pid2sid(sqlite *db, sqlite *cache, const char *unixname,
3282 		int is_user, idmap_mapping *req, idmap_id_res *res)
3283 {
3284 	const char	*winname, *windomain;
3285 	char		*canonname;
3286 	char		*default_domain = NULL;
3287 	char		*sql = NULL, *errmsg = NULL;
3288 	idmap_retcode	retcode;
3289 	char		*end;
3290 	const char	**values;
3291 	sqlite_vm	*vm = NULL;
3292 	int		ncol, r, nrow;
3293 	int		is_wuser;
3294 	const char	*me = "name_based_mapping_pid2sid";
3295 
3296 	assert(unixname != NULL); /* We have unixname */
3297 	assert(req->id2name == NULL); /* We don't have winname */
3298 	assert(res->id.idmap_id_u.sid.prefix == NULL); /* No SID either */
3299 
3300 	RDLOCK_CONFIG();
3301 	if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
3302 		default_domain =
3303 		    strdup(_idmapdstate.cfg->pgcfg.default_domain);
3304 		if (default_domain == NULL) {
3305 			UNLOCK_CONFIG();
3306 			idmapdlog(LOG_ERR, "Out of memory");
3307 			retcode = IDMAP_ERR_MEMORY;
3308 			goto out;
3309 		}
3310 	}
3311 	UNLOCK_CONFIG();
3312 
3313 	sql = sqlite_mprintf(
3314 	    "SELECT winname_display, windomain, w2u_order FROM namerules WHERE "
3315 	    "u2w_order > 0 AND is_user = %d AND "
3316 	    "(unixname = %Q OR unixname = '*') "
3317 	    "ORDER BY u2w_order ASC;", is_user, unixname);
3318 	if (sql == NULL) {
3319 		idmapdlog(LOG_ERR, "Out of memory");
3320 		retcode = IDMAP_ERR_MEMORY;
3321 		goto out;
3322 	}
3323 
3324 	if (sqlite_compile(db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
3325 		retcode = IDMAP_ERR_INTERNAL;
3326 		idmapdlog(LOG_ERR, "%s: database error (%s)", me,
3327 		    CHECK_NULL(errmsg));
3328 		sqlite_freemem(errmsg);
3329 		goto out;
3330 	}
3331 
3332 	for (nrow = 0; ; ) {
3333 		r = sqlite_step(vm, &ncol, &values, NULL);
3334 		assert(r != SQLITE_LOCKED && r != SQLITE_BUSY);
3335 		if (r == SQLITE_ROW) {
3336 			nrow++;
3337 			if (ncol < 3) {
3338 				retcode = IDMAP_ERR_INTERNAL;
3339 				goto out;
3340 			}
3341 			if (values[0] == NULL) {
3342 				/* values [1] and [2] can be null */
3343 				retcode = IDMAP_ERR_INTERNAL;
3344 				goto out;
3345 			}
3346 			if (EMPTY_NAME(values[0])) {
3347 				retcode = IDMAP_ERR_NOMAPPING;
3348 				goto out;
3349 			}
3350 
3351 			if (values[0][0] == '*') {
3352 				if (nrow > 1) {
3353 					/*
3354 					 * There were non-wildcard rules where
3355 					 * windows identity doesn't exist
3356 					 */
3357 					retcode = IDMAP_ERR_NOMAPPING;
3358 					goto out;
3359 				}
3360 				winname = unixname;
3361 			} else {
3362 				winname = values[0];
3363 			}
3364 
3365 			if (values[1] != NULL)
3366 				windomain = values[1];
3367 			else if (default_domain != NULL)
3368 				windomain = default_domain;
3369 			else {
3370 				idmapdlog(LOG_ERR, "%s: no domain", me);
3371 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
3372 				goto out;
3373 			}
3374 			/* Lookup winname@domain to sid */
3375 
3376 			is_wuser = res->id.idtype == IDMAP_USID ? 1
3377 			    : res->id.idtype == IDMAP_GSID ? 0
3378 			    : -1;
3379 
3380 			retcode = lookup_name2sid(cache, winname, windomain,
3381 			    &is_wuser, &canonname,
3382 			    &res->id.idmap_id_u.sid.prefix,
3383 			    &res->id.idmap_id_u.sid.rid, req);
3384 
3385 			if (retcode == IDMAP_ERR_NOTFOUND) {
3386 				continue;
3387 			}
3388 
3389 			goto out;
3390 		} else if (r == SQLITE_DONE) {
3391 			retcode = IDMAP_ERR_NOTFOUND;
3392 			goto out;
3393 		} else {
3394 			(void) sqlite_finalize(vm, &errmsg);
3395 			vm = NULL;
3396 			idmapdlog(LOG_ERR, "%s: database error (%s)", me,
3397 			    CHECK_NULL(errmsg));
3398 			sqlite_freemem(errmsg);
3399 			retcode = IDMAP_ERR_INTERNAL;
3400 			goto out;
3401 		}
3402 	}
3403 
3404 out:
3405 	if (sql != NULL)
3406 		sqlite_freemem(sql);
3407 	if (retcode == IDMAP_SUCCESS) {
3408 		res->id.idtype = is_wuser ? IDMAP_USID : IDMAP_GSID;
3409 
3410 		if (values[2] != NULL)
3411 			res->direction =
3412 			    (strtol(values[2], &end, 10) == 0)?
3413 			    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
3414 		else
3415 			res->direction = IDMAP_DIRECTION_U2W;
3416 
3417 		req->id2name = canonname;
3418 		if (req->id2name != NULL) {
3419 			if (windomain == default_domain) {
3420 				req->id2domain = (char *)windomain;
3421 				default_domain = NULL;
3422 			} else {
3423 				req->id2domain = strdup(windomain);
3424 			}
3425 		}
3426 	}
3427 	if (vm != NULL)
3428 		(void) sqlite_finalize(vm, NULL);
3429 	if (default_domain != NULL)
3430 		free(default_domain);
3431 	return (retcode);
3432 }
3433 
3434 /*
3435  * Convention when processing unix2win requests:
3436  *
3437  * Unix identity:
3438  * req->id1name =
3439  *              unixname if given otherwise unixname found will be placed
3440  *              here.
3441  * req->id1domain =
3442  *              NOT USED
3443  * req->id1.idtype =
3444  *              Given type (IDMAP_UID or IDMAP_GID)
3445  * req->id1..[uid or gid] =
3446  *              UID/GID if given otherwise UID/GID found will be placed here.
3447  *
3448  * Windows identity:
3449  * req->id2name =
3450  *              winname found will be placed here.
3451  * req->id2domain =
3452  *              windomain found will be placed here.
3453  * res->id.idtype =
3454  *              Target type initialized from req->id2.idtype. If
3455  *              it is IDMAP_SID then actual type (IDMAP_USID/GSID) found
3456  *              will be placed here.
3457  * req->id..sid.[prefix, rid] =
3458  *              SID found will be placed here.
3459  *
3460  * Others:
3461  * res->retcode =
3462  *              Return status for this request will be placed here.
3463  * res->direction =
3464  *              Direction found will be placed here. Direction
3465  *              meaning whether the resultant mapping is valid
3466  *              only from unix2win or bi-directional.
3467  * req->direction =
3468  *              INTERNAL USE. Used by idmapd to set various
3469  *              flags (_IDMAP_F_xxxx) to aid in processing
3470  *              of the request.
3471  * req->id2.idtype =
3472  *              INTERNAL USE. Initially this is the requested target
3473  *              type and is used to initialize res->id.idtype.
3474  *              ad_lookup_batch() uses this field temporarily to store
3475  *              sid_type obtained by the batched AD lookups and after
3476  *              use resets it to IDMAP_NONE to prevent xdr from
3477  *              mis-interpreting the contents of req->id2.
3478  * req->id2..[uid or gid or sid] =
3479  *              NOT USED
3480  */
3481 
3482 /*
3483  * This function does the following:
3484  * 1. Lookup well-known SIDs table.
3485  * 2. Lookup cache.
3486  * 3. Check if the client does not want new mapping to be allocated
3487  *    in which case this pass is the final pass.
3488  * 4. Set AD/NLDAP lookup flags if it determines that the next stage needs
3489  *    to do AD/NLDAP lookup.
3490  */
3491 idmap_retcode
3492 pid2sid_first_pass(lookup_state_t *state, sqlite *cache,
3493 		idmap_mapping *req, idmap_id_res *res, int is_user,
3494 		int getname)
3495 {
3496 	idmap_retcode	retcode;
3497 	bool_t		gen_localsid_on_err = FALSE;
3498 
3499 	/* Initialize result */
3500 	res->id.idtype = req->id2.idtype;
3501 	res->direction = IDMAP_DIRECTION_UNDEF;
3502 
3503 	if (req->id2.idmap_id_u.sid.prefix != NULL) {
3504 		/* sanitize sidprefix */
3505 		free(req->id2.idmap_id_u.sid.prefix);
3506 		req->id2.idmap_id_u.sid.prefix = NULL;
3507 	}
3508 
3509 	/* Lookup well-known SIDs table */
3510 	retcode = lookup_wksids_pid2sid(req, res, is_user);
3511 	if (retcode != IDMAP_ERR_NOTFOUND)
3512 		goto out;
3513 
3514 	/* Lookup cache */
3515 	retcode = lookup_cache_pid2sid(cache, req, res, is_user, getname);
3516 	if (retcode != IDMAP_ERR_NOTFOUND)
3517 		goto out;
3518 
3519 	/* Ephemeral ids cannot be allocated during pid2sid */
3520 	if (IS_EPHEMERAL(req->id1.idmap_id_u.uid)) {
3521 		retcode = IDMAP_ERR_NOMAPPING;
3522 		goto out;
3523 	}
3524 
3525 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req) || AVOID_NAMESERVICE(req)) {
3526 		gen_localsid_on_err = TRUE;
3527 		retcode = IDMAP_ERR_NOMAPPING;
3528 		goto out;
3529 	}
3530 
3531 	/* Set flags for the next stage */
3532 	if (AD_MODE(req->id1.idtype, state)) {
3533 		/*
3534 		 * If AD-based name mapping is enabled then the next stage
3535 		 * will need to lookup AD using unixname to get the
3536 		 * corresponding winname.
3537 		 */
3538 		if (req->id1name == NULL) {
3539 			/* Get unixname if only pid is given. */
3540 			retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid,
3541 			    is_user, &req->id1name);
3542 			if (retcode != IDMAP_SUCCESS)
3543 				goto out;
3544 		}
3545 		req->direction |= _IDMAP_F_LOOKUP_AD;
3546 		state->ad_nqueries++;
3547 	} else if (NLDAP_OR_MIXED_MODE(req->id1.idtype, state)) {
3548 		/*
3549 		 * If native LDAP or mixed mode is enabled for name mapping
3550 		 * then the next stage will need to lookup native LDAP using
3551 		 * unixname/pid to get the corresponding winname.
3552 		 */
3553 		req->direction |= _IDMAP_F_LOOKUP_NLDAP;
3554 		state->nldap_nqueries++;
3555 	}
3556 
3557 	/*
3558 	 * Failed to find non-expired entry in cache. Set the flag to
3559 	 * indicate that we are not done yet.
3560 	 */
3561 	state->pid2sid_done = FALSE;
3562 	req->direction |= _IDMAP_F_NOTDONE;
3563 	retcode = IDMAP_SUCCESS;
3564 
3565 out:
3566 	res->retcode = idmap_stat4prot(retcode);
3567 	if (ARE_WE_DONE(req->direction) && res->retcode != IDMAP_SUCCESS)
3568 		if (gen_localsid_on_err == TRUE)
3569 			(void) generate_localsid(req, res, is_user);
3570 	return (retcode);
3571 }
3572 
3573 idmap_retcode
3574 pid2sid_second_pass(lookup_state_t *state, sqlite *cache, sqlite *db,
3575 		idmap_mapping *req, idmap_id_res *res, int is_user)
3576 {
3577 	bool_t		gen_localsid_on_err = TRUE;
3578 	idmap_retcode	retcode = IDMAP_SUCCESS;
3579 
3580 	/* Check if second pass is needed */
3581 	if (ARE_WE_DONE(req->direction))
3582 		return (res->retcode);
3583 
3584 	/* Get status from previous pass */
3585 	retcode = res->retcode;
3586 	if (retcode != IDMAP_SUCCESS)
3587 		goto out;
3588 
3589 	/*
3590 	 * If directory-based name mapping is enabled then the winname
3591 	 * may already have been retrieved from the AD object (AD-mode)
3592 	 * or from native LDAP object (nldap-mode or mixed-mode) -- done.
3593 	 */
3594 	if (res->id.idmap_id_u.sid.prefix != NULL || req->id2name != NULL) {
3595 		if (AD_MODE(req->id1.idtype, state))
3596 			res->direction = IDMAP_DIRECTION_BI;
3597 		else if (NLDAP_MODE(req->id1.idtype, state))
3598 			res->direction = IDMAP_DIRECTION_BI;
3599 		else if (MIXED_MODE(req->id1.idtype, state))
3600 			res->direction = IDMAP_DIRECTION_W2U;
3601 		goto out;
3602 	}
3603 
3604 	if (req->id1name == NULL) {
3605 		/* Get unixname from name service */
3606 		retcode = ns_lookup_bypid(req->id1.idmap_id_u.uid, is_user,
3607 		    &req->id1name);
3608 		if (retcode != IDMAP_SUCCESS)
3609 			goto out;
3610 	} else if (req->id1.idmap_id_u.uid == SENTINEL_PID) {
3611 		/* Get pid from name service */
3612 		retcode = ns_lookup_byname(req->id1name, NULL, &req->id1);
3613 		if (retcode != IDMAP_SUCCESS) {
3614 			gen_localsid_on_err = FALSE;
3615 			goto out;
3616 		}
3617 	}
3618 
3619 	/* Use unixname to evaluate local name-based mapping rules */
3620 	retcode = name_based_mapping_pid2sid(db, cache, req->id1name, is_user,
3621 	    req, res);
3622 	if (retcode == IDMAP_ERR_NOTFOUND) {
3623 		retcode = generate_localsid(req, res, is_user);
3624 		gen_localsid_on_err = FALSE;
3625 	}
3626 
3627 out:
3628 	res->retcode = idmap_stat4prot(retcode);
3629 	if (res->retcode != IDMAP_SUCCESS) {
3630 		req->direction = _IDMAP_F_DONE;
3631 		if (gen_localsid_on_err == TRUE)
3632 			(void) generate_localsid(req, res, is_user);
3633 	}
3634 	if (!ARE_WE_DONE(req->direction))
3635 		state->pid2sid_done = FALSE;
3636 	return (retcode);
3637 }
3638 
3639 static
3640 idmap_retcode
3641 ad_lookup_by_sid(lookup_state_t *state,
3642 		const char *sidprefix, idmap_rid_t rid, int eunixtype,
3643 		char **name, char **domain, int *type, char **unixname)
3644 {
3645 	int			retries = 0;
3646 	idmap_query_state_t	*qs = NULL;
3647 	idmap_retcode		rc, retcode;
3648 
3649 retry:
3650 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, 1, &qs);
3651 	if (retcode != IDMAP_SUCCESS) {
3652 		degrade_svc();
3653 		idmapdlog(LOG_ERR,
3654 		    "Failed to create request for AD lookup by SID");
3655 		return (retcode);
3656 	}
3657 
3658 	restore_svc();
3659 
3660 	if (state != NULL)
3661 		idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
3662 		    state->ad_unixgroup_attr);
3663 
3664 	retcode = idmap_sid2name_batch_add1(qs, sidprefix, &rid, eunixtype,
3665 	    name, domain, type, unixname, &rc);
3666 
3667 	if (retcode != IDMAP_SUCCESS)
3668 		idmap_lookup_release_batch(&qs);
3669 	else
3670 		retcode = idmap_lookup_batch_end(&qs, NULL);
3671 
3672 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
3673 		goto retry;
3674 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
3675 		degrade_svc();
3676 
3677 	if (retcode != IDMAP_SUCCESS) {
3678 		idmapdlog(LOG_NOTICE, "AD lookup by SID failed");
3679 		return (retcode);
3680 	}
3681 	return (rc);
3682 }
3683 
3684 static
3685 int
3686 copy_mapping_request(idmap_mapping *mapping, idmap_mapping *request)
3687 {
3688 	(void) memset(mapping, 0, sizeof (*mapping));
3689 
3690 	mapping->flag = request->flag;
3691 	mapping->direction = _IDMAP_F_DONE;
3692 	mapping->id2.idtype = request->id2.idtype;
3693 
3694 	mapping->id1.idtype = request->id1.idtype;
3695 	if (IS_REQUEST_SID(*request, 1)) {
3696 		mapping->id1.idmap_id_u.sid.rid =
3697 		    request->id1.idmap_id_u.sid.rid;
3698 		if (!EMPTY_STRING(request->id1.idmap_id_u.sid.prefix)) {
3699 			mapping->id1.idmap_id_u.sid.prefix =
3700 			    strdup(request->id1.idmap_id_u.sid.prefix);
3701 			if (mapping->id1.idmap_id_u.sid.prefix == NULL)
3702 				goto errout;
3703 		}
3704 	} else {
3705 		mapping->id1.idmap_id_u.uid = request->id1.idmap_id_u.uid;
3706 	}
3707 
3708 	if (!EMPTY_STRING(request->id1domain)) {
3709 		mapping->id1domain = strdup(request->id1domain);
3710 		if (mapping->id1domain == NULL)
3711 			goto errout;
3712 	}
3713 
3714 	if (!EMPTY_STRING(request->id1name)) {
3715 		mapping->id1name = strdup(request->id1name);
3716 		if (mapping->id1name == NULL)
3717 			goto errout;
3718 	}
3719 
3720 	/* We don't need the rest of the request i.e request->id2 */
3721 	return (0);
3722 
3723 errout:
3724 	if (mapping->id1.idmap_id_u.sid.prefix != NULL)
3725 		free(mapping->id1.idmap_id_u.sid.prefix);
3726 	if (mapping->id1domain != NULL)
3727 		free(mapping->id1domain);
3728 	if (mapping->id1name != NULL)
3729 		free(mapping->id1name);
3730 
3731 	(void) memset(mapping, 0, sizeof (*mapping));
3732 	return (-1);
3733 }
3734 
3735 
3736 idmap_retcode
3737 get_w2u_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
3738 		idmap_mapping *mapping)
3739 {
3740 	idmap_id_res	idres;
3741 	lookup_state_t	state;
3742 	char		*cp;
3743 	idmap_retcode	retcode;
3744 	const char	*winname, *windomain;
3745 
3746 	(void) memset(&idres, 0, sizeof (idres));
3747 	(void) memset(&state, 0, sizeof (state));
3748 
3749 	/* Get directory-based name mapping info */
3750 	retcode = get_ds_namemap_type(&state);
3751 	if (retcode != IDMAP_SUCCESS)
3752 		goto out;
3753 
3754 	/*
3755 	 * Copy data from "request" to "mapping". Note that
3756 	 * empty strings are not copied from "request" to
3757 	 * "mapping" and therefore the coresponding strings in
3758 	 * "mapping" will be NULL. This eliminates having to
3759 	 * check for empty strings henceforth.
3760 	 */
3761 	if (copy_mapping_request(mapping, request) < 0) {
3762 		retcode = IDMAP_ERR_MEMORY;
3763 		goto out;
3764 	}
3765 
3766 	winname = mapping->id1name;
3767 	windomain = mapping->id1domain;
3768 
3769 	if (winname == NULL && windomain != NULL) {
3770 		retcode = IDMAP_ERR_ARG;
3771 		goto out;
3772 	}
3773 
3774 	/* Need atleast winname or sid to proceed */
3775 	if (winname == NULL && mapping->id1.idmap_id_u.sid.prefix == NULL) {
3776 		retcode = IDMAP_ERR_ARG;
3777 		goto out;
3778 	}
3779 
3780 	/*
3781 	 * If domainname is not given but we have a fully qualified
3782 	 * winname then extract the domainname from the winname,
3783 	 * otherwise use the default_domain from the config
3784 	 */
3785 	if (winname != NULL && windomain == NULL) {
3786 		retcode = IDMAP_SUCCESS;
3787 		if ((cp = strchr(winname, '@')) != NULL) {
3788 			*cp = '\0';
3789 			mapping->id1domain = strdup(cp + 1);
3790 			if (mapping->id1domain == NULL)
3791 				retcode = IDMAP_ERR_MEMORY;
3792 		} else if (lookup_wksids_name2sid(winname, NULL, NULL, NULL,
3793 		    NULL) != IDMAP_SUCCESS) {
3794 			/* well-known SIDs don't need domain */
3795 			RDLOCK_CONFIG();
3796 			if (_idmapdstate.cfg->pgcfg.default_domain != NULL) {
3797 				mapping->id1domain =
3798 				    strdup(_idmapdstate.cfg->
3799 				    pgcfg.default_domain);
3800 				if (mapping->id1domain == NULL)
3801 					retcode = IDMAP_ERR_MEMORY;
3802 			} else {
3803 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
3804 			}
3805 			UNLOCK_CONFIG();
3806 		}
3807 		if (retcode != IDMAP_SUCCESS)
3808 			goto out;
3809 	}
3810 
3811 	/*
3812 	 * First pass looks up the well-known SIDs table and cache
3813 	 * and handles localSIDs
3814 	 */
3815 	state.sid2pid_done = TRUE;
3816 	retcode = sid2pid_first_pass(&state, cache, mapping, &idres);
3817 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
3818 		goto out;
3819 
3820 	/* AD lookup by winname or by sid */
3821 	if (state.ad_nqueries > 0) {
3822 		retcode = ad_lookup(&state, mapping, &idres, 1, 1, 0);
3823 		if (IDMAP_ERROR(retcode))
3824 			goto out;
3825 	}
3826 
3827 	/*
3828 	 * If nldap-based name mapping is enabled then lookup native LDAP
3829 	 * directory service by winname to get pid and unixname. Ignore
3830 	 * non-fatal errors in which case we simply fallback to evaluating
3831 	 * local name-based mapping rules.
3832 	 */
3833 	if (mapping->id1name != NULL && NLDAP_MODE(idres.id.idtype, (&state))) {
3834 		retcode = nldap_lookup(mapping, &idres, 1, 1);
3835 		if (IDMAP_FATAL_ERROR(retcode))
3836 			goto out;
3837 		idres.retcode = IDMAP_SUCCESS;
3838 	}
3839 
3840 	/* Next pass performs name-based mapping and ephemeral mapping. */
3841 	state.sid2pid_done = TRUE;
3842 	retcode = sid2pid_second_pass(&state, cache, db, mapping, &idres);
3843 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
3844 		goto out;
3845 
3846 	/* Update cache */
3847 	(void) update_cache_sid2pid(&state, cache, mapping, &idres);
3848 
3849 out:
3850 	/*
3851 	 * Note that "mapping" is returned to the client. Therefore
3852 	 * copy whatever we have in "idres" to mapping->id2 and
3853 	 * free idres.
3854 	 */
3855 	mapping->direction = idres.direction;
3856 	mapping->id2 = idres.id;
3857 	(void) memset(&idres, 0, sizeof (idres));
3858 	if (retcode != IDMAP_SUCCESS)
3859 		mapping->id2.idmap_id_u.uid = UID_NOBODY;
3860 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
3861 	cleanup_lookup_state(&state);
3862 	return (retcode);
3863 }
3864 
3865 idmap_retcode
3866 get_u2w_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
3867 		idmap_mapping *mapping, int is_user)
3868 {
3869 	idmap_id_res	idres;
3870 	lookup_state_t	state;
3871 	idmap_retcode	retcode;
3872 	char		*canonname;
3873 	int		is_wuser;
3874 
3875 	/*
3876 	 * In order to re-use the pid2sid code, we convert
3877 	 * our input data into structs that are expected by
3878 	 * pid2sid_first_pass.
3879 	 */
3880 
3881 	(void) memset(&idres, 0, sizeof (idres));
3882 	(void) memset(&state, 0, sizeof (state));
3883 
3884 	/* Get directory-based name mapping info */
3885 	retcode = get_ds_namemap_type(&state);
3886 	if (retcode != IDMAP_SUCCESS)
3887 		goto out;
3888 
3889 	/*
3890 	 * Copy data from "request" to "mapping". Note that
3891 	 * empty strings are not copied from "request" to
3892 	 * "mapping" and therefore the coresponding strings in
3893 	 * "mapping" will be NULL. This eliminates having to
3894 	 * check for empty strings henceforth.
3895 	 */
3896 	if (copy_mapping_request(mapping, request) < 0) {
3897 		retcode = IDMAP_ERR_MEMORY;
3898 		goto out;
3899 	}
3900 
3901 	/*
3902 	 * For unix to windows mapping request, we need atleast a
3903 	 * unixname or uid/gid to proceed
3904 	 */
3905 	if (mapping->id1name == NULL &&
3906 	    mapping->id1.idmap_id_u.uid == SENTINEL_PID) {
3907 		retcode = IDMAP_ERR_ARG;
3908 		goto out;
3909 	}
3910 
3911 	/* First pass looks up cache and well-known SIDs */
3912 	state.pid2sid_done = TRUE;
3913 	retcode = pid2sid_first_pass(&state, cache, mapping, &idres,
3914 	    is_user, 1);
3915 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
3916 		goto out;
3917 
3918 	if (state.nldap_nqueries > 0) {
3919 		/*
3920 		 * This means directory-based name mapping (nldap or mixed
3921 		 * mode) is enabled. Lookup native LDAP directory service
3922 		 * by unixname or pid to get the winname. Ignore non-fatal
3923 		 * errors in which case we simply fallback to local name
3924 		 * based mapping rules.
3925 		 */
3926 		retcode = nldap_lookup(mapping, &idres, 0, 0);
3927 		if (IDMAP_FATAL_ERROR(retcode))
3928 			goto out;
3929 		idres.retcode = IDMAP_SUCCESS;
3930 
3931 		/*
3932 		 * If we've winname then get SID. We use lookup_name2sid()
3933 		 * instead of ad_lookup() in order to first resolve name2sid
3934 		 * using well-known SIDs table and name_cache before trying
3935 		 * AD.
3936 		 */
3937 		if (mapping->id2name != NULL) {
3938 			canonname = NULL;
3939 			is_wuser = -1;
3940 			retcode = lookup_name2sid(cache, mapping->id2name,
3941 			    mapping->id2domain, &is_wuser, &canonname,
3942 			    &idres.id.idmap_id_u.sid.prefix,
3943 			    &idres.id.idmap_id_u.sid.rid, mapping);
3944 			if (canonname != NULL) {
3945 				free(mapping->id2name);
3946 				mapping->id2name = canonname;
3947 			}
3948 			if (retcode == IDMAP_SUCCESS)
3949 				idres.id.idtype = is_wuser ? IDMAP_USID :
3950 				    IDMAP_GSID;
3951 			idres.retcode = retcode;
3952 		}
3953 	} else if (state.ad_nqueries > 0) {
3954 		/*
3955 		 * This means AD-based name mapping is enabled.
3956 		 * Lookup AD by unixname to get winname and sid.
3957 		 * Ignore non-fatal errors in which case we simply fallback
3958 		 * to local name based mapping rules.
3959 		 */
3960 		retcode = ad_lookup(&state, mapping, &idres, 0, 0, 1);
3961 		if (IDMAP_FATAL_ERROR(retcode))
3962 			goto out;
3963 		idres.retcode = IDMAP_SUCCESS;
3964 	}
3965 
3966 	/*
3967 	 * Next pass processes the result of the preceding passes/lookups.
3968 	 * It returns if there's nothing more to be done otherwise it
3969 	 * evaluates local name-based mapping rules
3970 	 */
3971 	state.pid2sid_done = TRUE;
3972 	retcode = pid2sid_second_pass(&state, cache, db, mapping, &idres,
3973 	    is_user);
3974 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
3975 		goto out;
3976 
3977 	/* Update cache */
3978 	(void) update_cache_pid2sid(&state, cache, mapping, &idres);
3979 
3980 out:
3981 	/*
3982 	 * Note that "mapping" is returned to the client. Therefore
3983 	 * copy whatever we have in "idres" to mapping->id2 and
3984 	 * free idres.
3985 	 */
3986 	mapping->direction = idres.direction;
3987 	mapping->id2 = idres.id;
3988 	(void) memset(&idres, 0, sizeof (idres));
3989 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
3990 	cleanup_lookup_state(&state);
3991 	return (retcode);
3992 }
3993 
3994 static
3995 idmap_retcode
3996 ad_lookup_by_unixname(lookup_state_t *state,
3997 		const char *unixname, int is_user, int is_wuser,
3998 		char **sidprefix, idmap_rid_t *rid, char **winname,
3999 		char **domain, int *type)
4000 {
4001 	/* Lookup AD by unixname */
4002 	int			retries = 0;
4003 	idmap_query_state_t	*qs = NULL;
4004 	idmap_retcode		rc, retcode;
4005 
4006 retry:
4007 	retcode = idmap_lookup_batch_start(_idmapdstate.ad, 1, &qs);
4008 	if (retcode != IDMAP_SUCCESS) {
4009 		degrade_svc();
4010 		idmapdlog(LOG_ERR,
4011 		    "Failed to create request for AD lookup by unixname");
4012 		return (IDMAP_ERR_INTERNAL);
4013 	}
4014 
4015 	restore_svc();
4016 
4017 	if (state != NULL)
4018 		idmap_lookup_batch_set_unixattr(qs, state->ad_unixuser_attr,
4019 		    state->ad_unixgroup_attr);
4020 
4021 	retcode = idmap_unixname2sid_batch_add1(qs, unixname, is_user,
4022 	    is_wuser, sidprefix, rid, winname, domain, type, &rc);
4023 
4024 	if (retcode != IDMAP_SUCCESS)
4025 		idmap_lookup_release_batch(&qs);
4026 	else
4027 		retcode = idmap_lookup_batch_end(&qs, NULL);
4028 
4029 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
4030 		goto retry;
4031 	else if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
4032 		degrade_svc();
4033 
4034 	if (retcode != IDMAP_SUCCESS) {
4035 		idmapdlog(LOG_NOTICE, "AD lookup by unixname failed");
4036 		return (retcode);
4037 	}
4038 	return (rc);
4039 }
4040 
4041 /*
4042  * This function is called whenever a non-batched AD lookup needs to be
4043  * done (e.g. get_w2u_mapping() and get_u2w_mapping()). It's already
4044  * determined by the caller before calling this function that AD lookup is
4045  * needed and has already searched the well-known SIDs table and name_cache.
4046  */
4047 static
4048 idmap_retcode
4049 ad_lookup(lookup_state_t *state, idmap_mapping *req, idmap_id_res *res,
4050 		int w2u, int getunixattr, int byunixattr)
4051 {
4052 	idmap_retcode	retcode;
4053 	int		type, eunixtype, is_user, is_wuser;
4054 	char		*canonname = NULL;
4055 
4056 	if (w2u) {
4057 		/*
4058 		 * win2unix lookup requests (get_w2u_mapping()) calls this
4059 		 * function to lookup by sid OR winname and to retrieve
4060 		 * SID, winname, sidtype (user or group) and unixnames
4061 		 * from AD.
4062 		 */
4063 
4064 		/* Set the expected unixtype */
4065 		if (res->id.idtype == IDMAP_UID)
4066 			eunixtype = _IDMAP_T_USER;
4067 		else if (res->id.idtype == IDMAP_GID)
4068 			eunixtype = _IDMAP_T_GROUP;
4069 		else
4070 			eunixtype = _IDMAP_T_UNDEF;
4071 
4072 		if (req->id1.idmap_id_u.sid.prefix != NULL) {
4073 			/* AD lookup by sid */
4074 			retcode = ad_lookup_by_sid(
4075 			    state, req->id1.idmap_id_u.sid.prefix,
4076 			    req->id1.idmap_id_u.sid.rid, eunixtype,
4077 			    (req->id1name == NULL) ? &req->id1name : NULL,
4078 			    (req->id1domain == NULL) ? &req->id1domain : NULL,
4079 			    &type, (getunixattr && req->id2name == NULL)
4080 			    ? &req->id2name : NULL);
4081 		} else {
4082 			assert(req->id1name != NULL);
4083 			/* AD lookup by winname */
4084 			retcode = ad_lookup_by_winname(
4085 			    state, req->id1name, req->id1domain, eunixtype,
4086 			    &canonname, &req->id1.idmap_id_u.sid.prefix,
4087 			    &req->id1.idmap_id_u.sid.rid, &type,
4088 			    (getunixattr && req->id2name == NULL)
4089 			    ? &req->id2name : NULL);
4090 
4091 			if (canonname != NULL) {
4092 				free(req->id1name);
4093 				req->id1name = canonname;
4094 			}
4095 		}
4096 		if (retcode == IDMAP_SUCCESS) {
4097 			switch (type) {
4098 			case _IDMAP_T_USER:
4099 				if (res->id.idtype == IDMAP_POSIXID)
4100 					res->id.idtype = IDMAP_UID;
4101 				req->id1.idtype = IDMAP_USID;
4102 				break;
4103 			case _IDMAP_T_GROUP:
4104 				if (res->id.idtype == IDMAP_POSIXID)
4105 					res->id.idtype = IDMAP_GID;
4106 				req->id1.idtype = IDMAP_GSID;
4107 				break;
4108 			default:
4109 				return (IDMAP_ERR_SID);
4110 			}
4111 		}
4112 		return (retcode);
4113 	}
4114 
4115 	/*
4116 	 * unix2win lookup requests (get_u2w_mapping()) calls this
4117 	 * function to lookup AD by unixname and to retrieve
4118 	 * SID, winname, and sidtype (user or group) from AD.
4119 	 */
4120 
4121 	/* Set the expected unixtype */
4122 	eunixtype = (req->id1.idtype == IDMAP_UID) ? _IDMAP_T_USER :
4123 	    _IDMAP_T_GROUP;
4124 
4125 	if (byunixattr) {
4126 		/* AD lookup by unixname */
4127 		is_user = (IS_REQUEST_UID(*req)) ? 1 : 0;
4128 		if (res->id.idtype == IDMAP_USID)
4129 			is_wuser = 1;
4130 		else if (res->id.idtype == IDMAP_GSID)
4131 			is_wuser = 0;
4132 		else
4133 			is_wuser = is_user;
4134 		retcode = ad_lookup_by_unixname(
4135 		    state, req->id1name, is_user, is_wuser,
4136 		    (res->id.idmap_id_u.sid.prefix == NULL) ?
4137 		    &res->id.idmap_id_u.sid.prefix : NULL,
4138 		    (res->id.idmap_id_u.sid.prefix == NULL) ?
4139 		    &res->id.idmap_id_u.sid.rid : NULL,
4140 		    (req->id2name == NULL) ? &req->id2name : NULL,
4141 		    (req->id2domain == NULL) ? &req->id2domain : NULL, NULL);
4142 	} else if (res->id.idmap_id_u.sid.prefix != NULL) {
4143 		/* AD lookup by sid */
4144 		retcode = ad_lookup_by_sid(
4145 		    state, res->id.idmap_id_u.sid.prefix,
4146 		    res->id.idmap_id_u.sid.rid, eunixtype,
4147 		    (req->id2name == NULL) ? &req->id2name : NULL,
4148 		    (req->id2domain == NULL) ? &req->id2domain : NULL,
4149 		    NULL, (getunixattr && req->id1name == NULL)
4150 		    ? &req->id1name : NULL);
4151 	} else {
4152 		/* AD lookup by winname */
4153 		assert(req->id2name != NULL);
4154 		retcode = ad_lookup_by_winname(
4155 		    state, req->id2name, req->id2domain, eunixtype,
4156 		    &canonname, &res->id.idmap_id_u.sid.prefix,
4157 		    &res->id.idmap_id_u.sid.rid, NULL,
4158 		    (getunixattr && req->id1name == NULL)
4159 		    ? &req->id1name : NULL);
4160 
4161 		if (canonname != NULL) {
4162 			free(req->id2name);
4163 			req->id2name = canonname;
4164 		}
4165 	}
4166 
4167 	if (retcode == IDMAP_SUCCESS) {
4168 		switch (type) {
4169 		case _IDMAP_T_USER:
4170 			if (res->id.idtype == IDMAP_SID)
4171 				res->id.idtype = IDMAP_USID;
4172 			break;
4173 		case _IDMAP_T_GROUP:
4174 			if (res->id.idtype == IDMAP_SID)
4175 				res->id.idtype = IDMAP_GSID;
4176 			break;
4177 		default:
4178 			return (IDMAP_ERR_SID);
4179 		}
4180 	}
4181 	return (retcode);
4182 }
4183