xref: /illumos-gate/usr/src/lib/libsldap/common/ns_reads.c (revision 17a5fa85fe0c34b1146222e40a80b42f2aae8500)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright 2017 Nexenta Systems, Inc.  All rights reserved.
24  */
25 
26 #include <stdio.h>
27 #include <sys/types.h>
28 #include <stdlib.h>
29 #include <libintl.h>
30 #include <ctype.h>
31 #include <syslog.h>
32 #include <sys/stat.h>
33 #include <fcntl.h>
34 #include <unistd.h>
35 #include <string.h>
36 #include <strings.h>
37 #include <priv.h>
38 
39 #include "ns_sldap.h"
40 #include "ns_internal.h"
41 #include "ns_cache_door.h"
42 #include "ns_connmgmt.h"
43 
44 #define	_NIS_FILTER	"nisdomain=*"
45 #define	_NIS_DOMAIN	"nisdomain"
46 static const char *nis_domain_attrs[] = {
47 	_NIS_DOMAIN,
48 	(char *)NULL
49 };
50 
51 static int validate_filter(ns_ldap_cookie_t *cookie);
52 
53 void
54 __ns_ldap_freeEntry(ns_ldap_entry_t *ep)
55 {
56 	int		j, k = 0;
57 
58 	if (ep == NULL)
59 		return;
60 
61 	if (ep->attr_pair == NULL) {
62 		free(ep);
63 		return;
64 	}
65 	for (j = 0; j < ep->attr_count; j++) {
66 		if (ep->attr_pair[j] == NULL)
67 			continue;
68 		if (ep->attr_pair[j]->attrname)
69 			free(ep->attr_pair[j]->attrname);
70 		if (ep->attr_pair[j]->attrvalue) {
71 			for (k = 0; (k < ep->attr_pair[j]->value_count) &&
72 			    (ep->attr_pair[j]->attrvalue[k]); k++) {
73 				free(ep->attr_pair[j]->attrvalue[k]);
74 			}
75 			free(ep->attr_pair[j]->attrvalue);
76 		}
77 		free(ep->attr_pair[j]);
78 	}
79 	free(ep->attr_pair);
80 	free(ep);
81 }
82 
83 static void
84 _freeControlList(LDAPControl ***ctrls)
85 {
86 	LDAPControl	**ctrl;
87 
88 	if (ctrls == NULL || *ctrls == NULL)
89 		return;
90 
91 	for (ctrl = *ctrls; *ctrl != NULL; ctrl++)
92 		ldap_control_free(*ctrl);
93 	free(*ctrls);
94 	*ctrls = NULL;
95 }
96 /*
97  * Convert attribute type in a RDN that has an attribute mapping to the
98  * original mappped type.
99  * e.g.
100  * cn<->cn-st and iphostnumber<->iphostnumber-st
101  * cn-st=aaa+iphostnumber-st=10.10.01.01
102  * is mapped to
103  * cn=aaa+iphostnumber=10.10.01.01
104  *
105  * Input - service: e.g. hosts, passwd etc.
106  *         rdn: RDN
107  * Return: NULL - No attribute mapping in the RDN
108  *         Non-NULL - The attribute type(s) in the RDN are mapped and
109  *                    the memory is allocated for the new rdn.
110  *
111  */
112 static char *
113 _cvtRDN(const char *service, const char *rdn) {
114 	char	**attrs, **mapped_attrs, **mapp, *type, *value, *attr;
115 	char	*new_rdn = NULL;
116 	int	nAttr = 0, i, attr_mapped, len = 0;
117 
118 	/* Break down "type=value\0" pairs. Assume RDN is normalized */
119 	if ((attrs = ldap_explode_rdn(rdn, 0)) == NULL)
120 		return (NULL);
121 
122 	for (nAttr = 0; attrs[nAttr] != NULL; nAttr++);
123 
124 	if ((mapped_attrs = (char **)calloc(nAttr, sizeof (char *))) == NULL) {
125 		ldap_value_free(attrs);
126 		return (NULL);
127 	}
128 
129 	attr_mapped = 0;
130 	for (i = 0; i < nAttr; i++) {
131 		/* Parse type=value pair */
132 		if ((type = strtok_r(attrs[i], "=", &value)) == NULL ||
133 					value == NULL)
134 			goto cleanup;
135 		/* Reverse map: e.g. cn-sm -> cn */
136 		mapp = __ns_ldap_getOrigAttribute(service, type);
137 		if (mapp != NULL && mapp[0] != NULL) {
138 			/* The attribute mapping is found */
139 			type = mapp[0];
140 			attr_mapped = 1;
141 
142 			/* "type=value\0" */
143 			len = strlen(type) + strlen(value) + 2;
144 
145 			/* Reconstruct type=value pair. A string is allocated */
146 			if ((attr = (char *)calloc(1, len)) == NULL) {
147 				__s_api_free2dArray(mapp);
148 				goto cleanup;
149 			}
150 			(void) snprintf(attr, len, "%s=%s",
151 						type, value);
152 			mapped_attrs[i] = attr;
153 		} else {
154 			/*
155 			 * No attribute mapping. attrs[i] is going to be copied
156 			 * later. Restore "type\0value\0" back to
157 			 * "type=value\0".
158 			 */
159 			type[strlen(type)] = '=';
160 		}
161 		__s_api_free2dArray(mapp);
162 	}
163 	if (attr_mapped == 0)
164 		/* No attribute mapping. Don't bother to reconstruct RDN */
165 		goto cleanup;
166 
167 	len = 0;
168 	/* Reconstruct RDN from type=value pairs */
169 	for (i = 0; i < nAttr; i++) {
170 		if (mapped_attrs[i])
171 			len += strlen(mapped_attrs[i]);
172 		else
173 			len += strlen(attrs[i]);
174 		/* Add 1 for "+" */
175 		len++;
176 	}
177 	if ((new_rdn = (char *)calloc(1, ++len)) == NULL)
178 		goto cleanup;
179 	for (i = 0; i < nAttr; i++) {
180 		if (i > 0)
181 			/* Add seperator */
182 			(void) strlcat(new_rdn, "+", len);
183 
184 		if (mapped_attrs[i])
185 			(void) strlcat(new_rdn, mapped_attrs[i], len);
186 		else
187 			(void) strlcat(new_rdn, attrs[i], len);
188 
189 	}
190 cleanup:
191 	ldap_value_free(attrs);
192 	if (mapped_attrs) {
193 		if (attr_mapped) {
194 			for (i = 0; i < nAttr; i++) {
195 				if (mapped_attrs[i])
196 					free(mapped_attrs[i]);
197 			}
198 		}
199 		free(mapped_attrs);
200 	}
201 
202 	return (new_rdn);
203 }
204 /*
205  * Convert attribute type in a DN that has an attribute mapping to the
206  * original mappped type.
207  * e.g
208  * The mappings are cn<->cn-sm, iphostnumber<->iphostnumber-sm
209  *
210  * dn: cn-sm=aaa+iphostnumber-sm=9.9.9.9,dc=central,dc=sun,dc=com
211  * is converted to
212  * dn: cn=aaa+iphostnumber=9.9.9.9,dc=central,dc=sun,dc=com
213  *
214  * Input - service: e.g. hosts, passwd etc.
215  *         dn: the value of a distinguished name
216  * Return - NULL: error
217  *          non-NULL: A converted DN and the memory is allocated
218  */
219 static char *
220 _cvtDN(const char *service, const char *dn) {
221 	char	**mapped_rdns;
222 	char	**rdns, *new_rdn, *new_dn = NULL;
223 	int	nRdn = 0, i, len = 0, rdn_mapped;
224 
225 	if (service == NULL || dn == NULL)
226 		return (NULL);
227 
228 	if ((rdns = ldap_explode_dn(dn, 0)) == NULL)
229 		return (NULL);
230 
231 	for (nRdn = 0; rdns[nRdn] != NULL; nRdn++)
232 		;
233 
234 	if ((mapped_rdns = (char **)calloc(nRdn, sizeof (char *))) == NULL) {
235 		ldap_value_free(rdns);
236 		return (NULL);
237 	}
238 
239 	rdn_mapped = 0;
240 	/* Break down RDNs in a DN */
241 	for (i = 0; i < nRdn; i++) {
242 		if ((new_rdn = _cvtRDN(service, rdns[i])) != NULL) {
243 			mapped_rdns[i] = new_rdn;
244 			rdn_mapped = 1;
245 		}
246 	}
247 	if (rdn_mapped == 0) {
248 		/*
249 		 * No RDN contains any attribute mapping.
250 		 * Don't bother to reconstruct DN from RDN. Copy DN directly.
251 		 */
252 		new_dn = strdup(dn);
253 		goto cleanup;
254 	}
255 	/*
256 	 * Reconstruct dn from RDNs.
257 	 * Calculate the length first.
258 	 */
259 	for (i = 0; i < nRdn; i++) {
260 		if (mapped_rdns[i])
261 			len += strlen(mapped_rdns[i]);
262 		else
263 			len += strlen(rdns[i]);
264 
265 		/* add 1 for ',' */
266 		len ++;
267 	}
268 	if ((new_dn = (char *)calloc(1, ++len)) == NULL)
269 		goto cleanup;
270 	for (i = 0; i < nRdn; i++) {
271 		if (i > 0)
272 			/* Add seperator */
273 			(void) strlcat(new_dn, ",", len);
274 
275 		if (mapped_rdns[i])
276 			(void) strlcat(new_dn, mapped_rdns[i], len);
277 		else
278 			(void) strlcat(new_dn, rdns[i], len);
279 
280 	}
281 
282 cleanup:
283 	ldap_value_free(rdns);
284 	if (mapped_rdns) {
285 		if (rdn_mapped) {
286 			for (i = 0; i < nRdn; i++) {
287 				if (mapped_rdns[i])
288 					free(mapped_rdns[i]);
289 			}
290 		}
291 		free(mapped_rdns);
292 	}
293 
294 	return (new_dn);
295 }
296 /*
297  * Convert a single ldap entry from a LDAPMessage
298  * into an ns_ldap_entry structure.
299  * Schema map the entry if specified in flags
300  */
301 
302 static int
303 __s_api_cvtEntry(LDAP	*ld,
304 	const char	*service,
305 	LDAPMessage	*e,
306 	int		flags,
307 	ns_ldap_entry_t	**ret,
308 	ns_ldap_error_t	**error)
309 {
310 
311 	ns_ldap_entry_t	*ep = NULL;
312 	ns_ldap_attr_t	**ap = NULL;
313 	BerElement	*ber;
314 	char		*attr = NULL;
315 	char		**vals = NULL;
316 	char		**mapping;
317 	char		*dn;
318 	int		nAttrs = 0;
319 	int		i, j, k = 0;
320 	char		**gecos_mapping = NULL;
321 	int		gecos_val_index[3] = { -1, -1, -1};
322 	char		errstr[MAXERROR];
323 	int		schema_mapping_existed = FALSE;
324 	int		gecos_mapping_existed = FALSE;
325 	int		gecos_attr_matched;
326 	int		auto_service = FALSE;
327 	int		rc = NS_LDAP_SUCCESS;
328 
329 	if (e == NULL || ret == NULL || error == NULL)
330 		return (NS_LDAP_INVALID_PARAM);
331 
332 	*error = NULL;
333 
334 	ep = (ns_ldap_entry_t *)calloc(1, sizeof (ns_ldap_entry_t));
335 	if (ep == NULL)
336 		return (NS_LDAP_MEMORY);
337 
338 	if (service != NULL &&
339 	    (strncasecmp(service, "auto_", 5) == 0 ||
340 	    strcasecmp(service, "automount") == 0))
341 		auto_service = TRUE;
342 	/*
343 	 * see if schema mapping existed for the given service
344 	 */
345 	mapping = __ns_ldap_getOrigAttribute(service,
346 	    NS_HASH_SCHEMA_MAPPING_EXISTED);
347 	if (mapping) {
348 		schema_mapping_existed = TRUE;
349 		__s_api_free2dArray(mapping);
350 		mapping = NULL;
351 	} else if (auto_service) {
352 		/*
353 		 * If service == auto_* and no
354 		 * schema mapping found
355 		 * then try automount
356 		 * There is certain case that schema mapping exist
357 		 * but __ns_ldap_getOrigAttribute(service,
358 		 *	NS_HASH_SCHEMA_MAPPING_EXISTED);
359 		 * returns NULL.
360 		 * e.g.
361 		 * NS_LDAP_ATTRIBUTEMAP = automount:automountMapName=AAA
362 		 * NS_LDAP_OBJECTCLASSMAP = automount:automountMap=MynisMap
363 		 * NS_LDAP_OBJECTCLASSMAP = automount:automount=MynisObject
364 		 *
365 		 * Make a check for schema_mapping_existed here
366 		 * so later on __s_api_convert_automountmapname won't be called
367 		 * unnecessarily. It is also used for attribute mapping
368 		 * and objectclass mapping.
369 		 */
370 		mapping = __ns_ldap_getOrigAttribute("automount",
371 		    NS_HASH_SCHEMA_MAPPING_EXISTED);
372 		if (mapping) {
373 			schema_mapping_existed = TRUE;
374 			__s_api_free2dArray(mapping);
375 			mapping = NULL;
376 		}
377 	}
378 
379 	nAttrs = 1;  /* start with 1 for the DN attr */
380 	for (attr = ldap_first_attribute(ld, e, &ber); attr != NULL;
381 	    attr = ldap_next_attribute(ld, e, ber)) {
382 		nAttrs++;
383 		ldap_memfree(attr);
384 		attr = NULL;
385 	}
386 	ber_free(ber, 0);
387 	ber = NULL;
388 
389 	ep->attr_count = nAttrs;
390 
391 	/*
392 	 * add 1 for "gecos" 1 to N attribute mapping,
393 	 * just in case it is needed.
394 	 * ep->attr_count will be updated later if that is true.
395 	 */
396 	ap = (ns_ldap_attr_t **)calloc(ep->attr_count + 1,
397 	    sizeof (ns_ldap_attr_t *));
398 	if (ap == NULL) {
399 		__ns_ldap_freeEntry(ep);
400 		ep = NULL;
401 		return (NS_LDAP_MEMORY);
402 	}
403 	ep->attr_pair = ap;
404 
405 	/* DN attribute */
406 	dn = ldap_get_dn(ld, e);
407 	ap[0] = (ns_ldap_attr_t *)calloc(1, sizeof (ns_ldap_attr_t));
408 	if (ap[0] == NULL) {
409 		ldap_memfree(dn);
410 		dn = NULL;
411 		__ns_ldap_freeEntry(ep);
412 		ep = NULL;
413 		return (NS_LDAP_MEMORY);
414 	}
415 
416 	if ((ap[0]->attrname = strdup("dn")) == NULL) {
417 		ldap_memfree(dn);
418 		dn = NULL;
419 		__ns_ldap_freeEntry(ep);
420 		ep = NULL;
421 		return (NS_LDAP_INVALID_PARAM);
422 	}
423 	ap[0]->value_count = 1;
424 	if ((ap[0]->attrvalue = (char **)
425 	    calloc(2, sizeof (char *))) == NULL) {
426 		ldap_memfree(dn);
427 		dn = NULL;
428 		__ns_ldap_freeEntry(ep);
429 		ep = NULL;
430 		return (NS_LDAP_MEMORY);
431 	}
432 
433 	if (schema_mapping_existed && ((flags & NS_LDAP_NOT_CVT_DN) == 0))
434 		ap[0]->attrvalue[0] = _cvtDN(service, dn);
435 	else
436 		ap[0]->attrvalue[0] = strdup(dn);
437 
438 	if (ap[0]->attrvalue[0] == NULL) {
439 		ldap_memfree(dn);
440 		dn = NULL;
441 		__ns_ldap_freeEntry(ep);
442 		ep = NULL;
443 		return (NS_LDAP_MEMORY);
444 	}
445 	ldap_memfree(dn);
446 	dn = NULL;
447 
448 	if ((flags & NS_LDAP_NOMAP) == 0 && auto_service &&
449 	    schema_mapping_existed) {
450 		rc = __s_api_convert_automountmapname(service,
451 		    &ap[0]->attrvalue[0],
452 		    error);
453 		if (rc != NS_LDAP_SUCCESS) {
454 			__ns_ldap_freeEntry(ep);
455 			ep = NULL;
456 			return (rc);
457 		}
458 	}
459 
460 	/* other attributes */
461 	for (attr = ldap_first_attribute(ld, e, &ber), j = 1;
462 	    attr != NULL && j != nAttrs;
463 	    attr = ldap_next_attribute(ld, e, ber), j++) {
464 		/* allocate new attr name */
465 
466 		if ((ap[j] = (ns_ldap_attr_t *)
467 		    calloc(1, sizeof (ns_ldap_attr_t))) == NULL) {
468 			ber_free(ber, 0);
469 			ber = NULL;
470 			__ns_ldap_freeEntry(ep);
471 			ep = NULL;
472 			if (gecos_mapping)
473 				__s_api_free2dArray(gecos_mapping);
474 			gecos_mapping = NULL;
475 			return (NS_LDAP_MEMORY);
476 		}
477 
478 		if ((flags & NS_LDAP_NOMAP) || schema_mapping_existed == FALSE)
479 			mapping = NULL;
480 		else
481 			mapping = __ns_ldap_getOrigAttribute(service, attr);
482 
483 		if (mapping == NULL && auto_service &&
484 		    schema_mapping_existed && (flags & NS_LDAP_NOMAP) == 0)
485 			/*
486 			 * if service == auto_* and no schema mapping found
487 			 * and schema_mapping_existed is TRUE and NS_LDAP_NOMAP
488 			 * is not set then try automount e.g.
489 			 * NS_LDAP_ATTRIBUTEMAP = automount:automountMapName=AAA
490 			 */
491 			mapping = __ns_ldap_getOrigAttribute("automount",
492 			    attr);
493 
494 		if (mapping == NULL) {
495 			if ((ap[j]->attrname = strdup(attr)) == NULL) {
496 				ber_free(ber, 0);
497 				ber = NULL;
498 				__ns_ldap_freeEntry(ep);
499 				ep = NULL;
500 				if (gecos_mapping)
501 					__s_api_free2dArray(gecos_mapping);
502 				gecos_mapping = NULL;
503 				return (NS_LDAP_MEMORY);
504 			}
505 		} else {
506 			/*
507 			 * for "gecos" 1 to N mapping,
508 			 * do not remove the mapped attribute,
509 			 * just create a new gecos attribute
510 			 * and append it to the end of the attribute list
511 			 */
512 			if (strcasecmp(mapping[0], "gecos") == 0) {
513 				ap[j]->attrname = strdup(attr);
514 				gecos_mapping_existed = TRUE;
515 			} else
516 				ap[j]->attrname = strdup(mapping[0]);
517 
518 			if (ap[j]->attrname == NULL) {
519 				ber_free(ber, 0);
520 				ber = NULL;
521 				__ns_ldap_freeEntry(ep);
522 				ep = NULL;
523 				if (gecos_mapping)
524 					__s_api_free2dArray(gecos_mapping);
525 				gecos_mapping = NULL;
526 				return (NS_LDAP_MEMORY);
527 			}
528 			/*
529 			 * 1 to N attribute mapping processing
530 			 * is only done for "gecos"
531 			 */
532 
533 			if (strcasecmp(mapping[0], "gecos") == 0) {
534 				/*
535 				 * get attribute mapping for "gecos",
536 				 * need to know the number and order of the
537 				 * mapped attributes
538 				 */
539 				if (gecos_mapping == NULL) {
540 					gecos_mapping =
541 					    __ns_ldap_getMappedAttributes(
542 					    service, mapping[0]);
543 					if (gecos_mapping == NULL ||
544 					    gecos_mapping[0] == NULL) {
545 						/*
546 						 * this should never happens,
547 						 * syslog the error
548 						 */
549 						(void) sprintf(errstr,
550 						    gettext(
551 						    "Attribute mapping "
552 						    "inconsistency "
553 						    "found for attributes "
554 						    "'%s' and '%s'."),
555 						    mapping[0], attr);
556 						syslog(LOG_ERR, "libsldap: %s",
557 						    errstr);
558 
559 						ber_free(ber, 0);
560 						ber = NULL;
561 						__ns_ldap_freeEntry(ep);
562 						ep = NULL;
563 						__s_api_free2dArray(mapping);
564 						mapping = NULL;
565 						if (gecos_mapping)
566 							__s_api_free2dArray(
567 							    gecos_mapping);
568 						gecos_mapping = NULL;
569 						return (NS_LDAP_INTERNAL);
570 					}
571 				}
572 
573 				/*
574 				 * is this attribute the 1st, 2nd, or
575 				 * 3rd attr in the mapping list?
576 				 */
577 				gecos_attr_matched = FALSE;
578 				for (i = 0; i < 3 && gecos_mapping[i]; i++) {
579 					if (gecos_mapping[i] &&
580 					    strcasecmp(gecos_mapping[i],
581 					    attr) == 0) {
582 						gecos_val_index[i] = j;
583 						gecos_attr_matched = TRUE;
584 						break;
585 					}
586 				}
587 				if (gecos_attr_matched == FALSE) {
588 					/*
589 					 * Not match found.
590 					 * This should never happens,
591 					 * syslog the error
592 					 */
593 					(void) sprintf(errstr,
594 					    gettext(
595 					    "Attribute mapping "
596 					    "inconsistency "
597 					    "found for attributes "
598 					    "'%s' and '%s'."),
599 					    mapping[0], attr);
600 					syslog(LOG_ERR, "libsldap: %s", errstr);
601 
602 					ber_free(ber, 0);
603 					ber = NULL;
604 					__ns_ldap_freeEntry(ep);
605 					ep = NULL;
606 					__s_api_free2dArray(mapping);
607 					mapping = NULL;
608 					__s_api_free2dArray(gecos_mapping);
609 					gecos_mapping = NULL;
610 					return (NS_LDAP_INTERNAL);
611 				}
612 			}
613 			__s_api_free2dArray(mapping);
614 			mapping = NULL;
615 		}
616 
617 		if ((vals = ldap_get_values(ld, e, attr)) != NULL) {
618 
619 			if ((ap[j]->value_count =
620 			    ldap_count_values(vals)) == 0) {
621 				ldap_value_free(vals);
622 				vals = NULL;
623 				continue;
624 			} else {
625 				ap[j]->attrvalue = (char **)
626 				    calloc(ap[j]->value_count+1,
627 				    sizeof (char *));
628 				if (ap[j]->attrvalue == NULL) {
629 					ber_free(ber, 0);
630 					ber = NULL;
631 					__ns_ldap_freeEntry(ep);
632 					ep = NULL;
633 					if (gecos_mapping)
634 						__s_api_free2dArray(
635 						    gecos_mapping);
636 					gecos_mapping = NULL;
637 					return (NS_LDAP_MEMORY);
638 				}
639 			}
640 
641 			/* map object classes if necessary */
642 			if ((flags & NS_LDAP_NOMAP) == 0 &&
643 			    schema_mapping_existed && ap[j]->attrname &&
644 			    strcasecmp(ap[j]->attrname, "objectclass") == 0) {
645 				for (k = 0; k < ap[j]->value_count; k++) {
646 					mapping =
647 					    __ns_ldap_getOrigObjectClass(
648 					    service, vals[k]);
649 
650 					if (mapping == NULL && auto_service)
651 						/*
652 						 * if service == auto_* and no
653 						 * schema mapping found
654 						 * then try automount
655 						 */
656 					mapping =
657 					    __ns_ldap_getOrigObjectClass(
658 					    "automount", vals[k]);
659 
660 					if (mapping == NULL) {
661 						ap[j]->attrvalue[k] =
662 						    strdup(vals[k]);
663 					} else {
664 						ap[j]->attrvalue[k] =
665 						    strdup(mapping[0]);
666 						__s_api_free2dArray(mapping);
667 						mapping = NULL;
668 					}
669 					if (ap[j]->attrvalue[k] == NULL) {
670 						ber_free(ber, 0);
671 						ber = NULL;
672 						__ns_ldap_freeEntry(ep);
673 						ep = NULL;
674 						if (gecos_mapping)
675 							__s_api_free2dArray(
676 							    gecos_mapping);
677 						gecos_mapping = NULL;
678 						return (NS_LDAP_MEMORY);
679 					}
680 				}
681 			} else {
682 				for (k = 0; k < ap[j]->value_count; k++) {
683 					if ((ap[j]->attrvalue[k] =
684 					    strdup(vals[k])) == NULL) {
685 						ber_free(ber, 0);
686 						ber = NULL;
687 						__ns_ldap_freeEntry(ep);
688 						ep = NULL;
689 						if (gecos_mapping)
690 							__s_api_free2dArray(
691 							    gecos_mapping);
692 						gecos_mapping = NULL;
693 						return (NS_LDAP_MEMORY);
694 					}
695 				}
696 			}
697 
698 			ap[j]->attrvalue[k] = NULL;
699 			ldap_value_free(vals);
700 			vals = NULL;
701 		}
702 
703 		ldap_memfree(attr);
704 		attr = NULL;
705 	}
706 
707 	ber_free(ber, 0);
708 	ber = NULL;
709 
710 	if (gecos_mapping) {
711 		__s_api_free2dArray(gecos_mapping);
712 		gecos_mapping = NULL;
713 	}
714 
715 	/* special processing for gecos 1 to up to 3 attribute mapping */
716 	if (schema_mapping_existed && gecos_mapping_existed) {
717 
718 		int	f = -1;
719 
720 		for (i = 0; i < 3; i++) {
721 			k = gecos_val_index[i];
722 
723 			/*
724 			 * f is the index of the first returned
725 			 * attribute which "gecos" attribute mapped to
726 			 */
727 			if (k != -1 && f == -1)
728 				f = k;
729 
730 			if (k != -1 && ap[k]->value_count > 0 &&
731 			    ap[k]->attrvalue[0] &&
732 			    strlen(ap[k]->attrvalue[0]) > 0) {
733 
734 				if (k == f) {
735 					/*
736 					 * Create and fill in the last reserved
737 					 * ap with the data from the "gecos"
738 					 * mapping attributes
739 					 */
740 					ap[nAttrs] = (ns_ldap_attr_t *)
741 					    calloc(1,
742 					    sizeof (ns_ldap_attr_t));
743 					if (ap[nAttrs] == NULL) {
744 						__ns_ldap_freeEntry(ep);
745 						ep = NULL;
746 						return (NS_LDAP_MEMORY);
747 					}
748 					ap[nAttrs]->attrvalue = (char **)calloc(
749 					    2, sizeof (char *));
750 					if (ap[nAttrs]->attrvalue == NULL) {
751 						__ns_ldap_freeEntry(ep);
752 						ep = NULL;
753 						return (NS_LDAP_MEMORY);
754 					}
755 					/* add 1 more for a possible "," */
756 					ap[nAttrs]->attrvalue[0] =
757 					    (char *)calloc(
758 					    strlen(ap[f]->attrvalue[0]) +
759 					    2, 1);
760 					if (ap[nAttrs]->attrvalue[0] == NULL) {
761 						__ns_ldap_freeEntry(ep);
762 						ep = NULL;
763 						return (NS_LDAP_MEMORY);
764 					}
765 					(void) strcpy(ap[nAttrs]->attrvalue[0],
766 					    ap[f]->attrvalue[0]);
767 
768 					ap[nAttrs]->attrname = strdup("gecos");
769 					if (ap[nAttrs]->attrname == NULL) {
770 						__ns_ldap_freeEntry(ep);
771 						ep = NULL;
772 						return (NS_LDAP_MEMORY);
773 					}
774 
775 					ap[nAttrs]->value_count = 1;
776 					ep->attr_count = nAttrs + 1;
777 
778 				} else {
779 					char	*tmp = NULL;
780 
781 					/*
782 					 * realloc to add "," and
783 					 * ap[k]->attrvalue[0]
784 					 */
785 					tmp = (char *)realloc(
786 					    ap[nAttrs]->attrvalue[0],
787 					    strlen(ap[nAttrs]->
788 					    attrvalue[0]) +
789 					    strlen(ap[k]->
790 					    attrvalue[0]) + 2);
791 					if (tmp == NULL) {
792 						__ns_ldap_freeEntry(ep);
793 						ep = NULL;
794 						return (NS_LDAP_MEMORY);
795 					}
796 					ap[nAttrs]->attrvalue[0] = tmp;
797 					(void) strcat(ap[nAttrs]->attrvalue[0],
798 					    ",");
799 					(void) strcat(ap[nAttrs]->attrvalue[0],
800 					    ap[k]->attrvalue[0]);
801 				}
802 			}
803 		}
804 	}
805 
806 	*ret = ep;
807 	return (NS_LDAP_SUCCESS);
808 }
809 
810 static int
811 __s_api_getEntry(ns_ldap_cookie_t *cookie)
812 {
813 	ns_ldap_entry_t	*curEntry = NULL;
814 	int		ret;
815 
816 #ifdef DEBUG
817 	(void) fprintf(stderr, "__s_api_getEntry START\n");
818 #endif
819 
820 	if (cookie->resultMsg == NULL) {
821 		return (NS_LDAP_INVALID_PARAM);
822 	}
823 	ret = __s_api_cvtEntry(cookie->conn->ld, cookie->service,
824 	    cookie->resultMsg, cookie->i_flags,
825 	    &curEntry, &cookie->errorp);
826 	if (ret != NS_LDAP_SUCCESS) {
827 		return (ret);
828 	}
829 
830 	if (cookie->result == NULL) {
831 		cookie->result = (ns_ldap_result_t *)
832 		    calloc(1, sizeof (ns_ldap_result_t));
833 		if (cookie->result == NULL) {
834 			__ns_ldap_freeEntry(curEntry);
835 			curEntry = NULL;
836 			return (NS_LDAP_MEMORY);
837 		}
838 		cookie->result->entry = curEntry;
839 		cookie->nextEntry = curEntry;
840 	} else {
841 		cookie->nextEntry->next = curEntry;
842 		cookie->nextEntry = curEntry;
843 	}
844 	cookie->result->entries_count++;
845 
846 	return (NS_LDAP_SUCCESS);
847 }
848 
849 static int
850 __s_api_get_cachemgr_data(const char *type,
851 		const char *from, char **to)
852 {
853 	union {
854 		ldap_data_t	s_d;
855 		char		s_b[DOORBUFFERSIZE];
856 	} space;
857 	ldap_data_t	*sptr;
858 	int		ndata;
859 	int		adata;
860 	int		rc;
861 
862 #ifdef DEBUG
863 	(void) fprintf(stderr, "__s_api_get_cachemgr_data START\n");
864 #endif
865 	/*
866 	 * We are not going to perform DN to domain mapping
867 	 * in the Standalone mode
868 	 */
869 	if (__s_api_isStandalone()) {
870 		return (-1);
871 	}
872 
873 	if (from == NULL || from[0] == '\0' || to == NULL)
874 		return (-1);
875 
876 	*to = NULL;
877 	(void) memset(space.s_b, 0, DOORBUFFERSIZE);
878 
879 	space.s_d.ldap_call.ldap_callnumber = GETCACHE;
880 	(void) snprintf(space.s_d.ldap_call.ldap_u.domainname,
881 	    DOORBUFFERSIZE - sizeof (space.s_d.ldap_call.ldap_callnumber),
882 	    "%s%s%s",
883 	    type,
884 	    DOORLINESEP,
885 	    from);
886 	ndata = sizeof (space);
887 	adata = sizeof (ldap_call_t) +
888 	    strlen(space.s_d.ldap_call.ldap_u.domainname) + 1;
889 	sptr = &space.s_d;
890 
891 	rc = __ns_ldap_trydoorcall(&sptr, &ndata, &adata);
892 	if (rc != NS_CACHE_SUCCESS)
893 		return (-1);
894 	else
895 		*to = strdup(sptr->ldap_ret.ldap_u.buff);
896 	return (NS_LDAP_SUCCESS);
897 }
898 
899 static int
900 __s_api_set_cachemgr_data(const char *type,
901 		const char *from, const char *to)
902 {
903 	union {
904 		ldap_data_t	s_d;
905 		char		s_b[DOORBUFFERSIZE];
906 	} space;
907 	ldap_data_t	*sptr;
908 	int		ndata;
909 	int		adata;
910 	int		rc;
911 
912 #ifdef DEBUG
913 	(void) fprintf(stderr, "__s_api_set_cachemgr_data START\n");
914 #endif
915 	/*
916 	 * We are not going to perform DN to domain mapping
917 	 * in the Standalone mode
918 	 */
919 	if (__s_api_isStandalone()) {
920 		return (-1);
921 	}
922 
923 	if ((from == NULL) || (from[0] == '\0') ||
924 	    (to == NULL) || (to[0] == '\0'))
925 		return (-1);
926 
927 	(void) memset(space.s_b, 0, DOORBUFFERSIZE);
928 
929 	space.s_d.ldap_call.ldap_callnumber = SETCACHE;
930 	(void) snprintf(space.s_d.ldap_call.ldap_u.domainname,
931 	    DOORBUFFERSIZE - sizeof (space.s_d.ldap_call.ldap_callnumber),
932 	    "%s%s%s%s%s",
933 	    type,
934 	    DOORLINESEP,
935 	    from,
936 	    DOORLINESEP,
937 	    to);
938 
939 	ndata = sizeof (space);
940 	adata = sizeof (ldap_call_t) +
941 	    strlen(space.s_d.ldap_call.ldap_u.domainname) + 1;
942 	sptr = &space.s_d;
943 
944 	rc = __ns_ldap_trydoorcall(&sptr, &ndata, &adata);
945 	if (rc != NS_CACHE_SUCCESS)
946 		return (-1);
947 
948 	return (NS_LDAP_SUCCESS);
949 }
950 
951 
952 static char *
953 __s_api_remove_rdn_space(char *rdn)
954 {
955 	char	*tf, *tl, *vf, *vl, *eqsign;
956 
957 	/* if no space(s) to remove, return */
958 	if (strchr(rdn, SPACETOK) == NULL)
959 		return (rdn);
960 
961 	/* if no '=' separator, return */
962 	eqsign = strchr(rdn, '=');
963 	if (eqsign == NULL)
964 		return (rdn);
965 
966 	tf = rdn;
967 	tl = eqsign - 1;
968 	vf = eqsign + 1;
969 	vl = rdn + strlen(rdn) - 1;
970 
971 	/* now two strings, type and value */
972 	*eqsign = '\0';
973 
974 	/* remove type's leading spaces */
975 	while (tf < tl && *tf == SPACETOK)
976 		tf++;
977 	/* remove type's trailing spaces */
978 	while (tf < tl && *tl == SPACETOK)
979 		tl--;
980 	/* add '=' separator back */
981 	*(++tl) = '=';
982 	/* remove value's leading spaces */
983 	while (vf < vl && *vf == SPACETOK)
984 		vf++;
985 	/* remove value's trailing spaces */
986 	while (vf < vl && *vl == SPACETOK)
987 		*vl-- = '\0';
988 
989 	/* move value up if necessary */
990 	if (vf != tl + 1)
991 		(void) strcpy(tl + 1, vf);
992 
993 	return (tf);
994 }
995 
996 static
997 ns_ldap_cookie_t *
998 init_search_state_machine()
999 {
1000 	ns_ldap_cookie_t	*cookie;
1001 	ns_config_t		*cfg;
1002 
1003 	cookie = (ns_ldap_cookie_t *)calloc(1, sizeof (ns_ldap_cookie_t));
1004 	if (cookie == NULL)
1005 		return (NULL);
1006 	cookie->state = INIT;
1007 	/* assign other state variables */
1008 	cfg = __s_api_loadrefresh_config();
1009 	cookie->connectionId = -1;
1010 	if (cfg == NULL ||
1011 	    cfg->paramList[NS_LDAP_SEARCH_TIME_P].ns_ptype == NS_UNKNOWN) {
1012 		cookie->search_timeout.tv_sec = NS_DEFAULT_SEARCH_TIMEOUT;
1013 	} else {
1014 		cookie->search_timeout.tv_sec =
1015 		    cfg->paramList[NS_LDAP_SEARCH_TIME_P].ns_i;
1016 	}
1017 	if (cfg != NULL)
1018 		__s_api_release_config(cfg);
1019 	cookie->search_timeout.tv_usec = 0;
1020 
1021 	return (cookie);
1022 }
1023 
1024 static void
1025 delete_search_cookie(ns_ldap_cookie_t *cookie)
1026 {
1027 	if (cookie == NULL)
1028 		return;
1029 	if (cookie->connectionId > -1)
1030 		DropConnection(cookie->connectionId, cookie->i_flags);
1031 	if (cookie->filter)
1032 		free(cookie->filter);
1033 	if (cookie->i_filter)
1034 		free(cookie->i_filter);
1035 	if (cookie->service)
1036 		free(cookie->service);
1037 	if (cookie->sdlist)
1038 		(void) __ns_ldap_freeSearchDescriptors(&(cookie->sdlist));
1039 	if (cookie->result)
1040 		(void) __ns_ldap_freeResult(&cookie->result);
1041 	if (cookie->attribute)
1042 		__s_api_free2dArray(cookie->attribute);
1043 	if (cookie->errorp)
1044 		(void) __ns_ldap_freeError(&cookie->errorp);
1045 	if (cookie->reflist)
1046 		__s_api_deleteRefInfo(cookie->reflist);
1047 	if (cookie->basedn)
1048 		free(cookie->basedn);
1049 	if (cookie->ctrlCookie)
1050 		ber_bvfree(cookie->ctrlCookie);
1051 	_freeControlList(&cookie->p_serverctrls);
1052 	if (cookie->resultctrl)
1053 		ldap_controls_free(cookie->resultctrl);
1054 	free(cookie);
1055 }
1056 
1057 static int
1058 get_mapped_filter(ns_ldap_cookie_t *cookie, char **new_filter)
1059 {
1060 
1061 	typedef	struct	filter_mapping_info {
1062 		char	oc_or_attr;
1063 		char	*name_start;
1064 		char	*name_end;
1065 		char	*veq_pos;
1066 		char	*from_name;
1067 		char	*to_name;
1068 		char	**mapping;
1069 	} filter_mapping_info_t;
1070 
1071 	char			*c, *last_copied;
1072 	char			*filter_c, *filter_c_next;
1073 	char			*key, *tail, *head;
1074 	char			errstr[MAXERROR];
1075 	int			num_eq = 0, num_veq = 0;
1076 	int			in_quote = FALSE;
1077 	int			is_value = FALSE;
1078 	int			i, j, oc_len, len;
1079 	int			at_least_one = FALSE;
1080 	filter_mapping_info_t	**info, *info1;
1081 	char			**mapping;
1082 	char			*service, *filter, *err;
1083 	int			auto_service = FALSE;
1084 
1085 	if (cookie == NULL || new_filter == NULL)
1086 		return (NS_LDAP_INVALID_PARAM);
1087 
1088 	*new_filter = NULL;
1089 	service = cookie->service;
1090 	filter = cookie->filter;
1091 
1092 	/*
1093 	 * count the number of '=' char
1094 	 */
1095 	for (c = filter; *c; c++) {
1096 		if (*c == TOKENSEPARATOR)
1097 			num_eq++;
1098 	}
1099 
1100 	if (service != NULL && strncasecmp(service, "auto_", 5) == 0)
1101 		auto_service = TRUE;
1102 
1103 	/*
1104 	 * See if schema mapping existed for the given service.
1105 	 * If not, just return success.
1106 	 */
1107 	mapping = __ns_ldap_getOrigAttribute(service,
1108 	    NS_HASH_SCHEMA_MAPPING_EXISTED);
1109 
1110 	if (mapping == NULL && auto_service)
1111 		/*
1112 		 * if service == auto_* and no
1113 		 * schema mapping found
1114 		 * then try automount
1115 		 */
1116 		mapping = __ns_ldap_getOrigAttribute(
1117 		    "automount", NS_HASH_SCHEMA_MAPPING_EXISTED);
1118 
1119 	if (mapping)
1120 		__s_api_free2dArray(mapping);
1121 	else
1122 		return (NS_LDAP_SUCCESS);
1123 
1124 	/*
1125 	 * no '=' sign, just say OK and return nothing
1126 	 */
1127 	if (num_eq == 0)
1128 		return (NS_LDAP_SUCCESS);
1129 
1130 	/*
1131 	 * Make a copy of the filter string
1132 	 * for saving the name of the objectclasses or
1133 	 * attributes that need to be passed to the
1134 	 * objectclass or attribute mapping functions.
1135 	 * pointer "info->from_name" points to the locations
1136 	 * within this string.
1137 	 *
1138 	 * The input filter string, filter, will be used
1139 	 * to indicate where these names start and end.
1140 	 * pointers "info->name_start" and "info->name_end"
1141 	 * point to locations within the input filter string,
1142 	 * and are used at the end of this function to
1143 	 * merge the original filter data with the
1144 	 * mapped objectclass or attribute names.
1145 	 */
1146 	filter_c = strdup(filter);
1147 	if (filter_c == NULL)
1148 		return (NS_LDAP_MEMORY);
1149 	filter_c_next = filter_c;
1150 
1151 	/*
1152 	 * get memory for info arrays
1153 	 */
1154 	info = (filter_mapping_info_t **)calloc(num_eq + 1,
1155 	    sizeof (filter_mapping_info_t *));
1156 
1157 	if (info == NULL) {
1158 		free(filter_c);
1159 		return (NS_LDAP_MEMORY);
1160 	}
1161 
1162 	/*
1163 	 * find valid '=' for further processing,
1164 	 * ignore the "escaped =" (.i.e. "\="), or
1165 	 * "=" in quoted string
1166 	 */
1167 	for (c = filter_c; *c; c++) {
1168 
1169 		switch (*c) {
1170 		case TOKENSEPARATOR:
1171 			if (!in_quote && !is_value) {
1172 				info1 = (filter_mapping_info_t *)calloc(1,
1173 				    sizeof (filter_mapping_info_t));
1174 				if (!info1) {
1175 					free(filter_c);
1176 					for (i = 0; i < num_veq; i++)
1177 						free(info[i]);
1178 					free(info);
1179 					return (NS_LDAP_MEMORY);
1180 				}
1181 				info[num_veq] = info1;
1182 
1183 				/*
1184 				 * remember the location of this "="
1185 				 */
1186 				info[num_veq++]->veq_pos = c;
1187 
1188 				/*
1189 				 * skip until the end of the attribute value
1190 				 */
1191 				is_value = TRUE;
1192 			}
1193 			break;
1194 		case CPARATOK:
1195 			/*
1196 			 * mark the end of the attribute value
1197 			 */
1198 			if (!in_quote)
1199 				is_value = FALSE;
1200 			break;
1201 		case QUOTETOK:
1202 			/*
1203 			 * switch on/off the in_quote mode
1204 			 */
1205 			in_quote = (in_quote == FALSE);
1206 			break;
1207 		case '\\':
1208 			/*
1209 			 * ignore escape characters
1210 			 * don't skip if next char is '\0'
1211 			 */
1212 			if (!in_quote)
1213 				if (*(++c) == '\0')
1214 					c--;
1215 			break;
1216 		}
1217 
1218 	}
1219 
1220 	/*
1221 	 * for each valid "=" found, get the name to
1222 	 * be mapped
1223 	 */
1224 	oc_len = strlen("objectclass");
1225 	for (i = 0; i < num_veq; i++) {
1226 
1227 		/*
1228 		 * look at the left side of "=" to see
1229 		 * if assertion is "objectclass=<ocname>"
1230 		 * or "<attribute name>=<attribute value>"
1231 		 *
1232 		 * first skip spaces before "=".
1233 		 * Note that filter_c_next may not point to the
1234 		 * start of the filter string. For i > 0,
1235 		 * it points to the end of the last name processed + 2
1236 		 */
1237 		for (tail = info[i]->veq_pos; (tail > filter_c_next) &&
1238 		    (*(tail - 1) == SPACETOK); tail--)
1239 			;
1240 
1241 		/*
1242 		 * mark the end of the left side string (the key)
1243 		 */
1244 		*tail = '\0';
1245 		info[i]->name_end = tail - filter_c - 1 + filter;
1246 
1247 		/*
1248 		 * find the start of the key
1249 		 */
1250 		key = filter_c_next;
1251 		for (c = tail; filter_c_next <= c; c--) {
1252 			/* OPARATOK is '(' */
1253 			if (*c == OPARATOK ||
1254 			    *c == SPACETOK) {
1255 				key = c + 1;
1256 				break;
1257 			}
1258 		}
1259 		info[i]->name_start = key - filter_c + filter;
1260 
1261 		if ((key + oc_len) <= tail) {
1262 			if (strncasecmp(key, "objectclass",
1263 			    oc_len) == 0) {
1264 				/*
1265 				 * assertion is "objectclass=ocname",
1266 				 * ocname is the one needs to be mapped
1267 				 *
1268 				 * skip spaces after "=" to find start
1269 				 * of the ocname
1270 				 */
1271 				head = info[i]->veq_pos;
1272 				for (head = info[i]->veq_pos + 1;
1273 				    *head && *head == SPACETOK; head++)
1274 					;
1275 
1276 				/* ignore empty ocname */
1277 				if (!(*head))
1278 					continue;
1279 
1280 				info[i]->name_start = head - filter_c +
1281 				    filter;
1282 
1283 				/*
1284 				 * now find the end of the ocname
1285 				 */
1286 				for (c = head; ; c++) {
1287 					/* CPARATOK is ')' */
1288 					if (*c == CPARATOK ||
1289 					    *c == '\0' ||
1290 					    *c == SPACETOK) {
1291 						*c = '\0';
1292 						info[i]->name_end =
1293 						    c - filter_c - 1 +
1294 						    filter;
1295 						filter_c_next = c + 1;
1296 						info[i]->oc_or_attr = 'o';
1297 						info[i]->from_name = head;
1298 						break;
1299 					}
1300 				}
1301 			}
1302 		}
1303 
1304 		/*
1305 		 * assertion is not "objectclass=ocname",
1306 		 * assume assertion is "<key> = <value>",
1307 		 * <key> is the one needs to be mapped
1308 		 */
1309 		if (info[i]->from_name == NULL && strlen(key) > 0) {
1310 			info[i]->oc_or_attr = 'a';
1311 			info[i]->from_name = key;
1312 		}
1313 	}
1314 
1315 	/* perform schema mapping */
1316 	for (i = 0; i < num_veq; i++) {
1317 		if (info[i]->from_name == NULL)
1318 			continue;
1319 
1320 		if (info[i]->oc_or_attr == 'a')
1321 			info[i]->mapping =
1322 			    __ns_ldap_getMappedAttributes(service,
1323 			    info[i]->from_name);
1324 		else
1325 			info[i]->mapping =
1326 			    __ns_ldap_getMappedObjectClass(service,
1327 			    info[i]->from_name);
1328 
1329 		if (info[i]->mapping == NULL && auto_service)  {
1330 			/*
1331 			 * If no mapped attribute/objectclass is found
1332 			 * and service == auto*
1333 			 * try to find automount's
1334 			 * mapped attribute/objectclass
1335 			 */
1336 			if (info[i]->oc_or_attr == 'a')
1337 				info[i]->mapping =
1338 				    __ns_ldap_getMappedAttributes("automount",
1339 				    info[i]->from_name);
1340 			else
1341 				info[i]->mapping =
1342 				    __ns_ldap_getMappedObjectClass("automount",
1343 				    info[i]->from_name);
1344 		}
1345 
1346 		if (info[i]->mapping == NULL ||
1347 		    info[i]->mapping[0] == NULL) {
1348 			info[i]->to_name = NULL;
1349 		} else if (info[i]->mapping[1] == NULL) {
1350 			info[i]->to_name = info[i]->mapping[0];
1351 			at_least_one = TRUE;
1352 		} else {
1353 			__s_api_free2dArray(info[i]->mapping);
1354 			/*
1355 			 * multiple mapping
1356 			 * not allowed
1357 			 */
1358 			(void) sprintf(errstr,
1359 			    gettext(
1360 			    "Multiple attribute or objectclass "
1361 			    "mapping for '%s' in filter "
1362 			    "'%s' not allowed."),
1363 			    info[i]->from_name, filter);
1364 			err = strdup(errstr);
1365 			if (err) {
1366 				MKERROR(LOG_WARNING, cookie->errorp,
1367 				    NS_CONFIG_SYNTAX,
1368 				    err, NULL);
1369 			}
1370 
1371 			free(filter_c);
1372 			for (j = 0; j < num_veq; j++) {
1373 				if (info[j]->mapping)
1374 					__s_api_free2dArray(
1375 					    info[j]->mapping);
1376 				free(info[j]);
1377 			}
1378 			free(info);
1379 			return (NS_LDAP_CONFIG);
1380 		}
1381 	}
1382 
1383 
1384 	if (at_least_one) {
1385 
1386 		len = strlen(filter);
1387 		last_copied = filter - 1;
1388 
1389 		for (i = 0; i < num_veq; i++) {
1390 			if (info[i]->to_name)
1391 				len += strlen(info[i]->to_name);
1392 		}
1393 
1394 		*new_filter = (char *)calloc(1, len);
1395 		if (*new_filter == NULL) {
1396 			free(filter_c);
1397 			for (j = 0; j < num_veq; j++) {
1398 				if (info[j]->mapping)
1399 					__s_api_free2dArray(
1400 					    info[j]->mapping);
1401 				free(info[j]);
1402 			}
1403 			free(info);
1404 			return (NS_LDAP_MEMORY);
1405 		}
1406 
1407 		for (i = 0; i < num_veq; i++) {
1408 			if (info[i]->to_name != NULL &&
1409 			    info[i]->to_name != NULL) {
1410 
1411 				/*
1412 				 * copy the original filter data
1413 				 * between the last name and current
1414 				 * name
1415 				 */
1416 				if ((last_copied + 1) != info[i]->name_start)
1417 					(void) strncat(*new_filter,
1418 					    last_copied + 1,
1419 					    info[i]->name_start -
1420 					    last_copied - 1);
1421 
1422 				/* the data is copied */
1423 				last_copied = info[i]->name_end;
1424 
1425 				/*
1426 				 * replace the name with
1427 				 * the mapped name
1428 				 */
1429 				(void) strcat(*new_filter, info[i]->to_name);
1430 			}
1431 
1432 			/* copy the filter data after the last name */
1433 			if (i == (num_veq -1) &&
1434 			    info[i]->name_end <
1435 			    (filter + strlen(filter)))
1436 				(void) strncat(*new_filter, last_copied + 1,
1437 				    filter + strlen(filter) -
1438 				    last_copied - 1);
1439 		}
1440 
1441 	}
1442 
1443 	/* free memory */
1444 	free(filter_c);
1445 	for (j = 0; j < num_veq; j++) {
1446 		if (info[j]->mapping)
1447 			__s_api_free2dArray(info[j]->mapping);
1448 		free(info[j]);
1449 	}
1450 	free(info);
1451 
1452 	return (NS_LDAP_SUCCESS);
1453 }
1454 
1455 static int
1456 setup_next_search(ns_ldap_cookie_t *cookie)
1457 {
1458 	ns_ldap_search_desc_t	*dptr;
1459 	int			scope;
1460 	char			*filter, *str;
1461 	int			baselen;
1462 	int			rc;
1463 	void			**param;
1464 
1465 	dptr = *cookie->sdpos;
1466 	scope = cookie->i_flags & (NS_LDAP_SCOPE_BASE |
1467 	    NS_LDAP_SCOPE_ONELEVEL |
1468 	    NS_LDAP_SCOPE_SUBTREE);
1469 	if (scope)
1470 		cookie->scope = scope;
1471 	else
1472 		cookie->scope = dptr->scope;
1473 	switch (cookie->scope) {
1474 	case NS_LDAP_SCOPE_BASE:
1475 		cookie->scope = LDAP_SCOPE_BASE;
1476 		break;
1477 	case NS_LDAP_SCOPE_ONELEVEL:
1478 		cookie->scope = LDAP_SCOPE_ONELEVEL;
1479 		break;
1480 	case NS_LDAP_SCOPE_SUBTREE:
1481 		cookie->scope = LDAP_SCOPE_SUBTREE;
1482 		break;
1483 	}
1484 
1485 	filter = NULL;
1486 	if (cookie->use_filtercb && cookie->init_filter_cb &&
1487 	    dptr->filter && strlen(dptr->filter) > 0) {
1488 		(*cookie->init_filter_cb)(dptr, &filter,
1489 		    cookie->userdata);
1490 	}
1491 	if (filter == NULL) {
1492 		if (cookie->i_filter == NULL) {
1493 			cookie->err_rc = NS_LDAP_INVALID_PARAM;
1494 			return (-1);
1495 		} else {
1496 			if (cookie->filter)
1497 				free(cookie->filter);
1498 			cookie->filter = strdup(cookie->i_filter);
1499 			if (cookie->filter == NULL) {
1500 				cookie->err_rc = NS_LDAP_MEMORY;
1501 				return (-1);
1502 			}
1503 		}
1504 	} else {
1505 		if (cookie->filter)
1506 			free(cookie->filter);
1507 		cookie->filter = strdup(filter);
1508 		free(filter);
1509 		if (cookie->filter == NULL) {
1510 			cookie->err_rc = NS_LDAP_MEMORY;
1511 			return (-1);
1512 		}
1513 	}
1514 
1515 	/*
1516 	 * perform attribute/objectclass mapping on filter
1517 	 */
1518 	filter = NULL;
1519 
1520 	if (cookie->service) {
1521 		rc = get_mapped_filter(cookie, &filter);
1522 		if (rc != NS_LDAP_SUCCESS) {
1523 			cookie->err_rc = rc;
1524 			return (-1);
1525 		} else {
1526 			/*
1527 			 * get_mapped_filter returns
1528 			 * NULL filter pointer, if
1529 			 * no mapping was done
1530 			 */
1531 			if (filter) {
1532 				free(cookie->filter);
1533 				cookie->filter = filter;
1534 			}
1535 		}
1536 	}
1537 
1538 	/*
1539 	 * validate filter to make sure it's legal
1540 	 * [remove redundant ()'s]
1541 	 */
1542 	rc = validate_filter(cookie);
1543 	if (rc != NS_LDAP_SUCCESS) {
1544 		cookie->err_rc = rc;
1545 		return (-1);
1546 	}
1547 
1548 	baselen = strlen(dptr->basedn);
1549 	if (baselen > 0 && dptr->basedn[baselen-1] == COMMATOK) {
1550 		rc = __ns_ldap_getParam(NS_LDAP_SEARCH_BASEDN_P,
1551 		    (void ***)&param, &cookie->errorp);
1552 		if (rc != NS_LDAP_SUCCESS) {
1553 			cookie->err_rc = rc;
1554 			return (-1);
1555 		}
1556 		str = ((char **)param)[0];
1557 		baselen += strlen(str)+1;
1558 		if (cookie->basedn)
1559 			free(cookie->basedn);
1560 		cookie->basedn = (char *)malloc(baselen);
1561 		if (cookie->basedn == NULL) {
1562 			cookie->err_rc = NS_LDAP_MEMORY;
1563 			return (-1);
1564 		}
1565 		(void) strcpy(cookie->basedn, dptr->basedn);
1566 		(void) strcat(cookie->basedn, str);
1567 		(void) __ns_ldap_freeParam(&param);
1568 	} else {
1569 		if (cookie->basedn)
1570 			free(cookie->basedn);
1571 		cookie->basedn = strdup(dptr->basedn);
1572 	}
1573 	return (0);
1574 }
1575 
1576 static int
1577 setup_referral_search(ns_ldap_cookie_t *cookie)
1578 {
1579 	ns_referral_info_t	*ref;
1580 
1581 	ref = cookie->refpos;
1582 	cookie->scope = ref->refScope;
1583 	if (cookie->filter) {
1584 		free(cookie->filter);
1585 	}
1586 	cookie->filter = strdup(ref->refFilter);
1587 	if (cookie->basedn) {
1588 		free(cookie->basedn);
1589 	}
1590 	cookie->basedn = strdup(ref->refDN);
1591 	if (cookie->filter == NULL || cookie->basedn == NULL) {
1592 		cookie->err_rc = NS_LDAP_MEMORY;
1593 		return (-1);
1594 	}
1595 	return (0);
1596 }
1597 
1598 static int
1599 get_current_session(ns_ldap_cookie_t *cookie)
1600 {
1601 	ConnectionID	connectionId = -1;
1602 	Connection	*conp = NULL;
1603 	int		rc;
1604 	int		fail_if_new_pwd_reqd = 1;
1605 
1606 	rc = __s_api_getConnection(NULL, cookie->i_flags,
1607 	    cookie->i_auth, &connectionId, &conp,
1608 	    &cookie->errorp, fail_if_new_pwd_reqd,
1609 	    cookie->nopasswd_acct_mgmt, cookie->conn_user);
1610 
1611 	/*
1612 	 * If password control attached in *cookie->errorp,
1613 	 * e.g. rc == NS_LDAP_SUCCESS_WITH_INFO,
1614 	 * free the error structure (we do not need
1615 	 * the sec_to_expired info).
1616 	 * Reset rc to NS_LDAP_SUCCESS.
1617 	 */
1618 	if (rc == NS_LDAP_SUCCESS_WITH_INFO) {
1619 		(void) __ns_ldap_freeError(
1620 		    &cookie->errorp);
1621 		cookie->errorp = NULL;
1622 		rc = NS_LDAP_SUCCESS;
1623 	}
1624 
1625 	if (rc != NS_LDAP_SUCCESS) {
1626 		cookie->err_rc = rc;
1627 		return (-1);
1628 	}
1629 	cookie->conn = conp;
1630 	cookie->connectionId = connectionId;
1631 
1632 	return (0);
1633 }
1634 
1635 static int
1636 get_next_session(ns_ldap_cookie_t *cookie)
1637 {
1638 	ConnectionID	connectionId = -1;
1639 	Connection	*conp = NULL;
1640 	int		rc;
1641 	int		fail_if_new_pwd_reqd = 1;
1642 
1643 	if (cookie->connectionId > -1) {
1644 		DropConnection(cookie->connectionId, cookie->i_flags);
1645 		cookie->connectionId = -1;
1646 	}
1647 
1648 	/* If using a MT connection, return it. */
1649 	if (cookie->conn_user != NULL &&
1650 	    cookie->conn_user->conn_mt != NULL)
1651 		__s_api_conn_mt_return(cookie->conn_user);
1652 
1653 	rc = __s_api_getConnection(NULL, cookie->i_flags,
1654 	    cookie->i_auth, &connectionId, &conp,
1655 	    &cookie->errorp, fail_if_new_pwd_reqd,
1656 	    cookie->nopasswd_acct_mgmt, cookie->conn_user);
1657 
1658 	/*
1659 	 * If password control attached in *cookie->errorp,
1660 	 * e.g. rc == NS_LDAP_SUCCESS_WITH_INFO,
1661 	 * free the error structure (we do not need
1662 	 * the sec_to_expired info).
1663 	 * Reset rc to NS_LDAP_SUCCESS.
1664 	 */
1665 	if (rc == NS_LDAP_SUCCESS_WITH_INFO) {
1666 		(void) __ns_ldap_freeError(
1667 		    &cookie->errorp);
1668 		cookie->errorp = NULL;
1669 		rc = NS_LDAP_SUCCESS;
1670 	}
1671 
1672 	if (rc != NS_LDAP_SUCCESS) {
1673 		cookie->err_rc = rc;
1674 		return (-1);
1675 	}
1676 	cookie->conn = conp;
1677 	cookie->connectionId = connectionId;
1678 	return (0);
1679 }
1680 
1681 static int
1682 get_referral_session(ns_ldap_cookie_t *cookie)
1683 {
1684 	ConnectionID	connectionId = -1;
1685 	Connection	*conp = NULL;
1686 	int		rc;
1687 	int		fail_if_new_pwd_reqd = 1;
1688 
1689 	if (cookie->connectionId > -1) {
1690 		DropConnection(cookie->connectionId, cookie->i_flags);
1691 		cookie->connectionId = -1;
1692 	}
1693 
1694 	/* set it up to use a connection opened for referral */
1695 	if (cookie->conn_user != NULL) {
1696 		/* If using a MT connection, return it. */
1697 		if (cookie->conn_user->conn_mt != NULL)
1698 			__s_api_conn_mt_return(cookie->conn_user);
1699 		cookie->conn_user->referral = B_TRUE;
1700 	}
1701 
1702 	rc = __s_api_getConnection(cookie->refpos->refHost, 0,
1703 	    cookie->i_auth, &connectionId, &conp,
1704 	    &cookie->errorp, fail_if_new_pwd_reqd,
1705 	    cookie->nopasswd_acct_mgmt, cookie->conn_user);
1706 
1707 	/*
1708 	 * If password control attached in *cookie->errorp,
1709 	 * e.g. rc == NS_LDAP_SUCCESS_WITH_INFO,
1710 	 * free the error structure (we do not need
1711 	 * the sec_to_expired info).
1712 	 * Reset rc to NS_LDAP_SUCCESS.
1713 	 */
1714 	if (rc == NS_LDAP_SUCCESS_WITH_INFO) {
1715 		(void) __ns_ldap_freeError(
1716 		    &cookie->errorp);
1717 		cookie->errorp = NULL;
1718 		rc = NS_LDAP_SUCCESS;
1719 	}
1720 
1721 	if (rc != NS_LDAP_SUCCESS) {
1722 		cookie->err_rc = rc;
1723 		return (-1);
1724 	}
1725 	cookie->conn = conp;
1726 	cookie->connectionId = connectionId;
1727 	return (0);
1728 }
1729 
1730 static int
1731 paging_supported(ns_ldap_cookie_t *cookie)
1732 {
1733 	int		rc;
1734 
1735 	cookie->listType = 0;
1736 	rc = __s_api_isCtrlSupported(cookie->conn,
1737 	    LDAP_CONTROL_VLVREQUEST);
1738 	if (rc == NS_LDAP_SUCCESS) {
1739 		cookie->listType = VLVCTRLFLAG;
1740 		return (1);
1741 	}
1742 	rc = __s_api_isCtrlSupported(cookie->conn,
1743 	    LDAP_CONTROL_SIMPLE_PAGE);
1744 	if (rc == NS_LDAP_SUCCESS) {
1745 		cookie->listType = SIMPLEPAGECTRLFLAG;
1746 		return (1);
1747 	}
1748 	return (0);
1749 }
1750 
1751 typedef struct servicesorttype {
1752 	char *service;
1753 	ns_srvsidesort_t type;
1754 } servicesorttype_t;
1755 
1756 static servicesorttype_t *sort_type = NULL;
1757 static int sort_type_size = 0;
1758 static int sort_type_hwm = 0;
1759 static mutex_t sort_type_mutex = DEFAULTMUTEX;
1760 
1761 
1762 static ns_srvsidesort_t
1763 get_srvsidesort_type(char *service)
1764 {
1765 	int i;
1766 	ns_srvsidesort_t type = SSS_UNKNOWN;
1767 
1768 	if (service == NULL)
1769 		return (type);
1770 
1771 	(void) mutex_lock(&sort_type_mutex);
1772 	if (sort_type != NULL) {
1773 		for (i = 0; i < sort_type_hwm; i++) {
1774 			if (strcmp(sort_type[i].service, service) == 0) {
1775 				type = sort_type[i].type;
1776 				break;
1777 			}
1778 		}
1779 	}
1780 	(void) mutex_unlock(&sort_type_mutex);
1781 	return (type);
1782 }
1783 
1784 static void
1785 update_srvsidesort_type(char *service, ns_srvsidesort_t type)
1786 {
1787 	int i, size;
1788 	servicesorttype_t *tmp;
1789 
1790 	if (service == NULL)
1791 		return;
1792 
1793 	(void) mutex_lock(&sort_type_mutex);
1794 
1795 	for (i = 0; i < sort_type_hwm; i++) {
1796 		if (strcmp(sort_type[i].service, service) == 0) {
1797 			sort_type[i].type = type;
1798 			(void) mutex_unlock(&sort_type_mutex);
1799 			return;
1800 		}
1801 	}
1802 	if (sort_type == NULL) {
1803 		size = 10;
1804 		tmp = malloc(size * sizeof (servicesorttype_t));
1805 		if (tmp == NULL) {
1806 			(void) mutex_unlock(&sort_type_mutex);
1807 			return;
1808 		}
1809 		sort_type = tmp;
1810 		sort_type_size = size;
1811 	} else if (sort_type_hwm >= sort_type_size) {
1812 		size = sort_type_size + 10;
1813 		tmp = realloc(sort_type, size * sizeof (servicesorttype_t));
1814 		if (tmp == NULL) {
1815 			(void) mutex_unlock(&sort_type_mutex);
1816 			return;
1817 		}
1818 		sort_type = tmp;
1819 		sort_type_size = size;
1820 	}
1821 	sort_type[sort_type_hwm].service = strdup(service);
1822 	if (sort_type[sort_type_hwm].service == NULL) {
1823 		(void) mutex_unlock(&sort_type_mutex);
1824 		return;
1825 	}
1826 	sort_type[sort_type_hwm].type = type;
1827 	sort_type_hwm++;
1828 
1829 	(void) mutex_unlock(&sort_type_mutex);
1830 }
1831 
1832 static int
1833 setup_vlv_params(ns_ldap_cookie_t *cookie)
1834 {
1835 	LDAPControl	**ctrls;
1836 	LDAPsortkey	**sortkeylist;
1837 	LDAPControl	*sortctrl = NULL;
1838 	LDAPControl	*vlvctrl = NULL;
1839 	LDAPVirtualList	vlist;
1840 	char		*sortattr;
1841 	int		rc;
1842 	int		free_sort = FALSE;
1843 
1844 	_freeControlList(&cookie->p_serverctrls);
1845 
1846 	if (cookie->sortTypeTry == SSS_UNKNOWN)
1847 		cookie->sortTypeTry = get_srvsidesort_type(cookie->service);
1848 	if (cookie->sortTypeTry == SSS_UNKNOWN)
1849 		cookie->sortTypeTry = SSS_SINGLE_ATTR;
1850 
1851 	if (cookie->sortTypeTry == SSS_SINGLE_ATTR) {
1852 		if ((cookie->i_flags & NS_LDAP_NOMAP) == 0 &&
1853 		    cookie->i_sortattr) {
1854 			sortattr =  __ns_ldap_mapAttribute(cookie->service,
1855 			    cookie->i_sortattr);
1856 			free_sort = TRUE;
1857 		} else if (cookie->i_sortattr) {
1858 			sortattr = (char *)cookie->i_sortattr;
1859 		} else {
1860 			sortattr = "cn";
1861 		}
1862 	} else {
1863 		sortattr = "cn uid";
1864 	}
1865 
1866 	rc = ldap_create_sort_keylist(&sortkeylist, sortattr);
1867 	if (free_sort)
1868 		free(sortattr);
1869 	if (rc != LDAP_SUCCESS) {
1870 		(void) ldap_get_option(cookie->conn->ld,
1871 		    LDAP_OPT_ERROR_NUMBER, &rc);
1872 		return (rc);
1873 	}
1874 	rc = ldap_create_sort_control(cookie->conn->ld,
1875 	    sortkeylist, 1, &sortctrl);
1876 	ldap_free_sort_keylist(sortkeylist);
1877 	if (rc != LDAP_SUCCESS) {
1878 		(void) ldap_get_option(cookie->conn->ld,
1879 		    LDAP_OPT_ERROR_NUMBER, &rc);
1880 		return (rc);
1881 	}
1882 
1883 	vlist.ldvlist_index = cookie->index;
1884 	vlist.ldvlist_size = 0;
1885 
1886 	vlist.ldvlist_before_count = 0;
1887 	vlist.ldvlist_after_count = LISTPAGESIZE-1;
1888 	vlist.ldvlist_attrvalue = NULL;
1889 	vlist.ldvlist_extradata = NULL;
1890 
1891 	rc = ldap_create_virtuallist_control(cookie->conn->ld,
1892 	    &vlist, &vlvctrl);
1893 	if (rc != LDAP_SUCCESS) {
1894 		ldap_control_free(sortctrl);
1895 		(void) ldap_get_option(cookie->conn->ld, LDAP_OPT_ERROR_NUMBER,
1896 		    &rc);
1897 		return (rc);
1898 	}
1899 
1900 	ctrls = (LDAPControl **)calloc(3, sizeof (LDAPControl *));
1901 	if (ctrls == NULL) {
1902 		ldap_control_free(sortctrl);
1903 		ldap_control_free(vlvctrl);
1904 		return (LDAP_NO_MEMORY);
1905 	}
1906 
1907 	ctrls[0] = sortctrl;
1908 	ctrls[1] = vlvctrl;
1909 
1910 	cookie->p_serverctrls = ctrls;
1911 	return (LDAP_SUCCESS);
1912 }
1913 
1914 static int
1915 setup_simplepg_params(ns_ldap_cookie_t *cookie)
1916 {
1917 	LDAPControl	**ctrls;
1918 	LDAPControl	*pgctrl = NULL;
1919 	int		rc;
1920 
1921 	_freeControlList(&cookie->p_serverctrls);
1922 
1923 	rc = ldap_create_page_control(cookie->conn->ld, LISTPAGESIZE,
1924 	    cookie->ctrlCookie, (char)0, &pgctrl);
1925 	if (rc != LDAP_SUCCESS) {
1926 		(void) ldap_get_option(cookie->conn->ld, LDAP_OPT_ERROR_NUMBER,
1927 		    &rc);
1928 		return (rc);
1929 	}
1930 
1931 	ctrls = (LDAPControl **)calloc(2, sizeof (LDAPControl *));
1932 	if (ctrls == NULL) {
1933 		ldap_control_free(pgctrl);
1934 		return (LDAP_NO_MEMORY);
1935 	}
1936 	ctrls[0] = pgctrl;
1937 	cookie->p_serverctrls = ctrls;
1938 	return (LDAP_SUCCESS);
1939 }
1940 
1941 static void
1942 proc_result_referrals(ns_ldap_cookie_t *cookie)
1943 {
1944 	int 		errCode, i, rc;
1945 	char 		**referrals = NULL;
1946 
1947 	/*
1948 	 * Only follow one level of referrals, i.e.
1949 	 * if already in referral mode, do nothing
1950 	 */
1951 	if (cookie->refpos == NULL) {
1952 		cookie->new_state = END_RESULT;
1953 		rc = ldap_parse_result(cookie->conn->ld,
1954 		    cookie->resultMsg,
1955 		    &errCode, NULL,
1956 		    NULL, &referrals,
1957 		    NULL, 0);
1958 		if (rc != NS_LDAP_SUCCESS) {
1959 			(void) ldap_get_option(cookie->conn->ld,
1960 			    LDAP_OPT_ERROR_NUMBER,
1961 			    &cookie->err_rc);
1962 			cookie->new_state = LDAP_ERROR;
1963 			return;
1964 		}
1965 		if (errCode == LDAP_REFERRAL) {
1966 			for (i = 0; referrals[i] != NULL;
1967 			    i++) {
1968 				/* add to referral list */
1969 				rc = __s_api_addRefInfo(
1970 				    &cookie->reflist,
1971 				    referrals[i],
1972 				    cookie->basedn,
1973 				    &cookie->scope,
1974 				    cookie->filter,
1975 				    cookie->conn->ld);
1976 				if (rc != NS_LDAP_SUCCESS) {
1977 					cookie->new_state =
1978 					    ERROR;
1979 					break;
1980 				}
1981 			}
1982 			ldap_value_free(referrals);
1983 		}
1984 	}
1985 }
1986 
1987 static void
1988 proc_search_references(ns_ldap_cookie_t *cookie)
1989 {
1990 	char 		**refurls = NULL;
1991 	int 		i, rc;
1992 
1993 	/*
1994 	 * Only follow one level of referrals, i.e.
1995 	 * if already in referral mode, do nothing
1996 	 */
1997 	if (cookie->refpos == NULL) {
1998 		refurls = ldap_get_reference_urls(
1999 		    cookie->conn->ld,
2000 		    cookie->resultMsg);
2001 		if (refurls == NULL) {
2002 			(void) ldap_get_option(cookie->conn->ld,
2003 			    LDAP_OPT_ERROR_NUMBER,
2004 			    &cookie->err_rc);
2005 			cookie->new_state = LDAP_ERROR;
2006 			return;
2007 		}
2008 		for (i = 0; refurls[i] != NULL; i++) {
2009 			/* add to referral list */
2010 			rc = __s_api_addRefInfo(
2011 			    &cookie->reflist,
2012 			    refurls[i],
2013 			    cookie->basedn,
2014 			    &cookie->scope,
2015 			    cookie->filter,
2016 			    cookie->conn->ld);
2017 			if (rc != NS_LDAP_SUCCESS) {
2018 				cookie->new_state =
2019 				    ERROR;
2020 				break;
2021 			}
2022 		}
2023 		/* free allocated storage */
2024 		for (i = 0; refurls[i] != NULL; i++)
2025 			free(refurls[i]);
2026 	}
2027 }
2028 
2029 static ns_state_t
2030 multi_result(ns_ldap_cookie_t *cookie)
2031 {
2032 	char		errstr[MAXERROR];
2033 	char		*err;
2034 	ns_ldap_error_t **errorp = NULL;
2035 	LDAPControl	**retCtrls = NULL;
2036 	int		i, rc;
2037 	int		errCode;
2038 	int		finished = 0;
2039 	unsigned long	target_posp = 0;
2040 	unsigned long	list_size = 0;
2041 	unsigned int	count = 0;
2042 	char 		**referrals = NULL;
2043 
2044 	if (cookie->listType == VLVCTRLFLAG) {
2045 		rc = ldap_parse_result(cookie->conn->ld, cookie->resultMsg,
2046 		    &errCode, NULL, NULL, &referrals, &retCtrls, 0);
2047 		if (rc != LDAP_SUCCESS) {
2048 			(void) ldap_get_option(cookie->conn->ld,
2049 			    LDAP_OPT_ERROR_NUMBER,
2050 			    &cookie->err_rc);
2051 			(void) sprintf(errstr,
2052 			    gettext("LDAP ERROR (%d): %s.\n"),
2053 			    cookie->err_rc,
2054 			    gettext(ldap_err2string(cookie->err_rc)));
2055 			err = strdup(errstr);
2056 			MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL, err,
2057 			    NULL);
2058 			cookie->err_rc = NS_LDAP_INTERNAL;
2059 			cookie->errorp = *errorp;
2060 			return (LDAP_ERROR);
2061 		}
2062 		if (errCode == LDAP_REFERRAL) {
2063 			for (i = 0; referrals[i] != NULL;
2064 			    i++) {
2065 				/* add to referral list */
2066 				rc = __s_api_addRefInfo(
2067 				    &cookie->reflist,
2068 				    referrals[i],
2069 				    cookie->basedn,
2070 				    &cookie->scope,
2071 				    cookie->filter,
2072 				    cookie->conn->ld);
2073 				if (rc != NS_LDAP_SUCCESS) {
2074 					ldap_value_free(
2075 					    referrals);
2076 					if (retCtrls)
2077 						ldap_controls_free(
2078 						    retCtrls);
2079 					return (ERROR);
2080 				}
2081 			}
2082 			ldap_value_free(referrals);
2083 			if (retCtrls)
2084 				ldap_controls_free(retCtrls);
2085 			return (END_RESULT);
2086 		}
2087 		if (retCtrls) {
2088 			rc = ldap_parse_virtuallist_control(
2089 			    cookie->conn->ld, retCtrls,
2090 			    &target_posp, &list_size, &errCode);
2091 			if (rc == LDAP_SUCCESS) {
2092 				/*
2093 				 * AD does not return valid target_posp
2094 				 * and list_size
2095 				 */
2096 				if (target_posp != 0 && list_size != 0) {
2097 					cookie->index =
2098 					    target_posp + LISTPAGESIZE;
2099 					if (cookie->index > list_size)
2100 						finished = 1;
2101 				} else {
2102 					if (cookie->entryCount < LISTPAGESIZE)
2103 						finished = 1;
2104 					else
2105 						cookie->index +=
2106 						    cookie->entryCount;
2107 				}
2108 			}
2109 			ldap_controls_free(retCtrls);
2110 			retCtrls = NULL;
2111 		}
2112 		else
2113 			finished = 1;
2114 	} else if (cookie->listType == SIMPLEPAGECTRLFLAG) {
2115 		rc = ldap_parse_result(cookie->conn->ld, cookie->resultMsg,
2116 		    &errCode, NULL, NULL, &referrals, &retCtrls, 0);
2117 		if (rc != LDAP_SUCCESS) {
2118 			(void) ldap_get_option(cookie->conn->ld,
2119 			    LDAP_OPT_ERROR_NUMBER,
2120 			    &cookie->err_rc);
2121 			(void) sprintf(errstr,
2122 			    gettext("LDAP ERROR (%d): %s.\n"),
2123 			    cookie->err_rc,
2124 			    gettext(ldap_err2string(cookie->err_rc)));
2125 			err = strdup(errstr);
2126 			MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL, err,
2127 			    NULL);
2128 			cookie->err_rc = NS_LDAP_INTERNAL;
2129 			cookie->errorp = *errorp;
2130 			return (LDAP_ERROR);
2131 		}
2132 		if (errCode == LDAP_REFERRAL) {
2133 			for (i = 0; referrals[i] != NULL;
2134 			    i++) {
2135 				/* add to referral list */
2136 				rc = __s_api_addRefInfo(
2137 				    &cookie->reflist,
2138 				    referrals[i],
2139 				    cookie->basedn,
2140 				    &cookie->scope,
2141 				    cookie->filter,
2142 				    cookie->conn->ld);
2143 				if (rc != NS_LDAP_SUCCESS) {
2144 					ldap_value_free(
2145 					    referrals);
2146 					if (retCtrls)
2147 						ldap_controls_free(
2148 						    retCtrls);
2149 					return (ERROR);
2150 				}
2151 			}
2152 			ldap_value_free(referrals);
2153 			if (retCtrls)
2154 				ldap_controls_free(retCtrls);
2155 			return (END_RESULT);
2156 		}
2157 		if (retCtrls) {
2158 			if (cookie->ctrlCookie)
2159 				ber_bvfree(cookie->ctrlCookie);
2160 			cookie->ctrlCookie = NULL;
2161 			rc = ldap_parse_page_control(
2162 			    cookie->conn->ld, retCtrls,
2163 			    &count, &cookie->ctrlCookie);
2164 			if (rc == LDAP_SUCCESS) {
2165 				if ((cookie->ctrlCookie == NULL) ||
2166 				    (cookie->ctrlCookie->bv_val == NULL) ||
2167 				    (cookie->ctrlCookie->bv_len == 0))
2168 					finished = 1;
2169 			}
2170 			ldap_controls_free(retCtrls);
2171 			retCtrls = NULL;
2172 		}
2173 		else
2174 			finished = 1;
2175 	}
2176 	if (!finished && cookie->listType == VLVCTRLFLAG)
2177 		return (NEXT_VLV);
2178 	if (!finished && cookie->listType == SIMPLEPAGECTRLFLAG)
2179 		return (NEXT_PAGE);
2180 	if (finished)
2181 		return (END_RESULT);
2182 	return (ERROR);
2183 }
2184 
2185 /*
2186  * clear_results(ns_ldap_cookie_t):
2187  *
2188  * Attempt to obtain remnants of ldap responses and free them.  If remnants are
2189  * not obtained within a certain time period tell the server we wish to abandon
2190  * the request.
2191  *
2192  * Note that we do not initially tell the server to abandon the request as that
2193  * can be an expensive operation for the server, while it is cheap for us to
2194  * just flush the input.
2195  *
2196  * If something was to remain in libldap queue as a result of some error then
2197  * it would be freed later during drop connection call or when no other
2198  * requests share the connection.
2199  */
2200 static void
2201 clear_results(ns_ldap_cookie_t *cookie)
2202 {
2203 	int rc;
2204 	if (cookie->conn != NULL && cookie->conn->ld != NULL &&
2205 	    (cookie->connectionId != -1 ||
2206 	    (cookie->conn_user != NULL &&
2207 	    cookie->conn_user->conn_mt != NULL)) &&
2208 	    cookie->msgId != 0) {
2209 		/*
2210 		 * We need to cleanup the rest of response (if there is such)
2211 		 * and LDAP abandon is too heavy for LDAP servers, so we will
2212 		 * wait for the rest of response till timeout and "process" it.
2213 		 */
2214 		rc = ldap_result(cookie->conn->ld, cookie->msgId, LDAP_MSG_ALL,
2215 		    (struct timeval *)&cookie->search_timeout,
2216 		    &cookie->resultMsg);
2217 		if (rc != -1 && rc != 0 && cookie->resultMsg != NULL) {
2218 			(void) ldap_msgfree(cookie->resultMsg);
2219 			cookie->resultMsg = NULL;
2220 		}
2221 
2222 		/*
2223 		 * If there was timeout then we will send  ABANDON request to
2224 		 * LDAP server to decrease load.
2225 		 */
2226 		if (rc == 0)
2227 			(void) ldap_abandon_ext(cookie->conn->ld, cookie->msgId,
2228 			    NULL, NULL);
2229 		/* Disassociate cookie with msgId */
2230 		cookie->msgId = 0;
2231 	}
2232 }
2233 
2234 /*
2235  * This state machine performs one or more LDAP searches to a given
2236  * directory server using service search descriptors and schema
2237  * mapping as appropriate.  The approximate pseudocode for
2238  * this routine is the following:
2239  *    Given the current configuration [set/reset connection etc.]
2240  *    and the current service search descriptor list
2241  *        or default search filter parameters
2242  *    foreach (service search filter) {
2243  *        initialize the filter [via filter_init if appropriate]
2244  *		  get a valid session/connection (preferably the current one)
2245  *					Recover if the connection is lost
2246  *        perform the search
2247  *        foreach (result entry) {
2248  *            process result [via callback if appropriate]
2249  *                save result for caller if accepted.
2250  *                exit and return all collected if allResults found;
2251  *        }
2252  *    }
2253  *    return collected results and exit
2254  */
2255 
2256 static
2257 ns_state_t
2258 search_state_machine(ns_ldap_cookie_t *cookie, ns_state_t state, int cycle)
2259 {
2260 	char		errstr[MAXERROR];
2261 	char		*err;
2262 	int		rc, ret;
2263 	int		rc_save;
2264 	ns_ldap_entry_t	*nextEntry;
2265 	ns_ldap_error_t *error = NULL;
2266 	ns_ldap_error_t **errorp;
2267 	struct timeval	tv;
2268 
2269 	errorp = &error;
2270 	cookie->state = state;
2271 	errstr[0] = '\0';
2272 
2273 	for (;;) {
2274 		switch (cookie->state) {
2275 		case CLEAR_RESULTS:
2276 			clear_results(cookie);
2277 			cookie->new_state = EXIT;
2278 			break;
2279 		case GET_ACCT_MGMT_INFO:
2280 			/*
2281 			 * Set the flag to get ldap account management controls.
2282 			 */
2283 			cookie->nopasswd_acct_mgmt = 1;
2284 			cookie->new_state = INIT;
2285 			break;
2286 		case EXIT:
2287 			/* state engine/connection cleaned up in delete */
2288 			if (cookie->attribute) {
2289 				__s_api_free2dArray(cookie->attribute);
2290 				cookie->attribute = NULL;
2291 			}
2292 			if (cookie->reflist) {
2293 				__s_api_deleteRefInfo(cookie->reflist);
2294 				cookie->reflist = NULL;
2295 			}
2296 			return (EXIT);
2297 		case INIT:
2298 			cookie->sdpos = NULL;
2299 			cookie->new_state = NEXT_SEARCH_DESCRIPTOR;
2300 			if (cookie->attribute) {
2301 				__s_api_free2dArray(cookie->attribute);
2302 				cookie->attribute = NULL;
2303 			}
2304 			if ((cookie->i_flags & NS_LDAP_NOMAP) == 0 &&
2305 			    cookie->i_attr) {
2306 				cookie->attribute =
2307 				    __ns_ldap_mapAttributeList(
2308 				    cookie->service,
2309 				    cookie->i_attr);
2310 			}
2311 			break;
2312 		case REINIT:
2313 			/* Check if we've reached MAX retries. */
2314 			cookie->retries++;
2315 			if (cookie->retries > NS_LIST_TRY_MAX - 1) {
2316 				cookie->new_state = LDAP_ERROR;
2317 				break;
2318 			}
2319 
2320 			/*
2321 			 * Even if we still have retries left, check
2322 			 * if retry is possible.
2323 			 */
2324 			if (cookie->conn_user != NULL) {
2325 				int		retry;
2326 				ns_conn_mgmt_t	*cmg;
2327 				cmg = cookie->conn_user->conn_mgmt;
2328 				retry = cookie->conn_user->retry;
2329 				if (cmg != NULL && cmg->cfg_reloaded == 1)
2330 					retry = 1;
2331 				if (retry == 0) {
2332 					cookie->new_state = LDAP_ERROR;
2333 					break;
2334 				}
2335 			}
2336 			/*
2337 			 * Free results if any, reset to the first
2338 			 * search descriptor and start a new session.
2339 			 */
2340 			if (cookie->resultMsg != NULL) {
2341 				(void) ldap_msgfree(cookie->resultMsg);
2342 				cookie->resultMsg = NULL;
2343 			}
2344 			(void) __ns_ldap_freeError(&cookie->errorp);
2345 			(void) __ns_ldap_freeResult(&cookie->result);
2346 			cookie->sdpos = cookie->sdlist;
2347 			cookie->err_from_result = 0;
2348 			cookie->err_rc = 0;
2349 			cookie->new_state = NEXT_SESSION;
2350 			break;
2351 		case NEXT_SEARCH_DESCRIPTOR:
2352 			/* get next search descriptor */
2353 			if (cookie->sdpos == NULL) {
2354 				cookie->sdpos = cookie->sdlist;
2355 				cookie->new_state = GET_SESSION;
2356 			} else {
2357 				cookie->sdpos++;
2358 				cookie->new_state = NEXT_SEARCH;
2359 			}
2360 			if (*cookie->sdpos == NULL)
2361 				cookie->new_state = EXIT;
2362 			break;
2363 		case GET_SESSION:
2364 			if (get_current_session(cookie) < 0)
2365 				cookie->new_state = NEXT_SESSION;
2366 			else
2367 				cookie->new_state = NEXT_SEARCH;
2368 			break;
2369 		case NEXT_SESSION:
2370 			if (get_next_session(cookie) < 0)
2371 				cookie->new_state = RESTART_SESSION;
2372 			else
2373 				cookie->new_state = NEXT_SEARCH;
2374 			break;
2375 		case RESTART_SESSION:
2376 			if (cookie->i_flags & NS_LDAP_HARD) {
2377 				cookie->new_state = NEXT_SESSION;
2378 				break;
2379 			}
2380 			(void) sprintf(errstr,
2381 			    gettext("Session error no available conn.\n"),
2382 			    state);
2383 			err = strdup(errstr);
2384 			MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL, err,
2385 			    NULL);
2386 			cookie->err_rc = NS_LDAP_INTERNAL;
2387 			cookie->errorp = *errorp;
2388 			cookie->new_state = EXIT;
2389 			break;
2390 		case NEXT_SEARCH:
2391 			/* setup referrals search if necessary */
2392 			if (cookie->refpos) {
2393 				if (setup_referral_search(cookie) < 0) {
2394 					cookie->new_state = EXIT;
2395 					break;
2396 				}
2397 			} else if (setup_next_search(cookie) < 0) {
2398 				cookie->new_state = EXIT;
2399 				break;
2400 			}
2401 			/* only do VLV/PAGE on scopes onelevel/subtree */
2402 			if (paging_supported(cookie)) {
2403 				if (cookie->use_paging &&
2404 				    (cookie->scope != LDAP_SCOPE_BASE)) {
2405 					cookie->index = 1;
2406 					if (cookie->listType == VLVCTRLFLAG)
2407 						cookie->new_state = NEXT_VLV;
2408 					else
2409 						cookie->new_state = NEXT_PAGE;
2410 					break;
2411 				}
2412 			}
2413 			cookie->new_state = ONE_SEARCH;
2414 			break;
2415 		case NEXT_VLV:
2416 			rc = setup_vlv_params(cookie);
2417 			if (rc != LDAP_SUCCESS) {
2418 				cookie->err_rc = rc;
2419 				cookie->new_state = LDAP_ERROR;
2420 				break;
2421 			}
2422 			cookie->next_state = MULTI_RESULT;
2423 			cookie->new_state = DO_SEARCH;
2424 			break;
2425 		case NEXT_PAGE:
2426 			rc = setup_simplepg_params(cookie);
2427 			if (rc != LDAP_SUCCESS) {
2428 				cookie->err_rc = rc;
2429 				cookie->new_state = LDAP_ERROR;
2430 				break;
2431 			}
2432 			cookie->next_state = MULTI_RESULT;
2433 			cookie->new_state = DO_SEARCH;
2434 			break;
2435 		case ONE_SEARCH:
2436 			cookie->next_state = NEXT_RESULT;
2437 			cookie->new_state = DO_SEARCH;
2438 			break;
2439 		case DO_SEARCH:
2440 			cookie->entryCount = 0;
2441 			rc = ldap_search_ext(cookie->conn->ld,
2442 			    cookie->basedn,
2443 			    cookie->scope,
2444 			    cookie->filter,
2445 			    cookie->attribute,
2446 			    0,
2447 			    cookie->p_serverctrls,
2448 			    NULL,
2449 			    &cookie->search_timeout, 0,
2450 			    &cookie->msgId);
2451 			if (rc != LDAP_SUCCESS) {
2452 				if (rc == LDAP_BUSY ||
2453 				    rc == LDAP_UNAVAILABLE ||
2454 				    rc == LDAP_UNWILLING_TO_PERFORM ||
2455 				    rc == LDAP_CONNECT_ERROR ||
2456 				    rc == LDAP_SERVER_DOWN) {
2457 
2458 					if (cookie->reinit_on_retriable_err) {
2459 						cookie->err_rc = rc;
2460 						cookie->new_state = REINIT;
2461 					} else
2462 						cookie->new_state =
2463 						    NEXT_SESSION;
2464 
2465 					/*
2466 					 * If not able to reach the
2467 					 * server, inform the ldap
2468 					 * cache manager that the
2469 					 * server should be removed
2470 					 * from it's server list.
2471 					 * Thus, the manager will not
2472 					 * return this server on the next
2473 					 * get-server request and will
2474 					 * also reduce the server list
2475 					 * refresh TTL, so that it will
2476 					 * find out sooner when the server
2477 					 * is up again.
2478 					 */
2479 					if ((rc == LDAP_CONNECT_ERROR ||
2480 					    rc == LDAP_SERVER_DOWN) &&
2481 					    (cookie->conn_user == NULL ||
2482 					    cookie->conn_user->conn_mt ==
2483 					    NULL)) {
2484 						ret = __s_api_removeServer(
2485 						    cookie->conn->serverAddr);
2486 						if (ret == NS_CACHE_NOSERVER &&
2487 						    cookie->conn_auth_type
2488 						    == NS_LDAP_AUTH_NONE) {
2489 							/*
2490 							 * Couldn't remove
2491 							 * server from server
2492 							 * list.
2493 							 * Exit to avoid
2494 							 * potential infinite
2495 							 * loop.
2496 							 */
2497 							cookie->err_rc = rc;
2498 							cookie->new_state =
2499 							    LDAP_ERROR;
2500 						}
2501 						if (cookie->connectionId > -1) {
2502 							/*
2503 							 * NS_LDAP_NEW_CONN
2504 							 * indicates that the
2505 							 * connection should
2506 							 * be deleted, not
2507 							 * kept alive
2508 							 */
2509 							DropConnection(
2510 							    cookie->
2511 							    connectionId,
2512 							    NS_LDAP_NEW_CONN);
2513 							cookie->connectionId =
2514 							    -1;
2515 						}
2516 					} else if ((rc == LDAP_CONNECT_ERROR ||
2517 					    rc == LDAP_SERVER_DOWN) &&
2518 					    cookie->conn_user != NULL) {
2519 						if (cookie->
2520 						    reinit_on_retriable_err) {
2521 							/*
2522 							 * MT connection not
2523 							 * usable, close it
2524 							 * before REINIT.
2525 							 * rc has already
2526 							 * been saved in
2527 							 * cookie->err_rc above.
2528 							 */
2529 							__s_api_conn_mt_close(
2530 							    cookie->conn_user,
2531 							    rc,
2532 							    &cookie->errorp);
2533 						} else {
2534 							/*
2535 							 * MT connection not
2536 							 * usable, close it in
2537 							 * the LDAP_ERROR state.
2538 							 * A retry will be done
2539 							 * next if allowed.
2540 							 */
2541 							cookie->err_rc = rc;
2542 							cookie->new_state =
2543 							    LDAP_ERROR;
2544 						}
2545 					}
2546 					break;
2547 				}
2548 				cookie->err_rc = rc;
2549 				cookie->new_state = LDAP_ERROR;
2550 				break;
2551 			}
2552 			cookie->new_state = cookie->next_state;
2553 			break;
2554 		case NEXT_RESULT:
2555 			/*
2556 			 * Caller (e.g. __ns_ldap_list_batch_add)
2557 			 * does not want to block on ldap_result().
2558 			 * Therefore we execute ldap_result() with
2559 			 * a zeroed timeval.
2560 			 */
2561 			if (cookie->no_wait == B_TRUE)
2562 				(void) memset(&tv, 0, sizeof (tv));
2563 			else
2564 				tv = cookie->search_timeout;
2565 			rc = ldap_result(cookie->conn->ld, cookie->msgId,
2566 			    LDAP_MSG_ONE,
2567 			    &tv,
2568 			    &cookie->resultMsg);
2569 			if (rc == LDAP_RES_SEARCH_RESULT) {
2570 				cookie->new_state = END_RESULT;
2571 				/* check and process referrals info */
2572 				if (cookie->followRef)
2573 					proc_result_referrals(
2574 					    cookie);
2575 				(void) ldap_msgfree(cookie->resultMsg);
2576 				cookie->resultMsg = NULL;
2577 				break;
2578 			}
2579 			/* handle referrals if necessary */
2580 			if (rc == LDAP_RES_SEARCH_REFERENCE) {
2581 				if (cookie->followRef)
2582 					proc_search_references(cookie);
2583 				(void) ldap_msgfree(cookie->resultMsg);
2584 				cookie->resultMsg = NULL;
2585 				break;
2586 			}
2587 			if (rc != LDAP_RES_SEARCH_ENTRY) {
2588 				switch (rc) {
2589 				case 0:
2590 					if (cookie->no_wait == B_TRUE) {
2591 						(void) ldap_msgfree(
2592 						    cookie->resultMsg);
2593 						cookie->resultMsg = NULL;
2594 						return (cookie->new_state);
2595 					}
2596 					rc = LDAP_TIMEOUT;
2597 					break;
2598 				case -1:
2599 					rc = ldap_get_lderrno(cookie->conn->ld,
2600 					    NULL, NULL);
2601 					break;
2602 				default:
2603 					rc = ldap_result2error(cookie->conn->ld,
2604 					    cookie->resultMsg, 1);
2605 					break;
2606 				}
2607 				if ((rc == LDAP_TIMEOUT ||
2608 				    rc == LDAP_SERVER_DOWN) &&
2609 				    (cookie->conn_user == NULL ||
2610 				    cookie->conn_user->conn_mt == NULL)) {
2611 					if (rc == LDAP_TIMEOUT)
2612 						(void) __s_api_removeServer(
2613 						    cookie->conn->serverAddr);
2614 					if (cookie->connectionId > -1) {
2615 						DropConnection(
2616 						    cookie->connectionId,
2617 						    NS_LDAP_NEW_CONN);
2618 						cookie->connectionId = -1;
2619 					}
2620 					cookie->err_from_result = 1;
2621 				}
2622 				(void) ldap_msgfree(cookie->resultMsg);
2623 				cookie->resultMsg = NULL;
2624 				if (rc == LDAP_BUSY ||
2625 				    rc == LDAP_UNAVAILABLE ||
2626 				    rc == LDAP_UNWILLING_TO_PERFORM) {
2627 					if (cookie->reinit_on_retriable_err) {
2628 						cookie->err_rc = rc;
2629 						cookie->err_from_result = 1;
2630 						cookie->new_state = REINIT;
2631 					} else
2632 						cookie->new_state =
2633 						    NEXT_SESSION;
2634 					break;
2635 				}
2636 				if ((rc == LDAP_CONNECT_ERROR ||
2637 				    rc == LDAP_SERVER_DOWN) &&
2638 				    cookie->reinit_on_retriable_err) {
2639 					ns_ldap_error_t *errorp = NULL;
2640 					cookie->err_rc = rc;
2641 					cookie->err_from_result = 1;
2642 					cookie->new_state = REINIT;
2643 					if (cookie->conn_user != NULL)
2644 						__s_api_conn_mt_close(
2645 						    cookie->conn_user,
2646 						    rc, &errorp);
2647 					if (errorp != NULL) {
2648 						(void) __ns_ldap_freeError(
2649 						    &cookie->errorp);
2650 						cookie->errorp = errorp;
2651 					}
2652 					break;
2653 				}
2654 				cookie->err_rc = rc;
2655 				cookie->new_state = LDAP_ERROR;
2656 				break;
2657 			}
2658 			/* else LDAP_RES_SEARCH_ENTRY */
2659 			/* get account management response control */
2660 			if (cookie->nopasswd_acct_mgmt == 1) {
2661 				rc = ldap_get_entry_controls(cookie->conn->ld,
2662 				    cookie->resultMsg,
2663 				    &(cookie->resultctrl));
2664 				if (rc != LDAP_SUCCESS) {
2665 					cookie->new_state = LDAP_ERROR;
2666 					cookie->err_rc = rc;
2667 					break;
2668 				}
2669 			}
2670 			rc = __s_api_getEntry(cookie);
2671 			(void) ldap_msgfree(cookie->resultMsg);
2672 			cookie->resultMsg = NULL;
2673 			if (rc != NS_LDAP_SUCCESS) {
2674 				cookie->new_state = LDAP_ERROR;
2675 				break;
2676 			}
2677 			cookie->new_state = PROCESS_RESULT;
2678 			cookie->next_state = NEXT_RESULT;
2679 			break;
2680 		case MULTI_RESULT:
2681 			if (cookie->no_wait == B_TRUE)
2682 				(void) memset(&tv, 0, sizeof (tv));
2683 			else
2684 				tv = cookie->search_timeout;
2685 			rc = ldap_result(cookie->conn->ld, cookie->msgId,
2686 			    LDAP_MSG_ONE,
2687 			    &tv,
2688 			    &cookie->resultMsg);
2689 			if (rc == LDAP_RES_SEARCH_RESULT) {
2690 				rc = ldap_result2error(cookie->conn->ld,
2691 				    cookie->resultMsg, 0);
2692 				if (rc == LDAP_ADMINLIMIT_EXCEEDED &&
2693 				    cookie->listType == VLVCTRLFLAG &&
2694 				    cookie->sortTypeTry == SSS_SINGLE_ATTR) {
2695 					/* Try old "cn uid" server side sort */
2696 					cookie->sortTypeTry = SSS_CN_UID_ATTRS;
2697 					cookie->new_state = NEXT_VLV;
2698 					(void) ldap_msgfree(cookie->resultMsg);
2699 					cookie->resultMsg = NULL;
2700 					break;
2701 				}
2702 				if (rc != LDAP_SUCCESS) {
2703 					cookie->err_rc = rc;
2704 					cookie->new_state = LDAP_ERROR;
2705 					(void) ldap_msgfree(cookie->resultMsg);
2706 					cookie->resultMsg = NULL;
2707 					break;
2708 				}
2709 				cookie->new_state = multi_result(cookie);
2710 				(void) ldap_msgfree(cookie->resultMsg);
2711 				cookie->resultMsg = NULL;
2712 				break;
2713 			}
2714 			/* handle referrals if necessary */
2715 			if (rc == LDAP_RES_SEARCH_REFERENCE &&
2716 			    cookie->followRef) {
2717 				proc_search_references(cookie);
2718 				(void) ldap_msgfree(cookie->resultMsg);
2719 				cookie->resultMsg = NULL;
2720 				break;
2721 			}
2722 			if (rc != LDAP_RES_SEARCH_ENTRY) {
2723 				switch (rc) {
2724 				case 0:
2725 					if (cookie->no_wait == B_TRUE) {
2726 						(void) ldap_msgfree(
2727 						    cookie->resultMsg);
2728 						cookie->resultMsg = NULL;
2729 						return (cookie->new_state);
2730 					}
2731 					rc = LDAP_TIMEOUT;
2732 					break;
2733 				case -1:
2734 					rc = ldap_get_lderrno(cookie->conn->ld,
2735 					    NULL, NULL);
2736 					break;
2737 				default:
2738 					rc = ldap_result2error(cookie->conn->ld,
2739 					    cookie->resultMsg, 1);
2740 					break;
2741 				}
2742 				if ((rc == LDAP_TIMEOUT ||
2743 				    rc == LDAP_SERVER_DOWN) &&
2744 				    (cookie->conn_user == NULL ||
2745 				    cookie->conn_user->conn_mt == NULL)) {
2746 					if (rc == LDAP_TIMEOUT)
2747 						(void) __s_api_removeServer(
2748 						    cookie->conn->serverAddr);
2749 					if (cookie->connectionId > -1) {
2750 						DropConnection(
2751 						    cookie->connectionId,
2752 						    NS_LDAP_NEW_CONN);
2753 						cookie->connectionId = -1;
2754 					}
2755 					cookie->err_from_result = 1;
2756 				}
2757 				(void) ldap_msgfree(cookie->resultMsg);
2758 				cookie->resultMsg = NULL;
2759 				if (rc == LDAP_BUSY ||
2760 				    rc == LDAP_UNAVAILABLE ||
2761 				    rc == LDAP_UNWILLING_TO_PERFORM) {
2762 					if (cookie->reinit_on_retriable_err) {
2763 						cookie->err_rc = rc;
2764 						cookie->err_from_result = 1;
2765 						cookie->new_state = REINIT;
2766 					} else
2767 						cookie->new_state =
2768 						    NEXT_SESSION;
2769 					break;
2770 				}
2771 
2772 				if ((rc == LDAP_CONNECT_ERROR ||
2773 				    rc == LDAP_SERVER_DOWN) &&
2774 				    cookie->reinit_on_retriable_err) {
2775 					ns_ldap_error_t *errorp = NULL;
2776 					cookie->err_rc = rc;
2777 					cookie->err_from_result = 1;
2778 					cookie->new_state = REINIT;
2779 					if (cookie->conn_user != NULL)
2780 						__s_api_conn_mt_close(
2781 						    cookie->conn_user,
2782 						    rc, &errorp);
2783 					if (errorp != NULL) {
2784 						(void) __ns_ldap_freeError(
2785 						    &cookie->errorp);
2786 						cookie->errorp = errorp;
2787 					}
2788 					break;
2789 				}
2790 				cookie->err_rc = rc;
2791 				cookie->new_state = LDAP_ERROR;
2792 				break;
2793 			}
2794 			/* else LDAP_RES_SEARCH_ENTRY */
2795 			cookie->entryCount++;
2796 			rc = __s_api_getEntry(cookie);
2797 			(void) ldap_msgfree(cookie->resultMsg);
2798 			cookie->resultMsg = NULL;
2799 			if (rc != NS_LDAP_SUCCESS) {
2800 				cookie->new_state = LDAP_ERROR;
2801 				break;
2802 			}
2803 			/*
2804 			 * If VLV search was successfull save the server
2805 			 * side sort type tried.
2806 			 */
2807 			if (cookie->listType == VLVCTRLFLAG)
2808 				update_srvsidesort_type(cookie->service,
2809 				    cookie->sortTypeTry);
2810 
2811 			cookie->new_state = PROCESS_RESULT;
2812 			cookie->next_state = MULTI_RESULT;
2813 			break;
2814 		case PROCESS_RESULT:
2815 			/* NOTE THIS STATE MAY BE PROCESSED BY CALLER */
2816 			if (cookie->use_usercb && cookie->callback) {
2817 				rc = 0;
2818 				for (nextEntry = cookie->result->entry;
2819 				    nextEntry != NULL;
2820 				    nextEntry = nextEntry->next) {
2821 					rc = (*cookie->callback)(nextEntry,
2822 					    cookie->userdata);
2823 
2824 					if (rc == NS_LDAP_CB_DONE) {
2825 					/* cb doesn't want any more data */
2826 						rc = NS_LDAP_PARTIAL;
2827 						cookie->err_rc = rc;
2828 						break;
2829 					} else if (rc != NS_LDAP_CB_NEXT) {
2830 					/* invalid return code */
2831 						rc = NS_LDAP_OP_FAILED;
2832 						cookie->err_rc = rc;
2833 						break;
2834 					}
2835 				}
2836 				(void) __ns_ldap_freeResult(&cookie->result);
2837 				cookie->result = NULL;
2838 			}
2839 			if (rc != 0) {
2840 				cookie->new_state = EXIT;
2841 				break;
2842 			}
2843 			/* NOTE PREVIOUS STATE SPECIFIES NEXT STATE */
2844 			cookie->new_state = cookie->next_state;
2845 			break;
2846 		case END_PROCESS_RESULT:
2847 			cookie->new_state = cookie->next_state;
2848 			break;
2849 		case END_RESULT:
2850 			/*
2851 			 * XXX DO WE NEED THIS CASE?
2852 			 * if (search is complete) {
2853 			 * 	cookie->new_state = EXIT;
2854 			 * } else
2855 			 */
2856 				/*
2857 				 * entering referral mode if necessary
2858 				 */
2859 				if (cookie->followRef && cookie->reflist)
2860 					cookie->new_state =
2861 					    NEXT_REFERRAL;
2862 				else
2863 					cookie->new_state =
2864 					    NEXT_SEARCH_DESCRIPTOR;
2865 			break;
2866 		case NEXT_REFERRAL:
2867 			/* get next referral info */
2868 			if (cookie->refpos == NULL)
2869 				cookie->refpos =
2870 				    cookie->reflist;
2871 			else
2872 				cookie->refpos =
2873 				    cookie->refpos->next;
2874 			/* check see if done with all referrals */
2875 			if (cookie->refpos != NULL)
2876 				cookie->new_state =
2877 				    GET_REFERRAL_SESSION;
2878 			else {
2879 				__s_api_deleteRefInfo(cookie->reflist);
2880 				cookie->reflist = NULL;
2881 				cookie->new_state =
2882 				    NEXT_SEARCH_DESCRIPTOR;
2883 				if (cookie->conn_user != NULL)
2884 					cookie->conn_user->referral = B_FALSE;
2885 			}
2886 			break;
2887 		case GET_REFERRAL_SESSION:
2888 			if (get_referral_session(cookie) < 0)
2889 				cookie->new_state = EXIT;
2890 			else {
2891 				cookie->new_state = NEXT_SEARCH;
2892 			}
2893 			break;
2894 		case LDAP_ERROR:
2895 			rc_save = cookie->err_rc;
2896 			if (cookie->err_from_result) {
2897 				if (cookie->err_rc == LDAP_SERVER_DOWN) {
2898 					(void) sprintf(errstr,
2899 					    gettext("LDAP ERROR (%d): "
2900 					    "Error occurred during"
2901 					    " receiving results. "
2902 					    "Connection to server lost."),
2903 					    cookie->err_rc);
2904 				} else if (cookie->err_rc == LDAP_TIMEOUT) {
2905 					(void) sprintf(errstr,
2906 					    gettext("LDAP ERROR (%d): "
2907 					    "Error occurred during"
2908 					    " receiving results. %s"
2909 					    "."), cookie->err_rc,
2910 					    ldap_err2string(
2911 					    cookie->err_rc));
2912 				}
2913 			} else
2914 				(void) sprintf(errstr,
2915 				    gettext("LDAP ERROR (%d): %s."),
2916 				    cookie->err_rc,
2917 				    ldap_err2string(cookie->err_rc));
2918 			err = strdup(errstr);
2919 			if (cookie->err_from_result) {
2920 				if (cookie->err_rc == LDAP_SERVER_DOWN) {
2921 					MKERROR(LOG_INFO, *errorp,
2922 					    cookie->err_rc, err, NULL);
2923 				} else {
2924 					MKERROR(LOG_WARNING, *errorp,
2925 					    cookie->err_rc, err, NULL);
2926 				}
2927 			} else {
2928 				MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL,
2929 				    err, NULL);
2930 			}
2931 			cookie->err_rc = NS_LDAP_INTERNAL;
2932 			cookie->errorp = *errorp;
2933 			if (cookie->conn_user != NULL)  {
2934 				if (rc_save == LDAP_SERVER_DOWN ||
2935 				    rc_save == LDAP_CONNECT_ERROR) {
2936 					/*
2937 					 * MT connection is not usable,
2938 					 * close it.
2939 					 */
2940 					__s_api_conn_mt_close(cookie->conn_user,
2941 					    rc_save, &cookie->errorp);
2942 					return (ERROR);
2943 				}
2944 			}
2945 			return (ERROR);
2946 		default:
2947 		case ERROR:
2948 			(void) sprintf(errstr,
2949 			    gettext("Internal State machine exit (%d).\n"),
2950 			    cookie->state);
2951 			err = strdup(errstr);
2952 			MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL, err,
2953 			    NULL);
2954 			cookie->err_rc = NS_LDAP_INTERNAL;
2955 			cookie->errorp = *errorp;
2956 			return (ERROR);
2957 		}
2958 
2959 		if (cookie->conn_user != NULL &&
2960 		    cookie->conn_user->bad_mt_conn ==  B_TRUE) {
2961 			__s_api_conn_mt_close(cookie->conn_user, 0, NULL);
2962 			cookie->err_rc = cookie->conn_user->ns_rc;
2963 			cookie->errorp = cookie->conn_user->ns_error;
2964 			cookie->conn_user->ns_error = NULL;
2965 			return (ERROR);
2966 		}
2967 
2968 		if (cycle == ONE_STEP) {
2969 			return (cookie->new_state);
2970 		}
2971 		cookie->state = cookie->new_state;
2972 	}
2973 	/*NOTREACHED*/
2974 #if 0
2975 	(void) sprintf(errstr,
2976 	    gettext("Unexpected State machine error.\n"));
2977 	err = strdup(errstr);
2978 	MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL, err, NULL);
2979 	cookie->err_rc = NS_LDAP_INTERNAL;
2980 	cookie->errorp = *errorp;
2981 	return (ERROR);
2982 #endif
2983 }
2984 
2985 /*
2986  * For a lookup of shadow data, if shadow update is enabled,
2987  * check the calling process' privilege to ensure it's
2988  * allowed to perform such operation.
2989  */
2990 static int
2991 check_shadow(ns_ldap_cookie_t *cookie, const char *service)
2992 {
2993 	char errstr[MAXERROR];
2994 	char *err;
2995 	boolean_t priv;
2996 	/* caller */
2997 	priv_set_t *ps;
2998 	/* zone */
2999 	priv_set_t *zs;
3000 
3001 	/*
3002 	 * If service is "shadow", we may need
3003 	 * to use privilege credentials.
3004 	 */
3005 	if ((strcmp(service, "shadow") == 0) &&
3006 	    __ns_ldap_is_shadow_update_enabled()) {
3007 		/*
3008 		 * Since we release admin credentials after
3009 		 * connection is closed and we do not cache
3010 		 * them, we allow any root or all zone
3011 		 * privilege process to read shadow data.
3012 		 */
3013 		priv = (geteuid() == 0);
3014 		if (!priv) {
3015 			/* caller */
3016 			ps = priv_allocset();
3017 
3018 			(void) getppriv(PRIV_EFFECTIVE, ps);
3019 			zs = priv_str_to_set("zone", ",", NULL);
3020 			priv = priv_isequalset(ps, zs);
3021 			priv_freeset(ps);
3022 			priv_freeset(zs);
3023 		}
3024 		if (!priv) {
3025 			(void) sprintf(errstr,
3026 			    gettext("Permission denied"));
3027 			err = strdup(errstr);
3028 			if (err == NULL)
3029 				return (NS_LDAP_MEMORY);
3030 			MKERROR(LOG_INFO, cookie->errorp, NS_LDAP_INTERNAL, err,
3031 			    NULL);
3032 			return (NS_LDAP_INTERNAL);
3033 		}
3034 		cookie->i_flags |= NS_LDAP_READ_SHADOW;
3035 		/*
3036 		 * We do not want to reuse connection (hence
3037 		 * keep it open) with admin credentials.
3038 		 * If NS_LDAP_KEEP_CONN is set, reject the
3039 		 * request.
3040 		 */
3041 		if (cookie->i_flags & NS_LDAP_KEEP_CONN)
3042 			return (NS_LDAP_INVALID_PARAM);
3043 		cookie->i_flags |= NS_LDAP_NEW_CONN;
3044 	}
3045 
3046 	return (NS_LDAP_SUCCESS);
3047 }
3048 
3049 /*
3050  * internal function for __ns_ldap_list
3051  */
3052 static int
3053 ldap_list(
3054 	ns_ldap_list_batch_t *batch,
3055 	const char *service,
3056 	const char *filter,
3057 	const char *sortattr,
3058 	int (*init_filter_cb)(const ns_ldap_search_desc_t *desc,
3059 	char **realfilter, const void *userdata),
3060 	const char * const *attribute,
3061 	const ns_cred_t *auth,
3062 	const int flags,
3063 	ns_ldap_result_t **rResult, /* return result entries */
3064 	ns_ldap_error_t **errorp,
3065 	int *rcp,
3066 	int (*callback)(const ns_ldap_entry_t *entry, const void *userdata),
3067 	const void *userdata, ns_conn_user_t *conn_user)
3068 {
3069 	ns_ldap_cookie_t	*cookie;
3070 	ns_ldap_search_desc_t	**sdlist = NULL;
3071 	ns_ldap_search_desc_t	*dptr;
3072 	ns_ldap_error_t		*error = NULL;
3073 	char			**dns = NULL;
3074 	int			scope;
3075 	int			rc;
3076 	int			from_result;
3077 
3078 	*errorp = NULL;
3079 	*rResult = NULL;
3080 	*rcp = NS_LDAP_SUCCESS;
3081 
3082 	/*
3083 	 * Sanity check - NS_LDAP_READ_SHADOW is for our
3084 	 * own internal use.
3085 	 */
3086 	if (flags & NS_LDAP_READ_SHADOW)
3087 		return (NS_LDAP_INVALID_PARAM);
3088 
3089 	/* Initialize State machine cookie */
3090 	cookie = init_search_state_machine();
3091 	if (cookie == NULL) {
3092 		*rcp = NS_LDAP_MEMORY;
3093 		return (NS_LDAP_MEMORY);
3094 	}
3095 	cookie->conn_user = conn_user;
3096 
3097 	/* see if need to follow referrals */
3098 	rc = __s_api_toFollowReferrals(flags,
3099 	    &cookie->followRef, errorp);
3100 	if (rc != NS_LDAP_SUCCESS) {
3101 		delete_search_cookie(cookie);
3102 		*rcp = rc;
3103 		return (rc);
3104 	}
3105 
3106 	/* get the service descriptor - or create a default one */
3107 	rc = __s_api_get_SSD_from_SSDtoUse_service(service,
3108 	    &sdlist, &error);
3109 	if (rc != NS_LDAP_SUCCESS) {
3110 		delete_search_cookie(cookie);
3111 		*errorp = error;
3112 		*rcp = rc;
3113 		return (rc);
3114 	}
3115 
3116 	if (sdlist == NULL) {
3117 		/* Create default service Desc */
3118 		sdlist = (ns_ldap_search_desc_t **)calloc(2,
3119 		    sizeof (ns_ldap_search_desc_t *));
3120 		if (sdlist == NULL) {
3121 			delete_search_cookie(cookie);
3122 			cookie = NULL;
3123 			*rcp = NS_LDAP_MEMORY;
3124 			return (NS_LDAP_MEMORY);
3125 		}
3126 		dptr = (ns_ldap_search_desc_t *)
3127 		    calloc(1, sizeof (ns_ldap_search_desc_t));
3128 		if (dptr == NULL) {
3129 			free(sdlist);
3130 			delete_search_cookie(cookie);
3131 			cookie = NULL;
3132 			*rcp = NS_LDAP_MEMORY;
3133 			return (NS_LDAP_MEMORY);
3134 		}
3135 		sdlist[0] = dptr;
3136 
3137 		/* default base */
3138 		rc = __s_api_getDNs(&dns, service, &cookie->errorp);
3139 		if (rc != NS_LDAP_SUCCESS) {
3140 			if (dns) {
3141 				__s_api_free2dArray(dns);
3142 				dns = NULL;
3143 			}
3144 			*errorp = cookie->errorp;
3145 			cookie->errorp = NULL;
3146 			delete_search_cookie(cookie);
3147 			cookie = NULL;
3148 			*rcp = rc;
3149 			return (rc);
3150 		}
3151 		dptr->basedn = strdup(dns[0]);
3152 		__s_api_free2dArray(dns);
3153 		dns = NULL;
3154 
3155 		/* default scope */
3156 		scope = 0;
3157 		rc = __s_api_getSearchScope(&scope, &cookie->errorp);
3158 		dptr->scope = scope;
3159 	}
3160 
3161 	cookie->sdlist = sdlist;
3162 
3163 	/*
3164 	 * use VLV/PAGE control only if NS_LDAP_PAGE_CTRL is set
3165 	 */
3166 	if (flags & NS_LDAP_PAGE_CTRL)
3167 		cookie->use_paging = TRUE;
3168 	else
3169 		cookie->use_paging = FALSE;
3170 
3171 	/* Set up other arguments */
3172 	cookie->userdata = userdata;
3173 	if (init_filter_cb != NULL) {
3174 		cookie->init_filter_cb = init_filter_cb;
3175 		cookie->use_filtercb = 1;
3176 	}
3177 	if (callback != NULL) {
3178 		cookie->callback = callback;
3179 		cookie->use_usercb = 1;
3180 	}
3181 
3182 	/* check_shadow() may add extra value to cookie->i_flags */
3183 	cookie->i_flags = flags;
3184 	if (service) {
3185 		cookie->service = strdup(service);
3186 		if (cookie->service == NULL) {
3187 			delete_search_cookie(cookie);
3188 			cookie = NULL;
3189 			*rcp = NS_LDAP_MEMORY;
3190 			return (NS_LDAP_MEMORY);
3191 		}
3192 
3193 		/*
3194 		 * If given, use the credential given by the caller, and
3195 		 * skip the credential check required for shadow update.
3196 		 */
3197 		if (auth == NULL) {
3198 			rc = check_shadow(cookie, service);
3199 			if (rc != NS_LDAP_SUCCESS) {
3200 				*errorp = cookie->errorp;
3201 				cookie->errorp = NULL;
3202 				delete_search_cookie(cookie);
3203 				cookie = NULL;
3204 				*rcp = rc;
3205 				return (rc);
3206 			}
3207 		}
3208 	}
3209 
3210 	cookie->i_filter = strdup(filter);
3211 	cookie->i_attr = attribute;
3212 	cookie->i_auth = auth;
3213 	cookie->i_sortattr = sortattr;
3214 
3215 	if (batch != NULL) {
3216 		cookie->batch = batch;
3217 		cookie->reinit_on_retriable_err = B_TRUE;
3218 		cookie->no_wait = B_TRUE;
3219 		(void) search_state_machine(cookie, INIT, 0);
3220 		cookie->no_wait = B_FALSE;
3221 		rc = cookie->err_rc;
3222 
3223 		if (rc == NS_LDAP_SUCCESS) {
3224 			/*
3225 			 * Here rc == NS_LDAP_SUCCESS means that the state
3226 			 * machine init'ed successfully. The actual status
3227 			 * of the search will be determined by
3228 			 * __ns_ldap_list_batch_end(). Add the cookie to our
3229 			 * batch.
3230 			 */
3231 			cookie->caller_result = rResult;
3232 			cookie->caller_errorp = errorp;
3233 			cookie->caller_rc = rcp;
3234 			cookie->next_cookie_in_batch = batch->cookie_list;
3235 			batch->cookie_list = cookie;
3236 			batch->nactive++;
3237 			return (rc);
3238 		}
3239 		/*
3240 		 * If state machine init failed then copy error to the caller
3241 		 * and delete the cookie.
3242 		 */
3243 	} else {
3244 		(void) search_state_machine(cookie, INIT, 0);
3245 	}
3246 
3247 	/* Copy results back to user */
3248 	rc = cookie->err_rc;
3249 	if (rc != NS_LDAP_SUCCESS) {
3250 		if (conn_user != NULL && conn_user->ns_error != NULL) {
3251 			*errorp = conn_user->ns_error;
3252 			conn_user->ns_error = NULL;
3253 		} else
3254 			*errorp = cookie->errorp;
3255 	}
3256 	*rResult = cookie->result;
3257 	from_result = cookie->err_from_result;
3258 
3259 	cookie->errorp = NULL;
3260 	cookie->result = NULL;
3261 	delete_search_cookie(cookie);
3262 	cookie = NULL;
3263 
3264 	if (from_result == 0 && *rResult == NULL)
3265 		rc = NS_LDAP_NOTFOUND;
3266 	*rcp = rc;
3267 	return (rc);
3268 }
3269 
3270 
3271 /*
3272  * __ns_ldap_list performs one or more LDAP searches to a given
3273  * directory server using service search descriptors and schema
3274  * mapping as appropriate. The operation may be retried a
3275  * couple of times in error situations.
3276  */
3277 int
3278 __ns_ldap_list(
3279 	const char *service,
3280 	const char *filter,
3281 	int (*init_filter_cb)(const ns_ldap_search_desc_t *desc,
3282 	char **realfilter, const void *userdata),
3283 	const char * const *attribute,
3284 	const ns_cred_t *auth,
3285 	const int flags,
3286 	ns_ldap_result_t **rResult, /* return result entries */
3287 	ns_ldap_error_t **errorp,
3288 	int (*callback)(const ns_ldap_entry_t *entry, const void *userdata),
3289 	const void *userdata)
3290 {
3291 	int mod_flags;
3292 	/*
3293 	 * Strip the NS_LDAP_PAGE_CTRL option as this interface does not
3294 	 * support this. If you want to use this option call the API
3295 	 * __ns_ldap_list_sort() with has the sort attribute.
3296 	 */
3297 	mod_flags = flags & (~NS_LDAP_PAGE_CTRL);
3298 
3299 	return (__ns_ldap_list_sort(service, filter, NULL, init_filter_cb,
3300 	    attribute, auth, mod_flags, rResult, errorp,
3301 	    callback, userdata));
3302 }
3303 
3304 /*
3305  * __ns_ldap_list_sort performs one or more LDAP searches to a given
3306  * directory server using service search descriptors and schema
3307  * mapping as appropriate. The operation may be retried a
3308  * couple of times in error situations.
3309  */
3310 int
3311 __ns_ldap_list_sort(
3312 	const char *service,
3313 	const char *filter,
3314 	const char *sortattr,
3315 	int (*init_filter_cb)(const ns_ldap_search_desc_t *desc,
3316 	char **realfilter, const void *userdata),
3317 	const char * const *attribute,
3318 	const ns_cred_t *auth,
3319 	const int flags,
3320 	ns_ldap_result_t **rResult, /* return result entries */
3321 	ns_ldap_error_t **errorp,
3322 	int (*callback)(const ns_ldap_entry_t *entry, const void *userdata),
3323 	const void *userdata)
3324 {
3325 	ns_conn_user_t	*cu = NULL;
3326 	int		try_cnt = 0;
3327 	int		rc = NS_LDAP_SUCCESS, trc;
3328 
3329 	for (;;) {
3330 		if (__s_api_setup_retry_search(&cu, NS_CONN_USER_SEARCH,
3331 		    &try_cnt, &rc, errorp) == 0)
3332 			break;
3333 		rc = ldap_list(NULL, service, filter, sortattr, init_filter_cb,
3334 		    attribute, auth, flags, rResult, errorp, &trc, callback,
3335 		    userdata, cu);
3336 	}
3337 
3338 	return (rc);
3339 }
3340 
3341 /*
3342  * Create and initialize batch for native LDAP lookups
3343  */
3344 int
3345 __ns_ldap_list_batch_start(ns_ldap_list_batch_t **batch)
3346 {
3347 	*batch = calloc(1, sizeof (ns_ldap_list_batch_t));
3348 	if (*batch == NULL)
3349 		return (NS_LDAP_MEMORY);
3350 	return (NS_LDAP_SUCCESS);
3351 }
3352 
3353 
3354 /*
3355  * Add a LDAP search request to the batch.
3356  */
3357 int
3358 __ns_ldap_list_batch_add(
3359 	ns_ldap_list_batch_t *batch,
3360 	const char *service,
3361 	const char *filter,
3362 	int (*init_filter_cb)(const ns_ldap_search_desc_t *desc,
3363 	char **realfilter, const void *userdata),
3364 	const char * const *attribute,
3365 	const ns_cred_t *auth,
3366 	const int flags,
3367 	ns_ldap_result_t **rResult, /* return result entries */
3368 	ns_ldap_error_t **errorp,
3369 	int *rcp,
3370 	int (*callback)(const ns_ldap_entry_t *entry, const void *userdata),
3371 	const void *userdata)
3372 {
3373 	ns_conn_user_t	*cu;
3374 	int		rc;
3375 	int		mod_flags;
3376 
3377 	cu =  __s_api_conn_user_init(NS_CONN_USER_SEARCH, NULL, 0);
3378 	if (cu == NULL) {
3379 		if (rcp != NULL)
3380 			*rcp = NS_LDAP_MEMORY;
3381 		return (NS_LDAP_MEMORY);
3382 	}
3383 
3384 	/*
3385 	 * Strip the NS_LDAP_PAGE_CTRL option as the batch interface does not
3386 	 * support this.
3387 	 */
3388 	mod_flags = flags & (~NS_LDAP_PAGE_CTRL);
3389 
3390 	rc = ldap_list(batch, service, filter, NULL, init_filter_cb, attribute,
3391 	    auth, mod_flags, rResult, errorp, rcp, callback, userdata, cu);
3392 
3393 	/*
3394 	 * Free the conn_user if the cookie was not batched. If the cookie
3395 	 * was batched then __ns_ldap_list_batch_end or release will free the
3396 	 * conn_user. The batch API instructs the search_state_machine
3397 	 * to reinit and retry (max 3 times) on retriable LDAP errors.
3398 	 */
3399 	if (rc != NS_LDAP_SUCCESS && cu != NULL) {
3400 		if (cu->conn_mt != NULL)
3401 			__s_api_conn_mt_return(cu);
3402 		__s_api_conn_user_free(cu);
3403 	}
3404 	return (rc);
3405 }
3406 
3407 
3408 /*
3409  * Free batch.
3410  */
3411 void
3412 __ns_ldap_list_batch_release(ns_ldap_list_batch_t *batch)
3413 {
3414 	ns_ldap_cookie_t	*c, *next;
3415 
3416 	for (c = batch->cookie_list; c != NULL; c = next) {
3417 		next = c->next_cookie_in_batch;
3418 		if (c->conn_user != NULL) {
3419 			if (c->conn_user->conn_mt != NULL)
3420 				__s_api_conn_mt_return(c->conn_user);
3421 			__s_api_conn_user_free(c->conn_user);
3422 			c->conn_user = NULL;
3423 		}
3424 		delete_search_cookie(c);
3425 	}
3426 	free(batch);
3427 }
3428 
3429 #define	LD_USING_STATE(st) \
3430 	((st == DO_SEARCH) || (st == MULTI_RESULT) || (st == NEXT_RESULT))
3431 
3432 /*
3433  * Process batch. Everytime this function is called it selects an
3434  * active cookie from the batch and single steps through the
3435  * search_state_machine for the selected cookie. If lookup associated
3436  * with the cookie is complete (success or error) then the cookie is
3437  * removed from the batch and its memory freed.
3438  *
3439  * Returns 1 (if batch still has active cookies)
3440  *         0 (if batch has no more active cookies)
3441  *        -1 (on errors, *rcp will contain the error code)
3442  *
3443  * The caller should call this function in a loop as long as it returns 1
3444  * to process all the requests added to the batch. The results (and errors)
3445  * will be available in the locations provided by the caller at the time of
3446  * __ns_ldap_list_batch_add().
3447  */
3448 static
3449 int
3450 __ns_ldap_list_batch_process(ns_ldap_list_batch_t *batch, int *rcp)
3451 {
3452 	ns_ldap_cookie_t	*c, *ptr, **prev;
3453 	ns_state_t		state;
3454 	ns_ldap_error_t		*errorp = NULL;
3455 	int			rc;
3456 
3457 	/* Check if are already done */
3458 	if (batch->nactive == 0)
3459 		return (0);
3460 
3461 	/* Get the next cookie from the batch */
3462 	c = (batch->next_cookie == NULL) ?
3463 	    batch->cookie_list : batch->next_cookie;
3464 
3465 	batch->next_cookie = c->next_cookie_in_batch;
3466 
3467 	/*
3468 	 * Checks the status of the cookie's connection if it needs
3469 	 * to use that connection for ldap_search_ext or ldap_result.
3470 	 * If the connection is no longer good but worth retrying
3471 	 * then reinit the search_state_machine for this cookie
3472 	 * starting from the first search descriptor. REINIT will
3473 	 * clear any leftover results if max retries have not been
3474 	 * reached and redo the search (which may also involve
3475 	 * following referrals again).
3476 	 *
3477 	 * Note that each cookie in the batch will make this
3478 	 * determination when it reaches one of the LD_USING_STATES.
3479 	 */
3480 	if (LD_USING_STATE(c->new_state) && c->conn_user != NULL) {
3481 		rc = __s_api_setup_getnext(c->conn_user, &c->err_rc, &errorp);
3482 		if (rc == LDAP_BUSY || rc == LDAP_UNAVAILABLE ||
3483 		    rc == LDAP_UNWILLING_TO_PERFORM) {
3484 			if (errorp != NULL) {
3485 				(void) __ns_ldap_freeError(&c->errorp);
3486 				c->errorp = errorp;
3487 			}
3488 			c->new_state = REINIT;
3489 		} else if (rc == LDAP_CONNECT_ERROR ||
3490 		    rc == LDAP_SERVER_DOWN) {
3491 			if (errorp != NULL) {
3492 				(void) __ns_ldap_freeError(&c->errorp);
3493 				c->errorp = errorp;
3494 			}
3495 			c->new_state = REINIT;
3496 			/*
3497 			 * MT connection is not usable,
3498 			 * close it before REINIT.
3499 			 */
3500 			__s_api_conn_mt_close(
3501 			    c->conn_user, rc, NULL);
3502 		} else if (rc != NS_LDAP_SUCCESS) {
3503 			if (rcp != NULL)
3504 				*rcp = rc;
3505 			*c->caller_result = NULL;
3506 			*c->caller_errorp = errorp;
3507 			*c->caller_rc = rc;
3508 			return (-1);
3509 		}
3510 	}
3511 
3512 	for (;;) {
3513 		/* Single step through the search_state_machine */
3514 		state = search_state_machine(c, c->new_state, ONE_STEP);
3515 		switch (state) {
3516 		case LDAP_ERROR:
3517 			(void) search_state_machine(c, state, ONE_STEP);
3518 			(void) search_state_machine(c, CLEAR_RESULTS, ONE_STEP);
3519 			/* FALLTHROUGH */
3520 		case ERROR:
3521 		case EXIT:
3522 			*c->caller_result = c->result;
3523 			*c->caller_errorp = c->errorp;
3524 			*c->caller_rc =
3525 			    (c->result == NULL && c->err_from_result == 0)
3526 			    ? NS_LDAP_NOTFOUND : c->err_rc;
3527 			c->result = NULL;
3528 			c->errorp = NULL;
3529 			/* Remove the cookie from the batch */
3530 			ptr = batch->cookie_list;
3531 			prev = &batch->cookie_list;
3532 			while (ptr != NULL) {
3533 				if (ptr == c) {
3534 					*prev = ptr->next_cookie_in_batch;
3535 					break;
3536 				}
3537 				prev = &ptr->next_cookie_in_batch;
3538 				ptr = ptr->next_cookie_in_batch;
3539 			}
3540 			/* Delete cookie and decrement active cookie count */
3541 			if (c->conn_user != NULL) {
3542 				if (c->conn_user->conn_mt != NULL)
3543 					__s_api_conn_mt_return(c->conn_user);
3544 				__s_api_conn_user_free(c->conn_user);
3545 				c->conn_user = NULL;
3546 			}
3547 			delete_search_cookie(c);
3548 			batch->nactive--;
3549 			break;
3550 		case NEXT_RESULT:
3551 		case MULTI_RESULT:
3552 			/*
3553 			 * This means that search_state_machine needs to do
3554 			 * another ldap_result() for the cookie in question.
3555 			 * We only do at most one ldap_result() per call in
3556 			 * this function and therefore we return. This allows
3557 			 * the caller to process results from other cookies
3558 			 * in the batch without getting tied up on just one
3559 			 * cookie.
3560 			 */
3561 			break;
3562 		default:
3563 			/*
3564 			 * This includes states that follow NEXT_RESULT or
3565 			 * MULTI_RESULT such as PROCESS_RESULT and
3566 			 * END_PROCESS_RESULT. We continue processing
3567 			 * this cookie till we reach either the error, exit
3568 			 * or the result states.
3569 			 */
3570 			continue;
3571 		}
3572 		break;
3573 	}
3574 
3575 	/* Return 0 if no more cookies left otherwise 1 */
3576 	return ((batch->nactive > 0) ? 1 : 0);
3577 }
3578 
3579 
3580 /*
3581  * Process all the active cookies in the batch and when none
3582  * remains finalize the batch.
3583  */
3584 int
3585 __ns_ldap_list_batch_end(ns_ldap_list_batch_t *batch)
3586 {
3587 	int rc = NS_LDAP_SUCCESS;
3588 	while (__ns_ldap_list_batch_process(batch, &rc) > 0)
3589 		;
3590 	__ns_ldap_list_batch_release(batch);
3591 	return (rc);
3592 }
3593 
3594 /*
3595  * find_domainname performs one or more LDAP searches to
3596  * find the value of the nisdomain attribute associated with
3597  * the input DN (with no retry).
3598  */
3599 
3600 static int
3601 find_domainname(const char *dn, char **domainname, const ns_cred_t *cred,
3602     ns_ldap_error_t **errorp, ns_conn_user_t *conn_user)
3603 {
3604 
3605 	ns_ldap_cookie_t	*cookie;
3606 	ns_ldap_search_desc_t	**sdlist;
3607 	ns_ldap_search_desc_t	*dptr;
3608 	int			rc;
3609 	char			**value;
3610 	int			flags = 0;
3611 
3612 	*domainname = NULL;
3613 	*errorp = NULL;
3614 
3615 	/* Initialize State machine cookie */
3616 	cookie = init_search_state_machine();
3617 	if (cookie == NULL) {
3618 		return (NS_LDAP_MEMORY);
3619 	}
3620 	cookie->conn_user = conn_user;
3621 
3622 	/* see if need to follow referrals */
3623 	rc = __s_api_toFollowReferrals(flags,
3624 	    &cookie->followRef, errorp);
3625 	if (rc != NS_LDAP_SUCCESS) {
3626 		delete_search_cookie(cookie);
3627 		return (rc);
3628 	}
3629 
3630 	/* Create default service Desc */
3631 	sdlist = (ns_ldap_search_desc_t **)calloc(2,
3632 	    sizeof (ns_ldap_search_desc_t *));
3633 	if (sdlist == NULL) {
3634 		delete_search_cookie(cookie);
3635 		cookie = NULL;
3636 		return (NS_LDAP_MEMORY);
3637 	}
3638 	dptr = (ns_ldap_search_desc_t *)
3639 	    calloc(1, sizeof (ns_ldap_search_desc_t));
3640 	if (dptr == NULL) {
3641 		free(sdlist);
3642 		delete_search_cookie(cookie);
3643 		cookie = NULL;
3644 		return (NS_LDAP_MEMORY);
3645 	}
3646 	sdlist[0] = dptr;
3647 
3648 	/* search base is dn */
3649 	dptr->basedn = strdup(dn);
3650 
3651 	/* search scope is base */
3652 	dptr->scope = NS_LDAP_SCOPE_BASE;
3653 
3654 	/* search filter is "nisdomain=*" */
3655 	dptr->filter = strdup(_NIS_FILTER);
3656 
3657 	cookie->sdlist = sdlist;
3658 	cookie->i_filter = strdup(dptr->filter);
3659 	cookie->i_attr = nis_domain_attrs;
3660 	cookie->i_auth = cred;
3661 	cookie->i_flags = 0;
3662 
3663 	/* Process search */
3664 	rc = search_state_machine(cookie, INIT, 0);
3665 
3666 	/* Copy domain name if found */
3667 	rc = cookie->err_rc;
3668 	if (rc != NS_LDAP_SUCCESS) {
3669 		if (conn_user != NULL && conn_user->ns_error != NULL) {
3670 			*errorp = conn_user->ns_error;
3671 			conn_user->ns_error = NULL;
3672 		} else
3673 			*errorp = cookie->errorp;
3674 	}
3675 	if (cookie->result == NULL)
3676 		rc = NS_LDAP_NOTFOUND;
3677 	if (rc == NS_LDAP_SUCCESS) {
3678 		value = __ns_ldap_getAttr(cookie->result->entry,
3679 		    _NIS_DOMAIN);
3680 		if (value[0])
3681 			*domainname = strdup(value[0]);
3682 		else
3683 			rc = NS_LDAP_NOTFOUND;
3684 	}
3685 	if (cookie->result != NULL)
3686 		(void) __ns_ldap_freeResult(&cookie->result);
3687 	cookie->errorp = NULL;
3688 	delete_search_cookie(cookie);
3689 	cookie = NULL;
3690 	return (rc);
3691 }
3692 
3693 /*
3694  * __s_api_find_domainname performs one or more LDAP searches to
3695  * find the value of the nisdomain attribute associated with
3696  * the input DN (with retry).
3697  */
3698 
3699 static int
3700 __s_api_find_domainname(const char *dn, char **domainname,
3701     const ns_cred_t *cred, ns_ldap_error_t **errorp)
3702 {
3703 	ns_conn_user_t	*cu = NULL;
3704 	int		try_cnt = 0;
3705 	int		rc = NS_LDAP_SUCCESS;
3706 
3707 	for (;;) {
3708 		if (__s_api_setup_retry_search(&cu, NS_CONN_USER_SEARCH,
3709 		    &try_cnt, &rc, errorp) == 0)
3710 			break;
3711 		rc = find_domainname(dn, domainname, cred, errorp, cu);
3712 	}
3713 
3714 	return (rc);
3715 }
3716 
3717 static int
3718 firstEntry(
3719     const char *service,
3720     const char *filter,
3721     const char *sortattr,
3722     int (*init_filter_cb)(const ns_ldap_search_desc_t *desc,
3723     char **realfilter, const void *userdata),
3724     const char * const *attribute,
3725     const ns_cred_t *auth,
3726     const int flags,
3727     void **vcookie,
3728     ns_ldap_result_t **result,
3729     ns_ldap_error_t ** errorp,
3730     const void *userdata,
3731     ns_conn_user_t *conn_user)
3732 {
3733 	ns_ldap_cookie_t	*cookie = NULL;
3734 	ns_ldap_error_t		*error = NULL;
3735 	ns_state_t		state;
3736 	ns_ldap_search_desc_t	**sdlist;
3737 	ns_ldap_search_desc_t	*dptr;
3738 	char			**dns = NULL;
3739 	int			scope;
3740 	int			rc;
3741 
3742 	*errorp = NULL;
3743 	*result = NULL;
3744 
3745 	/*
3746 	 * Sanity check - NS_LDAP_READ_SHADOW is for our
3747 	 * own internal use.
3748 	 */
3749 	if (flags & NS_LDAP_READ_SHADOW)
3750 		return (NS_LDAP_INVALID_PARAM);
3751 
3752 	/* get the service descriptor - or create a default one */
3753 	rc = __s_api_get_SSD_from_SSDtoUse_service(service,
3754 	    &sdlist, &error);
3755 	if (rc != NS_LDAP_SUCCESS) {
3756 		*errorp = error;
3757 		return (rc);
3758 	}
3759 	if (sdlist == NULL) {
3760 		/* Create default service Desc */
3761 		sdlist = (ns_ldap_search_desc_t **)calloc(2,
3762 		    sizeof (ns_ldap_search_desc_t *));
3763 		if (sdlist == NULL) {
3764 			return (NS_LDAP_MEMORY);
3765 		}
3766 		dptr = (ns_ldap_search_desc_t *)
3767 		    calloc(1, sizeof (ns_ldap_search_desc_t));
3768 		if (dptr == NULL) {
3769 			free(sdlist);
3770 			return (NS_LDAP_MEMORY);
3771 		}
3772 		sdlist[0] = dptr;
3773 
3774 		/* default base */
3775 		rc = __s_api_getDNs(&dns, service, &error);
3776 		if (rc != NS_LDAP_SUCCESS) {
3777 			if (dns) {
3778 				__s_api_free2dArray(dns);
3779 				dns = NULL;
3780 			}
3781 			if (sdlist) {
3782 				(void) __ns_ldap_freeSearchDescriptors(
3783 				    &sdlist);
3784 
3785 				sdlist = NULL;
3786 			}
3787 			*errorp = error;
3788 			return (rc);
3789 		}
3790 		dptr->basedn = strdup(dns[0]);
3791 		__s_api_free2dArray(dns);
3792 		dns = NULL;
3793 
3794 		/* default scope */
3795 		scope = 0;
3796 		cookie = init_search_state_machine();
3797 		if (cookie == NULL) {
3798 			if (sdlist) {
3799 				(void) __ns_ldap_freeSearchDescriptors(&sdlist);
3800 				sdlist = NULL;
3801 			}
3802 			return (NS_LDAP_MEMORY);
3803 		}
3804 		rc = __s_api_getSearchScope(&scope, &cookie->errorp);
3805 		dptr->scope = scope;
3806 	}
3807 
3808 	/* Initialize State machine cookie */
3809 	if (cookie == NULL)
3810 		cookie = init_search_state_machine();
3811 	if (cookie == NULL) {
3812 		if (sdlist) {
3813 			(void) __ns_ldap_freeSearchDescriptors(&sdlist);
3814 			sdlist = NULL;
3815 		}
3816 		return (NS_LDAP_MEMORY);
3817 	}
3818 
3819 	/* identify self as a getent user */
3820 	cookie->conn_user = conn_user;
3821 
3822 	cookie->sdlist = sdlist;
3823 
3824 	/* see if need to follow referrals */
3825 	rc = __s_api_toFollowReferrals(flags,
3826 	    &cookie->followRef, errorp);
3827 	if (rc != NS_LDAP_SUCCESS) {
3828 		delete_search_cookie(cookie);
3829 		return (rc);
3830 	}
3831 
3832 	/*
3833 	 * use VLV/PAGE control only if NS_LDAP_NO_PAGE_CTRL is not set
3834 	 */
3835 	if (flags & NS_LDAP_NO_PAGE_CTRL)
3836 		cookie->use_paging = FALSE;
3837 	else
3838 		cookie->use_paging = TRUE;
3839 
3840 	/* Set up other arguments */
3841 	cookie->userdata = userdata;
3842 	if (init_filter_cb != NULL) {
3843 		cookie->init_filter_cb = init_filter_cb;
3844 		cookie->use_filtercb = 1;
3845 	}
3846 	cookie->use_usercb = 0;
3847 	/* check_shadow() may add extra value to cookie->i_flags */
3848 	cookie->i_flags = flags;
3849 	if (service) {
3850 		cookie->service = strdup(service);
3851 		if (cookie->service == NULL) {
3852 			delete_search_cookie(cookie);
3853 			return (NS_LDAP_MEMORY);
3854 		}
3855 
3856 		/*
3857 		 * If given, use the credential given by the caller, and
3858 		 * skip the credential check required for shadow update.
3859 		 */
3860 		if (auth == NULL) {
3861 			rc = check_shadow(cookie, service);
3862 			if (rc != NS_LDAP_SUCCESS) {
3863 				*errorp = cookie->errorp;
3864 				cookie->errorp = NULL;
3865 				delete_search_cookie(cookie);
3866 				cookie = NULL;
3867 				return (rc);
3868 			}
3869 		}
3870 	}
3871 
3872 	cookie->i_filter = strdup(filter);
3873 	cookie->i_attr = attribute;
3874 	cookie->i_sortattr = sortattr;
3875 	cookie->i_auth = auth;
3876 
3877 	state = INIT;
3878 	for (;;) {
3879 		state = search_state_machine(cookie, state, ONE_STEP);
3880 		switch (state) {
3881 		case PROCESS_RESULT:
3882 			*result = cookie->result;
3883 			cookie->result = NULL;
3884 			*vcookie = (void *)cookie;
3885 			return (NS_LDAP_SUCCESS);
3886 		case LDAP_ERROR:
3887 			state = search_state_machine(cookie, state, ONE_STEP);
3888 			state = search_state_machine(cookie, CLEAR_RESULTS,
3889 			    ONE_STEP);
3890 			/* FALLTHROUGH */
3891 		case ERROR:
3892 			rc = cookie->err_rc;
3893 			if (conn_user != NULL && conn_user->ns_error != NULL) {
3894 				*errorp = conn_user->ns_error;
3895 				conn_user->ns_error = NULL;
3896 			} else {
3897 				*errorp = cookie->errorp;
3898 				cookie->errorp = NULL;
3899 			}
3900 			delete_search_cookie(cookie);
3901 			return (rc);
3902 		case EXIT:
3903 			rc = cookie->err_rc;
3904 			if (rc != NS_LDAP_SUCCESS) {
3905 				*errorp = cookie->errorp;
3906 				cookie->errorp = NULL;
3907 			} else {
3908 				rc = NS_LDAP_NOTFOUND;
3909 			}
3910 
3911 			delete_search_cookie(cookie);
3912 			return (rc);
3913 
3914 		default:
3915 			break;
3916 		}
3917 	}
3918 }
3919 
3920 int
3921 __ns_ldap_firstEntry(
3922     const char *service,
3923     const char *filter,
3924     const char *vlv_sort,
3925     int (*init_filter_cb)(const ns_ldap_search_desc_t *desc,
3926     char **realfilter, const void *userdata),
3927     const char * const *attribute,
3928     const ns_cred_t *auth,
3929     const int flags,
3930     void **vcookie,
3931     ns_ldap_result_t **result,
3932     ns_ldap_error_t ** errorp,
3933     const void *userdata)
3934 {
3935 	ns_conn_user_t	*cu = NULL;
3936 	int		try_cnt = 0;
3937 	int		rc = NS_LDAP_SUCCESS;
3938 
3939 	for (;;) {
3940 		if (__s_api_setup_retry_search(&cu, NS_CONN_USER_GETENT,
3941 		    &try_cnt, &rc, errorp) == 0)
3942 			break;
3943 		rc = firstEntry(service, filter, vlv_sort, init_filter_cb,
3944 		    attribute, auth, flags, vcookie, result, errorp, userdata,
3945 		    cu);
3946 	}
3947 	return (rc);
3948 }
3949 
3950 /*ARGSUSED2*/
3951 int
3952 __ns_ldap_nextEntry(void *vcookie, ns_ldap_result_t **result,
3953     ns_ldap_error_t ** errorp)
3954 {
3955 	ns_ldap_cookie_t	*cookie;
3956 	ns_state_t		state;
3957 	int			rc;
3958 
3959 	cookie = (ns_ldap_cookie_t *)vcookie;
3960 	cookie->result = NULL;
3961 	*result = NULL;
3962 
3963 	if (cookie->conn_user != NULL) {
3964 		rc = __s_api_setup_getnext(cookie->conn_user,
3965 		    &cookie->err_rc, errorp);
3966 		if (rc != NS_LDAP_SUCCESS)
3967 			return (rc);
3968 	}
3969 
3970 	state = END_PROCESS_RESULT;
3971 	for (;;) {
3972 		state = search_state_machine(cookie, state, ONE_STEP);
3973 		switch (state) {
3974 		case PROCESS_RESULT:
3975 			*result = cookie->result;
3976 			cookie->result = NULL;
3977 			return (NS_LDAP_SUCCESS);
3978 		case LDAP_ERROR:
3979 			state = search_state_machine(cookie, state, ONE_STEP);
3980 			state = search_state_machine(cookie, CLEAR_RESULTS,
3981 			    ONE_STEP);
3982 			/* FALLTHROUGH */
3983 		case ERROR:
3984 			rc = cookie->err_rc;
3985 			*errorp = cookie->errorp;
3986 			cookie->errorp = NULL;
3987 			return (rc);
3988 		case EXIT:
3989 			return (NS_LDAP_SUCCESS);
3990 		}
3991 	}
3992 }
3993 
3994 int
3995 __ns_ldap_endEntry(
3996 	void **vcookie,
3997 	ns_ldap_error_t ** errorp)
3998 {
3999 	ns_ldap_cookie_t	*cookie;
4000 	int			rc;
4001 
4002 	if (*vcookie == NULL)
4003 		return (NS_LDAP_INVALID_PARAM);
4004 
4005 	cookie = (ns_ldap_cookie_t *)(*vcookie);
4006 	cookie->result = NULL;
4007 
4008 	/* Complete search */
4009 	rc = search_state_machine(cookie, CLEAR_RESULTS, 0);
4010 
4011 	/* Copy results back to user */
4012 	rc = cookie->err_rc;
4013 	if (rc != NS_LDAP_SUCCESS)
4014 		*errorp = cookie->errorp;
4015 
4016 	cookie->errorp = NULL;
4017 	if (cookie->conn_user != NULL) {
4018 		if (cookie->conn_user->conn_mt != NULL)
4019 			__s_api_conn_mt_return(cookie->conn_user);
4020 		__s_api_conn_user_free(cookie->conn_user);
4021 	}
4022 	delete_search_cookie(cookie);
4023 	cookie = NULL;
4024 	*vcookie = NULL;
4025 
4026 	return (rc);
4027 }
4028 
4029 
4030 int
4031 __ns_ldap_freeResult(ns_ldap_result_t **result)
4032 {
4033 
4034 	ns_ldap_entry_t	*curEntry = NULL;
4035 	ns_ldap_entry_t	*delEntry = NULL;
4036 	int		i;
4037 	ns_ldap_result_t	*res = *result;
4038 
4039 #ifdef DEBUG
4040 	(void) fprintf(stderr, "__ns_ldap_freeResult START\n");
4041 #endif
4042 	if (res == NULL)
4043 		return (NS_LDAP_INVALID_PARAM);
4044 
4045 	if (res->entry != NULL)
4046 		curEntry = res->entry;
4047 
4048 	for (i = 0; i < res->entries_count; i++) {
4049 		if (curEntry != NULL) {
4050 			delEntry = curEntry;
4051 			curEntry = curEntry->next;
4052 			__ns_ldap_freeEntry(delEntry);
4053 		}
4054 	}
4055 
4056 	free(res);
4057 	*result = NULL;
4058 	return (NS_LDAP_SUCCESS);
4059 }
4060 
4061 /*ARGSUSED*/
4062 int
4063 __ns_ldap_auth(const ns_cred_t *auth,
4064 		    const int flags,
4065 		    ns_ldap_error_t **errorp,
4066 		    LDAPControl **serverctrls,
4067 		    LDAPControl **clientctrls)
4068 {
4069 
4070 	ConnectionID	connectionId = -1;
4071 	Connection	*conp;
4072 	int		rc = 0;
4073 	int		do_not_fail_if_new_pwd_reqd = 0;
4074 	int		nopasswd_acct_mgmt = 0;
4075 	ns_conn_user_t	*conn_user;
4076 
4077 
4078 #ifdef DEBUG
4079 	(void) fprintf(stderr, "__ns_ldap_auth START\n");
4080 #endif
4081 
4082 	*errorp = NULL;
4083 	if (!auth)
4084 		return (NS_LDAP_INVALID_PARAM);
4085 
4086 	conn_user = __s_api_conn_user_init(NS_CONN_USER_AUTH,
4087 	    NULL, B_FALSE);
4088 
4089 	rc = __s_api_getConnection(NULL, flags | NS_LDAP_NEW_CONN,
4090 	    auth, &connectionId, &conp, errorp,
4091 	    do_not_fail_if_new_pwd_reqd, nopasswd_acct_mgmt,
4092 	    conn_user);
4093 
4094 	if (conn_user != NULL)
4095 		__s_api_conn_user_free(conn_user);
4096 
4097 	if (rc == NS_LDAP_OP_FAILED && *errorp)
4098 		(void) __ns_ldap_freeError(errorp);
4099 
4100 	if (connectionId > -1)
4101 		DropConnection(connectionId, flags);
4102 	return (rc);
4103 }
4104 
4105 char **
4106 __ns_ldap_getAttr(const ns_ldap_entry_t *entry, const char *attrname)
4107 {
4108 	int	i;
4109 
4110 	if (entry == NULL)
4111 		return (NULL);
4112 	for (i = 0; i < entry->attr_count; i++) {
4113 		if (strcasecmp(entry->attr_pair[i]->attrname, attrname) == NULL)
4114 			return (entry->attr_pair[i]->attrvalue);
4115 	}
4116 	return (NULL);
4117 }
4118 
4119 ns_ldap_attr_t *
4120 __ns_ldap_getAttrStruct(const ns_ldap_entry_t *entry, const char *attrname)
4121 {
4122 	int	i;
4123 
4124 	if (entry == NULL)
4125 		return (NULL);
4126 	for (i = 0; i < entry->attr_count; i++) {
4127 		if (strcasecmp(entry->attr_pair[i]->attrname, attrname) == NULL)
4128 			return (entry->attr_pair[i]);
4129 	}
4130 	return (NULL);
4131 }
4132 
4133 
4134 /*ARGSUSED*/
4135 int
4136 __ns_ldap_uid2dn(const char *uid,
4137 		char **userDN,
4138 		const ns_cred_t *cred,	/* cred is ignored */
4139 		ns_ldap_error_t **errorp)
4140 {
4141 	ns_ldap_result_t	*result = NULL;
4142 	char		*filter, *userdata;
4143 	char		errstr[MAXERROR];
4144 	char		**value;
4145 	int		rc = 0;
4146 	int		i = 0;
4147 	size_t		len;
4148 
4149 	*errorp = NULL;
4150 	*userDN = NULL;
4151 	if ((uid == NULL) || (uid[0] == '\0'))
4152 		return (NS_LDAP_INVALID_PARAM);
4153 
4154 	while (uid[i] != '\0') {
4155 		if (uid[i] == '=') {
4156 			*userDN = strdup(uid);
4157 			return (NS_LDAP_SUCCESS);
4158 		}
4159 		i++;
4160 	}
4161 	i = 0;
4162 	while ((uid[i] != '\0') && (isdigit(uid[i])))
4163 		i++;
4164 	if (uid[i] == '\0') {
4165 		len = strlen(UIDNUMFILTER) + strlen(uid) + 1;
4166 		filter = (char *)malloc(len);
4167 		if (filter == NULL) {
4168 			*userDN = NULL;
4169 			return (NS_LDAP_MEMORY);
4170 		}
4171 		(void) snprintf(filter, len, UIDNUMFILTER, uid);
4172 
4173 		len = strlen(UIDNUMFILTER_SSD) + strlen(uid) + 1;
4174 		userdata = (char *)malloc(len);
4175 		if (userdata == NULL) {
4176 			*userDN = NULL;
4177 			return (NS_LDAP_MEMORY);
4178 		}
4179 		(void) snprintf(userdata, len, UIDNUMFILTER_SSD, uid);
4180 	} else {
4181 		len = strlen(UIDFILTER) + strlen(uid) + 1;
4182 		filter = (char *)malloc(len);
4183 		if (filter == NULL) {
4184 			*userDN = NULL;
4185 			return (NS_LDAP_MEMORY);
4186 		}
4187 		(void) snprintf(filter, len, UIDFILTER, uid);
4188 
4189 		len = strlen(UIDFILTER_SSD) + strlen(uid) + 1;
4190 		userdata = (char *)malloc(len);
4191 		if (userdata == NULL) {
4192 			*userDN = NULL;
4193 			return (NS_LDAP_MEMORY);
4194 		}
4195 		(void) snprintf(userdata, len, UIDFILTER_SSD, uid);
4196 	}
4197 
4198 	/*
4199 	 * we want to retrieve the DN as it appears in LDAP
4200 	 * hence the use of NS_LDAP_NOT_CVT_DN in flags
4201 	 */
4202 	rc = __ns_ldap_list("passwd", filter,
4203 	    __s_api_merge_SSD_filter,
4204 	    NULL, cred, NS_LDAP_NOT_CVT_DN,
4205 	    &result, errorp, NULL,
4206 	    userdata);
4207 	free(filter);
4208 	filter = NULL;
4209 	free(userdata);
4210 	userdata = NULL;
4211 	if (rc != NS_LDAP_SUCCESS) {
4212 		if (result) {
4213 			(void) __ns_ldap_freeResult(&result);
4214 			result = NULL;
4215 		}
4216 		return (rc);
4217 	}
4218 	if (result->entries_count > 1) {
4219 		(void) __ns_ldap_freeResult(&result);
4220 		result = NULL;
4221 		*userDN = NULL;
4222 		(void) sprintf(errstr,
4223 		    gettext("Too many entries are returned for %s"), uid);
4224 		MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL, strdup(errstr),
4225 		    NULL);
4226 		return (NS_LDAP_INTERNAL);
4227 	}
4228 
4229 	value = __ns_ldap_getAttr(result->entry, "dn");
4230 	*userDN = strdup(value[0]);
4231 	(void) __ns_ldap_freeResult(&result);
4232 	result = NULL;
4233 	return (NS_LDAP_SUCCESS);
4234 }
4235 
4236 #define	_P_UID	"uid"
4237 static const char *dn2uid_attrs[] = {
4238 	_P_CN,
4239 	_P_UID,
4240 	(char *)NULL
4241 };
4242 
4243 /*ARGSUSED*/
4244 int
4245 __ns_ldap_dn2uid(const char *dn,
4246 		char **userID,
4247 		const ns_cred_t *cred,	/* cred is ignored */
4248 		ns_ldap_error_t **errorp)
4249 {
4250 	ns_ldap_result_t	*result = NULL;
4251 	char		*filter, *userdata;
4252 	char		errstr[MAXERROR];
4253 	char		**value;
4254 	int		rc = 0;
4255 	size_t		len;
4256 
4257 	*errorp = NULL;
4258 	*userID = NULL;
4259 	if ((dn == NULL) || (dn[0] == '\0'))
4260 		return (NS_LDAP_INVALID_PARAM);
4261 
4262 	len = strlen(UIDDNFILTER) + strlen(dn) + 1;
4263 	filter = (char *)malloc(len);
4264 	if (filter == NULL) {
4265 		return (NS_LDAP_MEMORY);
4266 	}
4267 	(void) snprintf(filter, len, UIDDNFILTER, dn);
4268 
4269 	len = strlen(UIDDNFILTER_SSD) + strlen(dn) + 1;
4270 	userdata = (char *)malloc(len);
4271 	if (userdata == NULL) {
4272 		return (NS_LDAP_MEMORY);
4273 	}
4274 	(void) snprintf(userdata, len, UIDDNFILTER_SSD, dn);
4275 
4276 	/*
4277 	 * Unlike uid2dn, we DO want attribute mapping, so that
4278 	 * "uid" is mapped to/from samAccountName, for example.
4279 	 */
4280 	rc = __ns_ldap_list("passwd", filter,
4281 	    __s_api_merge_SSD_filter,
4282 	    dn2uid_attrs, cred, 0,
4283 	    &result, errorp, NULL,
4284 	    userdata);
4285 	free(filter);
4286 	filter = NULL;
4287 	free(userdata);
4288 	userdata = NULL;
4289 	if (rc != NS_LDAP_SUCCESS)
4290 		goto out;
4291 
4292 	if (result->entries_count > 1) {
4293 		(void) sprintf(errstr,
4294 		    gettext("Too many entries are returned for %s"), dn);
4295 		MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL, strdup(errstr),
4296 		    0);
4297 		rc = NS_LDAP_INTERNAL;
4298 		goto out;
4299 	}
4300 
4301 	value = __ns_ldap_getAttr(result->entry, _P_UID);
4302 	if (value == NULL || value[0] == NULL) {
4303 		rc = NS_LDAP_NOTFOUND;
4304 		goto out;
4305 	}
4306 
4307 	*userID = strdup(value[0]);
4308 	rc = NS_LDAP_SUCCESS;
4309 
4310 out:
4311 	(void) __ns_ldap_freeResult(&result);
4312 	result = NULL;
4313 	return (rc);
4314 }
4315 
4316 /*ARGSUSED*/
4317 int
4318 __ns_ldap_host2dn(const char *host,
4319 		const char *domain,
4320 		char **hostDN,
4321 		const ns_cred_t *cred,	/* cred is ignored */
4322 		ns_ldap_error_t **errorp)
4323 {
4324 	ns_ldap_result_t	*result = NULL;
4325 	char		*filter, *userdata;
4326 	char		errstr[MAXERROR];
4327 	char		**value;
4328 	int		rc;
4329 	size_t		len;
4330 
4331 /*
4332  * XXX
4333  * the domain parameter needs to be used in case domain is not local, if
4334  * this routine is to support multi domain setups, it needs lots of work...
4335  */
4336 	*errorp = NULL;
4337 	*hostDN = NULL;
4338 	if ((host == NULL) || (host[0] == '\0'))
4339 		return (NS_LDAP_INVALID_PARAM);
4340 
4341 	len = strlen(HOSTFILTER) + strlen(host) + 1;
4342 	filter = (char *)malloc(len);
4343 	if (filter == NULL) {
4344 		return (NS_LDAP_MEMORY);
4345 	}
4346 	(void) snprintf(filter,	len, HOSTFILTER, host);
4347 
4348 	len = strlen(HOSTFILTER_SSD) + strlen(host) + 1;
4349 	userdata = (char *)malloc(len);
4350 	if (userdata == NULL) {
4351 		return (NS_LDAP_MEMORY);
4352 	}
4353 	(void) snprintf(userdata, len, HOSTFILTER_SSD, host);
4354 
4355 	/*
4356 	 * we want to retrieve the DN as it appears in LDAP
4357 	 * hence the use of NS_LDAP_NOT_CVT_DN in flags
4358 	 */
4359 	rc = __ns_ldap_list("hosts", filter,
4360 	    __s_api_merge_SSD_filter,
4361 	    NULL, cred, NS_LDAP_NOT_CVT_DN, &result,
4362 	    errorp, NULL,
4363 	    userdata);
4364 	free(filter);
4365 	filter = NULL;
4366 	free(userdata);
4367 	userdata = NULL;
4368 	if (rc != NS_LDAP_SUCCESS) {
4369 		if (result) {
4370 			(void) __ns_ldap_freeResult(&result);
4371 			result = NULL;
4372 		}
4373 		return (rc);
4374 	}
4375 
4376 	if (result->entries_count > 1) {
4377 		(void) __ns_ldap_freeResult(&result);
4378 		result = NULL;
4379 		*hostDN = NULL;
4380 		(void) sprintf(errstr,
4381 		    gettext("Too many entries are returned for %s"), host);
4382 		MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL, strdup(errstr),
4383 		    NULL);
4384 		return (NS_LDAP_INTERNAL);
4385 	}
4386 
4387 	value = __ns_ldap_getAttr(result->entry, "dn");
4388 	*hostDN = strdup(value[0]);
4389 	(void) __ns_ldap_freeResult(&result);
4390 	result = NULL;
4391 	return (NS_LDAP_SUCCESS);
4392 }
4393 
4394 /*ARGSUSED*/
4395 int
4396 __ns_ldap_dn2domain(const char *dn,
4397 			char **domain,
4398 			const ns_cred_t *cred,
4399 			ns_ldap_error_t **errorp)
4400 {
4401 	int		rc, pnum, i, j, len = 0;
4402 	char		*newdn, **rdns = NULL;
4403 	char		**dns, *dn1;
4404 
4405 	*errorp = NULL;
4406 
4407 	if (domain == NULL)
4408 		return (NS_LDAP_INVALID_PARAM);
4409 	else
4410 		*domain = NULL;
4411 
4412 	if ((dn == NULL) || (dn[0] == '\0'))
4413 		return (NS_LDAP_INVALID_PARAM);
4414 
4415 	/*
4416 	 * break dn into rdns
4417 	 */
4418 	dn1 = strdup(dn);
4419 	if (dn1 == NULL)
4420 		return (NS_LDAP_MEMORY);
4421 	rdns = ldap_explode_dn(dn1, 0);
4422 	free(dn1);
4423 	if (rdns == NULL || *rdns == NULL)
4424 		return (NS_LDAP_INVALID_PARAM);
4425 
4426 	for (i = 0; rdns[i]; i++)
4427 		len += strlen(rdns[i]) + 1;
4428 	pnum = i;
4429 
4430 	newdn = (char *)malloc(len + 1);
4431 	dns = (char **)calloc(pnum, sizeof (char *));
4432 	if (newdn == NULL || dns == NULL) {
4433 		if (newdn)
4434 			free(newdn);
4435 		ldap_value_free(rdns);
4436 		return (NS_LDAP_MEMORY);
4437 	}
4438 
4439 	/* construct a semi-normalized dn, newdn */
4440 	*newdn = '\0';
4441 	for (i = 0; rdns[i]; i++) {
4442 		dns[i] = newdn + strlen(newdn);
4443 		(void) strcat(newdn,
4444 		    __s_api_remove_rdn_space(rdns[i]));
4445 		(void) strcat(newdn, ",");
4446 	}
4447 	/* remove the last ',' */
4448 	newdn[strlen(newdn) - 1] = '\0';
4449 	ldap_value_free(rdns);
4450 
4451 	/*
4452 	 * loop and find the domain name associated with newdn,
4453 	 * removing rdn one by one from left to right
4454 	 */
4455 	for (i = 0; i < pnum; i++) {
4456 
4457 		if (*errorp)
4458 			(void) __ns_ldap_freeError(errorp);
4459 
4460 		/*
4461 		 *  try cache manager first
4462 		 */
4463 		rc = __s_api_get_cachemgr_data(NS_CACHE_DN2DOMAIN,
4464 		    dns[i], domain);
4465 		if (rc != NS_LDAP_SUCCESS) {
4466 			/*
4467 			 *  try ldap server second
4468 			 */
4469 			rc = __s_api_find_domainname(dns[i], domain,
4470 			    cred, errorp);
4471 		} else {
4472 			/*
4473 			 * skip the last one,
4474 			 * since it is already cached by ldap_cachemgr
4475 			 */
4476 			i--;
4477 		}
4478 		if (rc == NS_LDAP_SUCCESS) {
4479 			if (__s_api_nscd_proc()) {
4480 				/*
4481 				 * If it's nscd, ask cache manager to save the
4482 				 * dn to domain mapping(s)
4483 				 */
4484 				for (j = 0; j <= i; j++) {
4485 					(void) __s_api_set_cachemgr_data(
4486 					    NS_CACHE_DN2DOMAIN,
4487 					    dns[j],
4488 					    *domain);
4489 				}
4490 			}
4491 			break;
4492 		}
4493 	}
4494 
4495 	free(dns);
4496 	free(newdn);
4497 	if (rc != NS_LDAP_SUCCESS)
4498 		rc = NS_LDAP_NOTFOUND;
4499 	return (rc);
4500 }
4501 
4502 /*ARGSUSED*/
4503 int
4504 __ns_ldap_getServiceAuthMethods(const char *service,
4505 		ns_auth_t ***auth,
4506 		ns_ldap_error_t **errorp)
4507 {
4508 	char		errstr[MAXERROR];
4509 	int		rc, i, done = 0;
4510 	int		slen;
4511 	void		**param;
4512 	char		**sam, *srv, *send;
4513 	ns_auth_t	**authpp = NULL, *ap;
4514 	int		cnt, max;
4515 	ns_config_t	*cfg;
4516 	ns_ldap_error_t	*error = NULL;
4517 
4518 	if (errorp == NULL)
4519 		return (NS_LDAP_INVALID_PARAM);
4520 	*errorp = NULL;
4521 
4522 	if ((service == NULL) || (service[0] == '\0') ||
4523 	    (auth == NULL))
4524 		return (NS_LDAP_INVALID_PARAM);
4525 
4526 	*auth = NULL;
4527 	rc = __ns_ldap_getParam(NS_LDAP_SERVICE_AUTH_METHOD_P, &param, &error);
4528 	if (rc != NS_LDAP_SUCCESS || param == NULL) {
4529 		*errorp = error;
4530 		return (rc);
4531 	}
4532 	sam = (char **)param;
4533 
4534 	cfg = __s_api_get_default_config();
4535 	cnt = 0;
4536 
4537 	slen = strlen(service);
4538 
4539 	for (; *sam; sam++) {
4540 		srv = *sam;
4541 		if (strncasecmp(service, srv, slen) != 0)
4542 			continue;
4543 		srv += slen;
4544 		if (*srv != COLONTOK)
4545 			continue;
4546 		send = srv;
4547 		srv++;
4548 		for (max = 1; (send = strchr(++send, SEMITOK)) != NULL;
4549 		    max++) {}
4550 		authpp = (ns_auth_t **)calloc(++max, sizeof (ns_auth_t *));
4551 		if (authpp == NULL) {
4552 			(void) __ns_ldap_freeParam(&param);
4553 			__s_api_release_config(cfg);
4554 			return (NS_LDAP_MEMORY);
4555 		}
4556 		while (!done) {
4557 			send = strchr(srv, SEMITOK);
4558 			if (send != NULL) {
4559 				*send = '\0';
4560 				send++;
4561 			}
4562 			i = __s_get_enum_value(cfg, srv, NS_LDAP_AUTH_P);
4563 			if (i == -1) {
4564 				(void) __ns_ldap_freeParam(&param);
4565 				(void) sprintf(errstr,
4566 				gettext("Unsupported "
4567 				    "serviceAuthenticationMethod: %s.\n"), srv);
4568 				MKERROR(LOG_WARNING, *errorp, NS_CONFIG_SYNTAX,
4569 				    strdup(errstr), NULL);
4570 				__s_api_release_config(cfg);
4571 				return (NS_LDAP_CONFIG);
4572 			}
4573 			ap = __s_api_AuthEnumtoStruct((EnumAuthType_t)i);
4574 			if (ap == NULL) {
4575 				(void) __ns_ldap_freeParam(&param);
4576 				__s_api_release_config(cfg);
4577 				return (NS_LDAP_MEMORY);
4578 			}
4579 			authpp[cnt++] = ap;
4580 			if (send == NULL)
4581 				done = TRUE;
4582 			else
4583 				srv = send;
4584 		}
4585 	}
4586 
4587 	*auth = authpp;
4588 	(void) __ns_ldap_freeParam(&param);
4589 	__s_api_release_config(cfg);
4590 	return (NS_LDAP_SUCCESS);
4591 }
4592 
4593 /*
4594  * This routine is called when certain scenario occurs
4595  * e.g.
4596  * service == auto_home
4597  * SSD = automount: ou = mytest,
4598  * NS_LDAP_MAPATTRIBUTE= auto_home: automountMapName=AAA
4599  * NS_LDAP_OBJECTCLASSMAP= auto_home:automountMap=MynisMap
4600  * NS_LDAP_OBJECTCLASSMAP= auto_home:automount=MynisObject
4601  *
4602  * The automountMapName is prepended implicitely but is mapped
4603  * to AAA. So dn could appers as
4604  * dn: AAA=auto_home,ou=bar,dc=foo,dc=com
4605  * dn: automountKey=user_01,AAA=auto_home,ou=bar,dc=foo,dc=com
4606  * dn: automountKey=user_02,AAA=auto_home,ou=bar,dc=foo,dc=com
4607  * in the directory.
4608  * This function is called to covert the mapped attr back to
4609  * orig attr when the entries are searched and returned
4610  */
4611 
4612 int
4613 __s_api_convert_automountmapname(const char *service, char **dn,
4614 		ns_ldap_error_t **errp) {
4615 
4616 	char	**mapping = NULL;
4617 	char	*mapped_attr = NULL;
4618 	char	*automountmapname = "automountMapName";
4619 	char	*buffer = NULL;
4620 	int	rc = NS_LDAP_SUCCESS;
4621 	char	errstr[MAXERROR];
4622 
4623 	/*
4624 	 * dn is an input/out parameter, check it first
4625 	 */
4626 
4627 	if (service == NULL || dn == NULL || *dn == NULL)
4628 		return (NS_LDAP_INVALID_PARAM);
4629 
4630 	/*
4631 	 * Check to see if there is a mapped attribute for auto_xxx
4632 	 */
4633 
4634 	mapping = __ns_ldap_getMappedAttributes(service, automountmapname);
4635 
4636 	/*
4637 	 * if no mapped attribute for auto_xxx, try automount
4638 	 */
4639 
4640 	if (mapping == NULL)
4641 		mapping = __ns_ldap_getMappedAttributes(
4642 			"automount", automountmapname);
4643 
4644 	/*
4645 	 * if no mapped attribute is found, return SUCCESS (no op)
4646 	 */
4647 
4648 	if (mapping == NULL)
4649 		return (NS_LDAP_SUCCESS);
4650 
4651 	/*
4652 	 * if the mapped attribute is found and attr is not empty,
4653 	 * copy it
4654 	 */
4655 
4656 	if (mapping[0] != NULL) {
4657 		mapped_attr = strdup(mapping[0]);
4658 		__s_api_free2dArray(mapping);
4659 		if (mapped_attr == NULL) {
4660 			return (NS_LDAP_MEMORY);
4661 		}
4662 	} else {
4663 		__s_api_free2dArray(mapping);
4664 
4665 		(void) snprintf(errstr, (2 * MAXERROR),
4666 			gettext(
4667 			"Attribute nisMapName is mapped to an "
4668 			"empty string.\n"));
4669 
4670 		MKERROR(LOG_ERR, *errp, NS_CONFIG_SYNTAX,
4671 			strdup(errstr), NULL);
4672 
4673 		return (NS_LDAP_CONFIG);
4674 	}
4675 
4676 	/*
4677 	 * Locate the mapped attribute in the dn
4678 	 * and replace it if it exists
4679 	 */
4680 
4681 	rc = __s_api_replace_mapped_attr_in_dn(
4682 		(const char *) automountmapname, (const char *) mapped_attr,
4683 		(const char *) *dn, &buffer);
4684 
4685 	/* clean up */
4686 
4687 	free(mapped_attr);
4688 
4689 	/*
4690 	 * If mapped attr is found(buffer != NULL)
4691 	 *	a new dn is returned
4692 	 * If no mapped attribute is in dn,
4693 	 *	return NS_LDAP_SUCCESS (no op)
4694 	 * If no memory,
4695 	 *	return NS_LDAP_MEMORY (no op)
4696 	 */
4697 
4698 	if (buffer != NULL) {
4699 		free(*dn);
4700 		*dn = buffer;
4701 	}
4702 
4703 	return (rc);
4704 }
4705 
4706 /*
4707  * If the mapped attr is found in the dn,
4708  * 	return NS_LDAP_SUCCESS and a new_dn.
4709  * If no mapped attr is found,
4710  * 	return NS_LDAP_SUCCESS and *new_dn == NULL
4711  * If there is not enough memory,
4712  * 	return NS_LDAP_MEMORY and *new_dn == NULL
4713  */
4714 
4715 int
4716 __s_api_replace_mapped_attr_in_dn(
4717 	const char *orig_attr, const char *mapped_attr,
4718 	const char *dn, char **new_dn) {
4719 
4720 	char	**dnArray = NULL;
4721 	char	*cur = NULL, *start = NULL;
4722 	int	i = 0, found = 0;
4723 	int	len = 0, orig_len = 0, mapped_len = 0;
4724 	int	dn_len = 0, tmp_len = 0;
4725 
4726 	*new_dn = NULL;
4727 
4728 	/*
4729 	 * seperate dn into individual componets
4730 	 * e.g.
4731 	 * "automountKey=user_01" , "automountMapName_test=auto_home", ...
4732 	 */
4733 	dnArray = ldap_explode_dn(dn, 0);
4734 
4735 	/*
4736 	 * This will find "mapped attr=value" in dn.
4737 	 * It won't find match if mapped attr appears
4738 	 * in the value.
4739 	 */
4740 	for (i = 0; dnArray[i] != NULL; i++) {
4741 		/*
4742 		 * This function is called when reading from
4743 		 * the directory so assume each component has "=".
4744 		 * Any ill formatted dn should be rejected
4745 		 * before adding to the directory
4746 		 */
4747 		cur = strchr(dnArray[i], '=');
4748 		*cur = '\0';
4749 		if (strcasecmp(mapped_attr, dnArray[i]) == 0)
4750 			found = 1;
4751 		*cur = '=';
4752 		if (found) break;
4753 	}
4754 
4755 	if (!found) {
4756 		__s_api_free2dArray(dnArray);
4757 		*new_dn = NULL;
4758 		return (NS_LDAP_SUCCESS);
4759 	}
4760 	/*
4761 	 * The new length is *dn length + (difference between
4762 	 * orig attr and mapped attr) + 1 ;
4763 	 * e.g.
4764 	 * automountKey=aa,automountMapName_test=auto_home,dc=foo,dc=com
4765 	 * ==>
4766 	 * automountKey=aa,automountMapName=auto_home,dc=foo,dc=com
4767 	 */
4768 	mapped_len = strlen(mapped_attr);
4769 	orig_len = strlen(orig_attr);
4770 	dn_len = strlen(dn);
4771 	len = dn_len + orig_len - mapped_len + 1;
4772 	*new_dn = (char *)calloc(1, len);
4773 	if (*new_dn == NULL) {
4774 		__s_api_free2dArray(dnArray);
4775 		return (NS_LDAP_MEMORY);
4776 	}
4777 
4778 	/*
4779 	 * Locate the mapped attr in the dn.
4780 	 * Use dnArray[i] instead of mapped_attr
4781 	 * because mapped_attr could appear in
4782 	 * the value
4783 	 */
4784 
4785 	cur = strstr(dn, dnArray[i]);
4786 	__s_api_free2dArray(dnArray);
4787 	/* copy the portion before mapped attr in dn  */
4788 	start = *new_dn;
4789 	tmp_len = cur - dn;
4790 	(void) memcpy((void *) start, (const void*) dn, tmp_len);
4791 
4792 	/*
4793 	 * Copy the orig_attr. e.g. automountMapName
4794 	 * This replaces mapped attr with orig attr
4795 	 */
4796 	start = start + (cur - dn); /* move cursor in buffer */
4797 	(void) memcpy((void *) start, (const void*) orig_attr, orig_len);
4798 
4799 	/*
4800 	 * Copy the portion after mapped attr in dn
4801 	 */
4802 	cur = cur + mapped_len; /* move cursor in  dn  */
4803 	start = start + orig_len; /* move cursor in buffer */
4804 	(void) strcpy(start, cur);
4805 
4806 	return (NS_LDAP_SUCCESS);
4807 }
4808 
4809 /*
4810  * Validate Filter functions
4811  */
4812 
4813 /* ***** Start of modified libldap.so.5 filter parser ***** */
4814 
4815 /* filter parsing routine forward references */
4816 static int adj_filter_list(char *str);
4817 static int adj_simple_filter(char *str);
4818 static int unescape_filterval(char *val);
4819 static int hexchar2int(char c);
4820 static int adj_substring_filter(char *val);
4821 
4822 
4823 /*
4824  * assumes string manipulation is in-line
4825  * and all strings are sufficient in size
4826  * return value is the position after 'c'
4827  */
4828 
4829 static char *
4830 resync_str(char *str, char *next, char c)
4831 {
4832 	char	*ret;
4833 
4834 	ret = str + strlen(str);
4835 	*next = c;
4836 	if (ret == next)
4837 		return (ret);
4838 	(void) strcat(str, next);
4839 	return (ret);
4840 }
4841 
4842 static char *
4843 find_right_paren(char *s)
4844 {
4845 	int	balance, escape;
4846 
4847 	balance = 1;
4848 	escape = 0;
4849 	while (*s && balance) {
4850 		if (escape == 0) {
4851 			if (*s == '(')
4852 				balance++;
4853 			else if (*s == ')')
4854 				balance--;
4855 		}
4856 		if (*s == '\\' && ! escape)
4857 			escape = 1;
4858 		else
4859 			escape = 0;
4860 		if (balance)
4861 			s++;
4862 	}
4863 
4864 	return (*s ? s : NULL);
4865 }
4866 
4867 static char *
4868 adj_complex_filter(char	*str)
4869 {
4870 	char	*next;
4871 
4872 	/*
4873 	 * We have (x(filter)...) with str sitting on
4874 	 * the x.  We have to find the paren matching
4875 	 * the one before the x and put the intervening
4876 	 * filters by calling adj_filter_list().
4877 	 */
4878 
4879 	str++;
4880 	if ((next = find_right_paren(str)) == NULL)
4881 		return (NULL);
4882 
4883 	*next = '\0';
4884 	if (adj_filter_list(str) == -1)
4885 		return (NULL);
4886 	next = resync_str(str, next, ')');
4887 	next++;
4888 
4889 	return (next);
4890 }
4891 
4892 static int
4893 adj_filter(char *str)
4894 {
4895 	char	*next;
4896 	int	parens, balance, escape;
4897 	char	*np, *cp,  *dp;
4898 
4899 	parens = 0;
4900 	while (*str) {
4901 		switch (*str) {
4902 		case '(':
4903 			str++;
4904 			parens++;
4905 			switch (*str) {
4906 			case '&':
4907 				if ((str = adj_complex_filter(str)) == NULL)
4908 					return (-1);
4909 
4910 				parens--;
4911 				break;
4912 
4913 			case '|':
4914 				if ((str = adj_complex_filter(str)) == NULL)
4915 					return (-1);
4916 
4917 				parens--;
4918 				break;
4919 
4920 			case '!':
4921 				if ((str = adj_complex_filter(str)) == NULL)
4922 					return (-1);
4923 
4924 				parens--;
4925 				break;
4926 
4927 			case '(':
4928 				/* illegal ((case - generated by conversion */
4929 
4930 				/* find missing close) */
4931 				np = find_right_paren(str+1);
4932 
4933 				/* error if not found */
4934 				if (np == NULL)
4935 					return (-1);
4936 
4937 				/* remove redundant (and) */
4938 				for (dp = str, cp = str+1; cp < np; ) {
4939 					*dp++ = *cp++;
4940 				}
4941 				cp++;
4942 				while (*cp)
4943 					*dp++ = *cp++;
4944 				*dp = '\0';
4945 
4946 				/* re-start test at original ( */
4947 				parens--;
4948 				str--;
4949 				break;
4950 
4951 			default:
4952 				balance = 1;
4953 				escape = 0;
4954 				next = str;
4955 				while (*next && balance) {
4956 					if (escape == 0) {
4957 						if (*next == '(')
4958 							balance++;
4959 						else if (*next == ')')
4960 							balance--;
4961 					}
4962 					if (*next == '\\' && ! escape)
4963 						escape = 1;
4964 					else
4965 						escape = 0;
4966 					if (balance)
4967 						next++;
4968 				}
4969 				if (balance != 0)
4970 					return (-1);
4971 
4972 				*next = '\0';
4973 				if (adj_simple_filter(str) == -1) {
4974 					return (-1);
4975 				}
4976 				next = resync_str(str, next, ')');
4977 				next++;
4978 				str = next;
4979 				parens--;
4980 				break;
4981 			}
4982 			break;
4983 
4984 		case ')':
4985 			str++;
4986 			parens--;
4987 			break;
4988 
4989 		case ' ':
4990 			str++;
4991 			break;
4992 
4993 		default:	/* assume it's a simple type=value filter */
4994 			next = strchr(str, '\0');
4995 			if (adj_simple_filter(str) == -1) {
4996 				return (-1);
4997 			}
4998 			str = next;
4999 			break;
5000 		}
5001 	}
5002 
5003 	return (parens ? -1 : 0);
5004 }
5005 
5006 
5007 /*
5008  * Put a list of filters like this "(filter1)(filter2)..."
5009  */
5010 
5011 static int
5012 adj_filter_list(char *str)
5013 {
5014 	char	*next;
5015 	char	save;
5016 
5017 	while (*str) {
5018 		while (*str && isspace(*str))
5019 			str++;
5020 		if (*str == '\0')
5021 			break;
5022 
5023 		if ((next = find_right_paren(str + 1)) == NULL)
5024 			return (-1);
5025 		save = *++next;
5026 
5027 		/* now we have "(filter)" with str pointing to it */
5028 		*next = '\0';
5029 		if (adj_filter(str) == -1)
5030 			return (-1);
5031 		next = resync_str(str, next, save);
5032 
5033 		str = next;
5034 	}
5035 
5036 	return (0);
5037 }
5038 
5039 
5040 /*
5041  * is_valid_attr - returns 1 if a is a syntactically valid left-hand side
5042  * of a filter expression, 0 otherwise.  A valid string may contain only
5043  * letters, numbers, hyphens, semi-colons, colons and periods. examples:
5044  *	cn
5045  *	cn;lang-fr
5046  *	1.2.3.4;binary;dynamic
5047  *	mail;dynamic
5048  *	cn:dn:1.2.3.4
5049  *
5050  * For compatibility with older servers, we also allow underscores in
5051  * attribute types, even through they are not allowed by the LDAPv3 RFCs.
5052  */
5053 static int
5054 is_valid_attr(char *a)
5055 {
5056 	for (; *a; a++) {
5057 		if (!isascii(*a)) {
5058 			return (0);
5059 		} else if (!isalnum(*a)) {
5060 			switch (*a) {
5061 			case '-':
5062 			case '.':
5063 			case ';':
5064 			case ':':
5065 			case '_':
5066 				break; /* valid */
5067 			default:
5068 				return (0);
5069 			}
5070 		}
5071 	}
5072 	return (1);
5073 }
5074 
5075 static char *
5076 find_star(char *s)
5077 {
5078 	for (; *s; ++s) {
5079 		switch (*s) {
5080 		case '*':
5081 			return (s);
5082 		case '\\':
5083 			++s;
5084 			if (hexchar2int(s[0]) >= 0 && hexchar2int(s[1]) >= 0)
5085 				++s;
5086 		default:
5087 			break;
5088 		}
5089 	}
5090 	return (NULL);
5091 }
5092 
5093 static int
5094 adj_simple_filter(char *str)
5095 {
5096 	char		*s, *s2, *s3, filterop;
5097 	char		*value;
5098 	int		ftype = 0;
5099 	int		rc;
5100 
5101 	rc = -1;	/* pessimistic */
5102 
5103 	if ((str = strdup(str)) == NULL) {
5104 		return (rc);
5105 	}
5106 
5107 	if ((s = strchr(str, '=')) == NULL) {
5108 		goto free_and_return;
5109 	}
5110 	value = s + 1;
5111 	*s-- = '\0';
5112 	filterop = *s;
5113 	if (filterop == '<' || filterop == '>' || filterop == '~' ||
5114 	    filterop == ':') {
5115 		*s = '\0';
5116 	}
5117 
5118 	if (! is_valid_attr(str)) {
5119 		goto free_and_return;
5120 	}
5121 
5122 	switch (filterop) {
5123 	case '<': /* LDAP_FILTER_LE */
5124 	case '>': /* LDAP_FILTER_GE */
5125 	case '~': /* LDAP_FILTER_APPROX */
5126 		break;
5127 	case ':':	/* extended filter - v3 only */
5128 		/*
5129 		 * extended filter looks like this:
5130 		 *
5131 		 *	[type][':dn'][':'oid]':='value
5132 		 *
5133 		 * where one of type or :oid is required.
5134 		 *
5135 		 */
5136 		s2 = s3 = NULL;
5137 		if ((s2 = strrchr(str, ':')) == NULL) {
5138 			goto free_and_return;
5139 		}
5140 		if (strcasecmp(s2, ":dn") == 0) {
5141 			*s2 = '\0';
5142 		} else {
5143 			*s2 = '\0';
5144 			if ((s3 = strrchr(str, ':')) != NULL) {
5145 				if (strcasecmp(s3, ":dn") != 0) {
5146 					goto free_and_return;
5147 				}
5148 				*s3 = '\0';
5149 			}
5150 		}
5151 		if (unescape_filterval(value) < 0) {
5152 			goto free_and_return;
5153 		}
5154 		rc = 0;
5155 		goto free_and_return;
5156 		/* break; */
5157 	default:
5158 		if (find_star(value) == NULL) {
5159 			ftype = 0; /* LDAP_FILTER_EQUALITY */
5160 		} else if (strcmp(value, "*") == 0) {
5161 			ftype = 1; /* LDAP_FILTER_PRESENT */
5162 		} else {
5163 			rc = adj_substring_filter(value);
5164 			goto free_and_return;
5165 		}
5166 		break;
5167 	}
5168 
5169 	if (ftype != 0) {	/* == LDAP_FILTER_PRESENT */
5170 		rc = 0;
5171 	} else if (unescape_filterval(value) >= 0) {
5172 		rc = 0;
5173 	}
5174 	if (rc != -1) {
5175 		rc = 0;
5176 	}
5177 
5178 free_and_return:
5179 	free(str);
5180 	return (rc);
5181 }
5182 
5183 
5184 /*
5185  * Check in place both LDAPv2 (RFC-1960) and LDAPv3 (hexadecimal) escape
5186  * sequences within the null-terminated string 'val'.
5187  *
5188  * If 'val' contains invalid escape sequences we return -1.
5189  * Otherwise return 1
5190  */
5191 static int
5192 unescape_filterval(char *val)
5193 {
5194 	int	escape, firstdigit;
5195 	char	*s;
5196 
5197 	firstdigit = 0;
5198 	escape = 0;
5199 	for (s = val; *s; s++) {
5200 		if (escape) {
5201 			/*
5202 			 * first try LDAPv3 escape (hexadecimal) sequence
5203 			 */
5204 			if (hexchar2int(*s) < 0) {
5205 				if (firstdigit) {
5206 					/*
5207 					 * LDAPv2 (RFC1960) escape sequence
5208 					 */
5209 					escape = 0;
5210 				} else {
5211 					return (-1);
5212 				}
5213 			}
5214 			if (firstdigit) {
5215 				firstdigit = 0;
5216 			} else {
5217 				escape = 0;
5218 			}
5219 
5220 		} else if (*s != '\\') {
5221 			escape = 0;
5222 
5223 		} else {
5224 			escape = 1;
5225 			firstdigit = 1;
5226 		}
5227 	}
5228 
5229 	return (1);
5230 }
5231 
5232 
5233 /*
5234  * convert character 'c' that represents a hexadecimal digit to an integer.
5235  * if 'c' is not a hexidecimal digit [0-9A-Fa-f], -1 is returned.
5236  * otherwise the converted value is returned.
5237  */
5238 static int
5239 hexchar2int(char c)
5240 {
5241 	if (c >= '0' && c <= '9') {
5242 		return (c - '0');
5243 	}
5244 	if (c >= 'A' && c <= 'F') {
5245 		return (c - 'A' + 10);
5246 	}
5247 	if (c >= 'a' && c <= 'f') {
5248 		return (c - 'a' + 10);
5249 	}
5250 	return (-1);
5251 }
5252 
5253 static int
5254 adj_substring_filter(char *val)
5255 {
5256 	char		*nextstar;
5257 
5258 	for (; val != NULL; val = nextstar) {
5259 		if ((nextstar = find_star(val)) != NULL) {
5260 			*nextstar++ = '\0';
5261 		}
5262 
5263 		if (*val != '\0') {
5264 			if (unescape_filterval(val) < 0) {
5265 				return (-1);
5266 			}
5267 		}
5268 	}
5269 
5270 	return (0);
5271 }
5272 
5273 /* ***** End of modified libldap.so.5 filter parser ***** */
5274 
5275 
5276 /*
5277  * Walk filter, remove redundant parentheses in-line
5278  * verify that the filter is reasonable
5279  */
5280 static int
5281 validate_filter(ns_ldap_cookie_t *cookie)
5282 {
5283 	char			*filter = cookie->filter;
5284 	int			rc;
5285 
5286 	/* Parse filter looking for illegal values */
5287 
5288 	rc = adj_filter(filter);
5289 	if (rc != 0) {
5290 		return (NS_LDAP_OP_FAILED);
5291 	}
5292 
5293 	/* end of filter checking */
5294 
5295 	return (NS_LDAP_SUCCESS);
5296 }
5297 
5298 /*
5299  * Set the account management request control that needs to be sent to server.
5300  * This control is required to get the account management information of
5301  * a user to do local account checking.
5302  */
5303 static int
5304 setup_acctmgmt_params(ns_ldap_cookie_t *cookie)
5305 {
5306 	LDAPControl	*req = NULL, **requestctrls;
5307 
5308 	req = (LDAPControl *)malloc(sizeof (LDAPControl));
5309 
5310 	if (req == NULL)
5311 		return (NS_LDAP_MEMORY);
5312 
5313 	/* fill in the fields of this new control */
5314 	req->ldctl_iscritical = 1;
5315 	req->ldctl_oid = strdup(NS_LDAP_ACCOUNT_USABLE_CONTROL);
5316 	if (req->ldctl_oid == NULL) {
5317 		free(req);
5318 		return (NS_LDAP_MEMORY);
5319 	}
5320 	req->ldctl_value.bv_len = 0;
5321 	req->ldctl_value.bv_val = NULL;
5322 
5323 	requestctrls = (LDAPControl **)calloc(2, sizeof (LDAPControl *));
5324 	if (requestctrls == NULL) {
5325 		ldap_control_free(req);
5326 		return (NS_LDAP_MEMORY);
5327 	}
5328 
5329 	requestctrls[0] = req;
5330 
5331 	cookie->p_serverctrls = requestctrls;
5332 
5333 	return (NS_LDAP_SUCCESS);
5334 }
5335 
5336 /*
5337  * int get_new_acct_more_info(BerElement *ber,
5338  *     AcctUsableResponse_t *acctResp)
5339  *
5340  * Decode the more_info data from an Account Management control response,
5341  * when the account is not usable and when code style is from recent LDAP
5342  * servers (see below comments for parse_acct_cont_resp_msg() to get more
5343  * details on coding styles and ASN1 description).
5344  *
5345  * Expected BER encoding: {tbtbtbtiti}
5346  *      +t: tag is 0
5347  *	+b: TRUE if inactive due to account inactivation
5348  *      +t: tag is 1
5349  * 	+b: TRUE if password has been reset
5350  *      +t: tag is 2
5351  * 	+b: TRUE if password is expired
5352  *	+t: tag is 3
5353  *	+i: contains num of remaining grace, 0 means no grace
5354  *	+t: tag is 4
5355  *	+i: contains num of seconds before auto-unlock. -1 means acct is locked
5356  *		forever (i.e. until reset)
5357  *
5358  * Asumptions:
5359  * - ber is not null
5360  * - acctResp is not null and is initialized with default values for the
5361  *   fields in its AcctUsableResp.more_info structure
5362  * - the ber stream is received in the correct order, per the ASN1 description.
5363  *   We do not check this order and make the asumption that it is correct.
5364  *   Note that the ber stream may not (and will not in most cases) contain
5365  *   all fields.
5366  */
5367 static int
5368 get_new_acct_more_info(BerElement *ber, AcctUsableResponse_t *acctResp)
5369 {
5370 	int		rc = NS_LDAP_SUCCESS;
5371 	char		errstr[MAXERROR];
5372 	ber_tag_t	rTag = LBER_DEFAULT;
5373 	ber_len_t	rLen = 0;
5374 	ber_int_t	rValue;
5375 	char		*last;
5376 	int		berRC = 0;
5377 
5378 	/*
5379 	 * Look at what more_info BER element is/are left to be decoded.
5380 	 * look at each of them 1 by 1, without checking on their order
5381 	 * and possible multi values.
5382 	 */
5383 	for (rTag = ber_first_element(ber, &rLen, &last);
5384 	    rTag != LBER_END_OF_SEQORSET;
5385 	    rTag = ber_next_element(ber, &rLen, last)) {
5386 
5387 		berRC = 0;
5388 		switch (rTag) {
5389 		case 0 | LBER_CLASS_CONTEXT | LBER_PRIMITIVE:
5390 			/* inactive */
5391 			berRC = ber_scanf(ber, "b", &rValue);
5392 			if (berRC != LBER_ERROR) {
5393 				(acctResp->AcctUsableResp).more_info.
5394 				    inactive = (rValue != 0) ? 1 : 0;
5395 			}
5396 			break;
5397 
5398 		case 1 | LBER_CLASS_CONTEXT | LBER_PRIMITIVE:
5399 			/* reset */
5400 			berRC = ber_scanf(ber, "b", &rValue);
5401 			if (berRC != LBER_ERROR) {
5402 				(acctResp->AcctUsableResp).more_info.reset
5403 				    = (rValue != 0) ? 1 : 0;
5404 			}
5405 			break;
5406 
5407 		case 2 | LBER_CLASS_CONTEXT | LBER_PRIMITIVE:
5408 			/* expired */
5409 			berRC = ber_scanf(ber, "b", &rValue);
5410 			if (berRC != LBER_ERROR) {
5411 				(acctResp->AcctUsableResp).more_info.expired
5412 				    = (rValue != 0) ? 1 : 0;
5413 			}
5414 			break;
5415 
5416 		case 3 | LBER_CLASS_CONTEXT | LBER_PRIMITIVE:
5417 			/* remaining grace */
5418 			berRC = ber_scanf(ber, "i", &rValue);
5419 			if (berRC != LBER_ERROR) {
5420 				(acctResp->AcctUsableResp).more_info.rem_grace
5421 				    = rValue;
5422 			}
5423 			break;
5424 
5425 		case 4 | LBER_CLASS_CONTEXT | LBER_PRIMITIVE:
5426 			/* seconds before unlock */
5427 			berRC = ber_scanf(ber, "i", &rValue);
5428 			if (berRC != LBER_ERROR) {
5429 				(acctResp->AcctUsableResp).more_info.
5430 				    sec_b4_unlock = rValue;
5431 			}
5432 			break;
5433 
5434 		default :
5435 			(void) sprintf(errstr,
5436 			    gettext("invalid reason tag 0x%x"), rTag);
5437 			syslog(LOG_DEBUG, "libsldap: %s", errstr);
5438 			rc = NS_LDAP_INTERNAL;
5439 			break;
5440 		}
5441 		if (berRC == LBER_ERROR) {
5442 			(void) sprintf(errstr,
5443 			    gettext("error 0x%x decoding value for "
5444 			    "tag 0x%x"), berRC, rTag);
5445 			syslog(LOG_DEBUG, "libsldap: %s", errstr);
5446 			rc = NS_LDAP_INTERNAL;
5447 		}
5448 		if (rc != NS_LDAP_SUCCESS) {
5449 			/* exit the for loop */
5450 			break;
5451 		}
5452 	}
5453 
5454 	return (rc);
5455 }
5456 
5457 /*
5458  * int get_old_acct_opt_more_info(BerElement *ber,
5459  *     AcctUsableResponse_t *acctResp)
5460  *
5461  * Decode the optional more_info data from an Account Management control
5462  * response, when the account is not usable and when code style is from LDAP
5463  * server 5.2p4 (see below comments for parse_acct_cont_resp_msg() to get more
5464  * details on coding styles and ASN1 description).
5465  *
5466  * Expected BER encoding: titi}
5467  *	+t: tag is 2
5468  *	+i: contains num of remaining grace, 0 means no grace
5469  *	+t: tag is 3
5470  *	+i: contains num of seconds before auto-unlock. -1 means acct is locked
5471  *		forever (i.e. until reset)
5472  *
5473  * Asumptions:
5474  * - ber is a valid BER element
5475  * - acctResp is initialized for the fields in its AcctUsableResp.more_info
5476  *   structure
5477  */
5478 static int
5479 get_old_acct_opt_more_info(ber_tag_t tag, BerElement *ber,
5480     AcctUsableResponse_t *acctResp)
5481 {
5482 	int		rc = NS_LDAP_SUCCESS;
5483 	char		errstr[MAXERROR];
5484 	ber_len_t	len;
5485 	int		rem_grace, sec_b4_unlock;
5486 
5487 	switch (tag) {
5488 	case 2:
5489 		/* decode and maybe 3 is following */
5490 		if ((tag = ber_scanf(ber, "i", &rem_grace)) == LBER_ERROR) {
5491 			(void) sprintf(errstr, gettext("Can not get "
5492 			    "rem_grace"));
5493 			syslog(LOG_DEBUG, "libsldap: %s", errstr);
5494 			rc = NS_LDAP_INTERNAL;
5495 			break;
5496 		}
5497 		(acctResp->AcctUsableResp).more_info.rem_grace = rem_grace;
5498 
5499 		if ((tag = ber_peek_tag(ber, &len)) == LBER_ERROR) {
5500 			/* this is a success case, break to exit */
5501 			(void) sprintf(errstr, gettext("No more "
5502 			    "optional data"));
5503 			syslog(LOG_DEBUG, "libsldap: %s", errstr);
5504 			break;
5505 		}
5506 
5507 		if (tag == 3) {
5508 			if (ber_scanf(ber, "i", &sec_b4_unlock) == LBER_ERROR) {
5509 				(void) sprintf(errstr,
5510 				    gettext("Can not get sec_b4_unlock "
5511 				    "- 1st case"));
5512 				syslog(LOG_DEBUG, "libsldap: %s", errstr);
5513 				rc = NS_LDAP_INTERNAL;
5514 				break;
5515 			}
5516 			(acctResp->AcctUsableResp).more_info.sec_b4_unlock =
5517 			    sec_b4_unlock;
5518 		} else { /* unknown tag */
5519 			(void) sprintf(errstr, gettext("Unknown tag "
5520 			    "- 1st case"));
5521 			syslog(LOG_DEBUG, "libsldap: %s", errstr);
5522 			rc = NS_LDAP_INTERNAL;
5523 			break;
5524 		}
5525 		break;
5526 
5527 	case 3:
5528 		if (ber_scanf(ber, "i", &sec_b4_unlock) == LBER_ERROR) {
5529 			(void) sprintf(errstr, gettext("Can not get "
5530 			    "sec_b4_unlock - 2nd case"));
5531 			syslog(LOG_DEBUG, "libsldap: %s", errstr);
5532 			rc = NS_LDAP_INTERNAL;
5533 			break;
5534 		}
5535 		(acctResp->AcctUsableResp).more_info.sec_b4_unlock =
5536 		    sec_b4_unlock;
5537 		break;
5538 
5539 	default: /* unknown tag */
5540 		(void) sprintf(errstr, gettext("Unknown tag - 2nd case"));
5541 		syslog(LOG_DEBUG, "libsldap: %s", errstr);
5542 		rc = NS_LDAP_INTERNAL;
5543 		break;
5544 	}
5545 
5546 	return (rc);
5547 }
5548 
5549 /*
5550  * **** This function needs to be moved to libldap library ****
5551  * parse_acct_cont_resp_msg() parses the message received by server according to
5552  * following format (ASN1 notation):
5553  *
5554  *	ACCOUNT_USABLE_RESPONSE::= CHOICE {
5555  *		is_available		[0] INTEGER,
5556  *				** seconds before expiration **
5557  *		is_not_available	[1] more_info
5558  *	}
5559  *	more_info::= SEQUENCE {
5560  *		inactive		[0] BOOLEAN DEFAULT FALSE,
5561  *		reset			[1] BOOLEAN DEFAULT FALSE,
5562  *		expired			[2] BOOLEAN DEFAULT FALSE,
5563  *		remaining_grace		[3] INTEGER OPTIONAL,
5564  *		seconds_before_unlock	[4] INTEGER OPTIONAL
5565  *	}
5566  */
5567 /*
5568  * #define used to make the difference between coding style as done
5569  * by LDAP server 5.2p4 and newer LDAP servers. There are 4 values:
5570  * - DS52p4_USABLE: 5.2p4 coding style, account is usable
5571  * - DS52p4_NOT_USABLE: 5.2p4 coding style, account is not usable
5572  * - NEW_USABLE: newer LDAP servers coding style, account is usable
5573  * - NEW_NOT_USABLE: newer LDAP servers coding style, account is not usable
5574  *
5575  * An account would be considered not usable if for instance:
5576  * - it's been made inactive in the LDAP server
5577  * - or its password was reset in the LDAP server database
5578  * - or its password expired
5579  * - or the account has been locked, possibly forever
5580  */
5581 #define	DS52p4_USABLE		0x00
5582 #define	DS52p4_NOT_USABLE	0x01
5583 #define	NEW_USABLE		0x00 | LBER_CLASS_CONTEXT | LBER_PRIMITIVE
5584 #define	NEW_NOT_USABLE		0x01 | LBER_CLASS_CONTEXT | LBER_CONSTRUCTED
5585 static int
5586 parse_acct_cont_resp_msg(LDAPControl **ectrls, AcctUsableResponse_t *acctResp)
5587 {
5588 	int		rc = NS_LDAP_SUCCESS;
5589 	BerElement	*ber;
5590 	ber_tag_t 	tag;
5591 	ber_len_t	len;
5592 	int		i;
5593 	char		errstr[MAXERROR];
5594 	/* used for any coding style when account is usable */
5595 	int		seconds_before_expiry;
5596 	/* used for 5.2p4 coding style when account is not usable */
5597 	int		inactive, reset, expired;
5598 
5599 	if (ectrls == NULL) {
5600 		(void) sprintf(errstr, gettext("Invalid ectrls parameter"));
5601 		syslog(LOG_DEBUG, "libsldap: %s", errstr);
5602 		return (NS_LDAP_INVALID_PARAM);
5603 	}
5604 
5605 	for (i = 0; ectrls[i] != NULL; i++) {
5606 		if (strcmp(ectrls[i]->ldctl_oid, NS_LDAP_ACCOUNT_USABLE_CONTROL)
5607 		    == 0) {
5608 			break;
5609 		}
5610 	}
5611 
5612 	if (ectrls[i] == NULL) {
5613 		/* Ldap control is not found */
5614 		(void) sprintf(errstr, gettext("Account Usable Control "
5615 		    "not found"));
5616 		syslog(LOG_DEBUG, "libsldap: %s", errstr);
5617 		return (NS_LDAP_NOTFOUND);
5618 	}
5619 
5620 	/* Allocate a BER element from the control value and parse it. */
5621 	if ((ber = ber_init(&ectrls[i]->ldctl_value)) == NULL)
5622 		return (NS_LDAP_MEMORY);
5623 
5624 	if ((tag = ber_peek_tag(ber, &len)) == LBER_ERROR) {
5625 		/* Ldap decoding error */
5626 		(void) sprintf(errstr, gettext("Error decoding 1st tag"));
5627 		syslog(LOG_DEBUG, "libsldap: %s", errstr);
5628 		ber_free(ber, 1);
5629 		return (NS_LDAP_INTERNAL);
5630 	}
5631 
5632 	switch (tag) {
5633 	case DS52p4_USABLE:
5634 	case NEW_USABLE:
5635 		acctResp->choice = 0;
5636 		if (ber_scanf(ber, "i", &seconds_before_expiry)
5637 		    == LBER_ERROR) {
5638 			/* Ldap decoding error */
5639 			(void) sprintf(errstr, gettext("Can not get "
5640 			    "seconds_before_expiry"));
5641 			syslog(LOG_DEBUG, "libsldap: %s", errstr);
5642 			rc = NS_LDAP_INTERNAL;
5643 			break;
5644 		}
5645 		/* ber_scanf() succeeded */
5646 		(acctResp->AcctUsableResp).seconds_before_expiry =
5647 		    seconds_before_expiry;
5648 		break;
5649 
5650 	case DS52p4_NOT_USABLE:
5651 		acctResp->choice = 1;
5652 		if (ber_scanf(ber, "{bbb", &inactive, &reset, &expired)
5653 		    == LBER_ERROR) {
5654 			/* Ldap decoding error */
5655 			(void) sprintf(errstr, gettext("Can not get "
5656 			    "inactive/reset/expired"));
5657 			syslog(LOG_DEBUG, "libsldap: %s", errstr);
5658 			rc = NS_LDAP_INTERNAL;
5659 			break;
5660 		}
5661 		/* ber_scanf() succeeded */
5662 		(acctResp->AcctUsableResp).more_info.inactive =
5663 		    ((inactive == 0) ? 0 : 1);
5664 		(acctResp->AcctUsableResp).more_info.reset =
5665 		    ((reset == 0) ? 0 : 1);
5666 		(acctResp->AcctUsableResp).more_info.expired =
5667 		    ((expired == 0) ? 0 : 1);
5668 		(acctResp->AcctUsableResp).more_info.rem_grace = 0;
5669 		(acctResp->AcctUsableResp).more_info.sec_b4_unlock = 0;
5670 
5671 		if ((tag = ber_peek_tag(ber, &len)) == LBER_ERROR) {
5672 			/* this is a success case, break to exit */
5673 			(void) sprintf(errstr, gettext("No optional data"));
5674 			syslog(LOG_DEBUG, "libsldap: %s", errstr);
5675 			break;
5676 		}
5677 
5678 		/*
5679 		 * Look at what optional more_info BER element is/are
5680 		 * left to be decoded.
5681 		 */
5682 		rc = get_old_acct_opt_more_info(tag, ber, acctResp);
5683 		break;
5684 
5685 	case NEW_NOT_USABLE:
5686 		acctResp->choice = 1;
5687 		/*
5688 		 * Recent LDAP servers won't code more_info data for default
5689 		 * values (see above comments on ASN1 description for what
5690 		 * fields have default values & what fields are optional).
5691 		 */
5692 		(acctResp->AcctUsableResp).more_info.inactive = 0;
5693 		(acctResp->AcctUsableResp).more_info.reset = 0;
5694 		(acctResp->AcctUsableResp).more_info.expired = 0;
5695 		(acctResp->AcctUsableResp).more_info.rem_grace = 0;
5696 		(acctResp->AcctUsableResp).more_info.sec_b4_unlock = 0;
5697 
5698 		if (len == 0) {
5699 			/*
5700 			 * Nothing else to decode; this is valid and we
5701 			 * use default values set above.
5702 			 */
5703 			(void) sprintf(errstr, gettext("more_info is "
5704 			    "empty, using default values"));
5705 			syslog(LOG_DEBUG, "libsldap: %s", errstr);
5706 			break;
5707 		}
5708 
5709 		/*
5710 		 * Look at what more_info BER element is/are left to
5711 		 * be decoded.
5712 		 */
5713 		rc = get_new_acct_more_info(ber, acctResp);
5714 		break;
5715 
5716 	default:
5717 		(void) sprintf(errstr, gettext("unknwon coding style "
5718 		    "(tag: 0x%x)"), tag);
5719 		syslog(LOG_DEBUG, "libsldap: %s", errstr);
5720 		rc = NS_LDAP_INTERNAL;
5721 		break;
5722 	}
5723 
5724 	ber_free(ber, 1);
5725 	return (rc);
5726 }
5727 
5728 /*
5729  * internal function for __ns_ldap_getAcctMgmt()
5730  */
5731 static int
5732 getAcctMgmt(const char *user, AcctUsableResponse_t *acctResp,
5733 	ns_conn_user_t *conn_user)
5734 {
5735 	int		scope, rc;
5736 	char		ldapfilter[1024];
5737 	ns_ldap_cookie_t	*cookie;
5738 	ns_ldap_search_desc_t	**sdlist = NULL;
5739 	ns_ldap_search_desc_t	*dptr;
5740 	ns_ldap_error_t		*error = NULL;
5741 	char			**dns = NULL;
5742 	char		service[] = "shadow";
5743 
5744 	if (user == NULL || acctResp == NULL)
5745 		return (NS_LDAP_INVALID_PARAM);
5746 
5747 	/* Initialize State machine cookie */
5748 	cookie = init_search_state_machine();
5749 	if (cookie == NULL)
5750 		return (NS_LDAP_MEMORY);
5751 	cookie->conn_user = conn_user;
5752 
5753 	/* see if need to follow referrals */
5754 	rc = __s_api_toFollowReferrals(0,
5755 	    &cookie->followRef, &error);
5756 	if (rc != NS_LDAP_SUCCESS) {
5757 		(void) __ns_ldap_freeError(&error);
5758 		goto out;
5759 	}
5760 
5761 	/* get the service descriptor - or create a default one */
5762 	rc = __s_api_get_SSD_from_SSDtoUse_service(service,
5763 	    &sdlist, &error);
5764 	if (rc != NS_LDAP_SUCCESS) {
5765 		(void) __ns_ldap_freeError(&error);
5766 		goto out;
5767 	}
5768 
5769 	if (sdlist == NULL) {
5770 		/* Create default service Desc */
5771 		sdlist = (ns_ldap_search_desc_t **)calloc(2,
5772 		    sizeof (ns_ldap_search_desc_t *));
5773 		if (sdlist == NULL) {
5774 			rc = NS_LDAP_MEMORY;
5775 			goto out;
5776 		}
5777 		dptr = (ns_ldap_search_desc_t *)
5778 		    calloc(1, sizeof (ns_ldap_search_desc_t));
5779 		if (dptr == NULL) {
5780 			free(sdlist);
5781 			rc = NS_LDAP_MEMORY;
5782 			goto out;
5783 		}
5784 		sdlist[0] = dptr;
5785 
5786 		/* default base */
5787 		rc = __s_api_getDNs(&dns, service, &cookie->errorp);
5788 		if (rc != NS_LDAP_SUCCESS) {
5789 			if (dns) {
5790 				__s_api_free2dArray(dns);
5791 				dns = NULL;
5792 			}
5793 			(void) __ns_ldap_freeError(&(cookie->errorp));
5794 			cookie->errorp = NULL;
5795 			goto out;
5796 		}
5797 		dptr->basedn = strdup(dns[0]);
5798 		if (dptr->basedn == NULL) {
5799 			free(sdlist);
5800 			free(dptr);
5801 			if (dns) {
5802 				__s_api_free2dArray(dns);
5803 				dns = NULL;
5804 			}
5805 			rc = NS_LDAP_MEMORY;
5806 			goto out;
5807 		}
5808 		__s_api_free2dArray(dns);
5809 		dns = NULL;
5810 
5811 		/* default scope */
5812 		scope = 0;
5813 		rc = __s_api_getSearchScope(&scope, &cookie->errorp);
5814 		dptr->scope = scope;
5815 	}
5816 
5817 	cookie->sdlist = sdlist;
5818 
5819 	cookie->service = strdup(service);
5820 	if (cookie->service == NULL) {
5821 		rc = NS_LDAP_MEMORY;
5822 		goto out;
5823 	}
5824 
5825 	/* search for entries for this particular uid */
5826 	(void) snprintf(ldapfilter, sizeof (ldapfilter), "(uid=%s)", user);
5827 	cookie->i_filter = strdup(ldapfilter);
5828 	if (cookie->i_filter == NULL) {
5829 		rc = NS_LDAP_MEMORY;
5830 		goto out;
5831 	}
5832 
5833 	/* create the control request */
5834 	if ((rc = setup_acctmgmt_params(cookie)) != NS_LDAP_SUCCESS)
5835 		goto out;
5836 
5837 	/* Process search */
5838 	rc = search_state_machine(cookie, GET_ACCT_MGMT_INFO, 0);
5839 
5840 	/* Copy results back to user */
5841 	rc = cookie->err_rc;
5842 	if (rc != NS_LDAP_SUCCESS)
5843 			(void) __ns_ldap_freeError(&(cookie->errorp));
5844 
5845 	if (cookie->result == NULL)
5846 			goto out;
5847 
5848 	if ((rc = parse_acct_cont_resp_msg(cookie->resultctrl, acctResp))
5849 	    != NS_LDAP_SUCCESS)
5850 		goto out;
5851 
5852 	rc = NS_LDAP_SUCCESS;
5853 
5854 out:
5855 	delete_search_cookie(cookie);
5856 
5857 	return (rc);
5858 }
5859 
5860 /*
5861  * __ns_ldap_getAcctMgmt() is called from pam account management stack
5862  * for retrieving accounting information of users with no user password -
5863  * eg. rlogin, rsh, etc. This function uses the account management control
5864  * request to do a search on the server for the user in question. The
5865  * response control returned from the server is got from the cookie.
5866  * Input params: username of whose account mgmt information is to be got
5867  *		 pointer to hold the parsed account management information
5868  * Return values: NS_LDAP_SUCCESS on success or appropriate error
5869  *		code on failure
5870  */
5871 int
5872 __ns_ldap_getAcctMgmt(const char *user, AcctUsableResponse_t *acctResp)
5873 {
5874 	ns_conn_user_t	*cu = NULL;
5875 	int		try_cnt = 0;
5876 	int		rc = NS_LDAP_SUCCESS;
5877 	ns_ldap_error_t	*error = NULL;
5878 
5879 	for (;;) {
5880 		if (__s_api_setup_retry_search(&cu, NS_CONN_USER_SEARCH,
5881 		    &try_cnt, &rc, &error) == 0)
5882 			break;
5883 		rc = getAcctMgmt(user, acctResp, cu);
5884 	}
5885 	return (rc);
5886 }
5887