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