xref: /titanic_52/usr/src/cmd/idmap/idmapd/server.c (revision 074e084f68dd0b08686612bec695a0cfe249da6d)
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  * Service routines
30  */
31 
32 #include "idmapd.h"
33 #include "idmap_priv.h"
34 #include "nldaputils.h"
35 #include <signal.h>
36 #include <thread.h>
37 #include <string.h>
38 #include <strings.h>
39 #include <errno.h>
40 #include <assert.h>
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #include <ucred.h>
44 #include <pwd.h>
45 #include <auth_attr.h>
46 #include <secdb.h>
47 #include <sys/u8_textprep.h>
48 
49 #define	_VALIDATE_LIST_CB_DATA(col, val, siz)\
50 	retcode = validate_list_cb_data(cb_data, argc, argv, col,\
51 			(uchar_t **)val, siz);\
52 	if (retcode == IDMAP_NEXT) {\
53 		result->retcode = IDMAP_NEXT;\
54 		return (0);\
55 	} else if (retcode < 0) {\
56 		result->retcode = retcode;\
57 		return (1);\
58 	}
59 
60 #define	PROCESS_LIST_SVC_SQL(rcode, db, dbname, sql, limit, flag, cb, res, len)\
61 	rcode = process_list_svc_sql(db, dbname, sql, limit, flag, cb, res);\
62 	if (rcode == IDMAP_ERR_BUSY)\
63 		res->retcode = IDMAP_ERR_BUSY;\
64 	else if (rcode == IDMAP_SUCCESS && len == 0)\
65 		res->retcode = IDMAP_ERR_NOTFOUND;
66 
67 
68 #define	STRDUP_OR_FAIL(to, from) \
69 	if ((from) == NULL) \
70 		to = NULL; \
71 	else { \
72 		if ((to = strdup(from)) == NULL) \
73 			return (1); \
74 	}
75 
76 #define	STRDUP_CHECK(to, from) \
77 	if ((from) != NULL) { \
78 		to = strdup(from); \
79 		if (to == NULL) { \
80 			result->retcode = IDMAP_ERR_MEMORY; \
81 			goto out; \
82 		} \
83 	}
84 
85 /* ARGSUSED */
86 bool_t
87 idmap_null_1_svc(void *result, struct svc_req *rqstp)
88 {
89 	return (TRUE);
90 }
91 
92 /*
93  * RPC layer allocates empty strings to replace NULL char *.
94  * This utility function frees these empty strings.
95  */
96 static
97 void
98 sanitize_mapping_request(idmap_mapping *req)
99 {
100 	free(req->id1name);
101 	req->id1name = NULL;
102 	free(req->id1domain);
103 	req->id1domain = NULL;
104 	free(req->id2name);
105 	req->id2name = NULL;
106 	free(req->id2domain);
107 	req->id2domain = NULL;
108 	req->direction = _IDMAP_F_DONE;
109 }
110 
111 static
112 int
113 validate_mapped_id_by_name_req(idmap_mapping *req)
114 {
115 	int e;
116 
117 	if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req))
118 		return (IDMAP_SUCCESS);
119 
120 	if (IS_REQUEST_SID(*req, 1)) {
121 		if (!EMPTY_STRING(req->id1name) &&
122 		    u8_validate(req->id1name, strlen(req->id1name),
123 		    NULL, U8_VALIDATE_ENTIRE, &e) < 0)
124 			return (IDMAP_ERR_BAD_UTF8);
125 		if (!EMPTY_STRING(req->id1domain) &&
126 		    u8_validate(req->id1domain, strlen(req->id1domain),
127 		    NULL, U8_VALIDATE_ENTIRE, &e) < 0)
128 			return (IDMAP_ERR_BAD_UTF8);
129 	}
130 
131 	return (IDMAP_SUCCESS);
132 }
133 
134 static
135 int
136 validate_rule(idmap_namerule *rule)
137 {
138 	int e;
139 
140 	if (!EMPTY_STRING(rule->winname) &&
141 	    u8_validate(rule->winname, strlen(rule->winname),
142 	    NULL, U8_VALIDATE_ENTIRE, &e) < 0)
143 		return (IDMAP_ERR_BAD_UTF8);
144 
145 	if (!EMPTY_STRING(rule->windomain) &&
146 	    u8_validate(rule->windomain, strlen(rule->windomain),
147 	    NULL, U8_VALIDATE_ENTIRE, &e) < 0)
148 		return (IDMAP_ERR_BAD_UTF8);
149 
150 	return (IDMAP_SUCCESS);
151 
152 }
153 
154 static
155 bool_t
156 validate_rules(idmap_update_batch *batch)
157 {
158 	idmap_update_op	*up;
159 	int i;
160 
161 	for (i = 0; i < batch->idmap_update_batch_len; i++) {
162 		up = &(batch->idmap_update_batch_val[i]);
163 		if (validate_rule(&(up->idmap_update_op_u.rule))
164 		    != IDMAP_SUCCESS)
165 			return (IDMAP_ERR_BAD_UTF8);
166 	}
167 
168 	return (IDMAP_SUCCESS);
169 }
170 
171 /* ARGSUSED */
172 bool_t
173 idmap_get_mapped_ids_1_svc(idmap_mapping_batch batch,
174 		idmap_ids_res *result, struct svc_req *rqstp)
175 {
176 	sqlite		*cache = NULL, *db = NULL;
177 	lookup_state_t	state;
178 	idmap_retcode	retcode;
179 	uint_t		i;
180 
181 	/* Init */
182 	(void) memset(result, 0, sizeof (*result));
183 	(void) memset(&state, 0, sizeof (state));
184 
185 	/* Return success if nothing was requested */
186 	if (batch.idmap_mapping_batch_len < 1)
187 		goto out;
188 
189 	/* Get cache handle */
190 	result->retcode = get_cache_handle(&cache);
191 	if (result->retcode != IDMAP_SUCCESS)
192 		goto out;
193 	state.cache = cache;
194 
195 	/* Get db handle */
196 	result->retcode = get_db_handle(&db);
197 	if (result->retcode != IDMAP_SUCCESS)
198 		goto out;
199 	state.db = db;
200 
201 	/* Allocate result array */
202 	result->ids.ids_val = calloc(batch.idmap_mapping_batch_len,
203 	    sizeof (idmap_id_res));
204 	if (result->ids.ids_val == NULL) {
205 		idmapdlog(LOG_ERR, "Out of memory");
206 		result->retcode = IDMAP_ERR_MEMORY;
207 		goto out;
208 	}
209 	result->ids.ids_len = batch.idmap_mapping_batch_len;
210 
211 	/* Allocate hash table to check for duplicate sids */
212 	state.sid_history = calloc(batch.idmap_mapping_batch_len,
213 	    sizeof (*state.sid_history));
214 	if (state.sid_history == NULL) {
215 		idmapdlog(LOG_ERR, "Out of memory");
216 		result->retcode = IDMAP_ERR_MEMORY;
217 		goto out;
218 	}
219 	state.sid_history_size = batch.idmap_mapping_batch_len;
220 	for (i = 0; i < state.sid_history_size; i++) {
221 		state.sid_history[i].key = state.sid_history_size;
222 		state.sid_history[i].next = state.sid_history_size;
223 	}
224 	state.batch = &batch;
225 	state.result = result;
226 
227 	/* Get directory-based name mapping info */
228 	result->retcode = load_cfg_in_state(&state);
229 	if (result->retcode != IDMAP_SUCCESS)
230 		goto out;
231 
232 	/* Init our 'done' flags */
233 	state.sid2pid_done = state.pid2sid_done = TRUE;
234 
235 	/* First stage */
236 	for (i = 0; i < batch.idmap_mapping_batch_len; i++) {
237 		state.curpos = i;
238 		(void) sanitize_mapping_request(
239 		    &batch.idmap_mapping_batch_val[i]);
240 		if (IS_BATCH_SID(batch, i)) {
241 			retcode = sid2pid_first_pass(
242 			    &state,
243 			    &batch.idmap_mapping_batch_val[i],
244 			    &result->ids.ids_val[i]);
245 		} else if (IS_BATCH_UID(batch, i)) {
246 			retcode = pid2sid_first_pass(
247 			    &state,
248 			    &batch.idmap_mapping_batch_val[i],
249 			    &result->ids.ids_val[i], 1, 0);
250 		} else if (IS_BATCH_GID(batch, i)) {
251 			retcode = pid2sid_first_pass(
252 			    &state,
253 			    &batch.idmap_mapping_batch_val[i],
254 			    &result->ids.ids_val[i], 0, 0);
255 		} else {
256 			result->ids.ids_val[i].retcode = IDMAP_ERR_IDTYPE;
257 			continue;
258 		}
259 		if (IDMAP_FATAL_ERROR(retcode)) {
260 			result->retcode = retcode;
261 			goto out;
262 		}
263 	}
264 
265 	/* Check if we are done */
266 	if (state.sid2pid_done == TRUE && state.pid2sid_done == TRUE)
267 		goto out;
268 
269 	/*
270 	 * native LDAP lookups:
271 	 *  pid2sid:
272 	 *	- nldap or mixed mode. Lookup nldap by pid or unixname to get
273 	 *	  winname.
274 	 *  sid2pid:
275 	 *	- nldap mode. Got winname and sid (either given or found in
276 	 *	  name_cache). Lookup nldap by winname to get pid and
277 	 *	  unixname.
278 	 */
279 	if (state.nldap_nqueries) {
280 		retcode = nldap_lookup_batch(&state, &batch, result);
281 		if (IDMAP_FATAL_ERROR(retcode)) {
282 			result->retcode = retcode;
283 			goto out;
284 		}
285 	}
286 
287 	/*
288 	 * AD lookups:
289 	 *  pid2sid:
290 	 *	- nldap or mixed mode. Got winname from nldap lookup.
291 	 *	  winname2sid could not be resolved locally. Lookup AD
292 	 *	  by winname to get sid.
293 	 *	- ad mode. Got unixname. Lookup AD by unixname to get
294 	 *	  winname and sid.
295 	 *  sid2pid:
296 	 *	- ad or mixed mode. Lookup AD by sid or winname to get
297 	 *	  winname, sid and unixname.
298 	 *	- any mode. Got either sid or winname but not both. Lookup
299 	 *	  AD by sid or winname to get winname, sid.
300 	 */
301 	if (state.ad_nqueries) {
302 		retcode = ad_lookup_batch(&state, &batch, result);
303 		if (IDMAP_FATAL_ERROR(retcode)) {
304 			result->retcode = retcode;
305 			goto out;
306 		}
307 	}
308 
309 	/*
310 	 * native LDAP lookups:
311 	 *  sid2pid:
312 	 *	- nldap mode. Got winname and sid from AD lookup. Lookup nldap
313 	 *	  by winname to get pid and unixname.
314 	 */
315 	if (state.nldap_nqueries) {
316 		retcode = nldap_lookup_batch(&state, &batch, result);
317 		if (IDMAP_FATAL_ERROR(retcode)) {
318 			result->retcode = retcode;
319 			goto out;
320 		}
321 	}
322 
323 	/* Reset 'done' flags */
324 	state.sid2pid_done = state.pid2sid_done = TRUE;
325 
326 	/* Second stage */
327 	for (i = 0; i < batch.idmap_mapping_batch_len; i++) {
328 		state.curpos = i;
329 		if (IS_BATCH_SID(batch, i)) {
330 			retcode = sid2pid_second_pass(
331 			    &state,
332 			    &batch.idmap_mapping_batch_val[i],
333 			    &result->ids.ids_val[i]);
334 		} else if (IS_BATCH_UID(batch, i)) {
335 			retcode = pid2sid_second_pass(
336 			    &state,
337 			    &batch.idmap_mapping_batch_val[i],
338 			    &result->ids.ids_val[i], 1);
339 		} else if (IS_BATCH_GID(batch, i)) {
340 			retcode = pid2sid_second_pass(
341 			    &state,
342 			    &batch.idmap_mapping_batch_val[i],
343 			    &result->ids.ids_val[i], 0);
344 		} else {
345 			/* First stage has already set the error */
346 			continue;
347 		}
348 		if (IDMAP_FATAL_ERROR(retcode)) {
349 			result->retcode = retcode;
350 			goto out;
351 		}
352 	}
353 
354 	/* Check if we are done */
355 	if (state.sid2pid_done == TRUE && state.pid2sid_done == TRUE)
356 		goto out;
357 
358 	/* Reset our 'done' flags */
359 	state.sid2pid_done = state.pid2sid_done = TRUE;
360 
361 	/* Update cache in a single transaction */
362 	if (sql_exec_no_cb(cache, IDMAP_CACHENAME, "BEGIN TRANSACTION;")
363 	    != IDMAP_SUCCESS)
364 		goto out;
365 
366 	for (i = 0; i < batch.idmap_mapping_batch_len; i++) {
367 		state.curpos = i;
368 		if (IS_BATCH_SID(batch, i)) {
369 			(void) update_cache_sid2pid(
370 			    &state,
371 			    &batch.idmap_mapping_batch_val[i],
372 			    &result->ids.ids_val[i]);
373 		} else if ((IS_BATCH_UID(batch, i)) ||
374 		    (IS_BATCH_GID(batch, i))) {
375 			(void) update_cache_pid2sid(
376 			    &state,
377 			    &batch.idmap_mapping_batch_val[i],
378 			    &result->ids.ids_val[i]);
379 		}
380 	}
381 
382 	/* Commit if we have at least one successful update */
383 	if (state.sid2pid_done == FALSE || state.pid2sid_done == FALSE)
384 		(void) sql_exec_no_cb(cache, IDMAP_CACHENAME,
385 		    "COMMIT TRANSACTION;");
386 	else
387 		(void) sql_exec_no_cb(cache, IDMAP_CACHENAME,
388 		    "END TRANSACTION;");
389 
390 out:
391 	cleanup_lookup_state(&state);
392 	if (IDMAP_ERROR(result->retcode)) {
393 		xdr_free(xdr_idmap_ids_res, (caddr_t)result);
394 		result->ids.ids_len = 0;
395 		result->ids.ids_val = NULL;
396 	}
397 	result->retcode = idmap_stat4prot(result->retcode);
398 	return (TRUE);
399 }
400 
401 
402 /* ARGSUSED */
403 static
404 int
405 list_mappings_cb(void *parg, int argc, char **argv, char **colnames)
406 {
407 	list_cb_data_t		*cb_data;
408 	char			*str;
409 	idmap_mappings_res	*result;
410 	idmap_retcode		retcode;
411 	int			w2u, u2w;
412 	char			*end;
413 	static int		validated_column_names = 0;
414 	idmap_how		*how;
415 
416 	cb_data = (list_cb_data_t *)parg;
417 
418 	if (!validated_column_names) {
419 		assert(strcmp(colnames[0], "rowid") == 0);
420 		assert(strcmp(colnames[1], "sidprefix") == 0);
421 		assert(strcmp(colnames[2], "rid") == 0);
422 		assert(strcmp(colnames[3], "pid") == 0);
423 		assert(strcmp(colnames[4], "w2u") == 0);
424 		assert(strcmp(colnames[5], "u2w") == 0);
425 		assert(strcmp(colnames[6], "windomain") == 0);
426 		assert(strcmp(colnames[7], "canon_winname") == 0);
427 		assert(strcmp(colnames[8], "unixname") == 0);
428 		assert(strcmp(colnames[9], "is_user") == 0);
429 		assert(strcmp(colnames[10], "is_wuser") == 0);
430 		assert(strcmp(colnames[11], "map_type") == 0);
431 		assert(strcmp(colnames[12], "map_dn") == 0);
432 		assert(strcmp(colnames[13], "map_attr") == 0);
433 		assert(strcmp(colnames[14], "map_value") == 0);
434 		assert(strcmp(colnames[15], "map_windomain") == 0);
435 		assert(strcmp(colnames[16], "map_winname") == 0);
436 		assert(strcmp(colnames[17], "map_unixname") == 0);
437 		assert(strcmp(colnames[18], "map_is_nt4") == 0);
438 		validated_column_names = 1;
439 	}
440 
441 	result = (idmap_mappings_res *)cb_data->result;
442 
443 	_VALIDATE_LIST_CB_DATA(19, &result->mappings.mappings_val,
444 	    sizeof (idmap_mapping));
445 
446 	result->mappings.mappings_len++;
447 
448 	if ((str = strdup(argv[1])) == NULL)
449 		return (1);
450 	result->mappings.mappings_val[cb_data->next].id1.idmap_id_u.sid.prefix =
451 	    str;
452 	result->mappings.mappings_val[cb_data->next].id1.idmap_id_u.sid.rid =
453 	    strtoul(argv[2], &end, 10);
454 	result->mappings.mappings_val[cb_data->next].id1.idtype =
455 	    strtol(argv[10], &end, 10) ? IDMAP_USID : IDMAP_GSID;
456 
457 	result->mappings.mappings_val[cb_data->next].id2.idmap_id_u.uid =
458 	    strtoul(argv[3], &end, 10);
459 	result->mappings.mappings_val[cb_data->next].id2.idtype =
460 	    strtol(argv[9], &end, 10) ? IDMAP_UID : IDMAP_GID;
461 
462 	w2u = argv[4] ? strtol(argv[4], &end, 10) : 0;
463 	u2w = argv[5] ? strtol(argv[5], &end, 10) : 0;
464 
465 	if (w2u > 0 && u2w == 0)
466 		result->mappings.mappings_val[cb_data->next].direction =
467 		    IDMAP_DIRECTION_W2U;
468 	else if (w2u == 0 && u2w > 0)
469 		result->mappings.mappings_val[cb_data->next].direction =
470 		    IDMAP_DIRECTION_U2W;
471 	else
472 		result->mappings.mappings_val[cb_data->next].direction =
473 		    IDMAP_DIRECTION_BI;
474 
475 	STRDUP_OR_FAIL(result->mappings.mappings_val[cb_data->next].id1domain,
476 	    argv[6]);
477 
478 	STRDUP_OR_FAIL(result->mappings.mappings_val[cb_data->next].id1name,
479 	    argv[7]);
480 
481 	STRDUP_OR_FAIL(result->mappings.mappings_val[cb_data->next].id2name,
482 	    argv[8]);
483 
484 	if (cb_data->flag & IDMAP_REQ_FLG_MAPPING_INFO) {
485 		how = &result->mappings.mappings_val[cb_data->next].info.how;
486 		how->map_type = strtoul(argv[11], &end, 10);
487 		switch (how->map_type) {
488 		case IDMAP_MAP_TYPE_DS_AD:
489 			how->idmap_how_u.ad.dn =
490 			    strdup(argv[12]);
491 			how->idmap_how_u.ad.attr =
492 			    strdup(argv[13]);
493 			how->idmap_how_u.ad.value =
494 			    strdup(argv[14]);
495 			break;
496 
497 		case IDMAP_MAP_TYPE_DS_NLDAP:
498 			how->idmap_how_u.nldap.dn =
499 			    strdup(argv[12]);
500 			how->idmap_how_u.nldap.attr =
501 			    strdup(argv[13]);
502 			how->idmap_how_u.nldap.value =
503 			    strdup(argv[14]);
504 			break;
505 
506 		case IDMAP_MAP_TYPE_RULE_BASED:
507 			how->idmap_how_u.rule.windomain =
508 			    strdup(argv[15]);
509 			how->idmap_how_u.rule.winname =
510 			    strdup(argv[16]);
511 			how->idmap_how_u.rule.unixname =
512 			    strdup(argv[17]);
513 			how->idmap_how_u.rule.is_nt4 =
514 			    strtoul(argv[18], &end, 10);
515 			how->idmap_how_u.rule.is_user =
516 			    strtol(argv[9], &end, 10);
517 			how->idmap_how_u.rule.is_wuser =
518 			    strtol(argv[10], &end, 10);
519 			break;
520 
521 		case IDMAP_MAP_TYPE_EPHEMERAL:
522 			break;
523 
524 		case IDMAP_MAP_TYPE_LOCAL_SID:
525 			break;
526 
527 		default:
528 			/* Unknow mapping type */
529 			assert(FALSE);
530 		}
531 
532 	}
533 
534 	result->lastrowid = strtoll(argv[0], &end, 10);
535 	cb_data->next++;
536 	result->retcode = IDMAP_SUCCESS;
537 	return (0);
538 }
539 
540 
541 /* ARGSUSED */
542 bool_t
543 idmap_list_mappings_1_svc(int64_t lastrowid, uint64_t limit, int32_t flag,
544     idmap_mappings_res *result, struct svc_req *rqstp)
545 {
546 	sqlite		*cache = NULL;
547 	char		lbuf[30], rbuf[30];
548 	uint64_t	maxlimit;
549 	idmap_retcode	retcode;
550 	char		*sql = NULL;
551 	time_t		curtime;
552 
553 	(void) memset(result, 0, sizeof (*result));
554 	lbuf[0] = rbuf[0] = 0;
555 
556 	/* Current time */
557 	errno = 0;
558 	if ((curtime = time(NULL)) == (time_t)-1) {
559 		idmapdlog(LOG_ERR, "Failed to get current time (%s)",
560 		    strerror(errno));
561 		retcode = IDMAP_ERR_INTERNAL;
562 		goto out;
563 	}
564 
565 	RDLOCK_CONFIG();
566 	maxlimit = _idmapdstate.cfg->pgcfg.list_size_limit;
567 	UNLOCK_CONFIG();
568 
569 	/* Get cache handle */
570 	result->retcode = get_cache_handle(&cache);
571 	if (result->retcode != IDMAP_SUCCESS)
572 		goto out;
573 
574 	result->retcode = IDMAP_ERR_INTERNAL;
575 
576 	/* Create LIMIT expression. */
577 	if (limit == 0 || (maxlimit > 0 && maxlimit < limit))
578 		limit = maxlimit;
579 	if (limit > 0)
580 		(void) snprintf(lbuf, sizeof (lbuf),
581 		    "LIMIT %" PRIu64, limit + 1ULL);
582 
583 	(void) snprintf(rbuf, sizeof (rbuf), "rowid > %" PRIu64, lastrowid);
584 
585 	/*
586 	 * Combine all the above into a giant SELECT statement that
587 	 * will return the requested mappings
588 	 */
589 
590 	sql = sqlite_mprintf("SELECT rowid, sidprefix, rid, pid, w2u, "
591 	    "u2w, windomain, canon_winname, unixname, is_user, is_wuser, "
592 	    "map_type, map_dn, map_attr, map_value, map_windomain, "
593 	    "map_winname, map_unixname, map_is_nt4 "
594 	    "FROM idmap_cache WHERE %s AND "
595 	    "(pid >= 2147483648 OR (expiration = 0 OR "
596 	    "expiration ISNULL  OR expiration > %d)) "
597 	    "%s;",
598 	    rbuf, curtime, lbuf);
599 	if (sql == NULL) {
600 		result->retcode = IDMAP_ERR_MEMORY;
601 		idmapdlog(LOG_ERR, "Out of memory");
602 		goto out;
603 	}
604 
605 	/* Execute the SQL statement and update the return buffer */
606 	PROCESS_LIST_SVC_SQL(retcode, cache, IDMAP_CACHENAME, sql, limit,
607 	    flag, list_mappings_cb, result, result->mappings.mappings_len);
608 
609 out:
610 	if (sql)
611 		sqlite_freemem(sql);
612 	if (IDMAP_ERROR(result->retcode))
613 		(void) xdr_free(xdr_idmap_mappings_res, (caddr_t)result);
614 	result->retcode = idmap_stat4prot(result->retcode);
615 	return (TRUE);
616 }
617 
618 
619 /* ARGSUSED */
620 static
621 int
622 list_namerules_cb(void *parg, int argc, char **argv, char **colnames)
623 {
624 	list_cb_data_t		*cb_data;
625 	idmap_namerules_res	*result;
626 	idmap_retcode		retcode;
627 	int			w2u_order, u2w_order;
628 	char			*end;
629 	static int		validated_column_names = 0;
630 
631 	if (!validated_column_names) {
632 		assert(strcmp(colnames[0], "rowid") == 0);
633 		assert(strcmp(colnames[1], "is_user") == 0);
634 		assert(strcmp(colnames[2], "is_wuser") == 0);
635 		assert(strcmp(colnames[3], "windomain") == 0);
636 		assert(strcmp(colnames[4], "winname_display") == 0);
637 		assert(strcmp(colnames[5], "is_nt4") == 0);
638 		assert(strcmp(colnames[6], "unixname") == 0);
639 		assert(strcmp(colnames[7], "w2u_order") == 0);
640 		assert(strcmp(colnames[8], "u2w_order") == 0);
641 		validated_column_names = 1;
642 	}
643 
644 	cb_data = (list_cb_data_t *)parg;
645 	result = (idmap_namerules_res *)cb_data->result;
646 
647 	_VALIDATE_LIST_CB_DATA(9, &result->rules.rules_val,
648 	    sizeof (idmap_namerule));
649 
650 	result->rules.rules_len++;
651 
652 	result->rules.rules_val[cb_data->next].is_user =
653 	    strtol(argv[1], &end, 10);
654 
655 	result->rules.rules_val[cb_data->next].is_wuser =
656 	    strtol(argv[2], &end, 10);
657 
658 	STRDUP_OR_FAIL(result->rules.rules_val[cb_data->next].windomain,
659 	    argv[3]);
660 
661 	STRDUP_OR_FAIL(result->rules.rules_val[cb_data->next].winname,
662 	    argv[4]);
663 
664 	result->rules.rules_val[cb_data->next].is_nt4 =
665 	    strtol(argv[5], &end, 10);
666 
667 	STRDUP_OR_FAIL(result->rules.rules_val[cb_data->next].unixname,
668 	    argv[6]);
669 
670 	w2u_order = argv[7] ? strtol(argv[7], &end, 10) : 0;
671 	u2w_order = argv[8] ? strtol(argv[8], &end, 10) : 0;
672 
673 	if (w2u_order > 0 && u2w_order == 0)
674 		result->rules.rules_val[cb_data->next].direction =
675 		    IDMAP_DIRECTION_W2U;
676 	else if (w2u_order == 0 && u2w_order > 0)
677 		result->rules.rules_val[cb_data->next].direction =
678 		    IDMAP_DIRECTION_U2W;
679 	else
680 		result->rules.rules_val[cb_data->next].direction =
681 		    IDMAP_DIRECTION_BI;
682 
683 	result->lastrowid = strtoll(argv[0], &end, 10);
684 	cb_data->next++;
685 	result->retcode = IDMAP_SUCCESS;
686 	return (0);
687 }
688 
689 
690 /* ARGSUSED */
691 bool_t
692 idmap_list_namerules_1_svc(idmap_namerule rule, uint64_t lastrowid,
693 		uint64_t limit, idmap_namerules_res *result,
694 		struct svc_req *rqstp)
695 {
696 
697 	sqlite		*db = NULL;
698 	char		w2ubuf[15], u2wbuf[15];
699 	char		lbuf[30], rbuf[30];
700 	char		*sql = NULL;
701 	char		*expr = NULL;
702 	uint64_t	maxlimit;
703 	idmap_retcode	retcode;
704 
705 	(void) memset(result, 0, sizeof (*result));
706 	lbuf[0] = rbuf[0] = 0;
707 
708 	result->retcode = validate_rule(&rule);
709 	if (result->retcode != IDMAP_SUCCESS)
710 		goto out;
711 
712 	RDLOCK_CONFIG();
713 	maxlimit = _idmapdstate.cfg->pgcfg.list_size_limit;
714 	UNLOCK_CONFIG();
715 
716 	/* Get db handle */
717 	result->retcode = get_db_handle(&db);
718 	if (result->retcode != IDMAP_SUCCESS)
719 		goto out;
720 
721 	result->retcode = IDMAP_ERR_INTERNAL;
722 
723 	w2ubuf[0] = u2wbuf[0] = 0;
724 	if (rule.direction == IDMAP_DIRECTION_BI) {
725 		(void) snprintf(w2ubuf, sizeof (w2ubuf), "AND w2u_order > 0");
726 		(void) snprintf(u2wbuf, sizeof (u2wbuf), "AND u2w_order > 0");
727 	} else if (rule.direction == IDMAP_DIRECTION_W2U) {
728 		(void) snprintf(w2ubuf, sizeof (w2ubuf), "AND w2u_order > 0");
729 		(void) snprintf(u2wbuf, sizeof (u2wbuf),
730 		    "AND (u2w_order = 0 OR u2w_order ISNULL)");
731 	} else if (rule.direction == IDMAP_DIRECTION_U2W) {
732 		(void) snprintf(w2ubuf, sizeof (w2ubuf),
733 		    "AND (w2u_order = 0 OR w2u_order ISNULL)");
734 		(void) snprintf(u2wbuf, sizeof (u2wbuf), "AND u2w_order > 0");
735 	}
736 
737 	result->retcode = gen_sql_expr_from_rule(&rule, &expr);
738 	if (result->retcode != IDMAP_SUCCESS)
739 		goto out;
740 
741 	/* Create LIMIT expression. */
742 	if (limit == 0 || (maxlimit > 0 && maxlimit < limit))
743 		limit = maxlimit;
744 	if (limit > 0)
745 		(void) snprintf(lbuf, sizeof (lbuf),
746 		    "LIMIT %" PRIu64, limit + 1ULL);
747 
748 	(void) snprintf(rbuf, sizeof (rbuf), "rowid > %" PRIu64, lastrowid);
749 
750 	/*
751 	 * Combine all the above into a giant SELECT statement that
752 	 * will return the requested rules
753 	 */
754 	sql = sqlite_mprintf("SELECT rowid, is_user, is_wuser, windomain, "
755 	    "winname_display, is_nt4, unixname, w2u_order, u2w_order "
756 	    "FROM namerules WHERE "
757 	    " %s %s %s %s %s;",
758 	    rbuf, expr, w2ubuf, u2wbuf, lbuf);
759 
760 	if (sql == NULL) {
761 		result->retcode = IDMAP_ERR_MEMORY;
762 		idmapdlog(LOG_ERR, "Out of memory");
763 		goto out;
764 	}
765 
766 	/* Execute the SQL statement and update the return buffer */
767 	PROCESS_LIST_SVC_SQL(retcode, db, IDMAP_DBNAME, sql, limit,
768 	    0, list_namerules_cb, result, result->rules.rules_len);
769 
770 out:
771 	if (expr)
772 		sqlite_freemem(expr);
773 	if (sql)
774 		sqlite_freemem(sql);
775 	if (IDMAP_ERROR(result->retcode))
776 		(void) xdr_free(xdr_idmap_namerules_res, (caddr_t)result);
777 	result->retcode = idmap_stat4prot(result->retcode);
778 	return (TRUE);
779 }
780 
781 #define	IDMAP_RULES_AUTH	"solaris.admin.idmap.rules"
782 static int
783 verify_rules_auth(struct svc_req *rqstp)
784 {
785 	ucred_t		*uc = NULL;
786 	uid_t		uid;
787 	char		buf[1024];
788 	struct passwd	pwd;
789 
790 	if (svc_getcallerucred(rqstp->rq_xprt, &uc) != 0) {
791 		idmapdlog(LOG_ERR, "svc_getcallerucred failed during "
792 		    "authorization (%s)", strerror(errno));
793 		return (-1);
794 	}
795 
796 	uid = ucred_geteuid(uc);
797 	if (uid == (uid_t)-1) {
798 		idmapdlog(LOG_ERR, "ucred_geteuid failed during "
799 		    "authorization (%s)", strerror(errno));
800 		ucred_free(uc);
801 		return (-1);
802 	}
803 
804 	if (getpwuid_r(uid, &pwd, buf, sizeof (buf)) == NULL) {
805 		idmapdlog(LOG_ERR, "getpwuid_r(%u) failed during "
806 		    "authorization (%s)", uid, strerror(errno));
807 		ucred_free(uc);
808 		return (-1);
809 	}
810 
811 	if (chkauthattr(IDMAP_RULES_AUTH, pwd.pw_name) != 1) {
812 		idmapdlog(LOG_INFO, "%s is not authorized (%s)",
813 		    pwd.pw_name, IDMAP_RULES_AUTH);
814 		ucred_free(uc);
815 		return (-1);
816 	}
817 
818 	ucred_free(uc);
819 	return (1);
820 }
821 
822 /*
823  * Meaning of the return values is the following: For retcode ==
824  * IDMAP_SUCCESS, everything went OK and error_index is
825  * undefined. Otherwise, error_index >=0 shows the failed batch
826  * element. errro_index == -1 indicates failure at the beginning,
827  * error_index == -2 at the end.
828  */
829 
830 /* ARGSUSED */
831 bool_t
832 idmap_update_1_svc(idmap_update_batch batch, idmap_update_res *res,
833 		struct svc_req *rqstp)
834 {
835 	sqlite		*db = NULL;
836 	idmap_update_op	*up;
837 	int		i;
838 	int		trans = FALSE;
839 
840 	res->error_index = -1;
841 	(void) memset(&res->error_rule, 0, sizeof (res->error_rule));
842 	(void) memset(&res->conflict_rule, 0, sizeof (res->conflict_rule));
843 
844 	if (verify_rules_auth(rqstp) < 0) {
845 		res->retcode = IDMAP_ERR_PERMISSION_DENIED;
846 		goto out;
847 	}
848 
849 	if (batch.idmap_update_batch_len == 0 ||
850 	    batch.idmap_update_batch_val == NULL) {
851 		res->retcode = IDMAP_SUCCESS;
852 		goto out;
853 	}
854 
855 	res->retcode = validate_rules(&batch);
856 	if (res->retcode != IDMAP_SUCCESS)
857 		goto out;
858 
859 	/* Get db handle */
860 	res->retcode = get_db_handle(&db);
861 	if (res->retcode != IDMAP_SUCCESS)
862 		goto out;
863 
864 	res->retcode = sql_exec_no_cb(db, IDMAP_DBNAME, "BEGIN TRANSACTION;");
865 	if (res->retcode != IDMAP_SUCCESS)
866 		goto out;
867 	trans = TRUE;
868 
869 	for (i = 0; i < batch.idmap_update_batch_len; i++) {
870 		up = &batch.idmap_update_batch_val[i];
871 		switch (up->opnum) {
872 		case OP_NONE:
873 			res->retcode = IDMAP_SUCCESS;
874 			break;
875 		case OP_ADD_NAMERULE:
876 			res->retcode = add_namerule(db,
877 			    &up->idmap_update_op_u.rule);
878 			break;
879 		case OP_RM_NAMERULE:
880 			res->retcode = rm_namerule(db,
881 			    &up->idmap_update_op_u.rule);
882 			break;
883 		case OP_FLUSH_NAMERULES:
884 			res->retcode = flush_namerules(db);
885 			break;
886 		default:
887 			res->retcode = IDMAP_ERR_NOTSUPPORTED;
888 			break;
889 		};
890 
891 		if (res->retcode != IDMAP_SUCCESS) {
892 			res->error_index = i;
893 			if (up->opnum == OP_ADD_NAMERULE ||
894 			    up->opnum == OP_RM_NAMERULE) {
895 				idmap_stat r2 =
896 				    idmap_namerule_cpy(&res->error_rule,
897 				    &up->idmap_update_op_u.rule);
898 				if (r2 != IDMAP_SUCCESS)
899 					res->retcode = r2;
900 			}
901 			goto out;
902 		}
903 	}
904 
905 out:
906 	if (trans) {
907 		if (res->retcode == IDMAP_SUCCESS) {
908 			res->retcode =
909 			    sql_exec_no_cb(db, IDMAP_DBNAME,
910 			    "COMMIT TRANSACTION;");
911 			if (res->retcode !=  IDMAP_SUCCESS)
912 				res->error_index = -2;
913 		}
914 		else
915 			(void) sql_exec_no_cb(db, IDMAP_DBNAME,
916 			    "ROLLBACK TRANSACTION;");
917 	}
918 
919 	res->retcode = idmap_stat4prot(res->retcode);
920 
921 	return (TRUE);
922 }
923 
924 
925 /* ARGSUSED */
926 bool_t
927 idmap_get_mapped_id_by_name_1_svc(idmap_mapping request,
928 		idmap_mappings_res *result, struct svc_req *rqstp)
929 {
930 	sqlite		*cache = NULL, *db = NULL;
931 
932 	/* Init */
933 	(void) memset(result, 0, sizeof (*result));
934 
935 	result->retcode = validate_mapped_id_by_name_req(&request);
936 	if (result->retcode != IDMAP_SUCCESS)
937 		goto out;
938 
939 	/* Get cache handle */
940 	result->retcode = get_cache_handle(&cache);
941 	if (result->retcode != IDMAP_SUCCESS)
942 		goto out;
943 
944 	/* Get db handle */
945 	result->retcode = get_db_handle(&db);
946 	if (result->retcode != IDMAP_SUCCESS)
947 		goto out;
948 
949 	/* Allocate result */
950 	result->mappings.mappings_val = calloc(1, sizeof (idmap_mapping));
951 	if (result->mappings.mappings_val == NULL) {
952 		idmapdlog(LOG_ERR, "Out of memory");
953 		result->retcode = IDMAP_ERR_MEMORY;
954 		goto out;
955 	}
956 	result->mappings.mappings_len = 1;
957 
958 
959 	if (IS_REQUEST_SID(request, 1)) {
960 		result->retcode = get_w2u_mapping(
961 		    cache,
962 		    db,
963 		    &request,
964 		    result->mappings.mappings_val);
965 	} else if (IS_REQUEST_UID(request)) {
966 		result->retcode = get_u2w_mapping(
967 		    cache,
968 		    db,
969 		    &request,
970 		    result->mappings.mappings_val,
971 		    1);
972 	} else if (IS_REQUEST_GID(request)) {
973 		result->retcode = get_u2w_mapping(
974 		    cache,
975 		    db,
976 		    &request,
977 		    result->mappings.mappings_val,
978 		    0);
979 	} else {
980 		result->retcode = IDMAP_ERR_IDTYPE;
981 	}
982 
983 out:
984 	if (IDMAP_FATAL_ERROR(result->retcode)) {
985 		xdr_free(xdr_idmap_mappings_res, (caddr_t)result);
986 		result->mappings.mappings_len = 0;
987 		result->mappings.mappings_val = NULL;
988 	}
989 	result->retcode = idmap_stat4prot(result->retcode);
990 	return (TRUE);
991 }
992 
993 /* ARGSUSED */
994 bool_t
995 idmap_get_prop_1_svc(idmap_prop_type request,
996 		idmap_prop_res *result, struct svc_req *rqstp)
997 {
998 	idmap_pg_config_t *pgcfg;
999 	ad_disc_t ad_ctx;
1000 
1001 	/* Init */
1002 	(void) memset(result, 0, sizeof (*result));
1003 	result->retcode = IDMAP_SUCCESS;
1004 	result->value.prop = request;
1005 
1006 	RDLOCK_CONFIG();
1007 
1008 	/* Just shortcuts: */
1009 	pgcfg = &_idmapdstate.cfg->pgcfg;
1010 	ad_ctx = _idmapdstate.cfg->handles.ad_ctx;
1011 
1012 	switch (request) {
1013 	case PROP_LIST_SIZE_LIMIT:
1014 		result->value.idmap_prop_val_u.intval = pgcfg->list_size_limit;
1015 		result->auto_discovered = FALSE;
1016 		break;
1017 	case PROP_DEFAULT_DOMAIN:
1018 		result->auto_discovered = FALSE;
1019 		STRDUP_CHECK(result->value.idmap_prop_val_u.utf8val,
1020 		    pgcfg->default_domain);
1021 		break;
1022 	case PROP_DOMAIN_NAME:
1023 		STRDUP_CHECK(result->value.idmap_prop_val_u.utf8val,
1024 		    pgcfg->domain_name);
1025 		result->auto_discovered =
1026 		    ad_ctx->domain_name.type == AD_TYPE_AUTO ? TRUE : FALSE;
1027 		break;
1028 	case PROP_MACHINE_SID:
1029 		result->auto_discovered = FALSE;
1030 		STRDUP_CHECK(result->value.idmap_prop_val_u.utf8val,
1031 		    pgcfg->machine_sid);
1032 		break;
1033 	case PROP_DOMAIN_CONTROLLER:
1034 		if (pgcfg->domain_controller != NULL) {
1035 			(void) memcpy(&result->value.idmap_prop_val_u.dsval,
1036 			    pgcfg->domain_controller,
1037 			    sizeof (idmap_ad_disc_ds_t));
1038 		}
1039 		result->auto_discovered =
1040 		    ad_ctx->domain_controller.type == AD_TYPE_AUTO
1041 		    ? TRUE : FALSE;
1042 		break;
1043 	case PROP_FOREST_NAME:
1044 		STRDUP_CHECK(result->value.idmap_prop_val_u.utf8val,
1045 		    pgcfg->forest_name);
1046 		result->auto_discovered =
1047 		    ad_ctx->forest_name.type == AD_TYPE_AUTO
1048 		    ? TRUE : FALSE;
1049 		break;
1050 	case PROP_SITE_NAME:
1051 		STRDUP_CHECK(result->value.idmap_prop_val_u.utf8val,
1052 		    pgcfg->site_name);
1053 		result->auto_discovered =
1054 		    ad_ctx->site_name.type == AD_TYPE_AUTO
1055 		    ? TRUE : FALSE;
1056 		break;
1057 	case PROP_GLOBAL_CATALOG:
1058 		if (pgcfg->global_catalog != NULL) {
1059 			(void) memcpy(&result->value.idmap_prop_val_u.dsval,
1060 			    pgcfg->global_catalog, sizeof (idmap_ad_disc_ds_t));
1061 		}
1062 		result->auto_discovered =
1063 		    ad_ctx->global_catalog.type == AD_TYPE_AUTO
1064 		    ? TRUE : FALSE;
1065 		break;
1066 	case PROP_AD_UNIXUSER_ATTR:
1067 		STRDUP_CHECK(result->value.idmap_prop_val_u.utf8val,
1068 		    pgcfg->ad_unixuser_attr);
1069 		result->auto_discovered = FALSE;
1070 		break;
1071 	case PROP_AD_UNIXGROUP_ATTR:
1072 		STRDUP_CHECK(result->value.idmap_prop_val_u.utf8val,
1073 		    pgcfg->ad_unixgroup_attr);
1074 		result->auto_discovered = FALSE;
1075 		break;
1076 	case PROP_NLDAP_WINNAME_ATTR:
1077 		STRDUP_CHECK(result->value.idmap_prop_val_u.utf8val,
1078 		    pgcfg->nldap_winname_attr);
1079 		result->auto_discovered = FALSE;
1080 		break;
1081 	case PROP_DS_NAME_MAPPING_ENABLED:
1082 		result->value.idmap_prop_val_u.boolval =
1083 		    pgcfg->ds_name_mapping_enabled;
1084 		result->auto_discovered = FALSE;
1085 		break;
1086 	default:
1087 		result->retcode = IDMAP_ERR_PROP_UNKNOWN;
1088 		break;
1089 	}
1090 
1091 out:
1092 	UNLOCK_CONFIG();
1093 	if (IDMAP_FATAL_ERROR(result->retcode)) {
1094 		xdr_free(xdr_idmap_prop_res, (caddr_t)result);
1095 		result->value.prop = PROP_UNKNOWN;
1096 	}
1097 	result->retcode = idmap_stat4prot(result->retcode);
1098 	return (TRUE);
1099 }
1100 
1101 
1102 /* ARGSUSED */
1103 int
1104 idmap_prog_1_freeresult(SVCXPRT *transp, xdrproc_t xdr_result,
1105 		caddr_t result)
1106 {
1107 	(void) xdr_free(xdr_result, result);
1108 	return (TRUE);
1109 }
1110