1 /* $Cambridge: exim/src/src/lookups/ldap.c,v 1.1 2004/10/07 13:10:01 ph10 Exp $ */
3 /*************************************************
4 * Exim - an Internet mail transport agent *
5 *************************************************/
7 /* Copyright (c) University of Cambridge 1995 - 2004 */
8 /* See the file NOTICE for conditions of use and distribution. */
10 /* Many thanks to Stuart Lynne for contributing the original code for this
11 driver. Further contibutions from Michael Haardt, Brian Candler, Barry
12 Pederson, Peter Savitch and Christian Kellner. Particular thanks to Brian for
13 researching how to handle the different kinds of error. */
17 #include "lf_functions.h"
21 /* We can't just compile this code and allow the library mechanism to omit the
22 functions if they are not wanted, because we need to have the LDAP headers
23 available for compiling. Therefore, compile these functions only if LOOKUP_LDAP
24 is defined. However, some compilers don't like compiling empty modules, so keep
25 them happy with a dummy when skipping the rest. Make it reference itself to
26 stop picky compilers complaining that it is unused, and put in a dummy argument
27 to stop even pickier compilers complaining about infinite loops. */
30 static void dummy(int x
) { dummy(x
-1); }
34 /* Include LDAP headers */
40 /* Annoyingly, the different LDAP libraries handle errors in different ways,
41 and some other things too. There doesn't seem to be an automatic way of
42 distinguishing between them. Local/Makefile should contain a setting of
43 LDAP_LIB_TYPE, which in turn causes appropriate macros to be defined for the
44 different kinds. Those that matter are:
47 LDAP_LIB_SOLARIS with synonym LDAP_LIB_SOLARIS7
50 These others may be defined, but are in fact the default, so are not tested:
56 #if defined(LDAP_LIB_SOLARIS7) && ! defined(LDAP_LIB_SOLARIS)
57 #define LDAP_LIB_SOLARIS
61 /* Just in case LDAP_NO_LIMIT is not defined by some of these libraries. */
64 #define LDAP_NO_LIMIT 0
68 /* Just in case LDAP_DEREF_NEVER is not defined */
70 #ifndef LDAP_DEREF_NEVER
71 #define LDAP_DEREF_NEVER 0
75 /* For libraries without TCP connect timeouts */
77 #ifndef LDAP_X_IO_TIMEOUT_NO_TIMEOUT
78 #define LDAP_X_IO_TIMEOUT_NO_TIMEOUT (-1)
82 /* Four types of LDAP search are implemented */
84 #define SEARCH_LDAP_MULTIPLE 0 /* Get attributes from multiple entries */
85 #define SEARCH_LDAP_SINGLE 1 /* Get attributes from one entry only */
86 #define SEARCH_LDAP_DN 2 /* Get just the DN from one entry */
87 #define SEARCH_LDAP_AUTH 3 /* Just checking for authentication */
89 /* In all 4 cases, the DN is left in $ldap_dn (which post-dates the
90 SEARCH_LDAP_DN lookup). */
93 /* Structure and anchor for caching connections. */
95 typedef struct ldap_connection
{
96 struct ldap_connection
*next
;
105 static LDAP_CONNECTION
*ldap_connections
= NULL
;
109 /*************************************************
110 * Internal search function *
111 *************************************************/
113 /* This is the function that actually does the work. It is called (indirectly
114 via control_ldap_search) from eldap_find(), eldapauth_find(), eldapdn_find(),
115 and eldapm_find(), with a difference in the "search_type" argument.
117 The case of eldapauth_find() is special in that all it does is do
118 authentication, returning OK or FAIL as appropriate. This isn't used as a
119 lookup. Instead, it is called from expand.c as an expansion condition test.
121 The DN from a successful lookup is placed in $ldap_dn. This feature postdates
122 the provision of the SEARCH_LDAP_DN facility for returning just the DN as the
126 ldap_url the URL to be looked up
127 server server host name, when URL contains none
128 s_port server port, used when URL contains no name
129 search_type SEARCH_LDAP_MULTIPLE allows values from multiple entries
130 SEARCH_LDAP_SINGLE allows values from one entry only
131 SEARCH_LDAP_DN gets the DN from one entry
132 res set to point at the result (not used for ldapauth)
133 errmsg set to point a message if result is not OK
134 defer_break set TRUE if no more servers to be tried after a DEFER
135 user user name for authentication, or NULL
136 password password for authentication, or NULL
137 sizelimit max number of entries returned, or 0 for no limit
138 timelimit max time to wait, or 0 for no limit
139 tcplimit max time to connect, or NULL for OS default
140 deference the dereference option, which is one of
141 LDAP_DEREF_{NEVER,SEARCHING,FINDING,ALWAYS}
143 Returns: OK or FAIL or DEFER
144 FAIL is given only if a lookup was performed successfully, but
149 perform_ldap_search(uschar
*ldap_url
, uschar
*server
, int s_port
, int search_type
,
150 uschar
**res
, uschar
**errmsg
, BOOL
*defer_break
, uschar
*user
, uschar
*password
,
151 int sizelimit
, int timelimit
, int tcplimit
, int dereference
)
153 LDAPURLDesc
*ludp
= NULL
;
154 LDAPMessage
*result
= NULL
;
156 LDAP_CONNECTION
*lcp
;
158 struct timeval timeout
;
159 struct timeval
*timeoutptr
= NULL
;
170 uschar
*error1
= NULL
; /* string representation of errcode (static) */
171 uschar
*error2
= NULL
; /* error message from the server */
172 uschar
*matched
= NULL
; /* partially matched DN */
175 int error_yield
= DEFER
;
182 BOOL attribute_found
= FALSE
;
186 debug_printf("perform_ldap_search: ldap%s URL = \"%s\" server=%s port=%d "
187 "sizelimit=%d timelimit=%d tcplimit=%d\n",
188 (search_type
== SEARCH_LDAP_MULTIPLE
)? "m" :
189 (search_type
== SEARCH_LDAP_DN
)? "dn" :
190 (search_type
== SEARCH_LDAP_AUTH
)? "auth" : "",
191 ldap_url
, server
, s_port
, sizelimit
, timelimit
, tcplimit
);
193 /* Check if LDAP thinks the URL is a valid LDAP URL. We assume that if the LDAP
194 library that is in use doesn't recognize, say, "ldapi", it will barf here. */
196 if (!ldap_is_ldap_url(CS ldap_url
))
198 *errmsg
= string_sprintf("ldap_is_ldap_url: not an LDAP url \"%s\"\n",
200 goto RETURN_ERROR_BREAK
;
205 if ((rc
= ldap_url_parse(CS ldap_url
, &ludp
)) != 0)
207 *errmsg
= string_sprintf("ldap_url_parse: (error %d) parsing \"%s\"\n", rc
,
209 goto RETURN_ERROR_BREAK
;
212 /* If the host name is empty, take it from the separate argument, if one is
213 given. OpenLDAP 2.0.6 sets an unset hostname to "" rather than empty, but
214 expects NULL later in ldap_init() to mean "default", annoyingly. In OpenLDAP
215 2.0.11 this has changed (it uses NULL). */
217 if ((ludp
->lud_host
== NULL
|| ludp
->lud_host
[0] == 0) && server
!= NULL
)
224 host
= US ludp
->lud_host
;
225 if (host
!= NULL
&& host
[0] == 0) host
= NULL
;
226 port
= ludp
->lud_port
;
229 DEBUG(D_lookup
) debug_printf("after ldap_url_parse: host=%s port=%d\n",
232 if (port
== 0) port
= LDAP_PORT
; /* Default if none given */
233 sprintf(CS porttext
, ":%d", port
); /* For messages */
235 /* If the "host name" is actually a path, we are going to connect using a Unix
236 socket, regardless of whether "ldapi" was actually specified or not. This means
237 that a Unix socket can be declared in eldap_default_servers, and "traditional"
238 LDAP queries using just "ldap" can be used ("ldaps" is similarly overridden).
239 The path may start with "/" or it may already be escaped as "%2F" if it was
240 actually declared that way in eldap_default_servers. (I did it that way the
241 first time.) If the host name is not a path, the use of "ldapi" causes an
242 error, except in the default case. (But lud_scheme doesn't seem to exist in
247 if ((host
[0] == '/' || Ustrncmp(host
, "%2F", 3) == 0))
250 porttext
[0] = 0; /* Remove port from messages */
253 #if defined LDAP_LIB_OPENLDAP2
254 else if (strncmp(ludp
->lud_scheme
, "ldapi", 5) == 0)
256 *errmsg
= string_sprintf("ldapi requires an absolute path (\"%s\" given)",
263 /* Count the attributes; we need this later to tell us how to format results */
265 for (attrp
= USS ludp
->lud_attrs
; attrp
!= NULL
&& *attrp
!= NULL
; attrp
++)
268 /* See if we can find a cached connection to this host. The port is not
269 relevant for ldapi. The host name pointer is set to NULL if no host was given
270 (implying the library default), rather than to the empty string. Note that in
271 this case, there is no difference between ldap and ldapi. */
273 for (lcp
= ldap_connections
; lcp
!= NULL
; lcp
= lcp
->next
)
275 if ((host
== NULL
) != (lcp
->host
== NULL
) ||
276 (host
!= NULL
&& strcmpic(lcp
->host
, host
) != 0))
278 if (ldapi
|| port
== lcp
->port
) break;
281 /* If no cached connection found, we must open a connection to the server. If
282 the server name is actually an absolute path, we set ldapi=TRUE above. This
283 requests connection via a Unix socket. However, as far as I know, only OpenLDAP
284 supports the use of sockets, and the use of ldap_initialize(). */
291 /* --------------------------- OpenLDAP ------------------------ */
293 /* There seems to be a preference under OpenLDAP for ldap_initialize()
294 instead of ldap_init(), though I have as yet been unable to find
295 documentation that says this. (OpenLDAP documentation is sparse to
296 non-existent). So we handle OpenLDAP differently here. Also, support for
297 ldapi seems to be OpenLDAP-only at present. */
299 #ifdef LDAP_LIB_OPENLDAP2
301 /* We now need an empty string for the default host. Get some store in which
302 to build a URL for ldap_initialize(). In the ldapi case, it can't be bigger
303 than (9 + 3*Ustrlen(shost)), whereas in the other cases it can't be bigger
304 than the host name + "ldaps:///" plus : and a port number, say 20 + the
305 length of the host name. What we get should accommodate both, easily. */
307 uschar
*shost
= (host
== NULL
)? US
"" : host
;
308 uschar
*init_url
= store_get(20 + 3 * Ustrlen(shost
));
311 /* Handle connection via Unix socket ("ldapi"). We build a basic LDAP URI to
312 contain the path name, with slashes escaped as %2F. */
317 init_ptr
= init_url
+ 8;
318 Ustrcpy(init_url
, "ldapi://");
319 while ((ch
= *shost
++) != 0)
323 Ustrncpy(init_ptr
, "%2F", 3);
326 else *init_ptr
++ = ch
;
331 /* This is not an ldapi call. Just build a URI with the protocol type, host
336 init_ptr
= Ustrchr(ldap_url
, '/');
337 Ustrncpy(init_url
, ldap_url
, init_ptr
- ldap_url
);
338 init_ptr
= init_url
+ (init_ptr
- ldap_url
);
339 sprintf(CS init_ptr
, "//%s:%d/", shost
, port
);
342 /* Call ldap_initialize() and check the result */
344 DEBUG(D_lookup
) debug_printf("ldap_initialize with URL %s\n", init_url
);
345 rc
= ldap_initialize(&ld
, CS init_url
);
346 if (rc
!= LDAP_SUCCESS
)
348 *errmsg
= string_sprintf("ldap_initialize: (error %d) URL \"%s\"\n",
352 store_reset(init_url
); /* Might as well save memory when we can */
355 /* ------------------------- Not OpenLDAP ---------------------- */
357 /* For libraries other than OpenLDAP, use ldap_init(). */
359 #else /* LDAP_LIB_OPENLDAP2 */
360 ld
= ldap_init(CS host
, port
);
361 #endif /* LDAP_LIB_OPENLDAP2 */
363 /* -------------------------------------------------------------- */
366 /* Handle failure to initialize */
370 *errmsg
= string_sprintf("failed to initialize for LDAP server %s%s - %s",
371 host
, porttext
, strerror(errno
));
375 /* Set the TCP connect time limit if available. This is something that is
376 in Netscape SDK v4.1; I don't know about other libraries. */
378 #ifdef LDAP_X_OPT_CONNECT_TIMEOUT
379 ldap_set_option(ld
, LDAP_X_OPT_CONNECT_TIMEOUT
, (void *)&tcplimit
);
382 /* I could not get TLS to work until I set the version to 3. That version
383 seems to be the default nowadays. The RFC is dated 1997, so I would hope
384 that all the LDAP libraries support it. Therefore, if eldap_version hasn't
385 been set, go for v3 if we can. */
387 if (eldap_version
< 0)
390 eldap_version
= LDAP_VERSION3
;
396 #ifdef LDAP_OPT_PROTOCOL_VERSION
397 ldap_set_option(ld
, LDAP_OPT_PROTOCOL_VERSION
, (void *)&eldap_version
);
400 DEBUG(D_lookup
) debug_printf("initialized for LDAP (v%d) server %s%s\n",
401 eldap_version
, host
, porttext
);
403 /* If not using ldapi and TLS is available, set appropriate TLS options: hard
404 for "ldaps" and soft otherwise. */
406 #ifdef LDAP_OPT_X_TLS
410 if (strncmp(ludp
->lud_scheme
, "ldaps", 5) == 0)
412 tls_option
= LDAP_OPT_X_TLS_HARD
;
413 DEBUG(D_lookup
) debug_printf("LDAP_OPT_X_TLS_HARD set\n");
417 tls_option
= LDAP_OPT_X_TLS_TRY
;
418 DEBUG(D_lookup
) debug_printf("LDAP_OPT_X_TLS_TRY set\n");
420 ldap_set_option(ld
, LDAP_OPT_X_TLS
, (void *)&tls_option
);
422 #endif /* LDAP_OPT_X_TLS */
424 /* Now add this connection to the chain of cached connections */
426 lcp
= store_get(sizeof(LDAP_CONNECTION
));
427 lcp
->host
= (host
== NULL
)? NULL
: string_copy(host
);
430 lcp
->password
= NULL
;
433 lcp
->next
= ldap_connections
;
434 ldap_connections
= lcp
;
437 /* Found cached connection */
442 debug_printf("re-using cached connection to LDAP server %s%s\n",
446 /* Bind with the user/password supplied, or an anonymous bind if these values
447 are NULL, unless a cached connection is already bound with the same values. */
450 (lcp
->user
== NULL
&& user
!= NULL
) ||
451 (lcp
->user
!= NULL
&& user
== NULL
) ||
452 (lcp
->user
!= NULL
&& user
!= NULL
&& Ustrcmp(lcp
->user
, user
) != 0) ||
453 (lcp
->password
== NULL
&& password
!= NULL
) ||
454 (lcp
->password
!= NULL
&& password
== NULL
) ||
455 (lcp
->password
!= NULL
&& password
!= NULL
&&
456 Ustrcmp(lcp
->password
, password
) != 0))
458 DEBUG(D_lookup
) debug_printf("%sbinding with user=%s password=%s\n",
459 (lcp
->bound
)? "re-" : "", user
, password
);
460 if ((rc
= ldap_bind_s(lcp
->ld
, CS user
, CS password
, LDAP_AUTH_SIMPLE
))
463 /* Invalid credentials when just checking credentials returns FAIL. This
464 stops any further servers being tried. */
466 if (search_type
== SEARCH_LDAP_AUTH
&& rc
== LDAP_INVALID_CREDENTIALS
)
469 debug_printf("Invalid credentials: ldapauth returns FAIL\n");
471 goto RETURN_ERROR_NOMSG
;
474 /* Otherwise we have a problem that doesn't stop further servers from being
477 *errmsg
= string_sprintf("failed to bind the LDAP connection to server "
478 "%s%s - LDAP error %d: %s", host
, porttext
, rc
, ldap_err2string(rc
));
482 /* Successful bind */
485 lcp
->user
= (user
== NULL
)? NULL
: string_copy(user
);
486 lcp
->password
= (password
== NULL
)? NULL
: string_copy(password
);
489 /* If we are just checking credentials, return OK. */
491 if (search_type
== SEARCH_LDAP_AUTH
)
493 DEBUG(D_lookup
) debug_printf("Bind succeeded: ldapauth returns OK\n");
497 /* Before doing the search, set the time and size limits (if given). Here again
498 the different implementations of LDAP have chosen to do things differently. */
500 #if defined(LDAP_OPT_SIZELIMIT)
501 ldap_set_option(lcp
->ld
, LDAP_OPT_SIZELIMIT
, (void *)&sizelimit
);
502 ldap_set_option(lcp
->ld
, LDAP_OPT_TIMELIMIT
, (void *)&timelimit
);
504 lcp
->ld
->ld_sizelimit
= sizelimit
;
505 lcp
->ld
->ld_timelimit
= timelimit
;
508 /* Similarly for dereferencing aliases. Don't know if this is possible on
509 an LDAP library without LDAP_OPT_DEREF. */
511 #if defined(LDAP_OPT_DEREF)
512 ldap_set_option(lcp
->ld
, LDAP_OPT_DEREF
, (void *)&dereference
);
515 /* Start the search on the server. */
517 DEBUG(D_lookup
) debug_printf("Start search\n");
519 msgid
= ldap_search(lcp
->ld
, ludp
->lud_dn
, ludp
->lud_scope
, ludp
->lud_filter
,
524 *errmsg
= string_sprintf("ldap search initiation failed");
528 /* Loop to pick up results as they come in, setting a timeout if one was
533 timeout
.tv_sec
= timelimit
;
535 timeoutptr
= &timeout
;
538 while ((rc
= ldap_result(lcp
->ld
, msgid
, 0, timeoutptr
, &result
)) ==
539 LDAP_RES_SEARCH_ENTRY
)
543 DEBUG(D_lookup
) debug_printf("ldap_result loop\n");
545 for(e
= ldap_first_entry(lcp
->ld
, result
);
547 e
= ldap_next_entry(lcp
->ld
, e
))
550 BOOL insert_space
= FALSE
;
552 DEBUG(D_lookup
) debug_printf("LDAP entry loop\n");
554 rescount
++; /* Count results */
556 /* Results for multiple entries values are separated by newlines. */
558 if (data
!= NULL
) data
= string_cat(data
, &size
, &ptr
, US
"\n", 1);
560 /* Get the DN from the last result. */
562 new_dn
= US
ldap_get_dn(lcp
->ld
, e
);
567 #if defined LDAP_LIB_NETSCAPE || defined LDAP_LIB_OPENLDAP2
569 #else /* OPENLDAP 1, UMich, Solaris */
577 /* If the data we want is actually the DN rather than any attribute values,
578 (an "ldapdn" search) add it to the data string. If there are multiple
579 entries, the DNs will be concatenated, but we test for this case below, as
580 for SEARCH_LDAP_SINGLE, and give an error. */
582 if (search_type
== SEARCH_LDAP_DN
) /* Do not amalgamate these into one */
583 { /* condition, because of the else */
584 if (new_dn
!= NULL
) /* below, that's for the first only */
586 data
= string_cat(data
, &size
, &ptr
, new_dn
, Ustrlen(new_dn
));
588 attribute_found
= TRUE
;
592 /* Otherwise, loop through the entry, grabbing attribute values. If there's
593 only one attribute being retrieved, no attribute name is given, and the
594 result is not quoted. Multiple values are separated by (comma, space).
595 If more than one attribute is being retrieved, the data is given as a
596 sequence of name=value pairs, with the value always in quotes. If there are
597 multiple values, they are given within the quotes, comma separated. */
599 else for (attr
= US
ldap_first_attribute(lcp
->ld
, e
, &ber
);
601 attr
= US
ldap_next_attribute(lcp
->ld
, e
, ber
))
605 /* Get array of values for this attribute. */
607 if ((firstval
= values
= USS
ldap_get_values(lcp
->ld
, e
, CS attr
))
613 data
= string_cat(data
, &size
, &ptr
, US
" ", 1);
616 data
= string_cat(data
, &size
, &ptr
, attr
, Ustrlen(attr
));
617 data
= string_cat(data
, &size
, &ptr
, US
"=\"", 2);
620 while (*values
!= NULL
)
622 uschar
*value
= *values
;
623 int len
= Ustrlen(value
);
625 DEBUG(D_lookup
) debug_printf("LDAP attr loop %s:%s\n", attr
, value
);
627 if (values
!= firstval
)
628 data
= string_cat(data
, &size
, &ptr
, US
", ", 2);
630 /* For multiple attributes, the data is in quotes. We must escape
631 internal quotes, backslashes, newlines. */
636 for (j
= 0; j
< len
; j
++)
638 if (value
[j
] == '\n')
639 data
= string_cat(data
, &size
, &ptr
, US
"\\n", 2);
642 if (value
[j
] == '\"' || value
[j
] == '\\')
643 data
= string_cat(data
, &size
, &ptr
, US
"\\", 1);
644 data
= string_cat(data
, &size
, &ptr
, value
+j
, 1);
649 /* For single attributes, copy the value verbatim */
651 else data
= string_cat(data
, &size
, &ptr
, value
, len
);
653 /* Move on to the next value */
656 attribute_found
= TRUE
;
659 /* Closing quote at the end of the data for a named attribute. */
662 data
= string_cat(data
, &size
, &ptr
, US
"\"", 1);
664 /* Free the values */
666 ldap_value_free(CSS firstval
);
670 #if defined LDAP_LIB_NETSCAPE || defined LDAP_LIB_OPENLDAP2
672 /* Netscape and OpenLDAP2 LDAP's attrs are dynamically allocated and need
673 to be freed. UMich LDAP stores them in static storage and does not require
678 } /* End "for" loop for extracting attributes from an entry */
679 } /* End "for" loop for extracting entries from a result */
681 /* Free the result */
683 ldap_msgfree(result
);
685 } /* End "while" loop for multiple results */
687 /* Terminate the dynamic string that we have built and reclaim unused store */
692 store_reset(data
+ ptr
+ 1);
695 /* Copy the last dn into eldap_dn */
699 eldap_dn
= string_copy(dn
);
700 #if defined LDAP_LIB_NETSCAPE || defined LDAP_LIB_OPENLDAP2
702 #else /* OPENLDAP 1, UMich, Solaris */
707 DEBUG(D_lookup
) debug_printf("search ended by ldap_result yielding %d\n",rc
);
711 *errmsg
= US
"ldap_result timed out";
715 /* A return code of -1 seems to mean "ldap_result failed internally or couldn't
716 provide you with a message". Other error states seem to exist where
717 ldap_result() didn't give us any message from the server at all, leaving result
718 set to NULL. Apparently, "the error parameters of the LDAP session handle will
719 be set accordingly". That's the best we can do to retrieve an error status; we
720 can't use functions like ldap_result2error because they parse a message from
721 the server, which we didn't get.
723 Annoyingly, the different implementations of LDAP have gone for different
724 methods of handling error codes and generating error messages. */
726 if (rc
== -1 || result
== NULL
)
729 DEBUG(D_lookup
) debug_printf("ldap_result failed\n");
731 #if defined LDAP_LIB_SOLARIS || defined LDAP_LIB_OPENLDAP2
732 ldap_get_option(lcp
->ld
, LDAP_OPT_ERROR_NUMBER
, &err
);
733 *errmsg
= string_sprintf("ldap_result failed: %d, %s",
734 err
, ldap_err2string(err
));
736 #elif defined LDAP_LIB_NETSCAPE
737 /* Dubious (surely 'matched' is spurious here?) */
738 (void)ldap_get_lderrno(lcp
->ld
, &matched
, &error1
);
739 *errmsg
= string_sprintf("ldap_result failed: %s (%s)", error1
, matched
);
741 #else /* UMich LDAP aka OpenLDAP 1.x */
742 *errmsg
= string_sprintf("ldap_result failed: %d, %s",
743 lcp
->ld
->ld_errno
, ldap_err2string(lcp
->ld
->ld_errno
));
749 /* A return code that isn't -1 doesn't necessarily mean there were no problems
750 with the search. The message must be an LDAP_RES_SEARCH_RESULT or else it's
751 something we can't handle. */
753 if (rc
!= LDAP_RES_SEARCH_RESULT
)
755 *errmsg
= string_sprintf("ldap_result returned unexpected code %d", rc
);
759 /* We have a result message from the server. This doesn't yet mean all is well.
760 We need to parse the message to find out exactly what's happened. */
762 #if defined LDAP_LIB_SOLARIS || defined LDAP_LIB_OPENLDAP2
763 if (ldap_parse_result(lcp
->ld
, result
, &rc
, CSS
&matched
, CSS
&error2
, NULL
,
766 *errmsg
= US
"ldap_parse_result failed";
769 error1
= US
ldap_err2string(rc
);
771 #elif defined LDAP_LIB_NETSCAPE
772 /* Dubious (it doesn't reference 'result' at all!) */
773 rc
= ldap_get_lderrno(lcp
->ld
, &matched
, &error1
);
775 #else /* UMich LDAP aka OpenLDAP 1.x */
776 rc
= ldap_result2error(lcp
->ld
, result
, 0);
777 error1
= ldap_err2string(rc
);
778 error2
= lcp
->ld
->ld_error
;
779 matched
= lcp
->ld
->ld_matched
;
782 /* Process the status as follows:
784 (1) If we get LDAP_SIZELIMIT_EXCEEDED, just carry on, to return the
785 truncated result list.
787 (2) The range of errors defined by LDAP_NAME_ERROR generally mean "that
788 object does not, or cannot, exist in the database". For those cases we
791 (3) All other non-successes here are treated as some kind of problem with
792 the lookup, so return DEFER (which is the default in error_yield).
795 DEBUG(D_lookup
) debug_printf("ldap_parse_result yielded %d: %s\n",
796 rc
, ldap_err2string(rc
));
798 if (rc
!= LDAP_SUCCESS
&& rc
!= LDAP_SIZELIMIT_EXCEEDED
)
800 *errmsg
= string_sprintf("LDAP search failed - error %d: %s%s%s%s%s",
802 (error1
!= NULL
)? error1
: US
"",
803 (error2
!= NULL
&& error2
[0] != 0)? US
"/" : US
"",
804 (error2
!= NULL
)? error2
: US
"",
805 (matched
!= NULL
&& matched
[0] != 0)? US
"/" : US
"",
806 (matched
!= NULL
)? matched
: US
"");
808 #if defined LDAP_NAME_ERROR
809 if (LDAP_NAME_ERROR(rc
))
810 #elif defined NAME_ERROR /* OPENLDAP1 calls it this */
813 if (rc
== LDAP_NO_SUCH_OBJECT
)
817 DEBUG(D_lookup
) debug_printf("lookup failure forced\n");
823 /* The search succeeded. Check if we have too many results */
825 if (search_type
!= SEARCH_LDAP_MULTIPLE
&& rescount
> 1)
827 *errmsg
= string_sprintf("LDAP search: more than one entry (%d) was returned "
828 "(filter not specific enough?)", rescount
);
829 goto RETURN_ERROR_BREAK
;
832 /* Check if we have too few (zero) entries */
836 *errmsg
= string_sprintf("LDAP search: no results");
838 goto RETURN_ERROR_BREAK
;
841 /* If an entry was found, but it had no attributes, we behave as if no entries
842 were found, that is, the lookup failed. */
844 if (!attribute_found
)
846 *errmsg
= US
"LDAP search: found no attributes";
851 /* Otherwise, it's all worked */
853 DEBUG(D_lookup
) debug_printf("LDAP search: returning: %s\n", data
);
857 if (result
!= NULL
) ldap_msgfree(result
);
858 ldap_free_urldesc(ludp
);
867 DEBUG(D_lookup
) debug_printf("%s\n", *errmsg
);
870 if (result
!= NULL
) ldap_msgfree(result
);
871 if (ludp
!= NULL
) ldap_free_urldesc(ludp
);
873 #if defined LDAP_LIB_OPENLDAP2
874 if (error2
!= NULL
) ldap_memfree(error2
);
875 if (matched
!= NULL
) ldap_memfree(matched
);
883 /*************************************************
884 * Internal search control function *
885 *************************************************/
887 /* This function is called from eldap_find(), eldapauth_find(), eldapdn_find(),
888 and eldapm_find() with a difference in the "search_type" argument. It controls
889 calls to perform_ldap_search() which actually does the work. We call that
890 repeatedly for certain types of defer in the case when the URL contains no host
891 name and eldap_default_servers is set to a list of servers to try. This gives
892 more control than just passing over a list of hosts to ldap_open() because it
893 handles other kinds of defer as well as just a failure to open. Note that the
894 URL is defined to contain either zero or one "hostport" only.
896 Parameter data in addition to the URL can be passed as preceding text in the
897 string, as items of the form XXX=yyy. The URL itself can be detected because it
898 must begin "ldapx://", where x is empty, s, or i.
901 ldap_url the URL to be looked up, optionally preceded by other parameter
903 search_type SEARCH_LDAP_MULTIPLE allows values from multiple entries
904 SEARCH_LDAP_SINGLE allows values from one entry only
905 SEARCH_LDAP_DN gets the DN from one entry
906 res set to point at the result
907 errmsg set to point a message if result is not OK
909 Returns: OK or FAIL or DEFER
913 control_ldap_search(uschar
*ldap_url
, int search_type
, uschar
**res
,
916 BOOL defer_break
= FALSE
;
917 int timelimit
= LDAP_NO_LIMIT
;
918 int sizelimit
= LDAP_NO_LIMIT
;
919 int tcplimit
= LDAP_X_IO_TIMEOUT_NO_TIMEOUT
;
920 int dereference
= LDAP_DEREF_NEVER
;
922 uschar
*url
= ldap_url
;
925 uschar
*password
= NULL
;
926 uschar
*server
, *list
;
929 while (isspace(*url
)) url
++;
931 /* Until the string begins "ldap", search for the other parameter settings that
932 are recognized. They are of the form NAME=VALUE, with the value being
933 optionally double-quoted. There must still be a space after it, however. No
934 NAME has the value "ldap". */
936 while (strncmpic(url
, US
"ldap", 4) != 0)
939 while (*url
!= 0 && *url
!= '=') url
++;
944 namelen
= ++url
- name
;
945 value
= string_dequote(&url
);
948 if (strncmpic(name
, US
"USER=", namelen
) == 0) user
= value
;
949 else if (strncmpic(name
, US
"PASS=", namelen
) == 0) password
= value
;
950 else if (strncmpic(name
, US
"SIZE=", namelen
) == 0) sizelimit
= Uatoi(value
);
951 else if (strncmpic(name
, US
"TIME=", namelen
) == 0) timelimit
= Uatoi(value
);
952 else if (strncmpic(name
, US
"CONNECT=", namelen
) == 0) tcplimit
= Uatoi(value
) * 1000;
954 /* Don't know if all LDAP libraries have LDAP_OPT_DEREF */
956 #ifdef LDAP_OPT_DEREF
957 else if (strncmpic(name
, US
"DEREFERENCE=", namelen
) == 0)
959 if (strcmpic(value
, US
"never") == 0) dereference
= LDAP_DEREF_NEVER
;
960 else if (strcmpic(value
, US
"searching") == 0)
961 dereference
= LDAP_DEREF_SEARCHING
;
962 else if (strcmpic(value
, US
"finding") == 0)
963 dereference
= LDAP_DEREF_FINDING
;
964 if (strcmpic(value
, US
"always") == 0) dereference
= LDAP_DEREF_ALWAYS
;
967 else if (strncmpic(name
, US
"DEREFERENCE=", namelen
) == 0)
969 *errmsg
= string_sprintf("LDAP_OP_DEREF not defined in this LDAP "
970 "library - cannot use \"dereference\"");
971 DEBUG(D_lookup
) debug_printf("%s\n", *errmsg
);
980 string_sprintf("unknown parameter \"%.*s\" precedes LDAP URL",
982 DEBUG(D_lookup
) debug_printf("LDAP query error: %s\n", *errmsg
);
985 while (isspace(*url
)) url
++;
989 *errmsg
= US
"malformed parameter setting precedes LDAP URL";
990 DEBUG(D_lookup
) debug_printf("LDAP query error: %s\n", *errmsg
);
994 /* If user is set, de-URL-quote it. Some LDAP libraries do this for themselves,
995 but it seems that not all behave like this. The DN for the user is often the
996 result of ${quote_ldap_dn:...} quoting, which does apply URL quoting, because
997 that is needed when the DN is used as a base DN in a query. Sigh. This is all
998 far too complicated. */
1004 for (s
= user
; *s
!= 0; s
++)
1007 if (*s
== '%' && isxdigit(c
=s
[1]) && isxdigit(d
=s
[2]))
1012 (((c
>= 'a')? (10 + c
- 'a') : c
- '0') << 4) |
1013 ((d
>= 'a')? (10 + d
- 'a') : d
- '0');
1022 debug_printf("LDAP parameters: user=%s pass=%s size=%d time=%d connect=%d "
1023 "dereference=%d\n", user
, password
, sizelimit
, timelimit
, tcplimit
,
1026 /* If the request is just to check authentication, some credentials must
1027 be given. The password must not be empty because LDAP binds with an empty
1028 password are considered anonymous, and will succeed on most installations. */
1030 if (search_type
== SEARCH_LDAP_AUTH
)
1032 if (user
== NULL
|| password
== NULL
)
1034 *errmsg
= US
"ldapauth lookups must specify the username and password";
1037 if (password
[0] == 0)
1039 DEBUG(D_lookup
) debug_printf("Empty password: ldapauth returns FAIL\n");
1044 /* Check for valid ldap url starters */
1047 if (tolower(*p
) == 's' || tolower(*p
) == 'i') p
++;
1048 if (Ustrncmp(p
, "://", 3) != 0)
1050 *errmsg
= string_sprintf("LDAP URL does not start with \"ldap://\", "
1051 "\"ldaps://\", or \"ldapi://\" (it starts with \"%.16s...\")", url
);
1052 DEBUG(D_lookup
) debug_printf("LDAP query error: %s\n", *errmsg
);
1056 /* No default servers, or URL contains a server name: just one attempt */
1058 if (eldap_default_servers
== NULL
|| p
[3] != '/')
1060 return perform_ldap_search(url
, NULL
, 0, search_type
, res
, errmsg
,
1061 &defer_break
, user
, password
, sizelimit
, timelimit
, tcplimit
, dereference
);
1064 /* Loop through the default servers until OK or FAIL */
1066 list
= eldap_default_servers
;
1067 while ((server
= string_nextinlist(&list
, &sep
, buffer
, sizeof(buffer
))) != NULL
)
1071 uschar
*colon
= Ustrchr(server
, ':');
1075 port
= Uatoi(colon
+1);
1077 rc
= perform_ldap_search(url
, server
, port
, search_type
, res
, errmsg
,
1078 &defer_break
, user
, password
, sizelimit
, timelimit
, tcplimit
, dereference
);
1079 if (rc
!= DEFER
|| defer_break
) return rc
;
1087 /*************************************************
1088 * Find entry point *
1089 *************************************************/
1091 /* See local README for interface description. The different kinds of search
1092 are handled by a common function, with a flag to differentiate between them.
1093 The handle and filename arguments are not used. */
1096 eldap_find(void *handle
, uschar
*filename
, uschar
*ldap_url
, int length
,
1097 uschar
**result
, uschar
**errmsg
, BOOL
*do_cache
)
1099 /* Keep picky compilers happy */
1100 do_cache
= do_cache
;
1101 return(control_ldap_search(ldap_url
, SEARCH_LDAP_SINGLE
, result
, errmsg
));
1105 eldapm_find(void *handle
, uschar
*filename
, uschar
*ldap_url
, int length
,
1106 uschar
**result
, uschar
**errmsg
, BOOL
*do_cache
)
1108 /* Keep picky compilers happy */
1109 do_cache
= do_cache
;
1110 return(control_ldap_search(ldap_url
, SEARCH_LDAP_MULTIPLE
, result
, errmsg
));
1114 eldapdn_find(void *handle
, uschar
*filename
, uschar
*ldap_url
, int length
,
1115 uschar
**result
, uschar
**errmsg
, BOOL
*do_cache
)
1117 /* Keep picky compilers happy */
1118 do_cache
= do_cache
;
1119 return(control_ldap_search(ldap_url
, SEARCH_LDAP_DN
, result
, errmsg
));
1123 eldapauth_find(void *handle
, uschar
*filename
, uschar
*ldap_url
, int length
,
1124 uschar
**result
, uschar
**errmsg
, BOOL
*do_cache
)
1126 /* Keep picky compilers happy */
1127 do_cache
= do_cache
;
1128 return(control_ldap_search(ldap_url
, SEARCH_LDAP_AUTH
, result
, errmsg
));
1133 /*************************************************
1134 * Open entry point *
1135 *************************************************/
1137 /* See local README for interface description. */
1140 eldap_open(uschar
*filename
, uschar
**errmsg
)
1142 return (void *)(1); /* Just return something non-null */
1147 /*************************************************
1148 * Tidy entry point *
1149 *************************************************/
1151 /* See local README for interface description.
1152 Make sure that eldap_dn does not refer to reclaimed or worse, freed store */
1157 LDAP_CONNECTION
*lcp
= NULL
;
1160 while ((lcp
= ldap_connections
) != NULL
)
1162 DEBUG(D_lookup
) debug_printf("unbind LDAP connection to %s:%d\n", lcp
->host
,
1164 ldap_unbind(lcp
->ld
);
1165 ldap_connections
= lcp
->next
;
1171 /*************************************************
1172 * Quote entry point *
1173 *************************************************/
1175 /* LDAP quoting is unbelievably messy. For a start, two different levels of
1176 quoting have to be done: LDAP quoting, and URL quoting. The current
1177 specification is the result of a suggestion by Brian Candler. It recognizes
1180 (1) For text that appears in a search filter, the following escapes are
1181 required (see RFC 2254):
1189 Then the entire filter text must be URL-escaped. This kind of quoting is
1190 implemented by ${quote_ldap:....}. Note that we can never have a NULL
1191 in the input string, because that's a terminator.
1193 (2) For a DN that is part of a URL (i.e. the base DN), the characters
1197 must be quoted by backslashing. See RFC 2253. Leading and trailing spaces
1198 must be escaped, as must a leading #. Then the string must be URL-quoted.
1199 This type of quoting is implemented by ${quote_ldap_dn:....}.
1201 For URL quoting, the only characters that need not be quoted are the
1206 All the others must be hexified and preceded by %. This includes the
1207 backslashes used for LDAP quoting.
1209 For a DN that is given in the USER parameter for authentication, we need the
1210 same initial quoting as (2) but in this case, the result must NOT be
1211 URL-escaped, because it isn't a URL. The way this is handled is by
1212 de-URL-quoting the text when processing the USER parameter in
1213 control_ldap_search() above. That means that the same quote operator can be
1214 used. This has the additional advantage that spaces in the DN won't cause
1215 parsing problems. For example:
1217 USER=cn=${quote_ldap_dn:$1},%20dc=example,%20dc=com
1219 should be safe if there are spaces in $1.
1223 s the string to be quoted
1224 opt additional option text or NULL if none
1225 only "dn" is recognized
1227 Returns: the processed string or NULL for a bad option
1232 /* The characters in this string, together with alphanumerics, never need
1233 quoting in any way. */
1235 #define ALWAYS_LITERAL "!$'-._"
1237 /* The special characters in this string do not need to be URL-quoted. The set
1238 is a bit larger than the general literals. */
1240 #define URL_NONQUOTE ALWAYS_LITERAL "()*+"
1242 /* The following macros define the characters that are quoted by quote_ldap and
1243 quote_ldap_dn, respectively. */
1245 #define LDAP_QUOTE "*()\\"
1246 #define LDAP_DN_QUOTE ",+\"\\<>;"
1251 eldap_quote(uschar
*s
, uschar
*opt
)
1260 /* Test for a DN quotation. */
1264 if (Ustrcmp(opt
, "dn") != 0) return NULL
; /* No others recognized */
1268 /* Compute how much extra store we need for the string. This doesn't have to be
1269 exact as long as it isn't an underestimate. The worst case is the addition of 5
1270 extra bytes for a single character. This occurs for certain characters in DNs,
1271 where, for example, < turns into %5C%3C. For simplicity, we just add 5 for each
1272 possibly escaped character. The really fast way would be just to test for
1273 non-alphanumerics, but it is probably better to spot a few others that are
1274 never escaped, because if there are no specials at all, we can avoid copying
1277 while ((c
= *t
++) != 0)
1280 if (!isalnum(c
) && Ustrchr(ALWAYS_LITERAL
, c
) == NULL
) count
+= 5;
1282 if (count
== 0) return s
;
1284 /* Get sufficient store to hold the quoted string */
1286 t
= quoted
= store_get(len
+ count
+ 1);
1288 /* Handle plain quote_ldap */
1292 while ((c
= *s
++) != 0)
1296 if (Ustrchr(LDAP_QUOTE
, c
) != NULL
)
1298 sprintf(CS t
, "%%5C%02X", c
); /* e.g. * => %5C2A */
1302 if (Ustrchr(URL_NONQUOTE
, c
) == NULL
) /* e.g. ] => %5D */
1304 sprintf(CS t
, "%%%02X", c
);
1309 *t
++ = c
; /* unquoted character */
1313 /* Handle quote_ldap_dn */
1317 uschar
*ss
= s
+ len
;
1319 /* Find the last char before any trailing spaces */
1321 while (ss
> s
&& ss
[-1] == ' ') ss
--;
1323 /* Quote leading spaces and sharps */
1327 if (*s
!= ' ' && *s
!= '#') break;
1328 sprintf(CS t
, "%%5C%%%02X", *s
);
1332 /* Handle the rest of the string, up to the trailing spaces */
1339 if (Ustrchr(LDAP_DN_QUOTE
, c
) != NULL
)
1341 Ustrncpy(t
, "%5C", 3); /* insert \ where needed */
1342 t
+= 3; /* fall through to check URL */
1344 if (Ustrchr(URL_NONQUOTE
, c
) == NULL
) /* e.g. ] => %5D */
1346 sprintf(CS t
, "%%%02X", c
);
1351 *t
++ = c
; /* unquoted character, or non-URL quoted after %5C */
1354 /* Handle the trailing spaces */
1358 Ustrncpy(t
, "%5C%20", 6);
1363 /* Terminate the new string and return */
1369 #endif /* LOOKUP_LDAP */
1371 /* End of lookups/ldap.c */