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