]> granicus.if.org Git - apache/blob - modules/ldap/util_ldap.c
Clean up some compiler warnings
[apache] / modules / ldap / util_ldap.c
1 /* Copyright 2001-2004 The Apache Software Foundation
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 /*
17  * util_ldap.c: LDAP things
18  * 
19  * Original code from auth_ldap module for Apache v1.3:
20  * Copyright 1998, 1999 Enbridge Pipelines Inc. 
21  * Copyright 1999-2001 Dave Carrigan
22  */
23
24 #include <apr_ldap.h>
25 #include <apr_strings.h>
26
27 #include "ap_config.h"
28 #include "httpd.h"
29 #include "http_config.h"
30 #include "http_core.h"
31 #include "http_log.h"
32 #include "http_protocol.h"
33 #include "http_request.h"
34 #include "util_ldap.h"
35 #include "util_ldap_cache.h"
36
37 #if APR_HAVE_UNISTD_H
38 #include <unistd.h>
39 #endif
40
41 #if !APR_HAS_LDAP
42 #error mod_ldap requires APR-util to have LDAP support built in
43 #endif
44
45     /* defines for certificate file types
46     */
47 #define LDAP_CA_TYPE_UNKNOWN            0
48 #define LDAP_CA_TYPE_DER                1
49 #define LDAP_CA_TYPE_BASE64             2
50 #define LDAP_CA_TYPE_CERT7_DB           3
51
52
53 module AP_MODULE_DECLARE_DATA ldap_module;
54
55 int util_ldap_handler(request_rec *r);
56 void *util_ldap_create_config(apr_pool_t *p, server_rec *s);
57
58
59 /*
60  * Some definitions to help between various versions of apache.
61  */
62
63 #ifndef DOCTYPE_HTML_2_0
64 #define DOCTYPE_HTML_2_0  "<!DOCTYPE HTML PUBLIC \"-//IETF//" \
65                           "DTD HTML 2.0//EN\">\n"
66 #endif
67
68 #ifndef DOCTYPE_HTML_3_2
69 #define DOCTYPE_HTML_3_2  "<!DOCTYPE HTML PUBLIC \"-//W3C//" \
70                           "DTD HTML 3.2 Final//EN\">\n"
71 #endif
72
73 #ifndef DOCTYPE_HTML_4_0S
74 #define DOCTYPE_HTML_4_0S "<!DOCTYPE HTML PUBLIC \"-//W3C//" \
75                           "DTD HTML 4.0//EN\"\n" \
76                           "\"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
77 #endif
78
79 #ifndef DOCTYPE_HTML_4_0T
80 #define DOCTYPE_HTML_4_0T "<!DOCTYPE HTML PUBLIC \"-//W3C//" \
81                           "DTD HTML 4.0 Transitional//EN\"\n" \
82                           "\"http://www.w3.org/TR/REC-html40/loose.dtd\">\n"
83 #endif
84
85 #ifndef DOCTYPE_HTML_4_0F
86 #define DOCTYPE_HTML_4_0F "<!DOCTYPE HTML PUBLIC \"-//W3C//" \
87                           "DTD HTML 4.0 Frameset//EN\"\n" \
88                           "\"http://www.w3.org/TR/REC-html40/frameset.dtd\">\n"
89 #endif
90
91 #define LDAP_CACHE_LOCK() \
92     apr_global_mutex_lock(st->util_ldap_cache_lock)
93 #define LDAP_CACHE_UNLOCK() \
94     apr_global_mutex_unlock(st->util_ldap_cache_lock)
95
96
97 static void util_ldap_strdup (char **str, const char *newstr)
98 {
99     if (*str) {
100         free(*str);
101         *str = NULL;
102     }
103
104     if (newstr) {
105         *str = calloc(1, strlen(newstr)+1);
106         strcpy (*str, newstr);
107     }
108 }
109
110 /*
111  * Status Handler
112  * --------------
113  *
114  * This handler generates a status page about the current performance of
115  * the LDAP cache. It is enabled as follows:
116  *
117  * <Location /ldap-status>
118  *   SetHandler ldap-status
119  * </Location>
120  *
121  */
122 int util_ldap_handler(request_rec *r)
123 {
124     util_ldap_state_t *st = (util_ldap_state_t *)ap_get_module_config(r->server->module_config, &ldap_module);
125
126     r->allowed |= (1 << M_GET);
127     if (r->method_number != M_GET)
128         return DECLINED;
129
130     if (strcmp(r->handler, "ldap-status")) {
131         return DECLINED;
132     }
133
134     r->content_type = "text/html";
135     if (r->header_only)
136         return OK;
137
138     ap_rputs(DOCTYPE_HTML_3_2
139              "<html><head><title>LDAP Cache Information</title></head>\n", r);
140     ap_rputs("<body bgcolor='#ffffff'><h1 align=center>LDAP Cache Information</h1>\n", r);
141
142     util_ald_cache_display(r, st);
143
144     return OK;
145 }
146
147 /* ------------------------------------------------------------------ */
148
149
150 /*
151  * Closes an LDAP connection by unlocking it. The next time
152  * util_ldap_connection_find() is called this connection will be
153  * available for reuse.
154  */
155 LDAP_DECLARE(void) util_ldap_connection_close(util_ldap_connection_t *ldc)
156 {
157
158     /*
159      * QUESTION:
160      *
161      * Is it safe leaving bound connections floating around between the
162      * different modules? Keeping the user bound is a performance boost,
163      * but it is also a potential security problem - maybe.
164      *
165      * For now we unbind the user when we finish with a connection, but
166      * we don't have to...
167      */
168
169     /* mark our connection as available for reuse */
170
171 #if APR_HAS_THREADS
172     apr_thread_mutex_unlock(ldc->lock);
173 #endif
174 }
175
176
177 /*
178  * Destroys an LDAP connection by unbinding and closing the connection to
179  * the LDAP server. It is used to bring the connection back to a known
180  * state after an error, and during pool cleanup.
181  */
182 LDAP_DECLARE_NONSTD(apr_status_t) util_ldap_connection_unbind(void *param)
183 {
184     util_ldap_connection_t *ldc = param;
185
186     if (ldc) {
187         if (ldc->ldap) {
188             ldap_unbind_s(ldc->ldap);
189             ldc->ldap = NULL;
190         }
191         ldc->bound = 0;
192     }
193
194     return APR_SUCCESS;
195 }
196
197
198 /*
199  * Clean up an LDAP connection by unbinding and unlocking the connection.
200  * This function is registered with the pool cleanup function - causing
201  * the LDAP connections to be shut down cleanly on graceful restart.
202  */
203 LDAP_DECLARE_NONSTD(apr_status_t) util_ldap_connection_cleanup(void *param)
204 {
205     util_ldap_connection_t *ldc = param;
206
207     if (ldc) {
208
209         /* unbind and disconnect from the LDAP server */
210         util_ldap_connection_unbind(ldc);
211
212         /* free the username and password */
213         if (ldc->bindpw) {
214             free((void*)ldc->bindpw);
215         }
216         if (ldc->binddn) {
217             free((void*)ldc->binddn);
218         }
219
220         /* unlock this entry */
221         util_ldap_connection_close(ldc);
222     
223     }
224
225     return APR_SUCCESS;
226 }
227
228
229 /*
230  * Connect to the LDAP server and binds. Does not connect if already
231  * connected (i.e. ldc->ldap is non-NULL.) Does not bind if already bound.
232  *
233  * Returns LDAP_SUCCESS on success; and an error code on failure
234  */
235 LDAP_DECLARE(int) util_ldap_connection_open(request_rec *r, 
236                                             util_ldap_connection_t *ldc)
237 {
238     int result = 0;
239     int failures = 0;
240     int version  = LDAP_VERSION3;
241
242     /* If the connection is already bound, return
243     */
244     if (ldc->bound)
245     {
246         ldc->reason = "LDAP: connection open successful (already bound)";
247         return LDAP_SUCCESS;
248     }
249
250     /* create the ldap session handle
251     */
252     if (NULL == ldc->ldap)
253     {
254         apr_ldap_err_t *result = NULL;
255
256         apr_ldap_init(r->pool, &(ldc->ldap), ldc->host, ldc->port,
257                       ldc->secure, &(result));
258
259         if (result != NULL) {
260             ldc->reason = result->reason;
261         }
262
263         if (NULL == ldc->ldap)
264         {
265             ldc->bound = 0;
266             if (NULL == ldc->reason)
267                 ldc->reason = "LDAP: ldap initialization failed";
268             return(-1);
269         }
270
271         /* Set the alias dereferencing option */
272         ldap_set_option(ldc->ldap, LDAP_OPT_DEREF, &(ldc->deref));
273
274         /* always default to LDAP V3 */
275         ldap_set_option(ldc->ldap, LDAP_OPT_PROTOCOL_VERSION, &version);
276
277     }
278
279
280     /* loop trying to bind up to 10 times if LDAP_SERVER_DOWN error is
281      * returned.  Break out of the loop on Success or any other error.
282      *
283      * NOTE: Looping is probably not a great idea. If the server isn't 
284      * responding the chances it will respond after a few tries are poor.
285      * However, the original code looped and it only happens on
286      * the error condition.
287       */
288     for (failures=0; failures<10; failures++)
289     {
290         result = ldap_simple_bind_s(ldc->ldap, ldc->binddn, ldc->bindpw);
291         if (LDAP_SERVER_DOWN != result)
292             break;
293     }
294
295     /* free the handle if there was an error
296     */
297     if (LDAP_SUCCESS != result)
298     {
299         ldap_unbind_s(ldc->ldap);
300         ldc->ldap = NULL;
301         ldc->bound = 0;
302         ldc->reason = "LDAP: ldap_simple_bind_s() failed";
303     }
304     else {
305         ldc->bound = 1;
306         ldc->reason = "LDAP: connection open successful";
307     }
308
309     return(result);
310 }
311
312
313 /*
314  * Find an existing ldap connection struct that matches the
315  * provided ldap connection parameters.
316  *
317  * If not found in the cache, a new ldc structure will be allocated from st->pool
318  * and returned to the caller. If found in the cache, a pointer to the existing
319  * ldc structure will be returned.
320  */
321 LDAP_DECLARE(util_ldap_connection_t *)util_ldap_connection_find(request_rec *r, const char *host, int port,
322                                               const char *binddn, const char *bindpw, deref_options deref,
323                                               int secure )
324 {
325     struct util_ldap_connection_t *l, *p;       /* To traverse the linked list */
326
327     util_ldap_state_t *st = 
328         (util_ldap_state_t *)ap_get_module_config(r->server->module_config,
329         &ldap_module);
330
331
332 #if APR_HAS_THREADS
333     /* mutex lock this function */
334     if (!st->mutex) {
335         apr_thread_mutex_create(&st->mutex, APR_THREAD_MUTEX_DEFAULT, st->pool);
336     }
337     apr_thread_mutex_lock(st->mutex);
338 #endif
339
340     /* Search for an exact connection match in the list that is not
341      * being used.
342      */
343     for (l=st->connections,p=NULL; l; l=l->next) {
344 #if APR_HAS_THREADS
345         if (APR_SUCCESS == apr_thread_mutex_trylock(l->lock)) {
346 #endif
347         if ((l->port == port) && (strcmp(l->host, host) == 0) && 
348             ((!l->binddn && !binddn) || (l->binddn && binddn && !strcmp(l->binddn, binddn))) && 
349             ((!l->bindpw && !bindpw) || (l->bindpw && bindpw && !strcmp(l->bindpw, bindpw))) && 
350             (l->deref == deref) && (l->secure == secure)) {
351
352             break;
353         }
354 #if APR_HAS_THREADS
355             /* If this connection didn't match the criteria, then we
356              * need to unlock the mutex so it is available to be reused.
357              */
358             apr_thread_mutex_unlock(l->lock);
359         }
360 #endif
361         p = l;
362     }
363
364     /* If nothing found, search again, but we don't care about the
365      * binddn and bindpw this time.
366      */
367     if (!l) {
368         for (l=st->connections,p=NULL; l; l=l->next) {
369 #if APR_HAS_THREADS
370             if (APR_SUCCESS == apr_thread_mutex_trylock(l->lock)) {
371
372 #endif
373             if ((l->port == port) && (strcmp(l->host, host) == 0) && 
374                 (l->deref == deref) && (l->secure == secure)) {
375
376                 /* the bind credentials have changed */
377                 l->bound = 0;
378                 util_ldap_strdup((char**)&(l->binddn), binddn);
379                 util_ldap_strdup((char**)&(l->bindpw), bindpw);
380                 break;
381             }
382 #if APR_HAS_THREADS
383                 /* If this connection didn't match the criteria, then we
384                  * need to unlock the mutex so it is available to be reused.
385                  */
386                 apr_thread_mutex_unlock(l->lock);
387             }
388 #endif
389             p = l;
390         }
391     }
392
393 /* artificially disable cache */
394 /* l = NULL; */
395
396     /* If no connection what found after the second search, we
397      * must create one.
398      */
399     if (!l) {
400
401         /* 
402          * Add the new connection entry to the linked list. Note that we
403          * don't actually establish an LDAP connection yet; that happens
404          * the first time authentication is requested.
405          */
406         /* create the details to the pool in st */
407         l = apr_pcalloc(st->pool, sizeof(util_ldap_connection_t));
408 #if APR_HAS_THREADS
409         apr_thread_mutex_create(&l->lock, APR_THREAD_MUTEX_DEFAULT, st->pool);
410         apr_thread_mutex_lock(l->lock);
411 #endif
412         l->pool = st->pool;
413         l->bound = 0;
414         l->host = apr_pstrdup(st->pool, host);
415         l->port = port;
416         l->deref = deref;
417         util_ldap_strdup((char**)&(l->binddn), binddn);
418         util_ldap_strdup((char**)&(l->bindpw), bindpw);
419         l->secure = secure;
420
421         /* add the cleanup to the pool */
422         apr_pool_cleanup_register(l->pool, l,
423                                   util_ldap_connection_cleanup,
424                                   apr_pool_cleanup_null);
425
426         if (p) {
427             p->next = l;
428         }
429         else {
430             st->connections = l;
431         }
432     }
433
434 #if APR_HAS_THREADS
435     apr_thread_mutex_unlock(st->mutex);
436 #endif
437     return l;
438 }
439
440 /* ------------------------------------------------------------------ */
441
442 /*
443  * Compares two DNs to see if they're equal. The only way to do this correctly is to 
444  * search for the dn and then do ldap_get_dn() on the result. This should match the 
445  * initial dn, since it would have been also retrieved with ldap_get_dn(). This is
446  * expensive, so if the configuration value compare_dn_on_server is
447  * false, just does an ordinary strcmp.
448  *
449  * The lock for the ldap cache should already be acquired.
450  */
451 LDAP_DECLARE(int) util_ldap_cache_comparedn(request_rec *r, util_ldap_connection_t *ldc, 
452                             const char *url, const char *dn, const char *reqdn, 
453                             int compare_dn_on_server)
454 {
455     int result = 0;
456     util_url_node_t *curl; 
457     util_url_node_t curnode;
458     util_dn_compare_node_t *node;
459     util_dn_compare_node_t newnode;
460     int failures = 0;
461     LDAPMessage *res, *entry;
462     char *searchdn;
463
464     util_ldap_state_t *st =  (util_ldap_state_t *)ap_get_module_config(r->server->module_config, &ldap_module);
465
466     /* get cache entry (or create one) */
467     LDAP_CACHE_LOCK();
468
469     curnode.url = url;
470     curl = util_ald_cache_fetch(st->util_ldap_cache, &curnode);
471     if (curl == NULL) {
472         curl = util_ald_create_caches(st, url);
473     }
474     LDAP_CACHE_UNLOCK();
475
476     /* a simple compare? */
477     if (!compare_dn_on_server) {
478         /* unlock this read lock */
479         if (strcmp(dn, reqdn)) {
480             ldc->reason = "DN Comparison FALSE (direct strcmp())";
481             return LDAP_COMPARE_FALSE;
482         }
483         else {
484             ldc->reason = "DN Comparison TRUE (direct strcmp())";
485             return LDAP_COMPARE_TRUE;
486         }
487     }
488
489     if (curl) {
490         /* no - it's a server side compare */
491         LDAP_CACHE_LOCK();
492     
493         /* is it in the compare cache? */
494         newnode.reqdn = (char *)reqdn;
495         node = util_ald_cache_fetch(curl->dn_compare_cache, &newnode);
496         if (node != NULL) {
497             /* If it's in the cache, it's good */
498             /* unlock this read lock */
499             LDAP_CACHE_UNLOCK();
500             ldc->reason = "DN Comparison TRUE (cached)";
501             return LDAP_COMPARE_TRUE;
502         }
503     
504         /* unlock this read lock */
505         LDAP_CACHE_UNLOCK();
506     }
507
508 start_over:
509     if (failures++ > 10) {
510         /* too many failures */
511         return result;
512     }
513
514     /* make a server connection */
515     if (LDAP_SUCCESS != (result = util_ldap_connection_open(r, ldc))) {
516         /* connect to server failed */
517         return result;
518     }
519
520     /* search for reqdn */
521     if ((result = ldap_search_ext_s(ldc->ldap, reqdn, LDAP_SCOPE_BASE, 
522                                     "(objectclass=*)", NULL, 1, 
523                                     NULL, NULL, NULL, -1, &res)) == LDAP_SERVER_DOWN) {
524         ldc->reason = "DN Comparison ldap_search_ext_s() failed with server down";
525         util_ldap_connection_unbind(ldc);
526         goto start_over;
527     }
528     if (result != LDAP_SUCCESS) {
529         /* search for reqdn failed - no match */
530         ldc->reason = "DN Comparison ldap_search_ext_s() failed";
531         return result;
532     }
533
534     entry = ldap_first_entry(ldc->ldap, res);
535     searchdn = ldap_get_dn(ldc->ldap, entry);
536
537     ldap_msgfree(res);
538     if (strcmp(dn, searchdn) != 0) {
539         /* compare unsuccessful */
540         ldc->reason = "DN Comparison FALSE (checked on server)";
541         result = LDAP_COMPARE_FALSE;
542     }
543     else {
544         if (curl) {
545             /* compare successful - add to the compare cache */
546             LDAP_CACHE_LOCK();
547             newnode.reqdn = (char *)reqdn;
548             newnode.dn = (char *)dn;
549             
550             node = util_ald_cache_fetch(curl->dn_compare_cache, &newnode);
551             if ((node == NULL) || 
552                 (strcmp(reqdn, node->reqdn) != 0) || (strcmp(dn, node->dn) != 0)) {
553
554                 util_ald_cache_insert(curl->dn_compare_cache, &newnode);
555             }
556             LDAP_CACHE_UNLOCK();
557         }
558         ldc->reason = "DN Comparison TRUE (checked on server)";
559         result = LDAP_COMPARE_TRUE;
560     }
561     ldap_memfree(searchdn);
562     return result;
563
564 }
565
566 /*
567  * Does an generic ldap_compare operation. It accepts a cache that it will use
568  * to lookup the compare in the cache. We cache two kinds of compares 
569  * (require group compares) and (require user compares). Each compare has a different
570  * cache node: require group includes the DN; require user does not because the
571  * require user cache is owned by the 
572  *
573  */
574 LDAP_DECLARE(int) util_ldap_cache_compare(request_rec *r, util_ldap_connection_t *ldc,
575                           const char *url, const char *dn,
576                           const char *attrib, const char *value)
577 {
578     int result = 0;
579     util_url_node_t *curl; 
580     util_url_node_t curnode;
581     util_compare_node_t *compare_nodep;
582     util_compare_node_t the_compare_node;
583     apr_time_t curtime = 0; /* silence gcc -Wall */
584     int failures = 0;
585
586     util_ldap_state_t *st = 
587         (util_ldap_state_t *)ap_get_module_config(r->server->module_config,
588         &ldap_module);
589
590     /* get cache entry (or create one) */
591     LDAP_CACHE_LOCK();
592     curnode.url = url;
593     curl = util_ald_cache_fetch(st->util_ldap_cache, &curnode);
594     if (curl == NULL) {
595         curl = util_ald_create_caches(st, url);
596     }
597     LDAP_CACHE_UNLOCK();
598
599     if (curl) {
600         /* make a comparison to the cache */
601         LDAP_CACHE_LOCK();
602         curtime = apr_time_now();
603     
604         the_compare_node.dn = (char *)dn;
605         the_compare_node.attrib = (char *)attrib;
606         the_compare_node.value = (char *)value;
607         the_compare_node.result = 0;
608     
609         compare_nodep = util_ald_cache_fetch(curl->compare_cache, &the_compare_node);
610     
611         if (compare_nodep != NULL) {
612             /* found it... */
613             if (curtime - compare_nodep->lastcompare > st->compare_cache_ttl) {
614                 /* ...but it is too old */
615                 util_ald_cache_remove(curl->compare_cache, compare_nodep);
616             }
617             else {
618                 /* ...and it is good */
619                 /* unlock this read lock */
620                 LDAP_CACHE_UNLOCK();
621                 if (LDAP_COMPARE_TRUE == compare_nodep->result) {
622                     ldc->reason = "Comparison true (cached)";
623                     return compare_nodep->result;
624                 }
625                 else if (LDAP_COMPARE_FALSE == compare_nodep->result) {
626                     ldc->reason = "Comparison false (cached)";
627                     return compare_nodep->result;
628                 }
629                 else if (LDAP_NO_SUCH_ATTRIBUTE == compare_nodep->result) {
630                     ldc->reason = "Comparison no such attribute (cached)";
631                     return compare_nodep->result;
632                 }
633                 else {
634                     ldc->reason = "Comparison undefined (cached)";
635                     return compare_nodep->result;
636                 }
637             }
638         }
639         /* unlock this read lock */
640         LDAP_CACHE_UNLOCK();
641     }
642
643 start_over:
644     if (failures++ > 10) {
645         /* too many failures */
646         return result;
647     }
648     if (LDAP_SUCCESS != (result = util_ldap_connection_open(r, ldc))) {
649         /* connect failed */
650         return result;
651     }
652
653     if ((result = ldap_compare_s(ldc->ldap, dn, attrib, value))
654         == LDAP_SERVER_DOWN) { 
655         /* connection failed - try again */
656         ldc->reason = "ldap_compare_s() failed with server down";
657         util_ldap_connection_unbind(ldc);
658         goto start_over;
659     }
660
661     ldc->reason = "Comparison complete";
662     if ((LDAP_COMPARE_TRUE == result) || 
663         (LDAP_COMPARE_FALSE == result) ||
664         (LDAP_NO_SUCH_ATTRIBUTE == result)) {
665         if (curl) {
666             /* compare completed; caching result */
667             LDAP_CACHE_LOCK();
668             the_compare_node.lastcompare = curtime;
669             the_compare_node.result = result;
670
671             /* If the node doesn't exist then insert it, otherwise just update it with
672                the last results */
673             compare_nodep = util_ald_cache_fetch(curl->compare_cache, &the_compare_node);
674             if ((compare_nodep == NULL) || 
675                 (strcmp(the_compare_node.dn, compare_nodep->dn) != 0) || 
676                 (strcmp(the_compare_node.attrib, compare_nodep->attrib) != 0) || 
677                 (strcmp(the_compare_node.value, compare_nodep->value) != 0)) {
678
679                 util_ald_cache_insert(curl->compare_cache, &the_compare_node);
680             }
681             else {
682                 compare_nodep->lastcompare = curtime;
683                 compare_nodep->result = result;
684             }
685             LDAP_CACHE_UNLOCK();
686         }
687         if (LDAP_COMPARE_TRUE == result) {
688             ldc->reason = "Comparison true (adding to cache)";
689             return LDAP_COMPARE_TRUE;
690         }
691         else if (LDAP_COMPARE_FALSE == result) {
692             ldc->reason = "Comparison false (adding to cache)";
693             return LDAP_COMPARE_FALSE;
694         }
695         else {
696             ldc->reason = "Comparison no such attribute (adding to cache)";
697             return LDAP_NO_SUCH_ATTRIBUTE;
698         }
699     }
700     return result;
701 }
702
703 LDAP_DECLARE(int) util_ldap_cache_checkuserid(request_rec *r, util_ldap_connection_t *ldc,
704                               const char *url, const char *basedn, int scope, char **attrs,
705                               const char *filter, const char *bindpw, const char **binddn,
706                               const char ***retvals)
707 {
708     const char **vals = NULL;
709     int result = 0;
710     LDAPMessage *res, *entry;
711     char *dn;
712     int count;
713     int failures = 0;
714     util_url_node_t *curl;              /* Cached URL node */
715     util_url_node_t curnode;
716     util_search_node_t *search_nodep;   /* Cached search node */
717     util_search_node_t the_search_node;
718     apr_time_t curtime;
719
720     util_ldap_state_t *st = 
721         (util_ldap_state_t *)ap_get_module_config(r->server->module_config,
722         &ldap_module);
723
724     /* Get the cache node for this url */
725     LDAP_CACHE_LOCK();
726     curnode.url = url;
727     curl = (util_url_node_t *)util_ald_cache_fetch(st->util_ldap_cache, &curnode);
728     if (curl == NULL) {
729         curl = util_ald_create_caches(st, url);
730     }
731     LDAP_CACHE_UNLOCK();
732
733     if (curl) {
734         LDAP_CACHE_LOCK();
735         the_search_node.username = filter;
736         search_nodep = util_ald_cache_fetch(curl->search_cache, &the_search_node);
737         if (search_nodep != NULL && search_nodep->bindpw) {
738     
739             /* found entry in search cache... */
740             curtime = apr_time_now();
741     
742             /*
743              * Remove this item from the cache if its expired, or if the 
744              * sent password doesn't match the storepassword.
745              */
746             if ((curtime - search_nodep->lastbind) > st->search_cache_ttl) {
747                 /* ...but entry is too old */
748                 util_ald_cache_remove(curl->search_cache, search_nodep);
749             }
750             else if (strcmp(search_nodep->bindpw, bindpw) != 0) {
751             /* ...but cached password doesn't match sent password */
752                 util_ald_cache_remove(curl->search_cache, search_nodep);
753             }
754             else {
755                 /* ...and entry is valid */
756                 *binddn = search_nodep->dn;
757                 *retvals = search_nodep->vals;
758                 LDAP_CACHE_UNLOCK();
759                 ldc->reason = "Authentication successful (cached)";
760                 return LDAP_SUCCESS;
761             }
762         }
763         /* unlock this read lock */
764         LDAP_CACHE_UNLOCK();
765     }
766
767     /*  
768      * At this point, there is no valid cached search, so lets do the search.
769      */
770
771     /*
772      * If any LDAP operation fails due to LDAP_SERVER_DOWN, control returns here.
773      */
774 start_over:
775     if (failures++ > 10) {
776         return result;
777     }
778     if (LDAP_SUCCESS != (result = util_ldap_connection_open(r, ldc))) {
779         return result;
780     }
781
782     /* try do the search */
783     if ((result = ldap_search_ext_s(ldc->ldap,
784                                     basedn, scope, 
785                                     filter, attrs, 0, 
786                                     NULL, NULL, NULL, -1, &res)) == LDAP_SERVER_DOWN) {
787         ldc->reason = "ldap_search_ext_s() for user failed with server down";
788         util_ldap_connection_unbind(ldc);
789         goto start_over;
790     }
791
792     /* if there is an error (including LDAP_NO_SUCH_OBJECT) return now */
793     if (result != LDAP_SUCCESS) {
794         ldc->reason = "ldap_search_ext_s() for user failed";
795         return result;
796     }
797
798     /* 
799      * We should have found exactly one entry; to find a different
800      * number is an error.
801      */
802     count = ldap_count_entries(ldc->ldap, res);
803     if (count != 1) 
804     {
805         if (count == 0 )
806             ldc->reason = "User not found";
807         else
808             ldc->reason = "User is not unique (search found two or more matches)";
809         ldap_msgfree(res);
810         return LDAP_NO_SUCH_OBJECT;
811     }
812
813     entry = ldap_first_entry(ldc->ldap, res);
814
815     /* Grab the dn, copy it into the pool, and free it again */
816     dn = ldap_get_dn(ldc->ldap, entry);
817     *binddn = apr_pstrdup(r->pool, dn);
818     ldap_memfree(dn);
819
820     /* 
821      * A bind to the server with an empty password always succeeds, so
822      * we check to ensure that the password is not empty. This implies
823      * that users who actually do have empty passwords will never be
824      * able to authenticate with this module. I don't see this as a big
825      * problem.
826      */
827     if (strlen(bindpw) <= 0) {
828         ldap_msgfree(res);
829         ldc->reason = "Empty password not allowed";
830         return LDAP_INVALID_CREDENTIALS;
831     }
832
833     /* 
834      * Attempt to bind with the retrieved dn and the password. If the bind
835      * fails, it means that the password is wrong (the dn obviously
836      * exists, since we just retrieved it)
837      */
838     if ((result = 
839          ldap_simple_bind_s(ldc->ldap, *binddn, bindpw)) == 
840          LDAP_SERVER_DOWN) {
841         ldc->reason = "ldap_simple_bind_s() to check user credentials failed with server down";
842         ldap_msgfree(res);
843         util_ldap_connection_unbind(ldc);
844         goto start_over;
845     }
846
847     /* failure? if so - return */
848     if (result != LDAP_SUCCESS) {
849         ldc->reason = "ldap_simple_bind_s() to check user credentials failed";
850         ldap_msgfree(res);
851         util_ldap_connection_unbind(ldc);
852         return result;
853     }
854     else {
855         /*
856          * We have just bound the connection to a different user and password
857          * combination, which might be reused unintentionally next time this
858          * connection is used from the connection pool. To ensure no confusion,
859          * we mark the connection as unbound.
860          */
861         ldc->bound = 0;
862     }
863
864     /*
865      * Get values for the provided attributes.
866      */
867     if (attrs) {
868         int k = 0;
869         int i = 0;
870         while (attrs[k++]);
871         vals = apr_pcalloc(r->pool, sizeof(char *) * (k+1));
872         while (attrs[i]) {
873             char **values;
874             int j = 0;
875             char *str = NULL;
876             /* get values */
877             values = ldap_get_values(ldc->ldap, entry, attrs[i]);
878             while (values && values[j]) {
879                 str = str ? apr_pstrcat(r->pool, str, "; ", values[j], NULL) : apr_pstrdup(r->pool, values[j]);
880                 j++;
881             }
882             ldap_value_free(values);
883             vals[i] = str;
884             i++;
885         }
886         *retvals = vals;
887     }
888
889     /*          
890      * Add the new username to the search cache.
891      */
892     if (curl) {
893         LDAP_CACHE_LOCK();
894         the_search_node.username = filter;
895         the_search_node.dn = *binddn;
896         the_search_node.bindpw = bindpw;
897         the_search_node.lastbind = apr_time_now();
898         the_search_node.vals = vals;
899
900         /* Search again to make sure that another thread didn't ready insert this node
901            into the cache before we got here. If it does exist then update the lastbind */
902         search_nodep = util_ald_cache_fetch(curl->search_cache, &the_search_node);
903         if ((search_nodep == NULL) || 
904             (strcmp(*binddn, search_nodep->dn) != 0) || (strcmp(bindpw, search_nodep->bindpw) != 0)) {
905
906             util_ald_cache_insert(curl->search_cache, &the_search_node);
907         }
908         else {
909             search_nodep->lastbind = the_search_node.lastbind;
910         }
911         LDAP_CACHE_UNLOCK();
912     }
913     ldap_msgfree(res);
914
915     ldc->reason = "Authentication successful";
916     return LDAP_SUCCESS;
917 }
918
919
920 /*
921  * Reports if ssl support is enabled 
922  *
923  * 1 = enabled, 0 = not enabled
924  */
925 LDAP_DECLARE(int) util_ldap_ssl_supported(request_rec *r)
926 {
927    util_ldap_state_t *st = (util_ldap_state_t *)ap_get_module_config(
928                                 r->server->module_config, &ldap_module);
929
930    return(st->ssl_support);
931 }
932
933
934 /* ---------------------------------------- */
935 /* config directives */
936
937
938 static const char *util_ldap_set_cache_bytes(cmd_parms *cmd, void *dummy, const char *bytes)
939 {
940     util_ldap_state_t *st = 
941         (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config, 
942                                                   &ldap_module);
943
944     st->cache_bytes = atol(bytes);
945
946     ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, cmd->server, 
947                  "[%" APR_PID_T_FMT "] ldap cache: Setting shared memory "
948                  " cache size to %" APR_SIZE_T_FMT " bytes.", 
949                  getpid(), st->cache_bytes);
950
951     return NULL;
952 }
953
954 static const char *util_ldap_set_cache_file(cmd_parms *cmd, void *dummy, const char *file)
955 {
956     util_ldap_state_t *st = 
957         (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config, 
958                                                   &ldap_module);
959
960     if (file) {
961         st->cache_file = ap_server_root_relative(st->pool, file);
962     }
963     else {
964         st->cache_file = NULL;
965     }
966
967     ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, cmd->server, 
968                  "LDAP cache: Setting shared memory cache file to %s bytes.", 
969                  st->cache_file);
970
971     return NULL;
972 }
973
974 static const char *util_ldap_set_cache_ttl(cmd_parms *cmd, void *dummy, const char *ttl)
975 {
976     util_ldap_state_t *st = 
977         (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config, 
978                                                   &ldap_module);
979
980     st->search_cache_ttl = atol(ttl) * 1000000;
981
982     ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, cmd->server, 
983                       "[%d] ldap cache: Setting cache TTL to %ld microseconds.", 
984                       getpid(), st->search_cache_ttl);
985
986     return NULL;
987 }
988
989 static const char *util_ldap_set_cache_entries(cmd_parms *cmd, void *dummy, const char *size)
990 {
991     util_ldap_state_t *st = 
992         (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config, 
993                                                   &ldap_module);
994
995
996     st->search_cache_size = atol(size);
997     if (st->search_cache_size < 0) {
998         st->search_cache_size = 0;
999     }
1000
1001     ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, cmd->server, 
1002                       "[%d] ldap cache: Setting search cache size to %ld entries.", 
1003                       getpid(), st->search_cache_size);
1004
1005     return NULL;
1006 }
1007
1008 static const char *util_ldap_set_opcache_ttl(cmd_parms *cmd, void *dummy, const char *ttl)
1009 {
1010     util_ldap_state_t *st = 
1011         (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config, 
1012                                                   &ldap_module);
1013
1014     st->compare_cache_ttl = atol(ttl) * 1000000;
1015
1016     ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, cmd->server, 
1017                       "[%d] ldap cache: Setting operation cache TTL to %ld microseconds.", 
1018                       getpid(), st->compare_cache_ttl);
1019
1020     return NULL;
1021 }
1022
1023 static const char *util_ldap_set_opcache_entries(cmd_parms *cmd, void *dummy, const char *size)
1024 {
1025     util_ldap_state_t *st = 
1026         (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config, 
1027                                                   &ldap_module);
1028
1029     st->compare_cache_size = atol(size);
1030     if (st->compare_cache_size < 0) {
1031         st->compare_cache_size = 0;
1032     }
1033
1034     ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, cmd->server, 
1035                       "[%d] ldap cache: Setting operation cache size to %ld entries.", 
1036                       getpid(), st->compare_cache_size);
1037
1038     return NULL;
1039 }
1040
1041 static const char *util_ldap_set_cert_auth(cmd_parms *cmd, void *dummy, const char *file)
1042 {
1043     util_ldap_state_t *st = 
1044         (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config, 
1045                                                   &ldap_module);
1046     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1047     if (err != NULL) {
1048         return err;
1049     }
1050
1051     ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, cmd->server, 
1052                       "LDAP: SSL trusted certificate authority file - %s", 
1053                        file);
1054
1055     st->cert_auth_file = ap_server_root_relative(cmd->pool, file);
1056
1057     return(NULL);
1058 }
1059
1060
1061 static const char *util_ldap_set_cert_type(cmd_parms *cmd, void *dummy, const char *Type)
1062 {
1063     util_ldap_state_t *st = 
1064     (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config, 
1065                                               &ldap_module);
1066     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1067     if (err != NULL) {
1068         return err;
1069     }
1070
1071     ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, cmd->server, 
1072                       "LDAP: SSL trusted certificate authority file type - %s", 
1073                        Type);
1074
1075     if (0 == strcmp("DER_FILE", Type))
1076         st->cert_file_type = LDAP_CA_TYPE_DER;
1077
1078     else if (0 == strcmp("BASE64_FILE", Type))
1079         st->cert_file_type = LDAP_CA_TYPE_BASE64;
1080
1081     else if (0 == strcmp("CERT7_DB_PATH", Type))
1082         st->cert_file_type = LDAP_CA_TYPE_CERT7_DB;
1083
1084     else
1085         st->cert_file_type = LDAP_CA_TYPE_UNKNOWN;
1086
1087     return(NULL);
1088 }
1089
1090
1091 void *util_ldap_create_config(apr_pool_t *p, server_rec *s)
1092 {
1093     util_ldap_state_t *st = 
1094         (util_ldap_state_t *)apr_pcalloc(p, sizeof(util_ldap_state_t));
1095
1096     st->pool = p;
1097
1098     st->cache_bytes = 100000;
1099     st->search_cache_ttl = 600000000;
1100     st->search_cache_size = 1024;
1101     st->compare_cache_ttl = 600000000;
1102     st->compare_cache_size = 1024;
1103     st->connections = NULL;
1104     st->cert_auth_file = NULL;
1105     st->cert_file_type = LDAP_CA_TYPE_UNKNOWN;
1106     st->ssl_support = 0;
1107
1108     return st;
1109 }
1110
1111 static apr_status_t util_ldap_cleanup_module(void *data)
1112 {
1113
1114     server_rec *s = data;
1115     util_ldap_state_t *st = (util_ldap_state_t *)ap_get_module_config(
1116         s->module_config, &ldap_module);
1117     
1118     if (st->ssl_support) {
1119         apr_ldap_ssl_deinit();
1120     }
1121
1122     return APR_SUCCESS;
1123
1124 }
1125
1126 static int util_ldap_post_config(apr_pool_t *p, apr_pool_t *plog, 
1127                                  apr_pool_t *ptemp, server_rec *s)
1128 {
1129     apr_status_t result;
1130     char buf[MAX_STRING_LEN];
1131     server_rec *s_vhost;
1132     util_ldap_state_t *st_vhost;
1133
1134     util_ldap_state_t *st =
1135         (util_ldap_state_t *)ap_get_module_config(s->module_config, &ldap_module);
1136
1137     void *data;
1138     const char *userdata_key = "util_ldap_init";
1139
1140     /* util_ldap_post_config() will be called twice. Don't bother
1141      * going through all of the initialization on the first call
1142      * because it will just be thrown away.*/
1143     apr_pool_userdata_get(&data, userdata_key, s->process->pool);
1144     if (!data) {
1145         apr_pool_userdata_set((const void *)1, userdata_key,
1146                                apr_pool_cleanup_null, s->process->pool);
1147
1148 #if APR_HAS_SHARED_MEMORY
1149         /* If the cache file already exists then delete it.  Otherwise we are
1150          * going to run into problems creating the shared memory. */
1151         if (st->cache_file) {
1152             char *lck_file = apr_pstrcat (st->pool, st->cache_file, ".lck", NULL);
1153             apr_file_remove(st->cache_file, ptemp);
1154             apr_file_remove(lck_file, ptemp);
1155         }
1156 #endif
1157         return OK;
1158     }
1159
1160 #if APR_HAS_SHARED_MEMORY
1161     /* initializing cache if shared memory size is not zero and we already don't have shm address */
1162     if (!st->cache_shm && st->cache_bytes > 0) {
1163 #endif
1164         result = util_ldap_cache_init(p, st);
1165         if (result != APR_SUCCESS) {
1166             apr_strerror(result, buf, sizeof(buf));
1167             ap_log_error(APLOG_MARK, APLOG_ERR, result, s,
1168                          "LDAP cache: error while creating a shared memory segment: %s", buf);
1169         }
1170
1171
1172 #if APR_HAS_SHARED_MEMORY
1173         if (st->cache_file) {
1174             st->lock_file = apr_pstrcat (st->pool, st->cache_file, ".lck", NULL);
1175         }
1176         else
1177 #endif
1178             st->lock_file = ap_server_root_relative(st->pool, tmpnam(NULL));
1179
1180         result = apr_global_mutex_create(&st->util_ldap_cache_lock, st->lock_file, APR_LOCK_DEFAULT, st->pool);
1181         if (result != APR_SUCCESS) {
1182             return result;
1183         }
1184
1185         /* merge config in all vhost */
1186         s_vhost = s->next;
1187         while (s_vhost) {
1188             st_vhost = (util_ldap_state_t *)ap_get_module_config(s_vhost->module_config, &ldap_module);
1189
1190 #if APR_HAS_SHARED_MEMORY
1191             st_vhost->cache_shm = st->cache_shm;
1192             st_vhost->cache_rmm = st->cache_rmm;
1193             st_vhost->cache_file = st->cache_file;
1194             ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, result, s, 
1195                          "LDAP merging Shared Cache conf: shm=0x%pp rmm=0x%pp for VHOST: %s",
1196                          st->cache_shm, st->cache_rmm, s_vhost->server_hostname);
1197 #endif
1198             st_vhost->lock_file = st->lock_file;
1199             s_vhost = s_vhost->next;
1200         }
1201 #if APR_HAS_SHARED_MEMORY
1202     }
1203     else {
1204         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, "LDAP cache: LDAPSharedCacheSize is zero, disabling shared memory cache");
1205     }
1206 #endif
1207     
1208     /* log the LDAP SDK used 
1209      */
1210     {
1211         apr_ldap_err_t *result = NULL;
1212         apr_ldap_info(p, &(result));
1213         if (result != NULL) {
1214             ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s, result->reason);
1215         }
1216     }
1217
1218     apr_pool_cleanup_register(p, s, util_ldap_cleanup_module,
1219                               util_ldap_cleanup_module); 
1220
1221     /* initialize SSL support if requested
1222     */
1223     if (st->cert_auth_file) {
1224
1225         apr_ldap_err_t *result = NULL;
1226         int rc = apr_ldap_ssl_init(p,
1227                                    st->cert_auth_file,
1228                                    st->cert_file_type,
1229                                    &(result));
1230
1231         if (LDAP_SUCCESS == rc) {
1232             st->ssl_support = 1;
1233         }
1234         else if (NULL != result) {
1235             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, result->reason);
1236             st->ssl_support = 0;
1237         }
1238
1239     }
1240       
1241     /* log SSL status - If SSL isn't available it isn't necessarily
1242      * an error because the modules asking for LDAP connections 
1243      * may not ask for SSL support
1244      */
1245     if (st->ssl_support) {
1246        ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s, 
1247                          "LDAP: SSL support available" );
1248     }
1249     else {
1250        ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, s, 
1251                          "LDAP: SSL support unavailable" );
1252     }
1253     
1254     return(OK);
1255 }
1256
1257 static void util_ldap_child_init(apr_pool_t *p, server_rec *s)
1258 {
1259     apr_status_t sts;
1260     util_ldap_state_t *st =
1261         (util_ldap_state_t *)ap_get_module_config(s->module_config, &ldap_module);
1262
1263     sts = apr_global_mutex_child_init(&st->util_ldap_cache_lock, st->lock_file, p);
1264     if (sts != APR_SUCCESS) {
1265         ap_log_error(APLOG_MARK, APLOG_CRIT, sts, s, "failed to init caching lock in child process");
1266         return;
1267     }
1268     else {
1269         ap_log_error(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, s, 
1270                      "INIT global mutex %s in child %d ", st->lock_file, getpid());
1271     }
1272 }
1273
1274 command_rec util_ldap_cmds[] = {
1275     AP_INIT_TAKE1("LDAPSharedCacheSize", util_ldap_set_cache_bytes, NULL, RSRC_CONF,
1276                   "Sets the size of the shared memory cache in bytes. "
1277                   "Zero means disable the shared memory cache. Defaults to 100KB."),
1278
1279     AP_INIT_TAKE1("LDAPSharedCacheFile", util_ldap_set_cache_file, NULL, RSRC_CONF,
1280                   "Sets the file of the shared memory cache."
1281                   "Nothing means disable the shared memory cache."),
1282
1283     AP_INIT_TAKE1("LDAPCacheEntries", util_ldap_set_cache_entries, NULL, RSRC_CONF,
1284                   "Sets the maximum number of entries that are possible in the LDAP "
1285                   "search cache. "
1286                   "Zero means no limit; -1 disables the cache. Defaults to 1024 entries."),
1287
1288     AP_INIT_TAKE1("LDAPCacheTTL", util_ldap_set_cache_ttl, NULL, RSRC_CONF,
1289                   "Sets the maximum time (in seconds) that an item can be cached in the LDAP "
1290                   "search cache. Zero means no limit. Defaults to 600 seconds (10 minutes)."),
1291
1292     AP_INIT_TAKE1("LDAPOpCacheEntries", util_ldap_set_opcache_entries, NULL, RSRC_CONF,
1293                   "Sets the maximum number of entries that are possible in the LDAP "
1294                   "compare cache. "
1295                   "Zero means no limit; -1 disables the cache. Defaults to 1024 entries."),
1296
1297     AP_INIT_TAKE1("LDAPOpCacheTTL", util_ldap_set_opcache_ttl, NULL, RSRC_CONF,
1298                   "Sets the maximum time (in seconds) that an item is cached in the LDAP "
1299                   "operation cache. Zero means no limit. Defaults to 600 seconds (10 minutes)."),
1300
1301     AP_INIT_TAKE1("LDAPTrustedCA", util_ldap_set_cert_auth, NULL, RSRC_CONF,
1302                   "Sets the file containing the trusted Certificate Authority certificate. "
1303                   "Used to validate the LDAP server certificate for SSL connections."),
1304
1305     AP_INIT_TAKE1("LDAPTrustedCAType", util_ldap_set_cert_type, NULL, RSRC_CONF,
1306                  "Specifies the type of the Certificate Authority file.  "
1307                  "The following types are supported:  "
1308                  "    DER_FILE      - file in binary DER format "
1309                  "    BASE64_FILE   - file in Base64 format "
1310                  "    CERT7_DB_PATH - Netscape certificate database file "),
1311     {NULL}
1312 };
1313
1314 static void util_ldap_register_hooks(apr_pool_t *p)
1315 {
1316     ap_hook_post_config(util_ldap_post_config,NULL,NULL,APR_HOOK_MIDDLE);
1317     ap_hook_handler(util_ldap_handler, NULL, NULL, APR_HOOK_MIDDLE);
1318     ap_hook_child_init(util_ldap_child_init, NULL, NULL, APR_HOOK_MIDDLE);
1319 }
1320
1321 module ldap_module = {
1322    STANDARD20_MODULE_STUFF,
1323    NULL,                                /* dir config creater */
1324    NULL,                                /* dir merger --- default is to override */
1325    util_ldap_create_config,             /* server config */
1326    NULL,                                /* merge server config */
1327    util_ldap_cmds,                      /* command table */
1328    util_ldap_register_hooks,            /* set up request processing hooks */
1329 };