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