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