xref: /titanic_44/usr/src/cmd/idmap/idmapd/server.c (revision 98157a7002f4f2cf7978f3084ca5577f0a1d72b2)
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, cb, res, len)\
61 	rcode = process_list_svc_sql(db, dbname, sql, limit, 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 /* ARGSUSED */
77 bool_t
78 idmap_null_1_svc(void *result, struct svc_req *rqstp)
79 {
80 	return (TRUE);
81 }
82 
83 /*
84  * RPC layer allocates empty strings to replace NULL char *.
85  * This utility function frees these empty strings.
86  */
87 static
88 void
89 sanitize_mapping_request(idmap_mapping *req)
90 {
91 	free(req->id1name);
92 	req->id1name = NULL;
93 	free(req->id1domain);
94 	req->id1domain = NULL;
95 	free(req->id2name);
96 	req->id2name = NULL;
97 	free(req->id2domain);
98 	req->id2domain = NULL;
99 	req->direction = _IDMAP_F_DONE;
100 }
101 
102 static
103 int
104 validate_mapped_id_by_name_req(idmap_mapping *req)
105 {
106 	int e;
107 
108 	if (IS_REQUEST_UID(*req) || IS_REQUEST_GID(*req))
109 		return (IDMAP_SUCCESS);
110 
111 	if (IS_REQUEST_SID(*req, 1)) {
112 		if (!EMPTY_STRING(req->id1name) &&
113 		    u8_validate(req->id1name, strlen(req->id1name),
114 		    NULL, U8_VALIDATE_ENTIRE, &e) < 0)
115 			return (IDMAP_ERR_BAD_UTF8);
116 		if (!EMPTY_STRING(req->id1domain) &&
117 		    u8_validate(req->id1domain, strlen(req->id1domain),
118 		    NULL, U8_VALIDATE_ENTIRE, &e) < 0)
119 			return (IDMAP_ERR_BAD_UTF8);
120 	}
121 
122 	return (IDMAP_SUCCESS);
123 }
124 
125 static
126 int
127 validate_rule(idmap_namerule *rule)
128 {
129 	int e;
130 
131 	if (!EMPTY_STRING(rule->winname) &&
132 	    u8_validate(rule->winname, strlen(rule->winname),
133 	    NULL, U8_VALIDATE_ENTIRE, &e) < 0)
134 		return (IDMAP_ERR_BAD_UTF8);
135 
136 	if (!EMPTY_STRING(rule->windomain) &&
137 	    u8_validate(rule->windomain, strlen(rule->windomain),
138 	    NULL, U8_VALIDATE_ENTIRE, &e) < 0)
139 		return (IDMAP_ERR_BAD_UTF8);
140 
141 	return (IDMAP_SUCCESS);
142 
143 }
144 
145 static
146 bool_t
147 validate_rules(idmap_update_batch *batch)
148 {
149 	idmap_update_op	*up;
150 	int i;
151 
152 	for (i = 0; i < batch->idmap_update_batch_len; i++) {
153 		up = &(batch->idmap_update_batch_val[i]);
154 		if (validate_rule(&(up->idmap_update_op_u.rule))
155 		    != IDMAP_SUCCESS)
156 			return (IDMAP_ERR_BAD_UTF8);
157 	}
158 
159 	return (IDMAP_SUCCESS);
160 }
161 
162 /* ARGSUSED */
163 bool_t
164 idmap_get_mapped_ids_1_svc(idmap_mapping_batch batch,
165 		idmap_ids_res *result, struct svc_req *rqstp)
166 {
167 	sqlite		*cache = NULL, *db = NULL;
168 	lookup_state_t	state;
169 	idmap_retcode	retcode;
170 	uint_t		i;
171 
172 	/* Init */
173 	(void) memset(result, 0, sizeof (*result));
174 	(void) memset(&state, 0, sizeof (state));
175 
176 	/* Return success if nothing was requested */
177 	if (batch.idmap_mapping_batch_len < 1)
178 		goto out;
179 
180 	/* Get cache handle */
181 	result->retcode = get_cache_handle(&cache);
182 	if (result->retcode != IDMAP_SUCCESS)
183 		goto out;
184 
185 	/* Get db handle */
186 	result->retcode = get_db_handle(&db);
187 	if (result->retcode != IDMAP_SUCCESS)
188 		goto out;
189 
190 	/* Allocate result array */
191 	result->ids.ids_val = calloc(batch.idmap_mapping_batch_len,
192 	    sizeof (idmap_id_res));
193 	if (result->ids.ids_val == NULL) {
194 		idmapdlog(LOG_ERR, "Out of memory");
195 		result->retcode = IDMAP_ERR_MEMORY;
196 		goto out;
197 	}
198 	result->ids.ids_len = batch.idmap_mapping_batch_len;
199 
200 	/* Allocate hash table to check for duplicate sids */
201 	state.sid_history = calloc(batch.idmap_mapping_batch_len,
202 	    sizeof (*state.sid_history));
203 	if (state.sid_history == NULL) {
204 		idmapdlog(LOG_ERR, "Out of memory");
205 		result->retcode = IDMAP_ERR_MEMORY;
206 		goto out;
207 	}
208 	state.sid_history_size = batch.idmap_mapping_batch_len;
209 	for (i = 0; i < state.sid_history_size; i++) {
210 		state.sid_history[i].key = state.sid_history_size;
211 		state.sid_history[i].next = state.sid_history_size;
212 	}
213 	state.batch = &batch;
214 	state.result = result;
215 
216 	/* Get directory-based name mapping info */
217 	result->retcode = get_ds_namemap_type(&state);
218 	if (result->retcode != IDMAP_SUCCESS)
219 		goto out;
220 
221 	/* Init our 'done' flags */
222 	state.sid2pid_done = state.pid2sid_done = TRUE;
223 
224 	/* First stage */
225 	for (i = 0; i < batch.idmap_mapping_batch_len; i++) {
226 		state.curpos = i;
227 		(void) sanitize_mapping_request(
228 		    &batch.idmap_mapping_batch_val[i]);
229 		if (IS_BATCH_SID(batch, i)) {
230 			retcode = sid2pid_first_pass(
231 			    &state,
232 			    cache,
233 			    &batch.idmap_mapping_batch_val[i],
234 			    &result->ids.ids_val[i]);
235 		} else if (IS_BATCH_UID(batch, i)) {
236 			retcode = pid2sid_first_pass(
237 			    &state,
238 			    cache,
239 			    &batch.idmap_mapping_batch_val[i],
240 			    &result->ids.ids_val[i], 1, 0);
241 		} else if (IS_BATCH_GID(batch, i)) {
242 			retcode = pid2sid_first_pass(
243 			    &state,
244 			    cache,
245 			    &batch.idmap_mapping_batch_val[i],
246 			    &result->ids.ids_val[i], 0, 0);
247 		} else {
248 			result->ids.ids_val[i].retcode = IDMAP_ERR_IDTYPE;
249 			continue;
250 		}
251 		if (IDMAP_FATAL_ERROR(retcode)) {
252 			result->retcode = retcode;
253 			goto out;
254 		}
255 	}
256 
257 	/* Check if we are done */
258 	if (state.sid2pid_done == TRUE && state.pid2sid_done == TRUE)
259 		goto out;
260 
261 	/*
262 	 * native LDAP lookups:
263 	 * If nldap or mixed mode is enabled then pid2sid mapping requests
264 	 * need to lookup native LDAP directory service by uid/gid to get
265 	 * winname and unixname.
266 	 */
267 	if (state.nldap_nqueries) {
268 		retcode = nldap_lookup_batch(&state, &batch, result);
269 		if (IDMAP_FATAL_ERROR(retcode)) {
270 			result->retcode = retcode;
271 			goto out;
272 		}
273 	}
274 
275 	/*
276 	 * AD lookups:
277 	 * 1. The pid2sid requests in the preceding step which successfully
278 	 *    retrieved winname from native LDAP objects will now need to
279 	 *    lookup AD by winname to get sid.
280 	 * 2. The sid2pid requests will need to lookup AD by sid to get
281 	 *    winname and unixname (AD or mixed mode).
282 	 * 3. If AD-based name mapping is enabled then pid2sid mapping
283 	 *    requests need to lookup AD by unixname to get winname and sid.
284 	 */
285 	if (state.ad_nqueries) {
286 		retcode = ad_lookup_batch(&state, &batch, result);
287 		if (IDMAP_FATAL_ERROR(retcode)) {
288 			result->retcode = retcode;
289 			goto out;
290 		}
291 	}
292 
293 	/*
294 	 * native LDAP lookups:
295 	 * If nldap mode is enabled then sid2pid mapping requests
296 	 * which successfully retrieved winname from AD objects in the
297 	 * preceding step, will now need to lookup native LDAP directory
298 	 * service by winname to get unixname and pid.
299 	 */
300 	if (state.nldap_nqueries) {
301 		retcode = nldap_lookup_batch(&state, &batch, result);
302 		if (IDMAP_FATAL_ERROR(retcode)) {
303 			result->retcode = retcode;
304 			goto out;
305 		}
306 	}
307 
308 	/* Reset 'done' flags */
309 	state.sid2pid_done = state.pid2sid_done = TRUE;
310 
311 	/* Second stage */
312 	for (i = 0; i < batch.idmap_mapping_batch_len; i++) {
313 		state.curpos = i;
314 		if (IS_BATCH_SID(batch, i)) {
315 			retcode = sid2pid_second_pass(
316 			    &state,
317 			    cache,
318 			    db,
319 			    &batch.idmap_mapping_batch_val[i],
320 			    &result->ids.ids_val[i]);
321 		} else if (IS_BATCH_UID(batch, i)) {
322 			retcode = pid2sid_second_pass(
323 			    &state,
324 			    cache,
325 			    db,
326 			    &batch.idmap_mapping_batch_val[i],
327 			    &result->ids.ids_val[i], 1);
328 		} else if (IS_BATCH_GID(batch, i)) {
329 			retcode = pid2sid_second_pass(
330 			    &state,
331 			    cache,
332 			    db,
333 			    &batch.idmap_mapping_batch_val[i],
334 			    &result->ids.ids_val[i], 0);
335 		} else {
336 			/* First stage has already set the error */
337 			continue;
338 		}
339 		if (IDMAP_FATAL_ERROR(retcode)) {
340 			result->retcode = retcode;
341 			goto out;
342 		}
343 	}
344 
345 	/* Check if we are done */
346 	if (state.sid2pid_done == TRUE && state.pid2sid_done == TRUE)
347 		goto out;
348 
349 	/* Reset our 'done' flags */
350 	state.sid2pid_done = state.pid2sid_done = TRUE;
351 
352 	/* Update cache in a single transaction */
353 	if (sql_exec_no_cb(cache, IDMAP_CACHENAME, "BEGIN TRANSACTION;")
354 	    != IDMAP_SUCCESS)
355 		goto out;
356 
357 	for (i = 0; i < batch.idmap_mapping_batch_len; i++) {
358 		state.curpos = i;
359 		if (IS_BATCH_SID(batch, i)) {
360 			(void) update_cache_sid2pid(
361 			    &state,
362 			    cache,
363 			    &batch.idmap_mapping_batch_val[i],
364 			    &result->ids.ids_val[i]);
365 		} else if ((IS_BATCH_UID(batch, i)) ||
366 		    (IS_BATCH_GID(batch, i))) {
367 			(void) update_cache_pid2sid(
368 			    &state,
369 			    cache,
370 			    &batch.idmap_mapping_batch_val[i],
371 			    &result->ids.ids_val[i]);
372 		}
373 	}
374 
375 	/* Commit if we have at least one successful update */
376 	if (state.sid2pid_done == FALSE || state.pid2sid_done == FALSE)
377 		(void) sql_exec_no_cb(cache, IDMAP_CACHENAME,
378 		    "COMMIT TRANSACTION;");
379 	else
380 		(void) sql_exec_no_cb(cache, IDMAP_CACHENAME,
381 		    "END TRANSACTION;");
382 
383 out:
384 	cleanup_lookup_state(&state);
385 	if (IDMAP_ERROR(result->retcode)) {
386 		xdr_free(xdr_idmap_ids_res, (caddr_t)result);
387 		result->ids.ids_len = 0;
388 		result->ids.ids_val = NULL;
389 	}
390 	result->retcode = idmap_stat4prot(result->retcode);
391 	return (TRUE);
392 }
393 
394 
395 /* ARGSUSED */
396 static
397 int
398 list_mappings_cb(void *parg, int argc, char **argv, char **colnames)
399 {
400 	list_cb_data_t		*cb_data;
401 	char			*str;
402 	idmap_mappings_res	*result;
403 	idmap_retcode		retcode;
404 	int			w2u, u2w;
405 	char			*end;
406 	static int		validated_column_names = 0;
407 
408 	if (!validated_column_names) {
409 		assert(strcmp(colnames[0], "rowid") == 0);
410 		assert(strcmp(colnames[1], "sidprefix") == 0);
411 		assert(strcmp(colnames[2], "rid") == 0);
412 		assert(strcmp(colnames[3], "pid") == 0);
413 		assert(strcmp(colnames[4], "w2u") == 0);
414 		assert(strcmp(colnames[5], "u2w") == 0);
415 		assert(strcmp(colnames[6], "windomain") == 0);
416 		assert(strcmp(colnames[7], "canon_winname") == 0);
417 		assert(strcmp(colnames[8], "unixname") == 0);
418 		assert(strcmp(colnames[9], "is_user") == 0);
419 		assert(strcmp(colnames[10], "is_wuser") == 0);
420 		validated_column_names = 1;
421 	}
422 
423 
424 	cb_data = (list_cb_data_t *)parg;
425 	result = (idmap_mappings_res *)cb_data->result;
426 
427 	_VALIDATE_LIST_CB_DATA(11, &result->mappings.mappings_val,
428 	    sizeof (idmap_mapping));
429 
430 	result->mappings.mappings_len++;
431 
432 	if ((str = strdup(argv[1])) == NULL)
433 		return (1);
434 	result->mappings.mappings_val[cb_data->next].id1.idmap_id_u.sid.prefix =
435 	    str;
436 	result->mappings.mappings_val[cb_data->next].id1.idmap_id_u.sid.rid =
437 	    strtoul(argv[2], &end, 10);
438 	result->mappings.mappings_val[cb_data->next].id1.idtype =
439 	    strtol(argv[10], &end, 10) ? IDMAP_USID : IDMAP_GSID;
440 
441 	result->mappings.mappings_val[cb_data->next].id2.idmap_id_u.uid =
442 	    strtoul(argv[3], &end, 10);
443 	result->mappings.mappings_val[cb_data->next].id2.idtype =
444 	    strtol(argv[9], &end, 10) ? IDMAP_UID : IDMAP_GID;
445 
446 	w2u = argv[4] ? strtol(argv[4], &end, 10) : 0;
447 	u2w = argv[5] ? strtol(argv[5], &end, 10) : 0;
448 
449 	if (w2u > 0 && u2w == 0)
450 		result->mappings.mappings_val[cb_data->next].direction =
451 		    IDMAP_DIRECTION_W2U;
452 	else if (w2u == 0 && u2w > 0)
453 		result->mappings.mappings_val[cb_data->next].direction =
454 		    IDMAP_DIRECTION_U2W;
455 	else
456 		result->mappings.mappings_val[cb_data->next].direction =
457 		    IDMAP_DIRECTION_BI;
458 
459 	STRDUP_OR_FAIL(result->mappings.mappings_val[cb_data->next].id1domain,
460 	    argv[6]);
461 
462 	STRDUP_OR_FAIL(result->mappings.mappings_val[cb_data->next].id1name,
463 	    argv[7]);
464 
465 	STRDUP_OR_FAIL(result->mappings.mappings_val[cb_data->next].id2name,
466 	    argv[8]);
467 
468 
469 	result->lastrowid = strtoll(argv[0], &end, 10);
470 	cb_data->next++;
471 	result->retcode = IDMAP_SUCCESS;
472 	return (0);
473 }
474 
475 
476 /* ARGSUSED */
477 bool_t
478 idmap_list_mappings_1_svc(int64_t lastrowid, uint64_t limit,
479     idmap_mappings_res *result, struct svc_req *rqstp)
480 {
481 	sqlite		*cache = NULL;
482 	char		lbuf[30], rbuf[30];
483 	uint64_t	maxlimit;
484 	idmap_retcode	retcode;
485 	char		*sql = NULL;
486 
487 	(void) memset(result, 0, sizeof (*result));
488 	lbuf[0] = rbuf[0] = 0;
489 
490 	RDLOCK_CONFIG();
491 	maxlimit = _idmapdstate.cfg->pgcfg.list_size_limit;
492 	UNLOCK_CONFIG();
493 
494 	/* Get cache handle */
495 	result->retcode = get_cache_handle(&cache);
496 	if (result->retcode != IDMAP_SUCCESS)
497 		goto out;
498 
499 	result->retcode = IDMAP_ERR_INTERNAL;
500 
501 	/* Create LIMIT expression. */
502 	if (limit == 0 || (maxlimit > 0 && maxlimit < limit))
503 		limit = maxlimit;
504 	if (limit > 0)
505 		(void) snprintf(lbuf, sizeof (lbuf),
506 		    "LIMIT %" PRIu64, limit + 1ULL);
507 
508 	(void) snprintf(rbuf, sizeof (rbuf), "rowid > %" PRIu64, lastrowid);
509 
510 	/*
511 	 * Combine all the above into a giant SELECT statement that
512 	 * will return the requested mappings
513 	 */
514 	sql = sqlite_mprintf("SELECT rowid, sidprefix, rid, pid, w2u, u2w, "
515 	    "windomain, canon_winname, unixname, is_user, is_wuser "
516 	    " FROM idmap_cache WHERE "
517 	    " %s %s;",
518 	    rbuf, lbuf);
519 	if (sql == NULL) {
520 		idmapdlog(LOG_ERR, "Out of memory");
521 		goto out;
522 	}
523 
524 	/* Execute the SQL statement and update the return buffer */
525 	PROCESS_LIST_SVC_SQL(retcode, cache, IDMAP_CACHENAME, sql, limit,
526 	    list_mappings_cb, result, result->mappings.mappings_len);
527 
528 out:
529 	if (sql)
530 		sqlite_freemem(sql);
531 	if (IDMAP_ERROR(result->retcode))
532 		(void) xdr_free(xdr_idmap_mappings_res, (caddr_t)result);
533 	result->retcode = idmap_stat4prot(result->retcode);
534 	return (TRUE);
535 }
536 
537 
538 /* ARGSUSED */
539 static
540 int
541 list_namerules_cb(void *parg, int argc, char **argv, char **colnames)
542 {
543 	list_cb_data_t		*cb_data;
544 	idmap_namerules_res	*result;
545 	idmap_retcode		retcode;
546 	int			w2u_order, u2w_order;
547 	char			*end;
548 	static int		validated_column_names = 0;
549 
550 	if (!validated_column_names) {
551 		assert(strcmp(colnames[0], "rowid") == 0);
552 		assert(strcmp(colnames[1], "is_user") == 0);
553 		assert(strcmp(colnames[2], "is_wuser") == 0);
554 		assert(strcmp(colnames[3], "windomain") == 0);
555 		assert(strcmp(colnames[4], "winname_display") == 0);
556 		assert(strcmp(colnames[5], "is_nt4") == 0);
557 		assert(strcmp(colnames[6], "unixname") == 0);
558 		assert(strcmp(colnames[7], "w2u_order") == 0);
559 		assert(strcmp(colnames[8], "u2w_order") == 0);
560 		validated_column_names = 1;
561 	}
562 
563 	cb_data = (list_cb_data_t *)parg;
564 	result = (idmap_namerules_res *)cb_data->result;
565 
566 	_VALIDATE_LIST_CB_DATA(9, &result->rules.rules_val,
567 	    sizeof (idmap_namerule));
568 
569 	result->rules.rules_len++;
570 
571 	result->rules.rules_val[cb_data->next].is_user =
572 	    strtol(argv[1], &end, 10);
573 
574 	result->rules.rules_val[cb_data->next].is_wuser =
575 	    strtol(argv[2], &end, 10);
576 
577 	STRDUP_OR_FAIL(result->rules.rules_val[cb_data->next].windomain,
578 	    argv[3]);
579 
580 	STRDUP_OR_FAIL(result->rules.rules_val[cb_data->next].winname,
581 	    argv[4]);
582 
583 	result->rules.rules_val[cb_data->next].is_nt4 =
584 	    strtol(argv[5], &end, 10);
585 
586 	STRDUP_OR_FAIL(result->rules.rules_val[cb_data->next].unixname,
587 	    argv[6]);
588 
589 	w2u_order = argv[7] ? strtol(argv[7], &end, 10) : 0;
590 	u2w_order = argv[8] ? strtol(argv[8], &end, 10) : 0;
591 
592 	if (w2u_order > 0 && u2w_order == 0)
593 		result->rules.rules_val[cb_data->next].direction =
594 		    IDMAP_DIRECTION_W2U;
595 	else if (w2u_order == 0 && u2w_order > 0)
596 		result->rules.rules_val[cb_data->next].direction =
597 		    IDMAP_DIRECTION_U2W;
598 	else
599 		result->rules.rules_val[cb_data->next].direction =
600 		    IDMAP_DIRECTION_BI;
601 
602 	result->lastrowid = strtoll(argv[0], &end, 10);
603 	cb_data->next++;
604 	result->retcode = IDMAP_SUCCESS;
605 	return (0);
606 }
607 
608 
609 /* ARGSUSED */
610 bool_t
611 idmap_list_namerules_1_svc(idmap_namerule rule, uint64_t lastrowid,
612 		uint64_t limit, idmap_namerules_res *result,
613 		struct svc_req *rqstp)
614 {
615 
616 	sqlite		*db = NULL;
617 	char		w2ubuf[15], u2wbuf[15];
618 	char		lbuf[30], rbuf[30];
619 	char		*sql = NULL;
620 	char		*expr = NULL;
621 	uint64_t	maxlimit;
622 	idmap_retcode	retcode;
623 
624 	(void) memset(result, 0, sizeof (*result));
625 	lbuf[0] = rbuf[0] = 0;
626 
627 	result->retcode = validate_rule(&rule);
628 	if (result->retcode != IDMAP_SUCCESS)
629 		goto out;
630 
631 	RDLOCK_CONFIG();
632 	maxlimit = _idmapdstate.cfg->pgcfg.list_size_limit;
633 	UNLOCK_CONFIG();
634 
635 	/* Get db handle */
636 	result->retcode = get_db_handle(&db);
637 	if (result->retcode != IDMAP_SUCCESS)
638 		goto out;
639 
640 	result->retcode = IDMAP_ERR_INTERNAL;
641 
642 	w2ubuf[0] = u2wbuf[0] = 0;
643 	if (rule.direction == IDMAP_DIRECTION_BI) {
644 		(void) snprintf(w2ubuf, sizeof (w2ubuf), "AND w2u_order > 0");
645 		(void) snprintf(u2wbuf, sizeof (u2wbuf), "AND u2w_order > 0");
646 	} else if (rule.direction == IDMAP_DIRECTION_W2U) {
647 		(void) snprintf(w2ubuf, sizeof (w2ubuf), "AND w2u_order > 0");
648 		(void) snprintf(u2wbuf, sizeof (u2wbuf),
649 		    "AND (u2w_order = 0 OR u2w_order ISNULL)");
650 	} else if (rule.direction == IDMAP_DIRECTION_U2W) {
651 		(void) snprintf(w2ubuf, sizeof (w2ubuf),
652 		    "AND (w2u_order = 0 OR w2u_order ISNULL)");
653 		(void) snprintf(u2wbuf, sizeof (u2wbuf), "AND u2w_order > 0");
654 	}
655 
656 	result->retcode = gen_sql_expr_from_rule(&rule, &expr);
657 	if (result->retcode != IDMAP_SUCCESS)
658 		goto out;
659 
660 	/* Create LIMIT expression. */
661 	if (limit == 0 || (maxlimit > 0 && maxlimit < limit))
662 		limit = maxlimit;
663 	if (limit > 0)
664 		(void) snprintf(lbuf, sizeof (lbuf),
665 		    "LIMIT %" PRIu64, limit + 1ULL);
666 
667 	(void) snprintf(rbuf, sizeof (rbuf), "rowid > %" PRIu64, lastrowid);
668 
669 	/*
670 	 * Combine all the above into a giant SELECT statement that
671 	 * will return the requested rules
672 	 */
673 	sql = sqlite_mprintf("SELECT rowid, is_user, is_wuser, windomain, "
674 	    "winname_display, is_nt4, unixname, w2u_order, u2w_order "
675 	    "FROM namerules WHERE "
676 	    " %s %s %s %s %s;",
677 	    rbuf, expr, w2ubuf, u2wbuf, lbuf);
678 
679 	if (sql == NULL) {
680 		idmapdlog(LOG_ERR, "Out of memory");
681 		goto out;
682 	}
683 
684 	/* Execute the SQL statement and update the return buffer */
685 	PROCESS_LIST_SVC_SQL(retcode, db, IDMAP_DBNAME, sql, limit,
686 	    list_namerules_cb, result, result->rules.rules_len);
687 
688 out:
689 	if (expr)
690 		sqlite_freemem(expr);
691 	if (sql)
692 		sqlite_freemem(sql);
693 	if (IDMAP_ERROR(result->retcode))
694 		(void) xdr_free(xdr_idmap_namerules_res, (caddr_t)result);
695 	result->retcode = idmap_stat4prot(result->retcode);
696 	return (TRUE);
697 }
698 
699 #define	IDMAP_RULES_AUTH	"solaris.admin.idmap.rules"
700 static int
701 verify_rules_auth(struct svc_req *rqstp)
702 {
703 	ucred_t		*uc = NULL;
704 	uid_t		uid;
705 	char		buf[1024];
706 	struct passwd	pwd;
707 
708 	if (svc_getcallerucred(rqstp->rq_xprt, &uc) != 0) {
709 		idmapdlog(LOG_ERR, "svc_getcallerucred failed during "
710 		    "authorization (%s)", strerror(errno));
711 		return (-1);
712 	}
713 
714 	uid = ucred_geteuid(uc);
715 	if (uid == (uid_t)-1) {
716 		idmapdlog(LOG_ERR, "ucred_geteuid failed during "
717 		    "authorization (%s)", strerror(errno));
718 		ucred_free(uc);
719 		return (-1);
720 	}
721 
722 	if (getpwuid_r(uid, &pwd, buf, sizeof (buf)) == NULL) {
723 		idmapdlog(LOG_ERR, "getpwuid_r(%u) failed during "
724 		    "authorization (%s)", uid, strerror(errno));
725 		ucred_free(uc);
726 		return (-1);
727 	}
728 
729 	if (chkauthattr(IDMAP_RULES_AUTH, pwd.pw_name) != 1) {
730 		idmapdlog(LOG_INFO, "%s is not authorized (%s)",
731 		    pwd.pw_name, IDMAP_RULES_AUTH);
732 		ucred_free(uc);
733 		return (-1);
734 	}
735 
736 	ucred_free(uc);
737 	return (1);
738 }
739 
740 /*
741  * Meaning of the return values is the following: For retcode ==
742  * IDMAP_SUCCESS, everything went OK and error_index is
743  * undefined. Otherwise, error_index >=0 shows the failed batch
744  * element. errro_index == -1 indicates failure at the beginning,
745  * error_index == -2 at the end.
746  */
747 
748 /* ARGSUSED */
749 bool_t
750 idmap_update_1_svc(idmap_update_batch batch, idmap_update_res *res,
751 		struct svc_req *rqstp)
752 {
753 	sqlite		*db = NULL;
754 	idmap_update_op	*up;
755 	int		i;
756 	int		trans = FALSE;
757 
758 	res->error_index = -1;
759 	(void) memset(&res->error_rule, 0, sizeof (res->error_rule));
760 	(void) memset(&res->conflict_rule, 0, sizeof (res->conflict_rule));
761 
762 	if (verify_rules_auth(rqstp) < 0) {
763 		res->retcode = IDMAP_ERR_PERMISSION_DENIED;
764 		goto out;
765 	}
766 
767 	if (batch.idmap_update_batch_len == 0 ||
768 	    batch.idmap_update_batch_val == NULL) {
769 		res->retcode = IDMAP_SUCCESS;
770 		goto out;
771 	}
772 
773 	res->retcode = validate_rules(&batch);
774 	if (res->retcode != IDMAP_SUCCESS)
775 		goto out;
776 
777 	/* Get db handle */
778 	res->retcode = get_db_handle(&db);
779 	if (res->retcode != IDMAP_SUCCESS)
780 		goto out;
781 
782 	res->retcode = sql_exec_no_cb(db, IDMAP_DBNAME, "BEGIN TRANSACTION;");
783 	if (res->retcode != IDMAP_SUCCESS)
784 		goto out;
785 	trans = TRUE;
786 
787 	for (i = 0; i < batch.idmap_update_batch_len; i++) {
788 		up = &batch.idmap_update_batch_val[i];
789 		switch (up->opnum) {
790 		case OP_NONE:
791 			res->retcode = IDMAP_SUCCESS;
792 			break;
793 		case OP_ADD_NAMERULE:
794 			res->retcode = add_namerule(db,
795 			    &up->idmap_update_op_u.rule);
796 			break;
797 		case OP_RM_NAMERULE:
798 			res->retcode = rm_namerule(db,
799 			    &up->idmap_update_op_u.rule);
800 			break;
801 		case OP_FLUSH_NAMERULES:
802 			res->retcode = flush_namerules(db);
803 			break;
804 		default:
805 			res->retcode = IDMAP_ERR_NOTSUPPORTED;
806 			break;
807 		};
808 
809 		if (res->retcode != IDMAP_SUCCESS) {
810 			res->error_index = i;
811 			if (up->opnum == OP_ADD_NAMERULE ||
812 			    up->opnum == OP_RM_NAMERULE) {
813 				idmap_stat r2 =
814 				    idmap_namerule_cpy(&res->error_rule,
815 				    &up->idmap_update_op_u.rule);
816 				if (r2 != IDMAP_SUCCESS)
817 					res->retcode = r2;
818 			}
819 			goto out;
820 		}
821 	}
822 
823 out:
824 	if (trans) {
825 		if (res->retcode == IDMAP_SUCCESS) {
826 			res->retcode =
827 			    sql_exec_no_cb(db, IDMAP_DBNAME,
828 			    "COMMIT TRANSACTION;");
829 			if (res->retcode !=  IDMAP_SUCCESS)
830 				res->error_index = -2;
831 		}
832 		else
833 			(void) sql_exec_no_cb(db, IDMAP_DBNAME,
834 			    "ROLLBACK TRANSACTION;");
835 	}
836 
837 	res->retcode = idmap_stat4prot(res->retcode);
838 
839 	return (TRUE);
840 }
841 
842 
843 /* ARGSUSED */
844 bool_t
845 idmap_get_mapped_id_by_name_1_svc(idmap_mapping request,
846 		idmap_mappings_res *result, struct svc_req *rqstp)
847 {
848 	sqlite		*cache = NULL, *db = NULL;
849 
850 	/* Init */
851 	(void) memset(result, 0, sizeof (*result));
852 
853 	result->retcode = validate_mapped_id_by_name_req(&request);
854 	if (result->retcode != IDMAP_SUCCESS)
855 		goto out;
856 
857 	/* Get cache handle */
858 	result->retcode = get_cache_handle(&cache);
859 	if (result->retcode != IDMAP_SUCCESS)
860 		goto out;
861 
862 	/* Get db handle */
863 	result->retcode = get_db_handle(&db);
864 	if (result->retcode != IDMAP_SUCCESS)
865 		goto out;
866 
867 	/* Allocate result */
868 	result->mappings.mappings_val = calloc(1, sizeof (idmap_mapping));
869 	if (result->mappings.mappings_val == NULL) {
870 		idmapdlog(LOG_ERR, "Out of memory");
871 		result->retcode = IDMAP_ERR_MEMORY;
872 		goto out;
873 	}
874 	result->mappings.mappings_len = 1;
875 
876 
877 	if (IS_REQUEST_SID(request, 1)) {
878 		result->retcode = get_w2u_mapping(
879 		    cache,
880 		    db,
881 		    &request,
882 		    result->mappings.mappings_val);
883 	} else if (IS_REQUEST_UID(request)) {
884 		result->retcode = get_u2w_mapping(
885 		    cache,
886 		    db,
887 		    &request,
888 		    result->mappings.mappings_val,
889 		    1);
890 	} else if (IS_REQUEST_GID(request)) {
891 		result->retcode = get_u2w_mapping(
892 		    cache,
893 		    db,
894 		    &request,
895 		    result->mappings.mappings_val,
896 		    0);
897 	} else {
898 		result->retcode = IDMAP_ERR_IDTYPE;
899 	}
900 
901 out:
902 	if (IDMAP_FATAL_ERROR(result->retcode)) {
903 		xdr_free(xdr_idmap_mappings_res, (caddr_t)result);
904 		result->mappings.mappings_len = 0;
905 		result->mappings.mappings_val = NULL;
906 	}
907 	result->retcode = idmap_stat4prot(result->retcode);
908 	return (TRUE);
909 }
910 
911 
912 /* ARGSUSED */
913 int
914 idmap_prog_1_freeresult(SVCXPRT *transp, xdrproc_t xdr_result,
915 		caddr_t result)
916 {
917 	(void) xdr_free(xdr_result, result);
918 	return (TRUE);
919 }
920