Git init
[external/curl.git] / lib / ldap.c
1 /***************************************************************************
2  *                      _   _ ____  _
3  *  Project         ___| | | |  _ \| |
4  *                 / __| | | | |_) | |
5  *                | (__| |_| |  _ <| |___
6  *                 \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2010, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at http://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22
23 #include "setup.h"
24
25 #if !defined(CURL_DISABLE_LDAP) && !defined(USE_OPENLDAP)
26
27 /*
28  * Notice that USE_OPENLDAP is only a source code selection switch. When
29  * libcurl is built with USE_OPENLDAP defined the libcurl source code that
30  * gets compiled is the code from openldap.c, otherwise the code that gets
31  * compiled is the code from ldap.c.
32  *
33  * When USE_OPENLDAP is defined a recent version of the OpenLDAP library
34  * might be required for compilation and runtime. In order to use ancient
35  * OpenLDAP library versions, USE_OPENLDAP shall not be defined.
36  */
37
38 /* -- WIN32 approved -- */
39 #include <stdio.h>
40 #include <string.h>
41 #include <stdarg.h>
42 #include <stdlib.h>
43 #include <ctype.h>
44 #include <errno.h>
45
46 #ifdef CURL_LDAP_WIN            /* Use Windows LDAP implementation. */
47 # include <winldap.h>
48 # ifndef LDAP_VENDOR_NAME
49 #  error Your Platform SDK is NOT sufficient for LDAP support! Update your Platform SDK, or disable LDAP support!
50 # else
51 #  include <winber.h>
52 # endif
53 #else
54 # define LDAP_DEPRECATED 1      /* Be sure ldap_init() is defined. */
55 # ifdef HAVE_LBER_H
56 #  include <lber.h>
57 # endif
58 # include <ldap.h>
59 # if (defined(HAVE_LDAP_SSL) && defined(HAVE_LDAP_SSL_H))
60 #  include <ldap_ssl.h>
61 # endif /* HAVE_LDAP_SSL && HAVE_LDAP_SSL_H */
62 #endif
63
64 #ifdef HAVE_UNISTD_H
65 # include <unistd.h>
66 #endif
67
68 #include "urldata.h"
69 #include <curl/curl.h>
70 #include "sendf.h"
71 #include "escape.h"
72 #include "progress.h"
73 #include "transfer.h"
74 #include "strequal.h"
75 #include "strtok.h"
76 #include "curl_ldap.h"
77 #include "curl_memory.h"
78 #include "curl_base64.h"
79 #include "rawstr.h"
80
81 #define _MPRINTF_REPLACE /* use our functions only */
82 #include <curl/mprintf.h>
83
84 #include "memdebug.h"
85
86 #ifndef HAVE_LDAP_URL_PARSE
87
88 /* Use our own implementation. */
89
90 typedef struct {
91     char   *lud_host;
92     int     lud_port;
93     char   *lud_dn;
94     char  **lud_attrs;
95     int     lud_scope;
96     char   *lud_filter;
97     char  **lud_exts;
98 } CURL_LDAPURLDesc;
99
100 #undef LDAPURLDesc
101 #define LDAPURLDesc             CURL_LDAPURLDesc
102
103 static int  _ldap_url_parse (const struct connectdata *conn,
104                              LDAPURLDesc **ludp);
105 static void _ldap_free_urldesc (LDAPURLDesc *ludp);
106
107 #undef ldap_free_urldesc
108 #define ldap_free_urldesc       _ldap_free_urldesc
109 #endif
110
111 #ifdef DEBUG_LDAP
112   #define LDAP_TRACE(x)   do { \
113                             _ldap_trace ("%u: ", __LINE__); \
114                             _ldap_trace x; \
115                           } while(0)
116
117   static void _ldap_trace (const char *fmt, ...);
118 #else
119   #define LDAP_TRACE(x)   ((void)0)
120 #endif
121
122
123 static CURLcode Curl_ldap(struct connectdata *conn, bool *done);
124
125 /*
126  * LDAP protocol handler.
127  */
128
129 const struct Curl_handler Curl_handler_ldap = {
130   "LDAP",                               /* scheme */
131   ZERO_NULL,                            /* setup_connection */
132   Curl_ldap,                            /* do_it */
133   ZERO_NULL,                            /* done */
134   ZERO_NULL,                            /* do_more */
135   ZERO_NULL,                            /* connect_it */
136   ZERO_NULL,                            /* connecting */
137   ZERO_NULL,                            /* doing */
138   ZERO_NULL,                            /* proto_getsock */
139   ZERO_NULL,                            /* doing_getsock */
140   ZERO_NULL,                            /* perform_getsock */
141   ZERO_NULL,                            /* disconnect */
142   PORT_LDAP,                            /* defport */
143   PROT_LDAP                             /* protocol */
144 };
145
146 #ifdef HAVE_LDAP_SSL
147 /*
148  * LDAPS protocol handler.
149  */
150
151 const struct Curl_handler Curl_handler_ldaps = {
152   "LDAPS",                              /* scheme */
153   ZERO_NULL,                            /* setup_connection */
154   Curl_ldap,                            /* do_it */
155   ZERO_NULL,                            /* done */
156   ZERO_NULL,                            /* do_more */
157   ZERO_NULL,                            /* connect_it */
158   ZERO_NULL,                            /* connecting */
159   ZERO_NULL,                            /* doing */
160   ZERO_NULL,                            /* proto_getsock */
161   ZERO_NULL,                            /* doing_getsock */
162   ZERO_NULL,                            /* perform_getsock */
163   ZERO_NULL,                            /* disconnect */
164   PORT_LDAPS,                           /* defport */
165   PROT_LDAP | PROT_SSL                  /* protocol */
166 };
167 #endif
168
169
170 static CURLcode Curl_ldap(struct connectdata *conn, bool *done)
171 {
172   CURLcode status = CURLE_OK;
173   int rc = 0;
174   LDAP *server = NULL;
175   LDAPURLDesc *ludp = NULL;
176   LDAPMessage *result = NULL;
177   LDAPMessage *entryIterator;
178   int num = 0;
179   struct SessionHandle *data=conn->data;
180   int ldap_proto = LDAP_VERSION3;
181   int ldap_ssl = 0;
182   char *val_b64;
183   size_t val_b64_sz;
184   curl_off_t dlsize=0;
185 #ifdef LDAP_OPT_NETWORK_TIMEOUT
186   struct timeval ldap_timeout = {10,0}; /* 10 sec connection/search timeout */
187 #endif
188
189   *done = TRUE; /* unconditionally */
190   infof(data, "LDAP local: LDAP Vendor = %s ; LDAP Version = %d\n",
191           LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION);
192   infof(data, "LDAP local: %s\n", data->change.url);
193
194 #ifdef HAVE_LDAP_URL_PARSE
195   rc = ldap_url_parse(data->change.url, &ludp);
196 #else
197   rc = _ldap_url_parse(conn, &ludp);
198 #endif
199   if(rc != 0) {
200     failf(data, "LDAP local: %s", ldap_err2string(rc));
201     status = CURLE_LDAP_INVALID_URL;
202     goto quit;
203   }
204
205   /* Get the URL scheme ( either ldap or ldaps ) */
206   if(conn->protocol & PROT_SSL)
207     ldap_ssl = 1;
208   infof(data, "LDAP local: trying to establish %s connection\n",
209           ldap_ssl ? "encrypted" : "cleartext");
210
211 #ifdef LDAP_OPT_NETWORK_TIMEOUT
212   ldap_set_option(NULL, LDAP_OPT_NETWORK_TIMEOUT, &ldap_timeout);
213 #endif
214   ldap_set_option(NULL, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto);
215
216   if(ldap_ssl) {
217 #ifdef HAVE_LDAP_SSL
218 #ifdef CURL_LDAP_WIN
219     /* Win32 LDAP SDK doesnt support insecure mode without CA! */
220     server = ldap_sslinit(conn->host.name, (int)conn->port, 1);
221     ldap_set_option(server, LDAP_OPT_SSL, LDAP_OPT_ON);
222 #else
223     int ldap_option;
224     char* ldap_ca = data->set.str[STRING_SSL_CAFILE];
225 #if defined(CURL_HAS_NOVELL_LDAPSDK)
226     rc = ldapssl_client_init(NULL, NULL);
227     if(rc != LDAP_SUCCESS) {
228       failf(data, "LDAP local: ldapssl_client_init %s", ldap_err2string(rc));
229       status = CURLE_SSL_CERTPROBLEM;
230       goto quit;
231     }
232     if(data->set.ssl.verifypeer) {
233       /* Novell SDK supports DER or BASE64 files. */
234       int cert_type = LDAPSSL_CERT_FILETYPE_B64;
235       if((data->set.str[STRING_CERT_TYPE]) &&
236          (Curl_raw_equal(data->set.str[STRING_CERT_TYPE], "DER")))
237         cert_type = LDAPSSL_CERT_FILETYPE_DER;
238       if(!ldap_ca) {
239         failf(data, "LDAP local: ERROR %s CA cert not set!",
240               (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"));
241         status = CURLE_SSL_CERTPROBLEM;
242         goto quit;
243       }
244       infof(data, "LDAP local: using %s CA cert '%s'\n",
245               (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"),
246               ldap_ca);
247       rc = ldapssl_add_trusted_cert(ldap_ca, cert_type);
248       if(rc != LDAP_SUCCESS) {
249         failf(data, "LDAP local: ERROR setting %s CA cert: %s",
250                 (cert_type == LDAPSSL_CERT_FILETYPE_DER ? "DER" : "PEM"),
251                 ldap_err2string(rc));
252         status = CURLE_SSL_CERTPROBLEM;
253         goto quit;
254       }
255       ldap_option = LDAPSSL_VERIFY_SERVER;
256     } else {
257       ldap_option = LDAPSSL_VERIFY_NONE;
258     }
259     rc = ldapssl_set_verify_mode(ldap_option);
260     if(rc != LDAP_SUCCESS) {
261       failf(data, "LDAP local: ERROR setting cert verify mode: %s",
262               ldap_err2string(rc));
263       status = CURLE_SSL_CERTPROBLEM;
264       goto quit;
265     }
266     server = ldapssl_init(conn->host.name, (int)conn->port, 1);
267     if(server == NULL) {
268       failf(data, "LDAP local: Cannot connect to %s:%hu",
269               conn->host.name, conn->port);
270       status = CURLE_COULDNT_CONNECT;
271       goto quit;
272     }
273 #elif defined(LDAP_OPT_X_TLS)
274     if(data->set.ssl.verifypeer) {
275       /* OpenLDAP SDK supports BASE64 files. */
276       if((data->set.str[STRING_CERT_TYPE]) &&
277          (!Curl_raw_equal(data->set.str[STRING_CERT_TYPE], "PEM"))) {
278         failf(data, "LDAP local: ERROR OpenLDAP does only support PEM cert-type!");
279         status = CURLE_SSL_CERTPROBLEM;
280         goto quit;
281       }
282       if(!ldap_ca) {
283         failf(data, "LDAP local: ERROR PEM CA cert not set!");
284         status = CURLE_SSL_CERTPROBLEM;
285         goto quit;
286       }
287       infof(data, "LDAP local: using PEM CA cert: %s\n", ldap_ca);
288       rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTFILE, ldap_ca);
289       if(rc != LDAP_SUCCESS) {
290         failf(data, "LDAP local: ERROR setting PEM CA cert: %s",
291                 ldap_err2string(rc));
292         status = CURLE_SSL_CERTPROBLEM;
293         goto quit;
294       }
295       ldap_option = LDAP_OPT_X_TLS_DEMAND;
296     } else {
297       ldap_option = LDAP_OPT_X_TLS_NEVER;
298     }
299     rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &ldap_option);
300     if(rc != LDAP_SUCCESS) {
301       failf(data, "LDAP local: ERROR setting cert verify mode: %s",
302               ldap_err2string(rc));
303       status = CURLE_SSL_CERTPROBLEM;
304       goto quit;
305     }
306     server = ldap_init(conn->host.name, (int)conn->port);
307     if(server == NULL) {
308       failf(data, "LDAP local: Cannot connect to %s:%hu",
309               conn->host.name, conn->port);
310       status = CURLE_COULDNT_CONNECT;
311       goto quit;
312     }
313     ldap_option = LDAP_OPT_X_TLS_HARD;
314     rc = ldap_set_option(server, LDAP_OPT_X_TLS, &ldap_option);
315     if(rc != LDAP_SUCCESS) {
316       failf(data, "LDAP local: ERROR setting SSL/TLS mode: %s",
317               ldap_err2string(rc));
318       status = CURLE_SSL_CERTPROBLEM;
319       goto quit;
320     }
321 /*
322     rc = ldap_start_tls_s(server, NULL, NULL);
323     if(rc != LDAP_SUCCESS) {
324       failf(data, "LDAP local: ERROR starting SSL/TLS mode: %s",
325               ldap_err2string(rc));
326       status = CURLE_SSL_CERTPROBLEM;
327       goto quit;
328     }
329 */
330 #else
331     /* we should probably never come up to here since configure
332        should check in first place if we can support LDAP SSL/TLS */
333     failf(data, "LDAP local: SSL/TLS not supported with this version "
334             "of the OpenLDAP toolkit\n");
335     status = CURLE_SSL_CERTPROBLEM;
336     goto quit;
337 #endif
338 #endif
339 #endif /* CURL_LDAP_USE_SSL */
340   } else {
341     server = ldap_init(conn->host.name, (int)conn->port);
342     if(server == NULL) {
343       failf(data, "LDAP local: Cannot connect to %s:%hu",
344               conn->host.name, conn->port);
345       status = CURLE_COULDNT_CONNECT;
346       goto quit;
347     }
348   }
349 #ifdef CURL_LDAP_WIN
350   ldap_set_option(server, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto);
351 #endif
352
353   rc = ldap_simple_bind_s(server,
354                           conn->bits.user_passwd ? conn->user : NULL,
355                           conn->bits.user_passwd ? conn->passwd : NULL);
356   if(!ldap_ssl && rc != 0) {
357     ldap_proto = LDAP_VERSION2;
358     ldap_set_option(server, LDAP_OPT_PROTOCOL_VERSION, &ldap_proto);
359     rc = ldap_simple_bind_s(server,
360                             conn->bits.user_passwd ? conn->user : NULL,
361                             conn->bits.user_passwd ? conn->passwd : NULL);
362   }
363   if(rc != 0) {
364      failf(data, "LDAP local: ldap_simple_bind_s %s", ldap_err2string(rc));
365      status = CURLE_LDAP_CANNOT_BIND;
366      goto quit;
367   }
368
369   rc = ldap_search_s(server, ludp->lud_dn, ludp->lud_scope,
370                      ludp->lud_filter, ludp->lud_attrs, 0, &result);
371
372   if(rc != 0 && rc != LDAP_SIZELIMIT_EXCEEDED) {
373     failf(data, "LDAP remote: %s", ldap_err2string(rc));
374     status = CURLE_LDAP_SEARCH_FAILED;
375     goto quit;
376   }
377
378   for(num = 0, entryIterator = ldap_first_entry(server, result);
379       entryIterator;
380       entryIterator = ldap_next_entry(server, entryIterator), num++)
381   {
382     BerElement *ber = NULL;
383     char  *attribute;       /*! suspicious that this isn't 'const' */
384     char  *dn = ldap_get_dn(server, entryIterator);
385     int i;
386
387     Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"DN: ", 4);
388     Curl_client_write(conn, CLIENTWRITE_BODY, (char *)dn, 0);
389     Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 1);
390
391     dlsize += strlen(dn)+5;
392
393     for (attribute = ldap_first_attribute(server, entryIterator, &ber);
394          attribute;
395          attribute = ldap_next_attribute(server, entryIterator, ber))
396     {
397       BerValue **vals = ldap_get_values_len(server, entryIterator, attribute);
398
399       if(vals != NULL)
400       {
401         for (i = 0; (vals[i] != NULL); i++)
402         {
403           Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\t", 1);
404           Curl_client_write(conn, CLIENTWRITE_BODY, (char *) attribute, 0);
405           Curl_client_write(conn, CLIENTWRITE_BODY, (char *)": ", 2);
406           dlsize += strlen(attribute)+3;
407
408           if((strlen(attribute) > 7) &&
409               (strcmp(";binary",
410                       (char *)attribute +
411                       (strlen((char *)attribute) - 7)) == 0)) {
412             /* Binary attribute, encode to base64. */
413             val_b64_sz = Curl_base64_encode(data,
414                                             vals[i]->bv_val,
415                                             vals[i]->bv_len,
416                                             &val_b64);
417             if(val_b64_sz > 0) {
418               Curl_client_write(conn, CLIENTWRITE_BODY, val_b64, val_b64_sz);
419               free(val_b64);
420               dlsize += val_b64_sz;
421             }
422           }
423           else {
424             Curl_client_write(conn, CLIENTWRITE_BODY, vals[i]->bv_val,
425                               vals[i]->bv_len);
426             dlsize += vals[i]->bv_len;
427           }
428           Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 0);
429           dlsize++;
430         }
431
432         /* Free memory used to store values */
433         ldap_value_free_len(vals);
434       }
435       Curl_client_write(conn, CLIENTWRITE_BODY, (char *)"\n", 1);
436       dlsize++;
437       Curl_pgrsSetDownloadCounter(data, dlsize);
438       ldap_memfree(attribute);
439     }
440     ldap_memfree(dn);
441     if(ber)
442        ber_free(ber, 0);
443   }
444
445 quit:
446   if(result) {
447     ldap_msgfree(result);
448     LDAP_TRACE (("Received %d entries\n", num));
449   }
450   if(rc == LDAP_SIZELIMIT_EXCEEDED)
451     infof(data, "There are more than %d entries\n", num);
452   if(ludp)
453     ldap_free_urldesc(ludp);
454   if(server)
455     ldap_unbind_s(server);
456 #if defined(HAVE_LDAP_SSL) && defined(CURL_HAS_NOVELL_LDAPSDK)
457   if(ldap_ssl)
458     ldapssl_client_deinit();
459 #endif /* HAVE_LDAP_SSL && CURL_HAS_NOVELL_LDAPSDK */
460
461   /* no data to transfer */
462   Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
463   conn->bits.close = TRUE;
464
465   return status;
466 }
467
468 #ifdef DEBUG_LDAP
469 static void _ldap_trace (const char *fmt, ...)
470 {
471   static int do_trace = -1;
472   va_list args;
473
474   if(do_trace == -1) {
475     const char *env = getenv("CURL_TRACE");
476     do_trace = (env && strtol(env, NULL, 10) > 0);
477   }
478   if(!do_trace)
479     return;
480
481   va_start (args, fmt);
482   vfprintf (stderr, fmt, args);
483   va_end (args);
484 }
485 #endif
486
487 #ifndef HAVE_LDAP_URL_PARSE
488
489 /*
490  * Return scope-value for a scope-string.
491  */
492 static int str2scope (const char *p)
493 {
494   if(strequal(p, "one"))
495      return LDAP_SCOPE_ONELEVEL;
496   if(strequal(p, "onetree"))
497      return LDAP_SCOPE_ONELEVEL;
498   if(strequal(p, "base"))
499      return LDAP_SCOPE_BASE;
500   if(strequal(p, "sub"))
501      return LDAP_SCOPE_SUBTREE;
502   if(strequal( p, "subtree"))
503      return LDAP_SCOPE_SUBTREE;
504   return (-1);
505 }
506
507 /*
508  * Split 'str' into strings separated by commas.
509  * Note: res[] points into 'str'.
510  */
511 static char **split_str (char *str)
512 {
513   char **res, *lasts, *s;
514   int  i;
515
516   for (i = 2, s = strchr(str,','); s; i++)
517      s = strchr(++s,',');
518
519   res = calloc(i, sizeof(char*));
520   if(!res)
521     return NULL;
522
523   for (i = 0, s = strtok_r(str, ",", &lasts); s;
524        s = strtok_r(NULL, ",", &lasts), i++)
525     res[i] = s;
526   return res;
527 }
528
529 /*
530  * Unescape the LDAP-URL components
531  */
532 static bool unescape_elements (void *data, LDAPURLDesc *ludp)
533 {
534   int i;
535
536   if(ludp->lud_filter) {
537     ludp->lud_filter = curl_easy_unescape(data, ludp->lud_filter, 0, NULL);
538     if(!ludp->lud_filter)
539        return (FALSE);
540   }
541
542   for (i = 0; ludp->lud_attrs && ludp->lud_attrs[i]; i++) {
543     ludp->lud_attrs[i] = curl_easy_unescape(data, ludp->lud_attrs[i], 0, NULL);
544     if(!ludp->lud_attrs[i])
545        return (FALSE);
546   }
547
548   for (i = 0; ludp->lud_exts && ludp->lud_exts[i]; i++) {
549     ludp->lud_exts[i] = curl_easy_unescape(data, ludp->lud_exts[i], 0, NULL);
550     if(!ludp->lud_exts[i])
551        return (FALSE);
552   }
553
554   if(ludp->lud_dn) {
555     char *dn = ludp->lud_dn;
556     char *new_dn = curl_easy_unescape(data, dn, 0, NULL);
557
558     free(dn);
559     ludp->lud_dn = new_dn;
560     if(!new_dn)
561        return (FALSE);
562   }
563   return (TRUE);
564 }
565
566 /*
567  * Break apart the pieces of an LDAP URL.
568  * Syntax:
569  *   ldap://<hostname>:<port>/<base_dn>?<attributes>?<scope>?<filter>?<ext>
570  *
571  * <hostname> already known from 'conn->host.name'.
572  * <port>     already known from 'conn->remote_port'.
573  * extract the rest from 'conn->data->state.path+1'. All fields are optional.
574  * e.g.
575  *   ldap://<hostname>:<port>/?<attributes>?<scope>?<filter>
576  * yields ludp->lud_dn = "".
577  *
578  * Defined in RFC4516 section 2.
579  */
580 static int _ldap_url_parse2 (const struct connectdata *conn, LDAPURLDesc *ludp)
581 {
582   char *p, *q;
583   int i;
584
585   if(!conn->data ||
586       !conn->data->state.path ||
587       conn->data->state.path[0] != '/' ||
588       !checkprefix("LDAP", conn->data->change.url))
589     return LDAP_INVALID_SYNTAX;
590
591   ludp->lud_scope = LDAP_SCOPE_BASE;
592   ludp->lud_port  = conn->remote_port;
593   ludp->lud_host  = conn->host.name;
594
595   /* parse DN (Distinguished Name).
596    */
597   ludp->lud_dn = strdup(conn->data->state.path+1);
598   if(!ludp->lud_dn)
599     return LDAP_NO_MEMORY;
600
601   p = strchr(ludp->lud_dn, '?');
602   LDAP_TRACE (("DN '%.*s'\n", p ? (size_t)(p-ludp->lud_dn) :
603                strlen(ludp->lud_dn), ludp->lud_dn));
604
605   if(!p)
606     goto success;
607
608   *p++ = '\0';
609
610   /* parse attributes. skip "??".
611    */
612   q = strchr(p, '?');
613   if(q)
614     *q++ = '\0';
615
616   if(*p && *p != '?') {
617     ludp->lud_attrs = split_str(p);
618     if(!ludp->lud_attrs)
619       return LDAP_NO_MEMORY;
620
621     for (i = 0; ludp->lud_attrs[i]; i++)
622       LDAP_TRACE (("attr[%d] '%s'\n", i, ludp->lud_attrs[i]));
623   }
624
625   p = q;
626   if(!p)
627     goto success;
628
629   /* parse scope. skip "??"
630    */
631   q = strchr(p, '?');
632   if(q)
633     *q++ = '\0';
634
635   if(*p && *p != '?') {
636     ludp->lud_scope = str2scope(p);
637     if(ludp->lud_scope == -1)
638       return LDAP_INVALID_SYNTAX;
639     LDAP_TRACE (("scope %d\n", ludp->lud_scope));
640   }
641
642   p = q;
643   if(!p)
644     goto success;
645
646   /* parse filter
647    */
648   q = strchr(p, '?');
649   if(q)
650     *q++ = '\0';
651   if(!*p)
652     return LDAP_INVALID_SYNTAX;
653
654   ludp->lud_filter = p;
655   LDAP_TRACE (("filter '%s'\n", ludp->lud_filter));
656
657   p = q;
658   if(!p)
659     goto success;
660
661   /* parse extensions
662    */
663   ludp->lud_exts = split_str(p);
664   if(!ludp->lud_exts)
665     return LDAP_NO_MEMORY;
666
667   for (i = 0; ludp->lud_exts[i]; i++)
668     LDAP_TRACE (("exts[%d] '%s'\n", i, ludp->lud_exts[i]));
669
670   success:
671   if(!unescape_elements(conn->data, ludp))
672     return LDAP_NO_MEMORY;
673   return LDAP_SUCCESS;
674 }
675
676 static int _ldap_url_parse (const struct connectdata *conn,
677                             LDAPURLDesc **ludpp)
678 {
679   LDAPURLDesc *ludp = calloc(1, sizeof(*ludp));
680   int rc;
681
682   *ludpp = NULL;
683   if(!ludp)
684      return LDAP_NO_MEMORY;
685
686   rc = _ldap_url_parse2 (conn, ludp);
687   if(rc != LDAP_SUCCESS) {
688     _ldap_free_urldesc(ludp);
689     ludp = NULL;
690   }
691   *ludpp = ludp;
692   return (rc);
693 }
694
695 static void _ldap_free_urldesc (LDAPURLDesc *ludp)
696 {
697   int i;
698
699   if(!ludp)
700      return;
701
702   if(ludp->lud_dn)
703      free(ludp->lud_dn);
704
705   if(ludp->lud_filter)
706      free(ludp->lud_filter);
707
708   if(ludp->lud_attrs) {
709     for (i = 0; ludp->lud_attrs[i]; i++)
710        free(ludp->lud_attrs[i]);
711     free(ludp->lud_attrs);
712   }
713
714   if(ludp->lud_exts) {
715     for (i = 0; ludp->lud_exts[i]; i++)
716        free(ludp->lud_exts[i]);
717     free(ludp->lud_exts);
718   }
719   free (ludp);
720 }
721 #endif  /* !HAVE_LDAP_URL_PARSE */
722 #endif  /* !CURL_DISABLE_LDAP && !USE_OPENLDAP */