Improve error message when ldap_search fails in OpenLDAP or Solaris
[exim.git] / src / src / lookups / ldap.c
1 /* $Cambridge: exim/src/src/lookups/ldap.c,v 1.6 2004/12/21 13:59:15 ph10 Exp $ */
2
3 /*************************************************
4 *     Exim - an Internet mail transport agent    *
5 *************************************************/
6
7 /* Copyright (c) University of Cambridge 1995 - 2004 */
8 /* See the file NOTICE for conditions of use and distribution. */
9
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. */
14
15
16 #include "../exim.h"
17 #include "lf_functions.h"
18 #include "ldap.h"
19
20
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. */
28
29 #ifndef LOOKUP_LDAP
30 static void dummy(int x) { dummy(x-1); }
31 #else
32
33
34 /* Include LDAP headers */
35
36 #include <lber.h>
37 #include <ldap.h>
38
39
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:
45
46 LDAP_LIB_NETSCAPE
47 LDAP_LIB_SOLARIS   with synonym LDAP_LIB_SOLARIS7
48 LDAP_LIB_OPENLDAP2
49
50 These others may be defined, but are in fact the default, so are not tested:
51
52 LDAP_LIB_UMICHIGAN
53 LDAP_LIB_OPENLDAP1
54 */
55
56 #if defined(LDAP_LIB_SOLARIS7) && ! defined(LDAP_LIB_SOLARIS)
57 #define LDAP_LIB_SOLARIS
58 #endif
59
60
61 /* Just in case LDAP_NO_LIMIT is not defined by some of these libraries. */
62
63 #ifndef LDAP_NO_LIMIT
64 #define LDAP_NO_LIMIT 0
65 #endif
66
67
68 /* Just in case LDAP_DEREF_NEVER is not defined */
69
70 #ifndef LDAP_DEREF_NEVER
71 #define LDAP_DEREF_NEVER 0
72 #endif
73
74
75 /* Four types of LDAP search are implemented */
76
77 #define SEARCH_LDAP_MULTIPLE 0       /* Get attributes from multiple entries */
78 #define SEARCH_LDAP_SINGLE 1         /* Get attributes from one entry only */
79 #define SEARCH_LDAP_DN 2             /* Get just the DN from one entry */
80 #define SEARCH_LDAP_AUTH 3           /* Just checking for authentication */
81
82 /* In all 4 cases, the DN is left in $ldap_dn (which post-dates the
83 SEARCH_LDAP_DN lookup). */
84
85
86 /* Structure and anchor for caching connections. */
87
88 typedef struct ldap_connection {
89   struct ldap_connection *next;
90   uschar *host;
91   uschar *user;
92   uschar *password;
93   BOOL  bound;
94   int   port;
95   LDAP *ld;
96 } LDAP_CONNECTION;
97
98 static LDAP_CONNECTION *ldap_connections = NULL;
99
100
101
102 /*************************************************
103 *         Internal search function               *
104 *************************************************/
105
106 /* This is the function that actually does the work. It is called (indirectly
107 via control_ldap_search) from eldap_find(), eldapauth_find(), eldapdn_find(),
108 and eldapm_find(), with a difference in the "search_type" argument.
109
110 The case of eldapauth_find() is special in that all it does is do
111 authentication, returning OK or FAIL as appropriate. This isn't used as a
112 lookup. Instead, it is called from expand.c as an expansion condition test.
113
114 The DN from a successful lookup is placed in $ldap_dn. This feature postdates
115 the provision of the SEARCH_LDAP_DN facility for returning just the DN as the
116 data.
117
118 Arguments:
119   ldap_url      the URL to be looked up
120   server        server host name, when URL contains none
121   s_port        server port, used when URL contains no name
122   search_type   SEARCH_LDAP_MULTIPLE allows values from multiple entries
123                 SEARCH_LDAP_SINGLE allows values from one entry only
124                 SEARCH_LDAP_DN gets the DN from one entry
125   res           set to point at the result (not used for ldapauth)
126   errmsg        set to point a message if result is not OK
127   defer_break   set TRUE if no more servers to be tried after a DEFER
128   user          user name for authentication, or NULL
129   password      password for authentication, or NULL
130   sizelimit     max number of entries returned, or 0 for no limit
131   timelimit     max time to wait, or 0 for no limit
132   tcplimit      max time for network activity, e.g. connect, or 0 for OS default
133   deference     the dereference option, which is one of
134                   LDAP_DEREF_{NEVER,SEARCHING,FINDING,ALWAYS}
135
136 Returns:        OK or FAIL or DEFER
137                 FAIL is given only if a lookup was performed successfully, but
138                 returned no data.
139 */
140
141 static int
142 perform_ldap_search(uschar *ldap_url, uschar *server, int s_port, int search_type,
143   uschar **res, uschar **errmsg, BOOL *defer_break, uschar *user, uschar *password,
144   int sizelimit, int timelimit, int tcplimit, int dereference)
145 {
146 LDAPURLDesc     *ludp = NULL;
147 LDAPMessage     *result = NULL;
148 BerElement      *ber;
149 LDAP_CONNECTION *lcp;
150
151 struct timeval timeout;
152 struct timeval *timeoutptr = NULL;
153
154 uschar *attr;
155 uschar **attrp;
156 uschar *data = NULL;
157 uschar *dn = NULL;
158 uschar *host;
159 uschar **values;
160 uschar **firstval;
161 uschar porttext[16];
162
163 uschar *error1 = NULL;   /* string representation of errcode (static) */
164 uschar *error2 = NULL;   /* error message from the server */
165 uschar *matched = NULL;  /* partially matched DN */
166
167 int    attr_count = 0;
168 int    error_yield = DEFER;
169 int    msgid;
170 int    rc, ldap_rc, ldap_parse_rc;
171 int    port;
172 int    ptr = 0;
173 int    rescount = 0;
174 int    size = 0;
175 BOOL   attribute_found = FALSE;
176 BOOL   ldapi = FALSE;
177
178 DEBUG(D_lookup)
179   debug_printf("perform_ldap_search: ldap%s URL = \"%s\" server=%s port=%d "
180     "sizelimit=%d timelimit=%d tcplimit=%d\n",
181     (search_type == SEARCH_LDAP_MULTIPLE)? "m" :
182     (search_type == SEARCH_LDAP_DN)? "dn" :
183     (search_type == SEARCH_LDAP_AUTH)? "auth" : "",
184     ldap_url, server, s_port, sizelimit, timelimit, tcplimit);
185
186 /* Check if LDAP thinks the URL is a valid LDAP URL. We assume that if the LDAP
187 library that is in use doesn't recognize, say, "ldapi", it will barf here. */
188
189 if (!ldap_is_ldap_url(CS ldap_url))
190   {
191   *errmsg = string_sprintf("ldap_is_ldap_url: not an LDAP url \"%s\"\n",
192     ldap_url);
193   goto RETURN_ERROR_BREAK;
194   }
195
196 /* Parse the URL */
197
198 if ((rc = ldap_url_parse(CS ldap_url, &ludp)) != 0)
199   {
200   *errmsg = string_sprintf("ldap_url_parse: (error %d) parsing \"%s\"\n", rc,
201     ldap_url);
202   goto RETURN_ERROR_BREAK;
203   }
204
205 /* If the host name is empty, take it from the separate argument, if one is
206 given. OpenLDAP 2.0.6 sets an unset hostname to "" rather than empty, but
207 expects NULL later in ldap_init() to mean "default", annoyingly. In OpenLDAP
208 2.0.11 this has changed (it uses NULL). */
209
210 if ((ludp->lud_host == NULL || ludp->lud_host[0] == 0) && server != NULL)
211   {
212   host = server;
213   port = s_port;
214   }
215 else
216   {
217   host = US ludp->lud_host;
218   if (host != NULL && host[0] == 0) host = NULL;
219   port = ludp->lud_port;
220   }
221
222 DEBUG(D_lookup) debug_printf("after ldap_url_parse: host=%s port=%d\n",
223   host, port);
224
225 if (port == 0) port = LDAP_PORT;      /* Default if none given */
226 sprintf(CS porttext, ":%d", port);    /* For messages */
227
228 /* If the "host name" is actually a path, we are going to connect using a Unix
229 socket, regardless of whether "ldapi" was actually specified or not. This means
230 that a Unix socket can be declared in eldap_default_servers, and "traditional"
231 LDAP queries using just "ldap" can be used ("ldaps" is similarly overridden).
232 The path may start with "/" or it may already be escaped as "%2F" if it was
233 actually declared that way in eldap_default_servers. (I did it that way the
234 first time.) If the host name is not a path, the use of "ldapi" causes an
235 error, except in the default case. (But lud_scheme doesn't seem to exist in
236 older libraries.) */
237
238 if (host != NULL)
239   {
240   if ((host[0] == '/' || Ustrncmp(host, "%2F", 3) == 0))
241     {
242     ldapi = TRUE;
243     porttext[0] = 0;    /* Remove port from messages */
244     }
245
246   #if defined LDAP_LIB_OPENLDAP2
247   else if (strncmp(ludp->lud_scheme, "ldapi", 5) == 0)
248     {
249     *errmsg = string_sprintf("ldapi requires an absolute path (\"%s\" given)",
250       host);
251     goto RETURN_ERROR;
252     }
253   #endif
254   }
255
256 /* Count the attributes; we need this later to tell us how to format results */
257
258 for (attrp = USS ludp->lud_attrs; attrp != NULL && *attrp != NULL; attrp++)
259   attr_count++;
260
261 /* See if we can find a cached connection to this host. The port is not
262 relevant for ldapi. The host name pointer is set to NULL if no host was given
263 (implying the library default), rather than to the empty string. Note that in
264 this case, there is no difference between ldap and ldapi. */
265
266 for (lcp = ldap_connections; lcp != NULL; lcp = lcp->next)
267   {
268   if ((host == NULL) != (lcp->host == NULL) ||
269       (host != NULL && strcmpic(lcp->host, host) != 0))
270     continue;
271   if (ldapi || port == lcp->port) break;
272   }
273
274 /* Use this network timeout in any requests. */
275
276 if (tcplimit > 0)
277   {
278   timeout.tv_sec = tcplimit;
279   timeout.tv_usec = 0;
280   timeoutptr = &timeout;
281   }
282
283 /* If no cached connection found, we must open a connection to the server. If
284 the server name is actually an absolute path, we set ldapi=TRUE above. This
285 requests connection via a Unix socket. However, as far as I know, only OpenLDAP
286 supports the use of sockets, and the use of ldap_initialize(). */
287
288 if (lcp == NULL)
289   {
290   LDAP *ld;
291
292
293   /* --------------------------- OpenLDAP ------------------------ */
294
295   /* There seems to be a preference under OpenLDAP for ldap_initialize()
296   instead of ldap_init(), though I have as yet been unable to find
297   documentation that says this. (OpenLDAP documentation is sparse to
298   non-existent). So we handle OpenLDAP differently here. Also, support for
299   ldapi seems to be OpenLDAP-only at present. */
300
301   #ifdef LDAP_LIB_OPENLDAP2
302
303   /* We now need an empty string for the default host. Get some store in which
304   to build a URL for ldap_initialize(). In the ldapi case, it can't be bigger
305   than (9 + 3*Ustrlen(shost)), whereas in the other cases it can't be bigger
306   than the host name + "ldaps:///" plus : and a port number, say 20 + the
307   length of the host name. What we get should accommodate both, easily. */
308
309   uschar *shost = (host == NULL)? US"" : host;
310   uschar *init_url = store_get(20 + 3 * Ustrlen(shost));
311   uschar *init_ptr;
312
313   /* Handle connection via Unix socket ("ldapi"). We build a basic LDAP URI to
314   contain the path name, with slashes escaped as %2F. */
315
316   if (ldapi)
317     {
318     int ch;
319     init_ptr = init_url + 8;
320     Ustrcpy(init_url, "ldapi://");
321     while ((ch = *shost++) != 0)
322       {
323       if (ch == '/')
324         {
325         Ustrncpy(init_ptr, "%2F", 3);
326         init_ptr += 3;
327         }
328       else *init_ptr++ = ch;
329       }
330     *init_ptr = 0;
331     }
332
333   /* This is not an ldapi call. Just build a URI with the protocol type, host
334   name, and port. */
335
336   else
337     {
338     init_ptr = Ustrchr(ldap_url, '/');
339     Ustrncpy(init_url, ldap_url, init_ptr - ldap_url);
340     init_ptr = init_url + (init_ptr - ldap_url);
341     sprintf(CS init_ptr, "//%s:%d/", shost, port);
342     }
343
344   /* Call ldap_initialize() and check the result */
345
346   DEBUG(D_lookup) debug_printf("ldap_initialize with URL %s\n", init_url);
347   rc = ldap_initialize(&ld, CS init_url);
348   if (rc != LDAP_SUCCESS)
349     {
350     *errmsg = string_sprintf("ldap_initialize: (error %d) URL \"%s\"\n",
351       rc, init_url);
352     goto RETURN_ERROR;
353     }
354   store_reset(init_url);   /* Might as well save memory when we can */
355
356
357   /* ------------------------- Not OpenLDAP ---------------------- */
358
359   /* For libraries other than OpenLDAP, use ldap_init(). */
360
361   #else   /* LDAP_LIB_OPENLDAP2 */
362   ld = ldap_init(CS host, port);
363   #endif  /* LDAP_LIB_OPENLDAP2 */
364
365   /* -------------------------------------------------------------- */
366
367
368   /* Handle failure to initialize */
369
370   if (ld == NULL)
371     {
372     *errmsg = string_sprintf("failed to initialize for LDAP server %s%s - %s",
373       host, porttext, strerror(errno));
374     goto RETURN_ERROR;
375     }
376
377   /* Set the TCP connect time limit if available. This is something that is
378   in Netscape SDK v4.1; I don't know about other libraries. */
379
380   #ifdef LDAP_X_OPT_CONNECT_TIMEOUT
381   if (tcplimit > 0)
382     {
383     int timeout1000 = tcplimit*1000;
384     ldap_set_option(ld, LDAP_X_OPT_CONNECT_TIMEOUT, (void *)&timeout1000);
385     }
386   else
387     {
388     int notimeout = LDAP_X_IO_TIMEOUT_NO_TIMEOUT;
389     ldap_set_option(ld, LDAP_X_OPT_CONNECT_TIMEOUT, (void *)&notimeout);
390     }
391   #endif
392
393   /* Set the TCP connect timeout. This works with OpenLDAP 2.2.14. */
394
395   #ifdef LDAP_OPT_NETWORK_TIMEOUT
396   if (tcplimit > 0)
397     ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, (void *)timeoutptr);
398   #endif 
399
400   /* I could not get TLS to work until I set the version to 3. That version
401   seems to be the default nowadays. The RFC is dated 1997, so I would hope
402   that all the LDAP libraries support it. Therefore, if eldap_version hasn't
403   been set, go for v3 if we can. */
404
405   if (eldap_version < 0)
406     {
407     #ifdef LDAP_VERSION3
408     eldap_version = LDAP_VERSION3;
409     #else
410     eldap_version = 2;
411     #endif
412     }
413
414   #ifdef LDAP_OPT_PROTOCOL_VERSION
415   ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, (void *)&eldap_version);
416   #endif
417
418   DEBUG(D_lookup) debug_printf("initialized for LDAP (v%d) server %s%s\n",
419     eldap_version, host, porttext);
420
421   /* If not using ldapi and TLS is available, set appropriate TLS options: hard
422   for "ldaps" and soft otherwise. */
423
424   #ifdef LDAP_OPT_X_TLS
425   if (!ldapi)
426     {
427     int tls_option;
428     if (strncmp(ludp->lud_scheme, "ldaps", 5) == 0)
429       {
430       tls_option = LDAP_OPT_X_TLS_HARD;
431       DEBUG(D_lookup) debug_printf("LDAP_OPT_X_TLS_HARD set\n");
432       }
433     else
434       {
435       tls_option = LDAP_OPT_X_TLS_TRY;
436       DEBUG(D_lookup) debug_printf("LDAP_OPT_X_TLS_TRY set\n");
437       }
438     ldap_set_option(ld, LDAP_OPT_X_TLS, (void *)&tls_option);
439     }
440   #endif  /* LDAP_OPT_X_TLS */
441
442   /* Now add this connection to the chain of cached connections */
443
444   lcp = store_get(sizeof(LDAP_CONNECTION));
445   lcp->host = (host == NULL)? NULL : string_copy(host);
446   lcp->bound = FALSE;
447   lcp->user = NULL;
448   lcp->password = NULL;
449   lcp->port = port;
450   lcp->ld = ld;
451   lcp->next = ldap_connections;
452   ldap_connections = lcp;
453   }
454
455 /* Found cached connection */
456
457 else
458   {
459   DEBUG(D_lookup)
460     debug_printf("re-using cached connection to LDAP server %s%s\n",
461       host, porttext);
462   }
463
464 /* Bind with the user/password supplied, or an anonymous bind if these values
465 are NULL, unless a cached connection is already bound with the same values. */
466
467 if (!lcp->bound ||
468     (lcp->user == NULL && user != NULL) ||
469     (lcp->user != NULL && user == NULL) ||
470     (lcp->user != NULL && user != NULL && Ustrcmp(lcp->user, user) != 0) ||
471     (lcp->password == NULL && password != NULL) ||
472     (lcp->password != NULL && password == NULL) ||
473     (lcp->password != NULL && password != NULL &&
474       Ustrcmp(lcp->password, password) != 0))
475   {
476   DEBUG(D_lookup) debug_printf("%sbinding with user=%s password=%s\n",
477     (lcp->bound)? "re-" : "", user, password);
478   if ((msgid = ldap_bind(lcp->ld, CS user, CS password, LDAP_AUTH_SIMPLE))
479        == -1)
480     {
481     *errmsg = string_sprintf("failed to bind the LDAP connection to server "
482       "%s%s - ldap_bind() returned -1", host, porttext);
483     goto RETURN_ERROR;
484     }
485
486   if ((rc = ldap_result( lcp->ld, msgid, 1, timeoutptr, &result )) <= 0)
487     {
488     *errmsg = string_sprintf("failed to bind the LDAP connection to server "
489       "%s%s - LDAP error: %s", host, porttext, 
490       rc == -1 ? "result retrieval failed" : "timeout" );
491     result = NULL;
492     goto RETURN_ERROR;
493     }
494
495   rc = ldap_result2error( lcp->ld, result, 0 );
496
497   /* Invalid credentials when just checking credentials returns FAIL. This
498   stops any further servers being tried. */
499
500   if (search_type == SEARCH_LDAP_AUTH && rc == LDAP_INVALID_CREDENTIALS)
501     {
502     DEBUG(D_lookup)
503       debug_printf("Invalid credentials: ldapauth returns FAIL\n");
504     error_yield = FAIL;
505     goto RETURN_ERROR_NOMSG;
506     }
507
508   /* Otherwise we have a problem that doesn't stop further servers from being
509   tried. */
510
511   if (rc != LDAP_SUCCESS)
512     {
513     *errmsg = string_sprintf("failed to bind the LDAP connection to server "
514       "%s%s - LDAP error %d: %s", host, porttext, rc, ldap_err2string(rc));
515     goto RETURN_ERROR;
516     }
517
518   /* Successful bind */
519
520   lcp->bound = TRUE;
521   lcp->user = (user == NULL)? NULL : string_copy(user);
522   lcp->password = (password == NULL)? NULL : string_copy(password);
523
524   ldap_msgfree(result);
525   result = NULL;
526   }
527
528 /* If we are just checking credentials, return OK. */
529
530 if (search_type == SEARCH_LDAP_AUTH)
531   {
532   DEBUG(D_lookup) debug_printf("Bind succeeded: ldapauth returns OK\n");
533   goto RETURN_OK;
534   }
535
536 /* Before doing the search, set the time and size limits (if given). Here again
537 the different implementations of LDAP have chosen to do things differently. */
538
539 #if defined(LDAP_OPT_SIZELIMIT)
540 ldap_set_option(lcp->ld, LDAP_OPT_SIZELIMIT, (void *)&sizelimit);
541 ldap_set_option(lcp->ld, LDAP_OPT_TIMELIMIT, (void *)&timelimit);
542 #else
543 lcp->ld->ld_sizelimit = sizelimit;
544 lcp->ld->ld_timelimit = timelimit;
545 #endif
546
547 /* Similarly for dereferencing aliases. Don't know if this is possible on
548 an LDAP library without LDAP_OPT_DEREF. */
549
550 #if defined(LDAP_OPT_DEREF)
551 ldap_set_option(lcp->ld, LDAP_OPT_DEREF, (void *)&dereference);
552 #endif
553
554 /* Start the search on the server. */
555
556 DEBUG(D_lookup) debug_printf("Start search\n");
557
558 msgid = ldap_search(lcp->ld, ludp->lud_dn, ludp->lud_scope, ludp->lud_filter,
559   ludp->lud_attrs, 0);
560
561 if (msgid == -1)
562   {
563   #if defined LDAP_LIB_SOLARIS || defined LDAP_LIB_OPENLDAP2
564   int err;
565   ldap_get_option(lcp->ld, LDAP_OPT_ERROR_NUMBER, &err);
566   *errmsg = string_sprintf("ldap_search failed: %d, %s", err, 
567     ldap_err2string(err));
568       
569   #else    
570   *errmsg = string_sprintf("ldap_search failed");
571   #endif
572  
573   goto RETURN_ERROR;
574   }
575
576 /* Loop to pick up results as they come in, setting a timeout if one was
577 given. */
578
579 while ((rc = ldap_result(lcp->ld, msgid, 0, timeoutptr, &result)) ==
580         LDAP_RES_SEARCH_ENTRY)
581   {
582   LDAPMessage  *e;
583
584   DEBUG(D_lookup) debug_printf("ldap_result loop\n");
585
586   for(e = ldap_first_entry(lcp->ld, result);
587       e != NULL;
588       e = ldap_next_entry(lcp->ld, e))
589     {
590     uschar *new_dn;
591     BOOL insert_space = FALSE;
592
593     DEBUG(D_lookup) debug_printf("LDAP entry loop\n");
594
595     rescount++;   /* Count results */
596
597     /* Results for multiple entries values are separated by newlines. */
598
599     if (data != NULL) data = string_cat(data, &size, &ptr, US"\n", 1);
600
601     /* Get the DN from the last result. */
602
603     new_dn = US ldap_get_dn(lcp->ld, e);
604     if (new_dn != NULL)
605       {
606       if (dn != NULL)
607         {
608         #if defined LDAP_LIB_NETSCAPE || defined LDAP_LIB_OPENLDAP2
609         ldap_memfree(dn);
610         #else   /* OPENLDAP 1, UMich, Solaris */
611         free(dn);
612         #endif
613         }
614       /* Save for later */
615       dn = new_dn;
616       }
617
618     /* If the data we want is actually the DN rather than any attribute values,
619     (an "ldapdn" search) add it to the data string. If there are multiple
620     entries, the DNs will be concatenated, but we test for this case below, as
621     for SEARCH_LDAP_SINGLE, and give an error. */
622
623     if (search_type == SEARCH_LDAP_DN)   /* Do not amalgamate these into one */
624       {                                  /* condition, because of the else */
625       if (new_dn != NULL)                /* below, that's for the first only */
626         {
627         data = string_cat(data, &size, &ptr, new_dn, Ustrlen(new_dn));
628         data[ptr] = 0;
629         attribute_found = TRUE;
630         }
631       }
632
633     /* Otherwise, loop through the entry, grabbing attribute values. If there's
634     only one attribute being retrieved, no attribute name is given, and the
635     result is not quoted. Multiple values are separated by (comma, space).
636     If more than one attribute is being retrieved, the data is given as a
637     sequence of name=value pairs, with the value always in quotes. If there are
638     multiple values, they are given within the quotes, comma separated. */
639
640     else for (attr = US ldap_first_attribute(lcp->ld, e, &ber);
641               attr != NULL;
642               attr = US ldap_next_attribute(lcp->ld, e, ber))
643       {
644       if (attr[0] != 0)
645         {
646         /* Get array of values for this attribute. */
647
648         if ((firstval = values = USS ldap_get_values(lcp->ld, e, CS attr))
649              != NULL)
650           {
651           if (attr_count != 1)
652             {
653             if (insert_space)
654               data = string_cat(data, &size, &ptr, US" ", 1);
655             else
656               insert_space = TRUE;
657             data = string_cat(data, &size, &ptr, attr, Ustrlen(attr));
658             data = string_cat(data, &size, &ptr, US"=\"", 2);
659             }
660
661           while (*values != NULL)
662             {
663             uschar *value = *values;
664             int len = Ustrlen(value);
665
666             DEBUG(D_lookup) debug_printf("LDAP attr loop %s:%s\n", attr, value);
667
668             if (values != firstval)
669               data = string_cat(data, &size, &ptr, US", ", 2);
670
671             /* For multiple attributes, the data is in quotes. We must escape
672             internal quotes, backslashes, newlines. */
673
674             if (attr_count != 1)
675               {
676               int j;
677               for (j = 0; j < len; j++)
678                 {
679                 if (value[j] == '\n')
680                   data = string_cat(data, &size, &ptr, US"\\n", 2);
681                 else
682                   {
683                   if (value[j] == '\"' || value[j] == '\\')
684                     data = string_cat(data, &size, &ptr, US"\\", 1);
685                   data = string_cat(data, &size, &ptr, value+j, 1);
686                   }
687                 }
688               }
689
690             /* For single attributes, copy the value verbatim */
691
692             else data = string_cat(data, &size, &ptr, value, len);
693
694             /* Move on to the next value */
695
696             values++;
697             attribute_found = TRUE;
698             }
699
700           /* Closing quote at the end of the data for a named attribute. */
701
702           if (attr_count != 1)
703             data = string_cat(data, &size, &ptr, US"\"", 1);
704
705           /* Free the values */
706
707           ldap_value_free(CSS firstval);
708           }
709         }
710
711       #if defined LDAP_LIB_NETSCAPE || defined LDAP_LIB_OPENLDAP2
712
713       /* Netscape and OpenLDAP2 LDAP's attrs are dynamically allocated and need
714       to be freed. UMich LDAP stores them in static storage and does not require
715       this. */
716
717       ldap_memfree(attr);
718       #endif
719       }        /* End "for" loop for extracting attributes from an entry */
720     }          /* End "for" loop for extracting entries from a result */
721
722   /* Free the result */
723
724   ldap_msgfree(result);
725   result = NULL;
726   }            /* End "while" loop for multiple results */
727
728 /* Terminate the dynamic string that we have built and reclaim unused store */
729
730 if (data != NULL)
731   {
732   data[ptr] = 0;
733   store_reset(data + ptr + 1);
734   }
735
736 /* Copy the last dn into eldap_dn */
737
738 if (dn != NULL)
739   {
740   eldap_dn = string_copy(dn);
741   #if defined LDAP_LIB_NETSCAPE || defined LDAP_LIB_OPENLDAP2
742   ldap_memfree(dn);
743   #else   /* OPENLDAP 1, UMich, Solaris */
744   free(dn);
745   #endif
746   }
747
748 DEBUG(D_lookup) debug_printf("search ended by ldap_result yielding %d\n",rc);
749
750 if (rc == 0)
751   {
752   *errmsg = US"ldap_result timed out";
753   goto RETURN_ERROR;
754   }
755
756 /* A return code of -1 seems to mean "ldap_result failed internally or couldn't
757 provide you with a message". Other error states seem to exist where
758 ldap_result() didn't give us any message from the server at all, leaving result
759 set to NULL. Apparently, "the error parameters of the LDAP session handle will
760 be set accordingly". That's the best we can do to retrieve an error status; we
761 can't use functions like ldap_result2error because they parse a message from
762 the server, which we didn't get.
763
764 Annoyingly, the different implementations of LDAP have gone for different
765 methods of handling error codes and generating error messages. */
766
767 if (rc == -1 || result == NULL)
768   {
769   int err;
770   DEBUG(D_lookup) debug_printf("ldap_result failed\n");
771
772   #if defined LDAP_LIB_SOLARIS || defined LDAP_LIB_OPENLDAP2
773     ldap_get_option(lcp->ld, LDAP_OPT_ERROR_NUMBER, &err);
774     *errmsg = string_sprintf("ldap_result failed: %d, %s",
775       err, ldap_err2string(err));
776
777   #elif defined LDAP_LIB_NETSCAPE
778     /* Dubious (surely 'matched' is spurious here?) */
779     (void)ldap_get_lderrno(lcp->ld, &matched, &error1);
780     *errmsg = string_sprintf("ldap_result failed: %s (%s)", error1, matched);
781
782   #else                             /* UMich LDAP aka OpenLDAP 1.x */
783     *errmsg = string_sprintf("ldap_result failed: %d, %s",
784       lcp->ld->ld_errno, ldap_err2string(lcp->ld->ld_errno));
785   #endif
786
787   goto RETURN_ERROR;
788   }
789
790 /* A return code that isn't -1 doesn't necessarily mean there were no problems
791 with the search. The message must be an LDAP_RES_SEARCH_RESULT or 
792 LDAP_RES_SEARCH_REFERENCE or else it's something we can't handle. */
793
794 if (rc != LDAP_RES_SEARCH_RESULT && rc != LDAP_RES_SEARCH_REFERENCE)
795   {
796   *errmsg = string_sprintf("ldap_result returned unexpected code %d", rc);
797   goto RETURN_ERROR;
798   }
799
800 /* We have a result message from the server. This doesn't yet mean all is well.
801 We need to parse the message to find out exactly what's happened. */
802
803 #if defined LDAP_LIB_SOLARIS || defined LDAP_LIB_OPENLDAP2
804   ldap_rc = rc;
805   ldap_parse_rc = ldap_parse_result(lcp->ld, result, &rc, CSS &matched, 
806     CSS &error2, NULL, NULL, 0);
807   DEBUG(D_lookup) debug_printf("ldap_parse_result: %d\n", ldap_parse_rc);
808   if (ldap_parse_rc < 0 && 
809       (ldap_parse_rc != LDAP_NO_RESULTS_RETURNED ||
810        ldap_rc != LDAP_RES_SEARCH_REFERENCE))
811     {
812     *errmsg = string_sprintf("ldap_parse_result failed %d", ldap_parse_rc);
813     goto RETURN_ERROR;
814     }
815   error1 = US ldap_err2string(rc);
816
817 #elif defined LDAP_LIB_NETSCAPE
818   /* Dubious (it doesn't reference 'result' at all!) */
819   rc = ldap_get_lderrno(lcp->ld, &matched, &error1);
820
821 #else                             /* UMich LDAP aka OpenLDAP 1.x */
822   rc = ldap_result2error(lcp->ld, result, 0);
823   error1 = ldap_err2string(rc);
824   error2 = lcp->ld->ld_error;
825   matched = lcp->ld->ld_matched;
826 #endif
827
828 /* Process the status as follows:
829
830   (1) If we get LDAP_SIZELIMIT_EXCEEDED, just carry on, to return the
831       truncated result list.
832
833   (2) The range of errors defined by LDAP_NAME_ERROR generally mean "that
834       object does not, or cannot, exist in the database". For those cases we
835       fail the lookup.
836
837   (3) All other non-successes here are treated as some kind of problem with
838       the lookup, so return DEFER (which is the default in error_yield).
839 */
840
841 DEBUG(D_lookup) debug_printf("ldap_parse_result yielded %d: %s\n",
842   rc, ldap_err2string(rc));
843
844 if (rc != LDAP_SUCCESS && rc != LDAP_SIZELIMIT_EXCEEDED)
845   {
846   *errmsg = string_sprintf("LDAP search failed - error %d: %s%s%s%s%s",
847     rc,
848     (error1 != NULL)?                       error1  : US"",
849     (error2 != NULL && error2[0] != 0)?     US"/"   : US"",
850     (error2 != NULL)?                       error2  : US"",
851     (matched != NULL && matched[0] != 0)?   US"/"   : US"",
852     (matched != NULL)?                      matched : US"");
853
854   #if defined LDAP_NAME_ERROR
855   if (LDAP_NAME_ERROR(rc))
856   #elif defined NAME_ERROR    /* OPENLDAP1 calls it this */
857   if (NAME_ERROR(rc))
858   #else
859   if (rc == LDAP_NO_SUCH_OBJECT)
860   #endif
861
862     {
863     DEBUG(D_lookup) debug_printf("lookup failure forced\n");
864     error_yield = FAIL;
865     }
866   goto RETURN_ERROR;
867   }
868
869 /* The search succeeded. Check if we have too many results */
870
871 if (search_type != SEARCH_LDAP_MULTIPLE && rescount > 1)
872   {
873   *errmsg = string_sprintf("LDAP search: more than one entry (%d) was returned "
874     "(filter not specific enough?)", rescount);
875   goto RETURN_ERROR_BREAK;
876   }
877
878 /* Check if we have too few (zero) entries */
879
880 if (rescount < 1)
881   {
882   *errmsg = string_sprintf("LDAP search: no results");
883   error_yield = FAIL;
884   goto RETURN_ERROR_BREAK;
885   }
886
887 /* If an entry was found, but it had no attributes, we behave as if no entries
888 were found, that is, the lookup failed. */
889
890 if (!attribute_found)
891   {
892   *errmsg = US"LDAP search: found no attributes";
893   error_yield = FAIL;
894   goto RETURN_ERROR;
895   }
896
897 /* Otherwise, it's all worked */
898
899 DEBUG(D_lookup) debug_printf("LDAP search: returning: %s\n", data);
900 *res = data;
901
902 RETURN_OK:
903 if (result != NULL) ldap_msgfree(result);
904 ldap_free_urldesc(ludp);
905 return OK;
906
907 /* Error returns */
908
909 RETURN_ERROR_BREAK:
910 *defer_break = TRUE;
911
912 RETURN_ERROR:
913 DEBUG(D_lookup) debug_printf("%s\n", *errmsg);
914
915 RETURN_ERROR_NOMSG:
916 if (result != NULL) ldap_msgfree(result);
917 if (ludp != NULL) ldap_free_urldesc(ludp);
918
919 #if defined LDAP_LIB_OPENLDAP2
920   if (error2 != NULL)  ldap_memfree(error2);
921   if (matched != NULL) ldap_memfree(matched);
922 #endif
923
924 return error_yield;
925 }
926
927
928
929 /*************************************************
930 *        Internal search control function        *
931 *************************************************/
932
933 /* This function is called from eldap_find(), eldapauth_find(), eldapdn_find(),
934 and eldapm_find() with a difference in the "search_type" argument. It controls
935 calls to perform_ldap_search() which actually does the work. We call that
936 repeatedly for certain types of defer in the case when the URL contains no host
937 name and eldap_default_servers is set to a list of servers to try. This gives
938 more control than just passing over a list of hosts to ldap_open() because it
939 handles other kinds of defer as well as just a failure to open. Note that the
940 URL is defined to contain either zero or one "hostport" only.
941
942 Parameter data in addition to the URL can be passed as preceding text in the
943 string, as items of the form XXX=yyy. The URL itself can be detected because it
944 must begin "ldapx://", where x is empty, s, or i.
945
946 Arguments:
947   ldap_url      the URL to be looked up, optionally preceded by other parameter
948                 settings
949   search_type   SEARCH_LDAP_MULTIPLE allows values from multiple entries
950                 SEARCH_LDAP_SINGLE allows values from one entry only
951                 SEARCH_LDAP_DN gets the DN from one entry
952   res           set to point at the result
953   errmsg        set to point a message if result is not OK
954
955 Returns:        OK or FAIL or DEFER
956 */
957
958 static int
959 control_ldap_search(uschar *ldap_url, int search_type, uschar **res,
960   uschar **errmsg)
961 {
962 BOOL defer_break = FALSE;
963 int timelimit = LDAP_NO_LIMIT;
964 int sizelimit = LDAP_NO_LIMIT;
965 int tcplimit = 0;
966 int dereference = LDAP_DEREF_NEVER;
967 int sep = 0;
968 uschar *url = ldap_url;
969 uschar *p;
970 uschar *user = NULL;
971 uschar *password = NULL;
972 uschar *server, *list;
973 uschar buffer[512];
974
975 while (isspace(*url)) url++;
976
977 /* Until the string begins "ldap", search for the other parameter settings that
978 are recognized. They are of the form NAME=VALUE, with the value being
979 optionally double-quoted. There must still be a space after it, however. No
980 NAME has the value "ldap". */
981
982 while (strncmpic(url, US"ldap", 4) != 0)
983   {
984   uschar *name = url;
985   while (*url != 0 && *url != '=') url++;
986   if (*url == '=')
987     {
988     int namelen;
989     uschar *value;
990     namelen = ++url - name;
991     value = string_dequote(&url);
992     if (isspace(*url))
993       {
994       if (strncmpic(name, US"USER=", namelen) == 0) user = value;
995       else if (strncmpic(name, US"PASS=", namelen) == 0) password = value;
996       else if (strncmpic(name, US"SIZE=", namelen) == 0) sizelimit = Uatoi(value);
997       else if (strncmpic(name, US"TIME=", namelen) == 0) timelimit = Uatoi(value);
998       else if (strncmpic(name, US"CONNECT=", namelen) == 0) tcplimit = Uatoi(value);
999       else if (strncmpic(name, US"NETTIME=", namelen) == 0) tcplimit = Uatoi(value);
1000
1001       /* Don't know if all LDAP libraries have LDAP_OPT_DEREF */
1002
1003       #ifdef LDAP_OPT_DEREF
1004       else if (strncmpic(name, US"DEREFERENCE=", namelen) == 0)
1005         {
1006         if (strcmpic(value, US"never") == 0) dereference = LDAP_DEREF_NEVER;
1007         else if (strcmpic(value, US"searching") == 0)
1008           dereference = LDAP_DEREF_SEARCHING;
1009         else if (strcmpic(value, US"finding") == 0)
1010           dereference = LDAP_DEREF_FINDING;
1011         if (strcmpic(value, US"always") == 0) dereference = LDAP_DEREF_ALWAYS;
1012         }
1013       #else
1014       else if (strncmpic(name, US"DEREFERENCE=", namelen) == 0)
1015         {
1016         *errmsg = string_sprintf("LDAP_OP_DEREF not defined in this LDAP "
1017           "library - cannot use \"dereference\"");
1018         DEBUG(D_lookup) debug_printf("%s\n", *errmsg);
1019         return DEFER;
1020         }
1021
1022       #endif
1023
1024       else
1025         {
1026         *errmsg =
1027           string_sprintf("unknown parameter \"%.*s\" precedes LDAP URL",
1028             namelen, name);
1029         DEBUG(D_lookup) debug_printf("LDAP query error: %s\n", *errmsg);
1030         return DEFER;
1031         }
1032       while (isspace(*url)) url++;
1033       continue;
1034       }
1035     }
1036   *errmsg = US"malformed parameter setting precedes LDAP URL";
1037   DEBUG(D_lookup) debug_printf("LDAP query error: %s\n", *errmsg);
1038   return DEFER;
1039   }
1040
1041 /* If user is set, de-URL-quote it. Some LDAP libraries do this for themselves,
1042 but it seems that not all behave like this. The DN for the user is often the
1043 result of ${quote_ldap_dn:...} quoting, which does apply URL quoting, because
1044 that is needed when the DN is used as a base DN in a query. Sigh. This is all
1045 far too complicated. */
1046
1047 if (user != NULL)
1048   {
1049   uschar *s;
1050   uschar *t = user;
1051   for (s = user; *s != 0; s++)
1052     {
1053     int c, d;
1054     if (*s == '%' && isxdigit(c=s[1]) && isxdigit(d=s[2]))
1055       {
1056       c = tolower(c);
1057       d = tolower(d);
1058       *t++ =
1059         (((c >= 'a')? (10 + c - 'a') : c - '0') << 4) |
1060          ((d >= 'a')? (10 + d - 'a') : d - '0');
1061       s += 2;
1062       }
1063     else *t++ = *s;
1064     }
1065   *t = 0;
1066   }
1067
1068 DEBUG(D_lookup)
1069   debug_printf("LDAP parameters: user=%s pass=%s size=%d time=%d connect=%d "
1070     "dereference=%d\n", user, password, sizelimit, timelimit, tcplimit,
1071     dereference);
1072
1073 /* If the request is just to check authentication, some credentials must
1074 be given. The password must not be empty because LDAP binds with an empty
1075 password are considered anonymous, and will succeed on most installations. */
1076
1077 if (search_type == SEARCH_LDAP_AUTH)
1078   {
1079   if (user == NULL || password == NULL)
1080     {
1081     *errmsg = US"ldapauth lookups must specify the username and password";
1082     return DEFER;
1083     }
1084   if (password[0] == 0)
1085     {
1086     DEBUG(D_lookup) debug_printf("Empty password: ldapauth returns FAIL\n");
1087     return FAIL;
1088     }
1089   }
1090
1091 /* Check for valid ldap url starters */
1092
1093 p = url + 4;
1094 if (tolower(*p) == 's' || tolower(*p) == 'i') p++;
1095 if (Ustrncmp(p, "://", 3) != 0)
1096   {
1097   *errmsg = string_sprintf("LDAP URL does not start with \"ldap://\", "
1098     "\"ldaps://\", or \"ldapi://\" (it starts with \"%.16s...\")", url);
1099   DEBUG(D_lookup) debug_printf("LDAP query error: %s\n", *errmsg);
1100   return DEFER;
1101   }
1102
1103 /* No default servers, or URL contains a server name: just one attempt */
1104
1105 if (eldap_default_servers == NULL || p[3] != '/')
1106   {
1107   return perform_ldap_search(url, NULL, 0, search_type, res, errmsg,
1108     &defer_break, user, password, sizelimit, timelimit, tcplimit, dereference);
1109   }
1110
1111 /* Loop through the default servers until OK or FAIL */
1112
1113 list = eldap_default_servers;
1114 while ((server = string_nextinlist(&list, &sep, buffer, sizeof(buffer))) != NULL)
1115   {
1116   int rc;
1117   int port = 0;
1118   uschar *colon = Ustrchr(server, ':');
1119   if (colon != NULL)
1120     {
1121     *colon = 0;
1122     port = Uatoi(colon+1);
1123     }
1124   rc = perform_ldap_search(url, server, port, search_type, res, errmsg,
1125     &defer_break, user, password, sizelimit, timelimit, tcplimit, dereference);
1126   if (rc != DEFER || defer_break) return rc;
1127   }
1128
1129 return DEFER;
1130 }
1131
1132
1133
1134 /*************************************************
1135 *               Find entry point                 *
1136 *************************************************/
1137
1138 /* See local README for interface description. The different kinds of search
1139 are handled by a common function, with a flag to differentiate between them.
1140 The handle and filename arguments are not used. */
1141
1142 int
1143 eldap_find(void *handle, uschar *filename, uschar *ldap_url, int length,
1144   uschar **result, uschar **errmsg, BOOL *do_cache)
1145 {
1146 /* Keep picky compilers happy */
1147 do_cache = do_cache;
1148 return(control_ldap_search(ldap_url, SEARCH_LDAP_SINGLE, result, errmsg));
1149 }
1150
1151 int
1152 eldapm_find(void *handle, uschar *filename, uschar *ldap_url, int length,
1153   uschar **result, uschar **errmsg, BOOL *do_cache)
1154 {
1155 /* Keep picky compilers happy */
1156 do_cache = do_cache;
1157 return(control_ldap_search(ldap_url, SEARCH_LDAP_MULTIPLE, result, errmsg));
1158 }
1159
1160 int
1161 eldapdn_find(void *handle, uschar *filename, uschar *ldap_url, int length,
1162   uschar **result, uschar **errmsg, BOOL *do_cache)
1163 {
1164 /* Keep picky compilers happy */
1165 do_cache = do_cache;
1166 return(control_ldap_search(ldap_url, SEARCH_LDAP_DN, result, errmsg));
1167 }
1168
1169 int
1170 eldapauth_find(void *handle, uschar *filename, uschar *ldap_url, int length,
1171   uschar **result, uschar **errmsg, BOOL *do_cache)
1172 {
1173 /* Keep picky compilers happy */
1174 do_cache = do_cache;
1175 return(control_ldap_search(ldap_url, SEARCH_LDAP_AUTH, result, errmsg));
1176 }
1177
1178
1179
1180 /*************************************************
1181 *              Open entry point                  *
1182 *************************************************/
1183
1184 /* See local README for interface description. */
1185
1186 void *
1187 eldap_open(uschar *filename, uschar **errmsg)
1188 {
1189 return (void *)(1);    /* Just return something non-null */
1190 }
1191
1192
1193
1194 /*************************************************
1195 *               Tidy entry point                 *
1196 *************************************************/
1197
1198 /* See local README for interface description.
1199 Make sure that eldap_dn does not refer to reclaimed or worse, freed store */
1200
1201 void
1202 eldap_tidy(void)
1203 {
1204 LDAP_CONNECTION *lcp = NULL;
1205 eldap_dn = NULL;
1206
1207 while ((lcp = ldap_connections) != NULL)
1208   {
1209   DEBUG(D_lookup) debug_printf("unbind LDAP connection to %s:%d\n", lcp->host,
1210     lcp->port);
1211   ldap_unbind(lcp->ld);
1212   ldap_connections = lcp->next;
1213   }
1214 }
1215
1216
1217
1218 /*************************************************
1219 *               Quote entry point                *
1220 *************************************************/
1221
1222 /* LDAP quoting is unbelievably messy. For a start, two different levels of
1223 quoting have to be done: LDAP quoting, and URL quoting. The current
1224 specification is the result of a suggestion by Brian Candler. It recognizes
1225 two separate cases:
1226
1227 (1) For text that appears in a search filter, the following escapes are
1228     required (see RFC 2254):
1229
1230       *    ->   \2A
1231       (    ->   \28
1232       )    ->   \29
1233       \    ->   \5C
1234      NULL  ->   \00
1235
1236     Then the entire filter text must be URL-escaped. This kind of quoting is
1237     implemented by ${quote_ldap:....}. Note that we can never have a NULL
1238     in the input string, because that's a terminator.
1239
1240 (2) For a DN that is part of a URL (i.e. the base DN), the characters
1241
1242       , + " \ < > ;
1243
1244     must be quoted by backslashing. See RFC 2253. Leading and trailing spaces
1245     must be escaped, as must a leading #. Then the string must be URL-quoted.
1246     This type of quoting is implemented by ${quote_ldap_dn:....}.
1247
1248 For URL quoting, the only characters that need not be quoted are the
1249 alphamerics and
1250
1251   ! $ ' ( ) * + - . _
1252
1253 All the others must be hexified and preceded by %. This includes the
1254 backslashes used for LDAP quoting.
1255
1256 For a DN that is given in the USER parameter for authentication, we need the
1257 same initial quoting as (2) but in this case, the result must NOT be
1258 URL-escaped, because it isn't a URL. The way this is handled is by
1259 de-URL-quoting the text when processing the USER parameter in
1260 control_ldap_search() above. That means that the same quote operator can be
1261 used. This has the additional advantage that spaces in the DN won't cause
1262 parsing problems. For example:
1263
1264   USER=cn=${quote_ldap_dn:$1},%20dc=example,%20dc=com
1265
1266 should be safe if there are spaces in $1.
1267
1268
1269 Arguments:
1270   s          the string to be quoted
1271   opt        additional option text or NULL if none
1272              only "dn" is recognized
1273
1274 Returns:     the processed string or NULL for a bad option
1275 */
1276
1277
1278
1279 /* The characters in this string, together with alphanumerics, never need
1280 quoting in any way. */
1281
1282 #define ALWAYS_LITERAL  "!$'-._"
1283
1284 /* The special characters in this string do not need to be URL-quoted. The set
1285 is a bit larger than the general literals. */
1286
1287 #define URL_NONQUOTE    ALWAYS_LITERAL "()*+"
1288
1289 /* The following macros define the characters that are quoted by quote_ldap and
1290 quote_ldap_dn, respectively. */
1291
1292 #define LDAP_QUOTE      "*()\\"
1293 #define LDAP_DN_QUOTE   ",+\"\\<>;"
1294
1295
1296
1297 uschar *
1298 eldap_quote(uschar *s, uschar *opt)
1299 {
1300 register int c;
1301 int count = 0;
1302 int len = 0;
1303 BOOL dn = FALSE;
1304 uschar *t = s;
1305 uschar *quoted;
1306
1307 /* Test for a DN quotation. */
1308
1309 if (opt != NULL)
1310   {
1311   if (Ustrcmp(opt, "dn") != 0) return NULL;    /* No others recognized */
1312   dn = TRUE;
1313   }
1314
1315 /* Compute how much extra store we need for the string. This doesn't have to be
1316 exact as long as it isn't an underestimate. The worst case is the addition of 5
1317 extra bytes for a single character. This occurs for certain characters in DNs,
1318 where, for example, < turns into %5C%3C. For simplicity, we just add 5 for each
1319 possibly escaped character. The really fast way would be just to test for
1320 non-alphanumerics, but it is probably better to spot a few others that are
1321 never escaped, because if there are no specials at all, we can avoid copying
1322 the string. */
1323
1324 while ((c = *t++) != 0)
1325   {
1326   len++;
1327   if (!isalnum(c) && Ustrchr(ALWAYS_LITERAL, c) == NULL) count += 5;
1328   }
1329 if (count == 0) return s;
1330
1331 /* Get sufficient store to hold the quoted string */
1332
1333 t = quoted = store_get(len + count + 1);
1334
1335 /* Handle plain quote_ldap */
1336
1337 if (!dn)
1338   {
1339   while ((c = *s++) != 0)
1340     {
1341     if (!isalnum(c))
1342       {
1343       if (Ustrchr(LDAP_QUOTE, c) != NULL)
1344         {
1345         sprintf(CS t, "%%5C%02X", c);        /* e.g. * => %5C2A */
1346         t += 5;
1347         continue;
1348         }
1349       if (Ustrchr(URL_NONQUOTE, c) == NULL)  /* e.g. ] => %5D */
1350         {
1351         sprintf(CS t, "%%%02X", c);
1352         t += 3;
1353         continue;
1354         }
1355       }
1356     *t++ = c;                                /* unquoted character */
1357     }
1358   }
1359
1360 /* Handle quote_ldap_dn */
1361
1362 else
1363   {
1364   uschar *ss = s + len;
1365
1366   /* Find the last char before any trailing spaces */
1367
1368   while (ss > s && ss[-1] == ' ') ss--;
1369
1370   /* Quote leading spaces and sharps */
1371
1372   for (; s < ss; s++)
1373     {
1374     if (*s != ' ' && *s != '#') break;
1375     sprintf(CS t, "%%5C%%%02X", *s);
1376     t += 6;
1377     }
1378
1379   /* Handle the rest of the string, up to the trailing spaces */
1380
1381   while (s < ss)
1382     {
1383     c = *s++;
1384     if (!isalnum(c))
1385       {
1386       if (Ustrchr(LDAP_DN_QUOTE, c) != NULL)
1387         {
1388         Ustrncpy(t, "%5C", 3);               /* insert \ where needed */
1389         t += 3;                              /* fall through to check URL */
1390         }
1391       if (Ustrchr(URL_NONQUOTE, c) == NULL)  /* e.g. ] => %5D */
1392         {
1393         sprintf(CS t, "%%%02X", c);
1394         t += 3;
1395         continue;
1396         }
1397       }
1398     *t++ = c;    /* unquoted character, or non-URL quoted after %5C */
1399     }
1400
1401   /* Handle the trailing spaces */
1402
1403   while (*ss++ != 0)
1404     {
1405     Ustrncpy(t, "%5C%20", 6);
1406     t += 6;
1407     }
1408   }
1409
1410 /* Terminate the new string and return */
1411
1412 *t = 0;
1413 return quoted;
1414 }
1415
1416 #endif  /* LOOKUP_LDAP */
1417
1418 /* End of lookups/ldap.c */