xref: /titanic_44/usr/src/cmd/nscd/nscd_switch.c (revision 5b3e1433c6213363bcb6387e66fc84ee9ff21a5d)
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 2007 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, errno: %s \n",
381 	    res_str, db, op, src, arg->erange, strerror(arg->h_errno));
382 }
383 
384 /*
385  * Determine if a request should be done locally in the getXbyY caller's
386  * process. Return none zero if yes, 0 otherwise. This should be called
387  * before the switch engine steps through the backends/sources.
388  * This function returns 1 if:
389  *   -- the database is exec_attr and the search_flag is GET_ALL
390  */
391 static int
392 try_local(
393 	int			dbi,
394 	void			*arg)
395 {
396 	struct nss_XbyY_args	*ap = (struct nss_XbyY_args *)arg;
397 	_priv_execattr		*ep;
398 	int			rc = 0;
399 	char			*me = "try_local";
400 
401 	if (strcmp(NSCD_NSW_DB_NAME(dbi), NSS_DBNAM_EXECATTR) == 0) {
402 		if ((ep = ap->key.attrp) != NULL && ep->search_flag == GET_ALL)
403 			rc = 1;
404 	}
405 
406 	if (rc != 0) {
407 
408 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
409 		(me, "TRYLOCAL: exec_attr:GET_ALL\n");
410 	}
411 
412 	return (rc);
413 }
414 
415 /*
416  * Determine if a request should be done locally in the getXbyY caller's
417  * process. Return none zero if yes, 0 otherwise. This should be called
418  * before the switch engine invokes any backend.
419  * This function returns 1 if:
420  *   -- the database is shadow and the source is nisplus
421  */
422 static int
423 try_local2(
424 	int	dbi,
425 	int	srci)
426 {
427 	int	rc = 0;
428 	char	*me = "try_local2";
429 
430 	if (*NSCD_NSW_DB_NAME(dbi) == 's' &&
431 	    strcmp(NSCD_NSW_DB_NAME(dbi), NSS_DBNAM_SHADOW) == 0) {
432 		if (strcmp(NSCD_NSW_SRC_NAME(srci), "nisplus") == 0)
433 			rc = 1;
434 	}
435 
436 	if (rc != 0) {
437 
438 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
439 		(me, "TRYLOCAL: database: shadow, source: nisplus\n");
440 	}
441 
442 	return (rc);
443 }
444 
445 static nscd_rc_t
446 get_lib_func(void **handle, void **func, mutex_t *lock,
447 	char *lib, char *name, void **func_p)
448 {
449 	char	*me = "get_lib_func";
450 	void	*sym;
451 
452 	if (func_p != NULL && *handle != NULL && *func != NULL) {
453 		*func_p = *func;
454 		return (NSCD_SUCCESS);
455 	}
456 
457 	(void) mutex_lock(lock);
458 
459 	/* close the handle if requested */
460 	if (func_p == NULL) {
461 		if (*handle != NULL) {
462 			(void) dlclose(*handle);
463 			*handle = NULL;
464 			*func = NULL;
465 		}
466 		(void) mutex_unlock(lock);
467 		return (NSCD_SUCCESS);
468 	}
469 
470 	if (*handle != NULL && *func != NULL) {
471 		*func_p = *func;
472 		(void) mutex_unlock(lock);
473 		return (NSCD_SUCCESS);
474 	}
475 
476 	if (*handle == NULL) {
477 		*handle = dlopen(lib, RTLD_LAZY);
478 		if (*handle == NULL) {
479 			_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_ERROR)
480 			(me, "unable to dlopen %s\n", lib);
481 			(void) mutex_unlock(lock);
482 			return (NSCD_CFG_DLOPEN_ERROR);
483 		}
484 	}
485 
486 	if ((sym = dlsym(*handle, name)) == NULL) {
487 
488 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_ERROR)
489 		(me, "unable to find symbol %s:%s\n", lib, name);
490 		(void) mutex_unlock(lock);
491 		return (NSCD_CFG_DLSYM_ERROR);
492 	} else {
493 		*func_p = sym;
494 		*func = sym;
495 	}
496 
497 	(void) mutex_unlock(lock);
498 	return (NSCD_SUCCESS);
499 }
500 
501 static nscd_rc_t
502 get_libc_nss_search(void **func_p)
503 {
504 	static void	*handle = NULL;
505 	static void	*func = NULL;
506 	static mutex_t	lock = DEFAULTMUTEX;
507 
508 	return (get_lib_func(&handle, &func, &lock,
509 	    "libc.so", "nss_search", func_p));
510 }
511 
512 static nscd_rc_t
513 get_gss_func(void **func_p)
514 {
515 	static void	*handle = NULL;
516 	static void	*func = NULL;
517 	static mutex_t	lock = DEFAULTMUTEX;
518 
519 	return (get_lib_func(&handle, &func, &lock,
520 	    "libgss.so", "gss_inquire_cred", func_p));
521 }
522 
523 /*
524  * get_dns_funcs returns pointers to gethostbyname functions in the
525  * dynamically loaded nss_dns & nss_mdns modules that return host
526  * lookup results along with the TTL value in the DNS resource
527  * records. The dnsi parameter indicates whether the lookup database
528  * is hosts(0) or ipnodes(1). The srcname parameter identifies the DNS
529  * module: dns/mdns and the function returns the address of the specific
530  * gethostbyname function in func_p variable.
531  */
532 static nscd_rc_t
533 get_dns_funcs(int dnsi, nss_status_t (**func_p)(), const char *srcname)
534 {
535 	int		si;
536 	void		**funcpp;
537 	static void	*handle[2] = { NULL, NULL };
538 	static mutex_t	func_lock[2] = { DEFAULTMUTEX, DEFAULTMUTEX };
539 	static void 	*func[2][2] = {{NULL, NULL}, {NULL, NULL}};
540 	static const char	*lib[2] = { "nss_dns.so.1", "nss_mdns.so.1" };
541 	static const char 	*func_name[2][2] =
542 		{{ "_nss_get_dns_hosts_name", "_nss_get_dns_ipnodes_name" },
543 		{ "_nss_get_mdns_hosts_name", "_nss_get_mdns_ipnodes_name" }};
544 
545 	/* source index: 0 = dns, 1 = mdns */
546 	if (strcmp(srcname, "dns") == 0)
547 		si = 0;
548 	else
549 		si = 1;
550 
551 	/*
552 	 * function index (func[si][dnsi]):
553 	 * [0,0] = dns/hosts, [0,1] = dns/ipnodes,
554 	 * [1,0] = mdns/hosts, [1,1] = mdns/ipnodes
555 	 */
556 
557 	if (dnsi < 0) { /* close handle */
558 		funcpp = NULL;
559 		(void) mutex_lock(&func_lock[si]);
560 		func[si][0] = NULL;
561 		func[si][1] = NULL;
562 		(void) mutex_unlock(&func_lock[si]);
563 	} else
564 		funcpp = (void **)func_p;
565 
566 	return (get_lib_func(&handle[si], &func[si][dnsi], &func_lock[si],
567 	    (char *)lib[si], (char *)func_name[si][dnsi], funcpp));
568 }
569 
570 static nss_status_t
571 search_dns_withttl(nscd_sw_return_t *swret, const char *srcname, int dnsi)
572 {
573 	nss_status_t	(*func)();
574 	nss_status_t	res = NSS_UNAVAIL;
575 	nscd_rc_t	rc;
576 
577 	swret->noarg = 0;
578 	if (strcmp(srcname, "dns") != 0 && strcmp(srcname, "mdns") != 0)
579 		return (NSS_ERROR);
580 
581 	rc = get_dns_funcs(dnsi, &func, srcname);
582 	if (rc == NSCD_SUCCESS) {
583 		/*
584 		 * data_len in the packed buf header may be changed
585 		 * by the dns or mdns backend, reset it just in
586 		 * case
587 		 */
588 		((nss_pheader_t *)swret->pbuf)->data_len =
589 		    swret->datalen;
590 		res = (func)(NULL, &swret->pbuf, &swret->pbufsiz);
591 	}
592 	return (res);
593 }
594 
595 /*
596  * Returns a flag to indicate if needs to fall back to the
597  * main nscd when a per-user lookup failed with rc NSS_NOTFOUND.
598  */
599 static int
600 set_fallback_flag(char *srcname, nss_status_t rc)
601 {
602 	char	*me = "set_fallback_flag";
603 	if (strcmp(srcname, "ldap") == 0 && rc == NSS_NOTFOUND) {
604 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
605 		(me, "NSS_NOTFOUND (ldap): fallback to main nscd "
606 		"may be needed\n");
607 		return (1);
608 	}
609 	return (0);
610 }
611 
612 nss_status_t
613 nss_search(nss_db_root_t *rootp, nss_db_initf_t initf, int search_fnum,
614 	void *search_args)
615 {
616 	char			*me = "nss_search";
617 	nss_status_t		res = NSS_UNAVAIL;
618 	nscd_nsw_state_t	*s = NULL;
619 	int			n_src;
620 	unsigned int		status_vec = 0;
621 	int			dbi, srci = -1;
622 	int			check_loopback = 0;
623 	int			state_thr = 0;
624 	lb_key_t		key, *k = NULL;
625 	nss_db_root_t		root_db;
626 	nscd_nsw_params_t	params;
627 	nscd_sw_return_t	*swret;
628 
629 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
630 	(me, "rootp = %p, initf = %p, search_fnum = %d, "
631 	    "search_args = %p\n", rootp, initf,
632 	    search_fnum, search_args);
633 
634 	NSCD_SW_STATS_G.lookup_request_received_g++;
635 	NSCD_SW_STATS_G.lookup_request_in_progress_g++;
636 	NSCD_SW_STATS_G.lookup_request_queued_g++;
637 
638 	/* determine db index, cfg db index, etc */
639 	if (getparams(search_fnum, initf, &params) ==
640 	    NSCD_CFG_UNSUPPORTED_SWITCH_DB) {
641 		/*
642 		 * if unsupported database and the request is from the
643 		 * the door, tell the door client to try it locally
644 		 */
645 		if (initf == nscd_initf) {
646 			res = NSS_TRYLOCAL;
647 			goto error_exit;
648 		} else { /* otherwise, let libc:nss_search() handle it */
649 			nss_status_t	(*func)();
650 
651 			if (get_libc_nss_search((void **)&func) ==
652 			    NSCD_SUCCESS)
653 				return ((func)(rootp, initf, search_fnum,
654 				    search_args));
655 			else
656 				goto error_exit;
657 		}
658 	}
659 	dbi = params.dbi;
660 
661 	/* get address of the switch engine return data area */
662 	if (initf == nscd_initf) {
663 		swret = (nscd_sw_return_t *)params.p.private;
664 		swret->srci = -1;
665 	} else {
666 		swret = NULL;
667 		params.dnsi = -1;
668 	}
669 
670 	/*
671 	 * for door request that should be processed by the client,
672 	 * send it back with status NSS_TRYLOCAL
673 	 */
674 	if (initf == nscd_initf && try_local(dbi, search_args) == 1) {
675 		res = NSS_TRYLOCAL;
676 		goto error_exit;
677 	}
678 
679 	NSCD_SW_STATS(dbi).lookup_request_received++;
680 	NSCD_SW_STATS(dbi).lookup_request_in_progress++;
681 	NSCD_SW_STATS(dbi).lookup_request_queued++;
682 
683 	/* if lookup not enabled, return NSS_UNAVAIL  */
684 	if (!(NSCD_SW_CFG_G.enable_lookup_g == nscd_true &&
685 	    NSCD_SW_CFG(dbi).enable_lookup == nscd_true)) {
686 
687 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
688 		(me, "lookup not enabled for %s\n", NSCD_NSW_DB_NAME(dbi));
689 
690 		goto error_exit;
691 	}
692 
693 	/* determine if loopback checking is configured */
694 	if (NSCD_SW_CFG_G.enable_loopback_checking_g == nscd_true &&
695 	    NSCD_SW_CFG(dbi).enable_loopback_checking == nscd_true) {
696 		check_loopback = 1;
697 
698 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
699 		(me, "loopback checking enabled for %s\n",
700 		    NSCD_NSW_DB_NAME(dbi));
701 	}
702 
703 	if (check_loopback) {
704 		k = get_loopback_key();
705 		if (k != NULL) {
706 			if (k->dbi != dbi || k->fnum != search_fnum) {
707 				clear_loopback_key(k);
708 				k = NULL;
709 			}
710 		}
711 	}
712 
713 	if (s == 0) {
714 		nscd_rc_t	rc;
715 
716 		if (check_loopback) {
717 			rc = _nscd_get_nsw_state_thread(&root_db, &params);
718 			state_thr = 1;
719 		} else
720 			rc = _nscd_get_nsw_state(&root_db, &params);
721 
722 		NSCD_SW_STATS_G.lookup_request_queued_g--;
723 		NSCD_SW_STATS(dbi).lookup_request_queued--;
724 
725 		if (rc != NSCD_SUCCESS)
726 				goto error_exit;
727 
728 		s = (nscd_nsw_state_t *)root_db.s;
729 	}
730 
731 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
732 	(me, "database = %s, config = >>%s<<\n", NSCD_NSW_DB_NAME(dbi),
733 	    (*s->nsw_cfg_p)->nsw_cfg_str);
734 
735 	for (n_src = 0;  n_src < s->max_src;  n_src++) {
736 		nss_backend_t		*be = NULL;
737 		nss_backend_op_t	funcp = NULL;
738 		struct __nsw_lookup_v1	*lkp;
739 		int			smf_state;
740 		int			n_loop = 0;
741 		int			max_retry = 10;
742 
743 		res = NSS_UNAVAIL;
744 
745 		if (n_src == 0)
746 			lkp = s->config->lookups;
747 		else
748 			lkp = lkp->next;
749 
750 		/* set the number of max. retries */
751 		if (lkp->actions[__NSW_TRYAGAIN] == __NSW_TRYAGAIN_NTIMES)
752 			max_retry = lkp->max_retries;
753 
754 		srci = (*s->nsw_cfg_p)->src_idx[n_src];
755 		if (swret != NULL)
756 			swret->srci = srci;
757 
758 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
759 		(me, "nsw source = %s\n", NSCD_NSW_SRC_NAME(srci));
760 
761 		/* if no privilege to look up, skip */
762 		if (params.privdb == 1 && swret != NULL &&
763 		    strcmp(NSCD_NSW_SRC_NAME(srci), "files") == 0 &&
764 		    _nscd_check_client_read_priv() != 0) {
765 			_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
766 			(me, "no privilege to look up, skip source\n");
767 
768 			goto next_src;
769 		}
770 
771 		/* get state of the (backend) client service */
772 		smf_state = _nscd_get_smf_state(srci, dbi, 0);
773 
774 		/* stop if the source is one that should be TRYLOCAL */
775 		if (initf == nscd_initf &&
776 		    (smf_state == NSCD_SVC_STATE_UNKNOWN_SRC ||
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 		if (be == NULL || (params.dnsi < 0 && (funcp == NULL ||
808 		    (smf_state != NSCD_SVC_STATE_UNINITED &&
809 		    smf_state != NSCD_SVC_STATE_UNKNOWN_SRC &&
810 		    smf_state < SCF_STATE_ONLINE)))) {
811 
812 			_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE,
813 			    NSCD_LOG_LEVEL_DEBUG)
814 			(me, "unable to look up source %s: be = %p, "
815 			"smf state = %d, funcp = %p\n",
816 			    NSCD_NSW_SRC_NAME(srci), be, smf_state, funcp);
817 
818 			goto next_src;
819 		}
820 
821 		do {
822 			/*
823 			 * we can only retry max_retry times,
824 			 * otherwise threads may get stuck in this
825 			 * do-while loop forever
826 			 */
827 			if (n_loop > max_retry) {
828 				if (swret != NULL)
829 					res = NSS_TRYLOCAL;
830 				goto free_nsw_state;
831 			}
832 
833 			/*
834 			 * set up to prevent loopback
835 			 */
836 			if (check_loopback && k == NULL) {
837 				key.srci = srci;
838 				key.dbi = dbi;
839 				key.fnum = search_fnum;
840 				key.lb_flagp = &check_loopback;
841 				(void) set_loopback_key(&key);
842 				k = &key;
843 			}
844 
845 			_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE,
846 			    NSCD_LOG_LEVEL_DEBUG)
847 			(me, "looking up source = %s, loop# = %d \n",
848 			    NSCD_NSW_SRC_NAME(srci), n_loop);
849 
850 			/*
851 			 * search the backend, if hosts lookups,
852 			 * try to get the hosts data with ttl first
853 			 */
854 			if (params.dnsi >= 0) {
855 				res = search_dns_withttl(swret,
856 				    NSCD_NSW_SRC_NAME(srci), params.dnsi);
857 				/*
858 				 * if not able to get ttl, fall back
859 				 * to the regular backend call
860 				 */
861 				if (res == NSS_ERROR)
862 					res = (*funcp)(be, search_args);
863 				else {
864 					/*
865 					 * status/result are in the
866 					 * packed buffer, not
867 					 * search_args
868 					 */
869 					swret->noarg = 1;
870 				}
871 			} else
872 				res = (*funcp)(be, search_args);
873 			if (swret != NULL)
874 				swret->errnum = errno;
875 
876 			/*
877 			 * backend is not up, check and update the
878 			 * smf state table
879 			 */
880 			if (res == NSS_UNAVAIL)
881 				(void) _nscd_get_smf_state(srci, dbi, 1);
882 
883 			/*
884 			 * may need to fall back to use the main nscd
885 			 * if per-user lookup
886 			 */
887 			if (_whoami == NSCD_CHILD && swret != NULL)
888 				swret->fallback = set_fallback_flag(
889 				    NSCD_NSW_SRC_NAME(srci), res);
890 
891 			_NSCD_LOG_IF(NSCD_LOG_SWITCH_ENGINE,
892 			    NSCD_LOG_LEVEL_DEBUG) {
893 
894 				/*
895 				 * set up to trace the result/status
896 				 * of the dns/ttl lookup
897 				 */
898 				if (swret != NULL && swret->noarg == 1) {
899 					nss_pheader_t *phdr;
900 					struct nss_XbyY_args *arg;
901 					arg = (struct nss_XbyY_args *)
902 					    search_args;
903 					phdr = (nss_pheader_t *)swret->pbuf;
904 					arg->buf.buffer = (char *)phdr +
905 					    phdr->data_off;
906 					arg->returnlen = phdr->data_len;
907 					if (phdr->p_errno == ERANGE)
908 						arg->erange = 1;
909 					arg->h_errno = phdr->p_herrno;
910 				}
911 
912 				trace_result(dbi, srci, search_fnum, res,
913 				    (nss_XbyY_args_t *)search_args);
914 			}
915 
916 			n_loop++;
917 		} while (retry_test(res, n_loop, lkp));
918 
919 		next_src:
920 
921 		status_vec |= (1 << res);
922 
923 		if (__NSW_ACTION_V1(lkp, res) == __NSW_RETURN) {
924 			break;
925 		}
926 	}
927 
928 	free_nsw_state:
929 
930 	if (state_thr == 1)
931 		_nscd_put_nsw_state_thread(s);
932 	else
933 		_nscd_put_nsw_state(s);
934 	if (check_loopback && k != NULL)
935 		clear_loopback_key(k);
936 
937 	if (res != NSS_SUCCESS)
938 		goto error_exit;
939 
940 	NSCD_SW_STATS_G.lookup_request_succeeded_g++;
941 	NSCD_SW_STATS(dbi).lookup_request_succeeded++;
942 	NSCD_SW_STATS_G.lookup_request_in_progress_g--;
943 	NSCD_SW_STATS(dbi).lookup_request_in_progress--;
944 
945 	return (NSS_SUCCESS);
946 
947 	error_exit:
948 
949 	NSCD_SW_STATS_G.lookup_request_failed_g++;
950 	NSCD_SW_STATS_G.lookup_request_in_progress_g--;
951 	NSCD_SW_STATS(dbi).lookup_request_failed++;
952 	NSCD_SW_STATS(dbi).lookup_request_in_progress--;
953 
954 	return (res);
955 }
956 
957 
958 /* ===> get/set/endent */
959 
960 static void		nss_setent_u(nss_db_root_t *,
961 				    nss_db_initf_t,
962 				    nss_getent_t *);
963 static nss_status_t	nss_getent_u(nss_db_root_t *,
964 				    nss_db_initf_t,
965 				    nss_getent_t *,
966 				    void *);
967 static void		nss_endent_u(nss_db_root_t *,
968 				    nss_db_initf_t,
969 				    nss_getent_t *);
970 
971 void
972 nss_setent(nss_db_root_t *rootp, nss_db_initf_t initf,
973 	nss_getent_t *contextpp)
974 {
975 	if (contextpp == 0)
976 		return;
977 	nss_setent_u(rootp, initf, contextpp);
978 }
979 
980 nss_status_t
981 nss_getent(nss_db_root_t *rootp, nss_db_initf_t initf, nss_getent_t *contextpp,
982 	void *args)
983 {
984 	nss_status_t		status;
985 
986 	if (contextpp == 0) {
987 		return (NSS_UNAVAIL);
988 	}
989 	status = nss_getent_u(rootp, initf, contextpp, args);
990 	return (status);
991 }
992 
993 void
994 nss_endent(nss_db_root_t *rootp, nss_db_initf_t initf,
995 	nss_getent_t *contextpp)
996 {
997 	if (contextpp == 0)
998 		return;
999 	nss_endent_u(rootp, initf, contextpp);
1000 }
1001 
1002 /*ARGSUSED*/
1003 static void
1004 end_iter_u(nss_db_root_t *rootp, struct nss_getent_context *contextp)
1005 {
1006 	nscd_getent_context_t	*ctx;
1007 	nscd_nsw_state_t	*s;
1008 	nss_backend_t		*be;
1009 	int			n_src;
1010 
1011 	ctx = (nscd_getent_context_t *)contextp;
1012 	s = ctx->nsw_state;
1013 	n_src = ctx->n_src;
1014 	be = ctx->be;
1015 
1016 	if (s != 0) {
1017 		if (n_src < s->max_src && be != 0) {
1018 			(void) NSS_INVOKE_DBOP(be, NSS_DBOP_ENDENT, 0);
1019 			ctx->be = 0;  /* Should be unnecessary, but hey */
1020 		}
1021 	}
1022 	ctx->n_src = 0;
1023 }
1024 
1025 static void
1026 nss_setent_u(nss_db_root_t *rootp, nss_db_initf_t initf,
1027 	nss_getent_t *contextpp)
1028 {
1029 	char			*me = "nss_setent_u";
1030 	nscd_nsw_state_t	*s;
1031 	nscd_getent_context_t	*contextp;
1032 	nscd_nsw_params_t	params;
1033 	nss_db_root_t		root;
1034 	nss_backend_t		*be;
1035 	int			n_src, i;
1036 	nscd_sw_return_t	*swret = NULL;
1037 
1038 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1039 	(me, "rootp = %p, initf = %p, contextpp = %p \n",
1040 	    rootp, initf, contextpp);
1041 
1042 	/*
1043 	 * Get the nsw db index via the initf function. If unsupported
1044 	 * database, no need to continue
1045 	 */
1046 	if (getparams(-1, initf, &params) == NSCD_CFG_UNSUPPORTED_SWITCH_DB)
1047 		return;
1048 
1049 	/* get address of the switch engine return data area */
1050 	if (initf == nscd_initf)
1051 		swret = (nscd_sw_return_t *)params.p.private;
1052 
1053 	/* if no privilege to look up, return */
1054 	if (params.privdb == 1 && swret != NULL &&
1055 	    _nscd_check_client_read_priv() != 0) {
1056 
1057 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1058 		(me, "no privilege \n");
1059 		return;
1060 	}
1061 
1062 	if ((contextp = (nscd_getent_context_t *)contextpp->ctx) == 0) {
1063 		if ((_nscd_get_getent_ctx(contextpp, &params)) !=
1064 		    NSCD_SUCCESS) {
1065 			return;
1066 		}
1067 		contextp = (nscd_getent_context_t *)contextpp->ctx;
1068 	}
1069 	s = contextp->nsw_state;
1070 
1071 	if (s == 0) {
1072 		if (_nscd_get_nsw_state(&root, &params) !=
1073 		    NSCD_SUCCESS) {
1074 			return;
1075 		}
1076 		s = (nscd_nsw_state_t *)root.s;
1077 		contextp->nsw_state = s;
1078 
1079 	} else {
1080 		s	= contextp->nsw_state;
1081 		n_src	= contextp->n_src;
1082 		be	= contextp->be;
1083 		if (n_src == 0 && be != 0) {
1084 			/*
1085 			 * Optimization:  don't do endent, don't change
1086 			 *   backends, just do the setent.  Look Ma, no locks
1087 			 *   (nor any context that needs updating).
1088 			 */
1089 			(void) NSS_INVOKE_DBOP(be, NSS_DBOP_SETENT, 0);
1090 			return;
1091 		}
1092 		if (n_src < s->max_src && be != 0) {
1093 			(void) NSS_INVOKE_DBOP(be, NSS_DBOP_ENDENT, 0);
1094 			contextp->be = 0;	/* Play it safe */
1095 		}
1096 	}
1097 	for (n_src = 0, be = 0; n_src < s->max_src &&
1098 	    (be = s->be[n_src]) == 0; n_src++) {
1099 		;
1100 	}
1101 
1102 	contextp->n_src	= n_src;
1103 	contextp->be	= be;
1104 
1105 	if (be == 0) {
1106 		/* Things are broken enough that we can't do setent/getent */
1107 		nss_endent_u(rootp, initf, contextpp);
1108 		return;
1109 	}
1110 
1111 	/*
1112 	 * make sure all the backends are supported
1113 	 */
1114 	for (i = 0; i < s->max_src; i++) {
1115 		int	st, srci;
1116 
1117 		srci = (*s->nsw_cfg_p)->src_idx[i];
1118 		st = _nscd_get_smf_state(srci, params.dbi, 1);
1119 		if (st == NSCD_SVC_STATE_UNKNOWN_SRC ||
1120 		    st == NSCD_SVC_STATE_UNINITED || (params.privdb &&
1121 		    try_local2(params.dbi, srci) == 1)) {
1122 			nss_endent_u(rootp, initf, contextpp);
1123 
1124 			_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE,
1125 			    NSCD_LOG_LEVEL_DEBUG)
1126 			(me, "backend (%s) not available (state = %d)\n",
1127 			    NSCD_NSW_SRC_NAME(srci), st);
1128 
1129 			return;
1130 		}
1131 	}
1132 
1133 	(void) NSS_INVOKE_DBOP(be, NSS_DBOP_SETENT, 0);
1134 }
1135 
1136 nss_status_t
1137 nss_getent_u(nss_db_root_t *rootp, nss_db_initf_t initf,
1138 	nss_getent_t *contextpp, void *args)
1139 {
1140 	char			*me = "nss_getent_u";
1141 	nscd_nsw_state_t	*s;
1142 	nscd_getent_context_t	*contextp;
1143 	int			n_src;
1144 	nss_backend_t		*be;
1145 
1146 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1147 	(me, "rootp = %p, initf = %p, contextpp = %p, args = %p\n",
1148 	    rootp, initf, contextpp, args);
1149 
1150 	if ((contextp = (nscd_getent_context_t *)contextpp->ctx) == 0) {
1151 		nss_setent_u(rootp, initf, contextpp);
1152 		if ((contextp = (nscd_getent_context_t *)contextpp->ctx) == 0) {
1153 			/* Give up */
1154 			_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE,
1155 			    NSCD_LOG_LEVEL_ERROR)
1156 			(me, "not able to obtain getent context ... give up\n");
1157 
1158 			return (NSS_UNAVAIL);
1159 		}
1160 	}
1161 
1162 	s	= contextp->nsw_state;
1163 	n_src	= contextp->n_src;
1164 	be	= contextp->be;
1165 
1166 	if (s == 0) {
1167 		/*
1168 		 * We've done an end_iter() and haven't done nss_setent()
1169 		 * or nss_endent() since;  we should stick in this state
1170 		 * until the caller invokes one of those two routines.
1171 		 */
1172 		return (NSS_SUCCESS);
1173 	}
1174 
1175 	while (n_src < s->max_src) {
1176 		nss_status_t		res;
1177 		struct __nsw_lookup_v1	*lkp = NULL;
1178 		int			n;
1179 
1180 		/* get the nsw config for the current source */
1181 		lkp = s->config->lookups;
1182 		for (n = 0; n < n_src; n++)
1183 			lkp = lkp->next;
1184 
1185 		if (be == 0) {
1186 			/* If it's null it's a bug, but let's play safe */
1187 			res = NSS_UNAVAIL;
1188 		} else {
1189 			_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE,
1190 			    NSCD_LOG_LEVEL_DEBUG)
1191 			(me, "database: %s, backend: %s, nsswitch config: %s\n",
1192 			    NSCD_NSW_DB_NAME(s->dbi),
1193 			    lkp->service_name,
1194 			    (*s->nsw_cfg_p)->nsw_cfg_str);
1195 
1196 			res = NSS_INVOKE_DBOP(be, NSS_DBOP_GETENT, args);
1197 		}
1198 
1199 		if (__NSW_ACTION_V1(lkp, res) == __NSW_RETURN) {
1200 			if (res != __NSW_SUCCESS) {
1201 				end_iter_u(rootp,
1202 				    (struct nss_getent_context *)contextp);
1203 			}
1204 			return (res);
1205 		}
1206 		(void) NSS_INVOKE_DBOP(be, NSS_DBOP_ENDENT, 0);
1207 		do {
1208 			n_src++;
1209 		} while (n_src < s->max_src &&
1210 		    (be = s->be[n_src]) == 0);
1211 		if (be == 0) {
1212 			/*
1213 			 * This is the case where we failed to get the backend
1214 			 * for the last source. We exhausted all sources.
1215 			 */
1216 			nss_endent_u(rootp, initf, contextpp);
1217 			return (NSS_NOTFOUND);
1218 		}
1219 		contextp->n_src	= n_src;
1220 		contextp->be	= be;
1221 		(void) NSS_INVOKE_DBOP(be, NSS_DBOP_SETENT, 0);
1222 	}
1223 	/* Got to the end of the sources without finding another entry */
1224 	end_iter_u(rootp, (struct nss_getent_context *)contextp);
1225 	return (NSS_SUCCESS);
1226 	/* success is either a successful entry or end of the sources */
1227 }
1228 
1229 /*ARGSUSED*/
1230 void
1231 nss_endent_u(nss_db_root_t *rootp, nss_db_initf_t initf,
1232 	nss_getent_t *contextpp)
1233 {
1234 	char			*me = "nss_endent_u";
1235 	nscd_getent_context_t	*contextp;
1236 
1237 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1238 	(me, "rootp = %p, initf = %p, contextpp = %p \n",
1239 	    rootp, initf, contextpp);
1240 
1241 	if ((contextp = (nscd_getent_context_t *)contextpp->ctx) == 0) {
1242 		/* nss_endent() on an unused context is a no-op */
1243 		return;
1244 	}
1245 	end_iter_u(rootp, (struct nss_getent_context *)contextp);
1246 	_nscd_put_getent_ctx(contextp);
1247 	contextpp->ctx = NULL;
1248 }
1249 
1250 /*
1251  * _nss_db_state_destr() and nss_delete() do nothing in nscd
1252  * but is needed to make the caller (below nscd) happy
1253  */
1254 /*ARGSUSED*/
1255 void
1256 _nss_db_state_destr(struct nss_db_state *s)
1257 {
1258 	/* nsw state in nscd is always reused, so do nothing here */
1259 }
1260 
1261 /*ARGSUSED*/
1262 void
1263 nss_delete(nss_db_root_t *rootp)
1264 {
1265 	/*
1266 	 * the only resource kept tracked by the nss_db_root_t
1267 	 * is the nsw state which is always reused and no need
1268 	 * to be freed. So just return.
1269 	 */
1270 }
1271 
1272 /*
1273  * Start of nss_psearch/nss_psetent()/nss_pgetent()/nss_pendent()
1274  * buffers switch entry points
1275  */
1276 
1277 /*
1278  * nss_psearch opens a packed structure header, assembles a local
1279  * nss_XbyY_args_t structure and calls the local copy of nss_search.
1280  * The return data is assembled in "files native format" in the
1281  * return buffer location.  Status if packed back up with the buffer
1282  * and the whole wad is returned to the cache or the client.
1283  */
1284 
1285 void
1286 nss_psearch(void *buffer, size_t length)
1287 {
1288 	/* inputs */
1289 	nss_db_initf_t		initf;
1290 	int			dbop;
1291 	int			rc;
1292 	nss_XbyY_args_t		arg;
1293 	nss_status_t		status;
1294 	nscd_sw_return_t	swret = { 0 }, *swrp = &swret;
1295 	nss_pheader_t		*pbuf = (nss_pheader_t *)buffer;
1296 	char			*me = "nss_psearch";
1297 
1298 	if (buffer == NULL || length == 0) {
1299 		NSCD_RETURN_STATUS(pbuf, NSS_ERROR, EFAULT);
1300 	}
1301 
1302 	status = nss_packed_arg_init(buffer, length,
1303 	    NULL, &initf, &dbop, &arg);
1304 	if (status != NSS_SUCCESS) {
1305 		NSCD_RETURN_STATUS(pbuf, status, -1);
1306 	}
1307 
1308 	/*
1309 	 * pass the address of the return data area
1310 	 * for the switch engine to return its own data
1311 	 */
1312 	(void) memcpy(&pbuf->nscdpriv, &swrp, sizeof (swrp));
1313 	swret.pbuf = buffer;
1314 	swret.pbufsiz = length;
1315 	swret.datalen = pbuf->data_len;
1316 
1317 	/*
1318 	 * use the generic nscd_initf for all database lookups
1319 	 * (the TSD key is the pointer to the packed header)
1320 	 */
1321 	rc = set_initf_key(pbuf);
1322 	if (rc != 0) {
1323 		NSCD_RETURN_STATUS(pbuf, NSS_UNAVAIL, EINVAL);
1324 	}
1325 	initf = nscd_initf;
1326 
1327 	/* Perform local search and pack results into return buffer */
1328 	/* nscd's search ignores db_root */
1329 	status = nss_search(NULL, initf, dbop, &arg);
1330 
1331 	/*
1332 	 * If status is NSS_NOTFOUND and ldap also returned
1333 	 * NSS_NOTFOUND, it is possible that the user does
1334 	 * not have a credential, so check and see if
1335 	 * needs to return NSS_ALTRETRY to let the main
1336 	 * nscd get a chance to process the lookup
1337 	 */
1338 	if (swret.fallback == 1 && status == NSS_NOTFOUND) {
1339 		OM_uint32	(*func)();
1340 		OM_uint32	stat;
1341 		nscd_rc_t	rc;
1342 
1343 		rc = get_gss_func((void **)&func);
1344 		if (rc == NSCD_SUCCESS) {
1345 			if (func(&stat, GSS_C_NO_CREDENTIAL,
1346 			    NULL, NULL, NULL, NULL) != GSS_S_COMPLETE) {
1347 
1348 				_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE,
1349 				    NSCD_LOG_LEVEL_DEBUG)
1350 			(me, "NSS_ALTRETRY: fallback to main nscd needed\n");
1351 
1352 				status = NSS_ALTRETRY;
1353 			}
1354 		}
1355 	}
1356 
1357 	NSCD_SET_STATUS(pbuf, status, -1);
1358 	errno = swret.errnum;
1359 
1360 	/*
1361 	 * move result/status from args to packed buffer only if
1362 	 * arg was being used
1363 	 */
1364 	if (!swret.noarg)
1365 		nss_packed_set_status(buffer, length, status,  &arg);
1366 
1367 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1368 	(me, "switch engine result: source is %s, status %d, "
1369 	"herrno is %d, errno is %s\n",
1370 	    (swret.srci != -1) ? NSCD_NSW_SRC_NAME(swret.srci) : "<NOTSET>",
1371 	    pbuf->p_status, pbuf->p_herrno, strerror(pbuf->p_errno));
1372 
1373 	/* clear the TSD key used by the generic initf */
1374 	clear_initf_key();
1375 	pbuf->nscdpriv = 0;
1376 }
1377 
1378 static void
1379 nscd_map_contextp(void *buffer, nss_getent_t *contextp,
1380 	nssuint_t **cookie_num_p, nssuint_t **seqnum_p, int setent)
1381 {
1382 	nss_pheader_t		*pbuf = (nss_pheader_t *)buffer;
1383 	nssuint_t		off;
1384 	nscd_getent_context_t	*ctx;
1385 	char			*me = "nscd_map_contextp";
1386 	nscd_getent_p1_cookie_t	*cookie;
1387 
1388 	if (buffer == NULL) {
1389 		NSCD_RETURN_STATUS(pbuf, NSS_ERROR, EFAULT);
1390 	}
1391 
1392 	off = pbuf->key_off;
1393 	cookie = (nscd_getent_p1_cookie_t *)((void *)((char *)buffer + off));
1394 	if (seqnum_p != NULL)
1395 		*seqnum_p = &cookie->p1_seqnum;
1396 
1397 	/*
1398 	 * if called by nss_psetent, and the passed in cookie number
1399 	 * is NSCD_NEW_COOKIE, then there is no cookie yet, return a
1400 	 * pointer pointing to where the cookie number will be stored.
1401 	 * Also because there is no cookie to validate, just return
1402 	 * success.
1403 	 *
1404 	 * On the other hand, if a cookie number is passed in, we need
1405 	 * to validate the cookie number before returning.
1406 	 */
1407 	if (cookie_num_p != NULL)
1408 		*cookie_num_p = &cookie->p1_cookie_num;
1409 	if (setent == 1 && cookie->p1_cookie_num == NSCD_NEW_COOKIE) {
1410 			NSCD_RETURN_STATUS_SUCCESS(pbuf);
1411 	}
1412 
1413 	/*
1414 	 * If the sequence number and start time match nscd's p0 cookie,
1415 	 * then either setent was done twice in a row or this is the
1416 	 * first getent after the setent, return success as well.
1417 	 */
1418 	if (cookie->p1_seqnum == NSCD_P0_COOKIE_SEQNUM) {
1419 		nscd_getent_p0_cookie_t *p0c =
1420 		    (nscd_getent_p0_cookie_t *)cookie;
1421 		if (p0c->p0_time == _nscd_get_start_time())
1422 			NSCD_RETURN_STATUS_SUCCESS(pbuf);
1423 	}
1424 
1425 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1426 	(me, "cookie # = %lld,  sequence # = %lld\n",
1427 	    cookie->p1_cookie_num, cookie->p1_seqnum);
1428 
1429 	ctx = _nscd_is_getent_ctx(cookie->p1_cookie_num);
1430 
1431 	if (ctx == NULL) {
1432 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1433 		(me, "invalid cookie # (%lld)\n", cookie->p1_cookie_num);
1434 
1435 		NSCD_RETURN_STATUS(pbuf, NSS_ERROR, EFAULT);
1436 	}
1437 
1438 	/* if not called by nss_psetent, verify sequence number */
1439 	if (setent != 1 && ctx->seq_num !=
1440 	    (nscd_seq_num_t)cookie->p1_seqnum) {
1441 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1442 		(me, "invalid sequence # (%lld)\n", cookie->p1_seqnum);
1443 
1444 		NSCD_RETURN_STATUS(pbuf, NSS_ERROR, EFAULT);
1445 	}
1446 
1447 	contextp->ctx = (struct nss_getent_context *)ctx;
1448 
1449 	NSCD_RETURN_STATUS_SUCCESS(pbuf);
1450 }
1451 
1452 void
1453 nss_psetent(void *buffer, size_t length, pid_t pid)
1454 {
1455 	nss_getent_t		context = { 0 };
1456 	nss_getent_t		*contextp = &context;
1457 	nssuint_t		*cookie_num_p;
1458 	nssuint_t		*seqnum_p;
1459 	nss_pheader_t		*pbuf = (nss_pheader_t *)buffer;
1460 	nscd_getent_p0_cookie_t *p0c;
1461 	char			*me = "nss_psetent";
1462 
1463 	if (buffer == NULL || length == 0) {
1464 		NSCD_RETURN_STATUS(pbuf, NSS_ERROR, EFAULT);
1465 	}
1466 
1467 	/*
1468 	 * If this is a per-user nscd, and the user does not have
1469 	 * the necessary credential, return NSS_TRYLOCAL, so the
1470 	 * setent/getent can be done locally in the process of the
1471 	 * setent call
1472 	 */
1473 	if (_whoami == NSCD_CHILD) {
1474 		OM_uint32	(*func)();
1475 		OM_uint32	stat;
1476 		nscd_rc_t	rc;
1477 
1478 		rc = get_gss_func((void **)&func);
1479 		if (rc == NSCD_SUCCESS) {
1480 			if (func(&stat, GSS_C_NO_CREDENTIAL,
1481 			    NULL, NULL, NULL, NULL) != GSS_S_COMPLETE) {
1482 
1483 				_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE,
1484 				    NSCD_LOG_LEVEL_DEBUG)
1485 			(me, "NSS_TRYLOCAL: fallback to caller process\n");
1486 				NSCD_RETURN_STATUS(pbuf, NSS_TRYLOCAL, 0);
1487 			}
1488 		}
1489 	}
1490 
1491 	/* check cookie number */
1492 	nscd_map_contextp(buffer, contextp, &cookie_num_p, &seqnum_p, 1);
1493 	if (NSCD_STATUS_IS_NOT_OK(pbuf))
1494 		return;
1495 
1496 	/* set cookie number and sequence number */
1497 	p0c = (nscd_getent_p0_cookie_t *)cookie_num_p;
1498 	if (contextp->ctx ==  NULL) {
1499 		/*
1500 		 * first setent (no existing getent context),
1501 		 * return a p0 cookie
1502 		 */
1503 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1504 		(me, "first setent, no getent context yet\n");
1505 	} else {
1506 		/*
1507 		 * doing setent on an existing getent context,
1508 		 * release resources allocated and return a
1509 		 * p0 cookie
1510 		 */
1511 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1512 		(me, "setent resetting sequence number = %lld\n",  *seqnum_p);
1513 
1514 		_nscd_put_getent_ctx((nscd_getent_context_t *)contextp->ctx);
1515 		contextp->ctx = NULL;
1516 	}
1517 
1518 	p0c->p0_pid = pid;
1519 	p0c->p0_time = _nscd_get_start_time();
1520 	p0c->p0_seqnum = NSCD_P0_COOKIE_SEQNUM;
1521 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1522 	(me, "returning a p0 cookie: pid = %ld, time = %ld, seq #= %llx\n",
1523 	    p0c->p0_pid, p0c->p0_time, p0c->p0_seqnum);
1524 
1525 	NSCD_RETURN_STATUS(pbuf, NSS_SUCCESS, 0);
1526 }
1527 
1528 static void
1529 delayed_setent(nss_pheader_t *pbuf, nss_db_initf_t initf,
1530 	nss_getent_t *contextp, nssuint_t *cookie_num_p,
1531 	nssuint_t *seqnum_p, pid_t pid)
1532 {
1533 	nscd_getent_context_t	*ctx;
1534 	nscd_sw_return_t	swret = { 0 }, *swrp = &swret;
1535 	char			*me = "delayed_setent";
1536 
1537 	/*
1538 	 * check credential
1539 	 */
1540 	_nscd_APP_check_cred(pbuf, &pid, "NSCD_DELAYED_SETENT",
1541 	    NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_ERROR);
1542 	if (NSCD_STATUS_IS_NOT_OK(pbuf)) {
1543 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1544 		(me, "invalid credential\n");
1545 		return;
1546 	}
1547 
1548 	/*
1549 	 * pass the packed header buffer pointer to nss_setent
1550 	 */
1551 	(void) memcpy(&pbuf->nscdpriv, &swrp, sizeof (swrp));
1552 	swret.pbuf = pbuf;
1553 
1554 	/* Perform local setent and set context */
1555 	nss_setent(NULL, initf, contextp);
1556 
1557 	/* insert cookie info into packed buffer header */
1558 	ctx = (nscd_getent_context_t *)contextp->ctx;
1559 	if (ctx != NULL) {
1560 		*cookie_num_p = ctx->cookie_num;
1561 		*seqnum_p = ctx->seq_num;
1562 		ctx->pid = pid;
1563 	} else {
1564 		/*
1565 		 * not able to allocate a getent context, the
1566 		 * client should try the enumeration locally
1567 		 */
1568 		*cookie_num_p = NSCD_LOCAL_COOKIE;
1569 		*seqnum_p = 0;
1570 
1571 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1572 		(me, "NSS_TRYLOCAL: cookie # = %lld,  sequence # = %lld\n",
1573 		    *cookie_num_p, *seqnum_p);
1574 		NSCD_RETURN_STATUS(pbuf, NSS_TRYLOCAL, 0);
1575 	}
1576 
1577 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1578 	(me, "NSS_SUCCESS: cookie # = %lld,  sequence # = %lld\n",
1579 	    ctx->cookie_num, ctx->seq_num);
1580 
1581 	NSCD_RETURN_STATUS(pbuf, NSS_SUCCESS, 0);
1582 }
1583 
1584 void
1585 nss_pgetent(void *buffer, size_t length)
1586 {
1587 	/* inputs */
1588 	nss_db_initf_t		initf;
1589 	nss_getent_t		context = { 0 };
1590 	nss_getent_t		*contextp = &context;
1591 	nss_XbyY_args_t		arg = { 0};
1592 	nss_status_t		status;
1593 	nssuint_t		*cookie_num_p;
1594 	nssuint_t		*seqnum_p;
1595 	nscd_getent_context_t	*ctx;
1596 	int			rc;
1597 	nss_pheader_t		*pbuf = (nss_pheader_t *)buffer;
1598 	char			*me = "nss_pgetent";
1599 
1600 	if (buffer == NULL || length == 0) {
1601 		NSCD_RETURN_STATUS(pbuf, NSS_ERROR, EFAULT);
1602 	}
1603 
1604 	/* verify the cookie passed in */
1605 	nscd_map_contextp(buffer, contextp, &cookie_num_p, &seqnum_p, 0);
1606 	if (NSCD_STATUS_IS_NOT_OK(pbuf))
1607 		return;
1608 	/*
1609 	 * use the generic nscd_initf for all the getent requests
1610 	 * (the TSD key is the pointer to the packed header)
1611 	 */
1612 	rc = set_initf_key(pbuf);
1613 	if (rc != 0) {
1614 		NSCD_RETURN_STATUS(pbuf, NSS_UNAVAIL, EINVAL);
1615 	}
1616 	initf = nscd_initf;
1617 
1618 	/* if no context yet, get one */
1619 	if (contextp->ctx ==  NULL) {
1620 		nscd_getent_p0_cookie_t *p0c =
1621 		    (nscd_getent_p0_cookie_t *)cookie_num_p;
1622 
1623 		delayed_setent(pbuf, initf, contextp, cookie_num_p,
1624 		    seqnum_p, p0c->p0_pid);
1625 		if (NSCD_STATUS_IS_NOT_OK(pbuf)) {
1626 			clear_initf_key();
1627 			return;
1628 		}
1629 	}
1630 
1631 	status = nss_packed_context_init(buffer, length,
1632 	    NULL, &initf, &contextp, &arg);
1633 	if (status != NSS_SUCCESS) {
1634 		NSCD_RETURN_STATUS(pbuf, status, -1);
1635 	}
1636 
1637 	/* Perform local search and pack results into return buffer */
1638 	status = nss_getent(NULL, initf, contextp, &arg);
1639 	NSCD_SET_STATUS(pbuf, status, -1);
1640 	nss_packed_set_status(buffer, length, status,  &arg);
1641 
1642 	/* increment sequence number in the buffer and nscd context */
1643 	if (status == NSS_SUCCESS) {
1644 		ctx = (nscd_getent_context_t *)contextp->ctx;
1645 		ctx->seq_num++;
1646 		*seqnum_p = ctx->seq_num;
1647 		*cookie_num_p = ctx->cookie_num;
1648 
1649 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1650 		(me, "getent OK, new sequence # = %lld, len = %lld,"
1651 		    " data = >>%s<<\n", *seqnum_p,
1652 		    pbuf->data_len, (char *)buffer + pbuf->data_off);
1653 	} else {
1654 		/* release the resources used */
1655 		ctx = (nscd_getent_context_t *)contextp->ctx;
1656 		if (ctx != NULL) {
1657 			_nscd_put_getent_ctx(ctx);
1658 			contextp->ctx = NULL;
1659 		}
1660 		_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1661 		(me, "getent failed, status = %d, sequence # = %lld\n",
1662 		    status, *seqnum_p);
1663 	}
1664 
1665 	/* clear the TSD key used by the generic initf */
1666 	clear_initf_key();
1667 }
1668 
1669 void
1670 nss_pendent(void *buffer, size_t length)
1671 {
1672 	nss_getent_t		context = { 0 };
1673 	nss_getent_t		*contextp = &context;
1674 	nssuint_t		*seqnum_p;
1675 	nssuint_t		*cookie_num_p;
1676 	nss_pheader_t		*pbuf = (nss_pheader_t *)buffer;
1677 	char			*me = "nss_pendent";
1678 
1679 	if (buffer == NULL || length == 0) {
1680 		NSCD_RETURN_STATUS(pbuf, NSS_ERROR, EFAULT);
1681 	}
1682 
1683 	/* map the contextp from the cookie information */
1684 	nscd_map_contextp(buffer, contextp, &cookie_num_p, &seqnum_p, 0);
1685 	if (NSCD_STATUS_IS_NOT_OK(pbuf))
1686 		return;
1687 
1688 	if (contextp->ctx == NULL)
1689 		return;
1690 
1691 	_NSCD_LOG(NSCD_LOG_SWITCH_ENGINE, NSCD_LOG_LEVEL_DEBUG)
1692 	(me, "endent, cookie = %lld, sequence # = %lld\n",
1693 	    *cookie_num_p, *seqnum_p);
1694 
1695 	/* Perform local endent and reset context */
1696 	nss_endent(NULL, NULL, contextp);
1697 	NSCD_RETURN_STATUS(pbuf, NSS_SUCCESS, 0);
1698 }
1699 
1700 /*ARGSUSED*/
1701 void
1702 nss_pdelete(void *buffer, size_t length)
1703 {
1704 	nss_pheader_t	*pbuf = (nss_pheader_t *)buffer;
1705 
1706 	/* unnecessary, kept for completeness */
1707 	NSCD_RETURN_STATUS_SUCCESS(pbuf);
1708 }
1709