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