xref: /titanic_51/usr/src/lib/libsldap/common/ns_reads.c (revision 5c0b7edee9bd9fad49038456b16972ff28fa4187)
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 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 #include <stdio.h>
29 #include <sys/types.h>
30 #include <stdlib.h>
31 #include <libintl.h>
32 #include <ctype.h>
33 #include <syslog.h>
34 #include <sys/stat.h>
35 #include <fcntl.h>
36 #include <unistd.h>
37 #include <string.h>
38 #include <strings.h>
39 
40 #include "ns_sldap.h"
41 #include "ns_internal.h"
42 #include "ns_cache_door.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 	if ((mapped_rdns = (char **)calloc(nRdn, sizeof (char *))) == NULL) {
234 		ldap_value_free(rdns);
235 		return (NULL);
236 	}
237 
238 	rdn_mapped = 0;
239 	/* Break down RDNs in a DN */
240 	for (i = 0; i < nRdn; i++) {
241 		if ((new_rdn = _cvtRDN(service, rdns[i])) != NULL) {
242 			mapped_rdns[i] = new_rdn;
243 			rdn_mapped = 1;
244 		}
245 	}
246 	if (rdn_mapped == 0) {
247 		/*
248 		 * No RDN contains any attribute mapping.
249 		 * Don't bother to reconstruct DN from RDN. Copy DN directly.
250 		 */
251 		new_dn = strdup(dn);
252 		goto cleanup;
253 	}
254 	/*
255 	 * Reconstruct dn from RDNs.
256 	 * Calculate the length first.
257 	 */
258 	for (i = 0; i < nRdn; i++) {
259 		if (mapped_rdns[i])
260 			len += strlen(mapped_rdns[i]);
261 		else
262 			len += strlen(rdns[i]);
263 
264 		/* add 1 for ',' */
265 		len ++;
266 	}
267 	if ((new_dn = (char *)calloc(1, ++len)) == NULL)
268 		goto cleanup;
269 	for (i = 0; i < nRdn; i++) {
270 		if (i > 0)
271 			/* Add seperator */
272 			(void) strlcat(new_dn, ",", len);
273 
274 		if (mapped_rdns[i])
275 			(void) strlcat(new_dn, mapped_rdns[i], len);
276 		else
277 			(void) strlcat(new_dn, rdns[i], len);
278 
279 	}
280 
281 cleanup:
282 	ldap_value_free(rdns);
283 	if (mapped_rdns) {
284 		if (rdn_mapped) {
285 			for (i = 0; i < nRdn; i++) {
286 				if (mapped_rdns[i])
287 					free(mapped_rdns[i]);
288 			}
289 		}
290 		free(mapped_rdns);
291 	}
292 
293 	return (new_dn);
294 }
295 /*
296  * Convert a single ldap entry from a LDAPMessage
297  * into an ns_ldap_entry structure.
298  * Schema map the entry if specified in flags
299  */
300 
301 static int
302 __s_api_cvtEntry(LDAP	*ld,
303 	const char	*service,
304 	LDAPMessage	*e,
305 	int		flags,
306 	ns_ldap_entry_t	**ret,
307 	ns_ldap_error_t	**error)
308 {
309 
310 	ns_ldap_entry_t	*ep = NULL;
311 	ns_ldap_attr_t	**ap = NULL;
312 	BerElement	*ber;
313 	char		*attr = NULL;
314 	char		**vals = NULL;
315 	char		**mapping;
316 	char		*dn;
317 	int		nAttrs = 0;
318 	int		i, j, k = 0;
319 	char		**gecos_mapping = NULL;
320 	int		gecos_val_index[3] = { -1, -1, -1};
321 	char		errstr[MAXERROR];
322 	int		schema_mapping_existed = FALSE;
323 	int		gecos_mapping_existed = FALSE;
324 	int		gecos_attr_matched;
325 	int		auto_service = FALSE;
326 	int		rc = NS_LDAP_SUCCESS;
327 
328 	if (e == NULL || ret == NULL || error == NULL)
329 		return (NS_LDAP_INVALID_PARAM);
330 
331 	*error = NULL;
332 
333 	ep = (ns_ldap_entry_t *)calloc(1, sizeof (ns_ldap_entry_t));
334 	if (ep == NULL)
335 		return (NS_LDAP_MEMORY);
336 
337 	if (service != NULL &&
338 	    (strncasecmp(service, "auto_", 5) == 0 ||
339 	    strcasecmp(service, "automount") == 0))
340 		auto_service = TRUE;
341 	/*
342 	 * see if schema mapping existed for the given service
343 	 */
344 	mapping = __ns_ldap_getOrigAttribute(service,
345 	    NS_HASH_SCHEMA_MAPPING_EXISTED);
346 	if (mapping) {
347 		schema_mapping_existed = TRUE;
348 		__s_api_free2dArray(mapping);
349 		mapping = NULL;
350 	} else if (auto_service) {
351 		/*
352 		 * If service == auto_* and no
353 		 * schema mapping found
354 		 * then try automount
355 		 * There is certain case that schema mapping exist
356 		 * but __ns_ldap_getOrigAttribute(service,
357 		 *	NS_HASH_SCHEMA_MAPPING_EXISTED);
358 		 * returns NULL.
359 		 * e.g.
360 		 * NS_LDAP_ATTRIBUTEMAP = automount:automountMapName=AAA
361 		 * NS_LDAP_OBJECTCLASSMAP = automount:automountMap=MynisMap
362 		 * NS_LDAP_OBJECTCLASSMAP = automount:automount=MynisObject
363 		 *
364 		 * Make a check for schema_mapping_existed here
365 		 * so later on __s_api_convert_automountmapname won't be called
366 		 * unnecessarily. It is also used for attribute mapping
367 		 * and objectclass mapping.
368 		 */
369 		mapping = __ns_ldap_getOrigAttribute("automount",
370 		    NS_HASH_SCHEMA_MAPPING_EXISTED);
371 		if (mapping) {
372 			schema_mapping_existed = TRUE;
373 			__s_api_free2dArray(mapping);
374 			mapping = NULL;
375 		}
376 	}
377 
378 	nAttrs = 1;  /* start with 1 for the DN attr */
379 	for (attr = ldap_first_attribute(ld, e, &ber); attr != NULL;
380 	    attr = ldap_next_attribute(ld, e, ber)) {
381 		nAttrs++;
382 		ldap_memfree(attr);
383 		attr = NULL;
384 	}
385 	ber_free(ber, 0);
386 	ber = NULL;
387 
388 	ep->attr_count = nAttrs;
389 
390 	/*
391 	 * add 1 for "gecos" 1 to N attribute mapping,
392 	 * just in case it is needed.
393 	 * ep->attr_count will be updated later if that is true.
394 	 */
395 	ap = (ns_ldap_attr_t **)calloc(ep->attr_count + 1,
396 	    sizeof (ns_ldap_attr_t *));
397 	if (ap == NULL) {
398 		__ns_ldap_freeEntry(ep);
399 		ep = NULL;
400 		return (NS_LDAP_MEMORY);
401 	}
402 	ep->attr_pair = ap;
403 
404 	/* DN attribute */
405 	dn = ldap_get_dn(ld, e);
406 	ap[0] = (ns_ldap_attr_t *)calloc(1, sizeof (ns_ldap_attr_t));
407 	if (ap[0] == NULL) {
408 		ldap_memfree(dn);
409 		dn = NULL;
410 		__ns_ldap_freeEntry(ep);
411 		ep = NULL;
412 		return (NS_LDAP_MEMORY);
413 	}
414 
415 	if ((ap[0]->attrname = strdup("dn")) == NULL) {
416 		ldap_memfree(dn);
417 		dn = NULL;
418 		__ns_ldap_freeEntry(ep);
419 		ep = NULL;
420 		return (NS_LDAP_INVALID_PARAM);
421 	}
422 	ap[0]->value_count = 1;
423 	if ((ap[0]->attrvalue = (char **)
424 	    calloc(2, sizeof (char *))) == NULL) {
425 		ldap_memfree(dn);
426 		dn = NULL;
427 		__ns_ldap_freeEntry(ep);
428 		ep = NULL;
429 		return (NS_LDAP_MEMORY);
430 	}
431 
432 	if (schema_mapping_existed && ((flags & NS_LDAP_NOT_CVT_DN) == 0))
433 		ap[0]->attrvalue[0] = _cvtDN(service, dn);
434 	else
435 		ap[0]->attrvalue[0] = strdup(dn);
436 
437 	if (ap[0]->attrvalue[0] == NULL) {
438 		ldap_memfree(dn);
439 		dn = NULL;
440 		__ns_ldap_freeEntry(ep);
441 		ep = NULL;
442 		return (NS_LDAP_MEMORY);
443 	}
444 	ldap_memfree(dn);
445 	dn = NULL;
446 
447 	if ((flags & NS_LDAP_NOMAP) == 0 && auto_service &&
448 	    schema_mapping_existed) {
449 		rc = __s_api_convert_automountmapname(service,
450 		    &ap[0]->attrvalue[0],
451 		    error);
452 		if (rc != NS_LDAP_SUCCESS) {
453 			__ns_ldap_freeEntry(ep);
454 			ep = NULL;
455 			return (rc);
456 		}
457 	}
458 
459 	/* other attributes */
460 	for (attr = ldap_first_attribute(ld, e, &ber), j = 1;
461 	    attr != NULL && j != nAttrs;
462 	    attr = ldap_next_attribute(ld, e, ber), j++) {
463 		/* allocate new attr name */
464 
465 		if ((ap[j] = (ns_ldap_attr_t *)
466 		    calloc(1, sizeof (ns_ldap_attr_t))) == NULL) {
467 			ber_free(ber, 0);
468 			ber = NULL;
469 			__ns_ldap_freeEntry(ep);
470 			ep = NULL;
471 			if (gecos_mapping)
472 				__s_api_free2dArray(gecos_mapping);
473 			gecos_mapping = NULL;
474 			return (NS_LDAP_MEMORY);
475 		}
476 
477 		if ((flags & NS_LDAP_NOMAP) || schema_mapping_existed == FALSE)
478 			mapping = NULL;
479 		else
480 			mapping = __ns_ldap_getOrigAttribute(service, attr);
481 
482 		if (mapping == NULL && auto_service &&
483 		    schema_mapping_existed && (flags & NS_LDAP_NOMAP) == 0)
484 			/*
485 			 * if service == auto_* and no schema mapping found
486 			 * and schema_mapping_existed is TRUE and NS_LDAP_NOMAP
487 			 * is not set then try automount e.g.
488 			 * NS_LDAP_ATTRIBUTEMAP = automount:automountMapName=AAA
489 			 */
490 			mapping = __ns_ldap_getOrigAttribute("automount",
491 			    attr);
492 
493 		if (mapping == NULL) {
494 			if ((ap[j]->attrname = strdup(attr)) == NULL) {
495 				ber_free(ber, 0);
496 				ber = NULL;
497 				__ns_ldap_freeEntry(ep);
498 				ep = NULL;
499 				if (gecos_mapping)
500 					__s_api_free2dArray(gecos_mapping);
501 				gecos_mapping = NULL;
502 				return (NS_LDAP_MEMORY);
503 			}
504 		} else {
505 			/*
506 			 * for "gecos" 1 to N mapping,
507 			 * do not remove the mapped attribute,
508 			 * just create a new gecos attribute
509 			 * and append it to the end of the attribute list
510 			 */
511 			if (strcasecmp(mapping[0], "gecos") == 0) {
512 				ap[j]->attrname = strdup(attr);
513 				gecos_mapping_existed = TRUE;
514 			} else
515 				ap[j]->attrname = strdup(mapping[0]);
516 
517 			if (ap[j]->attrname == NULL) {
518 				ber_free(ber, 0);
519 				ber = NULL;
520 				__ns_ldap_freeEntry(ep);
521 				ep = NULL;
522 				if (gecos_mapping)
523 					__s_api_free2dArray(gecos_mapping);
524 				gecos_mapping = NULL;
525 				return (NS_LDAP_MEMORY);
526 			}
527 			/*
528 			 * 1 to N attribute mapping processing
529 			 * is only done for "gecos"
530 			 */
531 
532 			if (strcasecmp(mapping[0], "gecos") == 0) {
533 				/*
534 				 * get attribute mapping for "gecos",
535 				 * need to know the number and order of the
536 				 * mapped attributes
537 				 */
538 				if (gecos_mapping == NULL) {
539 					gecos_mapping =
540 					    __ns_ldap_getMappedAttributes(
541 					    service, mapping[0]);
542 					if (gecos_mapping == NULL ||
543 					    gecos_mapping[0] == NULL) {
544 						/*
545 						 * this should never happens,
546 						 * syslog the error
547 						 */
548 						(void) sprintf(errstr,
549 						    gettext(
550 						    "Attribute mapping "
551 						    "inconsistency "
552 						    "found for attributes "
553 						    "'%s' and '%s'."),
554 						    mapping[0], attr);
555 						syslog(LOG_ERR, "libsldap: %s",
556 						    errstr);
557 
558 						ber_free(ber, 0);
559 						ber = NULL;
560 						__ns_ldap_freeEntry(ep);
561 						ep = NULL;
562 						__s_api_free2dArray(mapping);
563 						mapping = NULL;
564 						if (gecos_mapping)
565 							__s_api_free2dArray(
566 							    gecos_mapping);
567 						gecos_mapping = NULL;
568 						return (NS_LDAP_INTERNAL);
569 					}
570 				}
571 
572 				/*
573 				 * is this attribute the 1st, 2nd, or
574 				 * 3rd attr in the mapping list?
575 				 */
576 				gecos_attr_matched = FALSE;
577 				for (i = 0; i < 3 && gecos_mapping[i]; i++) {
578 					if (gecos_mapping[i] &&
579 					    strcasecmp(gecos_mapping[i],
580 					    attr) == 0) {
581 						gecos_val_index[i] = j;
582 						gecos_attr_matched = TRUE;
583 						break;
584 					}
585 				}
586 				if (gecos_attr_matched == FALSE) {
587 					/*
588 					 * Not match found.
589 					 * This should never happens,
590 					 * syslog the error
591 					 */
592 					(void) sprintf(errstr,
593 					    gettext(
594 					    "Attribute mapping "
595 					    "inconsistency "
596 					    "found for attributes "
597 					    "'%s' and '%s'."),
598 					    mapping[0], attr);
599 					syslog(LOG_ERR, "libsldap: %s", errstr);
600 
601 					ber_free(ber, 0);
602 					ber = NULL;
603 					__ns_ldap_freeEntry(ep);
604 					ep = NULL;
605 					__s_api_free2dArray(mapping);
606 					mapping = NULL;
607 					__s_api_free2dArray(gecos_mapping);
608 					gecos_mapping = NULL;
609 					return (NS_LDAP_INTERNAL);
610 				}
611 			}
612 			__s_api_free2dArray(mapping);
613 			mapping = NULL;
614 		}
615 
616 		if ((vals = ldap_get_values(ld, e, attr)) != NULL) {
617 
618 			if ((ap[j]->value_count =
619 			    ldap_count_values(vals)) == 0) {
620 				ldap_value_free(vals);
621 				vals = NULL;
622 				continue;
623 			} else {
624 				ap[j]->attrvalue = (char **)
625 				    calloc(ap[j]->value_count+1,
626 				    sizeof (char *));
627 				if (ap[j]->attrvalue == NULL) {
628 					ber_free(ber, 0);
629 					ber = NULL;
630 					__ns_ldap_freeEntry(ep);
631 					ep = NULL;
632 					if (gecos_mapping)
633 						__s_api_free2dArray(
634 						    gecos_mapping);
635 					gecos_mapping = NULL;
636 					return (NS_LDAP_MEMORY);
637 				}
638 			}
639 
640 			/* map object classes if necessary */
641 			if ((flags & NS_LDAP_NOMAP) == 0 &&
642 			    schema_mapping_existed && ap[j]->attrname &&
643 			    strcasecmp(ap[j]->attrname, "objectclass") == 0) {
644 				for (k = 0; k < ap[j]->value_count; k++) {
645 					mapping =
646 					    __ns_ldap_getOrigObjectClass(
647 					    service, vals[k]);
648 
649 					if (mapping == NULL && auto_service)
650 						/*
651 						 * if service == auto_* and no
652 						 * schema mapping found
653 						 * then try automount
654 						 */
655 					mapping =
656 					    __ns_ldap_getOrigObjectClass(
657 					    "automount", vals[k]);
658 
659 					if (mapping == NULL) {
660 						ap[j]->attrvalue[k] =
661 						    strdup(vals[k]);
662 					} else {
663 						ap[j]->attrvalue[k] =
664 						    strdup(mapping[0]);
665 						__s_api_free2dArray(mapping);
666 						mapping = NULL;
667 					}
668 					if (ap[j]->attrvalue[k] == NULL) {
669 						ber_free(ber, 0);
670 						ber = NULL;
671 						__ns_ldap_freeEntry(ep);
672 						ep = NULL;
673 						if (gecos_mapping)
674 							__s_api_free2dArray(
675 							    gecos_mapping);
676 						gecos_mapping = NULL;
677 						return (NS_LDAP_MEMORY);
678 					}
679 				}
680 			} else {
681 				for (k = 0; k < ap[j]->value_count; k++) {
682 					if ((ap[j]->attrvalue[k] =
683 					    strdup(vals[k])) == NULL) {
684 						ber_free(ber, 0);
685 						ber = NULL;
686 						__ns_ldap_freeEntry(ep);
687 						ep = NULL;
688 						if (gecos_mapping)
689 							__s_api_free2dArray(
690 							    gecos_mapping);
691 						gecos_mapping = NULL;
692 						return (NS_LDAP_MEMORY);
693 					}
694 				}
695 			}
696 
697 			ap[j]->attrvalue[k] = NULL;
698 			ldap_value_free(vals);
699 			vals = NULL;
700 		}
701 
702 		ldap_memfree(attr);
703 		attr = NULL;
704 	}
705 
706 	ber_free(ber, 0);
707 	ber = NULL;
708 
709 	if (gecos_mapping) {
710 		__s_api_free2dArray(gecos_mapping);
711 		gecos_mapping = NULL;
712 	}
713 
714 	/* special processing for gecos 1 to up to 3 attribute mapping */
715 	if (schema_mapping_existed && gecos_mapping_existed) {
716 
717 		int	f = -1;
718 
719 		for (i = 0; i < 3; i++) {
720 			k = gecos_val_index[i];
721 
722 			/*
723 			 * f is the index of the first returned
724 			 * attribute which "gecos" attribute mapped to
725 			 */
726 			if (k != -1 && f == -1)
727 				f = k;
728 
729 			if (k != -1 && ap[k]->value_count > 0 &&
730 			    ap[k]->attrvalue[0] &&
731 			    strlen(ap[k]->attrvalue[0]) > 0) {
732 
733 				if (k == f) {
734 					/*
735 					 * Create and fill in the last reserved
736 					 * ap with the data from the "gecos"
737 					 * mapping attributes
738 					 */
739 					ap[nAttrs] = (ns_ldap_attr_t *)
740 					    calloc(1,
741 					    sizeof (ns_ldap_attr_t));
742 					if (ap[nAttrs] == NULL) {
743 						__ns_ldap_freeEntry(ep);
744 						ep = NULL;
745 						return (NS_LDAP_MEMORY);
746 					}
747 					ap[nAttrs]->attrvalue = (char **)calloc(
748 					    2, sizeof (char *));
749 					if (ap[nAttrs]->attrvalue == NULL) {
750 						__ns_ldap_freeEntry(ep);
751 						ep = NULL;
752 						return (NS_LDAP_MEMORY);
753 					}
754 					/* add 1 more for a possible "," */
755 					ap[nAttrs]->attrvalue[0] =
756 					    (char *)calloc(
757 					    strlen(ap[f]->attrvalue[0]) +
758 					    2, 1);
759 					if (ap[nAttrs]->attrvalue[0] == NULL) {
760 						__ns_ldap_freeEntry(ep);
761 						ep = NULL;
762 						return (NS_LDAP_MEMORY);
763 					}
764 					(void) strcpy(ap[nAttrs]->attrvalue[0],
765 					    ap[f]->attrvalue[0]);
766 
767 					ap[nAttrs]->attrname = strdup("gecos");
768 					if (ap[nAttrs]->attrname == NULL) {
769 						__ns_ldap_freeEntry(ep);
770 						ep = NULL;
771 						return (NS_LDAP_MEMORY);
772 					}
773 
774 					ap[nAttrs]->value_count = 1;
775 					ep->attr_count = nAttrs + 1;
776 
777 				} else {
778 					char	*tmp = NULL;
779 
780 					/*
781 					 * realloc to add "," and
782 					 * ap[k]->attrvalue[0]
783 					 */
784 					tmp = (char *)realloc(
785 					    ap[nAttrs]->attrvalue[0],
786 					    strlen(ap[nAttrs]->
787 					    attrvalue[0]) +
788 					    strlen(ap[k]->
789 					    attrvalue[0]) + 2);
790 					if (tmp == NULL) {
791 						__ns_ldap_freeEntry(ep);
792 						ep = NULL;
793 						return (NS_LDAP_MEMORY);
794 					}
795 					ap[nAttrs]->attrvalue[0] = tmp;
796 					(void) strcat(ap[nAttrs]->attrvalue[0],
797 					    ",");
798 					(void) strcat(ap[nAttrs]->attrvalue[0],
799 					    ap[k]->attrvalue[0]);
800 				}
801 			}
802 		}
803 	}
804 
805 	*ret = ep;
806 	return (NS_LDAP_SUCCESS);
807 }
808 
809 static int
810 __s_api_getEntry(ns_ldap_cookie_t *cookie)
811 {
812 	ns_ldap_entry_t	*curEntry = NULL;
813 	int		ret;
814 
815 #ifdef DEBUG
816 	(void) fprintf(stderr, "__s_api_getEntry START\n");
817 #endif
818 
819 	if (cookie->resultMsg == NULL) {
820 		return (NS_LDAP_INVALID_PARAM);
821 	}
822 	ret = __s_api_cvtEntry(cookie->conn->ld, cookie->service,
823 	    cookie->resultMsg, cookie->i_flags,
824 	    &curEntry, &cookie->errorp);
825 	if (ret != NS_LDAP_SUCCESS) {
826 		return (ret);
827 	}
828 
829 	if (cookie->result == NULL) {
830 		cookie->result = (ns_ldap_result_t *)
831 		    calloc(1, sizeof (ns_ldap_result_t));
832 		if (cookie->result == NULL) {
833 			__ns_ldap_freeEntry(curEntry);
834 			curEntry = NULL;
835 			return (NS_LDAP_MEMORY);
836 		}
837 		cookie->result->entry = curEntry;
838 		cookie->nextEntry = curEntry;
839 	} else {
840 		cookie->nextEntry->next = curEntry;
841 		cookie->nextEntry = curEntry;
842 	}
843 	cookie->result->entries_count++;
844 
845 	return (NS_LDAP_SUCCESS);
846 }
847 
848 static int
849 __s_api_get_cachemgr_data(const char *type,
850 		const char *from, char **to)
851 {
852 	union {
853 		ldap_data_t	s_d;
854 		char		s_b[DOORBUFFERSIZE];
855 	} space;
856 	ldap_data_t	*sptr;
857 	int		ndata;
858 	int		adata;
859 	int		rc;
860 
861 #ifdef DEBUG
862 	(void) fprintf(stderr, "__s_api_get_cachemgr_data START\n");
863 #endif
864 
865 	if (from == NULL || from[0] == '\0' || to == NULL)
866 		return (-1);
867 
868 	*to = NULL;
869 	(void) memset(space.s_b, 0, DOORBUFFERSIZE);
870 
871 	space.s_d.ldap_call.ldap_callnumber = GETCACHE;
872 	(void) snprintf(space.s_d.ldap_call.ldap_u.domainname,
873 	    DOORBUFFERSIZE - sizeof (space.s_d.ldap_call.ldap_callnumber),
874 	    "%s%s%s",
875 	    type,
876 	    DOORLINESEP,
877 	    from);
878 	ndata = sizeof (space);
879 	adata = sizeof (ldap_call_t) +
880 	    strlen(space.s_d.ldap_call.ldap_u.domainname) + 1;
881 	sptr = &space.s_d;
882 
883 	rc = __ns_ldap_trydoorcall(&sptr, &ndata, &adata);
884 	if (rc != SUCCESS)
885 		return (-1);
886 	else
887 		*to = strdup(sptr->ldap_ret.ldap_u.buff);
888 	return (NS_LDAP_SUCCESS);
889 }
890 
891 static int
892 __s_api_set_cachemgr_data(const char *type,
893 		const char *from, const char *to)
894 {
895 	union {
896 		ldap_data_t	s_d;
897 		char		s_b[DOORBUFFERSIZE];
898 	} space;
899 	ldap_data_t	*sptr;
900 	int		ndata;
901 	int		adata;
902 	int		rc;
903 
904 #ifdef DEBUG
905 	(void) fprintf(stderr, "__s_api_set_cachemgr_data START\n");
906 #endif
907 
908 	if ((from == NULL) || (from[0] == '\0') ||
909 	    (to == NULL) || (to[0] == '\0'))
910 		return (-1);
911 
912 	(void) memset(space.s_b, 0, DOORBUFFERSIZE);
913 
914 	space.s_d.ldap_call.ldap_callnumber = SETCACHE;
915 	(void) snprintf(space.s_d.ldap_call.ldap_u.domainname,
916 	    DOORBUFFERSIZE - sizeof (space.s_d.ldap_call.ldap_callnumber),
917 	    "%s%s%s%s%s",
918 	    type,
919 	    DOORLINESEP,
920 	    from,
921 	    DOORLINESEP,
922 	    to);
923 
924 	ndata = sizeof (space);
925 	adata = sizeof (ldap_call_t) +
926 	    strlen(space.s_d.ldap_call.ldap_u.domainname) + 1;
927 	sptr = &space.s_d;
928 
929 	rc = __ns_ldap_trydoorcall(&sptr, &ndata, &adata);
930 	if (rc != SUCCESS)
931 		return (-1);
932 
933 	return (NS_LDAP_SUCCESS);
934 }
935 
936 
937 static char *
938 __s_api_remove_rdn_space(char *rdn)
939 {
940 	char	*tf, *tl, *vf, *vl, *eqsign;
941 
942 	/* if no space(s) to remove, return */
943 	if (strchr(rdn, SPACETOK) == NULL)
944 		return (rdn);
945 
946 	/* if no '=' separator, return */
947 	eqsign = strchr(rdn, '=');
948 	if (eqsign == NULL)
949 		return (rdn);
950 
951 	tf = rdn;
952 	tl = eqsign - 1;
953 	vf = eqsign + 1;
954 	vl = rdn + strlen(rdn) - 1;
955 
956 	/* now two strings, type and value */
957 	*eqsign = '\0';
958 
959 	/* remove type's leading spaces */
960 	while (tf < tl && *tf == SPACETOK)
961 		tf++;
962 	/* remove type's trailing spaces */
963 	while (tf < tl && *tl == SPACETOK)
964 		tl--;
965 	/* add '=' separator back */
966 	*(++tl) = '=';
967 	/* remove value's leading spaces */
968 	while (vf < vl && *vf == SPACETOK)
969 		vf++;
970 	/* remove value's trailing spaces */
971 	while (vf < vl && *vl == SPACETOK)
972 		*vl-- = '\0';
973 
974 	/* move value up if necessary */
975 	if (vf != tl + 1)
976 		(void) strcpy(tl + 1, vf);
977 
978 	return (tf);
979 }
980 
981 static
982 ns_ldap_cookie_t *
983 init_search_state_machine()
984 {
985 	ns_ldap_cookie_t	*cookie;
986 	ns_config_t		*cfg;
987 
988 	cookie = (ns_ldap_cookie_t *)calloc(1, sizeof (ns_ldap_cookie_t));
989 	if (cookie == NULL)
990 		return (NULL);
991 	cookie->state = INIT;
992 	/* assign other state variables */
993 	cfg = __s_api_loadrefresh_config();
994 	cookie->connectionId = -1;
995 	if (cfg == NULL ||
996 	    cfg->paramList[NS_LDAP_SEARCH_TIME_P].ns_ptype == NS_UNKNOWN) {
997 		cookie->search_timeout.tv_sec = NS_DEFAULT_SEARCH_TIMEOUT;
998 	} else {
999 		cookie->search_timeout.tv_sec =
1000 		    cfg->paramList[NS_LDAP_SEARCH_TIME_P].ns_i;
1001 	}
1002 	if (cfg != NULL)
1003 		__s_api_release_config(cfg);
1004 	cookie->search_timeout.tv_usec = 0;
1005 
1006 	return (cookie);
1007 }
1008 
1009 static void
1010 delete_search_cookie(ns_ldap_cookie_t *cookie)
1011 {
1012 	if (cookie == NULL)
1013 		return;
1014 	if (cookie->connectionId > -1)
1015 		DropConnection(cookie->connectionId, cookie->i_flags);
1016 	if (cookie->filter)
1017 		free(cookie->filter);
1018 	if (cookie->i_filter)
1019 		free(cookie->i_filter);
1020 	if (cookie->service)
1021 		free(cookie->service);
1022 	if (cookie->sdlist)
1023 		(void) __ns_ldap_freeSearchDescriptors(&(cookie->sdlist));
1024 	if (cookie->result)
1025 		(void) __ns_ldap_freeResult(&cookie->result);
1026 	if (cookie->attribute)
1027 		__s_api_free2dArray(cookie->attribute);
1028 	if (cookie->errorp)
1029 		(void) __ns_ldap_freeError(&cookie->errorp);
1030 	if (cookie->reflist)
1031 		__s_api_deleteRefInfo(cookie->reflist);
1032 	if (cookie->basedn)
1033 		free(cookie->basedn);
1034 	if (cookie->ctrlCookie)
1035 		ber_bvfree(cookie->ctrlCookie);
1036 	_freeControlList(&cookie->p_serverctrls);
1037 	if (cookie->resultctrl)
1038 		ldap_controls_free(cookie->resultctrl);
1039 	free(cookie);
1040 }
1041 
1042 static int
1043 get_mapped_filter(ns_ldap_cookie_t *cookie, char **new_filter)
1044 {
1045 
1046 	typedef	struct	filter_mapping_info {
1047 		char	oc_or_attr;
1048 		char	*name_start;
1049 		char	*name_end;
1050 		char	*veq_pos;
1051 		char	*from_name;
1052 		char	*to_name;
1053 		char	**mapping;
1054 	} filter_mapping_info_t;
1055 
1056 	char			*c, *last_copied;
1057 	char			*filter_c, *filter_c_next;
1058 	char			*key, *tail, *head;
1059 	char			errstr[MAXERROR];
1060 	int			num_eq = 0, num_veq = 0;
1061 	int			in_quote = FALSE;
1062 	int			is_value = FALSE;
1063 	int			i, j, oc_len, len;
1064 	int			at_least_one = FALSE;
1065 	filter_mapping_info_t	**info, *info1;
1066 	char			**mapping;
1067 	char			*service, *filter, *err;
1068 	int			auto_service = FALSE;
1069 
1070 	if (cookie == NULL || new_filter == NULL)
1071 		return (NS_LDAP_INVALID_PARAM);
1072 
1073 	*new_filter = NULL;
1074 	service = cookie->service;
1075 	filter = cookie->filter;
1076 
1077 	/*
1078 	 * count the number of '=' char
1079 	 */
1080 	for (c = filter; *c; c++) {
1081 		if (*c == TOKENSEPARATOR)
1082 			num_eq++;
1083 	}
1084 
1085 	if (service != NULL && strncasecmp(service, "auto_", 5) == 0)
1086 		auto_service = TRUE;
1087 
1088 	/*
1089 	 * See if schema mapping existed for the given service.
1090 	 * If not, just return success.
1091 	 */
1092 	mapping = __ns_ldap_getOrigAttribute(service,
1093 	    NS_HASH_SCHEMA_MAPPING_EXISTED);
1094 
1095 	if (mapping == NULL && auto_service)
1096 		/*
1097 		 * if service == auto_* and no
1098 		 * schema mapping found
1099 		 * then try automount
1100 		 */
1101 		mapping = __ns_ldap_getOrigAttribute(
1102 		    "automount", NS_HASH_SCHEMA_MAPPING_EXISTED);
1103 
1104 	if (mapping)
1105 		__s_api_free2dArray(mapping);
1106 	else
1107 		return (NS_LDAP_SUCCESS);
1108 
1109 	/*
1110 	 * no '=' sign, just say OK and return nothing
1111 	 */
1112 	if (num_eq == 0)
1113 		return (NS_LDAP_SUCCESS);
1114 
1115 	/*
1116 	 * Make a copy of the filter string
1117 	 * for saving the name of the objectclasses or
1118 	 * attributes that need to be passed to the
1119 	 * objectclass or attribute mapping functions.
1120 	 * pointer "info->from_name" points to the locations
1121 	 * within this string.
1122 	 *
1123 	 * The input filter string, filter, will be used
1124 	 * to indicate where these names start and end.
1125 	 * pointers "info->name_start" and "info->name_end"
1126 	 * point to locations within the input filter string,
1127 	 * and are used at the end of this function to
1128 	 * merge the original filter data with the
1129 	 * mapped objectclass or attribute names.
1130 	 */
1131 	filter_c = strdup(filter);
1132 	if (filter_c == NULL)
1133 		return (NS_LDAP_MEMORY);
1134 	filter_c_next = filter_c;
1135 
1136 	/*
1137 	 * get memory for info arrays
1138 	 */
1139 	info = (filter_mapping_info_t **)calloc(num_eq + 1,
1140 	    sizeof (filter_mapping_info_t *));
1141 
1142 	if (info == NULL) {
1143 		free(filter_c);
1144 		return (NS_LDAP_MEMORY);
1145 	}
1146 
1147 	/*
1148 	 * find valid '=' for further processing,
1149 	 * ignore the "escaped =" (.i.e. "\="), or
1150 	 * "=" in quoted string
1151 	 */
1152 	for (c = filter_c; *c; c++) {
1153 
1154 		switch (*c) {
1155 		case TOKENSEPARATOR:
1156 			if (!in_quote && !is_value) {
1157 				info1 = (filter_mapping_info_t *)calloc(1,
1158 				    sizeof (filter_mapping_info_t));
1159 				if (!info1) {
1160 					free(filter_c);
1161 					for (i = 0; i < num_veq; i++)
1162 						free(info[i]);
1163 					free(info);
1164 					return (NS_LDAP_MEMORY);
1165 				}
1166 				info[num_veq] = info1;
1167 
1168 				/*
1169 				 * remember the location of this "="
1170 				 */
1171 				info[num_veq++]->veq_pos = c;
1172 
1173 				/*
1174 				 * skip until the end of the attribute value
1175 				 */
1176 				is_value = TRUE;
1177 			}
1178 			break;
1179 		case CPARATOK:
1180 			/*
1181 			 * mark the end of the attribute value
1182 			 */
1183 			if (!in_quote)
1184 				is_value = FALSE;
1185 			break;
1186 		case QUOTETOK:
1187 			/*
1188 			 * switch on/off the in_quote mode
1189 			 */
1190 			in_quote = (in_quote == FALSE);
1191 			break;
1192 		case '\\':
1193 			/*
1194 			 * ignore escape characters
1195 			 * don't skip if next char is '\0'
1196 			 */
1197 			if (!in_quote)
1198 				if (*(++c) == '\0')
1199 					c--;
1200 			break;
1201 		}
1202 
1203 	}
1204 
1205 	/*
1206 	 * for each valid "=" found, get the name to
1207 	 * be mapped
1208 	 */
1209 	oc_len = strlen("objectclass");
1210 	for (i = 0; i < num_veq; i++) {
1211 
1212 		/*
1213 		 * look at the left side of "=" to see
1214 		 * if assertion is "objectclass=<ocname>"
1215 		 * or "<attribute name>=<attribute value>"
1216 		 *
1217 		 * first skip spaces before "=".
1218 		 * Note that filter_c_next may not point to the
1219 		 * start of the filter string. For i > 0,
1220 		 * it points to the end of the last name processed + 2
1221 		 */
1222 		for (tail = info[i]->veq_pos; (tail > filter_c_next) &&
1223 		    (*(tail - 1) == SPACETOK); tail--)
1224 			;
1225 
1226 		/*
1227 		 * mark the end of the left side string (the key)
1228 		 */
1229 		*tail = '\0';
1230 		info[i]->name_end = tail - filter_c - 1 + filter;
1231 
1232 		/*
1233 		 * find the start of the key
1234 		 */
1235 		key = filter_c_next;
1236 		for (c = tail; filter_c_next <= c; c--) {
1237 			/* OPARATOK is '(' */
1238 			if (*c == OPARATOK ||
1239 			    *c == SPACETOK) {
1240 				key = c + 1;
1241 				break;
1242 			}
1243 		}
1244 		info[i]->name_start = key - filter_c + filter;
1245 
1246 		if ((key + oc_len) <= tail) {
1247 			if (strncasecmp(key, "objectclass",
1248 			    oc_len) == 0) {
1249 				/*
1250 				 * assertion is "objectclass=ocname",
1251 				 * ocname is the one needs to be mapped
1252 				 *
1253 				 * skip spaces after "=" to find start
1254 				 * of the ocname
1255 				 */
1256 				head = info[i]->veq_pos;
1257 				for (head = info[i]->veq_pos + 1;
1258 				    *head && *head == SPACETOK; head++)
1259 					;
1260 
1261 				/* ignore empty ocname */
1262 				if (!(*head))
1263 					continue;
1264 
1265 				info[i]->name_start = head - filter_c +
1266 				    filter;
1267 
1268 				/*
1269 				 * now find the end of the ocname
1270 				 */
1271 				for (c = head; ; c++) {
1272 					/* CPARATOK is ')' */
1273 					if (*c == CPARATOK ||
1274 					    *c == '\0' ||
1275 					    *c == SPACETOK) {
1276 						*c = '\0';
1277 						info[i]->name_end =
1278 						    c - filter_c - 1 +
1279 						    filter;
1280 						filter_c_next = c + 1;
1281 						info[i]->oc_or_attr = 'o';
1282 						info[i]->from_name = head;
1283 						break;
1284 					}
1285 				}
1286 			}
1287 		}
1288 
1289 		/*
1290 		 * assertion is not "objectclass=ocname",
1291 		 * assume assertion is "<key> = <value>",
1292 		 * <key> is the one needs to be mapped
1293 		 */
1294 		if (info[i]->from_name == NULL && strlen(key) > 0) {
1295 			info[i]->oc_or_attr = 'a';
1296 			info[i]->from_name = key;
1297 		}
1298 	}
1299 
1300 	/* perform schema mapping */
1301 	for (i = 0; i < num_veq; i++) {
1302 		if (info[i]->from_name == NULL)
1303 			continue;
1304 
1305 		if (info[i]->oc_or_attr == 'a')
1306 			info[i]->mapping =
1307 			    __ns_ldap_getMappedAttributes(service,
1308 			    info[i]->from_name);
1309 		else
1310 			info[i]->mapping =
1311 			    __ns_ldap_getMappedObjectClass(service,
1312 			    info[i]->from_name);
1313 
1314 		if (info[i]->mapping == NULL && auto_service)  {
1315 			/*
1316 			 * If no mapped attribute/objectclass is found
1317 			 * and service == auto*
1318 			 * try to find automount's
1319 			 * mapped attribute/objectclass
1320 			 */
1321 			if (info[i]->oc_or_attr == 'a')
1322 				info[i]->mapping =
1323 				    __ns_ldap_getMappedAttributes("automount",
1324 				    info[i]->from_name);
1325 			else
1326 				info[i]->mapping =
1327 				    __ns_ldap_getMappedObjectClass("automount",
1328 				    info[i]->from_name);
1329 		}
1330 
1331 		if (info[i]->mapping == NULL ||
1332 		    info[i]->mapping[0] == NULL) {
1333 			info[i]->to_name = NULL;
1334 		} else if (info[i]->mapping[1] == NULL) {
1335 			info[i]->to_name = info[i]->mapping[0];
1336 			at_least_one = TRUE;
1337 		} else {
1338 			__s_api_free2dArray(info[i]->mapping);
1339 			/*
1340 			 * multiple mapping
1341 			 * not allowed
1342 			 */
1343 			(void) sprintf(errstr,
1344 			    gettext(
1345 			    "Multiple attribute or objectclass "
1346 			    "mapping for '%s' in filter "
1347 			    "'%s' not allowed."),
1348 			    info[i]->from_name, filter);
1349 			err = strdup(errstr);
1350 			if (err)
1351 				MKERROR(LOG_WARNING, cookie->errorp,
1352 				    NS_CONFIG_SYNTAX,
1353 				    err, NULL);
1354 
1355 			free(filter_c);
1356 			for (j = 0; j < num_veq; j++) {
1357 				if (info[j]->mapping)
1358 					__s_api_free2dArray(
1359 					    info[j]->mapping);
1360 				free(info[j]);
1361 			}
1362 			free(info);
1363 			return (NS_LDAP_CONFIG);
1364 		}
1365 	}
1366 
1367 
1368 	if (at_least_one) {
1369 
1370 		len = strlen(filter);
1371 		last_copied = filter - 1;
1372 
1373 		for (i = 0; i < num_veq; i++) {
1374 			if (info[i]->to_name)
1375 				len += strlen(info[i]->to_name);
1376 		}
1377 
1378 		*new_filter = (char *)calloc(1, len);
1379 		if (*new_filter == NULL) {
1380 			free(filter_c);
1381 			for (j = 0; j < num_veq; j++) {
1382 				if (info[j]->mapping)
1383 					__s_api_free2dArray(
1384 					    info[j]->mapping);
1385 				free(info[j]);
1386 			}
1387 			free(info);
1388 			return (NS_LDAP_MEMORY);
1389 		}
1390 
1391 		for (i = 0; i < num_veq; i++) {
1392 			if (info[i]->to_name != NULL &&
1393 			    info[i]->to_name != NULL) {
1394 
1395 				/*
1396 				 * copy the original filter data
1397 				 * between the last name and current
1398 				 * name
1399 				 */
1400 				if ((last_copied + 1) != info[i]->name_start)
1401 					(void) strncat(*new_filter,
1402 					    last_copied + 1,
1403 					    info[i]->name_start -
1404 					    last_copied - 1);
1405 
1406 				/* the data is copied */
1407 				last_copied = info[i]->name_end;
1408 
1409 				/*
1410 				 * replace the name with
1411 				 * the mapped name
1412 				 */
1413 				(void) strcat(*new_filter, info[i]->to_name);
1414 			}
1415 
1416 			/* copy the filter data after the last name */
1417 			if (i == (num_veq -1) &&
1418 			    info[i]->name_end <
1419 			    (filter + strlen(filter)))
1420 				(void) strncat(*new_filter, last_copied + 1,
1421 				    filter + strlen(filter) -
1422 				    last_copied - 1);
1423 		}
1424 
1425 	}
1426 
1427 	/* free memory */
1428 	free(filter_c);
1429 	for (j = 0; j < num_veq; j++) {
1430 		if (info[j]->mapping)
1431 			__s_api_free2dArray(info[j]->mapping);
1432 		free(info[j]);
1433 	}
1434 	free(info);
1435 
1436 	return (NS_LDAP_SUCCESS);
1437 }
1438 
1439 static int
1440 setup_next_search(ns_ldap_cookie_t *cookie)
1441 {
1442 	ns_ldap_search_desc_t	*dptr;
1443 	int			scope;
1444 	char			*filter, *str;
1445 	int			baselen;
1446 	int			rc;
1447 	void			**param;
1448 
1449 	dptr = *cookie->sdpos;
1450 	scope = cookie->i_flags & (NS_LDAP_SCOPE_BASE |
1451 	    NS_LDAP_SCOPE_ONELEVEL |
1452 	    NS_LDAP_SCOPE_SUBTREE);
1453 	if (scope)
1454 		cookie->scope = scope;
1455 	else
1456 		cookie->scope = dptr->scope;
1457 	switch (cookie->scope) {
1458 	case NS_LDAP_SCOPE_BASE:
1459 		cookie->scope = LDAP_SCOPE_BASE;
1460 		break;
1461 	case NS_LDAP_SCOPE_ONELEVEL:
1462 		cookie->scope = LDAP_SCOPE_ONELEVEL;
1463 		break;
1464 	case NS_LDAP_SCOPE_SUBTREE:
1465 		cookie->scope = LDAP_SCOPE_SUBTREE;
1466 		break;
1467 	}
1468 
1469 	filter = NULL;
1470 	if (cookie->use_filtercb && cookie->init_filter_cb &&
1471 	    dptr->filter && strlen(dptr->filter) > 0) {
1472 		(*cookie->init_filter_cb)(dptr, &filter,
1473 		    cookie->userdata);
1474 	}
1475 	if (filter == NULL) {
1476 		if (cookie->i_filter == NULL) {
1477 			cookie->err_rc = NS_LDAP_INVALID_PARAM;
1478 			return (-1);
1479 		} else {
1480 			if (cookie->filter)
1481 				free(cookie->filter);
1482 			cookie->filter = strdup(cookie->i_filter);
1483 			if (cookie->filter == NULL) {
1484 				cookie->err_rc = NS_LDAP_MEMORY;
1485 				return (-1);
1486 			}
1487 		}
1488 	} else {
1489 		if (cookie->filter)
1490 			free(cookie->filter);
1491 		cookie->filter = strdup(filter);
1492 		free(filter);
1493 		if (cookie->filter == NULL) {
1494 			cookie->err_rc = NS_LDAP_MEMORY;
1495 			return (-1);
1496 		}
1497 	}
1498 
1499 	/*
1500 	 * perform attribute/objectclass mapping on filter
1501 	 */
1502 	filter = NULL;
1503 
1504 	if (cookie->service) {
1505 		rc = get_mapped_filter(cookie, &filter);
1506 		if (rc != NS_LDAP_SUCCESS) {
1507 			cookie->err_rc = rc;
1508 			return (-1);
1509 		} else {
1510 			/*
1511 			 * get_mapped_filter returns
1512 			 * NULL filter pointer, if
1513 			 * no mapping was done
1514 			 */
1515 			if (filter) {
1516 				free(cookie->filter);
1517 				cookie->filter = filter;
1518 			}
1519 		}
1520 	}
1521 
1522 	/*
1523 	 * validate filter to make sure it's legal
1524 	 * [remove redundant ()'s]
1525 	 */
1526 	rc = validate_filter(cookie);
1527 	if (rc != NS_LDAP_SUCCESS) {
1528 		cookie->err_rc = rc;
1529 		return (-1);
1530 	}
1531 
1532 	baselen = strlen(dptr->basedn);
1533 	if (baselen > 0 && dptr->basedn[baselen-1] == COMMATOK) {
1534 		rc = __ns_ldap_getParam(NS_LDAP_SEARCH_BASEDN_P,
1535 		    (void ***)&param, &cookie->errorp);
1536 		if (rc != NS_LDAP_SUCCESS) {
1537 			cookie->err_rc = rc;
1538 			return (-1);
1539 		}
1540 		str = ((char **)param)[0];
1541 		baselen += strlen(str)+1;
1542 		if (cookie->basedn)
1543 			free(cookie->basedn);
1544 		cookie->basedn = (char *)malloc(baselen);
1545 		if (cookie->basedn == NULL) {
1546 			cookie->err_rc = NS_LDAP_MEMORY;
1547 			return (-1);
1548 		}
1549 		(void) strcpy(cookie->basedn, dptr->basedn);
1550 		(void) strcat(cookie->basedn, str);
1551 		(void) __ns_ldap_freeParam(&param);
1552 	} else {
1553 		if (cookie->basedn)
1554 			free(cookie->basedn);
1555 		cookie->basedn = strdup(dptr->basedn);
1556 	}
1557 	return (0);
1558 }
1559 
1560 static int
1561 setup_referral_search(ns_ldap_cookie_t *cookie)
1562 {
1563 	ns_referral_info_t	*ref;
1564 
1565 	ref = cookie->refpos;
1566 	cookie->scope = ref->refScope;
1567 	if (cookie->filter) {
1568 		free(cookie->filter);
1569 	}
1570 	cookie->filter = strdup(ref->refFilter);
1571 	if (cookie->basedn) {
1572 		free(cookie->basedn);
1573 	}
1574 	cookie->basedn = strdup(ref->refDN);
1575 	if (cookie->filter == NULL || cookie->basedn == NULL) {
1576 		cookie->err_rc = NS_LDAP_MEMORY;
1577 		return (-1);
1578 	}
1579 	return (0);
1580 }
1581 
1582 static int
1583 get_current_session(ns_ldap_cookie_t *cookie)
1584 {
1585 	ConnectionID	connectionId = -1;
1586 	Connection	*conp = NULL;
1587 	int		rc;
1588 	int		fail_if_new_pwd_reqd = 1;
1589 
1590 	rc = __s_api_getConnection(NULL, cookie->i_flags,
1591 	    cookie->i_auth, &connectionId, &conp,
1592 	    &cookie->errorp, fail_if_new_pwd_reqd,
1593 	    cookie->nopasswd_acct_mgmt);
1594 
1595 	/*
1596 	 * If password control attached in *cookie->errorp,
1597 	 * e.g. rc == NS_LDAP_SUCCESS_WITH_INFO,
1598 	 * free the error structure (we do not need
1599 	 * the sec_to_expired info).
1600 	 * Reset rc to NS_LDAP_SUCCESS.
1601 	 */
1602 	if (rc == NS_LDAP_SUCCESS_WITH_INFO) {
1603 		(void) __ns_ldap_freeError(
1604 		    &cookie->errorp);
1605 		cookie->errorp = NULL;
1606 		rc = NS_LDAP_SUCCESS;
1607 	}
1608 
1609 	if (rc != NS_LDAP_SUCCESS) {
1610 		cookie->err_rc = rc;
1611 		return (-1);
1612 	}
1613 	cookie->conn = conp;
1614 	cookie->connectionId = connectionId;
1615 
1616 	return (0);
1617 }
1618 
1619 static int
1620 get_next_session(ns_ldap_cookie_t *cookie)
1621 {
1622 	ConnectionID	connectionId = -1;
1623 	Connection	*conp = NULL;
1624 	int		rc;
1625 	int		fail_if_new_pwd_reqd = 1;
1626 
1627 	if (cookie->connectionId > -1)
1628 		DropConnection(cookie->connectionId, cookie->i_flags);
1629 
1630 	rc = __s_api_getConnection(NULL, cookie->i_flags,
1631 	    cookie->i_auth, &connectionId, &conp,
1632 	    &cookie->errorp, fail_if_new_pwd_reqd,
1633 	    cookie->nopasswd_acct_mgmt);
1634 
1635 	/*
1636 	 * If password control attached in *cookie->errorp,
1637 	 * e.g. rc == NS_LDAP_SUCCESS_WITH_INFO,
1638 	 * free the error structure (we do not need
1639 	 * the sec_to_expired info).
1640 	 * Reset rc to NS_LDAP_SUCCESS.
1641 	 */
1642 	if (rc == NS_LDAP_SUCCESS_WITH_INFO) {
1643 		(void) __ns_ldap_freeError(
1644 		    &cookie->errorp);
1645 		cookie->errorp = NULL;
1646 		rc = NS_LDAP_SUCCESS;
1647 	}
1648 
1649 	if (rc != NS_LDAP_SUCCESS) {
1650 		cookie->err_rc = rc;
1651 		return (-1);
1652 	}
1653 	cookie->conn = conp;
1654 	cookie->connectionId = connectionId;
1655 	return (0);
1656 }
1657 
1658 static int
1659 get_referral_session(ns_ldap_cookie_t *cookie)
1660 {
1661 	ConnectionID	connectionId = -1;
1662 	Connection	*conp = NULL;
1663 	int		rc;
1664 	int		fail_if_new_pwd_reqd = 1;
1665 
1666 	if (cookie->connectionId > -1)
1667 		DropConnection(cookie->connectionId, cookie->i_flags);
1668 
1669 	rc = __s_api_getConnection(cookie->refpos->refHost, 0,
1670 	    cookie->i_auth, &connectionId, &conp,
1671 	    &cookie->errorp, fail_if_new_pwd_reqd,
1672 	    cookie->nopasswd_acct_mgmt);
1673 
1674 	/*
1675 	 * If password control attached in *cookie->errorp,
1676 	 * e.g. rc == NS_LDAP_SUCCESS_WITH_INFO,
1677 	 * free the error structure (we do not need
1678 	 * the sec_to_expired info).
1679 	 * Reset rc to NS_LDAP_SUCCESS.
1680 	 */
1681 	if (rc == NS_LDAP_SUCCESS_WITH_INFO) {
1682 		(void) __ns_ldap_freeError(
1683 		    &cookie->errorp);
1684 		cookie->errorp = NULL;
1685 		rc = NS_LDAP_SUCCESS;
1686 	}
1687 
1688 	if (rc != NS_LDAP_SUCCESS) {
1689 		cookie->err_rc = rc;
1690 		return (-1);
1691 	}
1692 	cookie->conn = conp;
1693 	cookie->connectionId = connectionId;
1694 	return (0);
1695 }
1696 
1697 static int
1698 paging_supported(ns_ldap_cookie_t *cookie)
1699 {
1700 	int		rc;
1701 
1702 	cookie->listType = 0;
1703 	rc = __s_api_isCtrlSupported(cookie->conn,
1704 	    LDAP_CONTROL_VLVREQUEST);
1705 	if (rc == NS_LDAP_SUCCESS) {
1706 		cookie->listType = VLVCTRLFLAG;
1707 		return (1);
1708 	}
1709 	rc = __s_api_isCtrlSupported(cookie->conn,
1710 	    LDAP_CONTROL_SIMPLE_PAGE);
1711 	if (rc == NS_LDAP_SUCCESS) {
1712 		cookie->listType = SIMPLEPAGECTRLFLAG;
1713 		return (1);
1714 	}
1715 	return (0);
1716 }
1717 
1718 static int
1719 setup_vlv_params(ns_ldap_cookie_t *cookie)
1720 {
1721 	LDAPControl	**ctrls;
1722 	LDAPsortkey	**sortkeylist;
1723 	LDAPControl	*sortctrl = NULL;
1724 	LDAPControl	*vlvctrl = NULL;
1725 	LDAPVirtualList	vlist;
1726 	int		rc;
1727 
1728 	_freeControlList(&cookie->p_serverctrls);
1729 
1730 	rc = ldap_create_sort_keylist(&sortkeylist, SORTKEYLIST);
1731 	if (rc != LDAP_SUCCESS) {
1732 		(void) ldap_get_option(cookie->conn->ld,
1733 		    LDAP_OPT_ERROR_NUMBER, &rc);
1734 		return (rc);
1735 	}
1736 	rc = ldap_create_sort_control(cookie->conn->ld,
1737 	    sortkeylist, 1, &sortctrl);
1738 	ldap_free_sort_keylist(sortkeylist);
1739 	if (rc != LDAP_SUCCESS) {
1740 		(void) ldap_get_option(cookie->conn->ld,
1741 		    LDAP_OPT_ERROR_NUMBER, &rc);
1742 		return (rc);
1743 	}
1744 
1745 	vlist.ldvlist_index = cookie->index;
1746 	vlist.ldvlist_size = 0;
1747 
1748 	vlist.ldvlist_before_count = 0;
1749 	vlist.ldvlist_after_count = LISTPAGESIZE-1;
1750 	vlist.ldvlist_attrvalue = NULL;
1751 	vlist.ldvlist_extradata = NULL;
1752 
1753 	rc = ldap_create_virtuallist_control(cookie->conn->ld,
1754 	    &vlist, &vlvctrl);
1755 	if (rc != LDAP_SUCCESS) {
1756 		ldap_control_free(sortctrl);
1757 		(void) ldap_get_option(cookie->conn->ld, LDAP_OPT_ERROR_NUMBER,
1758 		    &rc);
1759 		return (rc);
1760 	}
1761 
1762 	ctrls = (LDAPControl **)calloc(3, sizeof (LDAPControl *));
1763 	if (ctrls == NULL) {
1764 		ldap_control_free(sortctrl);
1765 		ldap_control_free(vlvctrl);
1766 		return (LDAP_NO_MEMORY);
1767 	}
1768 
1769 	ctrls[0] = sortctrl;
1770 	ctrls[1] = vlvctrl;
1771 
1772 	cookie->p_serverctrls = ctrls;
1773 	return (LDAP_SUCCESS);
1774 }
1775 
1776 static int
1777 setup_simplepg_params(ns_ldap_cookie_t *cookie)
1778 {
1779 	LDAPControl	**ctrls;
1780 	LDAPControl	*pgctrl = NULL;
1781 	int		rc;
1782 
1783 	_freeControlList(&cookie->p_serverctrls);
1784 
1785 	rc = ldap_create_page_control(cookie->conn->ld, LISTPAGESIZE,
1786 	    cookie->ctrlCookie, (char)0, &pgctrl);
1787 	if (rc != LDAP_SUCCESS) {
1788 		(void) ldap_get_option(cookie->conn->ld, LDAP_OPT_ERROR_NUMBER,
1789 		    &rc);
1790 		return (rc);
1791 	}
1792 
1793 	ctrls = (LDAPControl **)calloc(2, sizeof (LDAPControl *));
1794 	if (ctrls == NULL) {
1795 		ldap_control_free(pgctrl);
1796 		return (LDAP_NO_MEMORY);
1797 	}
1798 	ctrls[0] = pgctrl;
1799 	cookie->p_serverctrls = ctrls;
1800 	return (LDAP_SUCCESS);
1801 }
1802 
1803 static void
1804 proc_result_referrals(ns_ldap_cookie_t *cookie)
1805 {
1806 	int 		errCode, i, rc;
1807 	char 		**referrals = NULL;
1808 
1809 	/*
1810 	 * Only follow one level of referrals, i.e.
1811 	 * if already in referral mode, do nothing
1812 	 */
1813 	if (cookie->refpos == NULL) {
1814 		cookie->new_state = END_RESULT;
1815 		rc = ldap_parse_result(cookie->conn->ld,
1816 		    cookie->resultMsg,
1817 		    &errCode, NULL,
1818 		    NULL, &referrals,
1819 		    NULL, 0);
1820 		if (rc != NS_LDAP_SUCCESS) {
1821 			(void) ldap_get_option(cookie->conn->ld,
1822 			    LDAP_OPT_ERROR_NUMBER,
1823 			    &cookie->err_rc);
1824 			cookie->new_state = LDAP_ERROR;
1825 			return;
1826 		}
1827 		if (errCode == LDAP_REFERRAL) {
1828 			for (i = 0; referrals[i] != NULL;
1829 			    i++) {
1830 				/* add to referral list */
1831 				rc = __s_api_addRefInfo(
1832 				    &cookie->reflist,
1833 				    referrals[i],
1834 				    cookie->basedn,
1835 				    &cookie->scope,
1836 				    cookie->filter,
1837 				    cookie->conn->ld);
1838 				if (rc != NS_LDAP_SUCCESS) {
1839 					cookie->new_state =
1840 					    ERROR;
1841 					break;
1842 				}
1843 			}
1844 			ldap_value_free(referrals);
1845 		}
1846 	}
1847 }
1848 
1849 static void
1850 proc_search_references(ns_ldap_cookie_t *cookie)
1851 {
1852 	char 		**refurls = NULL;
1853 	int 		i, rc;
1854 
1855 	/*
1856 	 * Only follow one level of referrals, i.e.
1857 	 * if already in referral mode, do nothing
1858 	 */
1859 	if (cookie->refpos == NULL) {
1860 		refurls = ldap_get_reference_urls(
1861 		    cookie->conn->ld,
1862 		    cookie->resultMsg);
1863 		if (refurls == NULL) {
1864 			(void) ldap_get_option(cookie->conn->ld,
1865 			    LDAP_OPT_ERROR_NUMBER,
1866 			    &cookie->err_rc);
1867 			cookie->new_state = LDAP_ERROR;
1868 			return;
1869 		}
1870 		for (i = 0; refurls[i] != NULL; i++) {
1871 			/* add to referral list */
1872 			rc = __s_api_addRefInfo(
1873 			    &cookie->reflist,
1874 			    refurls[i],
1875 			    cookie->basedn,
1876 			    &cookie->scope,
1877 			    cookie->filter,
1878 			    cookie->conn->ld);
1879 			if (rc != NS_LDAP_SUCCESS) {
1880 				cookie->new_state =
1881 				    ERROR;
1882 				break;
1883 			}
1884 		}
1885 		/* free allocated storage */
1886 		for (i = 0; refurls[i] != NULL; i++)
1887 			free(refurls[i]);
1888 	}
1889 }
1890 
1891 static ns_state_t
1892 multi_result(ns_ldap_cookie_t *cookie)
1893 {
1894 	char		errstr[MAXERROR];
1895 	char		*err;
1896 	ns_ldap_error_t **errorp = NULL;
1897 	LDAPControl	**retCtrls = NULL;
1898 	int		i, rc;
1899 	int		errCode;
1900 	int		finished = 0;
1901 	unsigned long	target_posp = 0;
1902 	unsigned long	list_size = 0;
1903 	unsigned int	count = 0;
1904 	char 		**referrals = NULL;
1905 
1906 	if (cookie->listType == VLVCTRLFLAG) {
1907 		rc = ldap_parse_result(cookie->conn->ld, cookie->resultMsg,
1908 		    &errCode, NULL, NULL, &referrals, &retCtrls, 0);
1909 		if (rc != LDAP_SUCCESS) {
1910 			(void) ldap_get_option(cookie->conn->ld,
1911 			    LDAP_OPT_ERROR_NUMBER,
1912 			    &cookie->err_rc);
1913 			(void) sprintf(errstr,
1914 			    gettext("LDAP ERROR (%d): %s.\n"),
1915 			    cookie->err_rc,
1916 			    gettext(ldap_err2string(cookie->err_rc)));
1917 			err = strdup(errstr);
1918 			MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL, err,
1919 			    NULL);
1920 			cookie->err_rc = NS_LDAP_INTERNAL;
1921 			cookie->errorp = *errorp;
1922 			return (LDAP_ERROR);
1923 		}
1924 		if (errCode == LDAP_REFERRAL) {
1925 			for (i = 0; referrals[i] != NULL;
1926 			    i++) {
1927 				/* add to referral list */
1928 				rc = __s_api_addRefInfo(
1929 				    &cookie->reflist,
1930 				    referrals[i],
1931 				    cookie->basedn,
1932 				    &cookie->scope,
1933 				    cookie->filter,
1934 				    cookie->conn->ld);
1935 				if (rc != NS_LDAP_SUCCESS) {
1936 					ldap_value_free(
1937 					    referrals);
1938 					if (retCtrls)
1939 						ldap_controls_free(
1940 						    retCtrls);
1941 					return (ERROR);
1942 				}
1943 			}
1944 			ldap_value_free(referrals);
1945 			if (retCtrls)
1946 				ldap_controls_free(retCtrls);
1947 			return (END_RESULT);
1948 		}
1949 		if (retCtrls) {
1950 			rc = ldap_parse_virtuallist_control(
1951 			    cookie->conn->ld, retCtrls,
1952 			    &target_posp, &list_size, &errCode);
1953 			if (rc == LDAP_SUCCESS) {
1954 				cookie->index = target_posp + LISTPAGESIZE;
1955 				if (cookie->index > list_size) {
1956 					finished = 1;
1957 				}
1958 			}
1959 			ldap_controls_free(retCtrls);
1960 			retCtrls = NULL;
1961 		}
1962 		else
1963 			finished = 1;
1964 	} else if (cookie->listType == SIMPLEPAGECTRLFLAG) {
1965 		rc = ldap_parse_result(cookie->conn->ld, cookie->resultMsg,
1966 		    &errCode, NULL, NULL, &referrals, &retCtrls, 0);
1967 		if (rc != LDAP_SUCCESS) {
1968 			(void) ldap_get_option(cookie->conn->ld,
1969 			    LDAP_OPT_ERROR_NUMBER,
1970 			    &cookie->err_rc);
1971 			(void) sprintf(errstr,
1972 			    gettext("LDAP ERROR (%d): %s.\n"),
1973 			    cookie->err_rc,
1974 			    gettext(ldap_err2string(cookie->err_rc)));
1975 			err = strdup(errstr);
1976 			MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL, err,
1977 			    NULL);
1978 			cookie->err_rc = NS_LDAP_INTERNAL;
1979 			cookie->errorp = *errorp;
1980 			return (LDAP_ERROR);
1981 		}
1982 		if (errCode == LDAP_REFERRAL) {
1983 			for (i = 0; referrals[i] != NULL;
1984 			    i++) {
1985 				/* add to referral list */
1986 				rc = __s_api_addRefInfo(
1987 				    &cookie->reflist,
1988 				    referrals[i],
1989 				    cookie->basedn,
1990 				    &cookie->scope,
1991 				    cookie->filter,
1992 				    cookie->conn->ld);
1993 				if (rc != NS_LDAP_SUCCESS) {
1994 					ldap_value_free(
1995 					    referrals);
1996 					if (retCtrls)
1997 						ldap_controls_free(
1998 						    retCtrls);
1999 					return (ERROR);
2000 				}
2001 			}
2002 			ldap_value_free(referrals);
2003 			if (retCtrls)
2004 				ldap_controls_free(retCtrls);
2005 			return (END_RESULT);
2006 		}
2007 		if (retCtrls) {
2008 			if (cookie->ctrlCookie)
2009 				ber_bvfree(cookie->ctrlCookie);
2010 			cookie->ctrlCookie = NULL;
2011 			rc = ldap_parse_page_control(
2012 			    cookie->conn->ld, retCtrls,
2013 			    &count, &cookie->ctrlCookie);
2014 			if (rc == LDAP_SUCCESS) {
2015 				if ((cookie->ctrlCookie == NULL) ||
2016 				    (cookie->ctrlCookie->bv_val == NULL) ||
2017 				    (cookie->ctrlCookie->bv_len == 0))
2018 					finished = 1;
2019 			}
2020 			ldap_controls_free(retCtrls);
2021 			retCtrls = NULL;
2022 		}
2023 		else
2024 			finished = 1;
2025 	}
2026 	if (!finished && cookie->listType == VLVCTRLFLAG)
2027 		return (NEXT_VLV);
2028 	if (!finished && cookie->listType == SIMPLEPAGECTRLFLAG)
2029 		return (NEXT_PAGE);
2030 	if (finished)
2031 		return (END_RESULT);
2032 	return (ERROR);
2033 }
2034 
2035 /*
2036  * This state machine performs one or more LDAP searches to a given
2037  * directory server using service search descriptors and schema
2038  * mapping as appropriate.  The approximate pseudocode for
2039  * this routine is the following:
2040  *    Given the current configuration [set/reset connection etc.]
2041  *    and the current service search descriptor list
2042  *        or default search filter parameters
2043  *    foreach (service search filter) {
2044  *        initialize the filter [via filter_init if appropriate]
2045  *		  get a valid session/connection (preferably the current one)
2046  *					Recover if the connection is lost
2047  *        perform the search
2048  *        foreach (result entry) {
2049  *            process result [via callback if appropriate]
2050  *                save result for caller if accepted.
2051  *                exit and return all collected if allResults found;
2052  *        }
2053  *    }
2054  *    return collected results and exit
2055  */
2056 
2057 static
2058 ns_state_t
2059 search_state_machine(ns_ldap_cookie_t *cookie, ns_state_t state, int cycle)
2060 {
2061 	char		errstr[MAXERROR];
2062 	char		*err;
2063 	int		rc, ret;
2064 	ns_ldap_entry_t	*nextEntry;
2065 	ns_ldap_error_t *error = NULL;
2066 	ns_ldap_error_t **errorp;
2067 
2068 	errorp = &error;
2069 	cookie->err_rc = 0;
2070 	cookie->state = state;
2071 	errstr[0] = '\0';
2072 
2073 	for (;;) {
2074 		switch (cookie->state) {
2075 		case CLEAR_RESULTS:
2076 			(void) ldap_abandon_ext(cookie->conn->ld,
2077 			    cookie->msgId, NULL, NULL);
2078 			cookie->new_state = EXIT;
2079 			break;
2080 		case GET_ACCT_MGMT_INFO:
2081 			/*
2082 			 * Set the flag to get ldap account management controls.
2083 			 */
2084 			cookie->nopasswd_acct_mgmt = 1;
2085 			cookie->new_state = INIT;
2086 			break;
2087 		case EXIT:
2088 			/* state engine/connection cleaned up in delete */
2089 			if (cookie->attribute) {
2090 				__s_api_free2dArray(cookie->attribute);
2091 				cookie->attribute = NULL;
2092 			}
2093 			if (cookie->reflist) {
2094 				__s_api_deleteRefInfo(cookie->reflist);
2095 				cookie->reflist = NULL;
2096 			}
2097 			return (EXIT);
2098 		case INIT:
2099 			cookie->sdpos = NULL;
2100 			cookie->new_state = NEXT_SEARCH_DESCRIPTOR;
2101 			if (cookie->attribute) {
2102 				__s_api_free2dArray(cookie->attribute);
2103 				cookie->attribute = NULL;
2104 			}
2105 			if ((cookie->i_flags & NS_LDAP_NOMAP) == 0 &&
2106 			    cookie->i_attr) {
2107 				cookie->attribute =
2108 				    __ns_ldap_mapAttributeList(
2109 				    cookie->service,
2110 				    cookie->i_attr);
2111 			}
2112 			break;
2113 		case NEXT_SEARCH_DESCRIPTOR:
2114 			/* get next search descriptor */
2115 			if (cookie->sdpos == NULL) {
2116 				cookie->sdpos = cookie->sdlist;
2117 				cookie->new_state = GET_SESSION;
2118 			} else {
2119 				cookie->sdpos++;
2120 				cookie->new_state = NEXT_SEARCH;
2121 			}
2122 			if (*cookie->sdpos == NULL)
2123 				cookie->new_state = EXIT;
2124 			break;
2125 		case GET_SESSION:
2126 			if (get_current_session(cookie) < 0)
2127 				cookie->new_state = NEXT_SESSION;
2128 			else
2129 				cookie->new_state = NEXT_SEARCH;
2130 			break;
2131 		case NEXT_SESSION:
2132 			if (get_next_session(cookie) < 0)
2133 				cookie->new_state = RESTART_SESSION;
2134 			else
2135 				cookie->new_state = NEXT_SEARCH;
2136 			break;
2137 		case RESTART_SESSION:
2138 			if (cookie->i_flags & NS_LDAP_HARD) {
2139 				cookie->new_state = NEXT_SESSION;
2140 				break;
2141 			}
2142 			(void) sprintf(errstr,
2143 			    gettext("Session error no available conn.\n"),
2144 			    state);
2145 			err = strdup(errstr);
2146 			MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL, err,
2147 			    NULL);
2148 			cookie->err_rc = NS_LDAP_INTERNAL;
2149 			cookie->errorp = *errorp;
2150 			cookie->new_state = EXIT;
2151 			break;
2152 		case NEXT_SEARCH:
2153 			/* setup referrals search if necessary */
2154 			if (cookie->refpos) {
2155 				if (setup_referral_search(cookie) < 0) {
2156 					cookie->new_state = EXIT;
2157 					break;
2158 				}
2159 			} else if (setup_next_search(cookie) < 0) {
2160 				cookie->new_state = EXIT;
2161 				break;
2162 			}
2163 			/* only do VLV/PAGE on scopes onelevel/subtree */
2164 			if (paging_supported(cookie)) {
2165 				if (cookie->use_paging &&
2166 				    (cookie->scope != LDAP_SCOPE_BASE)) {
2167 					cookie->index = 1;
2168 					if (cookie->listType == VLVCTRLFLAG)
2169 						cookie->new_state = NEXT_VLV;
2170 					else
2171 						cookie->new_state = NEXT_PAGE;
2172 					break;
2173 				}
2174 			}
2175 			cookie->new_state = ONE_SEARCH;
2176 			break;
2177 		case NEXT_VLV:
2178 			rc = setup_vlv_params(cookie);
2179 			if (rc != LDAP_SUCCESS) {
2180 				cookie->err_rc = rc;
2181 				cookie->new_state = LDAP_ERROR;
2182 				break;
2183 			}
2184 			cookie->next_state = MULTI_RESULT;
2185 			cookie->new_state = DO_SEARCH;
2186 			break;
2187 		case NEXT_PAGE:
2188 			rc = setup_simplepg_params(cookie);
2189 			if (rc != LDAP_SUCCESS) {
2190 				cookie->err_rc = rc;
2191 				cookie->new_state = LDAP_ERROR;
2192 				break;
2193 			}
2194 			cookie->next_state = MULTI_RESULT;
2195 			cookie->new_state = DO_SEARCH;
2196 			break;
2197 		case ONE_SEARCH:
2198 			cookie->next_state = NEXT_RESULT;
2199 			cookie->new_state = DO_SEARCH;
2200 			break;
2201 		case DO_SEARCH:
2202 			rc = ldap_search_ext(cookie->conn->ld,
2203 			    cookie->basedn,
2204 			    cookie->scope,
2205 			    cookie->filter,
2206 			    cookie->attribute,
2207 			    0,
2208 			    cookie->p_serverctrls,
2209 			    NULL,
2210 			    &cookie->search_timeout, 0,
2211 			    &cookie->msgId);
2212 			if (rc != LDAP_SUCCESS) {
2213 				if (rc == LDAP_BUSY ||
2214 				    rc == LDAP_UNAVAILABLE ||
2215 				    rc == LDAP_UNWILLING_TO_PERFORM ||
2216 				    rc == LDAP_CONNECT_ERROR ||
2217 				    rc == LDAP_SERVER_DOWN) {
2218 
2219 					cookie->new_state = NEXT_SESSION;
2220 
2221 					/*
2222 					 * If not able to reach the
2223 					 * server, inform the ldap
2224 					 * cache manager that the
2225 					 * server should be removed
2226 					 * from it's server list.
2227 					 * Thus, the manager will not
2228 					 * return this server on the next
2229 					 * get-server request and will
2230 					 * also reduce the server list
2231 					 * refresh TTL, so that it will
2232 					 * find out sooner when the server
2233 					 * is up again.
2234 					 */
2235 					if (rc == LDAP_CONNECT_ERROR ||
2236 					    rc == LDAP_SERVER_DOWN) {
2237 						ret = __s_api_removeServer(
2238 						    cookie->conn->serverAddr);
2239 						if (ret == NOSERVER &&
2240 						    cookie->conn_auth_type
2241 						    == NS_LDAP_AUTH_NONE) {
2242 							/*
2243 							 * Couldn't remove
2244 							 * server from server
2245 							 * list.
2246 							 * Exit to avoid
2247 							 * potential infinite
2248 							 * loop.
2249 							 */
2250 							cookie->err_rc = rc;
2251 							cookie->new_state =
2252 							    LDAP_ERROR;
2253 						}
2254 						if (cookie->connectionId > -1) {
2255 							/*
2256 							 * NS_LDAP_NEW_CONN
2257 							 * indicates that the
2258 							 * connection should
2259 							 * be deleted, not
2260 							 * kept alive
2261 							 */
2262 							DropConnection(
2263 							    cookie->
2264 							    connectionId,
2265 							    NS_LDAP_NEW_CONN);
2266 							cookie->connectionId =
2267 							    -1;
2268 						}
2269 					}
2270 					break;
2271 				}
2272 				cookie->err_rc = rc;
2273 				cookie->new_state = LDAP_ERROR;
2274 				break;
2275 			}
2276 			cookie->new_state = cookie->next_state;
2277 			break;
2278 		case NEXT_RESULT:
2279 			rc = ldap_result(cookie->conn->ld, cookie->msgId,
2280 			    LDAP_MSG_ONE,
2281 			    (struct timeval *)&cookie->search_timeout,
2282 			    &cookie->resultMsg);
2283 			if (rc == LDAP_RES_SEARCH_RESULT) {
2284 				cookie->new_state = END_RESULT;
2285 				/* check and process referrals info */
2286 				if (cookie->followRef)
2287 					proc_result_referrals(
2288 					    cookie);
2289 				(void) ldap_msgfree(cookie->resultMsg);
2290 				cookie->resultMsg = NULL;
2291 				break;
2292 			}
2293 			/* handle referrals if necessary */
2294 			if (rc == LDAP_RES_SEARCH_REFERENCE) {
2295 				if (cookie->followRef)
2296 					proc_search_references(cookie);
2297 				(void) ldap_msgfree(cookie->resultMsg);
2298 				cookie->resultMsg = NULL;
2299 				break;
2300 			}
2301 			if (rc != LDAP_RES_SEARCH_ENTRY) {
2302 				switch (rc) {
2303 				case 0:
2304 					rc = LDAP_TIMEOUT;
2305 					break;
2306 				case -1:
2307 					rc = ldap_get_lderrno(cookie->conn->ld,
2308 					    NULL, NULL);
2309 					break;
2310 				default:
2311 					rc = ldap_result2error(cookie->conn->ld,
2312 					    cookie->resultMsg, 1);
2313 					break;
2314 				}
2315 				if (rc == LDAP_TIMEOUT ||
2316 				    rc == LDAP_SERVER_DOWN) {
2317 					if (rc == LDAP_TIMEOUT)
2318 						(void) __s_api_removeServer(
2319 						    cookie->conn->serverAddr);
2320 					if (cookie->connectionId > -1) {
2321 						DropConnection(
2322 						    cookie->connectionId,
2323 						    NS_LDAP_NEW_CONN);
2324 						cookie->connectionId = -1;
2325 					}
2326 					cookie->err_from_result = 1;
2327 				}
2328 				(void) ldap_msgfree(cookie->resultMsg);
2329 				cookie->resultMsg = NULL;
2330 				if (rc == LDAP_BUSY ||
2331 				    rc == LDAP_UNAVAILABLE ||
2332 				    rc == LDAP_UNWILLING_TO_PERFORM) {
2333 					cookie->new_state = NEXT_SESSION;
2334 					break;
2335 				}
2336 				cookie->err_rc = rc;
2337 				cookie->new_state = LDAP_ERROR;
2338 				break;
2339 			}
2340 			/* else LDAP_RES_SEARCH_ENTRY */
2341 			/* get account management response control */
2342 			if (cookie->nopasswd_acct_mgmt == 1) {
2343 				rc = ldap_get_entry_controls(cookie->conn->ld,
2344 				    cookie->resultMsg,
2345 				    &(cookie->resultctrl));
2346 				if (rc != LDAP_SUCCESS) {
2347 					cookie->new_state = LDAP_ERROR;
2348 					cookie->err_rc = rc;
2349 					break;
2350 				}
2351 			}
2352 			rc = __s_api_getEntry(cookie);
2353 			(void) ldap_msgfree(cookie->resultMsg);
2354 			cookie->resultMsg = NULL;
2355 			if (rc != NS_LDAP_SUCCESS) {
2356 				cookie->new_state = LDAP_ERROR;
2357 				break;
2358 			}
2359 			cookie->new_state = PROCESS_RESULT;
2360 			cookie->next_state = NEXT_RESULT;
2361 			break;
2362 		case MULTI_RESULT:
2363 			rc = ldap_result(cookie->conn->ld, cookie->msgId,
2364 			    LDAP_MSG_ONE,
2365 			    (struct timeval *)&cookie->search_timeout,
2366 			    &cookie->resultMsg);
2367 			if (rc == LDAP_RES_SEARCH_RESULT) {
2368 				rc = ldap_result2error(cookie->conn->ld,
2369 				    cookie->resultMsg, 0);
2370 				if (rc != LDAP_SUCCESS) {
2371 					cookie->err_rc = rc;
2372 					cookie->new_state = LDAP_ERROR;
2373 					(void) ldap_msgfree(cookie->resultMsg);
2374 					break;
2375 				}
2376 				cookie->new_state = multi_result(cookie);
2377 				(void) ldap_msgfree(cookie->resultMsg);
2378 				cookie->resultMsg = NULL;
2379 				break;
2380 			}
2381 			/* handle referrals if necessary */
2382 			if (rc == LDAP_RES_SEARCH_REFERENCE &&
2383 			    cookie->followRef) {
2384 				proc_search_references(cookie);
2385 				(void) ldap_msgfree(cookie->resultMsg);
2386 				cookie->resultMsg = NULL;
2387 				break;
2388 			}
2389 			if (rc != LDAP_RES_SEARCH_ENTRY) {
2390 				switch (rc) {
2391 				case 0:
2392 					rc = LDAP_TIMEOUT;
2393 					break;
2394 				case -1:
2395 					rc = ldap_get_lderrno(cookie->conn->ld,
2396 					    NULL, NULL);
2397 					break;
2398 				default:
2399 					rc = ldap_result2error(cookie->conn->ld,
2400 					    cookie->resultMsg, 1);
2401 					break;
2402 				}
2403 				if (rc == LDAP_TIMEOUT ||
2404 				    rc == LDAP_SERVER_DOWN) {
2405 					if (rc == LDAP_TIMEOUT)
2406 						(void) __s_api_removeServer(
2407 						    cookie->conn->serverAddr);
2408 					if (cookie->connectionId > -1) {
2409 						DropConnection(
2410 						    cookie->connectionId,
2411 						    NS_LDAP_NEW_CONN);
2412 						cookie->connectionId = -1;
2413 					}
2414 					cookie->err_from_result = 1;
2415 				}
2416 				(void) ldap_msgfree(cookie->resultMsg);
2417 				cookie->resultMsg = NULL;
2418 				if (rc == LDAP_BUSY ||
2419 				    rc == LDAP_UNAVAILABLE ||
2420 				    rc == LDAP_UNWILLING_TO_PERFORM) {
2421 					cookie->new_state = NEXT_SESSION;
2422 					break;
2423 				}
2424 				cookie->err_rc = rc;
2425 				cookie->new_state = LDAP_ERROR;
2426 				break;
2427 			}
2428 			/* else LDAP_RES_SEARCH_ENTRY */
2429 			rc = __s_api_getEntry(cookie);
2430 			(void) ldap_msgfree(cookie->resultMsg);
2431 			cookie->resultMsg = NULL;
2432 			if (rc != NS_LDAP_SUCCESS) {
2433 				cookie->new_state = LDAP_ERROR;
2434 				break;
2435 			}
2436 			cookie->new_state = PROCESS_RESULT;
2437 			cookie->next_state = MULTI_RESULT;
2438 			break;
2439 		case PROCESS_RESULT:
2440 			/* NOTE THIS STATE MAY BE PROCESSED BY CALLER */
2441 			if (cookie->use_usercb && cookie->callback) {
2442 				rc = 0;
2443 				for (nextEntry = cookie->result->entry;
2444 				    nextEntry != NULL;
2445 				    nextEntry = nextEntry->next) {
2446 					rc = (*cookie->callback)(nextEntry,
2447 					    cookie->userdata);
2448 
2449 					if (rc == NS_LDAP_CB_DONE) {
2450 					/* cb doesn't want any more data */
2451 						rc = NS_LDAP_PARTIAL;
2452 						cookie->err_rc = rc;
2453 						break;
2454 					} else if (rc != NS_LDAP_CB_NEXT) {
2455 					/* invalid return code */
2456 						rc = NS_LDAP_OP_FAILED;
2457 						cookie->err_rc = rc;
2458 						break;
2459 					}
2460 				}
2461 				(void) __ns_ldap_freeResult(&cookie->result);
2462 				cookie->result = NULL;
2463 			}
2464 			if (rc != 0) {
2465 				cookie->new_state = EXIT;
2466 				break;
2467 			}
2468 			/* NOTE PREVIOUS STATE SPECIFIES NEXT STATE */
2469 			cookie->new_state = cookie->next_state;
2470 			break;
2471 		case END_PROCESS_RESULT:
2472 			cookie->new_state = cookie->next_state;
2473 			break;
2474 		case END_RESULT:
2475 			/*
2476 			 * XXX DO WE NEED THIS CASE?
2477 			 * if (search is complete) {
2478 			 * 	cookie->new_state = EXIT;
2479 			 * } else
2480 			 */
2481 				/*
2482 				 * entering referral mode if necessary
2483 				 */
2484 				if (cookie->followRef && cookie->reflist)
2485 					cookie->new_state =
2486 					    NEXT_REFERRAL;
2487 				else
2488 					cookie->new_state =
2489 					    NEXT_SEARCH_DESCRIPTOR;
2490 			break;
2491 		case NEXT_REFERRAL:
2492 			/* get next referral info */
2493 			if (cookie->refpos == NULL)
2494 				cookie->refpos =
2495 				    cookie->reflist;
2496 			else
2497 				cookie->refpos =
2498 				    cookie->refpos->next;
2499 			/* check see if done with all referrals */
2500 			if (cookie->refpos != NULL)
2501 				cookie->new_state =
2502 				    GET_REFERRAL_SESSION;
2503 			else {
2504 				__s_api_deleteRefInfo(cookie->reflist);
2505 				cookie->reflist = NULL;
2506 				cookie->new_state =
2507 				    NEXT_SEARCH_DESCRIPTOR;
2508 			}
2509 			break;
2510 		case GET_REFERRAL_SESSION:
2511 			if (get_referral_session(cookie) < 0)
2512 				cookie->new_state = EXIT;
2513 			else {
2514 				cookie->new_state = NEXT_SEARCH;
2515 			}
2516 			break;
2517 		case LDAP_ERROR:
2518 			if (cookie->err_from_result) {
2519 				if (cookie->err_rc == LDAP_SERVER_DOWN) {
2520 					(void) sprintf(errstr,
2521 					    gettext("LDAP ERROR (%d): "
2522 					    "Error occurred during"
2523 					    " receiving results. "
2524 					    "This may be due to a "
2525 					    "stalled connection."),
2526 					    cookie->err_rc);
2527 				} else if (cookie->err_rc == LDAP_TIMEOUT) {
2528 					(void) sprintf(errstr,
2529 					    gettext("LDAP ERROR (%d): "
2530 					    "Error occurred during"
2531 					    " receiving results. %s"
2532 					    "."), cookie->err_rc,
2533 					    ldap_err2string(
2534 					    cookie->err_rc));
2535 				}
2536 			} else
2537 				(void) sprintf(errstr,
2538 				    gettext("LDAP ERROR (%d): %s."),
2539 				    cookie->err_rc,
2540 				    ldap_err2string(cookie->err_rc));
2541 			err = strdup(errstr);
2542 			if (cookie->err_from_result) {
2543 				MKERROR(LOG_WARNING, *errorp, cookie->err_rc,
2544 				    err, NULL);
2545 			} else {
2546 				MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL,
2547 				    err, NULL);
2548 			}
2549 			cookie->err_rc = NS_LDAP_INTERNAL;
2550 			cookie->errorp = *errorp;
2551 			return (ERROR);
2552 		default:
2553 		case ERROR:
2554 			(void) sprintf(errstr,
2555 			    gettext("Internal State machine exit (%d).\n"),
2556 			    cookie->state);
2557 			err = strdup(errstr);
2558 			MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL, err,
2559 			    NULL);
2560 			cookie->err_rc = NS_LDAP_INTERNAL;
2561 			cookie->errorp = *errorp;
2562 			return (ERROR);
2563 		}
2564 
2565 		if (cycle == ONE_STEP) {
2566 			return (cookie->new_state);
2567 		}
2568 		cookie->state = cookie->new_state;
2569 	}
2570 	/*NOTREACHED*/
2571 #if 0
2572 	(void) sprintf(errstr,
2573 	    gettext("Unexpected State machine error.\n"));
2574 	err = strdup(errstr);
2575 	MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL, err, NULL);
2576 	cookie->err_rc = NS_LDAP_INTERNAL;
2577 	cookie->errorp = *errorp;
2578 	return (ERROR);
2579 #endif
2580 }
2581 
2582 
2583 
2584 /*
2585  * __ns_ldap_list performs one or more LDAP searches to a given
2586  * directory server using service search descriptors and schema
2587  * mapping as appropriate.
2588  */
2589 
2590 int
2591 __ns_ldap_list(
2592 	const char *service,
2593 	const char *filter,
2594 	int (*init_filter_cb)(const ns_ldap_search_desc_t *desc,
2595 	char **realfilter, const void *userdata),
2596 	const char * const *attribute,
2597 	const ns_cred_t *auth,
2598 	const int flags,
2599 	ns_ldap_result_t **rResult, /* return result entries */
2600 	ns_ldap_error_t **errorp,
2601 	int (*callback)(const ns_ldap_entry_t *entry, const void *userdata),
2602 	const void *userdata)
2603 {
2604 	ns_ldap_cookie_t	*cookie;
2605 	ns_ldap_search_desc_t	**sdlist = NULL;
2606 	ns_ldap_search_desc_t	*dptr;
2607 	ns_ldap_error_t		*error = NULL;
2608 	char			**dns = NULL;
2609 	int			scope;
2610 	int			rc;
2611 	int			from_result;
2612 
2613 	*errorp = NULL;
2614 
2615 	/* Initialize State machine cookie */
2616 	cookie = init_search_state_machine();
2617 	if (cookie == NULL) {
2618 		return (NS_LDAP_MEMORY);
2619 	}
2620 
2621 	/* see if need to follow referrals */
2622 	rc = __s_api_toFollowReferrals(flags,
2623 	    &cookie->followRef, errorp);
2624 	if (rc != NS_LDAP_SUCCESS) {
2625 		delete_search_cookie(cookie);
2626 		return (rc);
2627 	}
2628 
2629 	/* get the service descriptor - or create a default one */
2630 	rc = __s_api_get_SSD_from_SSDtoUse_service(service,
2631 	    &sdlist, errorp);
2632 	if (rc != NS_LDAP_SUCCESS) {
2633 		delete_search_cookie(cookie);
2634 		*errorp = error;
2635 		return (rc);
2636 	}
2637 
2638 	if (sdlist == NULL) {
2639 		/* Create default service Desc */
2640 		sdlist = (ns_ldap_search_desc_t **)calloc(2,
2641 		    sizeof (ns_ldap_search_desc_t *));
2642 		if (sdlist == NULL) {
2643 			delete_search_cookie(cookie);
2644 			cookie = NULL;
2645 			return (NS_LDAP_MEMORY);
2646 		}
2647 		dptr = (ns_ldap_search_desc_t *)
2648 		    calloc(1, sizeof (ns_ldap_search_desc_t));
2649 		if (dptr == NULL) {
2650 			free(sdlist);
2651 			delete_search_cookie(cookie);
2652 			cookie = NULL;
2653 			return (NS_LDAP_MEMORY);
2654 		}
2655 		sdlist[0] = dptr;
2656 
2657 		/* default base */
2658 		rc = __s_api_getDNs(&dns, service, &cookie->errorp);
2659 		if (rc != NS_LDAP_SUCCESS) {
2660 			if (dns) {
2661 				__s_api_free2dArray(dns);
2662 				dns = NULL;
2663 			}
2664 			*errorp = cookie->errorp;
2665 			cookie->errorp = NULL;
2666 			delete_search_cookie(cookie);
2667 			cookie = NULL;
2668 			return (rc);
2669 		}
2670 		dptr->basedn = strdup(dns[0]);
2671 		__s_api_free2dArray(dns);
2672 		dns = NULL;
2673 
2674 		/* default scope */
2675 		scope = 0;
2676 		rc = __s_api_getSearchScope(&scope, &cookie->errorp);
2677 		dptr->scope = scope;
2678 	}
2679 
2680 	cookie->sdlist = sdlist;
2681 
2682 	/*
2683 	 * use VLV/PAGE control only if NS_LDAP_PAGE_CTRL is set
2684 	 */
2685 	if (flags & NS_LDAP_PAGE_CTRL)
2686 		cookie->use_paging = TRUE;
2687 	else
2688 		cookie->use_paging = FALSE;
2689 
2690 	/* Set up other arguments */
2691 	cookie->userdata = userdata;
2692 	if (init_filter_cb != NULL) {
2693 		cookie->init_filter_cb = init_filter_cb;
2694 		cookie->use_filtercb = 1;
2695 	}
2696 	if (callback != NULL) {
2697 		cookie->callback = callback;
2698 		cookie->use_usercb = 1;
2699 	}
2700 	if (service) {
2701 		cookie->service = strdup(service);
2702 		if (cookie->service == NULL) {
2703 			delete_search_cookie(cookie);
2704 			cookie = NULL;
2705 			return (NS_LDAP_MEMORY);
2706 		}
2707 	}
2708 
2709 	cookie->i_filter = strdup(filter);
2710 	cookie->i_attr = attribute;
2711 	cookie->i_auth = auth;
2712 	cookie->i_flags = flags;
2713 
2714 	/* Process search */
2715 	rc = search_state_machine(cookie, INIT, 0);
2716 
2717 	/* Copy results back to user */
2718 	rc = cookie->err_rc;
2719 	if (rc != NS_LDAP_SUCCESS)
2720 		*errorp = cookie->errorp;
2721 	*rResult = cookie->result;
2722 	from_result = cookie->err_from_result;
2723 
2724 	cookie->errorp = NULL;
2725 	cookie->result = NULL;
2726 	delete_search_cookie(cookie);
2727 	cookie = NULL;
2728 
2729 	if (from_result == 0 && *rResult == NULL)
2730 		rc = NS_LDAP_NOTFOUND;
2731 	return (rc);
2732 }
2733 
2734 /*
2735  * __s_api_find_domainname performs one or more LDAP searches to
2736  * find the value of the nisdomain attribute associated with
2737  * the input DN
2738  */
2739 
2740 static int
2741 __s_api_find_domainname(
2742 	const char *dn,
2743 	char **domainname,
2744 	const ns_cred_t *cred,
2745 	ns_ldap_error_t **errorp)
2746 {
2747 
2748 	ns_ldap_cookie_t	*cookie;
2749 	ns_ldap_search_desc_t	**sdlist;
2750 	ns_ldap_search_desc_t	*dptr;
2751 	int			rc;
2752 	char			**value;
2753 	int			flags = 0;
2754 
2755 	*domainname = NULL;
2756 	*errorp = NULL;
2757 
2758 	/* Initialize State machine cookie */
2759 	cookie = init_search_state_machine();
2760 	if (cookie == NULL) {
2761 		return (NS_LDAP_MEMORY);
2762 	}
2763 
2764 	/* see if need to follow referrals */
2765 	rc = __s_api_toFollowReferrals(flags,
2766 	    &cookie->followRef, errorp);
2767 	if (rc != NS_LDAP_SUCCESS) {
2768 		delete_search_cookie(cookie);
2769 		return (rc);
2770 	}
2771 
2772 	/* Create default service Desc */
2773 	sdlist = (ns_ldap_search_desc_t **)calloc(2,
2774 	    sizeof (ns_ldap_search_desc_t *));
2775 	if (sdlist == NULL) {
2776 		delete_search_cookie(cookie);
2777 		cookie = NULL;
2778 		return (NS_LDAP_MEMORY);
2779 	}
2780 	dptr = (ns_ldap_search_desc_t *)
2781 	    calloc(1, sizeof (ns_ldap_search_desc_t));
2782 	if (dptr == NULL) {
2783 		free(sdlist);
2784 		delete_search_cookie(cookie);
2785 		cookie = NULL;
2786 		return (NS_LDAP_MEMORY);
2787 	}
2788 	sdlist[0] = dptr;
2789 
2790 	/* search base is dn */
2791 	dptr->basedn = strdup(dn);
2792 
2793 	/* search scope is base */
2794 	dptr->scope = NS_LDAP_SCOPE_BASE;
2795 
2796 	/* search filter is "nisdomain=*" */
2797 	dptr->filter = strdup(_NIS_FILTER);
2798 
2799 	cookie->sdlist = sdlist;
2800 	cookie->i_filter = strdup(dptr->filter);
2801 	cookie->i_attr = nis_domain_attrs;
2802 	cookie->i_auth = cred;
2803 	cookie->i_flags = 0;
2804 
2805 	/* Process search */
2806 	rc = search_state_machine(cookie, INIT, 0);
2807 
2808 	/* Copy domain name if found */
2809 	rc = cookie->err_rc;
2810 	if (rc != NS_LDAP_SUCCESS)
2811 		*errorp = cookie->errorp;
2812 	if (cookie->result == NULL)
2813 		rc = NS_LDAP_NOTFOUND;
2814 	if (rc == NS_LDAP_SUCCESS) {
2815 		value = __ns_ldap_getAttr(cookie->result->entry,
2816 		    _NIS_DOMAIN);
2817 		if (value[0])
2818 			*domainname = strdup(value[0]);
2819 		else
2820 			rc = NS_LDAP_NOTFOUND;
2821 	}
2822 	if (cookie->result != NULL)
2823 		(void) __ns_ldap_freeResult(&cookie->result);
2824 	cookie->errorp = NULL;
2825 	delete_search_cookie(cookie);
2826 	cookie = NULL;
2827 	return (rc);
2828 }
2829 
2830 int
2831 __ns_ldap_firstEntry(
2832 	const char *service,
2833 	const char *filter,
2834 	int (*init_filter_cb)(const ns_ldap_search_desc_t *desc,
2835 	char **realfilter, const void *userdata),
2836 	const char * const *attribute,
2837 	const ns_cred_t *auth,
2838 	const int flags,
2839 	void **vcookie,
2840 	ns_ldap_result_t **result,
2841 	ns_ldap_error_t ** errorp,
2842 	const void *userdata)
2843 {
2844 	ns_ldap_cookie_t	*cookie = NULL;
2845 	ns_ldap_error_t		*error = NULL;
2846 	ns_state_t		state;
2847 	ns_ldap_search_desc_t	**sdlist;
2848 	ns_ldap_search_desc_t	*dptr;
2849 	char			**dns = NULL;
2850 	int			scope;
2851 	int			rc;
2852 
2853 	*errorp = NULL;
2854 	*result = NULL;
2855 
2856 	/* get the service descriptor - or create a default one */
2857 	rc = __s_api_get_SSD_from_SSDtoUse_service(service,
2858 	    &sdlist, errorp);
2859 	if (rc != NS_LDAP_SUCCESS) {
2860 		*errorp = error;
2861 		return (rc);
2862 	}
2863 	if (sdlist == NULL) {
2864 		/* Create default service Desc */
2865 		sdlist = (ns_ldap_search_desc_t **)calloc(2,
2866 		    sizeof (ns_ldap_search_desc_t *));
2867 		if (sdlist == NULL) {
2868 			return (NS_LDAP_MEMORY);
2869 		}
2870 		dptr = (ns_ldap_search_desc_t *)
2871 		    calloc(1, sizeof (ns_ldap_search_desc_t));
2872 		if (dptr == NULL) {
2873 			free(sdlist);
2874 			return (NS_LDAP_MEMORY);
2875 		}
2876 		sdlist[0] = dptr;
2877 
2878 		/* default base */
2879 		rc = __s_api_getDNs(&dns, service, &error);
2880 		if (rc != NS_LDAP_SUCCESS) {
2881 			if (dns) {
2882 				__s_api_free2dArray(dns);
2883 				dns = NULL;
2884 			}
2885 			if (sdlist) {
2886 				(void) __ns_ldap_freeSearchDescriptors(
2887 				    &sdlist);
2888 
2889 				sdlist = NULL;
2890 			}
2891 			*errorp = error;
2892 			return (rc);
2893 		}
2894 		dptr->basedn = strdup(dns[0]);
2895 		__s_api_free2dArray(dns);
2896 		dns = NULL;
2897 
2898 		/* default scope */
2899 		scope = 0;
2900 		cookie = init_search_state_machine();
2901 		if (cookie == NULL) {
2902 			if (sdlist) {
2903 				(void) __ns_ldap_freeSearchDescriptors(&sdlist);
2904 				sdlist = NULL;
2905 			}
2906 			return (NS_LDAP_MEMORY);
2907 		}
2908 		rc = __s_api_getSearchScope(&scope, &cookie->errorp);
2909 		dptr->scope = scope;
2910 	}
2911 
2912 	/* Initialize State machine cookie */
2913 	if (cookie == NULL)
2914 		cookie = init_search_state_machine();
2915 	if (cookie == NULL) {
2916 		if (sdlist) {
2917 			(void) __ns_ldap_freeSearchDescriptors(&sdlist);
2918 			sdlist = NULL;
2919 		}
2920 		return (NS_LDAP_MEMORY);
2921 	}
2922 
2923 	cookie->sdlist = sdlist;
2924 
2925 	/* see if need to follow referrals */
2926 	rc = __s_api_toFollowReferrals(flags,
2927 	    &cookie->followRef, errorp);
2928 	if (rc != NS_LDAP_SUCCESS) {
2929 		delete_search_cookie(cookie);
2930 		return (rc);
2931 	}
2932 
2933 	/*
2934 	 * use VLV/PAGE control only if NS_LDAP_NO_PAGE_CTRL is not set
2935 	 */
2936 	if (flags & NS_LDAP_NO_PAGE_CTRL)
2937 		cookie->use_paging = FALSE;
2938 	else
2939 		cookie->use_paging = TRUE;
2940 
2941 	/* Set up other arguments */
2942 	cookie->userdata = userdata;
2943 	if (init_filter_cb != NULL) {
2944 		cookie->init_filter_cb = init_filter_cb;
2945 		cookie->use_filtercb = 1;
2946 	}
2947 	cookie->use_usercb = 0;
2948 	if (service) {
2949 		cookie->service = strdup(service);
2950 		if (cookie->service == NULL) {
2951 			delete_search_cookie(cookie);
2952 			return (NS_LDAP_MEMORY);
2953 		}
2954 	}
2955 
2956 	cookie->i_filter = strdup(filter);
2957 	cookie->i_attr = attribute;
2958 	cookie->i_auth = auth;
2959 	cookie->i_flags = flags;
2960 
2961 	state = INIT;
2962 	for (;;) {
2963 		state = search_state_machine(cookie, state, ONE_STEP);
2964 		switch (state) {
2965 		case PROCESS_RESULT:
2966 			*result = cookie->result;
2967 			cookie->result = NULL;
2968 			*vcookie = (void *)cookie;
2969 			return (NS_LDAP_SUCCESS);
2970 		case ERROR:
2971 		case LDAP_ERROR:
2972 			rc = cookie->err_rc;
2973 			*errorp = cookie->errorp;
2974 			cookie->errorp = NULL;
2975 			delete_search_cookie(cookie);
2976 			return (rc);
2977 		case EXIT:
2978 			rc = cookie->err_rc;
2979 			if (rc != NS_LDAP_SUCCESS) {
2980 				*errorp = cookie->errorp;
2981 				cookie->errorp = NULL;
2982 			} else {
2983 				rc = NS_LDAP_NOTFOUND;
2984 			}
2985 
2986 			delete_search_cookie(cookie);
2987 			return (rc);
2988 
2989 		default:
2990 			break;
2991 		}
2992 	}
2993 }
2994 
2995 /*ARGSUSED2*/
2996 int
2997 __ns_ldap_nextEntry(
2998 	void *vcookie,
2999 	ns_ldap_result_t **result,
3000 	ns_ldap_error_t ** errorp)
3001 {
3002 	ns_ldap_cookie_t	*cookie;
3003 	ns_state_t		state;
3004 	int			rc;
3005 
3006 	cookie = (ns_ldap_cookie_t *)vcookie;
3007 	cookie->result = NULL;
3008 	*result = NULL;
3009 
3010 	state = END_PROCESS_RESULT;
3011 	for (;;) {
3012 		/*
3013 		 * if the ldap connection being used is shared,
3014 		 * ensure the thread-specific data area for setting
3015 		 * status is allocated
3016 		 */
3017 		if (cookie->conn->shared > 0) {
3018 			rc = __s_api_check_MTC_tsd();
3019 			if (rc != NS_LDAP_SUCCESS)
3020 				return (rc);
3021 		}
3022 
3023 		state = search_state_machine(cookie, state, ONE_STEP);
3024 		switch (state) {
3025 		case PROCESS_RESULT:
3026 			*result = cookie->result;
3027 			cookie->result = NULL;
3028 			return (NS_LDAP_SUCCESS);
3029 		case ERROR:
3030 		case LDAP_ERROR:
3031 			rc = cookie->err_rc;
3032 			*errorp = cookie->errorp;
3033 			cookie->errorp = NULL;
3034 			return (rc);
3035 		case EXIT:
3036 			return (NS_LDAP_SUCCESS);
3037 		}
3038 	}
3039 }
3040 
3041 int
3042 __ns_ldap_endEntry(
3043 	void **vcookie,
3044 	ns_ldap_error_t ** errorp)
3045 {
3046 	ns_ldap_cookie_t	*cookie;
3047 	int			rc;
3048 
3049 	if (*vcookie == NULL)
3050 		return (NS_LDAP_INVALID_PARAM);
3051 
3052 	cookie = (ns_ldap_cookie_t *)(*vcookie);
3053 	cookie->result = NULL;
3054 
3055 	/* Complete search */
3056 	rc = search_state_machine(cookie, CLEAR_RESULTS, 0);
3057 
3058 	/* Copy results back to user */
3059 	rc = cookie->err_rc;
3060 	if (rc != NS_LDAP_SUCCESS)
3061 		*errorp = cookie->errorp;
3062 
3063 	cookie->errorp = NULL;
3064 	delete_search_cookie(cookie);
3065 	cookie = NULL;
3066 	*vcookie = NULL;
3067 
3068 	return (rc);
3069 }
3070 
3071 
3072 int
3073 __ns_ldap_freeResult(ns_ldap_result_t **result)
3074 {
3075 
3076 	ns_ldap_entry_t	*curEntry = NULL;
3077 	ns_ldap_entry_t	*delEntry = NULL;
3078 	int		i;
3079 	ns_ldap_result_t	*res = *result;
3080 
3081 #ifdef DEBUG
3082 	(void) fprintf(stderr, "__ns_ldap_freeResult START\n");
3083 #endif
3084 	if (res == NULL)
3085 		return (NS_LDAP_INVALID_PARAM);
3086 
3087 	if (res->entry != NULL)
3088 		curEntry = res->entry;
3089 
3090 	for (i = 0; i < res->entries_count; i++) {
3091 		if (curEntry != NULL) {
3092 			delEntry = curEntry;
3093 			curEntry = curEntry->next;
3094 			__ns_ldap_freeEntry(delEntry);
3095 		}
3096 	}
3097 
3098 	free(res);
3099 	*result = NULL;
3100 	return (NS_LDAP_SUCCESS);
3101 }
3102 
3103 /*ARGSUSED*/
3104 int
3105 __ns_ldap_auth(const ns_cred_t *auth,
3106 		    const int flags,
3107 		    ns_ldap_error_t **errorp,
3108 		    LDAPControl **serverctrls,
3109 		    LDAPControl **clientctrls)
3110 {
3111 
3112 	ConnectionID	connectionId = -1;
3113 	Connection	*conp;
3114 	int		rc = 0;
3115 	int		do_not_fail_if_new_pwd_reqd = 0;
3116 	int		nopasswd_acct_mgmt = 0;
3117 
3118 
3119 #ifdef DEBUG
3120 	(void) fprintf(stderr, "__ns_ldap_auth START\n");
3121 #endif
3122 
3123 	*errorp = NULL;
3124 	if (!auth)
3125 		return (NS_LDAP_INVALID_PARAM);
3126 
3127 	rc = __s_api_getConnection(NULL, flags | NS_LDAP_NEW_CONN,
3128 	    auth, &connectionId, &conp, errorp,
3129 	    do_not_fail_if_new_pwd_reqd, nopasswd_acct_mgmt);
3130 	if (rc == NS_LDAP_OP_FAILED && *errorp)
3131 		(void) __ns_ldap_freeError(errorp);
3132 
3133 	if (connectionId > -1)
3134 		DropConnection(connectionId, flags);
3135 	return (rc);
3136 }
3137 
3138 char **
3139 __ns_ldap_getAttr(const ns_ldap_entry_t *entry, const char *attrname)
3140 {
3141 	int	i;
3142 
3143 	if (entry == NULL)
3144 		return (NULL);
3145 	for (i = 0; i < entry->attr_count; i++) {
3146 		if (strcasecmp(entry->attr_pair[i]->attrname, attrname) == NULL)
3147 			return (entry->attr_pair[i]->attrvalue);
3148 	}
3149 	return (NULL);
3150 }
3151 
3152 ns_ldap_attr_t *
3153 __ns_ldap_getAttrStruct(const ns_ldap_entry_t *entry, const char *attrname)
3154 {
3155 	int	i;
3156 
3157 	if (entry == NULL)
3158 		return (NULL);
3159 	for (i = 0; i < entry->attr_count; i++) {
3160 		if (strcasecmp(entry->attr_pair[i]->attrname, attrname) == NULL)
3161 			return (entry->attr_pair[i]);
3162 	}
3163 	return (NULL);
3164 }
3165 
3166 
3167 /*ARGSUSED*/
3168 int
3169 __ns_ldap_uid2dn(const char *uid,
3170 		char **userDN,
3171 		const ns_cred_t *cred,	/* cred is ignored */
3172 		ns_ldap_error_t **errorp)
3173 {
3174 	ns_ldap_result_t	*result = NULL;
3175 	char		*filter, *userdata;
3176 	char		errstr[MAXERROR];
3177 	char		**value;
3178 	int		rc = 0;
3179 	int		i = 0;
3180 	size_t		len;
3181 
3182 	*errorp = NULL;
3183 	*userDN = NULL;
3184 	if ((uid == NULL) || (uid[0] == '\0'))
3185 		return (NS_LDAP_INVALID_PARAM);
3186 
3187 	while (uid[i] != '\0') {
3188 		if (uid[i] == '=') {
3189 			*userDN = strdup(uid);
3190 			return (NS_LDAP_SUCCESS);
3191 		}
3192 		i++;
3193 	}
3194 	i = 0;
3195 	while ((uid[i] != '\0') && (isdigit(uid[i])))
3196 		i++;
3197 	if (uid[i] == '\0') {
3198 		len = strlen(UIDNUMFILTER) + strlen(uid) + 1;
3199 		filter = (char *)malloc(len);
3200 		if (filter == NULL) {
3201 			*userDN = NULL;
3202 			return (NS_LDAP_MEMORY);
3203 		}
3204 		(void) snprintf(filter, len, UIDNUMFILTER, uid);
3205 
3206 		len = strlen(UIDNUMFILTER_SSD) + strlen(uid) + 1;
3207 		userdata = (char *)malloc(len);
3208 		if (userdata == NULL) {
3209 			*userDN = NULL;
3210 			return (NS_LDAP_MEMORY);
3211 		}
3212 		(void) snprintf(userdata, len, UIDNUMFILTER_SSD, uid);
3213 	} else {
3214 		len = strlen(UIDFILTER) + strlen(uid) + 1;
3215 		filter = (char *)malloc(len);
3216 		if (filter == NULL) {
3217 			*userDN = NULL;
3218 			return (NS_LDAP_MEMORY);
3219 		}
3220 		(void) snprintf(filter, len, UIDFILTER, uid);
3221 
3222 		len = strlen(UIDFILTER_SSD) + strlen(uid) + 1;
3223 		userdata = (char *)malloc(len);
3224 		if (userdata == NULL) {
3225 			*userDN = NULL;
3226 			return (NS_LDAP_MEMORY);
3227 		}
3228 		(void) snprintf(userdata, len, UIDFILTER_SSD, uid);
3229 	}
3230 
3231 	/*
3232 	 * we want to retrieve the DN as it appears in LDAP
3233 	 * hence the use of NS_LDAP_NOT_CVT_DN in flags
3234 	 */
3235 	rc = __ns_ldap_list("passwd", filter,
3236 	    __s_api_merge_SSD_filter,
3237 	    NULL, cred, NS_LDAP_NOT_CVT_DN,
3238 	    &result, errorp, NULL,
3239 	    userdata);
3240 	free(filter);
3241 	filter = NULL;
3242 	free(userdata);
3243 	userdata = NULL;
3244 	if (rc != NS_LDAP_SUCCESS) {
3245 		if (result) {
3246 			(void) __ns_ldap_freeResult(&result);
3247 			result = NULL;
3248 		}
3249 		return (rc);
3250 	}
3251 	if (result->entries_count > 1) {
3252 		(void) __ns_ldap_freeResult(&result);
3253 		result = NULL;
3254 		*userDN = NULL;
3255 		(void) sprintf(errstr,
3256 		    gettext("Too many entries are returned for %s"), uid);
3257 		MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL, strdup(errstr),
3258 		    NULL);
3259 		return (NS_LDAP_INTERNAL);
3260 	}
3261 
3262 	value = __ns_ldap_getAttr(result->entry, "dn");
3263 	*userDN = strdup(value[0]);
3264 	(void) __ns_ldap_freeResult(&result);
3265 	result = NULL;
3266 	return (NS_LDAP_SUCCESS);
3267 }
3268 
3269 
3270 /*ARGSUSED*/
3271 int
3272 __ns_ldap_host2dn(const char *host,
3273 		const char *domain,
3274 		char **hostDN,
3275 		const ns_cred_t *cred,	/* cred is ignored */
3276 		ns_ldap_error_t **errorp)
3277 {
3278 	ns_ldap_result_t	*result = NULL;
3279 	char		*filter, *userdata;
3280 	char		errstr[MAXERROR];
3281 	char		**value;
3282 	int		rc;
3283 	size_t		len;
3284 
3285 /*
3286  * XXX
3287  * the domain parameter needs to be used in case domain is not local, if
3288  * this routine is to support multi domain setups, it needs lots of work...
3289  */
3290 	*errorp = NULL;
3291 	*hostDN = NULL;
3292 	if ((host == NULL) || (host[0] == '\0'))
3293 		return (NS_LDAP_INVALID_PARAM);
3294 
3295 	len = strlen(HOSTFILTER) + strlen(host) + 1;
3296 	filter = (char *)malloc(len);
3297 	if (filter == NULL) {
3298 		return (NS_LDAP_MEMORY);
3299 	}
3300 	(void) snprintf(filter,	len, HOSTFILTER, host);
3301 
3302 	len = strlen(HOSTFILTER_SSD) + strlen(host) + 1;
3303 	userdata = (char *)malloc(len);
3304 	if (userdata == NULL) {
3305 		return (NS_LDAP_MEMORY);
3306 	}
3307 	(void) snprintf(userdata, len, HOSTFILTER_SSD, host);
3308 
3309 	/*
3310 	 * we want to retrieve the DN as it appears in LDAP
3311 	 * hence the use of NS_LDAP_NOT_CVT_DN in flags
3312 	 */
3313 	rc = __ns_ldap_list("hosts", filter,
3314 	    __s_api_merge_SSD_filter,
3315 	    NULL, cred, NS_LDAP_NOT_CVT_DN, &result,
3316 	    errorp, NULL,
3317 	    userdata);
3318 	free(filter);
3319 	filter = NULL;
3320 	free(userdata);
3321 	userdata = NULL;
3322 	if (rc != NS_LDAP_SUCCESS) {
3323 		if (result) {
3324 			(void) __ns_ldap_freeResult(&result);
3325 			result = NULL;
3326 		}
3327 		return (rc);
3328 	}
3329 
3330 	if (result->entries_count > 1) {
3331 		(void) __ns_ldap_freeResult(&result);
3332 		result = NULL;
3333 		*hostDN = NULL;
3334 		(void) sprintf(errstr,
3335 		    gettext("Too many entries are returned for %s"), host);
3336 		MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL, strdup(errstr),
3337 		    NULL);
3338 		return (NS_LDAP_INTERNAL);
3339 	}
3340 
3341 	value = __ns_ldap_getAttr(result->entry, "dn");
3342 	*hostDN = strdup(value[0]);
3343 	(void) __ns_ldap_freeResult(&result);
3344 	result = NULL;
3345 	return (NS_LDAP_SUCCESS);
3346 }
3347 
3348 /*ARGSUSED*/
3349 int
3350 __ns_ldap_dn2domain(const char *dn,
3351 			char **domain,
3352 			const ns_cred_t *cred,
3353 			ns_ldap_error_t **errorp)
3354 {
3355 	int		rc, pnum, i, j, len = 0;
3356 	char		*newdn, **rdns = NULL;
3357 	char		**dns, *dn1;
3358 
3359 	*errorp = NULL;
3360 
3361 	if (domain == NULL)
3362 		return (NS_LDAP_INVALID_PARAM);
3363 	else
3364 		*domain = NULL;
3365 
3366 	if ((dn == NULL) || (dn[0] == '\0'))
3367 		return (NS_LDAP_INVALID_PARAM);
3368 
3369 	/*
3370 	 * break dn into rdns
3371 	 */
3372 	dn1 = strdup(dn);
3373 	if (dn1 == NULL)
3374 		return (NS_LDAP_MEMORY);
3375 	rdns = ldap_explode_dn(dn1, 0);
3376 	free(dn1);
3377 	if (rdns == NULL || *rdns == NULL)
3378 		return (NS_LDAP_INVALID_PARAM);
3379 
3380 	for (i = 0; rdns[i]; i++)
3381 		len += strlen(rdns[i]) + 1;
3382 	pnum = i;
3383 
3384 	newdn = (char *)malloc(len + 1);
3385 	dns = (char **)calloc(pnum, sizeof (char *));
3386 	if (newdn == NULL || dns == NULL) {
3387 		if (newdn)
3388 			free(newdn);
3389 		ldap_value_free(rdns);
3390 		return (NS_LDAP_MEMORY);
3391 	}
3392 
3393 	/* construct a semi-normalized dn, newdn */
3394 	*newdn = '\0';
3395 	for (i = 0; rdns[i]; i++) {
3396 		dns[i] = newdn + strlen(newdn);
3397 		(void) strcat(newdn,
3398 		    __s_api_remove_rdn_space(rdns[i]));
3399 		(void) strcat(newdn, ",");
3400 	}
3401 	/* remove the last ',' */
3402 	newdn[strlen(newdn) - 1] = '\0';
3403 	ldap_value_free(rdns);
3404 
3405 	/*
3406 	 * loop and find the domain name associated with newdn,
3407 	 * removing rdn one by one from left to right
3408 	 */
3409 	for (i = 0; i < pnum; i++) {
3410 
3411 		if (*errorp)
3412 			(void) __ns_ldap_freeError(errorp);
3413 
3414 		/*
3415 		 *  try cache manager first
3416 		 */
3417 		rc = __s_api_get_cachemgr_data(NS_CACHE_DN2DOMAIN,
3418 		    dns[i], domain);
3419 		if (rc != NS_LDAP_SUCCESS) {
3420 			/*
3421 			 *  try ldap server second
3422 			 */
3423 			rc = __s_api_find_domainname(dns[i], domain,
3424 			    cred, errorp);
3425 		} else {
3426 			/*
3427 			 * skip the last one,
3428 			 * since it is already cached by ldap_cachemgr
3429 			 */
3430 			i--;
3431 		}
3432 		if (rc == NS_LDAP_SUCCESS) {
3433 			/*
3434 			 * ask cache manager to save the
3435 			 * dn to domain mapping(s)
3436 			 */
3437 			for (j = 0; j <= i; j++) {
3438 				(void) __s_api_set_cachemgr_data(
3439 				    NS_CACHE_DN2DOMAIN,
3440 				    dns[j],
3441 				    *domain);
3442 			}
3443 			break;
3444 		}
3445 	}
3446 
3447 	free(dns);
3448 	free(newdn);
3449 	if (rc != NS_LDAP_SUCCESS)
3450 		rc = NS_LDAP_NOTFOUND;
3451 	return (rc);
3452 }
3453 
3454 /*ARGSUSED*/
3455 int
3456 __ns_ldap_getServiceAuthMethods(const char *service,
3457 		ns_auth_t ***auth,
3458 		ns_ldap_error_t **errorp)
3459 {
3460 	char		errstr[MAXERROR];
3461 	int		rc, i, done = 0;
3462 	int		slen;
3463 	void		**param;
3464 	char		**sam, *srv, *send;
3465 	ns_auth_t	**authpp = NULL, *ap;
3466 	int		cnt, max;
3467 	ns_config_t	*cfg;
3468 	ns_ldap_error_t	*error = NULL;
3469 
3470 	if (errorp == NULL)
3471 		return (NS_LDAP_INVALID_PARAM);
3472 	*errorp = NULL;
3473 
3474 	if ((service == NULL) || (service[0] == '\0') ||
3475 	    (auth == NULL))
3476 		return (NS_LDAP_INVALID_PARAM);
3477 
3478 	*auth = NULL;
3479 	rc = __ns_ldap_getParam(NS_LDAP_SERVICE_AUTH_METHOD_P, &param, &error);
3480 	if (rc != NS_LDAP_SUCCESS || param == NULL) {
3481 		*errorp = error;
3482 		return (rc);
3483 	}
3484 	sam = (char **)param;
3485 
3486 	cfg = __s_api_get_default_config();
3487 	cnt = 0;
3488 
3489 	slen = strlen(service);
3490 
3491 	for (; *sam; sam++) {
3492 		srv = *sam;
3493 		if (strncasecmp(service, srv, slen) != 0)
3494 			continue;
3495 		srv += slen;
3496 		if (*srv != COLONTOK)
3497 			continue;
3498 		send = srv;
3499 		srv++;
3500 		for (max = 1; (send = strchr(++send, SEMITOK)) != NULL;
3501 		    max++) {}
3502 		authpp = (ns_auth_t **)calloc(++max, sizeof (ns_auth_t *));
3503 		if (authpp == NULL) {
3504 			(void) __ns_ldap_freeParam(&param);
3505 			__s_api_release_config(cfg);
3506 			return (NS_LDAP_MEMORY);
3507 		}
3508 		while (!done) {
3509 			send = strchr(srv, SEMITOK);
3510 			if (send != NULL) {
3511 				*send = '\0';
3512 				send++;
3513 			}
3514 			i = __s_get_enum_value(cfg, srv, NS_LDAP_AUTH_P);
3515 			if (i == -1) {
3516 				(void) __ns_ldap_freeParam(&param);
3517 				(void) sprintf(errstr,
3518 				gettext("Unsupported "
3519 				    "serviceAuthenticationMethod: %s.\n"), srv);
3520 				MKERROR(LOG_WARNING, *errorp, NS_CONFIG_SYNTAX,
3521 				    strdup(errstr), NULL);
3522 				__s_api_release_config(cfg);
3523 				return (NS_LDAP_CONFIG);
3524 			}
3525 			ap = __s_api_AuthEnumtoStruct((EnumAuthType_t)i);
3526 			if (ap == NULL) {
3527 				(void) __ns_ldap_freeParam(&param);
3528 				__s_api_release_config(cfg);
3529 				return (NS_LDAP_MEMORY);
3530 			}
3531 			authpp[cnt++] = ap;
3532 			if (send == NULL)
3533 				done = TRUE;
3534 			else
3535 				srv = send;
3536 		}
3537 	}
3538 
3539 	*auth = authpp;
3540 	(void) __ns_ldap_freeParam(&param);
3541 	__s_api_release_config(cfg);
3542 	return (NS_LDAP_SUCCESS);
3543 }
3544 
3545 /*
3546  * This routine is called when certain scenario occurs
3547  * e.g.
3548  * service == auto_home
3549  * SSD = automount: ou = mytest,
3550  * NS_LDAP_MAPATTRIBUTE= auto_home: automountMapName=AAA
3551  * NS_LDAP_OBJECTCLASSMAP= auto_home:automountMap=MynisMap
3552  * NS_LDAP_OBJECTCLASSMAP= auto_home:automount=MynisObject
3553  *
3554  * The automountMapName is prepended implicitely but is mapped
3555  * to AAA. So dn could appers as
3556  * dn: AAA=auto_home,ou=bar,dc=foo,dc=com
3557  * dn: automountKey=user_01,AAA=auto_home,ou=bar,dc=foo,dc=com
3558  * dn: automountKey=user_02,AAA=auto_home,ou=bar,dc=foo,dc=com
3559  * in the directory.
3560  * This function is called to covert the mapped attr back to
3561  * orig attr when the entries are searched and returned
3562  */
3563 
3564 int
3565 __s_api_convert_automountmapname(const char *service, char **dn,
3566 		ns_ldap_error_t **errp) {
3567 
3568 	char	**mapping = NULL;
3569 	char	*mapped_attr = NULL;
3570 	char	*automountmapname = "automountMapName";
3571 	char	*buffer = NULL;
3572 	int	rc = NS_LDAP_SUCCESS;
3573 	char	errstr[MAXERROR];
3574 
3575 	/*
3576 	 * dn is an input/out parameter, check it first
3577 	 */
3578 
3579 	if (service == NULL || dn == NULL || *dn == NULL)
3580 		return (NS_LDAP_INVALID_PARAM);
3581 
3582 	/*
3583 	 * Check to see if there is a mapped attribute for auto_xxx
3584 	 */
3585 
3586 	mapping = __ns_ldap_getMappedAttributes(service, automountmapname);
3587 
3588 	/*
3589 	 * if no mapped attribute for auto_xxx, try automount
3590 	 */
3591 
3592 	if (mapping == NULL)
3593 		mapping = __ns_ldap_getMappedAttributes(
3594 			"automount", automountmapname);
3595 
3596 	/*
3597 	 * if no mapped attribute is found, return SUCCESS (no op)
3598 	 */
3599 
3600 	if (mapping == NULL)
3601 		return (NS_LDAP_SUCCESS);
3602 
3603 	/*
3604 	 * if the mapped attribute is found and attr is not empty,
3605 	 * copy it
3606 	 */
3607 
3608 	if (mapping[0] != NULL) {
3609 		mapped_attr = strdup(mapping[0]);
3610 		__s_api_free2dArray(mapping);
3611 		if (mapped_attr == NULL) {
3612 			return (NS_LDAP_MEMORY);
3613 		}
3614 	} else {
3615 		__s_api_free2dArray(mapping);
3616 
3617 		(void) snprintf(errstr, (2 * MAXERROR),
3618 			gettext(
3619 			"Attribute nisMapName is mapped to an "
3620 			"empty string.\n"));
3621 
3622 		MKERROR(LOG_ERR, *errp, NS_CONFIG_SYNTAX,
3623 			strdup(errstr), NULL);
3624 
3625 		return (NS_LDAP_CONFIG);
3626 	}
3627 
3628 	/*
3629 	 * Locate the mapped attribute in the dn
3630 	 * and replace it if it exists
3631 	 */
3632 
3633 	rc = __s_api_replace_mapped_attr_in_dn(
3634 		(const char *) automountmapname, (const char *) mapped_attr,
3635 		(const char *) *dn, &buffer);
3636 
3637 	/* clean up */
3638 
3639 	free(mapped_attr);
3640 
3641 	/*
3642 	 * If mapped attr is found(buffer != NULL)
3643 	 *	a new dn is returned
3644 	 * If no mapped attribute is in dn,
3645 	 *	return NS_LDAP_SUCCESS (no op)
3646 	 * If no memory,
3647 	 *	return NS_LDAP_MEMORY (no op)
3648 	 */
3649 
3650 	if (buffer != NULL) {
3651 		free(*dn);
3652 		*dn = buffer;
3653 	}
3654 
3655 	return (rc);
3656 }
3657 
3658 /*
3659  * If the mapped attr is found in the dn,
3660  * 	return NS_LDAP_SUCCESS and a new_dn.
3661  * If no mapped attr is found,
3662  * 	return NS_LDAP_SUCCESS and *new_dn == NULL
3663  * If there is not enough memory,
3664  * 	return NS_LDAP_MEMORY and *new_dn == NULL
3665  */
3666 
3667 int
3668 __s_api_replace_mapped_attr_in_dn(
3669 	const char *orig_attr, const char *mapped_attr,
3670 	const char *dn, char **new_dn) {
3671 
3672 	char	**dnArray = NULL;
3673 	char	*cur = NULL, *start = NULL;
3674 	int	i = 0, found = 0;
3675 	int	len = 0, orig_len = 0, mapped_len = 0;
3676 	int	dn_len = 0, tmp_len = 0;
3677 
3678 	*new_dn = NULL;
3679 
3680 	/*
3681 	 * seperate dn into individual componets
3682 	 * e.g.
3683 	 * "automountKey=user_01" , "automountMapName_test=auto_home", ...
3684 	 */
3685 	dnArray = ldap_explode_dn(dn, 0);
3686 
3687 	/*
3688 	 * This will find "mapped attr=value" in dn.
3689 	 * It won't find match if mapped attr appears
3690 	 * in the value.
3691 	 */
3692 	for (i = 0; dnArray[i] != NULL; i++) {
3693 		/*
3694 		 * This function is called when reading from
3695 		 * the directory so assume each component has "=".
3696 		 * Any ill formatted dn should be rejected
3697 		 * before adding to the directory
3698 		 */
3699 		cur = strchr(dnArray[i], '=');
3700 		*cur = '\0';
3701 		if (strcasecmp(mapped_attr, dnArray[i]) == 0)
3702 			found = 1;
3703 		*cur = '=';
3704 		if (found) break;
3705 	}
3706 
3707 	if (!found) {
3708 		__s_api_free2dArray(dnArray);
3709 		*new_dn = NULL;
3710 		return (NS_LDAP_SUCCESS);
3711 	}
3712 	/*
3713 	 * The new length is *dn length + (difference between
3714 	 * orig attr and mapped attr) + 1 ;
3715 	 * e.g.
3716 	 * automountKey=aa,automountMapName_test=auto_home,dc=foo,dc=com
3717 	 * ==>
3718 	 * automountKey=aa,automountMapName=auto_home,dc=foo,dc=com
3719 	 */
3720 	mapped_len = strlen(mapped_attr);
3721 	orig_len = strlen(orig_attr);
3722 	dn_len = strlen(dn);
3723 	len = dn_len + orig_len - mapped_len + 1;
3724 	*new_dn = (char *)calloc(1, len);
3725 	if (*new_dn == NULL) {
3726 		__s_api_free2dArray(dnArray);
3727 		return (NS_LDAP_MEMORY);
3728 	}
3729 
3730 	/*
3731 	 * Locate the mapped attr in the dn.
3732 	 * Use dnArray[i] instead of mapped_attr
3733 	 * because mapped_attr could appear in
3734 	 * the value
3735 	 */
3736 
3737 	cur = strstr(dn, dnArray[i]);
3738 	__s_api_free2dArray(dnArray);
3739 	/* copy the portion before mapped attr in dn  */
3740 	start = *new_dn;
3741 	tmp_len = cur - dn;
3742 	(void) memcpy((void *) start, (const void*) dn, tmp_len);
3743 
3744 	/*
3745 	 * Copy the orig_attr. e.g. automountMapName
3746 	 * This replaces mapped attr with orig attr
3747 	 */
3748 	start = start + (cur - dn); /* move cursor in buffer */
3749 	(void) memcpy((void *) start, (const void*) orig_attr, orig_len);
3750 
3751 	/*
3752 	 * Copy the portion after mapped attr in dn
3753 	 */
3754 	cur = cur + mapped_len; /* move cursor in  dn  */
3755 	start = start + orig_len; /* move cursor in buffer */
3756 	(void) strcpy(start, cur);
3757 
3758 	return (NS_LDAP_SUCCESS);
3759 }
3760 
3761 /*
3762  * Validate Filter functions
3763  */
3764 
3765 /* ***** Start of modified libldap.so.5 filter parser ***** */
3766 
3767 /* filter parsing routine forward references */
3768 static int adj_filter_list(char *str);
3769 static int adj_simple_filter(char *str);
3770 static int unescape_filterval(char *val);
3771 static int hexchar2int(char c);
3772 static int adj_substring_filter(char *val);
3773 
3774 
3775 /*
3776  * assumes string manipulation is in-line
3777  * and all strings are sufficient in size
3778  * return value is the position after 'c'
3779  */
3780 
3781 static char *
3782 resync_str(char *str, char *next, char c)
3783 {
3784 	char	*ret;
3785 
3786 	ret = str + strlen(str);
3787 	*next = c;
3788 	if (ret == next)
3789 		return (ret);
3790 	(void) strcat(str, next);
3791 	return (ret);
3792 }
3793 
3794 static char *
3795 find_right_paren(char *s)
3796 {
3797 	int	balance, escape;
3798 
3799 	balance = 1;
3800 	escape = 0;
3801 	while (*s && balance) {
3802 		if (escape == 0) {
3803 			if (*s == '(')
3804 				balance++;
3805 			else if (*s == ')')
3806 				balance--;
3807 		}
3808 		if (*s == '\\' && ! escape)
3809 			escape = 1;
3810 		else
3811 			escape = 0;
3812 		if (balance)
3813 			s++;
3814 	}
3815 
3816 	return (*s ? s : NULL);
3817 }
3818 
3819 static char *
3820 adj_complex_filter(char	*str)
3821 {
3822 	char	*next;
3823 
3824 	/*
3825 	 * We have (x(filter)...) with str sitting on
3826 	 * the x.  We have to find the paren matching
3827 	 * the one before the x and put the intervening
3828 	 * filters by calling adj_filter_list().
3829 	 */
3830 
3831 	str++;
3832 	if ((next = find_right_paren(str)) == NULL)
3833 		return (NULL);
3834 
3835 	*next = '\0';
3836 	if (adj_filter_list(str) == -1)
3837 		return (NULL);
3838 	next = resync_str(str, next, ')');
3839 	next++;
3840 
3841 	return (next);
3842 }
3843 
3844 static int
3845 adj_filter(char *str)
3846 {
3847 	char	*next;
3848 	int	parens, balance, escape;
3849 	char	*np, *cp,  *dp;
3850 
3851 	parens = 0;
3852 	while (*str) {
3853 		switch (*str) {
3854 		case '(':
3855 			str++;
3856 			parens++;
3857 			switch (*str) {
3858 			case '&':
3859 				if ((str = adj_complex_filter(str)) == NULL)
3860 					return (-1);
3861 
3862 				parens--;
3863 				break;
3864 
3865 			case '|':
3866 				if ((str = adj_complex_filter(str)) == NULL)
3867 					return (-1);
3868 
3869 				parens--;
3870 				break;
3871 
3872 			case '!':
3873 				if ((str = adj_complex_filter(str)) == NULL)
3874 					return (-1);
3875 
3876 				parens--;
3877 				break;
3878 
3879 			case '(':
3880 				/* illegal ((case - generated by conversion */
3881 
3882 				/* find missing close) */
3883 				np = find_right_paren(str+1);
3884 
3885 				/* error if not found */
3886 				if (np == NULL)
3887 					return (-1);
3888 
3889 				/* remove redundant (and) */
3890 				for (dp = str, cp = str+1; cp < np; ) {
3891 					*dp++ = *cp++;
3892 				}
3893 				cp++;
3894 				while (*cp)
3895 					*dp++ = *cp++;
3896 				*dp = '\0';
3897 
3898 				/* re-start test at original ( */
3899 				parens--;
3900 				str--;
3901 				break;
3902 
3903 			default:
3904 				balance = 1;
3905 				escape = 0;
3906 				next = str;
3907 				while (*next && balance) {
3908 					if (escape == 0) {
3909 						if (*next == '(')
3910 							balance++;
3911 						else if (*next == ')')
3912 							balance--;
3913 					}
3914 					if (*next == '\\' && ! escape)
3915 						escape = 1;
3916 					else
3917 						escape = 0;
3918 					if (balance)
3919 						next++;
3920 				}
3921 				if (balance != 0)
3922 					return (-1);
3923 
3924 				*next = '\0';
3925 				if (adj_simple_filter(str) == -1) {
3926 					return (-1);
3927 				}
3928 				next = resync_str(str, next, ')');
3929 				next++;
3930 				str = next;
3931 				parens--;
3932 				break;
3933 			}
3934 			break;
3935 
3936 		case ')':
3937 			str++;
3938 			parens--;
3939 			break;
3940 
3941 		case ' ':
3942 			str++;
3943 			break;
3944 
3945 		default:	/* assume it's a simple type=value filter */
3946 			next = strchr(str, '\0');
3947 			if (adj_simple_filter(str) == -1) {
3948 				return (-1);
3949 			}
3950 			str = next;
3951 			break;
3952 		}
3953 	}
3954 
3955 	return (parens ? -1 : 0);
3956 }
3957 
3958 
3959 /*
3960  * Put a list of filters like this "(filter1)(filter2)..."
3961  */
3962 
3963 static int
3964 adj_filter_list(char *str)
3965 {
3966 	char	*next;
3967 	char	save;
3968 
3969 	while (*str) {
3970 		while (*str && isspace(*str))
3971 			str++;
3972 		if (*str == '\0')
3973 			break;
3974 
3975 		if ((next = find_right_paren(str + 1)) == NULL)
3976 			return (-1);
3977 		save = *++next;
3978 
3979 		/* now we have "(filter)" with str pointing to it */
3980 		*next = '\0';
3981 		if (adj_filter(str) == -1)
3982 			return (-1);
3983 		next = resync_str(str, next, save);
3984 
3985 		str = next;
3986 	}
3987 
3988 	return (0);
3989 }
3990 
3991 
3992 /*
3993  * is_valid_attr - returns 1 if a is a syntactically valid left-hand side
3994  * of a filter expression, 0 otherwise.  A valid string may contain only
3995  * letters, numbers, hyphens, semi-colons, colons and periods. examples:
3996  *	cn
3997  *	cn;lang-fr
3998  *	1.2.3.4;binary;dynamic
3999  *	mail;dynamic
4000  *	cn:dn:1.2.3.4
4001  *
4002  * For compatibility with older servers, we also allow underscores in
4003  * attribute types, even through they are not allowed by the LDAPv3 RFCs.
4004  */
4005 static int
4006 is_valid_attr(char *a)
4007 {
4008 	for (; *a; a++) {
4009 		if (!isascii(*a)) {
4010 			return (0);
4011 		} else if (!isalnum(*a)) {
4012 			switch (*a) {
4013 			case '-':
4014 			case '.':
4015 			case ';':
4016 			case ':':
4017 			case '_':
4018 				break; /* valid */
4019 			default:
4020 				return (0);
4021 			}
4022 		}
4023 	}
4024 	return (1);
4025 }
4026 
4027 static char *
4028 find_star(char *s)
4029 {
4030 	for (; *s; ++s) {
4031 		switch (*s) {
4032 		case '*':
4033 			return (s);
4034 		case '\\':
4035 			++s;
4036 			if (hexchar2int(s[0]) >= 0 && hexchar2int(s[1]) >= 0)
4037 				++s;
4038 		default:
4039 			break;
4040 		}
4041 	}
4042 	return (NULL);
4043 }
4044 
4045 static int
4046 adj_simple_filter(char *str)
4047 {
4048 	char		*s, *s2, *s3, filterop;
4049 	char		*value;
4050 	int		ftype = 0;
4051 	int		rc;
4052 
4053 	rc = -1;	/* pessimistic */
4054 
4055 	if ((str = strdup(str)) == NULL) {
4056 		return (rc);
4057 	}
4058 
4059 	if ((s = strchr(str, '=')) == NULL) {
4060 		goto free_and_return;
4061 	}
4062 	value = s + 1;
4063 	*s-- = '\0';
4064 	filterop = *s;
4065 	if (filterop == '<' || filterop == '>' || filterop == '~' ||
4066 	    filterop == ':') {
4067 		*s = '\0';
4068 	}
4069 
4070 	if (! is_valid_attr(str)) {
4071 		goto free_and_return;
4072 	}
4073 
4074 	switch (filterop) {
4075 	case '<': /* LDAP_FILTER_LE */
4076 	case '>': /* LDAP_FILTER_GE */
4077 	case '~': /* LDAP_FILTER_APPROX */
4078 		break;
4079 	case ':':	/* extended filter - v3 only */
4080 		/*
4081 		 * extended filter looks like this:
4082 		 *
4083 		 *	[type][':dn'][':'oid]':='value
4084 		 *
4085 		 * where one of type or :oid is required.
4086 		 *
4087 		 */
4088 		s2 = s3 = NULL;
4089 		if ((s2 = strrchr(str, ':')) == NULL) {
4090 			goto free_and_return;
4091 		}
4092 		if (strcasecmp(s2, ":dn") == 0) {
4093 			*s2 = '\0';
4094 		} else {
4095 			*s2 = '\0';
4096 			if ((s3 = strrchr(str, ':')) != NULL) {
4097 				if (strcasecmp(s3, ":dn") != 0) {
4098 					goto free_and_return;
4099 				}
4100 				*s3 = '\0';
4101 			}
4102 		}
4103 		if (unescape_filterval(value) < 0) {
4104 			goto free_and_return;
4105 		}
4106 		rc = 0;
4107 		goto free_and_return;
4108 		/* break; */
4109 	default:
4110 		if (find_star(value) == NULL) {
4111 			ftype = 0; /* LDAP_FILTER_EQUALITY */
4112 		} else if (strcmp(value, "*") == 0) {
4113 			ftype = 1; /* LDAP_FILTER_PRESENT */
4114 		} else {
4115 			rc = adj_substring_filter(value);
4116 			goto free_and_return;
4117 		}
4118 		break;
4119 	}
4120 
4121 	if (ftype != 0) {	/* == LDAP_FILTER_PRESENT */
4122 		rc = 0;
4123 	} else if (unescape_filterval(value) >= 0) {
4124 		rc = 0;
4125 	}
4126 	if (rc != -1) {
4127 		rc = 0;
4128 	}
4129 
4130 free_and_return:
4131 	free(str);
4132 	return (rc);
4133 }
4134 
4135 
4136 /*
4137  * Check in place both LDAPv2 (RFC-1960) and LDAPv3 (hexadecimal) escape
4138  * sequences within the null-terminated string 'val'.
4139  *
4140  * If 'val' contains invalid escape sequences we return -1.
4141  * Otherwise return 1
4142  */
4143 static int
4144 unescape_filterval(char *val)
4145 {
4146 	int	escape, firstdigit;
4147 	char	*s;
4148 
4149 	firstdigit = 0;
4150 	escape = 0;
4151 	for (s = val; *s; s++) {
4152 		if (escape) {
4153 			/*
4154 			 * first try LDAPv3 escape (hexadecimal) sequence
4155 			 */
4156 			if (hexchar2int(*s) < 0) {
4157 				if (firstdigit) {
4158 					/*
4159 					 * LDAPv2 (RFC1960) escape sequence
4160 					 */
4161 					escape = 0;
4162 				} else {
4163 					return (-1);
4164 				}
4165 			}
4166 			if (firstdigit) {
4167 				firstdigit = 0;
4168 			} else {
4169 				escape = 0;
4170 			}
4171 
4172 		} else if (*s != '\\') {
4173 			escape = 0;
4174 
4175 		} else {
4176 			escape = 1;
4177 			firstdigit = 1;
4178 		}
4179 	}
4180 
4181 	return (1);
4182 }
4183 
4184 
4185 /*
4186  * convert character 'c' that represents a hexadecimal digit to an integer.
4187  * if 'c' is not a hexidecimal digit [0-9A-Fa-f], -1 is returned.
4188  * otherwise the converted value is returned.
4189  */
4190 static int
4191 hexchar2int(char c)
4192 {
4193 	if (c >= '0' && c <= '9') {
4194 		return (c - '0');
4195 	}
4196 	if (c >= 'A' && c <= 'F') {
4197 		return (c - 'A' + 10);
4198 	}
4199 	if (c >= 'a' && c <= 'f') {
4200 		return (c - 'a' + 10);
4201 	}
4202 	return (-1);
4203 }
4204 
4205 static int
4206 adj_substring_filter(char *val)
4207 {
4208 	char		*nextstar;
4209 
4210 	for (; val != NULL; val = nextstar) {
4211 		if ((nextstar = find_star(val)) != NULL) {
4212 			*nextstar++ = '\0';
4213 		}
4214 
4215 		if (*val != '\0') {
4216 			if (unescape_filterval(val) < 0) {
4217 				return (-1);
4218 			}
4219 		}
4220 	}
4221 
4222 	return (0);
4223 }
4224 
4225 /* ***** End of modified libldap.so.5 filter parser ***** */
4226 
4227 
4228 /*
4229  * Walk filter, remove redundant parentheses in-line
4230  * verify that the filter is reasonable
4231  */
4232 static int
4233 validate_filter(ns_ldap_cookie_t *cookie)
4234 {
4235 	char			*filter = cookie->filter;
4236 	int			rc;
4237 
4238 	/* Parse filter looking for illegal values */
4239 
4240 	rc = adj_filter(filter);
4241 	if (rc != 0) {
4242 		return (NS_LDAP_OP_FAILED);
4243 	}
4244 
4245 	/* end of filter checking */
4246 
4247 	return (NS_LDAP_SUCCESS);
4248 }
4249 
4250 /*
4251  * Set the account management request control that needs to be sent to server.
4252  * This control is required to get the account management information of
4253  * a user to do local account checking.
4254  */
4255 static int
4256 setup_acctmgmt_params(ns_ldap_cookie_t *cookie)
4257 {
4258 	LDAPControl	*req = NULL, **requestctrls;
4259 
4260 	req = (LDAPControl *)malloc(sizeof (LDAPControl));
4261 
4262 	if (req == NULL)
4263 		return (NS_LDAP_MEMORY);
4264 
4265 	/* fill in the fields of this new control */
4266 	req->ldctl_iscritical = 1;
4267 	req->ldctl_oid = strdup(NS_LDAP_ACCOUNT_USABLE_CONTROL);
4268 	if (req->ldctl_oid == NULL) {
4269 		free(req);
4270 		return (NS_LDAP_MEMORY);
4271 	}
4272 	req->ldctl_value.bv_len = 0;
4273 	req->ldctl_value.bv_val = NULL;
4274 
4275 	requestctrls = (LDAPControl **)calloc(2, sizeof (LDAPControl *));
4276 	if (requestctrls == NULL) {
4277 		ldap_control_free(req);
4278 		return (NS_LDAP_MEMORY);
4279 	}
4280 
4281 	requestctrls[0] = req;
4282 
4283 	cookie->p_serverctrls = requestctrls;
4284 
4285 	return (NS_LDAP_SUCCESS);
4286 }
4287 
4288 /*
4289  * int get_new_acct_more_info(BerElement *ber,
4290  *     AcctUsableResponse_t *acctResp)
4291  *
4292  * Decode the more_info data from an Account Management control response,
4293  * when the account is not usable and when code style is from recent LDAP
4294  * servers (see below comments for parse_acct_cont_resp_msg() to get more
4295  * details on coding styles and ASN1 description).
4296  *
4297  * Expected BER encoding: {tbtbtbtiti}
4298  *      +t: tag is 0
4299  *	+b: TRUE if inactive due to account inactivation
4300  *      +t: tag is 1
4301  * 	+b: TRUE if password has been reset
4302  *      +t: tag is 2
4303  * 	+b: TRUE if password is expired
4304  *	+t: tag is 3
4305  *	+i: contains num of remaining grace, 0 means no grace
4306  *	+t: tag is 4
4307  *	+i: contains num of seconds before auto-unlock. -1 means acct is locked
4308  *		forever (i.e. until reset)
4309  *
4310  * Asumptions:
4311  * - ber is not null
4312  * - acctResp is not null and is initialized with default values for the
4313  *   fields in its AcctUsableResp.more_info structure
4314  * - the ber stream is received in the correct order, per the ASN1 description.
4315  *   We do not check this order and make the asumption that it is correct.
4316  *   Note that the ber stream may not (and will not in most cases) contain
4317  *   all fields.
4318  */
4319 static int
4320 get_new_acct_more_info(BerElement *ber, AcctUsableResponse_t *acctResp)
4321 {
4322 	int		rc = NS_LDAP_SUCCESS;
4323 	char		errstr[MAXERROR];
4324 	ber_tag_t	rTag = LBER_DEFAULT;
4325 	ber_len_t	rLen = 0;
4326 	ber_int_t	rValue;
4327 	char		*last;
4328 	int		berRC = 0;
4329 
4330 	/*
4331 	 * Look at what more_info BER element is/are left to be decoded.
4332 	 * look at each of them 1 by 1, without checking on their order
4333 	 * and possible multi values.
4334 	 */
4335 	for (rTag = ber_first_element(ber, &rLen, &last);
4336 	    rTag != LBER_END_OF_SEQORSET;
4337 	    rTag = ber_next_element(ber, &rLen, last)) {
4338 
4339 		berRC = 0;
4340 		switch (rTag) {
4341 		case 0 | LBER_CLASS_CONTEXT | LBER_PRIMITIVE:
4342 			/* inactive */
4343 			berRC = ber_scanf(ber, "b", &rValue);
4344 			if (berRC != LBER_ERROR) {
4345 				(acctResp->AcctUsableResp).more_info.
4346 				    inactive = (rValue != 0) ? 1 : 0;
4347 			}
4348 			break;
4349 
4350 		case 1 | LBER_CLASS_CONTEXT | LBER_PRIMITIVE:
4351 			/* reset */
4352 			berRC = ber_scanf(ber, "b", &rValue);
4353 			if (berRC != LBER_ERROR) {
4354 				(acctResp->AcctUsableResp).more_info.reset
4355 				    = (rValue != 0) ? 1 : 0;
4356 			}
4357 			break;
4358 
4359 		case 2 | LBER_CLASS_CONTEXT | LBER_PRIMITIVE:
4360 			/* expired */
4361 			berRC = ber_scanf(ber, "b", &rValue);
4362 			if (berRC != LBER_ERROR) {
4363 				(acctResp->AcctUsableResp).more_info.expired
4364 				    = (rValue != 0) ? 1 : 0;
4365 			}
4366 			break;
4367 
4368 		case 3 | LBER_CLASS_CONTEXT | LBER_PRIMITIVE:
4369 			/* remaining grace */
4370 			berRC = ber_scanf(ber, "i", &rValue);
4371 			if (berRC != LBER_ERROR) {
4372 				(acctResp->AcctUsableResp).more_info.rem_grace
4373 				    = rValue;
4374 			}
4375 			break;
4376 
4377 		case 4 | LBER_CLASS_CONTEXT | LBER_PRIMITIVE:
4378 			/* seconds before unlock */
4379 			berRC = ber_scanf(ber, "i", &rValue);
4380 			if (berRC != LBER_ERROR) {
4381 				(acctResp->AcctUsableResp).more_info.
4382 				    sec_b4_unlock = rValue;
4383 			}
4384 			break;
4385 
4386 		default :
4387 			(void) sprintf(errstr,
4388 			    gettext("invalid reason tag 0x%x"), rTag);
4389 			syslog(LOG_DEBUG, "libsldap: %s", errstr);
4390 			rc = NS_LDAP_INTERNAL;
4391 			break;
4392 		}
4393 		if (berRC == LBER_ERROR) {
4394 			(void) sprintf(errstr,
4395 			    gettext("error 0x%x decoding value for "
4396 			    "tag 0x%x"), berRC, rTag);
4397 			syslog(LOG_DEBUG, "libsldap: %s", errstr);
4398 			rc = NS_LDAP_INTERNAL;
4399 		}
4400 		if (rc != NS_LDAP_SUCCESS) {
4401 			/* exit the for loop */
4402 			break;
4403 		}
4404 	}
4405 
4406 	return (rc);
4407 }
4408 
4409 /*
4410  * int get_old_acct_opt_more_info(BerElement *ber,
4411  *     AcctUsableResponse_t *acctResp)
4412  *
4413  * Decode the optional more_info data from an Account Management control
4414  * response, when the account is not usable and when code style is from LDAP
4415  * server 5.2p4 (see below comments for parse_acct_cont_resp_msg() to get more
4416  * details on coding styles and ASN1 description).
4417  *
4418  * Expected BER encoding: titi}
4419  *	+t: tag is 2
4420  *	+i: contains num of remaining grace, 0 means no grace
4421  *	+t: tag is 3
4422  *	+i: contains num of seconds before auto-unlock. -1 means acct is locked
4423  *		forever (i.e. until reset)
4424  *
4425  * Asumptions:
4426  * - ber is a valid BER element
4427  * - acctResp is initialized for the fields in its AcctUsableResp.more_info
4428  *   structure
4429  */
4430 static int
4431 get_old_acct_opt_more_info(ber_tag_t tag, BerElement *ber,
4432     AcctUsableResponse_t *acctResp)
4433 {
4434 	int		rc = NS_LDAP_SUCCESS;
4435 	char		errstr[MAXERROR];
4436 	ber_len_t	len;
4437 	int		rem_grace, sec_b4_unlock;
4438 
4439 	switch (tag) {
4440 	case 2:
4441 		/* decode and maybe 3 is following */
4442 		if ((tag = ber_scanf(ber, "i", &rem_grace)) == LBER_ERROR) {
4443 			(void) sprintf(errstr, gettext("Can not get "
4444 			    "rem_grace"));
4445 			syslog(LOG_DEBUG, "libsldap: %s", errstr);
4446 			rc = NS_LDAP_INTERNAL;
4447 			break;
4448 		}
4449 		(acctResp->AcctUsableResp).more_info.rem_grace = rem_grace;
4450 
4451 		if ((tag = ber_peek_tag(ber, &len)) == LBER_ERROR) {
4452 			/* this is a success case, break to exit */
4453 			(void) sprintf(errstr, gettext("No more "
4454 			    "optional data"));
4455 			syslog(LOG_DEBUG, "libsldap: %s", errstr);
4456 			break;
4457 		}
4458 
4459 		if (tag == 3) {
4460 			if (ber_scanf(ber, "i", &sec_b4_unlock) == LBER_ERROR) {
4461 				(void) sprintf(errstr,
4462 				    gettext("Can not get sec_b4_unlock "
4463 				    "- 1st case"));
4464 				syslog(LOG_DEBUG, "libsldap: %s", errstr);
4465 				rc = NS_LDAP_INTERNAL;
4466 				break;
4467 			}
4468 			(acctResp->AcctUsableResp).more_info.sec_b4_unlock =
4469 			    sec_b4_unlock;
4470 		} else { /* unknown tag */
4471 			(void) sprintf(errstr, gettext("Unknown tag "
4472 			    "- 1st case"));
4473 			syslog(LOG_DEBUG, "libsldap: %s", errstr);
4474 			rc = NS_LDAP_INTERNAL;
4475 			break;
4476 		}
4477 		break;
4478 
4479 	case 3:
4480 		if (ber_scanf(ber, "i", &sec_b4_unlock) == LBER_ERROR) {
4481 			(void) sprintf(errstr, gettext("Can not get "
4482 			    "sec_b4_unlock - 2nd case"));
4483 			syslog(LOG_DEBUG, "libsldap: %s", errstr);
4484 			rc = NS_LDAP_INTERNAL;
4485 			break;
4486 		}
4487 		(acctResp->AcctUsableResp).more_info.sec_b4_unlock =
4488 		    sec_b4_unlock;
4489 		break;
4490 
4491 	default: /* unknown tag */
4492 		(void) sprintf(errstr, gettext("Unknown tag - 2nd case"));
4493 		syslog(LOG_DEBUG, "libsldap: %s", errstr);
4494 		rc = NS_LDAP_INTERNAL;
4495 		break;
4496 	}
4497 
4498 	return (rc);
4499 }
4500 
4501 /*
4502  * **** This function needs to be moved to libldap library ****
4503  * parse_acct_cont_resp_msg() parses the message received by server according to
4504  * following format (ASN1 notation):
4505  *
4506  *	ACCOUNT_USABLE_RESPONSE::= CHOICE {
4507  *		is_available		[0] INTEGER,
4508  *				** seconds before expiration **
4509  *		is_not_available	[1] more_info
4510  *	}
4511  *	more_info::= SEQUENCE {
4512  *		inactive		[0] BOOLEAN DEFAULT FALSE,
4513  *		reset			[1] BOOLEAN DEFAULT FALSE,
4514  *		expired			[2] BOOLEAN DEFAULT FALSE,
4515  *		remaining_grace		[3] INTEGER OPTIONAL,
4516  *		seconds_before_unlock	[4] INTEGER OPTIONAL
4517  *	}
4518  */
4519 /*
4520  * #define used to make the difference between coding style as done
4521  * by LDAP server 5.2p4 and newer LDAP servers. There are 4 values:
4522  * - DS52p4_USABLE: 5.2p4 coding style, account is usable
4523  * - DS52p4_NOT_USABLE: 5.2p4 coding style, account is not usable
4524  * - NEW_USABLE: newer LDAP servers coding style, account is usable
4525  * - NEW_NOT_USABLE: newer LDAP servers coding style, account is not usable
4526  *
4527  * An account would be considered not usable if for instance:
4528  * - it's been made inactive in the LDAP server
4529  * - or its password was reset in the LDAP server database
4530  * - or its password expired
4531  * - or the account has been locked, possibly forever
4532  */
4533 #define	DS52p4_USABLE		0x00
4534 #define	DS52p4_NOT_USABLE	0x01
4535 #define	NEW_USABLE		0x00 | LBER_CLASS_CONTEXT | LBER_PRIMITIVE
4536 #define	NEW_NOT_USABLE		0x01 | LBER_CLASS_CONTEXT | LBER_CONSTRUCTED
4537 static int
4538 parse_acct_cont_resp_msg(LDAPControl **ectrls, AcctUsableResponse_t *acctResp)
4539 {
4540 	int		rc = NS_LDAP_SUCCESS;
4541 	BerElement	*ber;
4542 	ber_tag_t 	tag;
4543 	ber_len_t	len;
4544 	int		i;
4545 	char		errstr[MAXERROR];
4546 	/* used for any coding style when account is usable */
4547 	int		seconds_before_expiry;
4548 	/* used for 5.2p4 coding style when account is not usable */
4549 	int		inactive, reset, expired;
4550 
4551 	if (ectrls == NULL) {
4552 		(void) sprintf(errstr, gettext("Invalid ectrls parameter"));
4553 		syslog(LOG_DEBUG, "libsldap: %s", errstr);
4554 		return (NS_LDAP_INVALID_PARAM);
4555 	}
4556 
4557 	for (i = 0; ectrls[i] != NULL; i++) {
4558 		if (strcmp(ectrls[i]->ldctl_oid, NS_LDAP_ACCOUNT_USABLE_CONTROL)
4559 		    == 0) {
4560 			break;
4561 		}
4562 	}
4563 
4564 	if (ectrls[i] == NULL) {
4565 		/* Ldap control is not found */
4566 		(void) sprintf(errstr, gettext("Account Usable Control "
4567 		    "not found"));
4568 		syslog(LOG_DEBUG, "libsldap: %s", errstr);
4569 		return (NS_LDAP_NOTFOUND);
4570 	}
4571 
4572 	/* Allocate a BER element from the control value and parse it. */
4573 	if ((ber = ber_init(&ectrls[i]->ldctl_value)) == NULL)
4574 		return (NS_LDAP_MEMORY);
4575 
4576 	if ((tag = ber_peek_tag(ber, &len)) == LBER_ERROR) {
4577 		/* Ldap decoding error */
4578 		(void) sprintf(errstr, gettext("Error decoding 1st tag"));
4579 		syslog(LOG_DEBUG, "libsldap: %s", errstr);
4580 		ber_free(ber, 1);
4581 		return (NS_LDAP_INTERNAL);
4582 	}
4583 
4584 	switch (tag) {
4585 	case DS52p4_USABLE:
4586 	case NEW_USABLE:
4587 		acctResp->choice = 0;
4588 		if (ber_scanf(ber, "i", &seconds_before_expiry)
4589 		    == LBER_ERROR) {
4590 			/* Ldap decoding error */
4591 			(void) sprintf(errstr, gettext("Can not get "
4592 			    "seconds_before_expiry"));
4593 			syslog(LOG_DEBUG, "libsldap: %s", errstr);
4594 			rc = NS_LDAP_INTERNAL;
4595 			break;
4596 		}
4597 		/* ber_scanf() succeeded */
4598 		(acctResp->AcctUsableResp).seconds_before_expiry =
4599 		    seconds_before_expiry;
4600 		break;
4601 
4602 	case DS52p4_NOT_USABLE:
4603 		acctResp->choice = 1;
4604 		if (ber_scanf(ber, "{bbb", &inactive, &reset, &expired)
4605 		    == LBER_ERROR) {
4606 			/* Ldap decoding error */
4607 			(void) sprintf(errstr, gettext("Can not get "
4608 			    "inactive/reset/expired"));
4609 			syslog(LOG_DEBUG, "libsldap: %s", errstr);
4610 			rc = NS_LDAP_INTERNAL;
4611 			break;
4612 		}
4613 		/* ber_scanf() succeeded */
4614 		(acctResp->AcctUsableResp).more_info.inactive =
4615 		    ((inactive == 0) ? 0 : 1);
4616 		(acctResp->AcctUsableResp).more_info.reset =
4617 		    ((reset == 0) ? 0 : 1);
4618 		(acctResp->AcctUsableResp).more_info.expired =
4619 		    ((expired == 0) ? 0 : 1);
4620 		(acctResp->AcctUsableResp).more_info.rem_grace = 0;
4621 		(acctResp->AcctUsableResp).more_info.sec_b4_unlock = 0;
4622 
4623 		if ((tag = ber_peek_tag(ber, &len)) == LBER_ERROR) {
4624 			/* this is a success case, break to exit */
4625 			(void) sprintf(errstr, gettext("No optional data"));
4626 			syslog(LOG_DEBUG, "libsldap: %s", errstr);
4627 			break;
4628 		}
4629 
4630 		/*
4631 		 * Look at what optional more_info BER element is/are
4632 		 * left to be decoded.
4633 		 */
4634 		rc = get_old_acct_opt_more_info(tag, ber, acctResp);
4635 		break;
4636 
4637 	case NEW_NOT_USABLE:
4638 		acctResp->choice = 1;
4639 		/*
4640 		 * Recent LDAP servers won't code more_info data for default
4641 		 * values (see above comments on ASN1 description for what
4642 		 * fields have default values & what fields are optional).
4643 		 */
4644 		(acctResp->AcctUsableResp).more_info.inactive = 0;
4645 		(acctResp->AcctUsableResp).more_info.reset = 0;
4646 		(acctResp->AcctUsableResp).more_info.expired = 0;
4647 		(acctResp->AcctUsableResp).more_info.rem_grace = 0;
4648 		(acctResp->AcctUsableResp).more_info.sec_b4_unlock = 0;
4649 
4650 		if (len == 0) {
4651 			/*
4652 			 * Nothing else to decode; this is valid and we
4653 			 * use default values set above.
4654 			 */
4655 			(void) sprintf(errstr, gettext("more_info is "
4656 			    "empty, using default values"));
4657 			syslog(LOG_DEBUG, "libsldap: %s", errstr);
4658 			break;
4659 		}
4660 
4661 		/*
4662 		 * Look at what more_info BER element is/are left to
4663 		 * be decoded.
4664 		 */
4665 		rc = get_new_acct_more_info(ber, acctResp);
4666 		break;
4667 
4668 	default:
4669 		(void) sprintf(errstr, gettext("unknwon coding style "
4670 		    "(tag: 0x%x)"), tag);
4671 		syslog(LOG_DEBUG, "libsldap: %s", errstr);
4672 		rc = NS_LDAP_INTERNAL;
4673 		break;
4674 	}
4675 
4676 	ber_free(ber, 1);
4677 	return (rc);
4678 }
4679 
4680 /*
4681  * __ns_ldap_getAcctMgmt() is called from pam account management stack
4682  * for retrieving accounting information of users with no user password -
4683  * eg. rlogin, rsh, etc. This function uses the account management control
4684  * request to do a search on the server for the user in question. The
4685  * response control returned from the server is got from the cookie.
4686  * Input params: username of whose account mgmt information is to be got
4687  *		 pointer to hold the parsed account management information
4688  * Return values: NS_LDAP_SUCCESS on success or appropriate error
4689  *		code on failure
4690  */
4691 int
4692 __ns_ldap_getAcctMgmt(const char *user, AcctUsableResponse_t *acctResp)
4693 {
4694 	int		scope, rc;
4695 	char		ldapfilter[1024];
4696 	ns_ldap_cookie_t	*cookie;
4697 	ns_ldap_search_desc_t	**sdlist = NULL;
4698 	ns_ldap_search_desc_t	*dptr;
4699 	ns_ldap_error_t		*error = NULL;
4700 	char			**dns = NULL;
4701 	char		service[] = "shadow";
4702 
4703 	if (user == NULL || acctResp == NULL)
4704 		return (NS_LDAP_INVALID_PARAM);
4705 
4706 	/* Initialize State machine cookie */
4707 	cookie = init_search_state_machine();
4708 	if (cookie == NULL)
4709 		return (NS_LDAP_MEMORY);
4710 
4711 	/* see if need to follow referrals */
4712 	rc = __s_api_toFollowReferrals(0,
4713 	    &cookie->followRef, &error);
4714 	if (rc != NS_LDAP_SUCCESS) {
4715 		(void) __ns_ldap_freeError(&error);
4716 		goto out;
4717 	}
4718 
4719 	/* get the service descriptor - or create a default one */
4720 	rc = __s_api_get_SSD_from_SSDtoUse_service(service,
4721 	    &sdlist, &error);
4722 	if (rc != NS_LDAP_SUCCESS) {
4723 		(void) __ns_ldap_freeError(&error);
4724 		goto out;
4725 	}
4726 
4727 	if (sdlist == NULL) {
4728 		/* Create default service Desc */
4729 		sdlist = (ns_ldap_search_desc_t **)calloc(2,
4730 		    sizeof (ns_ldap_search_desc_t *));
4731 		if (sdlist == NULL) {
4732 			rc = NS_LDAP_MEMORY;
4733 			goto out;
4734 		}
4735 		dptr = (ns_ldap_search_desc_t *)
4736 		    calloc(1, sizeof (ns_ldap_search_desc_t));
4737 		if (dptr == NULL) {
4738 			free(sdlist);
4739 			rc = NS_LDAP_MEMORY;
4740 			goto out;
4741 		}
4742 		sdlist[0] = dptr;
4743 
4744 		/* default base */
4745 		rc = __s_api_getDNs(&dns, service, &cookie->errorp);
4746 		if (rc != NS_LDAP_SUCCESS) {
4747 			if (dns) {
4748 				__s_api_free2dArray(dns);
4749 				dns = NULL;
4750 			}
4751 			(void) __ns_ldap_freeError(&(cookie->errorp));
4752 			cookie->errorp = NULL;
4753 			goto out;
4754 		}
4755 		dptr->basedn = strdup(dns[0]);
4756 		if (dptr->basedn == NULL) {
4757 			free(sdlist);
4758 			free(dptr);
4759 			if (dns) {
4760 				__s_api_free2dArray(dns);
4761 				dns = NULL;
4762 			}
4763 			rc = NS_LDAP_MEMORY;
4764 			goto out;
4765 		}
4766 		__s_api_free2dArray(dns);
4767 		dns = NULL;
4768 
4769 		/* default scope */
4770 		scope = 0;
4771 		rc = __s_api_getSearchScope(&scope, &cookie->errorp);
4772 		dptr->scope = scope;
4773 	}
4774 
4775 	cookie->sdlist = sdlist;
4776 
4777 	cookie->service = strdup(service);
4778 	if (cookie->service == NULL) {
4779 		rc = NS_LDAP_MEMORY;
4780 		goto out;
4781 	}
4782 
4783 	/* search for entries for this particular uid */
4784 	(void) snprintf(ldapfilter, sizeof (ldapfilter), "(uid=%s)", user);
4785 	cookie->i_filter = strdup(ldapfilter);
4786 	if (cookie->i_filter == NULL) {
4787 		rc = NS_LDAP_MEMORY;
4788 		goto out;
4789 	}
4790 
4791 	/* create the control request */
4792 	if ((rc = setup_acctmgmt_params(cookie)) != NS_LDAP_SUCCESS)
4793 		goto out;
4794 
4795 	/* Process search */
4796 	rc = search_state_machine(cookie, GET_ACCT_MGMT_INFO, 0);
4797 
4798 	/* Copy results back to user */
4799 	rc = cookie->err_rc;
4800 	if (rc != NS_LDAP_SUCCESS)
4801 			(void) __ns_ldap_freeError(&(cookie->errorp));
4802 
4803 	if (cookie->result == NULL)
4804 			goto out;
4805 
4806 	if ((rc = parse_acct_cont_resp_msg(cookie->resultctrl, acctResp))
4807 	    != NS_LDAP_SUCCESS)
4808 		goto out;
4809 
4810 	rc = NS_LDAP_SUCCESS;
4811 
4812 out:
4813 	delete_search_cookie(cookie);
4814 
4815 	return (rc);
4816 }
4817