xref: /titanic_51/usr/src/cmd/idmap/idmapd/dbutils.c (revision 8d483882aa3390058094b043f3d62187b5d1de03)
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 <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <errno.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <rpc/rpc.h>
39 #include <sys/sid.h>
40 #include <time.h>
41 #include <pwd.h>
42 #include <grp.h>
43 
44 #include "idmapd.h"
45 #include "adutils.h"
46 #include "string.h"
47 #include "idmap_priv.h"
48 
49 static idmap_retcode sql_compile_n_step_once(sqlite *, char *,
50 		sqlite_vm **, int *, int, const char ***);
51 static idmap_retcode lookup_wksids_name2sid(const char *, char **,
52 		idmap_rid_t *, int *);
53 
54 #define	EMPTY_NAME(name)	(*name == 0 || strcmp(name, "\"\"") == 0)
55 
56 #define	EMPTY_STRING(str)	(str == NULL || *str == 0)
57 
58 #define	DO_NOT_ALLOC_NEW_ID_MAPPING(req)\
59 		(req->flag & IDMAP_REQ_FLG_NO_NEW_ID_ALLOC)
60 
61 #define	AVOID_NAMESERVICE(req)\
62 		(req->flag & IDMAP_REQ_FLG_NO_NAMESERVICE)
63 
64 #define	IS_EPHEMERAL(pid)	(pid > INT32_MAX)
65 
66 #define	LOCALRID_MIN	1000
67 
68 #define	SLEEP_TIME	20
69 
70 #define	NANO_SLEEP(rqtp, nsec)\
71 	rqtp.tv_sec = 0;\
72 	rqtp.tv_nsec = nsec * (NANOSEC / MILLISEC);\
73 	(void) nanosleep(&rqtp, NULL);
74 
75 
76 typedef enum init_db_option {
77 	FAIL_IF_CORRUPT = 0,
78 	REMOVE_IF_CORRUPT = 1
79 } init_db_option_t;
80 
81 
82 /*
83  * Initialize 'dbname' using 'sql'
84  */
85 static int
86 init_db_instance(const char *dbname, const char *sql, init_db_option_t opt,
87 		int *new_db_created)
88 {
89 	int rc = 0;
90 	int tries = 0;
91 	sqlite *db = NULL;
92 	char *str = NULL;
93 
94 	if (new_db_created != NULL)
95 		*new_db_created = 0;
96 
97 	db = sqlite_open(dbname, 0600, &str);
98 	while (db == NULL) {
99 		idmapdlog(LOG_ERR,
100 		    "Error creating database %s (%s)",
101 		    dbname, CHECK_NULL(str));
102 		sqlite_freemem(str);
103 		if (opt == FAIL_IF_CORRUPT || opt != REMOVE_IF_CORRUPT ||
104 		    tries > 0)
105 			return (-1);
106 
107 		tries++;
108 		(void) unlink(dbname);
109 		db = sqlite_open(dbname, 0600, &str);
110 	}
111 
112 	sqlite_busy_timeout(db, 3000);
113 	rc = sqlite_exec(db, "BEGIN TRANSACTION;", NULL, NULL, &str);
114 	if (SQLITE_OK != rc) {
115 		idmapdlog(LOG_ERR, "Cannot begin database transaction (%s)",
116 		    str);
117 		sqlite_freemem(str);
118 		sqlite_close(db);
119 		return (1);
120 	}
121 
122 	switch (sqlite_exec(db, sql, NULL, NULL, &str)) {
123 	case SQLITE_ERROR:
124 /*
125  * This is the normal situation: CREATE probably failed because tables
126  * already exist. It may indicate an error in SQL as well, but we cannot
127  * tell.
128  */
129 		sqlite_freemem(str);
130 		rc =  sqlite_exec(db, "ROLLBACK TRANSACTION",
131 		    NULL, NULL, &str);
132 		break;
133 	case SQLITE_OK:
134 		rc =  sqlite_exec(db, "COMMIT TRANSACTION",
135 		    NULL, NULL, &str);
136 		idmapdlog(LOG_INFO,
137 		    "Database created at %s", dbname);
138 
139 		if (new_db_created != NULL)
140 			*new_db_created = 1;
141 		break;
142 	default:
143 		idmapdlog(LOG_ERR,
144 		    "Error initializing database %s (%s)",
145 		    dbname, str);
146 		sqlite_freemem(str);
147 		rc =  sqlite_exec(db, "ROLLBACK TRANSACTION",
148 		    NULL, NULL, &str);
149 		break;
150 	}
151 
152 	if (SQLITE_OK != rc) {
153 		/* this is bad - database may be left in a locked state */
154 		idmapdlog(LOG_ERR,
155 		    "Error closing transaction (%s)", str);
156 		sqlite_freemem(str);
157 	}
158 
159 	(void) sqlite_close(db);
160 	return (rc);
161 }
162 
163 /*
164  * Get the database handle
165  */
166 idmap_retcode
167 get_db_handle(sqlite **db) {
168 	char	*errmsg;
169 
170 	/*
171 	 * TBD RFE: Retrieve the db handle from thread-specific storage
172 	 * If none exists, open and store in thread-specific storage.
173 	 */
174 
175 	*db = sqlite_open(IDMAP_DBNAME, 0, &errmsg);
176 	if (*db == NULL) {
177 		idmapdlog(LOG_ERR,
178 			"Error opening database %s (%s)",
179 			IDMAP_DBNAME, CHECK_NULL(errmsg));
180 		sqlite_freemem(errmsg);
181 		return (IDMAP_ERR_INTERNAL);
182 	}
183 	return (IDMAP_SUCCESS);
184 }
185 
186 /*
187  * Get the cache handle
188  */
189 idmap_retcode
190 get_cache_handle(sqlite **db) {
191 	char	*errmsg;
192 
193 	/*
194 	 * TBD RFE: Retrieve the db handle from thread-specific storage
195 	 * If none exists, open and store in thread-specific storage.
196 	 */
197 
198 	*db = sqlite_open(IDMAP_CACHENAME, 0, &errmsg);
199 	if (*db == NULL) {
200 		idmapdlog(LOG_ERR,
201 			"Error opening database %s (%s)",
202 			IDMAP_CACHENAME, CHECK_NULL(errmsg));
203 		sqlite_freemem(errmsg);
204 		return (IDMAP_ERR_INTERNAL);
205 	}
206 	return (IDMAP_SUCCESS);
207 }
208 
209 #define	CACHE_SQL\
210 	"CREATE TABLE idmap_cache ("\
211 	"	sidprefix TEXT,"\
212 	"	rid INTEGER,"\
213 	"	windomain TEXT,"\
214 	"	winname TEXT,"\
215 	"	pid INTEGER,"\
216 	"	unixname TEXT,"\
217 	"	is_user INTEGER,"\
218 	"	w2u INTEGER,"\
219 	"	u2w INTEGER,"\
220 	"	expiration INTEGER"\
221 	");"\
222 	"CREATE UNIQUE INDEX idmap_cache_sid_w2u ON idmap_cache"\
223 	"		(sidprefix, rid, w2u);"\
224 	"CREATE UNIQUE INDEX idmap_cache_pid_u2w ON idmap_cache"\
225 	"		(pid, is_user, u2w);"\
226 	"CREATE TABLE name_cache ("\
227 	"	sidprefix TEXT,"\
228 	"	rid INTEGER,"\
229 	"	name TEXT,"\
230 	"	domain TEXT,"\
231 	"	type INTEGER,"\
232 	"	expiration INTEGER"\
233 	");"\
234 	"CREATE UNIQUE INDEX name_cache_sid ON name_cache"\
235 	"		(sidprefix, rid);"
236 
237 #define	DB_SQL\
238 	"CREATE TABLE namerules ("\
239 	"	is_user INTEGER NOT NULL,"\
240 	"	windomain TEXT,"\
241 	"	winname TEXT NOT NULL,"\
242 	"	is_nt4 INTEGER NOT NULL,"\
243 	"	unixname NOT NULL,"\
244 	"	w2u_order INTEGER,"\
245 	"	u2w_order INTEGER"\
246 	");"\
247 	"CREATE UNIQUE INDEX namerules_w2u ON namerules"\
248 	"		(winname, windomain, is_user, w2u_order);"\
249 	"CREATE UNIQUE INDEX namerules_u2w ON namerules"\
250 	"		(unixname, is_user, u2w_order);"
251 
252 /*
253  * Initialize cache and db
254  */
255 int
256 init_dbs() {
257 	/* name-based mappings; probably OK to blow away in a pinch(?) */
258 	if (init_db_instance(IDMAP_DBNAME, DB_SQL, FAIL_IF_CORRUPT, NULL) < 0)
259 		return (-1);
260 
261 	/* mappings, name/SID lookup cache + ephemeral IDs; OK to blow away */
262 	if (init_db_instance(IDMAP_CACHENAME, CACHE_SQL, REMOVE_IF_CORRUPT,
263 			&_idmapdstate.new_eph_db) < 0)
264 		return (-1);
265 
266 	return (0);
267 }
268 
269 /*
270  * Finalize databases
271  */
272 void
273 fini_dbs() {
274 }
275 
276 /*
277  * This table is a listing of status codes that will returned to the
278  * client when a SQL command fails with the corresponding error message.
279  */
280 static msg_table_t sqlmsgtable[] = {
281 	{IDMAP_ERR_U2W_NAMERULE_CONFLICT,
282 	"columns unixname, is_user, u2w_order are not unique"},
283 	{IDMAP_ERR_W2U_NAMERULE_CONFLICT,
284 	"columns winname, windomain, is_user, w2u_order are not unique"},
285 	{-1, NULL}
286 };
287 
288 /*
289  * idmapd's version of string2stat to map SQLite messages to
290  * status codes
291  */
292 idmap_retcode
293 idmapd_string2stat(const char *msg) {
294 	int i;
295 	for (i = 0; sqlmsgtable[i].msg; i++) {
296 		if (strcasecmp(sqlmsgtable[i].msg, msg) == 0)
297 			return (sqlmsgtable[i].retcode);
298 	}
299 	return (IDMAP_ERR_OTHER);
300 }
301 
302 /*
303  * Execute the given SQL statment without using any callbacks
304  */
305 idmap_retcode
306 sql_exec_no_cb(sqlite *db, char *sql) {
307 	char		*errmsg = NULL;
308 	int		r, i, s;
309 	struct timespec	rqtp;
310 	idmap_retcode	retcode;
311 
312 	for (i = 0, s = SLEEP_TIME; i < MAX_TRIES; i++, s *= 2) {
313 		if (errmsg != NULL) {
314 			sqlite_freemem(errmsg);
315 			errmsg = NULL;
316 		}
317 		r = sqlite_exec(db, sql, NULL, NULL, &errmsg);
318 		if (r != SQLITE_BUSY)
319 			break;
320 		NANO_SLEEP(rqtp, s);
321 	}
322 
323 	if (r != SQLITE_OK) {
324 		idmapdlog(LOG_ERR, "Database error during %s (%s)",
325 			sql, CHECK_NULL(errmsg));
326 		if (r == SQLITE_BUSY) {
327 			retcode = IDMAP_ERR_BUSY;
328 		} else {
329 			retcode = idmap_string2stat(errmsg);
330 			if (retcode == IDMAP_ERR_OTHER)
331 				retcode = idmapd_string2stat(errmsg);
332 		}
333 		if (errmsg != NULL)
334 			sqlite_freemem(errmsg);
335 		return (retcode);
336 	}
337 
338 	return (IDMAP_SUCCESS);
339 }
340 
341 /*
342  * Generate expression that can be used in WHERE statements.
343  * Examples:
344  * <prefix> <col>      <op> <value>   <suffix>
345  * ""       "unixuser" "="  "foo" "AND"
346  */
347 idmap_retcode
348 gen_sql_expr_from_utf8str(const char *prefix, const char *col,
349 		const char *op, idmap_utf8str *value,
350 		const char *suffix, char **out) {
351 	char		*str;
352 	idmap_stat	retcode;
353 
354 	if (out == NULL)
355 		return (IDMAP_ERR_ARG);
356 
357 	if (value == NULL)
358 		return (IDMAP_SUCCESS);
359 
360 	retcode = idmap_utf82str(&str, 0, value);
361 	if (retcode != IDMAP_SUCCESS)
362 		return (retcode);
363 
364 	if (prefix == NULL)
365 		prefix = "";
366 	if (suffix == NULL)
367 		suffix = "";
368 
369 	*out = sqlite_mprintf("%s %s %s %Q %s",
370 			prefix, col, op, str, suffix);
371 	idmap_free(str);
372 	if (*out == NULL)
373 		return (IDMAP_ERR_MEMORY);
374 	return (IDMAP_SUCCESS);
375 }
376 
377 /*
378  * Generate and execute SQL statement for LIST RPC calls
379  */
380 idmap_retcode
381 process_list_svc_sql(sqlite *db, char *sql, uint64_t limit,
382 		list_svc_cb cb, void *result) {
383 	list_cb_data_t	cb_data;
384 	char		*errmsg = NULL;
385 	int		r, i, s;
386 	struct timespec	rqtp;
387 	idmap_retcode	retcode = IDMAP_ERR_INTERNAL;
388 
389 	(void) memset(&cb_data, 0, sizeof (cb_data));
390 	cb_data.result = result;
391 	cb_data.limit = limit;
392 
393 	for (i = 0, s = SLEEP_TIME; i < MAX_TRIES; i++, s *= 2) {
394 		r = sqlite_exec(db, sql, cb, &cb_data, &errmsg);
395 		switch (r) {
396 		case SQLITE_OK:
397 			retcode = IDMAP_SUCCESS;
398 			goto out;
399 		case SQLITE_BUSY:
400 			if (errmsg != NULL) {
401 				sqlite_freemem(errmsg);
402 				errmsg = NULL;
403 			}
404 			retcode = IDMAP_ERR_BUSY;
405 			idmapdlog(LOG_DEBUG,
406 			"Database busy, %d retries remaining",
407 				MAX_TRIES - i - 1);
408 			NANO_SLEEP(rqtp, s);
409 			continue;
410 		default:
411 			retcode = IDMAP_ERR_INTERNAL;
412 			idmapdlog(LOG_ERR,
413 				"Database error during %s (%s)",
414 				sql, CHECK_NULL(errmsg));
415 			goto out;
416 		};
417 	}
418 out:
419 	if (errmsg != NULL)
420 		sqlite_freemem(errmsg);
421 	return (retcode);
422 }
423 
424 /*
425  * This routine is called by callbacks that process the results of
426  * LIST RPC calls to validate data and to allocate memory for
427  * the result array.
428  */
429 idmap_retcode
430 validate_list_cb_data(list_cb_data_t *cb_data, int argc, char **argv,
431 		int ncol, uchar_t **list, size_t valsize) {
432 	size_t	nsize;
433 	void	*tmplist;
434 
435 	if (cb_data->limit > 0 && cb_data->next == cb_data->limit)
436 		return (IDMAP_NEXT);
437 
438 	if (argc < ncol || argv == NULL) {
439 		idmapdlog(LOG_ERR, "Invalid data");
440 		return (IDMAP_ERR_INTERNAL);
441 	}
442 
443 	/* alloc in bulk to reduce number of reallocs */
444 	if (cb_data->next >= cb_data->len) {
445 		nsize = (cb_data->len + SIZE_INCR) * valsize;
446 		tmplist = realloc(*list, nsize);
447 		if (tmplist == NULL) {
448 			idmapdlog(LOG_ERR, "Out of memory");
449 			return (IDMAP_ERR_MEMORY);
450 		}
451 		*list = tmplist;
452 		(void) memset(*list + (cb_data->len * valsize), 0,
453 			SIZE_INCR * valsize);
454 		cb_data->len += SIZE_INCR;
455 	}
456 	return (IDMAP_SUCCESS);
457 }
458 
459 static idmap_retcode
460 get_namerule_order(char *winname, char *windomain, char *unixname,
461 		int direction, int *w2u_order, int *u2w_order) {
462 
463 	*w2u_order = 0;
464 	*u2w_order = 0;
465 
466 	/*
467 	 * Windows to UNIX lookup order:
468 	 *  1. winname@domain (or winname) to ""
469 	 *  2. winname@domain (or winname) to unixname
470 	 *  3. winname@* to ""
471 	 *  4. winname@* to unixname
472 	 *  5. *@domain (or *) to *
473 	 *  6. *@domain (or *) to ""
474 	 *  7. *@domain (or *) to unixname
475 	 *  8. *@* to *
476 	 *  9. *@* to ""
477 	 * 10. *@* to unixname
478 	 *
479 	 * winname is a special case of winname@domain when domain is the
480 	 * default domain. Similarly * is a special case of *@domain when
481 	 * domain is the default domain.
482 	 *
483 	 * Note that "" has priority over specific names because "" inhibits
484 	 * mappings and traditionally deny rules always had higher priority.
485 	 */
486 	if (direction != IDMAP_DIRECTION_U2W) {
487 		/* bi-directional or from windows to unix */
488 		if (winname == NULL)
489 			return (IDMAP_ERR_W2U_NAMERULE);
490 		else if (unixname == NULL)
491 			return (IDMAP_ERR_W2U_NAMERULE);
492 		else if (EMPTY_NAME(winname))
493 			return (IDMAP_ERR_W2U_NAMERULE);
494 		else if (*winname == '*' && windomain && *windomain == '*') {
495 			if (*unixname == '*')
496 				*w2u_order = 8;
497 			else if (EMPTY_NAME(unixname))
498 				*w2u_order = 9;
499 			else /* unixname == name */
500 				*w2u_order = 10;
501 		} else if (*winname == '*') {
502 			if (*unixname == '*')
503 				*w2u_order = 5;
504 			else if (EMPTY_NAME(unixname))
505 				*w2u_order = 6;
506 			else /* name */
507 				*w2u_order = 7;
508 		} else if (windomain != NULL && *windomain == '*') {
509 			/* winname == name */
510 			if (*unixname == '*')
511 				return (IDMAP_ERR_W2U_NAMERULE);
512 			else if (EMPTY_NAME(unixname))
513 				*w2u_order = 3;
514 			else /* name */
515 				*w2u_order = 4;
516 		} else  {
517 			/* winname == name && windomain == null or name */
518 			if (*unixname == '*')
519 				return (IDMAP_ERR_W2U_NAMERULE);
520 			else if (EMPTY_NAME(unixname))
521 				*w2u_order = 1;
522 			else /* name */
523 				*w2u_order = 2;
524 		}
525 	}
526 
527 	/*
528 	 * 1. unixname to ""
529 	 * 2. unixname to winname@domain (or winname)
530 	 * 3. * to *@domain (or *)
531 	 * 4. * to ""
532 	 * 5. * to winname@domain (or winname)
533 	 */
534 	if (direction != IDMAP_DIRECTION_W2U) {
535 		/* bi-directional or from unix to windows */
536 		if (unixname == NULL || EMPTY_NAME(unixname))
537 			return (IDMAP_ERR_U2W_NAMERULE);
538 		else if (winname == NULL)
539 			return (IDMAP_ERR_U2W_NAMERULE);
540 		else if (windomain != NULL && *windomain == '*')
541 			return (IDMAP_ERR_U2W_NAMERULE);
542 		else if (*unixname == '*') {
543 			if (*winname == '*')
544 				*u2w_order = 3;
545 			else if (EMPTY_NAME(winname))
546 				*u2w_order = 4;
547 			else
548 				*u2w_order = 5;
549 		} else {
550 			if (*winname == '*')
551 				return (IDMAP_ERR_U2W_NAMERULE);
552 			else if (EMPTY_NAME(winname))
553 				*u2w_order = 1;
554 			else
555 				*u2w_order = 2;
556 		}
557 	}
558 	return (IDMAP_SUCCESS);
559 }
560 
561 /*
562  * Generate and execute SQL statement to add name-based mapping rule
563  */
564 idmap_retcode
565 add_namerule(sqlite *db, idmap_namerule *rule) {
566 	char		*sql = NULL;
567 	idmap_stat	retcode;
568 	char		*windomain = NULL, *winname = NULL, *dom = NULL;
569 	char		*unixname = NULL;
570 	int		w2u_order, u2w_order;
571 	char		w2ubuf[11], u2wbuf[11];
572 
573 	retcode = idmap_utf82str(&windomain, 0, &rule->windomain);
574 	if (retcode != IDMAP_SUCCESS)
575 		goto out;
576 	retcode = idmap_utf82str(&winname, 0, &rule->winname);
577 	if (retcode != IDMAP_SUCCESS)
578 		goto out;
579 	retcode = idmap_utf82str(&unixname, 0, &rule->unixname);
580 	if (retcode != IDMAP_SUCCESS)
581 		goto out;
582 
583 	retcode = get_namerule_order(winname, windomain, unixname,
584 			rule->direction, &w2u_order, &u2w_order);
585 	if (retcode != IDMAP_SUCCESS)
586 		goto out;
587 
588 	if (w2u_order)
589 		(void) snprintf(w2ubuf, sizeof (w2ubuf), "%d", w2u_order);
590 	if (u2w_order)
591 		(void) snprintf(u2wbuf, sizeof (u2wbuf), "%d", u2w_order);
592 
593 	/*
594 	 * For the triggers on namerules table to work correctly:
595 	 * 1) Use NULL instead of 0 for w2u_order and u2w_order
596 	 * 2) Use "" instead of NULL for "no domain"
597 	 */
598 
599 	if (windomain != NULL)
600 		dom = windomain;
601 	else if (lookup_wksids_name2sid(winname, NULL, NULL, NULL)
602 	    == IDMAP_SUCCESS) {
603 		/* well-known SIDs don't need domain */
604 		dom = "";
605 	}
606 
607 	RDLOCK_CONFIG();
608 	if (dom == NULL) {
609 		if (_idmapdstate.cfg->pgcfg.mapping_domain)
610 			dom = _idmapdstate.cfg->pgcfg.mapping_domain;
611 		else
612 			dom = "";
613 	}
614 	sql = sqlite_mprintf("INSERT OR ROLLBACK into namerules "
615 		"(is_user, windomain, winname, is_nt4, "
616 		"unixname, w2u_order, u2w_order) "
617 		"VALUES(%d, %Q, %Q, %d, %Q, %q, %q);",
618 		rule->is_user?1:0,
619 		dom,
620 		winname, rule->is_nt4?1:0,
621 		unixname,
622 		w2u_order?w2ubuf:NULL,
623 		u2w_order?u2wbuf:NULL);
624 	UNLOCK_CONFIG();
625 
626 	if (sql == NULL) {
627 		retcode = IDMAP_ERR_INTERNAL;
628 		idmapdlog(LOG_ERR, "Out of memory");
629 		goto out;
630 	}
631 
632 	retcode = sql_exec_no_cb(db, sql);
633 
634 	if (retcode == IDMAP_ERR_OTHER)
635 		retcode = IDMAP_ERR_CFG;
636 
637 out:
638 	if (windomain != NULL)
639 		idmap_free(windomain);
640 	if (winname != NULL)
641 		idmap_free(winname);
642 	if (unixname != NULL)
643 		idmap_free(unixname);
644 	if (sql != NULL)
645 		sqlite_freemem(sql);
646 	return (retcode);
647 }
648 
649 /*
650  * Flush name-based mapping rules
651  */
652 idmap_retcode
653 flush_namerules(sqlite *db, bool_t is_user) {
654 	char		*sql = NULL;
655 	idmap_stat	retcode;
656 
657 	sql = sqlite_mprintf("DELETE FROM namerules WHERE "
658 		"is_user = %d;", is_user?1:0);
659 
660 	if (sql == NULL) {
661 		idmapdlog(LOG_ERR, "Out of memory");
662 		return (IDMAP_ERR_MEMORY);
663 	}
664 
665 	retcode = sql_exec_no_cb(db, sql);
666 
667 	sqlite_freemem(sql);
668 	return (retcode);
669 }
670 
671 /*
672  * Generate and execute SQL statement to remove a name-based mapping rule
673  */
674 idmap_retcode
675 rm_namerule(sqlite *db, idmap_namerule *rule) {
676 	char		*sql = NULL;
677 	idmap_stat	retcode;
678 	char		*s_windomain = NULL, *s_winname = NULL;
679 	char		*s_unixname = NULL;
680 	char		buf[80];
681 
682 	if (rule->direction < 0 &&
683 			rule->windomain.idmap_utf8str_len < 1 &&
684 			rule->winname.idmap_utf8str_len < 1 &&
685 			rule->unixname.idmap_utf8str_len < 1)
686 		return (IDMAP_SUCCESS);
687 
688 	if (rule->direction < 0) {
689 		buf[0] = 0;
690 	} else if (rule->direction == IDMAP_DIRECTION_BI) {
691 		(void) snprintf(buf, sizeof (buf), "AND w2u_order > 0"
692 				" AND u2w_order > 0");
693 	} else if (rule->direction == IDMAP_DIRECTION_W2U) {
694 		(void) snprintf(buf, sizeof (buf), "AND w2u_order > 0"
695 				" AND (u2w_order = 0 OR u2w_order ISNULL)");
696 	} else if (rule->direction == IDMAP_DIRECTION_U2W) {
697 		(void) snprintf(buf, sizeof (buf), "AND u2w_order > 0"
698 				" AND (w2u_order = 0 OR w2u_order ISNULL)");
699 	}
700 
701 	retcode = IDMAP_ERR_INTERNAL;
702 	if (rule->windomain.idmap_utf8str_len > 0) {
703 		if (gen_sql_expr_from_utf8str("AND", "windomain", "=",
704 				&rule->windomain,
705 				"", &s_windomain) != IDMAP_SUCCESS)
706 			goto out;
707 	}
708 
709 	if (rule->winname.idmap_utf8str_len > 0) {
710 		if (gen_sql_expr_from_utf8str("AND", "winname", "=",
711 				&rule->winname,
712 				"", &s_winname) != IDMAP_SUCCESS)
713 			goto out;
714 	}
715 
716 	if (rule->unixname.idmap_utf8str_len > 0) {
717 		if (gen_sql_expr_from_utf8str("AND", "unixname", "=",
718 				&rule->unixname,
719 				"", &s_unixname) != IDMAP_SUCCESS)
720 			goto out;
721 	}
722 
723 	sql = sqlite_mprintf("DELETE FROM namerules WHERE "
724 		"is_user = %d %s %s %s %s;",
725 		rule->is_user?1:0,
726 		s_windomain?s_windomain:"",
727 		s_winname?s_winname:"",
728 		s_unixname?s_unixname:"",
729 		buf);
730 
731 	if (sql == NULL) {
732 		retcode = IDMAP_ERR_INTERNAL;
733 		idmapdlog(LOG_ERR, "Out of memory");
734 		goto out;
735 	}
736 
737 	retcode = sql_exec_no_cb(db, sql);
738 
739 out:
740 	if (s_windomain != NULL)
741 		sqlite_freemem(s_windomain);
742 	if (s_winname != NULL)
743 		sqlite_freemem(s_winname);
744 	if (s_unixname != NULL)
745 		sqlite_freemem(s_unixname);
746 	if (sql != NULL)
747 		sqlite_freemem(sql);
748 	return (retcode);
749 }
750 
751 /*
752  * Compile the given SQL query and step just once.
753  *
754  * Input:
755  * db  - db handle
756  * sql - SQL statement
757  *
758  * Output:
759  * vm     -  virtual SQL machine
760  * ncol   - number of columns in the result
761  * values - column values
762  *
763  * Return values:
764  * IDMAP_SUCCESS
765  * IDMAP_ERR_BUSY
766  * IDMAP_ERR_NOTFOUND
767  * IDMAP_ERR_INTERNAL
768  */
769 
770 static idmap_retcode
771 sql_compile_n_step_once(sqlite *db, char *sql, sqlite_vm **vm, int *ncol,
772 		int reqcol, const char ***values) {
773 	char		*errmsg = NULL;
774 	struct timespec	rqtp;
775 	int		i, r, s;
776 
777 	if (sqlite_compile(db, sql, NULL, vm, &errmsg) != SQLITE_OK) {
778 		idmapdlog(LOG_ERR,
779 			"Database error during %s (%s)",
780 			sql, CHECK_NULL(errmsg));
781 		sqlite_freemem(errmsg);
782 		return (IDMAP_ERR_INTERNAL);
783 	}
784 
785 	for (i = 0, s = SLEEP_TIME; i < MAX_TRIES; i++, s *= 2) {
786 		r = sqlite_step(*vm, ncol, values, NULL);
787 		if (r != SQLITE_BUSY)
788 			break;
789 		NANO_SLEEP(rqtp, s);
790 	}
791 
792 	if (r == SQLITE_BUSY) {
793 		(void) sqlite_finalize(*vm, NULL);
794 		*vm = NULL;
795 		return (IDMAP_ERR_BUSY);
796 	} else if (r == SQLITE_ROW) {
797 		if (ncol != NULL && *ncol < reqcol) {
798 			(void) sqlite_finalize(*vm, NULL);
799 			*vm = NULL;
800 			return (IDMAP_ERR_INTERNAL);
801 		}
802 		/* Caller will call finalize after using the results */
803 		return (IDMAP_SUCCESS);
804 	} else if (r == SQLITE_DONE) {
805 		(void) sqlite_finalize(*vm, NULL);
806 		*vm = NULL;
807 		return (IDMAP_ERR_NOTFOUND);
808 	}
809 
810 	(void) sqlite_finalize(*vm, &errmsg);
811 	*vm = NULL;
812 	idmapdlog(LOG_ERR, "Database error during %s (%s)",
813 		sql, CHECK_NULL(errmsg));
814 	sqlite_freemem(errmsg);
815 	return (IDMAP_ERR_INTERNAL);
816 }
817 
818 /*
819  * Table for well-known SIDs.
820  *
821  * Background:
822  *
823  * These well-known principals are stored (as of Windows Server 2003) under:
824  * cn=WellKnown Security Principals, cn=Configuration, dc=<forestRootDomain>
825  * They belong to objectClass "foreignSecurityPrincipal". They don't have
826  * "samAccountName" nor "userPrincipalName" attributes. Their names are
827  * available in "cn" and "name" attributes. Some of these principals have a
828  * second entry under CN=ForeignSecurityPrincipals,dc=<forestRootDomain> and
829  * these duplicate entries have the stringified SID in the "name" and "cn"
830  * attributes instead of the actual name.
831  *
832  * These principals remain constant across all operating systems. Using
833  * a hard-coded table here improves performance and avoids additional
834  * complexity in the AD lookup code in adutils.c
835  *
836  * Currently we don't support localization of well-known SID names,
837  * unlike Windows.
838  *
839  * Note that other well-known SIDs (i.e. S-1-5-<domain>-<w-k RID> and
840  * S-1-5-32-<w-k RID>) are not stored here because AD does have normal
841  * user/group objects for these objects and can be looked up using the
842  * existing AD lookup code.
843  */
844 static wksids_table_t wksids[] = {
845 	{"S-1-1", 0, "Everyone", 0, SENTINEL_PID, -1},
846 	{"S-1-3", 0, "Creator Owner", 1, IDMAP_WK_CREATOR_OWNER_UID, 0},
847 	{"S-1-3", 1, "Creator Group", 0, IDMAP_WK_CREATOR_GROUP_GID, 0},
848 	{"S-1-3", 2, "Creator Owner Server", 1, SENTINEL_PID, -1},
849 	{"S-1-3", 3, "Creator Group Server", 0, SENTINEL_PID, -1},
850 	{"S-1-5", 1, "Dialup", 0, SENTINEL_PID, -1},
851 	{"S-1-5", 2, "Network", 0, SENTINEL_PID, -1},
852 	{"S-1-5", 3, "Batch", 0, SENTINEL_PID, -1},
853 	{"S-1-5", 4, "Interactive", 0, SENTINEL_PID, -1},
854 	{"S-1-5", 6, "Service", 0, SENTINEL_PID, -1},
855 	{"S-1-5", 7, "Anonymous Logon", 0, GID_NOBODY, 0},
856 	{"S-1-5", 8, "Proxy", 0, SENTINEL_PID, -1},
857 	{"S-1-5", 9, "Enterprise Domain Controllers", 0, SENTINEL_PID, -1},
858 	{"S-1-5", 10, "Self", 0, SENTINEL_PID, -1},
859 	{"S-1-5", 11, "Authenticated Users", 0, SENTINEL_PID, -1},
860 	{"S-1-5", 12, "Restricted Code", 0, SENTINEL_PID, -1},
861 	{"S-1-5", 13, "Terminal Server User", 0, SENTINEL_PID, -1},
862 	{"S-1-5", 14, "Remote Interactive Logon", 0, SENTINEL_PID, -1},
863 	{"S-1-5", 15, "This Organization", 0, SENTINEL_PID, -1},
864 	{"S-1-5", 18, "Local System", 0, IDMAP_WK_LOCAL_SYSTEM_GID, 0},
865 	{"S-1-5", 19, "Local Service", 0, SENTINEL_PID, -1},
866 	{"S-1-5", 20, "Network Service", 0, SENTINEL_PID, -1},
867 	{"S-1-5", 1000, "Other Organization", 0, SENTINEL_PID, -1},
868 	{"S-1-5-64", 21, "Digest Authentication", 0, SENTINEL_PID, -1},
869 	{"S-1-5-64", 10, "NTLM Authentication", 0, SENTINEL_PID, -1},
870 	{"S-1-5-64", 14, "SChannel Authentication", 0, SENTINEL_PID, -1},
871 	{NULL, UINT32_MAX, NULL, -1, SENTINEL_PID, -1}
872 };
873 
874 static idmap_retcode
875 lookup_wksids_sid2pid(idmap_mapping *req, idmap_id_res *res) {
876 	int i;
877 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
878 		if (wksids[i].rid == req->id1.idmap_id_u.sid.rid &&
879 		    (strcasecmp(wksids[i].sidprefix,
880 		    req->id1.idmap_id_u.sid.prefix) == 0)) {
881 
882 			if (wksids[i].pid == SENTINEL_PID)
883 				/* Not mapped, break */
884 				break;
885 			else if (wksids[i].direction == IDMAP_DIRECTION_U2W)
886 				continue;
887 
888 			switch (req->id2.idtype) {
889 			case IDMAP_UID:
890 				if (wksids[i].is_user == 0)
891 					continue;
892 				res->id.idmap_id_u.uid = wksids[i].pid;
893 				res->direction = wksids[i].direction;
894 				return (IDMAP_SUCCESS);
895 			case IDMAP_GID:
896 				if (wksids[i].is_user == 1)
897 					continue;
898 				res->id.idmap_id_u.gid = wksids[i].pid;
899 				res->direction = wksids[i].direction;
900 				return (IDMAP_SUCCESS);
901 			case IDMAP_POSIXID:
902 				res->id.idmap_id_u.uid = wksids[i].pid;
903 				res->id.idtype = (!wksids[i].is_user)?
904 						IDMAP_GID:IDMAP_UID;
905 				res->direction = wksids[i].direction;
906 				return (IDMAP_SUCCESS);
907 			default:
908 				return (IDMAP_ERR_NOTSUPPORTED);
909 			}
910 		}
911 	}
912 	return (IDMAP_ERR_NOTFOUND);
913 }
914 
915 static idmap_retcode
916 lookup_wksids_pid2sid(idmap_mapping *req, idmap_id_res *res, int is_user) {
917 	int i;
918 	if (req->id2.idtype != IDMAP_SID)
919 		return (IDMAP_ERR_NOTSUPPORTED);
920 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
921 		if (wksids[i].pid == req->id1.idmap_id_u.uid &&
922 		    wksids[i].is_user == is_user &&
923 		    wksids[i].direction != IDMAP_DIRECTION_W2U) {
924 			res->id.idmap_id_u.sid.rid = wksids[i].rid;
925 			res->id.idmap_id_u.sid.prefix =
926 				strdup(wksids[i].sidprefix);
927 			if (res->id.idmap_id_u.sid.prefix == NULL) {
928 				idmapdlog(LOG_ERR, "Out of memory");
929 				return (IDMAP_ERR_MEMORY);
930 			}
931 			res->direction = wksids[i].direction;
932 			return (IDMAP_SUCCESS);
933 		}
934 	}
935 	return (IDMAP_ERR_NOTFOUND);
936 }
937 
938 static idmap_retcode
939 lookup_wksids_sid2name(const char *sidprefix, idmap_rid_t rid, char **name,
940 		int *type) {
941 	int i;
942 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
943 		if ((strcasecmp(wksids[i].sidprefix, sidprefix) == 0) &&
944 		    wksids[i].rid == rid) {
945 			if ((*name = strdup(wksids[i].winname)) == NULL) {
946 				idmapdlog(LOG_ERR, "Out of memory");
947 				return (IDMAP_ERR_MEMORY);
948 			}
949 			*type = (wksids[i].is_user)?
950 			    _IDMAP_T_USER:_IDMAP_T_GROUP;
951 			return (IDMAP_SUCCESS);
952 		}
953 	}
954 	return (IDMAP_ERR_NOTFOUND);
955 }
956 
957 static idmap_retcode
958 lookup_wksids_name2sid(const char *name, char **sidprefix, idmap_rid_t *rid,
959 		int *type) {
960 	int i;
961 	for (i = 0; wksids[i].sidprefix != NULL; i++) {
962 		if (strcasecmp(wksids[i].winname, name) == 0) {
963 			if (sidprefix != NULL && (*sidprefix =
964 			    strdup(wksids[i].sidprefix)) == NULL) {
965 				idmapdlog(LOG_ERR, "Out of memory");
966 				return (IDMAP_ERR_MEMORY);
967 			}
968 			if (type != NULL)
969 				*type = (wksids[i].is_user)?
970 				    _IDMAP_T_USER:_IDMAP_T_GROUP;
971 			if (rid != NULL)
972 				*rid = wksids[i].rid;
973 			return (IDMAP_SUCCESS);
974 		}
975 	}
976 	return (IDMAP_ERR_NOTFOUND);
977 }
978 
979 static idmap_retcode
980 lookup_cache_sid2pid(sqlite *cache, idmap_mapping *req, idmap_id_res *res) {
981 	char		*end;
982 	char		*sql = NULL;
983 	const char	**values;
984 	sqlite_vm	*vm = NULL;
985 	int		ncol, is_user;
986 	uid_t		pid;
987 	idmap_utf8str	*str;
988 	time_t		curtime, exp;
989 	idmap_retcode	retcode;
990 
991 	/* Current time */
992 	errno = 0;
993 	if ((curtime = time(NULL)) == (time_t)-1) {
994 		idmapdlog(LOG_ERR,
995 			"Failed to get current time (%s)",
996 			strerror(errno));
997 		retcode = IDMAP_ERR_INTERNAL;
998 		goto out;
999 	}
1000 
1001 	/* SQL to lookup the cache */
1002 	sql = sqlite_mprintf("SELECT pid, is_user, expiration, unixname, u2w "
1003 			"FROM idmap_cache WHERE "
1004 			"sidprefix = %Q AND rid = %u AND w2u = 1 AND "
1005 			"(pid >= 2147483648 OR "
1006 			"(expiration = 0 OR expiration ISNULL OR "
1007 			"expiration > %d));",
1008 			req->id1.idmap_id_u.sid.prefix,
1009 			req->id1.idmap_id_u.sid.rid,
1010 			curtime);
1011 	if (sql == NULL) {
1012 		idmapdlog(LOG_ERR, "Out of memory");
1013 		retcode = IDMAP_ERR_MEMORY;
1014 		goto out;
1015 	}
1016 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 5, &values);
1017 	sqlite_freemem(sql);
1018 
1019 	if (retcode == IDMAP_ERR_NOTFOUND) {
1020 		goto out;
1021 	} else if (retcode == IDMAP_SUCCESS) {
1022 		/* sanity checks */
1023 		if (values[0] == NULL || values[1] == NULL) {
1024 			retcode = IDMAP_ERR_CACHE;
1025 			goto out;
1026 		}
1027 
1028 		pid = strtoul(values[0], &end, 10);
1029 		is_user = strncmp(values[1], "0", 2)?1:0;
1030 
1031 		/*
1032 		 * We may have an expired ephemeral mapping. Consider
1033 		 * the expired entry as valid if we are not going to
1034 		 * perform name-based mapping. But do not renew the
1035 		 * expiration.
1036 		 * If we will be doing name-based mapping then store the
1037 		 * ephemeral pid in the result so that we can use it
1038 		 * if we end up doing dynamic mapping again.
1039 		 */
1040 		if (!DO_NOT_ALLOC_NEW_ID_MAPPING(req) &&
1041 				!AVOID_NAMESERVICE(req)) {
1042 			if (IS_EPHEMERAL(pid) && values[2] != NULL) {
1043 				exp = strtoll(values[2], &end, 10);
1044 				if (exp && exp <= curtime) {
1045 					/* Store the ephemeral pid */
1046 					res->id.idmap_id_u.uid = pid;
1047 					res->id.idtype = is_user?
1048 						IDMAP_UID:IDMAP_GID;
1049 					res->direction = IDMAP_DIRECTION_BI;
1050 					req->direction |= is_user?
1051 						_IDMAP_F_EXP_EPH_UID:
1052 						_IDMAP_F_EXP_EPH_GID;
1053 					retcode = IDMAP_ERR_NOTFOUND;
1054 					goto out;
1055 				}
1056 			}
1057 		}
1058 
1059 		switch (req->id2.idtype) {
1060 		case IDMAP_UID:
1061 			if (!is_user)
1062 				retcode = IDMAP_ERR_NOTUSER;
1063 			else
1064 				res->id.idmap_id_u.uid = pid;
1065 			break;
1066 		case IDMAP_GID:
1067 			if (is_user)
1068 				retcode = IDMAP_ERR_NOTGROUP;
1069 			else
1070 				res->id.idmap_id_u.gid = pid;
1071 			break;
1072 		case IDMAP_POSIXID:
1073 			res->id.idmap_id_u.uid = pid;
1074 			res->id.idtype = (is_user)?IDMAP_UID:IDMAP_GID;
1075 			break;
1076 		default:
1077 			retcode = IDMAP_ERR_NOTSUPPORTED;
1078 			break;
1079 		}
1080 	}
1081 
1082 out:
1083 	if (retcode == IDMAP_SUCCESS) {
1084 		if (values[4] != NULL)
1085 			res->direction =
1086 			    (strtol(values[4], &end, 10) == 0)?
1087 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
1088 		else
1089 			res->direction = IDMAP_DIRECTION_W2U;
1090 
1091 		if (values[3] != NULL) {
1092 			str = &req->id2name;
1093 			retcode = idmap_str2utf8(&str, values[3], 0);
1094 			if (retcode != IDMAP_SUCCESS) {
1095 				idmapdlog(LOG_ERR, "Out of memory");
1096 				retcode = IDMAP_ERR_MEMORY;
1097 			}
1098 		}
1099 	}
1100 	if (vm != NULL)
1101 		(void) sqlite_finalize(vm, NULL);
1102 	return (retcode);
1103 }
1104 
1105 static idmap_retcode
1106 lookup_cache_sid2name(sqlite *cache, const char *sidprefix, idmap_rid_t rid,
1107 		char **name, char **domain, int *type) {
1108 	char		*end;
1109 	char		*sql = NULL;
1110 	const char	**values;
1111 	sqlite_vm	*vm = NULL;
1112 	int		ncol;
1113 	time_t		curtime;
1114 	idmap_retcode	retcode = IDMAP_SUCCESS;
1115 
1116 	/* Get current time */
1117 	errno = 0;
1118 	if ((curtime = time(NULL)) == (time_t)-1) {
1119 		idmapdlog(LOG_ERR,
1120 			"Failed to get current time (%s)",
1121 			strerror(errno));
1122 		retcode = IDMAP_ERR_INTERNAL;
1123 		goto out;
1124 	}
1125 
1126 	/* SQL to lookup the cache */
1127 	sql = sqlite_mprintf("SELECT name, domain, type FROM name_cache WHERE "
1128 			"sidprefix = %Q AND rid = %u AND "
1129 			"(expiration = 0 OR expiration ISNULL OR "
1130 			"expiration > %d);",
1131 			sidprefix, rid, curtime);
1132 	if (sql == NULL) {
1133 		idmapdlog(LOG_ERR, "Out of memory");
1134 		retcode = IDMAP_ERR_MEMORY;
1135 		goto out;
1136 	}
1137 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 3, &values);
1138 	sqlite_freemem(sql);
1139 
1140 	if (retcode == IDMAP_SUCCESS) {
1141 		if (type != NULL) {
1142 			if (values[2] == NULL) {
1143 				retcode = IDMAP_ERR_CACHE;
1144 				goto out;
1145 			}
1146 			*type = strtol(values[2], &end, 10);
1147 		}
1148 
1149 		if (name != NULL && values[0] != NULL) {
1150 			if ((*name = strdup(values[0])) == NULL) {
1151 				idmapdlog(LOG_ERR, "Out of memory");
1152 				retcode = IDMAP_ERR_MEMORY;
1153 				goto out;
1154 			}
1155 		}
1156 
1157 		if (domain != NULL && values[1] != NULL) {
1158 			if ((*domain = strdup(values[1])) == NULL) {
1159 				if (name != NULL && *name) {
1160 					free(*name);
1161 					*name = NULL;
1162 				}
1163 				idmapdlog(LOG_ERR, "Out of memory");
1164 				retcode = IDMAP_ERR_MEMORY;
1165 				goto out;
1166 			}
1167 		}
1168 	}
1169 
1170 out:
1171 	if (vm != NULL)
1172 		(void) sqlite_finalize(vm, NULL);
1173 	return (retcode);
1174 }
1175 
1176 static idmap_retcode
1177 verify_type(idmap_id_type idtype, int type, idmap_id_res *res) {
1178 	switch (idtype) {
1179 	case IDMAP_UID:
1180 		if (type != _IDMAP_T_USER)
1181 			return (IDMAP_ERR_NOTUSER);
1182 		res->id.idtype = IDMAP_UID;
1183 		break;
1184 	case IDMAP_GID:
1185 		if (type != _IDMAP_T_GROUP)
1186 			return (IDMAP_ERR_NOTGROUP);
1187 		res->id.idtype = IDMAP_GID;
1188 		break;
1189 	case IDMAP_POSIXID:
1190 		if (type == _IDMAP_T_USER)
1191 			res->id.idtype = IDMAP_UID;
1192 		else if (type == _IDMAP_T_GROUP)
1193 			res->id.idtype = IDMAP_GID;
1194 		else
1195 			return (IDMAP_ERR_SID);
1196 		break;
1197 	default:
1198 		return (IDMAP_ERR_NOTSUPPORTED);
1199 	}
1200 	return (IDMAP_SUCCESS);
1201 }
1202 
1203 /*
1204  * Lookup sid to name locally
1205  */
1206 static idmap_retcode
1207 lookup_local_sid2name(sqlite *cache, idmap_mapping *req, idmap_id_res *res) {
1208 	int		type = -1;
1209 	idmap_retcode	retcode;
1210 	char		*sidprefix;
1211 	idmap_rid_t	rid;
1212 	char		*name = NULL, *domain = NULL;
1213 	idmap_utf8str	*str;
1214 
1215 	sidprefix = req->id1.idmap_id_u.sid.prefix;
1216 	rid = req->id1.idmap_id_u.sid.rid;
1217 
1218 	/* Lookup sids to name in well-known sids table */
1219 	retcode = lookup_wksids_sid2name(sidprefix, rid, &name, &type);
1220 	if (retcode != IDMAP_ERR_NOTFOUND)
1221 		goto out;
1222 
1223 	/* Lookup sid to name in cache */
1224 	retcode = lookup_cache_sid2name(cache, sidprefix, rid, &name,
1225 		&domain, &type);
1226 	if (retcode != IDMAP_SUCCESS)
1227 		goto out;
1228 
1229 out:
1230 	if (retcode == IDMAP_SUCCESS) {
1231 		/* Verify that the sid type matches the request */
1232 		retcode = verify_type(req->id2.idtype, type, res);
1233 
1234 		/* update state in 'req' */
1235 		if (name != NULL) {
1236 			str = &req->id1name;
1237 			(void) idmap_str2utf8(&str, name, 1);
1238 		}
1239 		if (domain != NULL) {
1240 			str = &req->id1domain;
1241 			(void) idmap_str2utf8(&str, domain, 1);
1242 		}
1243 	} else {
1244 		if (name != NULL)
1245 			free(name);
1246 		if (domain != NULL)
1247 			free(domain);
1248 	}
1249 	return (retcode);
1250 }
1251 
1252 idmap_retcode
1253 lookup_win_batch_sid2name(lookup_state_t *state, idmap_mapping_batch *batch,
1254 		idmap_ids_res *result) {
1255 	idmap_retcode	retcode;
1256 	int		ret, i;
1257 	int		retries = 0;
1258 	idmap_mapping	*req;
1259 	idmap_id_res	*res;
1260 
1261 	if (state->ad_nqueries == 0)
1262 		return (IDMAP_SUCCESS);
1263 
1264 retry:
1265 	ret = idmap_lookup_batch_start(_idmapdstate.ad, state->ad_nqueries,
1266 		&state->ad_lookup);
1267 	if (ret != 0) {
1268 		idmapdlog(LOG_ERR,
1269 		"Failed to create sid2name batch for AD lookup");
1270 		return (IDMAP_ERR_INTERNAL);
1271 	}
1272 
1273 	for (i = 0; i < batch->idmap_mapping_batch_len; i++) {
1274 		req = &batch->idmap_mapping_batch_val[i];
1275 		res = &result->ids.ids_val[i];
1276 
1277 		if (req->id1.idtype == IDMAP_SID &&
1278 				req->direction & _IDMAP_F_S2N_AD) {
1279 			if (retries == 0)
1280 				res->retcode = IDMAP_ERR_RETRIABLE_NET_ERR;
1281 			else if (res->retcode != IDMAP_ERR_RETRIABLE_NET_ERR)
1282 				continue;
1283 			retcode = idmap_sid2name_batch_add1(
1284 					state->ad_lookup,
1285 					req->id1.idmap_id_u.sid.prefix,
1286 					&req->id1.idmap_id_u.sid.rid,
1287 					&req->id1name.idmap_utf8str_val,
1288 					&req->id1domain.idmap_utf8str_val,
1289 					(int *)&res->id.idtype,
1290 					&res->retcode);
1291 
1292 			if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
1293 				break;
1294 			if (retcode != IDMAP_SUCCESS)
1295 				goto out;
1296 		}
1297 	}
1298 
1299 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
1300 		idmap_lookup_free_batch(&state->ad_lookup);
1301 	else
1302 		retcode = idmap_lookup_batch_end(&state->ad_lookup, NULL);
1303 
1304 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
1305 		goto retry;
1306 
1307 	return (retcode);
1308 
1309 out:
1310 	idmapdlog(LOG_NOTICE, "Windows SID to user/group name lookup failed");
1311 	idmap_lookup_free_batch(&state->ad_lookup);
1312 	return (retcode);
1313 }
1314 
1315 idmap_retcode
1316 sid2pid_first_pass(lookup_state_t *state, sqlite *cache, idmap_mapping *req,
1317 		idmap_id_res *res) {
1318 	idmap_retcode	retcode;
1319 
1320 	/*
1321 	 * The req->direction field is used to maintain state of the
1322 	 * sid2pid request.
1323 	 */
1324 	req->direction = _IDMAP_F_DONE;
1325 
1326 	if (req->id1.idmap_id_u.sid.prefix == NULL) {
1327 		retcode = IDMAP_ERR_SID;
1328 		goto out;
1329 	}
1330 	res->id.idtype = req->id2.idtype;
1331 	res->id.idmap_id_u.uid = UID_NOBODY;
1332 
1333 	/* Lookup well-known sid to pid mapping */
1334 	retcode = lookup_wksids_sid2pid(req, res);
1335 	if (retcode != IDMAP_ERR_NOTFOUND)
1336 		goto out;
1337 
1338 	/* Lookup sid to pid in cache */
1339 	retcode = lookup_cache_sid2pid(cache, req, res);
1340 	if (retcode != IDMAP_ERR_NOTFOUND)
1341 		goto out;
1342 
1343 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req) || AVOID_NAMESERVICE(req)) {
1344 		res->id.idmap_id_u.uid = SENTINEL_PID;
1345 		goto out;
1346 	}
1347 
1348 	/*
1349 	 * Failed to find non-expired entry in cache. Tell the caller
1350 	 * that we are not done yet.
1351 	 */
1352 	state->sid2pid_done = FALSE;
1353 
1354 	/*
1355 	 * Our next step is name-based mapping. To lookup name-based
1356 	 * mapping rules, we need the windows name and domain-name
1357 	 * associated with the SID.
1358 	 */
1359 
1360 	/*
1361 	 * Check if we already have the name (i.e name2pid lookups)
1362 	 */
1363 	if (req->id1name.idmap_utf8str_val != NULL &&
1364 	    req->id1domain.idmap_utf8str_val != NULL) {
1365 		retcode = IDMAP_SUCCESS;
1366 		req->direction |= _IDMAP_F_S2N_CACHE;
1367 		goto out;
1368 	}
1369 
1370 	/* Lookup sid to winname@domain locally first */
1371 	retcode = lookup_local_sid2name(cache, req, res);
1372 	if (retcode == IDMAP_SUCCESS) {
1373 		req->direction |= _IDMAP_F_S2N_CACHE;
1374 	} else if (retcode == IDMAP_ERR_NOTFOUND) {
1375 		/* Batch sid to name AD lookup request */
1376 		retcode = IDMAP_SUCCESS;
1377 		req->direction |= _IDMAP_F_S2N_AD;
1378 		state->ad_nqueries++;
1379 		goto out;
1380 	}
1381 
1382 
1383 out:
1384 	res->retcode = idmap_stat4prot(retcode);
1385 	return (retcode);
1386 }
1387 
1388 /*
1389  * Generate SID using the following convention
1390  * 	<machine-sid-prefix>-<1000 + uid>
1391  * 	<machine-sid-prefix>-<2^31 + gid>
1392  */
1393 static idmap_retcode
1394 generate_localsid(idmap_mapping *req, idmap_id_res *res, int is_user) {
1395 
1396 	if (_idmapdstate.cfg->pgcfg.machine_sid != NULL) {
1397 		/* Skip 1000 UIDs */
1398 		if (is_user && req->id1.idmap_id_u.uid >
1399 				(INT32_MAX - LOCALRID_MIN))
1400 			return (IDMAP_ERR_NOMAPPING);
1401 
1402 		RDLOCK_CONFIG();
1403 		res->id.idmap_id_u.sid.prefix =
1404 			strdup(_idmapdstate.cfg->pgcfg.machine_sid);
1405 		if (res->id.idmap_id_u.sid.prefix == NULL) {
1406 			UNLOCK_CONFIG();
1407 			idmapdlog(LOG_ERR, "Out of memory");
1408 			return (IDMAP_ERR_MEMORY);
1409 		}
1410 		UNLOCK_CONFIG();
1411 		res->id.idmap_id_u.sid.rid =
1412 			(is_user)?req->id1.idmap_id_u.uid + LOCALRID_MIN:
1413 			req->id1.idmap_id_u.gid + INT32_MAX + 1;
1414 		res->direction = IDMAP_DIRECTION_BI;
1415 
1416 		/*
1417 		 * Don't update name_cache because local sids don't have
1418 		 * valid windows names.
1419 		 * We mark the entry as being found in the namecache so that
1420 		 * the cache update routine doesn't update namecache.
1421 		 */
1422 		req->direction = _IDMAP_F_S2N_CACHE;
1423 		return (IDMAP_SUCCESS);
1424 	}
1425 
1426 	return (IDMAP_ERR_NOMAPPING);
1427 }
1428 
1429 static idmap_retcode
1430 lookup_localsid2pid(idmap_mapping *req, idmap_id_res *res) {
1431 	char		*sidprefix;
1432 	uint32_t	rid;
1433 	int		s;
1434 
1435 	/*
1436 	 * If the sidprefix == localsid then UID = last RID - 1000 or
1437 	 * GID = last RID - 2^31.
1438 	 */
1439 	sidprefix = req->id1.idmap_id_u.sid.prefix;
1440 	rid = req->id1.idmap_id_u.sid.rid;
1441 
1442 	RDLOCK_CONFIG();
1443 	s = (_idmapdstate.cfg->pgcfg.machine_sid)?
1444 		strcasecmp(sidprefix,
1445 		_idmapdstate.cfg->pgcfg.machine_sid):1;
1446 	UNLOCK_CONFIG();
1447 
1448 	if (s == 0) {
1449 		switch (req->id2.idtype) {
1450 		case IDMAP_UID:
1451 			if (rid > INT32_MAX) {
1452 				return (IDMAP_ERR_NOTUSER);
1453 			} else if (rid < LOCALRID_MIN) {
1454 				return (IDMAP_ERR_NOTFOUND);
1455 			}
1456 			res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
1457 			res->id.idtype = IDMAP_UID;
1458 			break;
1459 		case IDMAP_GID:
1460 			if (rid <= INT32_MAX) {
1461 				return (IDMAP_ERR_NOTGROUP);
1462 			}
1463 			res->id.idmap_id_u.gid = rid - INT32_MAX - 1;
1464 			res->id.idtype = IDMAP_GID;
1465 			break;
1466 		case IDMAP_POSIXID:
1467 			if (rid > INT32_MAX) {
1468 				res->id.idmap_id_u.gid =
1469 					rid - INT32_MAX - 1;
1470 				res->id.idtype = IDMAP_GID;
1471 			} else if (rid < LOCALRID_MIN) {
1472 				return (IDMAP_ERR_NOTFOUND);
1473 			} else {
1474 				res->id.idmap_id_u.uid = rid - LOCALRID_MIN;
1475 				res->id.idtype = IDMAP_UID;
1476 			}
1477 			break;
1478 		default:
1479 			return (IDMAP_ERR_NOTSUPPORTED);
1480 		}
1481 		return (IDMAP_SUCCESS);
1482 	}
1483 
1484 	return (IDMAP_ERR_NOTFOUND);
1485 }
1486 
1487 static idmap_retcode
1488 ns_lookup_byname(int is_user, const char *name, idmap_id_res *res) {
1489 	struct passwd	pwd;
1490 	struct group	grp;
1491 	char		buf[1024];
1492 	int		errnum;
1493 	const char	*me = "ns_lookup_byname";
1494 
1495 	if (is_user) {
1496 		if (getpwnam_r(name, &pwd, buf, sizeof (buf)) == NULL) {
1497 			errnum = errno;
1498 			idmapdlog(LOG_WARNING,
1499 			"%s: getpwnam_r(%s) failed (%s).",
1500 				me, name,
1501 				errnum?strerror(errnum):"not found");
1502 			if (errnum == 0)
1503 				return (IDMAP_ERR_NOTFOUND);
1504 			else
1505 				return (IDMAP_ERR_INTERNAL);
1506 		}
1507 		res->id.idmap_id_u.uid = pwd.pw_uid;
1508 		res->id.idtype = IDMAP_UID;
1509 	} else {
1510 		if (getgrnam_r(name, &grp, buf, sizeof (buf)) == NULL) {
1511 			errnum = errno;
1512 			idmapdlog(LOG_WARNING,
1513 			"%s: getgrnam_r(%s) failed (%s).",
1514 				me, name,
1515 				errnum?strerror(errnum):"not found");
1516 			if (errnum == 0)
1517 				return (IDMAP_ERR_NOTFOUND);
1518 			else
1519 				return (IDMAP_ERR_INTERNAL);
1520 		}
1521 		res->id.idmap_id_u.gid = grp.gr_gid;
1522 		res->id.idtype = IDMAP_GID;
1523 	}
1524 	return (IDMAP_SUCCESS);
1525 }
1526 
1527 /*
1528  * Name-based mapping
1529  *
1530  * Case 1: If no rule matches do ephemeral
1531  *
1532  * Case 2: If rule matches and unixname is "" then return no mapping.
1533  *
1534  * Case 3: If rule matches and unixname is specified then lookup name
1535  *  service using the unixname. If unixname not found then return no mapping.
1536  *
1537  * Case 4: If rule matches and unixname is * then lookup name service
1538  *  using winname as the unixname. If unixname not found then process
1539  *  other rules using the lookup order. If no other rule matches then do
1540  *  ephemeral. Otherwise, based on the matched rule do Case 2 or 3 or 4.
1541  *  This allows us to specify a fallback unixname per _domain_ or no mapping
1542  *  instead of the default behaviour of doing ephemeral mapping.
1543  *
1544  * Example 1:
1545  * *@sfbay == *
1546  * If looking up windows users foo@sfbay and foo does not exists in
1547  * the name service then foo@sfbay will be mapped to an ephemeral id.
1548  *
1549  * Example 2:
1550  * *@sfbay == *
1551  * *@sfbay => guest
1552  * If looking up windows users foo@sfbay and foo does not exists in
1553  * the name service then foo@sfbay will be mapped to guest.
1554  *
1555  * Example 3:
1556  * *@sfbay == *
1557  * *@sfbay => ""
1558  * If looking up windows users foo@sfbay and foo does not exists in
1559  * the name service then we will return no mapping for foo@sfbay.
1560  *
1561  */
1562 static idmap_retcode
1563 name_based_mapping_sid2pid(sqlite *db, idmap_mapping *req, idmap_id_res *res) {
1564 	const char	*unixname, *winname, *windomain;
1565 	char		*sql = NULL, *errmsg = NULL;
1566 	idmap_retcode	retcode;
1567 	char		*end;
1568 	const char	**values;
1569 	sqlite_vm	*vm = NULL;
1570 	struct timespec rqtp;
1571 	idmap_utf8str	*str;
1572 	int		ncol, r, i, s, is_user;
1573 	const char	*me = "name_based_mapping_sid2pid";
1574 
1575 	winname = req->id1name.idmap_utf8str_val;
1576 	windomain = req->id1domain.idmap_utf8str_val;
1577 	is_user = (res->id.idtype == IDMAP_UID)?1:0;
1578 
1579 	i = 0;
1580 	if (windomain == NULL) {
1581 		windomain = "";
1582 	} else {
1583 		RDLOCK_CONFIG();
1584 		if (_idmapdstate.cfg->pgcfg.mapping_domain != NULL) {
1585 			if (strcasecmp(_idmapdstate.cfg->pgcfg.mapping_domain,
1586 			    windomain) == 0)
1587 				i = 1;
1588 		}
1589 		UNLOCK_CONFIG();
1590 	}
1591 
1592 	sql = sqlite_mprintf(
1593 		"SELECT unixname, u2w_order FROM namerules WHERE "
1594 		"w2u_order > 0 AND is_user = %d AND "
1595 		"(winname = %Q OR winname = '*') AND "
1596 		"(windomain = %Q OR windomain = '*' %s) "
1597 		"ORDER BY w2u_order ASC;",
1598 		is_user, winname,
1599 		windomain,
1600 		i?"OR windomain ISNULL OR windomain = ''":"");
1601 	if (sql == NULL) {
1602 		idmapdlog(LOG_ERR, "Out of memory");
1603 		retcode = IDMAP_ERR_MEMORY;
1604 		goto out;
1605 	}
1606 
1607 	if (sqlite_compile(db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
1608 		retcode = IDMAP_ERR_INTERNAL;
1609 		idmapdlog(LOG_ERR,
1610 			"%s: database error (%s)",
1611 			me, CHECK_NULL(errmsg));
1612 		sqlite_freemem(errmsg);
1613 		goto out;
1614 	}
1615 
1616 	for (i = 0, s = SLEEP_TIME; ; ) {
1617 		r = sqlite_step(vm, &ncol, &values, NULL);
1618 
1619 		if (r == SQLITE_BUSY) {
1620 			if (++i < MAX_TRIES) {
1621 				NANO_SLEEP(rqtp, s);
1622 				s *= 2;
1623 				continue;
1624 			}
1625 			retcode = IDMAP_ERR_BUSY;
1626 			goto out;
1627 		} else if (r == SQLITE_ROW) {
1628 			if (ncol < 2) {
1629 				retcode = IDMAP_ERR_INTERNAL;
1630 				goto out;
1631 			}
1632 			if (values[0] == NULL) {
1633 				retcode = IDMAP_ERR_INTERNAL;
1634 				goto out;
1635 			}
1636 
1637 			if (EMPTY_NAME(values[0])) {
1638 				retcode = IDMAP_ERR_NOMAPPING;
1639 				goto out;
1640 			}
1641 			unixname = (values[0][0] == '*')?winname:values[0];
1642 			retcode = ns_lookup_byname(is_user, unixname, res);
1643 			if (retcode == IDMAP_ERR_NOTFOUND) {
1644 				if (unixname == winname)
1645 					/* Case 4 */
1646 					continue;
1647 				else
1648 					/* Case 3 */
1649 					retcode = IDMAP_ERR_NOMAPPING;
1650 			}
1651 			goto out;
1652 		} else if (r == SQLITE_DONE) {
1653 			retcode = IDMAP_ERR_NOTFOUND;
1654 			goto out;
1655 		} else {
1656 			(void) sqlite_finalize(vm, &errmsg);
1657 			vm = NULL;
1658 			idmapdlog(LOG_ERR,
1659 				"%s: database error (%s)",
1660 				me, CHECK_NULL(errmsg));
1661 			sqlite_freemem(errmsg);
1662 			retcode = IDMAP_ERR_INTERNAL;
1663 			goto out;
1664 		}
1665 	}
1666 
1667 out:
1668 	if (sql != NULL)
1669 		sqlite_freemem(sql);
1670 	if (retcode == IDMAP_SUCCESS) {
1671 		if (values[1] != NULL)
1672 			res->direction =
1673 			    (strtol(values[1], &end, 10) == 0)?
1674 			    IDMAP_DIRECTION_W2U:IDMAP_DIRECTION_BI;
1675 		else
1676 			res->direction = IDMAP_DIRECTION_W2U;
1677 		str = &req->id2name;
1678 		retcode = idmap_str2utf8(&str, unixname, 0);
1679 	}
1680 	if (vm != NULL)
1681 		(void) sqlite_finalize(vm, NULL);
1682 	return (retcode);
1683 }
1684 
1685 static
1686 int
1687 get_next_eph_uid(uid_t *next_uid)
1688 {
1689 	uid_t uid;
1690 	gid_t gid;
1691 	int err;
1692 
1693 	*next_uid = (uid_t)-1;
1694 	uid = _idmapdstate.next_uid++;
1695 	if (uid >= _idmapdstate.limit_uid) {
1696 		if ((err = allocids(0, 8192, &uid, 0, &gid)) != 0)
1697 			return (err);
1698 
1699 		_idmapdstate.limit_uid = uid + 8192;
1700 		_idmapdstate.next_uid = uid;
1701 	}
1702 	*next_uid = uid;
1703 
1704 	return (0);
1705 }
1706 
1707 static
1708 int
1709 get_next_eph_gid(gid_t *next_gid)
1710 {
1711 	uid_t uid;
1712 	gid_t gid;
1713 	int err;
1714 
1715 	*next_gid = (uid_t)-1;
1716 	gid = _idmapdstate.next_gid++;
1717 	if (gid >= _idmapdstate.limit_gid) {
1718 		if ((err = allocids(0, 0, &uid, 8192, &gid)) != 0)
1719 			return (err);
1720 
1721 		_idmapdstate.limit_gid = gid + 8192;
1722 		_idmapdstate.next_gid = gid;
1723 	}
1724 	*next_gid = gid;
1725 
1726 	return (0);
1727 }
1728 
1729 static
1730 int
1731 gethash(const char *str, uint32_t num, uint_t htsize) {
1732 	uint_t  hval, i, len;
1733 
1734 	if (str == NULL)
1735 		return (0);
1736 	for (len = strlen(str), hval = 0, i = 0; i < len; i++) {
1737 		hval += str[i];
1738 		hval += (hval << 10);
1739 		hval ^= (hval >> 6);
1740 	}
1741 	for (str = (const char *)&num, i = 0; i < sizeof (num); i++) {
1742 		hval += str[i];
1743 		hval += (hval << 10);
1744 		hval ^= (hval >> 6);
1745 	}
1746 	hval += (hval << 3);
1747 	hval ^= (hval >> 11);
1748 	hval += (hval << 15);
1749 	return (hval % htsize);
1750 }
1751 
1752 static
1753 int
1754 get_from_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid,
1755 		uid_t *pid) {
1756 	uint_t		next, key;
1757 	uint_t		htsize = state->sid_history_size;
1758 	idmap_sid	*sid;
1759 
1760 	next = gethash(prefix, rid, htsize);
1761 	while (next != htsize) {
1762 		key = state->sid_history[next].key;
1763 		if (key == htsize)
1764 			return (0);
1765 		sid = &state->batch->idmap_mapping_batch_val[key].id1.
1766 		    idmap_id_u.sid;
1767 		if (sid->rid == rid && strcmp(sid->prefix, prefix) == 0) {
1768 			*pid = state->result->ids.ids_val[key].id.
1769 			    idmap_id_u.uid;
1770 			return (1);
1771 		}
1772 		next = state->sid_history[next].next;
1773 	}
1774 	return (0);
1775 }
1776 
1777 static
1778 void
1779 add_to_sid_history(lookup_state_t *state, const char *prefix, uint32_t rid) {
1780 	uint_t		hash, next;
1781 	uint_t		htsize = state->sid_history_size;
1782 
1783 	hash = next = gethash(prefix, rid, htsize);
1784 	while (state->sid_history[next].key != htsize) {
1785 		next++;
1786 		next %= htsize;
1787 	}
1788 	state->sid_history[next].key = state->curpos;
1789 	if (hash == next)
1790 		return;
1791 	state->sid_history[next].next = state->sid_history[hash].next;
1792 	state->sid_history[hash].next = next;
1793 }
1794 
1795 /* ARGSUSED */
1796 static
1797 idmap_retcode
1798 dynamic_ephemeral_mapping(lookup_state_t *state, sqlite *cache,
1799 		idmap_mapping *req, idmap_id_res *res) {
1800 
1801 	uid_t		next_pid;
1802 
1803 	res->direction = IDMAP_DIRECTION_BI;
1804 
1805 	if (IS_EPHEMERAL(res->id.idmap_id_u.uid))
1806 		return (IDMAP_SUCCESS);
1807 
1808 	if (state->sid_history != NULL &&
1809 	    get_from_sid_history(state, req->id1.idmap_id_u.sid.prefix,
1810 	    req->id1.idmap_id_u.sid.rid, &next_pid)) {
1811 		res->id.idmap_id_u.uid = next_pid;
1812 		return (IDMAP_SUCCESS);
1813 	}
1814 
1815 	if (res->id.idtype == IDMAP_UID) {
1816 		if (get_next_eph_uid(&next_pid) != 0)
1817 			return (IDMAP_ERR_INTERNAL);
1818 		res->id.idmap_id_u.uid = next_pid;
1819 	} else {
1820 		if (get_next_eph_gid(&next_pid) != 0)
1821 			return (IDMAP_ERR_INTERNAL);
1822 		res->id.idmap_id_u.gid = next_pid;
1823 	}
1824 
1825 	if (state->sid_history != NULL)
1826 		add_to_sid_history(state, req->id1.idmap_id_u.sid.prefix,
1827 		    req->id1.idmap_id_u.sid.rid);
1828 
1829 	return (IDMAP_SUCCESS);
1830 }
1831 
1832 idmap_retcode
1833 sid2pid_second_pass(lookup_state_t *state, sqlite *cache, sqlite *db,
1834 		idmap_mapping *req, idmap_id_res *res) {
1835 	idmap_retcode	retcode;
1836 
1837 	/*
1838 	 * The req->direction field is used to maintain state of the
1839 	 * sid2pid request.
1840 	 */
1841 
1842 	/* Check if second pass is needed */
1843 	if (req->direction == _IDMAP_F_DONE)
1844 		return (res->retcode);
1845 
1846 	/* Get status from previous pass */
1847 	retcode = (res->retcode == IDMAP_NEXT)?IDMAP_SUCCESS:res->retcode;
1848 
1849 	if (retcode != IDMAP_SUCCESS) {
1850 		/* Reset return type */
1851 		res->id.idtype = req->id2.idtype;
1852 		res->id.idmap_id_u.uid = UID_NOBODY;
1853 
1854 		/* Check if this is a localsid */
1855 		if (retcode == IDMAP_ERR_NOTFOUND &&
1856 		    _idmapdstate.cfg->pgcfg.machine_sid) {
1857 			retcode = lookup_localsid2pid(req, res);
1858 			if (retcode == IDMAP_SUCCESS) {
1859 				state->sid2pid_done = FALSE;
1860 				req->direction = _IDMAP_F_S2N_CACHE;
1861 			}
1862 		}
1863 		goto out;
1864 	}
1865 
1866 	/*
1867 	 * Verify that the sid type matches the request if the
1868 	 * SID was validated by an AD lookup.
1869 	 */
1870 	if (req->direction & _IDMAP_F_S2N_AD) {
1871 		retcode = verify_type(req->id2.idtype,
1872 			(int)res->id.idtype, res);
1873 		if (retcode != IDMAP_SUCCESS) {
1874 			res->id.idtype = req->id2.idtype;
1875 			res->id.idmap_id_u.uid = UID_NOBODY;
1876 			goto out;
1877 		}
1878 	}
1879 
1880 	/* Name-based mapping */
1881 	retcode = name_based_mapping_sid2pid(db, req, res);
1882 	if (retcode == IDMAP_ERR_NOTFOUND)
1883 		/* If not found, do ephemeral mapping */
1884 		goto ephemeral;
1885 	else if (retcode != IDMAP_SUCCESS)
1886 		goto out;
1887 
1888 	state->sid2pid_done = FALSE;
1889 	goto out;
1890 
1891 
1892 ephemeral:
1893 	retcode = dynamic_ephemeral_mapping(state, cache, req, res);
1894 	if (retcode == IDMAP_SUCCESS)
1895 		state->sid2pid_done = FALSE;
1896 
1897 out:
1898 	res->retcode = idmap_stat4prot(retcode);
1899 	return (retcode);
1900 }
1901 
1902 idmap_retcode
1903 update_cache_pid2sid(lookup_state_t *state, sqlite *cache,
1904 		idmap_mapping *req, idmap_id_res *res) {
1905 	char		*sql = NULL;
1906 	idmap_retcode	retcode;
1907 
1908 	/* Check if we need to cache anything */
1909 	if (req->direction == _IDMAP_F_DONE)
1910 		return (IDMAP_SUCCESS);
1911 
1912 	/* We don't cache negative entries */
1913 	if (res->retcode != IDMAP_SUCCESS)
1914 		return (IDMAP_SUCCESS);
1915 
1916 	/*
1917 	 * Using NULL for u2w instead of 0 so that our trigger allows
1918 	 * the same pid to be the destination in multiple entries
1919 	 */
1920 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
1921 		"(sidprefix, rid, windomain, winname, pid, unixname, "
1922 		"is_user, expiration, w2u, u2w) "
1923 		"VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, "
1924 		"strftime('%%s','now') + 600, %q, 1); ",
1925 		res->id.idmap_id_u.sid.prefix,
1926 		res->id.idmap_id_u.sid.rid,
1927 		req->id2domain.idmap_utf8str_val,
1928 		req->id2name.idmap_utf8str_val,
1929 		req->id1.idmap_id_u.uid,
1930 		req->id1name.idmap_utf8str_val,
1931 		(req->id1.idtype == IDMAP_UID)?1:0,
1932 		(res->direction == 0)?"1":NULL);
1933 
1934 	if (sql == NULL) {
1935 		retcode = IDMAP_ERR_INTERNAL;
1936 		idmapdlog(LOG_ERR, "Out of memory");
1937 		goto out;
1938 	}
1939 
1940 	retcode = sql_exec_no_cb(cache, sql);
1941 	if (retcode != IDMAP_SUCCESS)
1942 		goto out;
1943 
1944 	state->pid2sid_done = FALSE;
1945 	sqlite_freemem(sql);
1946 	sql = NULL;
1947 
1948 	/* If sid2name was found in the cache, no need to update namecache */
1949 	if (req->direction & _IDMAP_F_S2N_CACHE)
1950 		goto out;
1951 
1952 	if (req->id2name.idmap_utf8str_val == NULL)
1953 		goto out;
1954 
1955 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
1956 		"(sidprefix, rid, name, domain, type, expiration) "
1957 		"VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
1958 		res->id.idmap_id_u.sid.prefix,
1959 		res->id.idmap_id_u.sid.rid,
1960 		req->id2name.idmap_utf8str_val,
1961 		req->id2domain.idmap_utf8str_val,
1962 		(req->id1.idtype == IDMAP_UID)?_IDMAP_T_USER:_IDMAP_T_GROUP);
1963 
1964 	if (sql == NULL) {
1965 		retcode = IDMAP_ERR_INTERNAL;
1966 		idmapdlog(LOG_ERR, "Out of memory");
1967 		goto out;
1968 	}
1969 
1970 	retcode = sql_exec_no_cb(cache, sql);
1971 
1972 out:
1973 	if (sql != NULL)
1974 		sqlite_freemem(sql);
1975 	return (retcode);
1976 }
1977 
1978 idmap_retcode
1979 update_cache_sid2pid(lookup_state_t *state, sqlite *cache,
1980 		idmap_mapping *req, idmap_id_res *res) {
1981 	char		*sql = NULL;
1982 	idmap_retcode	retcode;
1983 	int		is_eph_user;
1984 
1985 	/* Check if we need to cache anything */
1986 	if (req->direction == _IDMAP_F_DONE)
1987 		return (IDMAP_SUCCESS);
1988 
1989 	/* We don't cache negative entries */
1990 	if (res->retcode != IDMAP_SUCCESS)
1991 		return (IDMAP_SUCCESS);
1992 
1993 	if (req->direction & _IDMAP_F_EXP_EPH_UID)
1994 		is_eph_user = 1;
1995 	else if (req->direction & _IDMAP_F_EXP_EPH_GID)
1996 		is_eph_user = 0;
1997 	else
1998 		is_eph_user = -1;
1999 
2000 	if (is_eph_user >= 0 && !IS_EPHEMERAL(res->id.idmap_id_u.uid)) {
2001 		sql = sqlite_mprintf("UPDATE idmap_cache "
2002 			"SET w2u = 0 WHERE "
2003 			"sidprefix = %Q AND rid = %u AND w2u = 1 AND "
2004 			"pid >= 2147483648 AND is_user = %d;",
2005 			req->id1.idmap_id_u.sid.prefix,
2006 			req->id1.idmap_id_u.sid.rid,
2007 			is_eph_user);
2008 		if (sql == NULL) {
2009 			retcode = IDMAP_ERR_INTERNAL;
2010 			idmapdlog(LOG_ERR, "Out of memory");
2011 			goto out;
2012 		}
2013 
2014 		retcode = sql_exec_no_cb(cache, sql);
2015 		if (retcode != IDMAP_SUCCESS)
2016 			goto out;
2017 
2018 		sqlite_freemem(sql);
2019 		sql = NULL;
2020 	}
2021 
2022 	sql = sqlite_mprintf("INSERT OR REPLACE into idmap_cache "
2023 		"(sidprefix, rid, windomain, winname, pid, unixname, "
2024 		"is_user, expiration, w2u, u2w) "
2025 		"VALUES(%Q, %u, %Q, %Q, %u, %Q, %d, "
2026 		"strftime('%%s','now') + 600, 1, %q); ",
2027 		req->id1.idmap_id_u.sid.prefix,
2028 		req->id1.idmap_id_u.sid.rid,
2029 		req->id1domain.idmap_utf8str_val,
2030 		req->id1name.idmap_utf8str_val,
2031 		res->id.idmap_id_u.uid,
2032 		req->id2name.idmap_utf8str_val,
2033 		(res->id.idtype == IDMAP_UID)?1:0,
2034 		(res->direction == 0)?"1":NULL);
2035 
2036 	if (sql == NULL) {
2037 		retcode = IDMAP_ERR_INTERNAL;
2038 		idmapdlog(LOG_ERR, "Out of memory");
2039 		goto out;
2040 	}
2041 
2042 	retcode = sql_exec_no_cb(cache, sql);
2043 	if (retcode != IDMAP_SUCCESS)
2044 		goto out;
2045 
2046 	state->sid2pid_done = FALSE;
2047 	sqlite_freemem(sql);
2048 	sql = NULL;
2049 
2050 	/* If name2sid was found in the cache, no need to update namecache */
2051 	if (req->direction & _IDMAP_F_S2N_CACHE)
2052 		goto out;
2053 
2054 	if (req->id1name.idmap_utf8str_val == NULL)
2055 		goto out;
2056 
2057 	sql = sqlite_mprintf("INSERT OR REPLACE into name_cache "
2058 		"(sidprefix, rid, name, domain, type, expiration) "
2059 		"VALUES(%Q, %u, %Q, %Q, %d, strftime('%%s','now') + 3600); ",
2060 		req->id1.idmap_id_u.sid.prefix,
2061 		req->id1.idmap_id_u.sid.rid,
2062 		req->id1name.idmap_utf8str_val,
2063 		req->id1domain.idmap_utf8str_val,
2064 		(res->id.idtype == IDMAP_UID)?_IDMAP_T_USER:_IDMAP_T_GROUP);
2065 
2066 	if (sql == NULL) {
2067 		retcode = IDMAP_ERR_INTERNAL;
2068 		idmapdlog(LOG_ERR, "Out of memory");
2069 		goto out;
2070 	}
2071 
2072 	retcode = sql_exec_no_cb(cache, sql);
2073 
2074 out:
2075 	if (sql != NULL)
2076 		sqlite_freemem(sql);
2077 	return (retcode);
2078 }
2079 
2080 static idmap_retcode
2081 lookup_cache_pid2sid(sqlite *cache, idmap_mapping *req, idmap_id_res *res,
2082 		int is_user, int getname) {
2083 	char		*end;
2084 	char		*sql = NULL;
2085 	const char	**values;
2086 	sqlite_vm	*vm = NULL;
2087 	int		ncol;
2088 	idmap_retcode	retcode = IDMAP_SUCCESS;
2089 	idmap_utf8str	*str;
2090 	time_t		curtime;
2091 
2092 	/* Current time */
2093 	errno = 0;
2094 	if ((curtime = time(NULL)) == (time_t)-1) {
2095 		idmapdlog(LOG_ERR,
2096 			"Failed to get current time (%s)",
2097 			strerror(errno));
2098 		retcode = IDMAP_ERR_INTERNAL;
2099 		goto out;
2100 	}
2101 
2102 	/* SQL to lookup the cache */
2103 	sql = sqlite_mprintf("SELECT sidprefix, rid, winname, windomain, w2u "
2104 			"FROM idmap_cache WHERE "
2105 			"pid = %u AND u2w = 1 AND is_user = %d AND "
2106 			"(pid >= 2147483648 OR "
2107 			"(expiration = 0 OR expiration ISNULL OR "
2108 			"expiration > %d));",
2109 			req->id1.idmap_id_u.uid, is_user, curtime);
2110 	if (sql == NULL) {
2111 		idmapdlog(LOG_ERR, "Out of memory");
2112 		retcode = IDMAP_ERR_MEMORY;
2113 		goto out;
2114 	}
2115 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 5, &values);
2116 	sqlite_freemem(sql);
2117 
2118 	if (retcode == IDMAP_ERR_NOTFOUND)
2119 		goto out;
2120 	else if (retcode == IDMAP_SUCCESS) {
2121 		/* sanity checks */
2122 		if (values[0] == NULL || values[1] == NULL) {
2123 			retcode = IDMAP_ERR_CACHE;
2124 			goto out;
2125 		}
2126 
2127 		switch (req->id2.idtype) {
2128 		case IDMAP_SID:
2129 			res->id.idmap_id_u.sid.rid =
2130 				strtoul(values[1], &end, 10);
2131 			res->id.idmap_id_u.sid.prefix = strdup(values[0]);
2132 			if (res->id.idmap_id_u.sid.prefix == NULL) {
2133 				idmapdlog(LOG_ERR, "Out of memory");
2134 				retcode = IDMAP_ERR_MEMORY;
2135 				goto out;
2136 			}
2137 
2138 			if (values[4] != NULL)
2139 				res->direction =
2140 				    (strtol(values[4], &end, 10) == 0)?
2141 				    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
2142 			else
2143 				res->direction = IDMAP_DIRECTION_U2W;
2144 
2145 			if (getname == 0 || values[2] == NULL)
2146 				break;
2147 			str = &req->id2name;
2148 			retcode = idmap_str2utf8(&str, values[2], 0);
2149 			if (retcode != IDMAP_SUCCESS) {
2150 				idmapdlog(LOG_ERR, "Out of memory");
2151 				retcode = IDMAP_ERR_MEMORY;
2152 				goto out;
2153 			}
2154 
2155 			if (values[3] == NULL)
2156 				break;
2157 			str = &req->id2domain;
2158 			retcode = idmap_str2utf8(&str, values[3], 0);
2159 			if (retcode != IDMAP_SUCCESS) {
2160 				idmapdlog(LOG_ERR, "Out of memory");
2161 				retcode = IDMAP_ERR_MEMORY;
2162 				goto out;
2163 			}
2164 			break;
2165 		default:
2166 			retcode = IDMAP_ERR_NOTSUPPORTED;
2167 			break;
2168 		}
2169 	}
2170 
2171 out:
2172 	if (vm != NULL)
2173 		(void) sqlite_finalize(vm, NULL);
2174 	return (retcode);
2175 }
2176 
2177 static idmap_retcode
2178 lookup_cache_name2sid(sqlite *cache, const char *name, const char *domain,
2179 		char **sidprefix, idmap_rid_t *rid, int *type) {
2180 	char		*end;
2181 	char		*sql = NULL;
2182 	const char	**values;
2183 	sqlite_vm	*vm = NULL;
2184 	int		ncol;
2185 	time_t		curtime;
2186 	idmap_retcode	retcode = IDMAP_SUCCESS;
2187 
2188 	/* Get current time */
2189 	errno = 0;
2190 	if ((curtime = time(NULL)) == (time_t)-1) {
2191 		idmapdlog(LOG_ERR,
2192 			"Failed to get current time (%s)",
2193 			strerror(errno));
2194 		retcode = IDMAP_ERR_INTERNAL;
2195 		goto out;
2196 	}
2197 
2198 	/* SQL to lookup the cache */
2199 	sql = sqlite_mprintf("SELECT sidprefix, rid, type FROM name_cache "
2200 			"WHERE name = %Q AND domain = %Q AND "
2201 			"(expiration = 0 OR expiration ISNULL OR "
2202 			"expiration > %d);",
2203 			name, domain, curtime);
2204 	if (sql == NULL) {
2205 		idmapdlog(LOG_ERR, "Out of memory");
2206 		retcode = IDMAP_ERR_MEMORY;
2207 		goto out;
2208 	}
2209 	retcode = sql_compile_n_step_once(cache, sql, &vm, &ncol, 3, &values);
2210 	sqlite_freemem(sql);
2211 
2212 	if (retcode == IDMAP_SUCCESS) {
2213 		if (type != NULL) {
2214 			if (values[2] == NULL) {
2215 				retcode = IDMAP_ERR_CACHE;
2216 				goto out;
2217 			}
2218 			*type = strtol(values[2], &end, 10);
2219 		}
2220 
2221 		if (values[0] == NULL || values[1] == NULL) {
2222 			retcode = IDMAP_ERR_CACHE;
2223 			goto out;
2224 		}
2225 		if ((*sidprefix = strdup(values[0])) == NULL) {
2226 			idmapdlog(LOG_ERR, "Out of memory");
2227 			retcode = IDMAP_ERR_MEMORY;
2228 			goto out;
2229 		}
2230 		*rid = strtoul(values[1], &end, 10);
2231 	}
2232 
2233 out:
2234 	if (vm != NULL)
2235 		(void) sqlite_finalize(vm, NULL);
2236 	return (retcode);
2237 }
2238 
2239 static idmap_retcode
2240 lookup_win_name2sid(const char *name, const char *domain, char **sidprefix,
2241 		idmap_rid_t *rid, int *type) {
2242 	int			ret;
2243 	int			retries = 0;
2244 	idmap_query_state_t	*qs = NULL;
2245 	idmap_retcode		rc, retcode;
2246 
2247 	retcode = IDMAP_ERR_NOTFOUND;
2248 
2249 retry:
2250 	ret = idmap_lookup_batch_start(_idmapdstate.ad, 1, &qs);
2251 	if (ret != 0) {
2252 		idmapdlog(LOG_ERR,
2253 		"Failed to create name2sid batch for AD lookup");
2254 		return (IDMAP_ERR_INTERNAL);
2255 	}
2256 
2257 	retcode = idmap_name2sid_batch_add1(qs, name, domain, sidprefix,
2258 					rid, type, &rc);
2259 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
2260 		goto out;
2261 
2262 	if (retcode != IDMAP_SUCCESS) {
2263 		idmapdlog(LOG_ERR,
2264 		"Failed to batch name2sid for AD lookup");
2265 		idmap_lookup_free_batch(&qs);
2266 		return (IDMAP_ERR_INTERNAL);
2267 	}
2268 
2269 out:
2270 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR)
2271 		idmap_lookup_free_batch(&qs);
2272 	else
2273 		retcode = idmap_lookup_batch_end(&qs, NULL);
2274 
2275 	if (retcode == IDMAP_ERR_RETRIABLE_NET_ERR && retries++ < 2)
2276 		goto retry;
2277 
2278 	if (retcode != IDMAP_SUCCESS) {
2279 		idmapdlog(LOG_NOTICE, "Windows user/group name to SID lookup "
2280 		    "failed");
2281 		return (retcode);
2282 	} else
2283 		return (rc);
2284 	/* NOTREACHED */
2285 }
2286 
2287 static idmap_retcode
2288 lookup_name2sid(sqlite *cache, const char *name, const char *domain,
2289 		int *is_user, char **sidprefix, idmap_rid_t *rid,
2290 		idmap_mapping *req) {
2291 	int		type;
2292 	idmap_retcode	retcode;
2293 
2294 	/* Lookup name@domain to sid in the well-known sids table */
2295 	retcode = lookup_wksids_name2sid(name, sidprefix, rid, &type);
2296 	if (retcode == IDMAP_SUCCESS) {
2297 		req->direction |= _IDMAP_F_S2N_CACHE;
2298 		goto out;
2299 	} else if (retcode != IDMAP_ERR_NOTFOUND) {
2300 		return (retcode);
2301 	}
2302 
2303 	/* Lookup name@domain to sid in cache */
2304 	retcode = lookup_cache_name2sid(cache, name, domain, sidprefix,
2305 		rid, &type);
2306 	if (retcode == IDMAP_ERR_NOTFOUND) {
2307 		/* Lookup Windows NT/AD to map name@domain to sid */
2308 		retcode = lookup_win_name2sid(name, domain, sidprefix, rid,
2309 			&type);
2310 		if (retcode != IDMAP_SUCCESS)
2311 			return (retcode);
2312 		req->direction |= _IDMAP_F_S2N_AD;
2313 	} else if (retcode != IDMAP_SUCCESS) {
2314 		return (retcode);
2315 	} else {
2316 		/* Set flag */
2317 		req->direction |= _IDMAP_F_S2N_CACHE;
2318 	}
2319 
2320 out:
2321 	/*
2322 	 * Entry found (cache or Windows lookup)
2323 	 * is_user is both input as well as output parameter
2324 	 */
2325 	if (*is_user == 1) {
2326 		if (type != _IDMAP_T_USER)
2327 			return (IDMAP_ERR_NOTUSER);
2328 	} else if (*is_user == 0) {
2329 		if (type != _IDMAP_T_GROUP)
2330 			return (IDMAP_ERR_NOTGROUP);
2331 	} else if (*is_user == -1) {
2332 		/* Caller wants to know if its user or group */
2333 		if (type == _IDMAP_T_USER)
2334 			*is_user = 1;
2335 		else if (type == _IDMAP_T_GROUP)
2336 			*is_user = 0;
2337 		else
2338 			return (IDMAP_ERR_SID);
2339 	}
2340 
2341 	return (retcode);
2342 }
2343 
2344 static idmap_retcode
2345 name_based_mapping_pid2sid(sqlite *db, sqlite *cache, const char *unixname,
2346 		int is_user, idmap_mapping *req, idmap_id_res *res) {
2347 	const char	*winname, *windomain;
2348 	char		*mapping_domain = NULL;
2349 	char		*sql = NULL, *errmsg = NULL;
2350 	idmap_retcode	retcode;
2351 	char		*end;
2352 	const char	**values;
2353 	sqlite_vm	*vm = NULL;
2354 	idmap_utf8str	*str;
2355 	struct timespec	rqtp;
2356 	int		ncol, r, i, s;
2357 	const char	*me = "name_based_mapping_pid2sid";
2358 
2359 	RDLOCK_CONFIG();
2360 	if (_idmapdstate.cfg->pgcfg.mapping_domain != NULL) {
2361 		mapping_domain =
2362 			strdup(_idmapdstate.cfg->pgcfg.mapping_domain);
2363 		if (mapping_domain == NULL) {
2364 			UNLOCK_CONFIG();
2365 			idmapdlog(LOG_ERR, "Out of memory");
2366 			retcode = IDMAP_ERR_MEMORY;
2367 			goto out;
2368 		}
2369 	}
2370 	UNLOCK_CONFIG();
2371 
2372 	sql = sqlite_mprintf(
2373 		"SELECT winname, windomain, w2u_order FROM namerules WHERE "
2374 		"u2w_order > 0 AND is_user = %d AND "
2375 		"(unixname = %Q OR unixname = '*') "
2376 		"ORDER BY u2w_order ASC;",
2377 		is_user, unixname);
2378 	if (sql == NULL) {
2379 		idmapdlog(LOG_ERR, "Out of memory");
2380 		retcode = IDMAP_ERR_MEMORY;
2381 		goto out;
2382 	}
2383 
2384 	if (sqlite_compile(db, sql, NULL, &vm, &errmsg) != SQLITE_OK) {
2385 		retcode = IDMAP_ERR_INTERNAL;
2386 		idmapdlog(LOG_ERR,
2387 			"%s: database error (%s)",
2388 			me, CHECK_NULL(errmsg));
2389 		sqlite_freemem(errmsg);
2390 		goto out;
2391 	}
2392 
2393 	for (i = 0, s = SLEEP_TIME; ; ) {
2394 		r = sqlite_step(vm, &ncol, &values, NULL);
2395 		if (r == SQLITE_BUSY) {
2396 			if (++i < MAX_TRIES) {
2397 				NANO_SLEEP(rqtp, s);
2398 				s *= 2;
2399 				continue;
2400 			}
2401 			retcode = IDMAP_ERR_BUSY;
2402 			goto out;
2403 		} else if (r == SQLITE_ROW) {
2404 			if (ncol < 3) {
2405 				retcode = IDMAP_ERR_INTERNAL;
2406 				goto out;
2407 			}
2408 			if (values[0] == NULL) {
2409 				/* values [1] and [2] can be null */
2410 				retcode = IDMAP_ERR_INTERNAL;
2411 				goto out;
2412 			}
2413 			if (EMPTY_NAME(values[0])) {
2414 				retcode = IDMAP_ERR_NOMAPPING;
2415 				goto out;
2416 			}
2417 			winname = (values[0][0] == '*')?unixname:values[0];
2418 			if (values[1] != NULL)
2419 				windomain = values[1];
2420 			else if (mapping_domain != NULL)
2421 				windomain = mapping_domain;
2422 			else {
2423 				idmapdlog(LOG_ERR,
2424 					"%s: no domain", me);
2425 				retcode = IDMAP_ERR_DOMAIN_NOTFOUND;
2426 				goto out;
2427 			}
2428 			/* Lookup winname@domain to sid */
2429 			retcode = lookup_name2sid(cache, winname, windomain,
2430 				&is_user, &res->id.idmap_id_u.sid.prefix,
2431 				&res->id.idmap_id_u.sid.rid, req);
2432 			if (retcode == IDMAP_ERR_NOTFOUND) {
2433 				if (winname == unixname)
2434 					continue;
2435 				else
2436 					retcode = IDMAP_ERR_NOMAPPING;
2437 			}
2438 			goto out;
2439 		} else if (r == SQLITE_DONE) {
2440 			retcode = IDMAP_ERR_NOTFOUND;
2441 			goto out;
2442 		} else {
2443 			(void) sqlite_finalize(vm, &errmsg);
2444 			vm = NULL;
2445 			idmapdlog(LOG_ERR,
2446 				"%s: database error (%s)",
2447 				me, CHECK_NULL(errmsg));
2448 			sqlite_freemem(errmsg);
2449 			retcode = IDMAP_ERR_INTERNAL;
2450 			goto out;
2451 		}
2452 	}
2453 
2454 out:
2455 	if (sql != NULL)
2456 		sqlite_freemem(sql);
2457 	if (retcode == IDMAP_SUCCESS) {
2458 		if (values[2] != NULL)
2459 			res->direction =
2460 			    (strtol(values[2], &end, 10) == 0)?
2461 			    IDMAP_DIRECTION_U2W:IDMAP_DIRECTION_BI;
2462 		else
2463 			res->direction = IDMAP_DIRECTION_U2W;
2464 		str = &req->id2name;
2465 		retcode = idmap_str2utf8(&str, winname, 0);
2466 		if (retcode == IDMAP_SUCCESS) {
2467 			str = &req->id2domain;
2468 			if (windomain == mapping_domain) {
2469 				(void) idmap_str2utf8(&str, windomain, 1);
2470 				mapping_domain = NULL;
2471 			} else
2472 				retcode = idmap_str2utf8(&str, windomain, 0);
2473 		}
2474 	}
2475 	if (vm != NULL)
2476 		(void) sqlite_finalize(vm, NULL);
2477 	if (mapping_domain != NULL)
2478 		free(mapping_domain);
2479 	return (retcode);
2480 }
2481 
2482 idmap_retcode
2483 pid2sid_first_pass(lookup_state_t *state, sqlite *cache, sqlite *db,
2484 		idmap_mapping *req, idmap_id_res *res, int is_user,
2485 		int getname) {
2486 	char		*unixname = NULL;
2487 	struct passwd	pwd;
2488 	struct group	grp;
2489 	idmap_utf8str	*str;
2490 	char		buf[1024];
2491 	int		errnum;
2492 	idmap_retcode	retcode = IDMAP_SUCCESS;
2493 	const char	*me = "pid2sid";
2494 
2495 	req->direction = _IDMAP_F_DONE;
2496 	res->id.idtype = req->id2.idtype;
2497 
2498 	/* Lookup well-known SIDs */
2499 	retcode = lookup_wksids_pid2sid(req, res, is_user);
2500 	if (retcode != IDMAP_ERR_NOTFOUND)
2501 		goto out;
2502 
2503 	/* Lookup pid to sid in cache */
2504 	retcode = lookup_cache_pid2sid(cache, req, res, is_user, getname);
2505 	if (retcode != IDMAP_ERR_NOTFOUND)
2506 		goto out;
2507 
2508 	/* Ephemeral ids cannot be allocated during pid2sid */
2509 	if (IS_EPHEMERAL(req->id1.idmap_id_u.uid)) {
2510 		retcode = IDMAP_ERR_NOMAPPING;
2511 		goto out;
2512 	}
2513 
2514 	if (DO_NOT_ALLOC_NEW_ID_MAPPING(req) || AVOID_NAMESERVICE(req)) {
2515 		retcode = IDMAP_ERR_NOMAPPING;
2516 		goto out;
2517 	}
2518 
2519 	/* uid/gid to name */
2520 	if (req->id1name.idmap_utf8str_val != NULL) {
2521 		unixname = req->id1name.idmap_utf8str_val;
2522 	} if (is_user) {
2523 		errno = 0;
2524 		if (getpwuid_r(req->id1.idmap_id_u.uid, &pwd, buf,
2525 				sizeof (buf)) == NULL) {
2526 			errnum = errno;
2527 			idmapdlog(LOG_WARNING,
2528 			"%s: getpwuid_r(%u) failed (%s).",
2529 				me, req->id1.idmap_id_u.uid,
2530 				errnum?strerror(errnum):"not found");
2531 			retcode = (errnum == 0)?IDMAP_ERR_NOTFOUND:
2532 					IDMAP_ERR_INTERNAL;
2533 			goto fallback_localsid;
2534 		}
2535 		unixname = pwd.pw_name;
2536 	} else {
2537 		errno = 0;
2538 		if (getgrgid_r(req->id1.idmap_id_u.gid, &grp, buf,
2539 				sizeof (buf)) == NULL) {
2540 			errnum = errno;
2541 			idmapdlog(LOG_WARNING,
2542 			"%s: getgrgid_r(%u) failed (%s).",
2543 				me, req->id1.idmap_id_u.gid,
2544 				errnum?strerror(errnum):"not found");
2545 			retcode = (errnum == 0)?IDMAP_ERR_NOTFOUND:
2546 					IDMAP_ERR_INTERNAL;
2547 			goto fallback_localsid;
2548 		}
2549 		unixname = grp.gr_name;
2550 	}
2551 
2552 	/* Name-based mapping */
2553 	retcode = name_based_mapping_pid2sid(db, cache, unixname, is_user,
2554 		req, res);
2555 	if (retcode == IDMAP_ERR_NOTFOUND) {
2556 		retcode = generate_localsid(req, res, is_user);
2557 		goto out;
2558 	} else if (retcode == IDMAP_SUCCESS)
2559 		goto out;
2560 
2561 fallback_localsid:
2562 	/*
2563 	 * Here we generate localsid as fallback id on errors. Our
2564 	 * return status is the error that's been previously assigned.
2565 	 */
2566 	(void) generate_localsid(req, res, is_user);
2567 
2568 out:
2569 	if (retcode == IDMAP_SUCCESS) {
2570 		if (req->id1name.idmap_utf8str_val == NULL &&
2571 		    unixname != NULL) {
2572 			str = &req->id1name;
2573 			retcode = idmap_str2utf8(&str, unixname, 0);
2574 		}
2575 	}
2576 	if (req->direction != _IDMAP_F_DONE)
2577 		state->pid2sid_done = FALSE;
2578 	res->retcode = idmap_stat4prot(retcode);
2579 	return (retcode);
2580 }
2581 
2582 static idmap_retcode
2583 lookup_win_sid2name(const char *sidprefix, idmap_rid_t rid, char **name,
2584 		char **domain, int *type) {
2585 	int			ret;
2586 	idmap_query_state_t	*qs = NULL;
2587 	idmap_retcode		rc, retcode;
2588 
2589 	retcode = IDMAP_ERR_NOTFOUND;
2590 
2591 	ret = idmap_lookup_batch_start(_idmapdstate.ad, 1, &qs);
2592 	if (ret != 0) {
2593 		idmapdlog(LOG_ERR,
2594 		"Failed to create sid2name batch for AD lookup");
2595 		retcode = IDMAP_ERR_INTERNAL;
2596 		goto out;
2597 	}
2598 
2599 	ret = idmap_sid2name_batch_add1(
2600 			qs, sidprefix, &rid, name, domain, type, &rc);
2601 	if (ret != 0) {
2602 		idmapdlog(LOG_ERR,
2603 		"Failed to batch sid2name for AD lookup");
2604 		retcode = IDMAP_ERR_INTERNAL;
2605 		goto out;
2606 	}
2607 
2608 out:
2609 	if (qs != NULL) {
2610 		ret = idmap_lookup_batch_end(&qs, NULL);
2611 		if (ret != 0) {
2612 			idmapdlog(LOG_ERR,
2613 			"Failed to execute sid2name AD lookup");
2614 			retcode = IDMAP_ERR_INTERNAL;
2615 		} else
2616 			retcode = rc;
2617 	}
2618 
2619 	return (retcode);
2620 }
2621 
2622 static int
2623 copy_mapping_request(idmap_mapping *mapping, idmap_mapping *request)
2624 {
2625 	(void) memset(mapping, 0, sizeof (*mapping));
2626 
2627 	mapping->flag = request->flag;
2628 	mapping->direction = request->direction;
2629 	mapping->id2.idtype = request->id2.idtype;
2630 
2631 	mapping->id1.idtype = request->id1.idtype;
2632 	if (request->id1.idtype == IDMAP_SID) {
2633 		mapping->id1.idmap_id_u.sid.rid =
2634 		    request->id1.idmap_id_u.sid.rid;
2635 		if (!EMPTY_STRING(request->id1.idmap_id_u.sid.prefix)) {
2636 			mapping->id1.idmap_id_u.sid.prefix =
2637 			    strdup(request->id1.idmap_id_u.sid.prefix);
2638 			if (mapping->id1.idmap_id_u.sid.prefix == NULL)
2639 				return (-1);
2640 		}
2641 	} else {
2642 		mapping->id1.idmap_id_u.uid = request->id1.idmap_id_u.uid;
2643 	}
2644 
2645 	mapping->id1domain.idmap_utf8str_len =
2646 	    request->id1domain.idmap_utf8str_len;
2647 	if (mapping->id1domain.idmap_utf8str_len) {
2648 		mapping->id1domain.idmap_utf8str_val =
2649 		    strdup(request->id1domain.idmap_utf8str_val);
2650 		if (mapping->id1domain.idmap_utf8str_val == NULL)
2651 			return (-1);
2652 	}
2653 
2654 	mapping->id1name.idmap_utf8str_len  =
2655 	    request->id1name.idmap_utf8str_len;
2656 	if (mapping->id1name.idmap_utf8str_len) {
2657 		mapping->id1name.idmap_utf8str_val =
2658 		    strdup(request->id1name.idmap_utf8str_val);
2659 		if (mapping->id1name.idmap_utf8str_val == NULL)
2660 			return (-1);
2661 	}
2662 
2663 	/* We don't need the rest of the request i.e request->id2 */
2664 	return (0);
2665 
2666 errout:
2667 	if (mapping->id1.idmap_id_u.sid.prefix != NULL) {
2668 		free(mapping->id1.idmap_id_u.sid.prefix);
2669 		mapping->id1.idmap_id_u.sid.prefix = NULL;
2670 	}
2671 
2672 	if (mapping->id1domain.idmap_utf8str_val != NULL) {
2673 		free(mapping->id1domain.idmap_utf8str_val);
2674 		mapping->id1domain.idmap_utf8str_val = NULL;
2675 		mapping->id1domain.idmap_utf8str_len = 0;
2676 	}
2677 
2678 	if (mapping->id1name.idmap_utf8str_val != NULL) {
2679 		free(mapping->id1name.idmap_utf8str_val);
2680 		mapping->id1name.idmap_utf8str_val = NULL;
2681 		mapping->id1name.idmap_utf8str_len = 0;
2682 	}
2683 
2684 	(void) memset(mapping, 0, sizeof (*mapping));
2685 	return (-1);
2686 }
2687 
2688 
2689 idmap_retcode
2690 get_w2u_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
2691 		idmap_mapping *mapping) {
2692 	idmap_id_res	idres;
2693 	lookup_state_t	state;
2694 	idmap_utf8str	*str;
2695 	int		is_user;
2696 	idmap_retcode	retcode;
2697 	const char	*winname, *windomain;
2698 
2699 	(void) memset(&idres, 0, sizeof (idres));
2700 	(void) memset(&state, 0, sizeof (state));
2701 
2702 	if (request->id2.idtype == IDMAP_UID)
2703 		is_user = 1;
2704 	else if (request->id2.idtype == IDMAP_GID)
2705 		is_user = 0;
2706 	else if (request->id2.idtype == IDMAP_POSIXID)
2707 		is_user = -1;
2708 	else {
2709 		retcode = IDMAP_ERR_IDTYPE;
2710 		goto out;
2711 	}
2712 
2713 	/* Copy data from request to result */
2714 	if (copy_mapping_request(mapping, request) < 0) {
2715 		retcode = IDMAP_ERR_MEMORY;
2716 		goto out;
2717 	}
2718 
2719 	winname = mapping->id1name.idmap_utf8str_val;
2720 	windomain = mapping->id1domain.idmap_utf8str_val;
2721 
2722 	if (winname == NULL && windomain != NULL) {
2723 		retcode = IDMAP_ERR_ARG;
2724 		goto out;
2725 	}
2726 
2727 	if (winname != NULL && windomain == NULL) {
2728 		str = &mapping->id1domain;
2729 		RDLOCK_CONFIG();
2730 		if (_idmapdstate.cfg->pgcfg.mapping_domain != NULL) {
2731 			retcode = idmap_str2utf8(&str,
2732 				_idmapdstate.cfg->pgcfg.mapping_domain, 0);
2733 			if (retcode != IDMAP_SUCCESS) {
2734 				UNLOCK_CONFIG();
2735 				idmapdlog(LOG_ERR, "Out of memory");
2736 				retcode = IDMAP_ERR_MEMORY;
2737 				goto out;
2738 			}
2739 		}
2740 		UNLOCK_CONFIG();
2741 		windomain = mapping->id1domain.idmap_utf8str_val;
2742 	}
2743 
2744 	if (winname != NULL && mapping->id1.idmap_id_u.sid.prefix == NULL) {
2745 		retcode = lookup_name2sid(cache, winname, windomain,
2746 			&is_user, &mapping->id1.idmap_id_u.sid.prefix,
2747 			&mapping->id1.idmap_id_u.sid.rid, mapping);
2748 		if (retcode != IDMAP_SUCCESS)
2749 			goto out;
2750 		if (mapping->id2.idtype == IDMAP_POSIXID)
2751 			mapping->id2.idtype = is_user?IDMAP_UID:IDMAP_GID;
2752 	}
2753 
2754 	state.sid2pid_done = TRUE;
2755 	retcode = sid2pid_first_pass(&state, cache, mapping, &idres);
2756 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
2757 		goto out;
2758 
2759 	if (state.ad_nqueries) {
2760 		/* sid2name AD lookup */
2761 		retcode = lookup_win_sid2name(
2762 			mapping->id1.idmap_id_u.sid.prefix,
2763 			mapping->id1.idmap_id_u.sid.rid,
2764 			&mapping->id1name.idmap_utf8str_val,
2765 			&mapping->id1domain.idmap_utf8str_val,
2766 			(int *)&idres.id.idtype);
2767 
2768 		idres.retcode = retcode;
2769 	}
2770 
2771 	state.sid2pid_done = TRUE;
2772 	retcode = sid2pid_second_pass(&state, cache, db, mapping, &idres);
2773 	if (IDMAP_ERROR(retcode) || state.sid2pid_done == TRUE)
2774 		goto out;
2775 
2776 	/* Update cache */
2777 	(void) update_cache_sid2pid(&state, cache, mapping, &idres);
2778 
2779 out:
2780 	if (retcode == IDMAP_SUCCESS) {
2781 		mapping->direction = idres.direction;
2782 		mapping->id2 = idres.id;
2783 		(void) memset(&idres, 0, sizeof (idres));
2784 	} else {
2785 		mapping->id2.idmap_id_u.uid = UID_NOBODY;
2786 	}
2787 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
2788 	return (retcode);
2789 }
2790 
2791 idmap_retcode
2792 get_u2w_mapping(sqlite *cache, sqlite *db, idmap_mapping *request,
2793 		idmap_mapping *mapping, int is_user) {
2794 	idmap_id_res	idres;
2795 	lookup_state_t	state;
2796 	struct passwd	pwd;
2797 	struct group	grp;
2798 	char		buf[1024];
2799 	int		errnum;
2800 	idmap_retcode	retcode;
2801 	const char	*unixname;
2802 	const char	*me = "get_u2w_mapping";
2803 
2804 	/*
2805 	 * In order to re-use the pid2sid code, we convert
2806 	 * our input data into structs that are expected by
2807 	 * pid2sid_first_pass.
2808 	 */
2809 
2810 	(void) memset(&idres, 0, sizeof (idres));
2811 	(void) memset(&state, 0, sizeof (state));
2812 
2813 	/* Copy data from request to result */
2814 	if (copy_mapping_request(mapping, request) < 0) {
2815 		retcode = IDMAP_ERR_MEMORY;
2816 		goto out;
2817 	}
2818 
2819 	unixname = mapping->id1name.idmap_utf8str_val;
2820 
2821 	if (unixname == NULL && mapping->id1.idmap_id_u.uid == SENTINEL_PID) {
2822 		retcode = IDMAP_ERR_ARG;
2823 		goto out;
2824 	}
2825 
2826 	if (unixname != NULL && mapping->id1.idmap_id_u.uid == SENTINEL_PID) {
2827 		/* Get uid/gid by name */
2828 		if (is_user) {
2829 			errno = 0;
2830 			if (getpwnam_r(unixname, &pwd, buf,
2831 					sizeof (buf)) == NULL) {
2832 				errnum = errno;
2833 				idmapdlog(LOG_WARNING,
2834 				"%s: getpwnam_r(%s) failed (%s).",
2835 					me, unixname,
2836 					errnum?strerror(errnum):"not found");
2837 				retcode = (errnum == 0)?IDMAP_ERR_NOTFOUND:
2838 						IDMAP_ERR_INTERNAL;
2839 				goto out;
2840 			}
2841 			mapping->id1.idmap_id_u.uid = pwd.pw_uid;
2842 		} else {
2843 			errno = 0;
2844 			if (getgrnam_r(unixname, &grp, buf,
2845 					sizeof (buf)) == NULL) {
2846 				errnum = errno;
2847 				idmapdlog(LOG_WARNING,
2848 				"%s: getgrnam_r(%s) failed (%s).",
2849 					me, unixname,
2850 					errnum?strerror(errnum):"not found");
2851 				retcode = (errnum == 0)?IDMAP_ERR_NOTFOUND:
2852 						IDMAP_ERR_INTERNAL;
2853 				goto out;
2854 			}
2855 			mapping->id1.idmap_id_u.gid = grp.gr_gid;
2856 		}
2857 	}
2858 
2859 	state.pid2sid_done = TRUE;
2860 	retcode = pid2sid_first_pass(&state, cache, db, mapping, &idres,
2861 			is_user, 1);
2862 	if (IDMAP_ERROR(retcode) || state.pid2sid_done == TRUE)
2863 		goto out;
2864 
2865 	/* Update cache */
2866 	(void) update_cache_pid2sid(&state, cache, mapping, &idres);
2867 
2868 out:
2869 	mapping->direction = idres.direction;
2870 	mapping->id2 = idres.id;
2871 	(void) memset(&idres, 0, sizeof (idres));
2872 	xdr_free(xdr_idmap_id_res, (caddr_t)&idres);
2873 	return (retcode);
2874 }
2875