xref: /titanic_50/usr/src/lib/libsldap/common/ns_reads.c (revision 4088bb40326b75ef60834a6c2a92e29e25474b68)
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 2006 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_val == NULL))
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 
2046 	for (;;) {
2047 		switch (cookie->state) {
2048 		case GET_ACCT_MGMT_INFO:
2049 			/*
2050 			 * Set the flag to get ldap account management controls.
2051 			 */
2052 			cookie->nopasswd_acct_mgmt = 1;
2053 			cookie->new_state = INIT;
2054 			break;
2055 		case EXIT:
2056 			/* state engine/connection cleaned up in delete */
2057 			if (cookie->attribute) {
2058 				__s_api_free2dArray(cookie->attribute);
2059 				cookie->attribute = NULL;
2060 			}
2061 			if (cookie->reflist) {
2062 				__s_api_deleteRefInfo(cookie->reflist);
2063 				cookie->reflist = NULL;
2064 			}
2065 			return (EXIT);
2066 		case INIT:
2067 			cookie->sdpos = NULL;
2068 			cookie->new_state = NEXT_SEARCH_DESCRIPTOR;
2069 			if (cookie->attribute) {
2070 				__s_api_free2dArray(cookie->attribute);
2071 				cookie->attribute = NULL;
2072 			}
2073 			if ((cookie->i_flags & NS_LDAP_NOMAP) == 0 &&
2074 				cookie->i_attr) {
2075 				cookie->attribute =
2076 					__ns_ldap_mapAttributeList(
2077 						cookie->service,
2078 						cookie->i_attr);
2079 			}
2080 			break;
2081 		case NEXT_SEARCH_DESCRIPTOR:
2082 			/* get next search descriptor */
2083 			if (cookie->sdpos == NULL) {
2084 				cookie->sdpos = cookie->sdlist;
2085 				cookie->new_state = GET_SESSION;
2086 			} else {
2087 				cookie->sdpos++;
2088 				cookie->new_state = NEXT_SEARCH;
2089 			}
2090 			if (*cookie->sdpos == NULL)
2091 				cookie->new_state = EXIT;
2092 			break;
2093 		case GET_SESSION:
2094 			if (get_current_session(cookie) < 0)
2095 				cookie->new_state = NEXT_SESSION;
2096 			else
2097 				cookie->new_state = NEXT_SEARCH;
2098 			break;
2099 		case NEXT_SESSION:
2100 			if (get_next_session(cookie) < 0)
2101 				cookie->new_state = RESTART_SESSION;
2102 			else
2103 				cookie->new_state = NEXT_SEARCH;
2104 			break;
2105 		case RESTART_SESSION:
2106 			if (cookie->i_flags & NS_LDAP_HARD) {
2107 				cookie->new_state = NEXT_SESSION;
2108 				break;
2109 			}
2110 			(void) sprintf(errstr,
2111 				gettext("Session error no available conn.\n"),
2112 				state);
2113 			err = strdup(errstr);
2114 			MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL, err,
2115 				NULL);
2116 			cookie->err_rc = NS_LDAP_INTERNAL;
2117 			cookie->errorp = *errorp;
2118 			cookie->new_state = EXIT;
2119 			break;
2120 		case NEXT_SEARCH:
2121 			/* setup referrals search if necessary */
2122 			if (cookie->refpos) {
2123 				if (setup_referral_search(cookie) < 0) {
2124 					cookie->new_state = EXIT;
2125 					break;
2126 				}
2127 			} else if (setup_next_search(cookie) < 0) {
2128 				cookie->new_state = EXIT;
2129 				break;
2130 			}
2131 			/* only do VLV/PAGE on scopes onelevel/subtree */
2132 			if (paging_supported(cookie)) {
2133 				if (cookie->use_paging &&
2134 				    (cookie->scope != LDAP_SCOPE_BASE)) {
2135 					cookie->index = 1;
2136 					if (cookie->listType == VLVCTRLFLAG)
2137 						cookie->new_state = NEXT_VLV;
2138 					else
2139 						cookie->new_state = NEXT_PAGE;
2140 					break;
2141 				}
2142 			}
2143 			cookie->new_state = ONE_SEARCH;
2144 			break;
2145 		case NEXT_VLV:
2146 			rc = setup_vlv_params(cookie);
2147 			if (rc != LDAP_SUCCESS) {
2148 				cookie->err_rc = rc;
2149 				cookie->new_state = LDAP_ERROR;
2150 				break;
2151 			}
2152 			cookie->next_state = MULTI_RESULT;
2153 			cookie->new_state = DO_SEARCH;
2154 			break;
2155 		case NEXT_PAGE:
2156 			rc = setup_simplepg_params(cookie);
2157 			if (rc != LDAP_SUCCESS) {
2158 				cookie->err_rc = rc;
2159 				cookie->new_state = LDAP_ERROR;
2160 				break;
2161 			}
2162 			cookie->next_state = MULTI_RESULT;
2163 			cookie->new_state = DO_SEARCH;
2164 			break;
2165 		case ONE_SEARCH:
2166 			cookie->next_state = NEXT_RESULT;
2167 			cookie->new_state = DO_SEARCH;
2168 			break;
2169 		case DO_SEARCH:
2170 			rc = ldap_search_ext(cookie->conn->ld,
2171 				cookie->basedn,
2172 				cookie->scope,
2173 				cookie->filter,
2174 				cookie->attribute,
2175 				0,
2176 				cookie->p_serverctrls,
2177 				NULL,
2178 				&cookie->search_timeout, 0,
2179 				&cookie->msgId);
2180 			if (rc != LDAP_SUCCESS) {
2181 				if (rc == LDAP_BUSY ||
2182 				    rc == LDAP_UNAVAILABLE ||
2183 				    rc == LDAP_UNWILLING_TO_PERFORM ||
2184 				    rc == LDAP_CONNECT_ERROR ||
2185 				    rc == LDAP_SERVER_DOWN) {
2186 
2187 					cookie->new_state = NEXT_SESSION;
2188 
2189 					/*
2190 					 * If not able to reach the
2191 					 * server, inform the ldap
2192 					 * cache manager that the
2193 					 * server should be removed
2194 					 * from it's server list.
2195 					 * Thus, the manager will not
2196 					 * return this server on the next
2197 					 * get-server request and will
2198 					 * also reduce the server list
2199 					 * refresh TTL, so that it will
2200 					 * find out sooner when the server
2201 					 * is up again.
2202 					 */
2203 					if (rc == LDAP_CONNECT_ERROR ||
2204 						rc == LDAP_SERVER_DOWN) {
2205 						ret = __s_api_removeServer(
2206 						    cookie->conn->serverAddr);
2207 						if (ret == NOSERVER &&
2208 						    cookie->conn_auth_type
2209 							== NS_LDAP_AUTH_NONE) {
2210 							/*
2211 							 * Couldn't remove
2212 							 * server from server
2213 							 * list.
2214 							 * Exit to avoid
2215 							 * potential infinite
2216 							 * loop.
2217 							 */
2218 							cookie->err_rc = rc;
2219 							cookie->new_state =
2220 							    LDAP_ERROR;
2221 						}
2222 						if (cookie->connectionId > -1) {
2223 						    DropConnection(
2224 							cookie->connectionId,
2225 							NS_LDAP_NEW_CONN);
2226 						    cookie->connectionId = -1;
2227 						}
2228 					}
2229 					break;
2230 				}
2231 				cookie->err_rc = rc;
2232 				cookie->new_state = LDAP_ERROR;
2233 				break;
2234 			}
2235 			cookie->new_state = cookie->next_state;
2236 			break;
2237 		case NEXT_RESULT:
2238 			rc = ldap_result(cookie->conn->ld, cookie->msgId,
2239 				LDAP_MSG_ONE,
2240 				(struct timeval *)&cookie->search_timeout,
2241 				&cookie->resultMsg);
2242 			if (rc == LDAP_RES_SEARCH_RESULT) {
2243 				cookie->new_state = END_RESULT;
2244 				/* check and process referrals info */
2245 				if (cookie->followRef)
2246 					proc_result_referrals(
2247 						cookie);
2248 				(void) ldap_msgfree(cookie->resultMsg);
2249 				cookie->resultMsg = NULL;
2250 				break;
2251 			}
2252 			/* handle referrals if necessary */
2253 			if (rc == LDAP_RES_SEARCH_REFERENCE) {
2254 				if (cookie->followRef)
2255 					proc_search_references(cookie);
2256 				(void) ldap_msgfree(cookie->resultMsg);
2257 				cookie->resultMsg = NULL;
2258 				break;
2259 			}
2260 			if (rc != LDAP_RES_SEARCH_ENTRY) {
2261 				switch (rc) {
2262 				case 0:
2263 					rc = LDAP_TIMEOUT;
2264 					break;
2265 				case -1:
2266 					rc = ldap_get_lderrno(cookie->conn->ld,
2267 						    NULL, NULL);
2268 					break;
2269 				default:
2270 					rc = ldap_result2error(cookie->conn->ld,
2271 						cookie->resultMsg, 1);
2272 					break;
2273 				}
2274 				(void) ldap_msgfree(cookie->resultMsg);
2275 				cookie->resultMsg = NULL;
2276 				if (rc == LDAP_BUSY ||
2277 				    rc == LDAP_UNAVAILABLE ||
2278 				    rc == LDAP_UNWILLING_TO_PERFORM ||
2279 				    rc == LDAP_SERVER_DOWN) {
2280 					cookie->new_state = NEXT_SESSION;
2281 					break;
2282 				}
2283 				cookie->err_rc = rc;
2284 				cookie->new_state = LDAP_ERROR;
2285 				break;
2286 			}
2287 			/* else LDAP_RES_SEARCH_ENTRY */
2288 			/* get account management response control */
2289 			if (cookie->nopasswd_acct_mgmt == 1) {
2290 				rc = ldap_get_entry_controls(cookie->conn->ld,
2291 					cookie->resultMsg,
2292 					&(cookie->resultctrl));
2293 				if (rc != LDAP_SUCCESS) {
2294 					cookie->new_state = LDAP_ERROR;
2295 					cookie->err_rc = rc;
2296 					break;
2297 				}
2298 			}
2299 			rc = __s_api_getEntry(cookie);
2300 			(void) ldap_msgfree(cookie->resultMsg);
2301 			cookie->resultMsg = NULL;
2302 			if (rc != NS_LDAP_SUCCESS) {
2303 				cookie->new_state = LDAP_ERROR;
2304 				break;
2305 			}
2306 			cookie->new_state = PROCESS_RESULT;
2307 			cookie->next_state = NEXT_RESULT;
2308 			break;
2309 		case MULTI_RESULT:
2310 			rc = ldap_result(cookie->conn->ld, cookie->msgId,
2311 				LDAP_MSG_ONE,
2312 				(struct timeval *)&cookie->search_timeout,
2313 				&cookie->resultMsg);
2314 			if (rc == LDAP_RES_SEARCH_RESULT) {
2315 				rc = ldap_result2error(cookie->conn->ld,
2316 					cookie->resultMsg, 0);
2317 				if (rc != LDAP_SUCCESS) {
2318 					cookie->err_rc = rc;
2319 					cookie->new_state = LDAP_ERROR;
2320 					(void) ldap_msgfree(cookie->resultMsg);
2321 					break;
2322 				}
2323 				cookie->new_state = multi_result(cookie);
2324 				(void) ldap_msgfree(cookie->resultMsg);
2325 				cookie->resultMsg = NULL;
2326 				break;
2327 			}
2328 			/* handle referrals if necessary */
2329 			if (rc == LDAP_RES_SEARCH_REFERENCE &&
2330 				cookie->followRef) {
2331 				proc_search_references(cookie);
2332 				(void) ldap_msgfree(cookie->resultMsg);
2333 				cookie->resultMsg = NULL;
2334 				break;
2335 			}
2336 			if (rc != LDAP_RES_SEARCH_ENTRY) {
2337 				switch (rc) {
2338 				case 0:
2339 					rc = LDAP_TIMEOUT;
2340 					break;
2341 				case -1:
2342 					rc = ldap_get_lderrno(cookie->conn->ld,
2343 						    NULL, NULL);
2344 					break;
2345 				default:
2346 					rc = ldap_result2error(cookie->conn->ld,
2347 						cookie->resultMsg, 1);
2348 					break;
2349 				}
2350 				(void) ldap_msgfree(cookie->resultMsg);
2351 				cookie->resultMsg = NULL;
2352 				if (rc == LDAP_BUSY ||
2353 				    rc == LDAP_UNAVAILABLE ||
2354 				    rc == LDAP_UNWILLING_TO_PERFORM ||
2355 				    rc == LDAP_SERVER_DOWN) {
2356 					cookie->new_state = NEXT_SESSION;
2357 					break;
2358 				}
2359 				cookie->err_rc = rc;
2360 				cookie->new_state = LDAP_ERROR;
2361 				break;
2362 			}
2363 			/* else LDAP_RES_SEARCH_ENTRY */
2364 			rc = __s_api_getEntry(cookie);
2365 			(void) ldap_msgfree(cookie->resultMsg);
2366 			cookie->resultMsg = NULL;
2367 			if (rc != NS_LDAP_SUCCESS) {
2368 				cookie->new_state = LDAP_ERROR;
2369 				break;
2370 			}
2371 			cookie->new_state = PROCESS_RESULT;
2372 			cookie->next_state = MULTI_RESULT;
2373 			break;
2374 		case PROCESS_RESULT:
2375 			/* NOTE THIS STATE MAY BE PROCESSED BY CALLER */
2376 			if (cookie->use_usercb && cookie->callback) {
2377 				rc = 0;
2378 				for (nextEntry = cookie->result->entry;
2379 					nextEntry != NULL;
2380 					nextEntry = nextEntry->next) {
2381 					rc = (*cookie->callback)(nextEntry,
2382 						cookie->userdata);
2383 
2384 					if (rc == NS_LDAP_CB_DONE) {
2385 					/* cb doesn't want any more data */
2386 						rc = NS_LDAP_PARTIAL;
2387 						cookie->err_rc = rc;
2388 						break;
2389 					} else if (rc != NS_LDAP_CB_NEXT) {
2390 					/* invalid return code */
2391 						rc = NS_LDAP_OP_FAILED;
2392 						cookie->err_rc = rc;
2393 						break;
2394 					}
2395 				}
2396 				(void) __ns_ldap_freeResult(&cookie->result);
2397 				cookie->result = NULL;
2398 			}
2399 			if (rc != 0) {
2400 				cookie->new_state = EXIT;
2401 				break;
2402 			}
2403 			/* NOTE PREVIOUS STATE SPECIFIES NEXT STATE */
2404 			cookie->new_state = cookie->next_state;
2405 			break;
2406 		case END_PROCESS_RESULT:
2407 			cookie->new_state = cookie->next_state;
2408 			break;
2409 		case END_RESULT:
2410 			/*
2411 			 * XXX DO WE NEED THIS CASE?
2412 			 * if (search is complete) {
2413 			 * 	cookie->new_state = EXIT;
2414 			 * } else
2415 			 */
2416 				/*
2417 				 * entering referral mode if necessary
2418 				 */
2419 				if (cookie->followRef && cookie->reflist)
2420 					cookie->new_state =
2421 						NEXT_REFERRAL;
2422 				else
2423 					cookie->new_state =
2424 						NEXT_SEARCH_DESCRIPTOR;
2425 			break;
2426 		case NEXT_REFERRAL:
2427 			/* get next referral info */
2428 			if (cookie->refpos == NULL)
2429 				cookie->refpos =
2430 					cookie->reflist;
2431 			else
2432 				cookie->refpos =
2433 					cookie->refpos->next;
2434 			/* check see if done with all referrals */
2435 			if (cookie->refpos != NULL)
2436 				cookie->new_state =
2437 					GET_REFERRAL_SESSION;
2438 			else {
2439 				__s_api_deleteRefInfo(cookie->reflist);
2440 				cookie->reflist = NULL;
2441 				cookie->new_state =
2442 					NEXT_SEARCH_DESCRIPTOR;
2443 			}
2444 			break;
2445 		case GET_REFERRAL_SESSION:
2446 			if (get_referral_session(cookie) < 0)
2447 				cookie->new_state = EXIT;
2448 			else {
2449 				cookie->new_state = NEXT_SEARCH;
2450 			}
2451 			break;
2452 		case LDAP_ERROR:
2453 			(void) sprintf(errstr,
2454 				gettext("LDAP ERROR (%d): %s."),
2455 				cookie->err_rc,
2456 				ldap_err2string(cookie->err_rc));
2457 			err = strdup(errstr);
2458 			MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL, err,
2459 			NULL);
2460 			cookie->err_rc = NS_LDAP_INTERNAL;
2461 			cookie->errorp = *errorp;
2462 			return (ERROR);
2463 		default:
2464 		case ERROR:
2465 			(void) sprintf(errstr,
2466 				gettext("Internal State machine exit (%d).\n"),
2467 				cookie->state);
2468 			err = strdup(errstr);
2469 			MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL, err,
2470 			NULL);
2471 			cookie->err_rc = NS_LDAP_INTERNAL;
2472 			cookie->errorp = *errorp;
2473 			return (ERROR);
2474 		}
2475 
2476 		if (cycle == ONE_STEP) {
2477 			return (cookie->new_state);
2478 		}
2479 		cookie->state = cookie->new_state;
2480 	}
2481 	/*NOTREACHED*/
2482 #if 0
2483 	(void) sprintf(errstr,
2484 		gettext("Unexpected State machine error.\n"));
2485 	err = strdup(errstr);
2486 	MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL, err, NULL);
2487 	cookie->err_rc = NS_LDAP_INTERNAL;
2488 	cookie->errorp = *errorp;
2489 	return (ERROR);
2490 #endif
2491 }
2492 
2493 
2494 
2495 /*
2496  * __ns_ldap_list performs one or more LDAP searches to a given
2497  * directory server using service search descriptors and schema
2498  * mapping as appropriate.
2499  */
2500 
2501 int
2502 __ns_ldap_list(
2503 	const char *service,
2504 	const char *filter,
2505 	int (*init_filter_cb)(const ns_ldap_search_desc_t *desc,
2506 	char **realfilter, const void *userdata),
2507 	const char * const *attribute,
2508 	const ns_cred_t *auth,
2509 	const int flags,
2510 	ns_ldap_result_t **rResult, /* return result entries */
2511 	ns_ldap_error_t **errorp,
2512 	int (*callback)(const ns_ldap_entry_t *entry, const void *userdata),
2513 	const void *userdata)
2514 {
2515 	ns_ldap_cookie_t	*cookie;
2516 	ns_ldap_search_desc_t	**sdlist = NULL;
2517 	ns_ldap_search_desc_t	*dptr;
2518 	ns_ldap_error_t		*error = NULL;
2519 	char			**dns = NULL;
2520 	int			scope;
2521 	int			rc;
2522 
2523 	*errorp = NULL;
2524 
2525 	/* Initialize State machine cookie */
2526 	cookie = init_search_state_machine();
2527 	if (cookie == NULL) {
2528 		return (NS_LDAP_MEMORY);
2529 	}
2530 
2531 	/* see if need to follow referrals */
2532 	rc = __s_api_toFollowReferrals(flags,
2533 		&cookie->followRef, errorp);
2534 	if (rc != NS_LDAP_SUCCESS) {
2535 		delete_search_cookie(cookie);
2536 		return (rc);
2537 	}
2538 
2539 	/* get the service descriptor - or create a default one */
2540 	rc = __s_api_get_SSD_from_SSDtoUse_service(service,
2541 		&sdlist, errorp);
2542 	if (rc != NS_LDAP_SUCCESS) {
2543 		delete_search_cookie(cookie);
2544 		*errorp = error;
2545 		return (rc);
2546 	}
2547 
2548 	if (sdlist == NULL) {
2549 		/* Create default service Desc */
2550 		sdlist = (ns_ldap_search_desc_t **)calloc(2,
2551 					sizeof (ns_ldap_search_desc_t *));
2552 		if (sdlist == NULL) {
2553 			delete_search_cookie(cookie);
2554 			cookie = NULL;
2555 			return (NS_LDAP_MEMORY);
2556 		}
2557 		dptr = (ns_ldap_search_desc_t *)
2558 				calloc(1, sizeof (ns_ldap_search_desc_t));
2559 		if (dptr == NULL) {
2560 			free(sdlist);
2561 			delete_search_cookie(cookie);
2562 			cookie = NULL;
2563 			return (NS_LDAP_MEMORY);
2564 		}
2565 		sdlist[0] = dptr;
2566 
2567 		/* default base */
2568 		rc = __s_api_getDNs(&dns, service, &cookie->errorp);
2569 		if (rc != NS_LDAP_SUCCESS) {
2570 			if (dns) {
2571 				__s_api_free2dArray(dns);
2572 				dns = NULL;
2573 			}
2574 			*errorp = cookie->errorp;
2575 			cookie->errorp = NULL;
2576 			delete_search_cookie(cookie);
2577 			cookie = NULL;
2578 			return (rc);
2579 		}
2580 		dptr->basedn = strdup(dns[0]);
2581 		__s_api_free2dArray(dns);
2582 		dns = NULL;
2583 
2584 		/* default scope */
2585 		scope = 0;
2586 		rc = __s_api_getSearchScope(&scope, &cookie->errorp);
2587 		dptr->scope = scope;
2588 	}
2589 
2590 	cookie->sdlist = sdlist;
2591 
2592 	/*
2593 	 * use VLV/PAGE control only if NS_LDAP_PAGE_CTRL is set
2594 	 */
2595 	if (flags & NS_LDAP_PAGE_CTRL)
2596 		cookie->use_paging = TRUE;
2597 	else
2598 		cookie->use_paging = FALSE;
2599 
2600 	/* Set up other arguments */
2601 	cookie->userdata = userdata;
2602 	if (init_filter_cb != NULL) {
2603 		cookie->init_filter_cb = init_filter_cb;
2604 		cookie->use_filtercb = 1;
2605 	}
2606 	if (callback != NULL) {
2607 		cookie->callback = callback;
2608 		cookie->use_usercb = 1;
2609 	}
2610 	if (service) {
2611 		cookie->service = strdup(service);
2612 		if (cookie->service == NULL) {
2613 			delete_search_cookie(cookie);
2614 			cookie = NULL;
2615 			return (NS_LDAP_MEMORY);
2616 		}
2617 	}
2618 
2619 	cookie->i_filter = strdup(filter);
2620 	cookie->i_attr = attribute;
2621 	cookie->i_auth = auth;
2622 	cookie->i_flags = flags;
2623 
2624 	/* Process search */
2625 	rc = search_state_machine(cookie, INIT, 0);
2626 
2627 	/* Copy results back to user */
2628 	rc = cookie->err_rc;
2629 	if (rc != NS_LDAP_SUCCESS)
2630 		*errorp = cookie->errorp;
2631 	*rResult = cookie->result;
2632 
2633 	cookie->errorp = NULL;
2634 	cookie->result = NULL;
2635 	delete_search_cookie(cookie);
2636 	cookie = NULL;
2637 
2638 	if (*rResult == NULL)
2639 		rc = NS_LDAP_NOTFOUND;
2640 	return (rc);
2641 }
2642 
2643 /*
2644  * __s_api_find_domainname performs one or more LDAP searches to
2645  * find the value of the nisdomain attribute associated with
2646  * the input DN
2647  */
2648 
2649 static int
2650 __s_api_find_domainname(
2651 	const char *dn,
2652 	char **domainname,
2653 	const ns_cred_t *cred,
2654 	ns_ldap_error_t **errorp)
2655 {
2656 
2657 	ns_ldap_cookie_t	*cookie;
2658 	ns_ldap_search_desc_t	**sdlist;
2659 	ns_ldap_search_desc_t	*dptr;
2660 	int			rc;
2661 	char			**value;
2662 	int			flags = 0;
2663 
2664 	*domainname = NULL;
2665 	*errorp = NULL;
2666 
2667 	/* Initialize State machine cookie */
2668 	cookie = init_search_state_machine();
2669 	if (cookie == NULL) {
2670 		return (NS_LDAP_MEMORY);
2671 	}
2672 
2673 	/* see if need to follow referrals */
2674 	rc = __s_api_toFollowReferrals(flags,
2675 		&cookie->followRef, errorp);
2676 	if (rc != NS_LDAP_SUCCESS) {
2677 		delete_search_cookie(cookie);
2678 		return (rc);
2679 	}
2680 
2681 	/* Create default service Desc */
2682 	sdlist = (ns_ldap_search_desc_t **)calloc(2,
2683 				sizeof (ns_ldap_search_desc_t *));
2684 	if (sdlist == NULL) {
2685 		delete_search_cookie(cookie);
2686 		cookie = NULL;
2687 		return (NS_LDAP_MEMORY);
2688 	}
2689 	dptr = (ns_ldap_search_desc_t *)
2690 			calloc(1, sizeof (ns_ldap_search_desc_t));
2691 	if (dptr == NULL) {
2692 		free(sdlist);
2693 		delete_search_cookie(cookie);
2694 		cookie = NULL;
2695 		return (NS_LDAP_MEMORY);
2696 	}
2697 	sdlist[0] = dptr;
2698 
2699 	/* search base is dn */
2700 	dptr->basedn = strdup(dn);
2701 
2702 	/* search scope is base */
2703 	dptr->scope = NS_LDAP_SCOPE_BASE;
2704 
2705 	/* search filter is "nisdomain=*" */
2706 	dptr->filter = strdup(_NIS_FILTER);
2707 
2708 	cookie->sdlist = sdlist;
2709 	cookie->i_filter = strdup(dptr->filter);
2710 	cookie->i_attr = nis_domain_attrs;
2711 	cookie->i_auth = cred;
2712 	cookie->i_flags = 0;
2713 
2714 	/* Process search */
2715 	rc = search_state_machine(cookie, INIT, 0);
2716 
2717 	/* Copy domain name if found */
2718 	rc = cookie->err_rc;
2719 	if (rc != NS_LDAP_SUCCESS)
2720 		*errorp = cookie->errorp;
2721 	if (cookie->result == NULL)
2722 		rc = NS_LDAP_NOTFOUND;
2723 	if (rc == NS_LDAP_SUCCESS) {
2724 		value = __ns_ldap_getAttr(cookie->result->entry,
2725 			_NIS_DOMAIN);
2726 		if (value[0])
2727 			*domainname = strdup(value[0]);
2728 		else
2729 			rc = NS_LDAP_NOTFOUND;
2730 	}
2731 	if (cookie->result != NULL)
2732 		(void) __ns_ldap_freeResult(&cookie->result);
2733 	cookie->errorp = NULL;
2734 	delete_search_cookie(cookie);
2735 	cookie = NULL;
2736 	return (rc);
2737 }
2738 
2739 int
2740 __ns_ldap_firstEntry(
2741 	const char *service,
2742 	const char *filter,
2743 	int (*init_filter_cb)(const ns_ldap_search_desc_t *desc,
2744 	char **realfilter, const void *userdata),
2745 	const char * const *attribute,
2746 	const ns_cred_t *auth,
2747 	const int flags,
2748 	void **vcookie,
2749 	ns_ldap_result_t **result,
2750 	ns_ldap_error_t ** errorp,
2751 	const void *userdata)
2752 {
2753 	ns_ldap_cookie_t	*cookie = NULL;
2754 	ns_ldap_error_t		*error = NULL;
2755 	ns_state_t		state;
2756 	ns_ldap_search_desc_t	**sdlist;
2757 	ns_ldap_search_desc_t	*dptr;
2758 	char			**dns = NULL;
2759 	int			scope;
2760 	int			rc;
2761 
2762 	*errorp = NULL;
2763 	*result = NULL;
2764 
2765 	/* get the service descriptor - or create a default one */
2766 	rc = __s_api_get_SSD_from_SSDtoUse_service(service,
2767 			&sdlist, errorp);
2768 	if (rc != NS_LDAP_SUCCESS) {
2769 		*errorp = error;
2770 		return (rc);
2771 	}
2772 	if (sdlist == NULL) {
2773 		/* Create default service Desc */
2774 		sdlist = (ns_ldap_search_desc_t **)calloc(2,
2775 					sizeof (ns_ldap_search_desc_t *));
2776 		if (sdlist == NULL) {
2777 			return (NS_LDAP_MEMORY);
2778 		}
2779 		dptr = (ns_ldap_search_desc_t *)
2780 				calloc(1, sizeof (ns_ldap_search_desc_t));
2781 		if (dptr == NULL) {
2782 			free(sdlist);
2783 			return (NS_LDAP_MEMORY);
2784 		}
2785 		sdlist[0] = dptr;
2786 
2787 		/* default base */
2788 		rc = __s_api_getDNs(&dns, service, &error);
2789 		if (rc != NS_LDAP_SUCCESS) {
2790 			if (dns) {
2791 				__s_api_free2dArray(dns);
2792 				dns = NULL;
2793 			}
2794 			if (sdlist) {
2795 				(void) __ns_ldap_freeSearchDescriptors(
2796 					&sdlist);
2797 
2798 				sdlist = NULL;
2799 			}
2800 			*errorp = error;
2801 			return (rc);
2802 		}
2803 		dptr->basedn = strdup(dns[0]);
2804 		__s_api_free2dArray(dns);
2805 		dns = NULL;
2806 
2807 		/* default scope */
2808 		scope = 0;
2809 		cookie = init_search_state_machine();
2810 		if (cookie == NULL) {
2811 			if (sdlist) {
2812 				(void) __ns_ldap_freeSearchDescriptors(&sdlist);
2813 				sdlist = NULL;
2814 			}
2815 			return (NS_LDAP_MEMORY);
2816 		}
2817 		rc = __s_api_getSearchScope(&scope, &cookie->errorp);
2818 		dptr->scope = scope;
2819 	}
2820 
2821 	/* Initialize State machine cookie */
2822 	if (cookie == NULL)
2823 		cookie = init_search_state_machine();
2824 	if (cookie == NULL) {
2825 		if (sdlist) {
2826 			(void) __ns_ldap_freeSearchDescriptors(&sdlist);
2827 			sdlist = NULL;
2828 		}
2829 		return (NS_LDAP_MEMORY);
2830 	}
2831 
2832 	cookie->sdlist = sdlist;
2833 
2834 	/* see if need to follow referrals */
2835 	rc = __s_api_toFollowReferrals(flags,
2836 		&cookie->followRef, errorp);
2837 	if (rc != NS_LDAP_SUCCESS) {
2838 		delete_search_cookie(cookie);
2839 		return (rc);
2840 	}
2841 
2842 	/*
2843 	 * use VLV/PAGE control only if NS_LDAP_NO_PAGE_CTRL is not set
2844 	 */
2845 	if (flags & NS_LDAP_NO_PAGE_CTRL)
2846 		cookie->use_paging = FALSE;
2847 	else
2848 		cookie->use_paging = TRUE;
2849 
2850 	/* Set up other arguments */
2851 	cookie->userdata = userdata;
2852 	if (init_filter_cb != NULL) {
2853 		cookie->init_filter_cb = init_filter_cb;
2854 		cookie->use_filtercb = 1;
2855 	}
2856 	cookie->use_usercb = 0;
2857 	if (service) {
2858 		cookie->service = strdup(service);
2859 		if (cookie->service == NULL) {
2860 			delete_search_cookie(cookie);
2861 			return (NS_LDAP_MEMORY);
2862 		}
2863 	}
2864 
2865 	cookie->i_filter = strdup(filter);
2866 	cookie->i_attr = attribute;
2867 	cookie->i_auth = auth;
2868 	cookie->i_flags = flags;
2869 
2870 	state = INIT;
2871 	for (;;) {
2872 		state = search_state_machine(cookie, state, ONE_STEP);
2873 		switch (state) {
2874 		case PROCESS_RESULT:
2875 			*result = cookie->result;
2876 			cookie->result = NULL;
2877 			*vcookie = (void *)cookie;
2878 			return (NS_LDAP_SUCCESS);
2879 		case ERROR:
2880 		case LDAP_ERROR:
2881 			rc = cookie->err_rc;
2882 			*errorp = cookie->errorp;
2883 			cookie->errorp = NULL;
2884 			delete_search_cookie(cookie);
2885 			return (rc);
2886 		case EXIT:
2887 			rc = cookie->err_rc;
2888 			if (rc != NS_LDAP_SUCCESS) {
2889 				*errorp = cookie->errorp;
2890 				cookie->errorp = NULL;
2891 			} else {
2892 				rc = NS_LDAP_NOTFOUND;
2893 			}
2894 
2895 			delete_search_cookie(cookie);
2896 			return (rc);
2897 
2898 		default:
2899 			break;
2900 		}
2901 	}
2902 }
2903 
2904 /*ARGSUSED2*/
2905 int
2906 __ns_ldap_nextEntry(
2907 	void *vcookie,
2908 	ns_ldap_result_t **result,
2909 	ns_ldap_error_t ** errorp)
2910 {
2911 	ns_ldap_cookie_t	*cookie;
2912 	ns_state_t		state;
2913 	int			rc;
2914 
2915 	cookie = (ns_ldap_cookie_t *)vcookie;
2916 	cookie->result = NULL;
2917 	*result = NULL;
2918 
2919 	state = END_PROCESS_RESULT;
2920 	for (;;) {
2921 		state = search_state_machine(cookie, state, ONE_STEP);
2922 		switch (state) {
2923 		case PROCESS_RESULT:
2924 			*result = cookie->result;
2925 			cookie->result = NULL;
2926 			return (NS_LDAP_SUCCESS);
2927 		case ERROR:
2928 		case LDAP_ERROR:
2929 			rc = cookie->err_rc;
2930 			*errorp = cookie->errorp;
2931 			cookie->errorp = NULL;
2932 			return (rc);
2933 		case EXIT:
2934 			return (NS_LDAP_SUCCESS);
2935 		}
2936 	}
2937 }
2938 
2939 int
2940 __ns_ldap_endEntry(
2941 	void **vcookie,
2942 	ns_ldap_error_t ** errorp)
2943 {
2944 	ns_ldap_cookie_t	*cookie;
2945 	int			rc;
2946 
2947 	if (*vcookie == NULL)
2948 		return (NS_LDAP_INVALID_PARAM);
2949 
2950 	cookie = (ns_ldap_cookie_t *)(*vcookie);
2951 	cookie->result = NULL;
2952 
2953 	/* Complete search */
2954 	rc = search_state_machine(cookie, EXIT, 0);
2955 
2956 	/* Copy results back to user */
2957 	rc = cookie->err_rc;
2958 	if (rc != NS_LDAP_SUCCESS)
2959 		*errorp = cookie->errorp;
2960 
2961 	cookie->errorp = NULL;
2962 	delete_search_cookie(cookie);
2963 	cookie = NULL;
2964 	*vcookie = NULL;
2965 
2966 	return (rc);
2967 }
2968 
2969 
2970 int
2971 __ns_ldap_freeResult(ns_ldap_result_t **result)
2972 {
2973 
2974 	ns_ldap_entry_t	*curEntry = NULL;
2975 	ns_ldap_entry_t	*delEntry = NULL;
2976 	int		i;
2977 	ns_ldap_result_t	*res = *result;
2978 
2979 #ifdef DEBUG
2980 	(void) fprintf(stderr, "__ns_ldap_freeResult START\n");
2981 #endif
2982 	if (res == NULL)
2983 		return (NS_LDAP_INVALID_PARAM);
2984 
2985 	if (res->entry != NULL)
2986 		curEntry = res->entry;
2987 
2988 	for (i = 0; i < res->entries_count; i++) {
2989 		if (curEntry != NULL) {
2990 			delEntry = curEntry;
2991 			curEntry = curEntry->next;
2992 			__ns_ldap_freeEntry(delEntry);
2993 		}
2994 	}
2995 
2996 	free(res);
2997 	*result = NULL;
2998 	return (NS_LDAP_SUCCESS);
2999 }
3000 
3001 /*ARGSUSED*/
3002 int
3003 __ns_ldap_auth(const ns_cred_t *auth,
3004 		    const int flags,
3005 		    ns_ldap_error_t **errorp,
3006 		    LDAPControl **serverctrls,
3007 		    LDAPControl **clientctrls)
3008 {
3009 
3010 	ConnectionID	connectionId = -1;
3011 	Connection	*conp;
3012 	int		rc = 0;
3013 	int		do_not_fail_if_new_pwd_reqd = 0;
3014 	int		nopasswd_acct_mgmt = 0;
3015 
3016 
3017 #ifdef DEBUG
3018 	(void) fprintf(stderr, "__ns_ldap_auth START\n");
3019 #endif
3020 
3021 	*errorp = NULL;
3022 	if (!auth)
3023 		return (NS_LDAP_INVALID_PARAM);
3024 
3025 	rc = __s_api_getConnection(NULL, flags,
3026 			auth, &connectionId, &conp, errorp,
3027 			do_not_fail_if_new_pwd_reqd, nopasswd_acct_mgmt);
3028 	if (rc == NS_LDAP_OP_FAILED && *errorp)
3029 		(void) __ns_ldap_freeError(errorp);
3030 
3031 	if (connectionId > -1)
3032 		DropConnection(connectionId, flags);
3033 	return (rc);
3034 }
3035 
3036 char **
3037 __ns_ldap_getAttr(const ns_ldap_entry_t *entry, const char *attrname)
3038 {
3039 	int	i;
3040 
3041 	if (entry == NULL)
3042 		return (NULL);
3043 	for (i = 0; i < entry->attr_count; i++) {
3044 		if (strcasecmp(entry->attr_pair[i]->attrname, attrname) == NULL)
3045 			return (entry->attr_pair[i]->attrvalue);
3046 	}
3047 	return (NULL);
3048 }
3049 
3050 
3051 /*ARGSUSED*/
3052 int
3053 __ns_ldap_uid2dn(const char *uid,
3054 		char **userDN,
3055 		const ns_cred_t *cred,	/* cred is ignored */
3056 		ns_ldap_error_t **errorp)
3057 {
3058 	ns_ldap_result_t	*result = NULL;
3059 	char		*filter, *userdata;
3060 	char		errstr[MAXERROR];
3061 	char		**value;
3062 	int		rc = 0;
3063 	int		i = 0;
3064 	size_t		len;
3065 
3066 	*errorp = NULL;
3067 	*userDN = NULL;
3068 	if ((uid == NULL) || (uid[0] == '\0'))
3069 		return (NS_LDAP_INVALID_PARAM);
3070 
3071 	while (uid[i] != '\0') {
3072 		if (uid[i] == '=') {
3073 			*userDN = strdup(uid);
3074 			return (NS_LDAP_SUCCESS);
3075 		}
3076 		i++;
3077 	}
3078 	i = 0;
3079 	while ((uid[i] != '\0') && (isdigit(uid[i])))
3080 		i++;
3081 	if (uid[i] == '\0') {
3082 		len = strlen(UIDNUMFILTER) + strlen(uid) + 1;
3083 		filter = (char *)malloc(len);
3084 		if (filter == NULL) {
3085 			*userDN = NULL;
3086 			return (NS_LDAP_MEMORY);
3087 		}
3088 		(void) snprintf(filter, len, UIDNUMFILTER, uid);
3089 
3090 		len = strlen(UIDNUMFILTER_SSD) + strlen(uid) + 1;
3091 		userdata = (char *)malloc(len);
3092 		if (userdata == NULL) {
3093 			*userDN = NULL;
3094 			return (NS_LDAP_MEMORY);
3095 		}
3096 		(void) snprintf(userdata, len, UIDNUMFILTER_SSD, uid);
3097 	} else {
3098 		len = strlen(UIDFILTER) + strlen(uid) + 1;
3099 		filter = (char *)malloc(len);
3100 		if (filter == NULL) {
3101 			*userDN = NULL;
3102 			return (NS_LDAP_MEMORY);
3103 		}
3104 		(void) snprintf(filter, len, UIDFILTER, uid);
3105 
3106 		len = strlen(UIDFILTER_SSD) + strlen(uid) + 1;
3107 		userdata = (char *)malloc(len);
3108 		if (userdata == NULL) {
3109 			*userDN = NULL;
3110 			return (NS_LDAP_MEMORY);
3111 		}
3112 		(void) snprintf(userdata, len, UIDFILTER_SSD, uid);
3113 	}
3114 
3115 	/*
3116 	 * we want to retrieve the DN as it appears in LDAP
3117 	 * hence the use of NS_LDAP_NOT_CVT_DN in flags
3118 	 */
3119 	rc = __ns_ldap_list("passwd", filter,
3120 				__s_api_merge_SSD_filter,
3121 				NULL, cred, NS_LDAP_NOT_CVT_DN,
3122 				&result, errorp, NULL,
3123 				userdata);
3124 	free(filter);
3125 	filter = NULL;
3126 	free(userdata);
3127 	userdata = NULL;
3128 	if (rc != NS_LDAP_SUCCESS) {
3129 		if (result) {
3130 			(void) __ns_ldap_freeResult(&result);
3131 			result = NULL;
3132 		}
3133 		return (rc);
3134 	}
3135 	if (result->entries_count > 1) {
3136 		(void) __ns_ldap_freeResult(&result);
3137 		result = NULL;
3138 		*userDN = NULL;
3139 		(void) sprintf(errstr,
3140 			gettext("Too many entries are returned for %s"), uid);
3141 		MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL, strdup(errstr),
3142 			NULL);
3143 		return (NS_LDAP_INTERNAL);
3144 	}
3145 
3146 	value = __ns_ldap_getAttr(result->entry, "dn");
3147 	*userDN = strdup(value[0]);
3148 	(void) __ns_ldap_freeResult(&result);
3149 	result = NULL;
3150 	return (NS_LDAP_SUCCESS);
3151 }
3152 
3153 
3154 /*ARGSUSED*/
3155 int
3156 __ns_ldap_host2dn(const char *host,
3157 		const char *domain,
3158 		char **hostDN,
3159 		const ns_cred_t *cred,	/* cred is ignored */
3160 		ns_ldap_error_t **errorp)
3161 {
3162 	ns_ldap_result_t	*result = NULL;
3163 	char		*filter, *userdata;
3164 	char		errstr[MAXERROR];
3165 	char		**value;
3166 	int		rc;
3167 	size_t		len;
3168 
3169 /*
3170  * XXX
3171  * the domain parameter needs to be used in case domain is not local, if
3172  * this routine is to support multi domain setups, it needs lots of work...
3173  */
3174 	*errorp = NULL;
3175 	*hostDN = NULL;
3176 	if ((host == NULL) || (host[0] == '\0'))
3177 		return (NS_LDAP_INVALID_PARAM);
3178 
3179 	len = strlen(HOSTFILTER) + strlen(host) + 1;
3180 	filter = (char *)malloc(len);
3181 	if (filter == NULL) {
3182 		return (NS_LDAP_MEMORY);
3183 	}
3184 	(void) snprintf(filter,	len, HOSTFILTER, host);
3185 
3186 	len = strlen(HOSTFILTER_SSD) + strlen(host) + 1;
3187 	userdata = (char *)malloc(len);
3188 	if (userdata == NULL) {
3189 		return (NS_LDAP_MEMORY);
3190 	}
3191 	(void) snprintf(userdata, len, HOSTFILTER_SSD, host);
3192 
3193 	/*
3194 	 * we want to retrieve the DN as it appears in LDAP
3195 	 * hence the use of NS_LDAP_NOT_CVT_DN in flags
3196 	 */
3197 	rc = __ns_ldap_list("hosts", filter,
3198 				__s_api_merge_SSD_filter,
3199 				NULL, cred, NS_LDAP_NOT_CVT_DN, &result,
3200 				errorp, NULL,
3201 				userdata);
3202 	free(filter);
3203 	filter = NULL;
3204 	free(userdata);
3205 	userdata = NULL;
3206 	if (rc != NS_LDAP_SUCCESS) {
3207 		if (result) {
3208 			(void) __ns_ldap_freeResult(&result);
3209 			result = NULL;
3210 		}
3211 		return (rc);
3212 	}
3213 
3214 	if (result->entries_count > 1) {
3215 		(void) __ns_ldap_freeResult(&result);
3216 		result = NULL;
3217 		*hostDN = NULL;
3218 		(void) sprintf(errstr,
3219 			gettext("Too many entries are returned for %s"), host);
3220 		MKERROR(LOG_WARNING, *errorp, NS_LDAP_INTERNAL, strdup(errstr),
3221 			NULL);
3222 		return (NS_LDAP_INTERNAL);
3223 	}
3224 
3225 	value = __ns_ldap_getAttr(result->entry, "dn");
3226 	*hostDN = strdup(value[0]);
3227 	(void) __ns_ldap_freeResult(&result);
3228 	result = NULL;
3229 	return (NS_LDAP_SUCCESS);
3230 }
3231 
3232 /*ARGSUSED*/
3233 int
3234 __ns_ldap_dn2domain(const char *dn,
3235 			char **domain,
3236 			const ns_cred_t *cred,
3237 			ns_ldap_error_t **errorp)
3238 {
3239 	int		rc, pnum, i, j, len = 0;
3240 	char		*newdn, **rdns = NULL;
3241 	char		**dns, *dn1;
3242 
3243 	*errorp = NULL;
3244 
3245 	if (domain == NULL)
3246 		return (NS_LDAP_INVALID_PARAM);
3247 	else
3248 		*domain = NULL;
3249 
3250 	if ((dn == NULL) || (dn[0] == '\0'))
3251 		return (NS_LDAP_INVALID_PARAM);
3252 
3253 	/*
3254 	 * break dn into rdns
3255 	 */
3256 	dn1 = strdup(dn);
3257 	if (dn1 == NULL)
3258 		return (NS_LDAP_MEMORY);
3259 	rdns = ldap_explode_dn(dn1, 0);
3260 	free(dn1);
3261 	if (rdns == NULL || *rdns == NULL)
3262 		return (NS_LDAP_INVALID_PARAM);
3263 
3264 	for (i = 0; rdns[i]; i++)
3265 		len += strlen(rdns[i]) + 1;
3266 	pnum = i;
3267 
3268 	newdn = (char *)malloc(len + 1);
3269 	dns = (char **)calloc(pnum, sizeof (char *));
3270 	if (newdn == NULL || dns == NULL) {
3271 		if (newdn)
3272 			free(newdn);
3273 		ldap_value_free(rdns);
3274 		return (NS_LDAP_MEMORY);
3275 	}
3276 
3277 	/* construct a semi-normalized dn, newdn */
3278 	*newdn = '\0';
3279 	for (i = 0; rdns[i]; i++) {
3280 		dns[i] = newdn + strlen(newdn);
3281 		(void) strcat(newdn,
3282 			__s_api_remove_rdn_space(rdns[i]));
3283 		(void) strcat(newdn, ",");
3284 	}
3285 	/* remove the last ',' */
3286 	newdn[strlen(newdn) - 1] = '\0';
3287 	ldap_value_free(rdns);
3288 
3289 	/*
3290 	 * loop and find the domain name associated with newdn,
3291 	 * removing rdn one by one from left to right
3292 	 */
3293 	for (i = 0; i < pnum; i++) {
3294 
3295 		if (*errorp)
3296 			(void) __ns_ldap_freeError(errorp);
3297 
3298 		/*
3299 		 *  try cache manager first
3300 		 */
3301 		rc = __s_api_get_cachemgr_data(NS_CACHE_DN2DOMAIN,
3302 				dns[i], domain);
3303 		if (rc != NS_LDAP_SUCCESS) {
3304 			/*
3305 			 *  try ldap server second
3306 			 */
3307 			rc = __s_api_find_domainname(dns[i], domain,
3308 				cred, errorp);
3309 		} else {
3310 			/*
3311 			 * skip the last one,
3312 			 * since it is already cached by ldap_cachemgr
3313 			 */
3314 			i--;
3315 		}
3316 		if (rc == NS_LDAP_SUCCESS) {
3317 			/*
3318 			 * ask cache manager to save the
3319 			 * dn to domain mapping(s)
3320 			 */
3321 			for (j = 0; j <= i; j++) {
3322 				(void) __s_api_set_cachemgr_data(
3323 					NS_CACHE_DN2DOMAIN,
3324 					dns[j],
3325 					*domain);
3326 			}
3327 			break;
3328 		}
3329 	}
3330 
3331 	free(dns);
3332 	free(newdn);
3333 	if (rc != NS_LDAP_SUCCESS)
3334 		rc = NS_LDAP_NOTFOUND;
3335 	return (rc);
3336 }
3337 
3338 /*ARGSUSED*/
3339 int
3340 __ns_ldap_getServiceAuthMethods(const char *service,
3341 		ns_auth_t ***auth,
3342 		ns_ldap_error_t **errorp)
3343 {
3344 	char		errstr[MAXERROR];
3345 	int		rc, i, done = 0;
3346 	int		slen;
3347 	void		**param;
3348 	char		**sam, *srv, *send;
3349 	ns_auth_t	**authpp = NULL, *ap;
3350 	int		cnt, max;
3351 	ns_config_t	*cfg;
3352 	ns_ldap_error_t	*error = NULL;
3353 
3354 	if (errorp == NULL)
3355 		return (NS_LDAP_INVALID_PARAM);
3356 	*errorp = NULL;
3357 
3358 	if ((service == NULL) || (service[0] == '\0') ||
3359 		(auth == NULL))
3360 		return (NS_LDAP_INVALID_PARAM);
3361 
3362 	*auth = NULL;
3363 	rc = __ns_ldap_getParam(NS_LDAP_SERVICE_AUTH_METHOD_P, &param, &error);
3364 	if (rc != NS_LDAP_SUCCESS || param == NULL) {
3365 		*errorp = error;
3366 		return (rc);
3367 	}
3368 	sam = (char **)param;
3369 
3370 	cfg = __s_api_get_default_config();
3371 	cnt = 0;
3372 
3373 	slen = strlen(service);
3374 
3375 	for (; *sam; sam++) {
3376 		srv = *sam;
3377 		if (strncasecmp(service, srv, slen) != 0)
3378 			continue;
3379 		srv += slen;
3380 		if (*srv != COLONTOK)
3381 			continue;
3382 		send = srv;
3383 		srv++;
3384 		for (max = 1; (send = strchr(++send, SEMITOK)) != NULL;
3385 			max++) {}
3386 		authpp = (ns_auth_t **)calloc(++max, sizeof (ns_auth_t *));
3387 		if (authpp == NULL) {
3388 			(void) __ns_ldap_freeParam(&param);
3389 			__s_api_release_config(cfg);
3390 			return (NS_LDAP_MEMORY);
3391 		}
3392 		while (!done) {
3393 			send = strchr(srv, SEMITOK);
3394 			if (send != NULL) {
3395 				*send = '\0';
3396 				send++;
3397 			}
3398 			i = __s_get_enum_value(cfg, srv, NS_LDAP_AUTH_P);
3399 			if (i == -1) {
3400 				(void) __ns_ldap_freeParam(&param);
3401 				(void) sprintf(errstr,
3402 		gettext("Unsupported serviceAuthenticationMethod: %s.\n"), srv);
3403 				MKERROR(LOG_WARNING, *errorp, NS_CONFIG_SYNTAX,
3404 					strdup(errstr), NULL);
3405 				__s_api_release_config(cfg);
3406 				return (NS_LDAP_CONFIG);
3407 			}
3408 			ap = __s_api_AuthEnumtoStruct((EnumAuthType_t)i);
3409 			if (ap == NULL) {
3410 				(void) __ns_ldap_freeParam(&param);
3411 				__s_api_release_config(cfg);
3412 				return (NS_LDAP_MEMORY);
3413 			}
3414 			authpp[cnt++] = ap;
3415 			if (send == NULL)
3416 				done = TRUE;
3417 			else
3418 				srv = send;
3419 		}
3420 	}
3421 
3422 	*auth = authpp;
3423 	(void) __ns_ldap_freeParam(&param);
3424 	__s_api_release_config(cfg);
3425 	return (NS_LDAP_SUCCESS);
3426 }
3427 
3428 /*
3429  * This routine is called when certain scenario occurs
3430  * e.g.
3431  * service == auto_home
3432  * SSD = automount: ou = mytest,
3433  * NS_LDAP_MAPATTRIBUTE= auto_home: automountMapName=AAA
3434  * NS_LDAP_OBJECTCLASSMAP= auto_home:automountMap=MynisMap
3435  * NS_LDAP_OBJECTCLASSMAP= auto_home:automount=MynisObject
3436  *
3437  * The automountMapName is prepended implicitely but is mapped
3438  * to AAA. So dn could appers as
3439  * dn: AAA=auto_home,ou=bar,dc=foo,dc=com
3440  * dn: automountKey=user_01,AAA=auto_home,ou=bar,dc=foo,dc=com
3441  * dn: automountKey=user_02,AAA=auto_home,ou=bar,dc=foo,dc=com
3442  * in the directory.
3443  * This function is called to covert the mapped attr back to
3444  * orig attr when the entries are searched and returned
3445  */
3446 
3447 int
3448 __s_api_convert_automountmapname(const char *service, char **dn,
3449 		ns_ldap_error_t **errp) {
3450 
3451 	char	**mapping = NULL;
3452 	char	*mapped_attr = NULL;
3453 	char	*automountmapname = "automountMapName";
3454 	char	*buffer = NULL;
3455 	int	rc = NS_LDAP_SUCCESS;
3456 	char	errstr[MAXERROR];
3457 
3458 	/*
3459 	 * dn is an input/out parameter, check it first
3460 	 */
3461 
3462 	if (service == NULL || dn == NULL || *dn == NULL)
3463 		return (NS_LDAP_INVALID_PARAM);
3464 
3465 	/*
3466 	 * Check to see if there is a mapped attribute for auto_xxx
3467 	 */
3468 
3469 	mapping = __ns_ldap_getMappedAttributes(service, automountmapname);
3470 
3471 	/*
3472 	 * if no mapped attribute for auto_xxx, try automount
3473 	 */
3474 
3475 	if (mapping == NULL)
3476 		mapping = __ns_ldap_getMappedAttributes(
3477 			"automount", automountmapname);
3478 
3479 	/*
3480 	 * if no mapped attribute is found, return SUCCESS (no op)
3481 	 */
3482 
3483 	if (mapping == NULL)
3484 		return (NS_LDAP_SUCCESS);
3485 
3486 	/*
3487 	 * if the mapped attribute is found and attr is not empty,
3488 	 * copy it
3489 	 */
3490 
3491 	if (mapping[0] != NULL) {
3492 		mapped_attr = strdup(mapping[0]);
3493 		__s_api_free2dArray(mapping);
3494 		if (mapped_attr == NULL) {
3495 			return (NS_LDAP_MEMORY);
3496 		}
3497 	} else {
3498 		__s_api_free2dArray(mapping);
3499 
3500 		(void) snprintf(errstr, (2 * MAXERROR),
3501 			gettext(
3502 			"Attribute nisMapName is mapped to an "
3503 			"empty string.\n"));
3504 
3505 		MKERROR(LOG_ERR, *errp, NS_CONFIG_SYNTAX,
3506 			strdup(errstr), NULL);
3507 
3508 		return (NS_LDAP_CONFIG);
3509 	}
3510 
3511 	/*
3512 	 * Locate the mapped attribute in the dn
3513 	 * and replace it if it exists
3514 	 */
3515 
3516 	rc = __s_api_replace_mapped_attr_in_dn(
3517 		(const char *) automountmapname, (const char *) mapped_attr,
3518 		(const char *) *dn, &buffer);
3519 
3520 	/* clean up */
3521 
3522 	free(mapped_attr);
3523 
3524 	/*
3525 	 * If mapped attr is found(buffer != NULL)
3526 	 *	a new dn is returned
3527 	 * If no mapped attribute is in dn,
3528 	 *	return NS_LDAP_SUCCESS (no op)
3529 	 * If no memory,
3530 	 *	return NS_LDAP_MEMORY (no op)
3531 	 */
3532 
3533 	if (buffer != NULL) {
3534 		free(*dn);
3535 		*dn = buffer;
3536 	}
3537 
3538 	return (rc);
3539 }
3540 
3541 /*
3542  * If the mapped attr is found in the dn,
3543  * 	return NS_LDAP_SUCCESS and a new_dn.
3544  * If no mapped attr is found,
3545  * 	return NS_LDAP_SUCCESS and *new_dn == NULL
3546  * If there is not enough memory,
3547  * 	return NS_LDAP_MEMORY and *new_dn == NULL
3548  */
3549 
3550 int
3551 __s_api_replace_mapped_attr_in_dn(
3552 	const char *orig_attr, const char *mapped_attr,
3553 	const char *dn, char **new_dn) {
3554 
3555 	char	**dnArray = NULL;
3556 	char	*cur = NULL, *start = NULL;
3557 	int	i = 0, found = 0;
3558 	int	len = 0, orig_len = 0, mapped_len = 0;
3559 	int	dn_len = 0, tmp_len = 0;
3560 
3561 	*new_dn = NULL;
3562 
3563 	/*
3564 	 * seperate dn into individual componets
3565 	 * e.g.
3566 	 * "automountKey=user_01" , "automountMapName_test=auto_home", ...
3567 	 */
3568 	dnArray = ldap_explode_dn(dn, 0);
3569 
3570 	/*
3571 	 * This will find "mapped attr=value" in dn.
3572 	 * It won't find match if mapped attr appears
3573 	 * in the value.
3574 	 */
3575 	for (i = 0; dnArray[i] != NULL; i++) {
3576 		/*
3577 		 * This function is called when reading from
3578 		 * the directory so assume each component has "=".
3579 		 * Any ill formatted dn should be rejected
3580 		 * before adding to the directory
3581 		 */
3582 		cur = strchr(dnArray[i], '=');
3583 		*cur = '\0';
3584 		if (strcasecmp(mapped_attr, dnArray[i]) == 0)
3585 			found = 1;
3586 		*cur = '=';
3587 		if (found) break;
3588 	}
3589 
3590 	if (!found) {
3591 		__s_api_free2dArray(dnArray);
3592 		*new_dn = NULL;
3593 		return (NS_LDAP_SUCCESS);
3594 	}
3595 	/*
3596 	 * The new length is *dn length + (difference between
3597 	 * orig attr and mapped attr) + 1 ;
3598 	 * e.g.
3599 	 * automountKey=aa,automountMapName_test=auto_home,dc=foo,dc=com
3600 	 * ==>
3601 	 * automountKey=aa,automountMapName=auto_home,dc=foo,dc=com
3602 	 */
3603 	mapped_len = strlen(mapped_attr);
3604 	orig_len = strlen(orig_attr);
3605 	dn_len = strlen(dn);
3606 	len = dn_len + orig_len - mapped_len + 1;
3607 	*new_dn = (char *)calloc(1, len);
3608 	if (*new_dn == NULL) {
3609 		__s_api_free2dArray(dnArray);
3610 		return (NS_LDAP_MEMORY);
3611 	}
3612 
3613 	/*
3614 	 * Locate the mapped attr in the dn.
3615 	 * Use dnArray[i] instead of mapped_attr
3616 	 * because mapped_attr could appear in
3617 	 * the value
3618 	 */
3619 
3620 	cur = strstr(dn, dnArray[i]);
3621 	__s_api_free2dArray(dnArray);
3622 	/* copy the portion before mapped attr in dn  */
3623 	start = *new_dn;
3624 	tmp_len = cur - dn;
3625 	(void) memcpy((void *) start, (const void*) dn, tmp_len);
3626 
3627 	/*
3628 	 * Copy the orig_attr. e.g. automountMapName
3629 	 * This replaces mapped attr with orig attr
3630 	 */
3631 	start = start + (cur - dn); /* move cursor in buffer */
3632 	(void) memcpy((void *) start, (const void*) orig_attr, orig_len);
3633 
3634 	/*
3635 	 * Copy the portion after mapped attr in dn
3636 	 */
3637 	cur = cur + mapped_len; /* move cursor in  dn  */
3638 	start = start + orig_len; /* move cursor in buffer */
3639 	(void) strcpy(start, cur);
3640 
3641 	return (NS_LDAP_SUCCESS);
3642 }
3643 
3644 /*
3645  * Validate Filter functions
3646  */
3647 
3648 /* ***** Start of modified libldap.so.5 filter parser ***** */
3649 
3650 /* filter parsing routine forward references */
3651 static int adj_filter_list(char *str);
3652 static int adj_simple_filter(char *str);
3653 static int unescape_filterval(char *val);
3654 static int hexchar2int(char c);
3655 static int adj_substring_filter(char *val);
3656 
3657 
3658 /*
3659  * assumes string manipulation is in-line
3660  * and all strings are sufficient in size
3661  * return value is the position after 'c'
3662  */
3663 
3664 static char *
3665 resync_str(char *str, char *next, char c)
3666 {
3667 	char	*ret;
3668 
3669 	ret = str + strlen(str);
3670 	*next = c;
3671 	if (ret == next)
3672 		return (ret);
3673 	(void) strcat(str, next);
3674 	return (ret);
3675 }
3676 
3677 static char *
3678 find_right_paren(char *s)
3679 {
3680 	int	balance, escape;
3681 
3682 	balance = 1;
3683 	escape = 0;
3684 	while (*s && balance) {
3685 		if (escape == 0) {
3686 			if (*s == '(')
3687 				balance++;
3688 			else if (*s == ')')
3689 				balance--;
3690 		}
3691 		if (*s == '\\' && ! escape)
3692 			escape = 1;
3693 		else
3694 			escape = 0;
3695 		if (balance)
3696 			s++;
3697 	}
3698 
3699 	return (*s ? s : NULL);
3700 }
3701 
3702 static char *
3703 adj_complex_filter(char	*str)
3704 {
3705 	char	*next;
3706 
3707 	/*
3708 	 * We have (x(filter)...) with str sitting on
3709 	 * the x.  We have to find the paren matching
3710 	 * the one before the x and put the intervening
3711 	 * filters by calling adj_filter_list().
3712 	 */
3713 
3714 	str++;
3715 	if ((next = find_right_paren(str)) == NULL)
3716 		return (NULL);
3717 
3718 	*next = '\0';
3719 	if (adj_filter_list(str) == -1)
3720 		return (NULL);
3721 	next = resync_str(str, next, ')');
3722 	next++;
3723 
3724 	return (next);
3725 }
3726 
3727 static int
3728 adj_filter(char *str)
3729 {
3730 	char	*next;
3731 	int	parens, balance, escape;
3732 	char	*np, *cp,  *dp;
3733 
3734 	parens = 0;
3735 	while (*str) {
3736 		switch (*str) {
3737 		case '(':
3738 			str++;
3739 			parens++;
3740 			switch (*str) {
3741 			case '&':
3742 				if ((str = adj_complex_filter(str)) == NULL)
3743 					return (-1);
3744 
3745 				parens--;
3746 				break;
3747 
3748 			case '|':
3749 				if ((str = adj_complex_filter(str)) == NULL)
3750 					return (-1);
3751 
3752 				parens--;
3753 				break;
3754 
3755 			case '!':
3756 				if ((str = adj_complex_filter(str)) == NULL)
3757 					return (-1);
3758 
3759 				parens--;
3760 				break;
3761 
3762 			case '(':
3763 				/* illegal ((case - generated by conversion */
3764 
3765 				/* find missing close) */
3766 				np = find_right_paren(str+1);
3767 
3768 				/* error if not found */
3769 				if (np == NULL)
3770 					return (-1);
3771 
3772 				/* remove redundant (and) */
3773 				for (dp = str, cp = str+1; cp < np; ) {
3774 					*dp++ = *cp++;
3775 				}
3776 				cp++;
3777 				while (*cp)
3778 					*dp++ = *cp++;
3779 				*dp = '\0';
3780 
3781 				/* re-start test at original ( */
3782 				parens--;
3783 				str--;
3784 				break;
3785 
3786 			default:
3787 				balance = 1;
3788 				escape = 0;
3789 				next = str;
3790 				while (*next && balance) {
3791 					if (escape == 0) {
3792 						if (*next == '(')
3793 							balance++;
3794 						else if (*next == ')')
3795 							balance--;
3796 					}
3797 					if (*next == '\\' && ! escape)
3798 						escape = 1;
3799 					else
3800 						escape = 0;
3801 					if (balance)
3802 						next++;
3803 				}
3804 				if (balance != 0)
3805 					return (-1);
3806 
3807 				*next = '\0';
3808 				if (adj_simple_filter(str) == -1) {
3809 					return (-1);
3810 				}
3811 				next = resync_str(str, next, ')');
3812 				next++;
3813 				str = next;
3814 				parens--;
3815 				break;
3816 			}
3817 			break;
3818 
3819 		case ')':
3820 			str++;
3821 			parens--;
3822 			break;
3823 
3824 		case ' ':
3825 			str++;
3826 			break;
3827 
3828 		default:	/* assume it's a simple type=value filter */
3829 			next = strchr(str, '\0');
3830 			if (adj_simple_filter(str) == -1) {
3831 				return (-1);
3832 			}
3833 			str = next;
3834 			break;
3835 		}
3836 	}
3837 
3838 	return (parens ? -1 : 0);
3839 }
3840 
3841 
3842 /*
3843  * Put a list of filters like this "(filter1)(filter2)..."
3844  */
3845 
3846 static int
3847 adj_filter_list(char *str)
3848 {
3849 	char	*next;
3850 	char	save;
3851 
3852 	while (*str) {
3853 		while (*str && isspace(*str))
3854 			str++;
3855 		if (*str == '\0')
3856 			break;
3857 
3858 		if ((next = find_right_paren(str + 1)) == NULL)
3859 			return (-1);
3860 		save = *++next;
3861 
3862 		/* now we have "(filter)" with str pointing to it */
3863 		*next = '\0';
3864 		if (adj_filter(str) == -1)
3865 			return (-1);
3866 		next = resync_str(str, next, save);
3867 
3868 		str = next;
3869 	}
3870 
3871 	return (0);
3872 }
3873 
3874 
3875 /*
3876  * is_valid_attr - returns 1 if a is a syntactically valid left-hand side
3877  * of a filter expression, 0 otherwise.  A valid string may contain only
3878  * letters, numbers, hyphens, semi-colons, colons and periods. examples:
3879  *	cn
3880  *	cn;lang-fr
3881  *	1.2.3.4;binary;dynamic
3882  *	mail;dynamic
3883  *	cn:dn:1.2.3.4
3884  *
3885  * For compatibility with older servers, we also allow underscores in
3886  * attribute types, even through they are not allowed by the LDAPv3 RFCs.
3887  */
3888 static int
3889 is_valid_attr(char *a)
3890 {
3891 	for (; *a; a++) {
3892 		if (!isascii(*a)) {
3893 			return (0);
3894 		} else if (!isalnum(*a)) {
3895 			switch (*a) {
3896 			case '-':
3897 			case '.':
3898 			case ';':
3899 			case ':':
3900 			case '_':
3901 				break; /* valid */
3902 			default:
3903 				return (0);
3904 			}
3905 		}
3906 	}
3907 	return (1);
3908 }
3909 
3910 static char *
3911 find_star(char *s)
3912 {
3913 	for (; *s; ++s) {
3914 		switch (*s) {
3915 		case '*':
3916 			return (s);
3917 		case '\\':
3918 			++s;
3919 			if (hexchar2int(s[0]) >= 0 && hexchar2int(s[1]) >= 0)
3920 				++s;
3921 		default:
3922 			break;
3923 		}
3924 	}
3925 	return (NULL);
3926 }
3927 
3928 static int
3929 adj_simple_filter(char *str)
3930 {
3931 	char		*s, *s2, *s3, filterop;
3932 	char		*value;
3933 	int		ftype = 0;
3934 	int		rc;
3935 
3936 	rc = -1;	/* pessimistic */
3937 
3938 	if ((str = strdup(str)) == NULL) {
3939 		return (rc);
3940 	}
3941 
3942 	if ((s = strchr(str, '=')) == NULL) {
3943 		goto free_and_return;
3944 	}
3945 	value = s + 1;
3946 	*s-- = '\0';
3947 	filterop = *s;
3948 	if (filterop == '<' || filterop == '>' || filterop == '~' ||
3949 	    filterop == ':') {
3950 		*s = '\0';
3951 	}
3952 
3953 	if (! is_valid_attr(str)) {
3954 		goto free_and_return;
3955 	}
3956 
3957 	switch (filterop) {
3958 	case '<': /* LDAP_FILTER_LE */
3959 	case '>': /* LDAP_FILTER_GE */
3960 	case '~': /* LDAP_FILTER_APPROX */
3961 		break;
3962 	case ':':	/* extended filter - v3 only */
3963 		/*
3964 		 * extended filter looks like this:
3965 		 *
3966 		 *	[type][':dn'][':'oid]':='value
3967 		 *
3968 		 * where one of type or :oid is required.
3969 		 *
3970 		 */
3971 		s2 = s3 = NULL;
3972 		if ((s2 = strrchr(str, ':')) == NULL) {
3973 			goto free_and_return;
3974 		}
3975 		if (strcasecmp(s2, ":dn") == 0) {
3976 			*s2 = '\0';
3977 		} else {
3978 			*s2 = '\0';
3979 			if ((s3 = strrchr(str, ':')) != NULL) {
3980 				if (strcasecmp(s3, ":dn") != 0) {
3981 					goto free_and_return;
3982 				}
3983 				*s3 = '\0';
3984 			}
3985 		}
3986 		if (unescape_filterval(value) < 0) {
3987 			goto free_and_return;
3988 		}
3989 		rc = 0;
3990 		goto free_and_return;
3991 		/* break; */
3992 	default:
3993 		if (find_star(value) == NULL) {
3994 			ftype = 0; /* LDAP_FILTER_EQUALITY */
3995 		} else if (strcmp(value, "*") == 0) {
3996 			ftype = 1; /* LDAP_FILTER_PRESENT */
3997 		} else {
3998 			rc = adj_substring_filter(value);
3999 			goto free_and_return;
4000 		}
4001 		break;
4002 	}
4003 
4004 	if (ftype != 0) {	/* == LDAP_FILTER_PRESENT */
4005 		rc = 0;
4006 	} else if (unescape_filterval(value) >= 0) {
4007 		rc = 0;
4008 	}
4009 	if (rc != -1) {
4010 		rc = 0;
4011 	}
4012 
4013 free_and_return:
4014 	free(str);
4015 	return (rc);
4016 }
4017 
4018 
4019 /*
4020  * Check in place both LDAPv2 (RFC-1960) and LDAPv3 (hexadecimal) escape
4021  * sequences within the null-terminated string 'val'.
4022  *
4023  * If 'val' contains invalid escape sequences we return -1.
4024  * Otherwise return 1
4025  */
4026 static int
4027 unescape_filterval(char *val)
4028 {
4029 	int	escape, firstdigit;
4030 	char	*s;
4031 
4032 	firstdigit = 0;
4033 	escape = 0;
4034 	for (s = val; *s; s++) {
4035 		if (escape) {
4036 			/*
4037 			 * first try LDAPv3 escape (hexadecimal) sequence
4038 			 */
4039 			if (hexchar2int(*s) < 0) {
4040 				if (firstdigit) {
4041 					/*
4042 					 * LDAPv2 (RFC1960) escape sequence
4043 					 */
4044 					escape = 0;
4045 				} else {
4046 					return (-1);
4047 				}
4048 			}
4049 			if (firstdigit) {
4050 			    firstdigit = 0;
4051 			} else {
4052 			    escape = 0;
4053 			}
4054 
4055 		} else if (*s != '\\') {
4056 			escape = 0;
4057 
4058 		} else {
4059 			escape = 1;
4060 			firstdigit = 1;
4061 		}
4062 	}
4063 
4064 	return (1);
4065 }
4066 
4067 
4068 /*
4069  * convert character 'c' that represents a hexadecimal digit to an integer.
4070  * if 'c' is not a hexidecimal digit [0-9A-Fa-f], -1 is returned.
4071  * otherwise the converted value is returned.
4072  */
4073 static int
4074 hexchar2int(char c)
4075 {
4076 	if (c >= '0' && c <= '9') {
4077 		return (c - '0');
4078 	}
4079 	if (c >= 'A' && c <= 'F') {
4080 		return (c - 'A' + 10);
4081 	}
4082 	if (c >= 'a' && c <= 'f') {
4083 		return (c - 'a' + 10);
4084 	}
4085 	return (-1);
4086 }
4087 
4088 static int
4089 adj_substring_filter(char *val)
4090 {
4091 	char		*nextstar;
4092 
4093 	for (; val != NULL; val = nextstar) {
4094 		if ((nextstar = find_star(val)) != NULL) {
4095 			*nextstar++ = '\0';
4096 		}
4097 
4098 		if (*val != '\0') {
4099 			if (unescape_filterval(val) < 0) {
4100 				return (-1);
4101 			}
4102 		}
4103 	}
4104 
4105 	return (0);
4106 }
4107 
4108 /* ***** End of modified libldap.so.5 filter parser ***** */
4109 
4110 
4111 /*
4112  * Walk filter, remove redundant parentheses in-line
4113  * verify that the filter is reasonable
4114  */
4115 static int
4116 validate_filter(ns_ldap_cookie_t *cookie)
4117 {
4118 	char			*filter = cookie->filter;
4119 	int			rc;
4120 
4121 	/* Parse filter looking for illegal values */
4122 
4123 	rc = adj_filter(filter);
4124 	if (rc != 0) {
4125 		return (NS_LDAP_OP_FAILED);
4126 	}
4127 
4128 	/* end of filter checking */
4129 
4130 	return (NS_LDAP_SUCCESS);
4131 }
4132 
4133 /*
4134  * Set the account management request control that needs to be sent to server.
4135  * This control is required to get the account management information of
4136  * a user to do local account checking.
4137  */
4138 static int
4139 setup_acctmgmt_params(ns_ldap_cookie_t *cookie)
4140 {
4141 	LDAPControl	*req = NULL, **requestctrls;
4142 
4143 	req = (LDAPControl *)malloc(sizeof (LDAPControl));
4144 
4145 	if (req == NULL)
4146 		return (NS_LDAP_MEMORY);
4147 
4148 	/* fill in the fields of this new control */
4149 	req->ldctl_iscritical = 1;
4150 	req->ldctl_oid = strdup(NS_LDAP_ACCOUNT_USABLE_CONTROL);
4151 	if (req->ldctl_oid == NULL) {
4152 		free(req);
4153 		return (NS_LDAP_MEMORY);
4154 	}
4155 	req->ldctl_value.bv_len = 0;
4156 	req->ldctl_value.bv_val = NULL;
4157 
4158 	requestctrls = (LDAPControl **)calloc(2, sizeof (LDAPControl *));
4159 	if (requestctrls == NULL) {
4160 		ldap_control_free(req);
4161 		return (NS_LDAP_MEMORY);
4162 	}
4163 
4164 	requestctrls[0] = req;
4165 
4166 	cookie->p_serverctrls = requestctrls;
4167 
4168 	return (NS_LDAP_SUCCESS);
4169 }
4170 
4171 /*
4172  * **** This function needs to be moved to libldap library ****
4173  * parse_acct_cont_resp_msg() parses the message received by server according to
4174  * following format:
4175  * BER encoding:
4176  * * account is usable *ti*
4177  * 	+t: tag is 0
4178  * 	+i: contains the num of seconds before expiration. -1 means no expiry.
4179  * * account is not usable *t{bbbtiti}*
4180  *	+t: tag is 1
4181  *	+b: TRUE if inactive due to account inactivation
4182  * 	+b: TRUE if password has been reset
4183  * 	+b: TRUE if password is expired
4184  *	+t: tag is 2
4185  *	+i: contains num of remaining grace, 0 means no grace
4186  *	+t: tag is 3
4187  *	+i: contains num of seconds before auto-unlock. -1 means acct is locked
4188  *		forever (i.e. until reset)
4189  */
4190 static int
4191 parse_acct_cont_resp_msg(LDAPControl **ectrls, AcctUsableResponse_t *acctResp)
4192 {
4193 	BerElement	*ber;
4194 	int 		tag;
4195 	ber_len_t	len;
4196 	int		seconds_before_expiry, i;
4197 	int		inactive, reset, expired, rem_grace, sec_b4_unlock;
4198 
4199 	if (ectrls == NULL)
4200 		return (NS_LDAP_INVALID_PARAM);
4201 
4202 	for (i = 0; ectrls[i] != NULL; i++) {
4203 		if (strcmp(ectrls[i]->ldctl_oid, NS_LDAP_ACCOUNT_USABLE_CONTROL)
4204 			== 0)
4205 			goto found;
4206 		/* We have found some other control, ignore & continue */
4207 	}
4208 	/* Ldap control is not found */
4209 	return (NS_LDAP_NOTFOUND);
4210 
4211 found:
4212 	if ((ber = ber_init(&ectrls[i]->ldctl_value)) == NULL)
4213 		return (NS_LDAP_MEMORY);
4214 
4215 	if ((tag = ber_peek_tag(ber, &len)) == LBER_ERROR) {
4216 		/* Ldap decoding error */
4217 		ber_free(ber, 1);
4218 		return (NS_LDAP_INTERNAL);
4219 	}
4220 
4221 	switch (tag) {
4222 		case 0: acctResp->choice = 0;
4223 			if (ber_scanf(ber, "i", &seconds_before_expiry)
4224 				== LBER_ERROR) {
4225 				/* Ldap decoding error */
4226 				ber_free(ber, 1);
4227 				return (NS_LDAP_INTERNAL);
4228 			}
4229 			(acctResp->AcctUsableResp).seconds_before_expiry =
4230 				seconds_before_expiry;
4231 			ber_free(ber, 1);
4232 			return (NS_LDAP_SUCCESS);
4233 		case 1: acctResp->choice = 1;
4234 			if (ber_scanf(ber, "{bbb", &inactive, &reset, &expired)
4235 				== LBER_ERROR) {
4236 				/* Ldap decoding error */
4237 				ber_free(ber, 1);
4238 				return (NS_LDAP_INTERNAL);
4239 			}
4240 			(acctResp->AcctUsableResp).more_info.inactive =
4241 				inactive;
4242 			(acctResp->AcctUsableResp).more_info.reset =
4243 				reset;
4244 			(acctResp->AcctUsableResp).more_info.expired =
4245 				expired;
4246 			break;
4247 		default: /* Ldap decoding error */
4248 			ber_free(ber, 1);
4249 			return (NS_LDAP_INTERNAL);
4250 	}
4251 
4252 	if ((tag = ber_peek_tag(ber, &len)) == LBER_ERROR) {
4253 		ber_free(ber, 1);
4254 		return (NS_LDAP_SUCCESS);
4255 	}
4256 
4257 	switch (tag) {
4258 		case 2: if (ber_scanf(ber, "i", &rem_grace) == LBER_ERROR) {
4259 				ber_free(ber, 1);
4260 				return (NS_LDAP_INTERNAL);
4261 			}
4262 			(acctResp->AcctUsableResp).more_info.rem_grace =
4263 				rem_grace;
4264 			if ((tag = ber_peek_tag(ber, &len)) == LBER_ERROR) {
4265 				ber_free(ber, 1);
4266 				return (NS_LDAP_SUCCESS);
4267 			}
4268 			if (tag == 3)
4269 				goto timeb4unlock;
4270 			goto unknowntag;
4271 		case 3:
4272 timeb4unlock:
4273 			if (ber_scanf(ber, "i", &sec_b4_unlock) == LBER_ERROR) {
4274 				ber_free(ber, 1);
4275 				return (NS_LDAP_INTERNAL);
4276 			}
4277 			(acctResp->AcctUsableResp).more_info.sec_b4_unlock =
4278 				sec_b4_unlock;
4279 			break;
4280 		default:
4281 unknowntag:
4282 			ber_free(ber, 1);
4283 			return (NS_LDAP_INTERNAL);
4284 	}
4285 
4286 	ber_free(ber, 1);
4287 	return (NS_LDAP_SUCCESS);
4288 }
4289 
4290 /*
4291  * __ns_ldap_getAcctMgmt() is called from pam account management stack
4292  * for retrieving accounting information of users with no user password -
4293  * eg. rlogin, rsh, etc. This function uses the account management control
4294  * request to do a search on the server for the user in question. The
4295  * response control returned from the server is got from the cookie.
4296  * Input params: username of whose account mgmt information is to be got
4297  *		 pointer to hold the parsed account management information
4298  * Return values: NS_LDAP_SUCCESS on success or appropriate error
4299  *		code on failure
4300  */
4301 int
4302 __ns_ldap_getAcctMgmt(const char *user, AcctUsableResponse_t *acctResp)
4303 {
4304 	int		scope, rc;
4305 	char		ldapfilter[1024];
4306 	ns_ldap_cookie_t	*cookie;
4307 	ns_ldap_search_desc_t	**sdlist = NULL;
4308 	ns_ldap_search_desc_t	*dptr;
4309 	ns_ldap_error_t		*error = NULL;
4310 	char			**dns = NULL;
4311 	char		service[] = "shadow";
4312 
4313 	if (user == NULL || acctResp == NULL)
4314 		return (NS_LDAP_INVALID_PARAM);
4315 
4316 	/* Initialize State machine cookie */
4317 	cookie = init_search_state_machine();
4318 	if (cookie == NULL)
4319 		return (NS_LDAP_MEMORY);
4320 
4321 	/* see if need to follow referrals */
4322 	rc = __s_api_toFollowReferrals(0,
4323 		&cookie->followRef, &error);
4324 	if (rc != NS_LDAP_SUCCESS) {
4325 		(void) __ns_ldap_freeError(&error);
4326 		goto out;
4327 	}
4328 
4329 	/* get the service descriptor - or create a default one */
4330 	rc = __s_api_get_SSD_from_SSDtoUse_service(service,
4331 		&sdlist, &error);
4332 	if (rc != NS_LDAP_SUCCESS) {
4333 		(void) __ns_ldap_freeError(&error);
4334 		goto out;
4335 	}
4336 
4337 	if (sdlist == NULL) {
4338 		/* Create default service Desc */
4339 		sdlist = (ns_ldap_search_desc_t **)calloc(2,
4340 				sizeof (ns_ldap_search_desc_t *));
4341 		if (sdlist == NULL) {
4342 			rc = NS_LDAP_MEMORY;
4343 			goto out;
4344 		}
4345 		dptr = (ns_ldap_search_desc_t *)
4346 				calloc(1, sizeof (ns_ldap_search_desc_t));
4347 		if (dptr == NULL) {
4348 			free(sdlist);
4349 			rc = NS_LDAP_MEMORY;
4350 			goto out;
4351 		}
4352 		sdlist[0] = dptr;
4353 
4354 		/* default base */
4355 		rc = __s_api_getDNs(&dns, service, &cookie->errorp);
4356 		if (rc != NS_LDAP_SUCCESS) {
4357 			if (dns) {
4358 				__s_api_free2dArray(dns);
4359 				dns = NULL;
4360 			}
4361 			(void) __ns_ldap_freeError(&(cookie->errorp));
4362 			cookie->errorp = NULL;
4363 			goto out;
4364 		}
4365 		dptr->basedn = strdup(dns[0]);
4366 		if (dptr->basedn == NULL) {
4367 			free(sdlist);
4368 			free(dptr);
4369 			if (dns) {
4370 				__s_api_free2dArray(dns);
4371 				dns = NULL;
4372 			}
4373 			rc = NS_LDAP_MEMORY;
4374 			goto out;
4375 		}
4376 		__s_api_free2dArray(dns);
4377 		dns = NULL;
4378 
4379 		/* default scope */
4380 		scope = 0;
4381 		rc = __s_api_getSearchScope(&scope, &cookie->errorp);
4382 		dptr->scope = scope;
4383 	}
4384 
4385 	cookie->sdlist = sdlist;
4386 
4387 	cookie->service = strdup(service);
4388 	if (cookie->service == NULL) {
4389 		rc = NS_LDAP_MEMORY;
4390 		goto out;
4391 	}
4392 
4393 	/* search for entries for this particular uid */
4394 	(void) snprintf(ldapfilter, sizeof (ldapfilter), "(uid=%s)", user);
4395 	cookie->i_filter = strdup(ldapfilter);
4396 	if (cookie->i_filter == NULL) {
4397 		rc = NS_LDAP_MEMORY;
4398 		goto out;
4399 	}
4400 
4401 	/* create the control request */
4402 	if ((rc = setup_acctmgmt_params(cookie)) != NS_LDAP_SUCCESS)
4403 		goto out;
4404 
4405 	/* Process search */
4406 	rc = search_state_machine(cookie, GET_ACCT_MGMT_INFO, 0);
4407 
4408 	/* Copy results back to user */
4409 	rc = cookie->err_rc;
4410 	if (rc != NS_LDAP_SUCCESS)
4411 			(void) __ns_ldap_freeError(&(cookie->errorp));
4412 
4413 	if (cookie->result == NULL)
4414 			goto out;
4415 
4416 	if ((rc = parse_acct_cont_resp_msg(cookie->resultctrl, acctResp))
4417 		!= NS_LDAP_SUCCESS)
4418 		goto out;
4419 
4420 	rc = NS_LDAP_SUCCESS;
4421 
4422 out:
4423 	delete_search_cookie(cookie);
4424 
4425 	return (rc);
4426 }
4427