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