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