xref: /titanic_41/usr/src/cmd/nscd/nscd_switch.c (revision db2bae3047e71d795bde12e3baa621f4b6cc8930)
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 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #include <stdlib.h>	/* getenv() */
28 #include <assert.h>
29 #include <unistd.h>
30 #include <string.h>
31 #include <pthread.h>
32 #include <dlfcn.h>
33 #include <nss_dbdefs.h>
34 #include <exec_attr.h>
35 #include <gssapi/gssapi.h>
36 #include "nscd_door.h"
37 #include "nscd_switch.h"
38 #include "nscd_log.h"
39 #include "nscd_frontend.h"
40 
41 #pragma weak nss_search = _nss_search
42 #define	nss_search	_nss_search
43 
44 extern rwlock_t nscd_smf_service_state_lock;
45 
46 /* nscd id: main, forker, or child */
47 extern int _whoami;
48 
49 static int
50 retry_test(nss_status_t res, int n, struct __nsw_lookup_v1 *lkp)
51 {
52 	if (res != NSS_TRYAGAIN && res !=  NSS_NISSERVDNS_TRYAGAIN) {
53 		if (res == NSS_SUCCESS) {
54 			__NSW_UNPAUSE_ACTION(lkp->actions[__NSW_TRYAGAIN]);
55 			__NSW_UNPAUSE_ACTION(
56 			    lkp->actions[__NSW_NISSERVDNS_TRYAGAIN]);
57 		}
58 		return (0);
59 	}
60 
61 	if ((res == NSS_TRYAGAIN &&
62 	    lkp->actions[__NSW_TRYAGAIN] == __NSW_TRYAGAIN_FOREVER) ||
63 	    (res == NSS_NISSERVDNS_TRYAGAIN &&
64 	    lkp->actions[__NSW_NISSERVDNS_TRYAGAIN] == __NSW_TRYAGAIN_FOREVER))
65 		return (1);
66 
67 	if (res == NSS_TRYAGAIN &&
68 	    lkp->actions[__NSW_TRYAGAIN] == __NSW_TRYAGAIN_NTIMES)
69 		if (n <= lkp->max_retries)
70 			return (1);
71 		else {
72 			lkp->actions[__NSW_TRYAGAIN] = __NSW_TRYAGAIN_PAUSED;
73 			return (0);
74 		}
75 
76 	if (res == NSS_NISSERVDNS_TRYAGAIN &&
77 	    lkp->actions[__NSW_NISSERVDNS_TRYAGAIN] == __NSW_TRYAGAIN_NTIMES)
78 		if (n <= lkp->max_retries)
79 			return (1);
80 		else {
81 			lkp->actions[__NSW_NISSERVDNS_TRYAGAIN] =
82 			    __NSW_TRYAGAIN_PAUSED;
83 			return (0);
84 		}
85 
86 	return (0);
87 }
88 
89 static thread_key_t loopback_key = THR_ONCE_KEY;
90 typedef struct lb_key {
91 	int		srci;
92 	int		dbi;
93 	int		fnum;
94 	int		*lb_flagp;
95 } lb_key_t;
96 
97 static int
98 set_loopback_key(lb_key_t *key) {
99 
100 	int		rc;
101 
102 	rc = thr_keycreate_once(&loopback_key, NULL);
103 	/* set key if not already set */
104 	if (rc == 0 && pthread_getspecific(loopback_key) == NULL)
105 		rc = thr_setspecific(loopback_key, key);
106 
107 	return (rc);
108 }
109 
110 static lb_key_t *
111 get_loopback_key(void) {
112 
113 	char		*me = "get_loopback_key";
114 	lb_key_t	*k = NULL;
115 
116 	k = pthread_getspecific(loopback_key);
117 
118 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
119 	(me, "get loopback key, key = %p\n", k);
120 
121 	return (k);
122 }
123 
124 static void
125 clear_loopback_key(lb_key_t *key) {
126 
127 	char		*me = "clear_loopback_key";
128 
129 	if (loopback_key != THR_ONCE_KEY && key != NULL) {
130 		/*
131 		 * key->lb_flagp points to the location of the
132 		 * flag, check_flag, in the stack where it was
133 		 * first set; clearing the flag tells that
134 		 * stack the loopback error has been resolved
135 		 */
136 		*key->lb_flagp = 0;
137 		(void) thr_setspecific(loopback_key, NULL);
138 	}
139 
140 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
141 	(me, "key %p cleared\n", key);
142 }
143 
144 static thread_key_t initf_key = THR_ONCE_KEY;
145 
146 static int
147 set_initf_key(void *pbuf) {
148 
149 	int		rc;
150 
151 	rc = thr_keycreate_once(&initf_key, NULL);
152 	if (rc == 0)
153 		rc = thr_setspecific(initf_key, pbuf);
154 
155 	return (rc);
156 }
157 
158 static void *
159 get_initf_key(void) {
160 
161 	char		*me = "get_initf_key";
162 	void		*pbuf;
163 
164 	pbuf = pthread_getspecific(initf_key);
165 
166 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
167 	(me, "got initf pbuf, key = %p\n", pbuf);
168 
169 	return (pbuf);
170 }
171 
172 static void
173 clear_initf_key(void) {
174 
175 	char		*me = "clear_initf_key";
176 
177 	(void) thr_setspecific(initf_key, NULL);
178 
179 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
180 	(me, "initf pbuf cleared\n");
181 }
182 
183 /*
184  * Call the input initf function to extract the
185  * NSS front end parameters and examine them to
186  * determine if an NSS lookup is to be performed
187  * on a regular or a pseudo (called from compat
188  * backend) database. Then set the necessary
189  * parameters for later data structures creation
190  * and processing.
191  */
192 static nscd_rc_t
193 getparams(
194 	int			search_fnum,
195 	nss_db_initf_t		initf,
196 	nscd_nsw_params_t	*params)
197 {
198 
199 	nscd_rc_t	rc = NSCD_SUCCESS;
200 	nss_db_params_t	*p;
201 	int		j;
202 	char		*dbn;
203 	const char	*n;
204 	char		*me = "getparams";
205 
206 	p = &params->p;
207 	(void) memset(p, 0, sizeof (*p));
208 	(*initf)(p);
209 	params->dbi = -1;
210 	params->cfgdbi = -1;
211 	params->compati = -1;
212 	params->dnsi = -1;
213 
214 	/* map database name to index */
215 	n = p->name;
216 	for (j = 0; j < NSCD_NUM_DB; j++) {
217 		dbn = NSCD_NSW_DB_NAME(j);
218 		if (*n != *dbn)
219 			continue;
220 		if (strcmp(n, dbn) == 0) {
221 			params->dbi = j;
222 			if (*n != 'h' && *n != 'i' && *n != 's' && *n != 'a')
223 				break;
224 			if (strcmp(n, NSS_DBNAM_HOSTS) == 0 &&
225 			    search_fnum == NSS_DBOP_HOSTS_BYNAME)
226 				params->dnsi = 0;
227 			else if (strcmp(n, NSS_DBNAM_IPNODES) == 0 &&
228 			    search_fnum == NSS_DBOP_IPNODES_BYNAME)
229 				params->dnsi = 1;
230 			else if (strcmp(n, NSS_DBNAM_SHADOW) == 0)
231 				params->privdb = 1;
232 			break;
233 		}
234 	}
235 
236 	/*
237 	 * use the switch policy for passwd_compat or
238 	 * group_compat?
239 	 */
240 	if (p->config_name != NULL) {
241 
242 		n = p->config_name;
243 		for (j = 0; j < NSCD_NUM_DB; j++) {
244 			dbn = NSCD_NSW_DB_NAME(j);
245 			if (*n == *dbn) {
246 				if (strcmp(n, dbn) == 0) {
247 					params->cfgdbi = j;
248 					break;
249 				}
250 			}
251 		}
252 	}
253 
254 	/* map the database name to the pseudo database index */
255 	if (params->cfgdbi != -1) {
256 		if (strstr(p->config_name, "_compat") != NULL) {
257 			n = p->name;
258 			for (j = params->cfgdbi; j < NSCD_NUM_DB; j++) {
259 				dbn = NSCD_NSW_DB_NAME(j);
260 				if (*n == *dbn) {
261 					if (strcmp(n, dbn) == 0) {
262 						params->compati = j;
263 						break;
264 					}
265 				}
266 			}
267 		}
268 	}
269 
270 	/*
271 	 * if unsupported database, let caller determine what to do next
272 	 */
273 	if (params->dbi == -1) {
274 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
275 		(me, "unsupported database: %s\n", p->name);
276 		return (NSCD_CFG_UNSUPPORTED_SWITCH_DB);
277 	}
278 
279 	return (rc);
280 }
281 
282 static void
283 nscd_initf(nss_db_params_t	*p)
284 {
285 	nss_pheader_t		*pbuf;
286 	nssuint_t		off;
287 	nss_dbd_t		*pdbd;
288 	char			*me = "nscd_initf";
289 
290 	pbuf = (nss_pheader_t *)get_initf_key();
291 	if (pbuf == NULL) {
292 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
293 		(me, "ERROR: initf key not set\n");
294 		return;
295 	}
296 
297 	if (pbuf->dbd_len <= sizeof (nss_dbd_t)) {
298 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
299 		(me, "invalid db front params data ? dbd_len = %d\n",
300 		    pbuf->dbd_len);
301 		return;
302 	}
303 
304 	off = pbuf->dbd_off;
305 	pdbd = (nss_dbd_t *)((void *)((char *)pbuf + off));
306 
307 	p->name = (char *)pdbd + pdbd->o_name;
308 	p->config_name = (char *)pdbd + pdbd->o_config_name;
309 	p->default_config = (char *)pdbd + pdbd->o_default_config;
310 	p->flags = (enum nss_dbp_flags)pdbd->flags;
311 	(void) memcpy(&p->private, &pbuf->nscdpriv, sizeof (p->private));
312 
313 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
314 	(me, "db frontend params: name =%s, config_name = %s, "
315 	"default_config = %s, flags = %x\n", p->name,
316 	    (p->config_name && *p->config_name != '\0' ?
317 	    p->config_name : "<NOT SPECIFIED>"),
318 	    (p->default_config && *p->default_config != '\0' ?
319 	    p->default_config : "<NOT SPECIFIED>"),
320 	    p->flags);
321 }
322 
323 
324 static void
325 trace_result(
326 	int		dbi,
327 	int		srci,
328 	int		op,
329 	nss_status_t	res,
330 	nss_XbyY_args_t	*arg)
331 {
332 	char	*res_str;
333 	char	*src = "?";
334 	char	*db = "?";
335 	char	*data_str = "<NOT STRING FORMAT>";
336 	int	data_len = 0;
337 	char	*me = "trace_result";
338 
339 	switch (res) {
340 	case NSS_SUCCESS:
341 		res_str = "NSS_SUCCESS";
342 		break;
343 	case NSS_NOTFOUND:
344 		res_str = "NSS_NOTFOUND";
345 		break;
346 	case NSS_UNAVAIL:
347 		res_str = "NSS_UNAVAIL";
348 		break;
349 	case NSS_TRYAGAIN:
350 		res_str = "NSS_TRYAGAIN";
351 		break;
352 	case NSS_NISSERVDNS_TRYAGAIN:
353 		res_str = "NSS_NISSERVDNS_TRYAGAIN";
354 		break;
355 	default:
356 		res_str = "UNKNOWN STATUS";
357 		break;
358 	}
359 
360 	if (dbi != -1)
361 		db = NSCD_NSW_DB_NAME(dbi);
362 	if (srci != -1)
363 		src = NSCD_NSW_SRC_NAME(srci);
364 
365 	if (arg->buf.result == NULL) {
366 		data_str = arg->buf.buffer;
367 		data_len = arg->returnlen;
368 	}
369 
370 	if (res == NSS_SUCCESS) {
371 		_nscd_logit(me, "%s: database: %s, operation: %d, "
372 		    "source: %s returned >>%s<<, length = %d\n",
373 		    res_str, db, op, src, data_str, data_len);
374 		return;
375 	}
376 
377 	_nscd_logit(me, "%s: database: %s, operation: %d, source: %s, "
378 	    "erange= %d, herrno: %s (%d)\n",
379 	    res_str, db, op, src, arg->erange, hstrerror(arg->h_errno),
380 	    arg->h_errno);
381 }
382 
383 /*
384  * Determine if a request should be done locally in the getXbyY caller's
385  * process. Return none zero if yes, 0 otherwise. This should be called
386  * before the switch engine steps through the backends/sources.
387  * This function returns 1 if:
388  *   -- the database is exec_attr and the search_flag is GET_ALL
389  */
390 static int
391 try_local(
392 	int			dbi,
393 	void			*arg)
394 {
395 	struct nss_XbyY_args	*ap = (struct nss_XbyY_args *)arg;
396 	_priv_execattr		*ep;
397 	int			rc = 0;
398 	char			*me = "try_local";
399 
400 	if (strcmp(NSCD_NSW_DB_NAME(dbi), NSS_DBNAM_EXECATTR) == 0) {
401 		if ((ep = ap->key.attrp) != NULL && ep->search_flag == GET_ALL)
402 			rc = 1;
403 	}
404 
405 	if (rc != 0) {
406 
407 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
408 		(me, "TRYLOCAL: exec_attr:GET_ALL\n");
409 	}
410 
411 	return (rc);
412 }
413 
414 /*
415  * Determine if a request should be done locally in the getXbyY caller's
416  * process. Return none zero if yes, 0 otherwise. This should be called
417  * before the switch engine invokes any backend.
418  * This function returns 1 if:
419  *   -- the database is shadow and the source is nisplus
420  */
421 static int
422 try_local2(
423 	int	dbi,
424 	int	srci)
425 {
426 	int	rc = 0;
427 	char	*me = "try_local2";
428 
429 	if (*NSCD_NSW_DB_NAME(dbi) == 's' &&
430 	    strcmp(NSCD_NSW_DB_NAME(dbi), NSS_DBNAM_SHADOW) == 0) {
431 		if (strcmp(NSCD_NSW_SRC_NAME(srci), "nisplus") == 0)
432 			rc = 1;
433 	}
434 
435 	if (rc != 0) {
436 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
437 		(me, "TRYLOCAL: database: shadow, source: nisplus\n");
438 	}
439 
440 	return (rc);
441 }
442 
443 static nscd_rc_t
444 get_lib_func(void **handle, void **func, mutex_t *lock,
445 	char *lib, char *name, void **func_p)
446 {
447 	char	*me = "get_lib_func";
448 	void	*sym;
449 
450 	if (func_p != NULL && *handle != NULL && *func != NULL) {
451 		*func_p = *func;
452 		return (NSCD_SUCCESS);
453 	}
454 
455 	(void) mutex_lock(lock);
456 
457 	/* close the handle if requested */
458 	if (func_p == NULL) {
459 		if (*handle != NULL) {
460 			(void) dlclose(*handle);
461 			*handle = NULL;
462 			*func = NULL;
463 		}
464 		(void) mutex_unlock(lock);
465 		return (NSCD_SUCCESS);
466 	}
467 
468 	if (*handle != NULL && *func != NULL) {
469 		*func_p = *func;
470 		(void) mutex_unlock(lock);
471 		return (NSCD_SUCCESS);
472 	}
473 
474 	if (*handle == NULL) {
475 		*handle = dlopen(lib, RTLD_LAZY);
476 		if (*handle == NULL) {
477 			_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_ERROR)
478 			(me, "unable to dlopen %s\n", lib);
479 			(void) mutex_unlock(lock);
480 			return (NSCD_CFG_DLOPEN_ERROR);
481 		}
482 	}
483 
484 	if ((sym = dlsym(*handle, name)) == NULL) {
485 
486 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_ERROR)
487 		(me, "unable to find symbol %s:%s\n", lib, name);
488 		(void) mutex_unlock(lock);
489 		return (NSCD_CFG_DLSYM_ERROR);
490 	} else {
491 		*func_p = sym;
492 		*func = sym;
493 	}
494 
495 	(void) mutex_unlock(lock);
496 	return (NSCD_SUCCESS);
497 }
498 
499 static nscd_rc_t
500 get_libc_nss_search(void **func_p)
501 {
502 	static void	*handle = NULL;
503 	static void	*func = NULL;
504 	static mutex_t	lock = DEFAULTMUTEX;
505 
506 	return (get_lib_func(&handle, &func, &lock,
507 	    "libc.so", "nss_search", func_p));
508 }
509 
510 static nscd_rc_t
511 get_gss_func(void **func_p)
512 {
513 	static void	*handle = NULL;
514 	static void	*func = NULL;
515 	static mutex_t	lock = DEFAULTMUTEX;
516 
517 	return (get_lib_func(&handle, &func, &lock,
518 	    "libgss.so", "gss_inquire_cred", func_p));
519 }
520 
521 /*
522  * get_dns_funcs returns pointers to gethostbyname functions in the
523  * dynamically loaded nss_dns & nss_mdns modules that return host
524  * lookup results along with the TTL value in the DNS resource
525  * records. The dnsi parameter indicates whether the lookup database
526  * is hosts(0) or ipnodes(1). The srcname parameter identifies the DNS
527  * module: dns/mdns and the function returns the address of the specific
528  * gethostbyname function in func_p variable.
529  */
530 static nscd_rc_t
531 get_dns_funcs(int dnsi, nss_status_t (**func_p)(), const char *srcname)
532 {
533 	int		si;
534 	void		**funcpp;
535 	static void	*handle[2] = { NULL, NULL };
536 	static mutex_t	func_lock[2] = { DEFAULTMUTEX, DEFAULTMUTEX };
537 	static void 	*func[2][2] = {{NULL, NULL}, {NULL, NULL}};
538 	static const char	*lib[2] = { "nss_dns.so.1", "nss_mdns.so.1" };
539 	static const char 	*func_name[2][2] =
540 		{{ "_nss_get_dns_hosts_name", "_nss_get_dns_ipnodes_name" },
541 		{ "_nss_get_mdns_hosts_name", "_nss_get_mdns_ipnodes_name" }};
542 
543 	/* source index: 0 = dns, 1 = mdns */
544 	if (strcmp(srcname, "dns") == 0)
545 		si = 0;
546 	else
547 		si = 1;
548 
549 	/*
550 	 * function index (func[si][dnsi]):
551 	 * [0,0] = dns/hosts, [0,1] = dns/ipnodes,
552 	 * [1,0] = mdns/hosts, [1,1] = mdns/ipnodes
553 	 */
554 
555 	if (dnsi < 0) { /* close handle */
556 		funcpp = NULL;
557 		(void) mutex_lock(&func_lock[si]);
558 		func[si][0] = NULL;
559 		func[si][1] = NULL;
560 		(void) mutex_unlock(&func_lock[si]);
561 	} else
562 		funcpp = (void **)func_p;
563 
564 	return (get_lib_func(&handle[si], &func[si][dnsi], &func_lock[si],
565 	    (char *)lib[si], (char *)func_name[si][dnsi], funcpp));
566 }
567 
568 static nss_status_t
569 search_dns_withttl(nscd_sw_return_t *swret, const char *srcname, int dnsi)
570 {
571 	nss_status_t	(*func)();
572 	nss_status_t	res = NSS_UNAVAIL;
573 	nscd_rc_t	rc;
574 
575 	swret->noarg = 0;
576 	if (strcmp(srcname, "dns") != 0 && strcmp(srcname, "mdns") != 0)
577 		return (NSS_ERROR);
578 
579 	rc = get_dns_funcs(dnsi, &func, srcname);
580 	if (rc == NSCD_SUCCESS) {
581 		/*
582 		 * data_len in the packed buf header may be changed
583 		 * by the dns or mdns backend, reset it just in
584 		 * case
585 		 */
586 		((nss_pheader_t *)swret->pbuf)->data_len =
587 		    swret->datalen;
588 		res = (func)(NULL, &swret->pbuf, &swret->pbufsiz);
589 	}
590 	return (res);
591 }
592 
593 /*
594  * Returns a flag to indicate if needs to fall back to the
595  * main nscd when a per-user lookup failed with rc NSS_NOTFOUND.
596  */
597 static int
598 set_fallback_flag(char *srcname, nss_status_t rc)
599 {
600 	char	*me = "set_fallback_flag";
601 	if (strcmp(srcname, "ldap") == 0 && rc == NSS_NOTFOUND) {
602 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
603 		(me, "NSS_NOTFOUND (ldap): fallback to main nscd "
604 		"may be needed\n");
605 		return (1);
606 	}
607 	return (0);
608 }
609 
610 nss_status_t
611 nss_search(nss_db_root_t *rootp, nss_db_initf_t initf, int search_fnum,
612 	void *search_args)
613 {
614 	char			*me = "nss_search";
615 	nss_status_t		res = NSS_UNAVAIL;
616 	nscd_nsw_state_t	*s = NULL;
617 	int			n_src;
618 	unsigned int		status_vec = 0;
619 	int			dbi, srci = -1;
620 	int			check_loopback = 0;
621 	int			state_thr = 0;
622 	lb_key_t		key, *k = NULL;
623 	nss_db_root_t		root_db;
624 	nscd_nsw_params_t	params;
625 	nscd_sw_return_t	*swret;
626 
627 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
628 	(me, "rootp = %p, initf = %p, search_fnum = %d, "
629 	    "search_args = %p\n", rootp, initf,
630 	    search_fnum, search_args);
631 
632 	NSCD_SW_STATS_G.lookup_request_received_g++;
633 	NSCD_SW_STATS_G.lookup_request_in_progress_g++;
634 	NSCD_SW_STATS_G.lookup_request_queued_g++;
635 
636 	/* determine db index, cfg db index, etc */
637 	if (getparams(search_fnum, initf, &params) ==
638 	    NSCD_CFG_UNSUPPORTED_SWITCH_DB) {
639 		/*
640 		 * if unsupported database and the request is from the
641 		 * the door, tell the door client to try it locally
642 		 */
643 		if (initf == nscd_initf) {
644 			res = NSS_TRYLOCAL;
645 			goto error_exit;
646 		} else { /* otherwise, let libc:nss_search() handle it */
647 			nss_status_t	(*func)();
648 
649 			if (get_libc_nss_search((void **)&func) ==
650 			    NSCD_SUCCESS)
651 				return ((func)(rootp, initf, search_fnum,
652 				    search_args));
653 			else
654 				goto error_exit;
655 		}
656 	}
657 	dbi = params.dbi;
658 
659 	/* get address of the switch engine return data area */
660 	if (initf == nscd_initf) {
661 		swret = (nscd_sw_return_t *)params.p.private;
662 		swret->srci = -1;
663 	} else {
664 		swret = NULL;
665 		params.dnsi = -1;
666 	}
667 
668 	/*
669 	 * for door request that should be processed by the client,
670 	 * send it back with status NSS_TRYLOCAL
671 	 */
672 	if (initf == nscd_initf && try_local(dbi, search_args) == 1) {
673 		res = NSS_TRYLOCAL;
674 		goto error_exit;
675 	}
676 
677 	NSCD_SW_STATS(dbi).lookup_request_received++;
678 	NSCD_SW_STATS(dbi).lookup_request_in_progress++;
679 	NSCD_SW_STATS(dbi).lookup_request_queued++;
680 
681 	/* if lookup not enabled, return NSS_UNAVAIL  */
682 	if (!(NSCD_SW_CFG_G.enable_lookup_g == nscd_true &&
683 	    NSCD_SW_CFG(dbi).enable_lookup == nscd_true)) {
684 
685 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
686 		(me, "lookup not enabled for %s\n", NSCD_NSW_DB_NAME(dbi));
687 
688 		goto error_exit;
689 	}
690 
691 	/* determine if loopback checking is configured */
692 	if (NSCD_SW_CFG_G.enable_loopback_checking_g == nscd_true &&
693 	    NSCD_SW_CFG(dbi).enable_loopback_checking == nscd_true) {
694 		check_loopback = 1;
695 
696 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
697 		(me, "loopback checking enabled for %s\n",
698 		    NSCD_NSW_DB_NAME(dbi));
699 	}
700 
701 	if (check_loopback) {
702 		k = get_loopback_key();
703 		if (k != NULL) {
704 			if (k->dbi != dbi || k->fnum != search_fnum) {
705 				clear_loopback_key(k);
706 				k = NULL;
707 			}
708 		}
709 	}
710 
711 	if (s == 0) {
712 		nscd_rc_t	rc;
713 
714 		if (check_loopback) {
715 			rc = _nscd_get_nsw_state_thread(&root_db, &params);
716 			state_thr = 1;
717 		} else
718 			rc = _nscd_get_nsw_state(&root_db, &params);
719 
720 		NSCD_SW_STATS_G.lookup_request_queued_g--;
721 		NSCD_SW_STATS(dbi).lookup_request_queued--;
722 
723 		if (rc != NSCD_SUCCESS)
724 				goto error_exit;
725 
726 		s = (nscd_nsw_state_t *)root_db.s;
727 	}
728 
729 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
730 	(me, "database = %s, config = >>%s<<\n", NSCD_NSW_DB_NAME(dbi),
731 	    (*s->nsw_cfg_p)->nsw_cfg_str);
732 
733 	for (n_src = 0;  n_src < s->max_src;  n_src++) {
734 		nss_backend_t		*be = NULL;
735 		nss_backend_op_t	funcp = NULL;
736 		struct __nsw_lookup_v1	*lkp;
737 		int			smf_state;
738 		int			n_loop = 0;
739 		int			max_retry = 10;
740 
741 		res = NSS_UNAVAIL;
742 
743 		if (n_src == 0)
744 			lkp = s->config->lookups;
745 		else
746 			lkp = lkp->next;
747 
748 		/* set the number of max. retries */
749 		if (lkp->actions[__NSW_TRYAGAIN] == __NSW_TRYAGAIN_NTIMES)
750 			max_retry = lkp->max_retries;
751 
752 		srci = (*s->nsw_cfg_p)->src_idx[n_src];
753 		if (swret != NULL)
754 			swret->srci = srci;
755 
756 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
757 		(me, "nsw source = %s\n", NSCD_NSW_SRC_NAME(srci));
758 
759 		/* if no privilege to look up, skip */
760 		if (params.privdb == 1 && swret != NULL &&
761 		    strcmp(NSCD_NSW_SRC_NAME(srci), "files") == 0 &&
762 		    _nscd_check_client_read_priv() != 0) {
763 			_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
764 			(me, "no privilege to look up, skip source\n");
765 
766 			goto next_src;
767 		}
768 
769 		/* get state of the (backend) client service */
770 		smf_state = _nscd_get_smf_state(srci, dbi, 0);
771 
772 		/* stop if the source is one that should be TRYLOCAL */
773 		if (initf == nscd_initf &&	/* request is from the door */
774 		    (smf_state == NSCD_SVC_STATE_UNSUPPORTED_SRC ||
775 		    (smf_state == NSCD_SVC_STATE_FOREIGN_SRC &&
776 		    s->be_version_p[n_src] == NULL) ||
777 		    (params.privdb && try_local2(dbi, srci) == 1))) {
778 			_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
779 			(me, "returning TRYLOCAL ... \n");
780 			res = NSS_TRYLOCAL;
781 			goto free_nsw_state;
782 		}
783 
784 		if (check_loopback && k != NULL) {
785 
786 			if (k->srci == srci && k->dbi == dbi)
787 				if (k->fnum == search_fnum) {
788 
789 					_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE,
790 					    NSCD_LOG_LEVEL_DEBUG)
791 					(me, "loopback detected: "
792 					    "source = %s, database = %s "
793 					    "search fnum = %d\n",
794 					    NSCD_NSW_SRC_NAME(srci),
795 					    NSCD_NSW_DB_NAME(dbi), search_fnum);
796 
797 				NSCD_SW_STATS_G.loopback_nsw_db_skipped_g++;
798 				NSCD_SW_STATS(dbi).loopback_nsw_db_skipped++;
799 					continue;
800 				}
801 		}
802 
803 		be = s->be[n_src];
804 		if (be != NULL)
805 			funcp = NSS_LOOKUP_DBOP(be, search_fnum);
806 
807 		/* request could be from within nscd so check states again */
808 		if (be == NULL || (params.dnsi < 0 && (funcp == NULL ||
809 		    (smf_state != NSCD_SVC_STATE_UNINITED &&
810 		    smf_state != NSCD_SVC_STATE_UNSUPPORTED_SRC &&
811 		    smf_state != NSCD_SVC_STATE_FOREIGN_SRC &&
812 		    smf_state < SCF_STATE_ONLINE)))) {
813 
814 			_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE,
815 			    NSCD_LOG_LEVEL_DEBUG)
816 			(me, "unable to look up source %s: be = %p, "
817 			"smf state = %d, funcp = %p\n",
818 			    NSCD_NSW_SRC_NAME(srci), be, smf_state, funcp);
819 
820 			goto next_src;
821 		}
822 
823 		do {
824 			/*
825 			 * we can only retry max_retry times,
826 			 * otherwise threads may get stuck in this
827 			 * do-while loop forever
828 			 */
829 			if (n_loop > max_retry) {
830 				if (swret != NULL)
831 					res = NSS_TRYLOCAL;
832 				goto free_nsw_state;
833 			}
834 
835 			/*
836 			 * set up to prevent loopback
837 			 */
838 			if (check_loopback && k == NULL) {
839 				key.srci = srci;
840 				key.dbi = dbi;
841 				key.fnum = search_fnum;
842 				key.lb_flagp = &check_loopback;
843 				(void) set_loopback_key(&key);
844 				k = &key;
845 			}
846 
847 			_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE,
848 			    NSCD_LOG_LEVEL_DEBUG)
849 			(me, "looking up source = %s, loop# = %d \n",
850 			    NSCD_NSW_SRC_NAME(srci), n_loop);
851 
852 			/*
853 			 * search the backend, if hosts lookups,
854 			 * try to get the hosts data with ttl first
855 			 */
856 			if (params.dnsi >= 0) {
857 				res = search_dns_withttl(swret,
858 				    NSCD_NSW_SRC_NAME(srci), params.dnsi);
859 				/*
860 				 * if not able to get ttl, fall back
861 				 * to the regular backend call
862 				 */
863 				if (res == NSS_ERROR)
864 					res = (*funcp)(be, search_args);
865 				else {
866 					/*
867 					 * status/result are in the
868 					 * packed buffer, not
869 					 * search_args
870 					 */
871 					swret->noarg = 1;
872 				}
873 			} else
874 				res = (*funcp)(be, search_args);
875 			if (swret != NULL)
876 				swret->errnum = errno;
877 
878 			/*
879 			 * backend is not up, check and update the
880 			 * smf state table
881 			 */
882 			if (res == NSS_UNAVAIL)
883 				(void) _nscd_get_smf_state(srci, dbi, 1);
884 
885 			/*
886 			 * may need to fall back to use the main nscd
887 			 * if per-user lookup
888 			 */
889 			if (_whoami == NSCD_CHILD && swret != NULL)
890 				swret->fallback = set_fallback_flag(
891 				    NSCD_NSW_SRC_NAME(srci), res);
892 
893 			_NSCD_LOG_IF(NSCD_LOG_SWITCH_ENGINE,
894 			    NSCD_LOG_LEVEL_DEBUG) {
895 
896 				/*
897 				 * set up to trace the result/status
898 				 * of the dns/ttl lookup
899 				 */
900 				if (swret != NULL && swret->noarg == 1) {
901 					nss_pheader_t *phdr;
902 					struct nss_XbyY_args *arg;
903 					arg = (struct nss_XbyY_args *)
904 					    search_args;
905 					phdr = (nss_pheader_t *)swret->pbuf;
906 					arg->buf.buffer = (char *)phdr +
907 					    phdr->data_off;
908 					arg->returnlen = phdr->data_len;
909 					if (phdr->p_errno == ERANGE)
910 						arg->erange = 1;
911 					arg->h_errno = phdr->p_herrno;
912 				}
913 
914 				trace_result(dbi, srci, search_fnum, res,
915 				    (nss_XbyY_args_t *)search_args);
916 			}
917 
918 			n_loop++;
919 		} while (retry_test(res, n_loop, lkp));
920 
921 		next_src:
922 
923 		status_vec |= (1 << res);
924 
925 		if (__NSW_ACTION_V1(lkp, res) == __NSW_RETURN) {
926 			break;
927 		}
928 	}
929 
930 	free_nsw_state:
931 
932 	if (state_thr == 1)
933 		_nscd_put_nsw_state_thread(s);
934 	else
935 		_nscd_put_nsw_state(s);
936 	if (check_loopback && k != NULL)
937 		clear_loopback_key(k);
938 
939 	if (res != NSS_SUCCESS)
940 		goto error_exit;
941 
942 	NSCD_SW_STATS_G.lookup_request_succeeded_g++;
943 	NSCD_SW_STATS(dbi).lookup_request_succeeded++;
944 	NSCD_SW_STATS_G.lookup_request_in_progress_g--;
945 	NSCD_SW_STATS(dbi).lookup_request_in_progress--;
946 
947 	return (NSS_SUCCESS);
948 
949 	error_exit:
950 
951 	NSCD_SW_STATS_G.lookup_request_failed_g++;
952 	NSCD_SW_STATS_G.lookup_request_in_progress_g--;
953 	NSCD_SW_STATS(dbi).lookup_request_failed++;
954 	NSCD_SW_STATS(dbi).lookup_request_in_progress--;
955 
956 	return (res);
957 }
958 
959 
960 /* ===> get/set/endent */
961 
962 static void		nss_setent_u(nss_db_root_t *,
963 				    nss_db_initf_t,
964 				    nss_getent_t *);
965 static nss_status_t	nss_getent_u(nss_db_root_t *,
966 				    nss_db_initf_t,
967 				    nss_getent_t *,
968 				    void *);
969 static void		nss_endent_u(nss_db_root_t *,
970 				    nss_db_initf_t,
971 				    nss_getent_t *);
972 
973 void
974 nss_setent(nss_db_root_t *rootp, nss_db_initf_t initf,
975 	nss_getent_t *contextpp)
976 {
977 	if (contextpp == 0)
978 		return;
979 	nss_setent_u(rootp, initf, contextpp);
980 }
981 
982 nss_status_t
983 nss_getent(nss_db_root_t *rootp, nss_db_initf_t initf, nss_getent_t *contextpp,
984 	void *args)
985 {
986 	nss_status_t		status;
987 
988 	if (contextpp == 0) {
989 		return (NSS_UNAVAIL);
990 	}
991 	status = nss_getent_u(rootp, initf, contextpp, args);
992 	return (status);
993 }
994 
995 void
996 nss_endent(nss_db_root_t *rootp, nss_db_initf_t initf,
997 	nss_getent_t *contextpp)
998 {
999 	if (contextpp == 0)
1000 		return;
1001 	nss_endent_u(rootp, initf, contextpp);
1002 }
1003 
1004 /*ARGSUSED*/
1005 static void
1006 end_iter_u(nss_db_root_t *rootp, struct nss_getent_context *contextp)
1007 {
1008 	nscd_getent_context_t	*ctx;
1009 	nscd_nsw_state_t	*s;
1010 	nss_backend_t		*be;
1011 	int			n_src;
1012 
1013 	ctx = (nscd_getent_context_t *)contextp;
1014 	s = ctx->nsw_state;
1015 	n_src = ctx->n_src;
1016 	be = ctx->be;
1017 
1018 	if (s != 0) {
1019 		if (n_src < s->max_src && be != 0) {
1020 			(void) NSS_INVOKE_DBOP(be, NSS_DBOP_ENDENT, 0);
1021 			ctx->be = 0;  /* Should be unnecessary, but hey */
1022 		}
1023 	}
1024 	ctx->n_src = 0;
1025 }
1026 
1027 static void
1028 nss_setent_u(nss_db_root_t *rootp, nss_db_initf_t initf,
1029 	nss_getent_t *contextpp)
1030 {
1031 	char			*me = "nss_setent_u";
1032 	nscd_nsw_state_t	*s;
1033 	nscd_getent_context_t	*contextp;
1034 	nscd_nsw_params_t	params;
1035 	nss_db_root_t		root;
1036 	nss_backend_t		*be;
1037 	int			n_src, i;
1038 	nscd_sw_return_t	*swret = NULL;
1039 
1040 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1041 	(me, "rootp = %p, initf = %p, contextpp = %p \n",
1042 	    rootp, initf, contextpp);
1043 
1044 	/*
1045 	 * Get the nsw db index via the initf function. If unsupported
1046 	 * database, no need to continue
1047 	 */
1048 	if (getparams(-1, initf, &params) == NSCD_CFG_UNSUPPORTED_SWITCH_DB)
1049 		return;
1050 
1051 	/* get address of the switch engine return data area */
1052 	if (initf == nscd_initf)
1053 		swret = (nscd_sw_return_t *)params.p.private;
1054 
1055 	/* if no privilege to look up, return */
1056 	if (params.privdb == 1 && swret != NULL &&
1057 	    _nscd_check_client_read_priv() != 0) {
1058 
1059 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1060 		(me, "no privilege \n");
1061 		return;
1062 	}
1063 
1064 	if ((contextp = (nscd_getent_context_t *)contextpp->ctx) == 0) {
1065 		if ((_nscd_get_getent_ctx(contextpp, &params)) !=
1066 		    NSCD_SUCCESS) {
1067 			return;
1068 		}
1069 		contextp = (nscd_getent_context_t *)contextpp->ctx;
1070 	}
1071 	s = contextp->nsw_state;
1072 
1073 	if (s == 0) {
1074 		if (_nscd_get_nsw_state(&root, &params) !=
1075 		    NSCD_SUCCESS) {
1076 			return;
1077 		}
1078 		s = (nscd_nsw_state_t *)root.s;
1079 		contextp->nsw_state = s;
1080 
1081 	} else {
1082 		s	= contextp->nsw_state;
1083 		n_src	= contextp->n_src;
1084 		be	= contextp->be;
1085 		if (n_src == 0 && be != 0) {
1086 			/*
1087 			 * Optimization:  don't do endent, don't change
1088 			 *   backends, just do the setent.  Look Ma, no locks
1089 			 *   (nor any context that needs updating).
1090 			 */
1091 			(void) NSS_INVOKE_DBOP(be, NSS_DBOP_SETENT, 0);
1092 			return;
1093 		}
1094 		if (n_src < s->max_src && be != 0) {
1095 			(void) NSS_INVOKE_DBOP(be, NSS_DBOP_ENDENT, 0);
1096 			contextp->be = 0;	/* Play it safe */
1097 		}
1098 	}
1099 	for (n_src = 0, be = 0; n_src < s->max_src &&
1100 	    (be = s->be[n_src]) == 0; n_src++) {
1101 		;
1102 	}
1103 
1104 	contextp->n_src	= n_src;
1105 	contextp->be	= be;
1106 
1107 	if (be == 0) {
1108 		/* Things are broken enough that we can't do setent/getent */
1109 		nss_endent_u(rootp, initf, contextpp);
1110 		return;
1111 	}
1112 
1113 	/*
1114 	 * make sure all the backends are supported
1115 	 */
1116 	for (i = 0; i < s->max_src; i++) {
1117 		int	st, srci;
1118 
1119 		if (s->be[i] == NULL)
1120 			continue;
1121 
1122 		srci = (*s->nsw_cfg_p)->src_idx[i];
1123 		st = _nscd_get_smf_state(srci, params.dbi, 1);
1124 		if (st == NSCD_SVC_STATE_UNSUPPORTED_SRC ||
1125 		    (st == NSCD_SVC_STATE_FOREIGN_SRC &&
1126 		    s->be_version_p[i] == NULL && initf == nscd_initf) ||
1127 		    st == NSCD_SVC_STATE_UNINITED ||
1128 		    (params.privdb &&
1129 		    try_local2(params.dbi, srci) == 1)) {
1130 			nss_endent_u(rootp, initf, contextpp);
1131 
1132 			_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE,
1133 			    NSCD_LOG_LEVEL_DEBUG)
1134 			(me, "backend (%s) not available (state = %d)\n",
1135 			    NSCD_NSW_SRC_NAME(srci), st);
1136 
1137 			return;
1138 		}
1139 	}
1140 
1141 	(void) NSS_INVOKE_DBOP(be, NSS_DBOP_SETENT, 0);
1142 }
1143 
1144 nss_status_t
1145 nss_getent_u(nss_db_root_t *rootp, nss_db_initf_t initf,
1146 	nss_getent_t *contextpp, void *args)
1147 {
1148 	char			*me = "nss_getent_u";
1149 	nscd_nsw_state_t	*s;
1150 	nscd_getent_context_t	*contextp;
1151 	int			n_src;
1152 	nss_backend_t		*be;
1153 
1154 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1155 	(me, "rootp = %p, initf = %p, contextpp = %p, args = %p\n",
1156 	    rootp, initf, contextpp, args);
1157 
1158 	if ((contextp = (nscd_getent_context_t *)contextpp->ctx) == 0) {
1159 		nss_setent_u(rootp, initf, contextpp);
1160 		if ((contextp = (nscd_getent_context_t *)contextpp->ctx) == 0) {
1161 			/* Give up */
1162 			_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE,
1163 			    NSCD_LOG_LEVEL_ERROR)
1164 			(me, "not able to obtain getent context ... give up\n");
1165 
1166 			return (NSS_UNAVAIL);
1167 		}
1168 	}
1169 
1170 	s	= contextp->nsw_state;
1171 	n_src	= contextp->n_src;
1172 	be	= contextp->be;
1173 
1174 	if (s == 0) {
1175 		/*
1176 		 * We've done an end_iter() and haven't done nss_setent()
1177 		 * or nss_endent() since;  we should stick in this state
1178 		 * until the caller invokes one of those two routines.
1179 		 */
1180 		return (NSS_SUCCESS);
1181 	}
1182 
1183 	while (n_src < s->max_src) {
1184 		nss_status_t		res;
1185 		struct __nsw_lookup_v1	*lkp = NULL;
1186 		int			n;
1187 
1188 		/* get the nsw config for the current source */
1189 		lkp = s->config->lookups;
1190 		for (n = 0; n < n_src; n++)
1191 			lkp = lkp->next;
1192 
1193 		if (be == 0) {
1194 			/* If it's null it's a bug, but let's play safe */
1195 			res = NSS_UNAVAIL;
1196 		} else {
1197 			_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE,
1198 			    NSCD_LOG_LEVEL_DEBUG)
1199 			(me, "database: %s, backend: %s, nsswitch config: %s\n",
1200 			    NSCD_NSW_DB_NAME(s->dbi),
1201 			    lkp->service_name,
1202 			    (*s->nsw_cfg_p)->nsw_cfg_str);
1203 
1204 			res = NSS_INVOKE_DBOP(be, NSS_DBOP_GETENT, args);
1205 		}
1206 
1207 		if (__NSW_ACTION_V1(lkp, res) == __NSW_RETURN) {
1208 			if (res != __NSW_SUCCESS) {
1209 				end_iter_u(rootp,
1210 				    (struct nss_getent_context *)contextp);
1211 			}
1212 			return (res);
1213 		}
1214 		(void) NSS_INVOKE_DBOP(be, NSS_DBOP_ENDENT, 0);
1215 		do {
1216 			n_src++;
1217 		} while (n_src < s->max_src &&
1218 		    (be = s->be[n_src]) == 0);
1219 		if (be == 0) {
1220 			/*
1221 			 * This is the case where we failed to get the backend
1222 			 * for the last source. We exhausted all sources.
1223 			 */
1224 			nss_endent_u(rootp, initf, contextpp);
1225 			return (NSS_NOTFOUND);
1226 		}
1227 		contextp->n_src	= n_src;
1228 		contextp->be	= be;
1229 		(void) NSS_INVOKE_DBOP(be, NSS_DBOP_SETENT, 0);
1230 	}
1231 	/* Got to the end of the sources without finding another entry */
1232 	end_iter_u(rootp, (struct nss_getent_context *)contextp);
1233 	return (NSS_SUCCESS);
1234 	/* success is either a successful entry or end of the sources */
1235 }
1236 
1237 /*ARGSUSED*/
1238 void
1239 nss_endent_u(nss_db_root_t *rootp, nss_db_initf_t initf,
1240 	nss_getent_t *contextpp)
1241 {
1242 	char			*me = "nss_endent_u";
1243 	nscd_getent_context_t	*contextp;
1244 
1245 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1246 	(me, "rootp = %p, initf = %p, contextpp = %p \n",
1247 	    rootp, initf, contextpp);
1248 
1249 	if ((contextp = (nscd_getent_context_t *)contextpp->ctx) == 0) {
1250 		/* nss_endent() on an unused context is a no-op */
1251 		return;
1252 	}
1253 
1254 	if (_nscd_is_getent_ctx_in_use(contextp) == 0) {
1255 		end_iter_u(rootp, (struct nss_getent_context *)contextp);
1256 		_nscd_put_getent_ctx(contextp);
1257 		contextpp->ctx = NULL;
1258 	}
1259 }
1260 
1261 /*
1262  * _nss_db_state_destr() and nss_delete() do nothing in nscd
1263  * but is needed to make the caller (below nscd) happy
1264  */
1265 /*ARGSUSED*/
1266 void
1267 _nss_db_state_destr(struct nss_db_state *s)
1268 {
1269 	/* nsw state in nscd is always reused, so do nothing here */
1270 }
1271 
1272 /*ARGSUSED*/
1273 void
1274 nss_delete(nss_db_root_t *rootp)
1275 {
1276 	/*
1277 	 * the only resource kept tracked by the nss_db_root_t
1278 	 * is the nsw state which is always reused and no need
1279 	 * to be freed. So just return.
1280 	 */
1281 }
1282 
1283 /*
1284  * Start of nss_psearch/nss_psetent()/nss_pgetent()/nss_pendent()
1285  * buffers switch entry points
1286  */
1287 
1288 /*
1289  * nss_psearch opens a packed structure header, assembles a local
1290  * nss_XbyY_args_t structure and calls the local copy of nss_search.
1291  * The return data is assembled in "files native format" in the
1292  * return buffer location.  Status if packed back up with the buffer
1293  * and the whole wad is returned to the cache or the client.
1294  */
1295 
1296 void
1297 nss_psearch(void *buffer, size_t length)
1298 {
1299 	/* inputs */
1300 	nss_db_initf_t		initf;
1301 	int			dbop;
1302 	int			rc;
1303 	nss_XbyY_args_t		arg;
1304 	nss_status_t		status;
1305 	nscd_sw_return_t	swret = { 0 }, *swrp = &swret;
1306 	nss_pheader_t		*pbuf = (nss_pheader_t *)buffer;
1307 	char			*me = "nss_psearch";
1308 
1309 	if (buffer == NULL || length == 0) {
1310 		NSCD_RETURN_STATUS(pbuf, NSS_ERROR, EFAULT);
1311 	}
1312 
1313 	status = nss_packed_arg_init(buffer, length,
1314 	    NULL, &initf, &dbop, &arg);
1315 	if (status != NSS_SUCCESS) {
1316 		NSCD_RETURN_STATUS(pbuf, status, -1);
1317 	}
1318 
1319 	/*
1320 	 * pass the address of the return data area
1321 	 * for the switch engine to return its own data
1322 	 */
1323 	(void) memcpy(&pbuf->nscdpriv, &swrp, sizeof (swrp));
1324 	swret.pbuf = buffer;
1325 	swret.pbufsiz = length;
1326 	swret.datalen = pbuf->data_len;
1327 
1328 	/*
1329 	 * use the generic nscd_initf for all database lookups
1330 	 * (the TSD key is the pointer to the packed header)
1331 	 */
1332 	rc = set_initf_key(pbuf);
1333 	if (rc != 0) {
1334 		NSCD_RETURN_STATUS(pbuf, NSS_UNAVAIL, EINVAL);
1335 	}
1336 	initf = nscd_initf;
1337 
1338 	/* Perform local search and pack results into return buffer */
1339 	/* nscd's search ignores db_root */
1340 	status = nss_search(NULL, initf, dbop, &arg);
1341 
1342 	/*
1343 	 * If status is NSS_NOTFOUND and ldap also returned
1344 	 * NSS_NOTFOUND, it is possible that the user does
1345 	 * not have a credential, so check and see if
1346 	 * needs to return NSS_ALTRETRY to let the main
1347 	 * nscd get a chance to process the lookup
1348 	 */
1349 	if (swret.fallback == 1 && status == NSS_NOTFOUND) {
1350 		OM_uint32	(*func)();
1351 		OM_uint32	stat;
1352 		nscd_rc_t	rc;
1353 
1354 		rc = get_gss_func((void **)&func);
1355 		if (rc == NSCD_SUCCESS) {
1356 			if (func(&stat, GSS_C_NO_CREDENTIAL,
1357 			    NULL, NULL, NULL, NULL) != GSS_S_COMPLETE) {
1358 
1359 				_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE,
1360 				    NSCD_LOG_LEVEL_DEBUG)
1361 			(me, "NSS_ALTRETRY: fallback to main nscd needed\n");
1362 
1363 				status = NSS_ALTRETRY;
1364 			}
1365 		}
1366 	}
1367 
1368 	NSCD_SET_STATUS(pbuf, status, -1);
1369 	errno = swret.errnum;
1370 
1371 	/*
1372 	 * Move result/status from args to packed buffer only if
1373 	 * arg was being used and rc from the switch engine is not
1374 	 * NSS_TRYLOCAL.
1375 	 */
1376 	if (!swret.noarg && status != NSS_TRYLOCAL)
1377 		nss_packed_set_status(buffer, length, status,  &arg);
1378 
1379 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1380 	(me, "switch engine result: source is %s, status %d, "
1381 	"herrno is %d, errno is %s\n",
1382 	    (swret.srci != -1) ? NSCD_NSW_SRC_NAME(swret.srci) : "<NOTSET>",
1383 	    pbuf->p_status, pbuf->p_herrno, strerror(pbuf->p_errno));
1384 
1385 	/* clear the TSD key used by the generic initf */
1386 	clear_initf_key();
1387 	pbuf->nscdpriv = 0;
1388 }
1389 
1390 static void
1391 nscd_map_contextp(void *buffer, nss_getent_t *contextp,
1392     nssuint_t **cookie_num_p, nssuint_t **seqnum_p, int setent)
1393 {
1394 	nss_pheader_t		*pbuf = (nss_pheader_t *)buffer;
1395 	nssuint_t		off;
1396 	nscd_getent_context_t	*ctx;
1397 	char			*me = "nscd_map_contextp";
1398 	nscd_getent_p1_cookie_t	*cookie;
1399 
1400 	if (buffer == NULL) {
1401 		NSCD_RETURN_STATUS(pbuf, NSS_ERROR, EFAULT);
1402 	}
1403 
1404 	off = pbuf->key_off;
1405 	cookie = (nscd_getent_p1_cookie_t *)((void *)((char *)buffer + off));
1406 	if (seqnum_p != NULL)
1407 		*seqnum_p = &cookie->p1_seqnum;
1408 
1409 	/*
1410 	 * if called by nss_psetent, and the passed in cookie number
1411 	 * is NSCD_NEW_COOKIE, then there is no cookie yet, return a
1412 	 * pointer pointing to where the cookie number will be stored.
1413 	 * Also because there is no cookie to validate, just return
1414 	 * success.
1415 	 *
1416 	 * On the other hand, if a cookie number is passed in, we need
1417 	 * to validate the cookie number before returning.
1418 	 */
1419 	if (cookie_num_p != NULL)
1420 		*cookie_num_p = &cookie->p1_cookie_num;
1421 	if (setent == 1 && cookie->p1_cookie_num == NSCD_NEW_COOKIE) {
1422 			NSCD_RETURN_STATUS_SUCCESS(pbuf);
1423 	}
1424 
1425 	/*
1426 	 * If the sequence number and start time match nscd's p0 cookie,
1427 	 * then either setent was done twice in a row or this is the
1428 	 * first getent after the setent, return success as well.
1429 	 */
1430 	if (cookie->p1_seqnum == NSCD_P0_COOKIE_SEQNUM) {
1431 		nscd_getent_p0_cookie_t *p0c =
1432 		    (nscd_getent_p0_cookie_t *)cookie;
1433 		if (p0c->p0_time == _nscd_get_start_time())
1434 			NSCD_RETURN_STATUS_SUCCESS(pbuf);
1435 	}
1436 
1437 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1438 	(me, "cookie # = %lld,  sequence # = %lld\n",
1439 	    cookie->p1_cookie_num, cookie->p1_seqnum);
1440 
1441 	ctx = _nscd_is_getent_ctx(cookie->p1_cookie_num);
1442 
1443 	if (ctx == NULL) {
1444 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1445 		(me, "No matching context found (cookie number: %lld)\n",
1446 		    cookie->p1_cookie_num);
1447 
1448 		NSCD_RETURN_STATUS(pbuf, NSS_ERROR, EFAULT);
1449 	}
1450 
1451 	/* if not called by nss_psetent, verify sequence number */
1452 	if (setent != 1 && ctx->seq_num !=
1453 	    (nscd_seq_num_t)cookie->p1_seqnum) {
1454 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1455 		(me, "invalid sequence # (%lld)\n", cookie->p1_seqnum);
1456 
1457 		_nscd_free_ctx_if_aborted(ctx);
1458 		NSCD_RETURN_STATUS(pbuf, NSS_ERROR, EFAULT);
1459 	}
1460 
1461 	contextp->ctx = (struct nss_getent_context *)ctx;
1462 
1463 	NSCD_RETURN_STATUS_SUCCESS(pbuf);
1464 }
1465 
1466 void
1467 nss_psetent(void *buffer, size_t length, pid_t pid)
1468 {
1469 	nss_getent_t		context = { 0 };
1470 	nss_getent_t		*contextp = &context;
1471 	nssuint_t		*cookie_num_p;
1472 	nssuint_t		*seqnum_p;
1473 	nss_pheader_t		*pbuf = (nss_pheader_t *)buffer;
1474 	nscd_getent_p0_cookie_t *p0c;
1475 	char			*me = "nss_psetent";
1476 
1477 	if (buffer == NULL || length == 0) {
1478 		NSCD_RETURN_STATUS(pbuf, NSS_ERROR, EFAULT);
1479 	}
1480 
1481 	/*
1482 	 * If this is a per-user nscd, and the user does not have
1483 	 * the necessary credential, return NSS_TRYLOCAL, so the
1484 	 * setent/getent can be done locally in the process of the
1485 	 * setent call
1486 	 */
1487 	if (_whoami == NSCD_CHILD) {
1488 		OM_uint32	(*func)();
1489 		OM_uint32	stat;
1490 		nscd_rc_t	rc;
1491 
1492 		rc = get_gss_func((void **)&func);
1493 		if (rc == NSCD_SUCCESS) {
1494 			if (func(&stat, GSS_C_NO_CREDENTIAL,
1495 			    NULL, NULL, NULL, NULL) != GSS_S_COMPLETE) {
1496 
1497 				_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE,
1498 				    NSCD_LOG_LEVEL_DEBUG)
1499 			(me, "NSS_TRYLOCAL: fallback to caller process\n");
1500 				NSCD_RETURN_STATUS(pbuf, NSS_TRYLOCAL, 0);
1501 			}
1502 		}
1503 	}
1504 
1505 	/* check cookie number */
1506 	nscd_map_contextp(buffer, contextp, &cookie_num_p, &seqnum_p, 1);
1507 	if (NSCD_STATUS_IS_NOT_OK(pbuf))
1508 		return;
1509 
1510 	/* set cookie number and sequence number */
1511 	p0c = (nscd_getent_p0_cookie_t *)cookie_num_p;
1512 	if (contextp->ctx ==  NULL) {
1513 		/*
1514 		 * first setent (no existing getent context),
1515 		 * return a p0 cookie
1516 		 */
1517 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1518 		(me, "first setent, no getent context yet\n");
1519 	} else {
1520 		/*
1521 		 * doing setent on an existing getent context,
1522 		 * release resources allocated and return a
1523 		 * p0 cookie
1524 		 */
1525 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1526 		(me, "setent resetting sequence number = %lld\n",  *seqnum_p);
1527 
1528 		if (_nscd_is_getent_ctx_in_use((nscd_getent_context_t *)
1529 		    contextp->ctx) == 0) {
1530 			/*
1531 			 * context not in use, release the backend and
1532 			 * return the context to the pool
1533 			 */
1534 			end_iter_u(NULL, contextp->ctx);
1535 			_nscd_put_getent_ctx(
1536 			    (nscd_getent_context_t *)contextp->ctx);
1537 			contextp->ctx = NULL;
1538 		}
1539 	}
1540 
1541 	p0c->p0_pid = pid;
1542 	p0c->p0_time = _nscd_get_start_time();
1543 	p0c->p0_seqnum = NSCD_P0_COOKIE_SEQNUM;
1544 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1545 	(me, "returning a p0 cookie: pid = %ld, time = %ld, seq #= %llx\n",
1546 	    p0c->p0_pid, p0c->p0_time, p0c->p0_seqnum);
1547 
1548 	NSCD_RETURN_STATUS(pbuf, NSS_SUCCESS, 0);
1549 }
1550 
1551 static void
1552 delayed_setent(nss_pheader_t *pbuf, nss_db_initf_t initf,
1553 	nss_getent_t *contextp, nssuint_t *cookie_num_p,
1554 	nssuint_t *seqnum_p, pid_t pid)
1555 {
1556 	nscd_getent_context_t	*ctx;
1557 	nscd_sw_return_t	swret = { 0 }, *swrp = &swret;
1558 	char			*me = "delayed_setent";
1559 
1560 	/*
1561 	 * check credential
1562 	 */
1563 	_nscd_APP_check_cred(pbuf, &pid, "NSCD_DELAYED_SETENT",
1564 	    NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_ERROR);
1565 	if (NSCD_STATUS_IS_NOT_OK(pbuf)) {
1566 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1567 		(me, "invalid credential\n");
1568 		return;
1569 	}
1570 
1571 	/*
1572 	 * pass the packed header buffer pointer to nss_setent
1573 	 */
1574 	(void) memcpy(&pbuf->nscdpriv, &swrp, sizeof (swrp));
1575 	swret.pbuf = pbuf;
1576 
1577 	/* Perform local setent and set context */
1578 	nss_setent(NULL, initf, contextp);
1579 
1580 	/* insert cookie info into packed buffer header */
1581 	ctx = (nscd_getent_context_t *)contextp->ctx;
1582 	if (ctx != NULL) {
1583 		*cookie_num_p = ctx->cookie_num;
1584 		*seqnum_p = ctx->seq_num;
1585 		ctx->pid = pid;
1586 	} else {
1587 		/*
1588 		 * not able to allocate a getent context, the
1589 		 * client should try the enumeration locally
1590 		 */
1591 		*cookie_num_p = NSCD_LOCAL_COOKIE;
1592 		*seqnum_p = 0;
1593 
1594 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1595 		(me, "NSS_TRYLOCAL: cookie # = %lld,  sequence # = %lld\n",
1596 		    *cookie_num_p, *seqnum_p);
1597 		NSCD_RETURN_STATUS(pbuf, NSS_TRYLOCAL, 0);
1598 	}
1599 
1600 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1601 	(me, "NSS_SUCCESS: cookie # = %lld,  sequence # = %lld\n",
1602 	    ctx->cookie_num, ctx->seq_num);
1603 
1604 	NSCD_RETURN_STATUS(pbuf, NSS_SUCCESS, 0);
1605 }
1606 
1607 void
1608 nss_pgetent(void *buffer, size_t length)
1609 {
1610 	/* inputs */
1611 	nss_db_initf_t		initf;
1612 	nss_getent_t		context = { 0 };
1613 	nss_getent_t		*contextp = &context;
1614 	nss_XbyY_args_t		arg = { 0};
1615 	nss_status_t		status;
1616 	nssuint_t		*cookie_num_p;
1617 	nssuint_t		*seqnum_p;
1618 	nscd_getent_context_t	*ctx;
1619 	int			rc;
1620 	nss_pheader_t		*pbuf = (nss_pheader_t *)buffer;
1621 	char			*me = "nss_pgetent";
1622 
1623 	if (buffer == NULL || length == 0) {
1624 		NSCD_RETURN_STATUS(pbuf, NSS_ERROR, EFAULT);
1625 	}
1626 
1627 	/* verify the cookie passed in */
1628 	nscd_map_contextp(buffer, contextp, &cookie_num_p, &seqnum_p, 0);
1629 	if (NSCD_STATUS_IS_NOT_OK(pbuf))
1630 		return;
1631 
1632 	/*
1633 	 * use the generic nscd_initf for all the getent requests
1634 	 * (the TSD key is the pointer to the packed header)
1635 	 */
1636 	rc = set_initf_key(pbuf);
1637 	if (rc != 0) {
1638 		NSCD_RETURN_STATUS(pbuf, NSS_UNAVAIL, EINVAL);
1639 	}
1640 	initf = nscd_initf;
1641 
1642 	/* if no context yet, get one */
1643 	if (contextp->ctx ==  NULL) {
1644 		nscd_getent_p0_cookie_t *p0c =
1645 		    (nscd_getent_p0_cookie_t *)cookie_num_p;
1646 
1647 		delayed_setent(pbuf, initf, contextp, cookie_num_p,
1648 		    seqnum_p, p0c->p0_pid);
1649 		if (NSCD_STATUS_IS_NOT_OK(pbuf)) {
1650 			clear_initf_key();
1651 			return;
1652 		}
1653 	}
1654 
1655 	status = nss_packed_context_init(buffer, length,
1656 	    NULL, &initf, &contextp, &arg);
1657 	if (status != NSS_SUCCESS) {
1658 		clear_initf_key();
1659 		_nscd_free_ctx_if_aborted(
1660 		    (nscd_getent_context_t *)contextp->ctx);
1661 		NSCD_RETURN_STATUS(pbuf, status, -1);
1662 	}
1663 
1664 	/* Perform local search and pack results into return buffer */
1665 	status = nss_getent(NULL, initf, contextp, &arg);
1666 	NSCD_SET_STATUS(pbuf, status, -1);
1667 	nss_packed_set_status(buffer, length, status,  &arg);
1668 
1669 	/* increment sequence number in the buffer and nscd context */
1670 	if (status == NSS_SUCCESS) {
1671 		ctx = (nscd_getent_context_t *)contextp->ctx;
1672 		ctx->seq_num++;
1673 		*seqnum_p = ctx->seq_num;
1674 		*cookie_num_p = ctx->cookie_num;
1675 
1676 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1677 		(me, "getent OK, new sequence # = %lld, len = %lld,"
1678 		    " data = >>%s<<\n", *seqnum_p,
1679 		    pbuf->data_len, (char *)buffer + pbuf->data_off);
1680 
1681 		_nscd_free_ctx_if_aborted(ctx);
1682 	} else {
1683 		/* release the resources used */
1684 		ctx = (nscd_getent_context_t *)contextp->ctx;
1685 		if (ctx != NULL && _nscd_is_getent_ctx_in_use(ctx) == 0) {
1686 			_nscd_put_getent_ctx(ctx);
1687 			contextp->ctx = NULL;
1688 		}
1689 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1690 		(me, "getent failed, status = %d, sequence # = %lld\n",
1691 		    status, *seqnum_p);
1692 	}
1693 
1694 	/* clear the TSD key used by the generic initf */
1695 	clear_initf_key();
1696 }
1697 
1698 void
1699 nss_pendent(void *buffer, size_t length)
1700 {
1701 	nss_getent_t		context = { 0 };
1702 	nss_getent_t		*contextp = &context;
1703 	nssuint_t		*seqnum_p;
1704 	nssuint_t		*cookie_num_p;
1705 	nss_pheader_t		*pbuf = (nss_pheader_t *)buffer;
1706 	char			*me = "nss_pendent";
1707 
1708 	if (buffer == NULL || length == 0) {
1709 		NSCD_RETURN_STATUS(pbuf, NSS_ERROR, EFAULT);
1710 	}
1711 
1712 	/* map the contextp from the cookie information */
1713 	nscd_map_contextp(buffer, contextp, &cookie_num_p, &seqnum_p, 0);
1714 	if (NSCD_STATUS_IS_NOT_OK(pbuf))
1715 		return;
1716 
1717 	if (contextp->ctx == NULL)
1718 		return;
1719 
1720 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1721 	(me, "endent, cookie = %lld, sequence # = %lld\n",
1722 	    *cookie_num_p, *seqnum_p);
1723 
1724 	/* Perform local endent and reset context */
1725 	nss_endent(NULL, NULL, contextp);
1726 
1727 	NSCD_RETURN_STATUS(pbuf, NSS_SUCCESS, 0);
1728 }
1729 
1730 /*ARGSUSED*/
1731 void
1732 nss_pdelete(void *buffer, size_t length)
1733 {
1734 	nss_pheader_t	*pbuf = (nss_pheader_t *)buffer;
1735 
1736 	/* unnecessary, kept for completeness */
1737 	NSCD_RETURN_STATUS_SUCCESS(pbuf);
1738 }
1739