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