Fixed LDAP library file name bug (KNOWN_BUGS #1). configure now auto-detects
[platform/upstream/curl.git] / lib / ldap.c
1 /***************************************************************************
2  *                      _   _ ____  _
3  *  Project         ___| | | |  _ \| |
4  *                 / __| | | | |_) | |
5  *                | (__| |_| |  _ <| |___
6  *                \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2005, 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  * $Id$
22  ***************************************************************************/
23
24 #include "setup.h"
25
26 #ifndef CURL_DISABLE_LDAP
27 /* -- WIN32 approved -- */
28 #include <stdio.h>
29 #include <string.h>
30 #include <stdarg.h>
31 #include <stdlib.h>
32 #include <ctype.h>
33 #ifdef HAVE_SYS_TYPES_H
34 #include <sys/types.h>
35 #endif
36 #ifdef HAVE_SYS_STAT_H
37 #include <sys/stat.h>
38 #endif
39 #include <errno.h>
40
41 #if defined(WIN32)
42 # include <windows.h>
43 # include <malloc.h>
44 # include <winldap.h>
45 #endif
46
47 #ifdef HAVE_UNISTD_H
48 # include <unistd.h>
49 #endif
50
51 #ifdef HAVE_DLFCN_H
52 # include <dlfcn.h>
53 #endif
54
55 #include "urldata.h"
56 #include <curl/curl.h>
57 #include "sendf.h"
58 #include "escape.h"
59 #include "transfer.h"
60 #include "strequal.h"
61 #include "strtok.h"
62 #include "ldap.h"
63 #include "memory.h"
64
65 #define _MPRINTF_REPLACE /* use our functions only */
66 #include <curl/mprintf.h>
67
68 #include "memdebug.h"
69
70 /* WLdap32.dll functions are *not* stdcall. Must call these via __cdecl
71  * pointers in case libcurl was compiled as fastcall (cl -Gr). Watcom
72  * uses fastcall by default.
73  */
74 #if !defined(WIN32) && !defined(__cdecl)
75 #define __cdecl
76 #endif
77
78 #ifndef LDAP_SIZELIMIT_EXCEEDED
79 #define LDAP_SIZELIMIT_EXCEEDED 4
80 #endif
81
82 #define DLOPEN_MODE   RTLD_LAZY  /*! assume all dlopen() implementations have
83                                    this */
84
85 #if defined(RTLD_LAZY_GLOBAL)    /* It turns out some systems use this: */
86 # undef  DLOPEN_MODE
87 # define DLOPEN_MODE  RTLD_LAZY_GLOBAL
88 #elif defined(RTLD_GLOBAL)
89 # undef  DLOPEN_MODE
90 # define DLOPEN_MODE  (RTLD_LAZY | RTLD_GLOBAL)
91 #endif
92
93 #define DYNA_GET_FUNCTION(type, fnc) do { \
94           (fnc) = (type)DynaGetFunction(#fnc); \
95           if ((fnc) == NULL) \
96              return CURLE_FUNCTION_NOT_FOUND; \
97         } while (0)
98
99 /*! CygWin etc. configure could set these, but we don't want it.
100  * Must use WLdap32.dll code.
101  */
102 #if defined(WIN32)
103 #undef HAVE_DLOPEN
104 #undef HAVE_LIBDL
105 #endif
106
107 typedef void * (*dynafunc)(void *input);
108
109 /***********************************************************************
110  */
111 #if defined(HAVE_DLOPEN) || defined(HAVE_LIBDL) || defined(WIN32)
112 static void *libldap = NULL;
113 #if defined(DL_LBER_FILE)
114 static void *liblber = NULL;
115 #endif
116 #endif
117
118 static int DynaOpen(const char **mod_name)
119 {
120 #if defined(HAVE_DLOPEN) || defined(HAVE_LIBDL)
121   if (libldap == NULL) {
122     /*
123      * libldap.so can normally resolve its dependency on liblber.so
124      * automatically, but in broken installation it does not so
125      * handle it here by opening liblber.so as global.
126      */
127 #ifdef DL_LBER_FILE
128     *mod_name = DL_LBER_FILE;
129     liblber = dlopen(*mod_name, DLOPEN_MODE);
130     if (!liblber)
131       return 0;
132 #endif
133
134     /* Assume loading libldap.so will fail if loading of liblber.so failed
135      */
136     *mod_name = DL_LDAP_FILE;
137     libldap = dlopen(*mod_name, RTLD_LAZY);
138   }
139   return (libldap != NULL);
140
141 #elif defined(WIN32)
142   *mod_name = DL_LDAP_FILE;
143   if (!libldap)
144     libldap = (void*)LoadLibrary(*mod_name);
145   return (libldap != NULL);
146
147 #else
148   (void) mod_name;
149   return (0);
150 #endif
151 }
152
153 static void DynaClose(void)
154 {
155 #if defined(HAVE_DLOPEN) || defined(HAVE_LIBDL)
156   if (libldap) {
157     dlclose(libldap);
158     libldap=NULL;
159   }
160 #ifdef DL_LBER_FILE
161   if (liblber) {
162     dlclose(liblber);
163     liblber=NULL;
164   }
165 #endif
166 #elif defined(WIN32)
167   if (libldap) {
168     FreeLibrary ((HMODULE)libldap);
169     libldap = NULL;
170   }
171 #endif
172 }
173
174 static dynafunc DynaGetFunction(const char *name)
175 {
176   dynafunc func = (dynafunc)NULL;
177
178 #if defined(HAVE_DLOPEN) || defined(HAVE_LIBDL)
179   if (libldap) {
180     /* This typecast magic below was brought by Joe Halpin. In ISO C, you
181      * cannot typecast a data pointer to a function pointer, but that's
182      * exactly what we need to do here to avoid compiler warnings on picky
183      * compilers! */
184     *(void**) (&func) = dlsym(libldap, name);
185   }
186 #elif defined(WIN32)
187   if (libldap) {
188     func = (dynafunc)GetProcAddress((HINSTANCE)libldap, name);
189   }
190 #else
191   (void) name;
192 #endif
193   return func;
194 }
195
196 /***********************************************************************
197  */
198 typedef struct ldap_url_desc {
199     struct ldap_url_desc *lud_next;
200     char   *lud_scheme;
201     char   *lud_host;
202     int     lud_port;
203     char   *lud_dn;
204     char  **lud_attrs;
205     int     lud_scope;
206     char   *lud_filter;
207     char  **lud_exts;
208     int     lud_crit_exts;
209 } LDAPURLDesc;
210
211 #ifdef WIN32
212 static int  _ldap_url_parse (const struct connectdata *conn,
213                              LDAPURLDesc **ludp);
214 static void _ldap_free_urldesc (LDAPURLDesc *ludp);
215
216 static void (*ldap_free_urldesc)(LDAPURLDesc *) = _ldap_free_urldesc;
217 #endif
218
219 #ifdef DEBUG_LDAP
220   #define LDAP_TRACE(x)   do { \
221                             _ldap_trace ("%u: ", __LINE__); \
222                             _ldap_trace x; \
223                           } while (0)
224
225   static void _ldap_trace (const char *fmt, ...);
226 #else
227   #define LDAP_TRACE(x)   ((void)0)
228 #endif
229
230
231 CURLcode Curl_ldap(struct connectdata *conn, bool *done)
232 {
233   CURLcode status = CURLE_OK;
234   int rc = 0;
235 #ifndef WIN32
236   int    (*ldap_url_parse)(char *, LDAPURLDesc **);
237   void   (*ldap_free_urldesc)(void *);
238 #endif
239   void  *(__cdecl *ldap_init)(char *, int);
240   int    (__cdecl *ldap_simple_bind_s)(void *, char *, char *);
241   int    (__cdecl *ldap_unbind_s)(void *);
242   int    (__cdecl *ldap_search_s)(void *, char *, int, char *, char **,
243                                   int, void **);
244   void  *(__cdecl *ldap_first_entry)(void *, void *);
245   void  *(__cdecl *ldap_next_entry)(void *, void *);
246   char  *(__cdecl *ldap_err2string)(int);
247   char  *(__cdecl *ldap_get_dn)(void *, void *);
248   char  *(__cdecl *ldap_first_attribute)(void *, void *, void **);
249   char  *(__cdecl *ldap_next_attribute)(void *, void *, void *);
250   char **(__cdecl *ldap_get_values)(void *, void *, const char *);
251   void   (__cdecl *ldap_value_free)(char **);
252   void   (__cdecl *ldap_memfree)(void *);
253   void   (__cdecl *ber_free)(void *, int);
254
255   void *server;
256   LDAPURLDesc *ludp = NULL;
257   const char *mod_name;
258   void *result;
259   void *entryIterator;     /*! type should be 'LDAPMessage *' */
260   int num = 0;
261   struct SessionHandle *data=conn->data;
262
263   *done = TRUE; /* unconditionally */
264   infof(data, "LDAP local: %s\n", data->change.url);
265
266   if (!DynaOpen(&mod_name)) {
267     failf(data, "The %s LDAP library/libraries couldn't be opened", mod_name);
268     return CURLE_LIBRARY_NOT_FOUND;
269   }
270
271   /* The types are needed because ANSI C distinguishes between
272    * pointer-to-object (data) and pointer-to-function.
273    */
274   DYNA_GET_FUNCTION(void *(__cdecl *)(char *, int), ldap_init);
275   DYNA_GET_FUNCTION(int (__cdecl *)(void *, char *, char *), ldap_simple_bind_s);
276   DYNA_GET_FUNCTION(int (__cdecl *)(void *), ldap_unbind_s);
277 #ifndef WIN32
278   DYNA_GET_FUNCTION(int (*)(char *, LDAPURLDesc **), ldap_url_parse);
279   DYNA_GET_FUNCTION(void (*)(void *), ldap_free_urldesc);
280 #endif
281   DYNA_GET_FUNCTION(int (__cdecl *)(void *, char *, int, char *, char **, int,
282                             void **), ldap_search_s);
283   DYNA_GET_FUNCTION(void *(__cdecl *)(void *, void *), ldap_first_entry);
284   DYNA_GET_FUNCTION(void *(__cdecl *)(void *, void *), ldap_next_entry);
285   DYNA_GET_FUNCTION(char *(__cdecl *)(int), ldap_err2string);
286   DYNA_GET_FUNCTION(char *(__cdecl *)(void *, void *), ldap_get_dn);
287   DYNA_GET_FUNCTION(char *(__cdecl *)(void *, void *, void **), ldap_first_attribute);
288   DYNA_GET_FUNCTION(char *(__cdecl *)(void *, void *, void *), ldap_next_attribute);
289   DYNA_GET_FUNCTION(char **(__cdecl *)(void *, void *, const char *), ldap_get_values);
290   DYNA_GET_FUNCTION(void (__cdecl *)(char **), ldap_value_free);
291   DYNA_GET_FUNCTION(void (__cdecl *)(void *), ldap_memfree);
292   DYNA_GET_FUNCTION(void (__cdecl *)(void *, int), ber_free);
293
294   server = (*ldap_init)(conn->host.name, (int)conn->port);
295   if (server == NULL) {
296     failf(data, "LDAP local: Cannot connect to %s:%d",
297           conn->host.name, conn->port);
298     status = CURLE_COULDNT_CONNECT;
299     goto quit;
300   }
301
302   rc = (*ldap_simple_bind_s)(server,
303                              conn->bits.user_passwd ? conn->user : NULL,
304                              conn->bits.user_passwd ? conn->passwd : NULL);
305   if (rc != 0) {
306      failf(data, "LDAP local: %s", (*ldap_err2string)(rc));
307      status = CURLE_LDAP_CANNOT_BIND;
308      goto quit;
309   }
310
311 #ifdef WIN32
312   rc = _ldap_url_parse(conn, &ludp);
313 #else
314   rc = (*ldap_url_parse)(data->change.url, &ludp);
315 #endif
316
317   if (rc != 0) {
318      failf(data, "LDAP local: %s", (*ldap_err2string)(rc));
319      status = CURLE_LDAP_INVALID_URL;
320      goto quit;
321   }
322
323   rc = (*ldap_search_s)(server, ludp->lud_dn, ludp->lud_scope,
324                         ludp->lud_filter, ludp->lud_attrs, 0, &result);
325
326   if (rc != 0 && rc != LDAP_SIZELIMIT_EXCEEDED) {
327     failf(data, "LDAP remote: %s", (*ldap_err2string)(rc));
328     status = CURLE_LDAP_SEARCH_FAILED;
329     goto quit;
330   }
331
332   for(num = 0, entryIterator = (*ldap_first_entry)(server, result);
333       entryIterator;
334       entryIterator = (*ldap_next_entry)(server, entryIterator), num++)
335   {
336     void  *ber = NULL;      /*! is really 'BerElement **' */
337     void  *attribute;       /*! suspicious that this isn't 'const' */
338     char  *dn = (*ldap_get_dn)(server, entryIterator);
339     int i;
340
341     Curl_client_write(data, CLIENTWRITE_BODY, (char *)"DN: ", 4);
342     Curl_client_write(data, CLIENTWRITE_BODY, (char *)dn, 0);
343     Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 1);
344
345     for (attribute = (*ldap_first_attribute)(server, entryIterator, &ber);
346          attribute;
347          attribute = (*ldap_next_attribute)(server, entryIterator, ber))
348     {
349       char **vals = (*ldap_get_values)(server, entryIterator, attribute);
350
351       if (vals != NULL)
352       {
353         for (i = 0; (vals[i] != NULL); i++)
354         {
355           Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\t", 1);
356           Curl_client_write(data, CLIENTWRITE_BODY, (char*) attribute, 0);
357           Curl_client_write(data, CLIENTWRITE_BODY, (char *)": ", 2);
358           Curl_client_write(data, CLIENTWRITE_BODY, vals[i], 0);
359           Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 0);
360         }
361
362         /* Free memory used to store values */
363         (*ldap_value_free)(vals);
364       }
365       Curl_client_write(data, CLIENTWRITE_BODY, (char *)"\n", 1);
366
367       (*ldap_memfree)(attribute);
368     }
369     (*ldap_memfree)(dn);
370     if (ber)
371        (*ber_free)(ber, 0);
372   }
373
374 quit:
375   LDAP_TRACE (("Received %d entries\n", num));
376   if (rc == LDAP_SIZELIMIT_EXCEEDED)
377      infof(data, "There are more than %d entries\n", num);
378   if (ludp)
379      (*ldap_free_urldesc)(ludp);
380   if (server)
381      (*ldap_unbind_s)(server);
382
383   DynaClose();
384
385   /* no data to transfer */
386   Curl_Transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
387   conn->bits.close = TRUE;
388
389   return status;
390 }
391
392 #ifdef DEBUG_LDAP
393 static void _ldap_trace (const char *fmt, ...)
394 {
395   static int do_trace = -1;
396   va_list args;
397
398   if (do_trace == -1) {
399     const char *env = getenv("CURL_TRACE");
400     do_trace = (env && atoi(env) > 0);
401   }
402   if (!do_trace)
403     return;
404
405   va_start (args, fmt);
406   vfprintf (stderr, fmt, args);
407   va_end (args);
408 }
409 #endif
410
411 #ifdef WIN32
412 /*
413  * Return scope-value for a scope-string.
414  */
415 static int str2scope (const char *p)
416 {
417   if (!stricmp(p, "one"))
418      return LDAP_SCOPE_ONELEVEL;
419   if (!stricmp(p, "onetree"))
420      return LDAP_SCOPE_ONELEVEL;
421   if (!stricmp(p, "base"))
422      return LDAP_SCOPE_BASE;
423   if (!stricmp(p, "sub"))
424      return LDAP_SCOPE_SUBTREE;
425   if (!stricmp( p, "subtree"))
426      return LDAP_SCOPE_SUBTREE;
427   return (-1);
428 }
429
430 /*
431  * Split 'str' into strings separated by commas.
432  * Note: res[] points into 'str'.
433  */
434 static char **split_str (char *str)
435 {
436   char **res, *lasts, *s;
437   int  i;
438
439   for (i = 2, s = strchr(str,','); s; i++)
440      s = strchr(++s,',');
441
442   res = calloc(i, sizeof(char*));
443   if (!res)
444     return NULL;
445
446   for (i = 0, s = strtok_r(str, ",", &lasts); s;
447        s = strtok_r(NULL, ",", &lasts), i++)
448     res[i] = s;
449   return res;
450 }
451
452 /*
453  * Unescape the LDAP-URL components
454  */
455 static bool unescape_elements (LDAPURLDesc *ludp)
456 {
457   int i;
458
459   if (ludp->lud_filter) {
460     ludp->lud_filter = curl_unescape(ludp->lud_filter, 0);
461     if (!ludp->lud_filter)
462        return (FALSE);
463   }
464
465   for (i = 0; ludp->lud_attrs && ludp->lud_attrs[i]; i++) {
466     ludp->lud_attrs[i] = curl_unescape(ludp->lud_attrs[i], 0);
467     if (!ludp->lud_attrs[i])
468        return (FALSE);
469   }
470
471   for (i = 0; ludp->lud_exts && ludp->lud_exts[i]; i++) {
472     ludp->lud_exts[i] = curl_unescape(ludp->lud_exts[i], 0);
473     if (!ludp->lud_exts[i])
474        return (FALSE);
475   }
476
477   if (ludp->lud_dn) {
478     char *dn = ludp->lud_dn;
479     char *new_dn = curl_unescape(dn, 0);
480
481     free(dn);
482     ludp->lud_dn = new_dn;
483     if (!new_dn)
484        return (FALSE);
485   }
486   return (TRUE);
487 }
488
489 /*
490  * Break apart the pieces of an LDAP URL.
491  * Syntax:
492  *   ldap://<hostname>:<port>/<base_dn>?<attributes>?<scope>?<filter>?<ext>
493  *
494  * <hostname> already known from 'conn->host.name'.
495  * <port>     already known from 'conn->remote_port'.
496  * extract the rest from 'conn->path+1'. All fields are optional. e.g.
497  *   ldap://<hostname>:<port>/?<attributes>?<scope>?<filter> yields ludp->lud_dn = "".
498  *
499  * Ref. http://developer.netscape.com/docs/manuals/dirsdk/csdk30/url.htm#2831915
500  */
501 static int _ldap_url_parse2 (const struct connectdata *conn, LDAPURLDesc *ludp)
502 {
503   char *p, *q;
504   int i;
505
506   if (!conn->path || conn->path[0] != '/' ||
507       !checkprefix(conn->protostr, conn->data->change.url))
508      return LDAP_INVALID_SYNTAX;
509
510   ludp->lud_scope = LDAP_SCOPE_BASE;
511   ludp->lud_port  = conn->remote_port;
512   ludp->lud_host  = conn->host.name;
513
514   /* parse DN (Distinguished Name).
515    */
516   ludp->lud_dn = strdup(conn->path+1);
517   if (!ludp->lud_dn)
518      return LDAP_NO_MEMORY;
519
520   p = strchr(ludp->lud_dn, '?');
521   LDAP_TRACE (("DN '%.*s'\n", p ? (size_t)(p-ludp->lud_dn) : strlen(ludp->lud_dn),
522                ludp->lud_dn));
523
524   if (!p)
525      goto success;
526
527   *p++ = '\0';
528
529   /* parse attributes. skip "??".
530    */
531   q = strchr(p, '?');
532   if (q)
533      *q++ = '\0';
534
535   if (*p && *p != '?') {
536     ludp->lud_attrs = split_str(p);
537     if (!ludp->lud_attrs)
538        return LDAP_NO_MEMORY;
539
540     for (i = 0; ludp->lud_attrs[i]; i++)
541         LDAP_TRACE (("attr[%d] '%s'\n", i, ludp->lud_attrs[i]));
542   }
543
544   p = q;
545   if (!p)
546      goto success;
547
548   /* parse scope. skip "??"
549    */
550   q = strchr(p, '?');
551   if (q)
552      *q++ = '\0';
553
554   if (*p && *p != '?') {
555     ludp->lud_scope = str2scope(p);
556     if (ludp->lud_scope == -1)
557        return LDAP_INVALID_SYNTAX;
558     LDAP_TRACE (("scope %d\n", ludp->lud_scope));
559   }
560
561   p = q;
562   if (!p)
563      goto success;
564
565   /* parse filter
566    */
567   q = strchr(p, '?');
568   if (q)
569      *q++ = '\0';
570   if (!*p)
571      return LDAP_INVALID_SYNTAX;
572
573   ludp->lud_filter = p;
574   LDAP_TRACE (("filter '%s'\n", ludp->lud_filter));
575
576   p = q;
577   if (!p)
578      goto success;
579
580   /* parse extensions
581    */
582   ludp->lud_exts = split_str(p);
583   if (!ludp->lud_exts)
584      return LDAP_NO_MEMORY;
585
586   for (i = 0; ludp->lud_exts[i]; i++)
587       LDAP_TRACE (("exts[%d] '%s'\n", i, ludp->lud_exts[i]));
588
589 success:
590   if (!unescape_elements(ludp))
591      return LDAP_NO_MEMORY;
592   return LDAP_SUCCESS;
593 }
594
595 static int _ldap_url_parse (const struct connectdata *conn,
596                             LDAPURLDesc **ludpp)
597 {
598   LDAPURLDesc *ludp = calloc(sizeof(*ludp), 1);
599   int rc;
600
601   *ludpp = NULL;
602   if (!ludp)
603      return LDAP_NO_MEMORY;
604
605   rc = _ldap_url_parse2 (conn, ludp);
606   if (rc != LDAP_SUCCESS) {
607     _ldap_free_urldesc(ludp);
608     ludp = NULL;
609   }
610   *ludpp = ludp;
611   return (rc);
612 }
613
614 static void _ldap_free_urldesc (LDAPURLDesc *ludp)
615 {
616   int i;
617
618   if (!ludp)
619      return;
620
621   if (ludp->lud_dn)
622      free(ludp->lud_dn);
623
624   if (ludp->lud_filter)
625      free(ludp->lud_filter);
626
627   if (ludp->lud_attrs) {
628     for (i = 0; ludp->lud_attrs[i]; i++)
629        free(ludp->lud_attrs[i]);
630     free(ludp->lud_attrs);
631   }
632
633   if (ludp->lud_exts) {
634     for (i = 0; ludp->lud_exts[i]; i++)
635        free(ludp->lud_exts[i]);
636     free(ludp->lud_exts);
637   }
638   free (ludp);
639 }
640 #endif  /* WIN32 */
641 #endif  /* CURL_DISABLE_LDAP */