]> granicus.if.org Git - apache/blob - modules/ldap/util_ldap.c
Remove the global only flag from the LDAPConnectionTimeout directive and add it to...
[apache] / modules / ldap / util_ldap.c
1 /* Copyright 2001-2005 The Apache Software Foundation or its licensors, as
2  * applicable.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * util_ldap.c: LDAP things
19  *
20  * Original code from auth_ldap module for Apache v1.3:
21  * Copyright 1998, 1999 Enbridge Pipelines Inc.
22  * Copyright 1999-2001 Dave Carrigan
23  */
24
25 #include "httpd.h"
26 #include "http_config.h"
27 #include "http_core.h"
28 #include "http_log.h"
29 #include "http_protocol.h"
30 #include "http_request.h"
31 #include "util_ldap.h"
32 #include "util_ldap_cache.h"
33
34 #include <apr_strings.h>
35
36 #if APR_HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif
39
40 #if !APR_HAS_LDAP
41 #error mod_ldap requires APR-util to have LDAP support built in
42 #endif
43
44 #ifdef AP_NEED_SET_MUTEX_PERMS
45 #include "unixd.h"
46 #endif
47
48     /* defines for certificate file types
49     */
50 #define LDAP_CA_TYPE_UNKNOWN            0
51 #define LDAP_CA_TYPE_DER                1
52 #define LDAP_CA_TYPE_BASE64             2
53 #define LDAP_CA_TYPE_CERT7_DB           3
54
55
56 module AP_MODULE_DECLARE_DATA ldap_module;
57
58 #define LDAP_CACHE_LOCK() do {                                  \
59     if (st->util_ldap_cache_lock)                               \
60         apr_global_mutex_lock(st->util_ldap_cache_lock);        \
61 } while (0)
62
63 #define LDAP_CACHE_UNLOCK() do {                                \
64     if (st->util_ldap_cache_lock)                               \
65         apr_global_mutex_unlock(st->util_ldap_cache_lock);      \
66 } while (0)
67
68 static void util_ldap_strdup (char **str, const char *newstr)
69 {
70     if (*str) {
71         free(*str);
72         *str = NULL;
73     }
74
75     if (newstr) {
76         *str = strdup(newstr);
77     }
78 }
79
80 /*
81  * Status Handler
82  * --------------
83  *
84  * This handler generates a status page about the current performance of
85  * the LDAP cache. It is enabled as follows:
86  *
87  * <Location /ldap-status>
88  *   SetHandler ldap-status
89  * </Location>
90  *
91  */
92 static int util_ldap_handler(request_rec *r)
93 {
94     util_ldap_state_t *st = (util_ldap_state_t *)
95                             ap_get_module_config(r->server->module_config,
96                                                  &ldap_module);
97
98     r->allowed |= (1 << M_GET);
99     if (r->method_number != M_GET)
100         return DECLINED;
101
102     if (strcmp(r->handler, "ldap-status")) {
103         return DECLINED;
104     }
105
106     ap_set_content_type(r, "text/html");
107
108     if (r->header_only)
109         return OK;
110
111     ap_rputs(DOCTYPE_HTML_3_2
112              "<html><head><title>LDAP Cache Information</title></head>\n", r);
113     ap_rputs("<body bgcolor='#ffffff'><h1 align=center>LDAP Cache Information"
114              "</h1>\n", r);
115
116     util_ald_cache_display(r, st);
117
118     return OK;
119 }
120
121 /* ------------------------------------------------------------------ */
122
123
124 /*
125  * Closes an LDAP connection by unlocking it. The next time
126  * uldap_connection_find() is called this connection will be
127  * available for reuse.
128  */
129 static void uldap_connection_close(util_ldap_connection_t *ldc)
130 {
131
132     /*
133      * QUESTION:
134      *
135      * Is it safe leaving bound connections floating around between the
136      * different modules? Keeping the user bound is a performance boost,
137      * but it is also a potential security problem - maybe.
138      *
139      * For now we unbind the user when we finish with a connection, but
140      * we don't have to...
141      */
142
143     /* mark our connection as available for reuse */
144
145 #if APR_HAS_THREADS
146     apr_thread_mutex_unlock(ldc->lock);
147 #endif
148 }
149
150
151 /*
152  * Destroys an LDAP connection by unbinding and closing the connection to
153  * the LDAP server. It is used to bring the connection back to a known
154  * state after an error, and during pool cleanup.
155  */
156 static apr_status_t uldap_connection_unbind(void *param)
157 {
158     util_ldap_connection_t *ldc = param;
159
160     if (ldc) {
161         if (ldc->ldap) {
162             ldap_unbind_s(ldc->ldap);
163             ldc->ldap = NULL;
164         }
165         ldc->bound = 0;
166     }
167
168     return APR_SUCCESS;
169 }
170
171
172 /*
173  * Clean up an LDAP connection by unbinding and unlocking the connection.
174  * This function is registered with the pool cleanup function - causing
175  * the LDAP connections to be shut down cleanly on graceful restart.
176  */
177 static apr_status_t uldap_connection_cleanup(void *param)
178 {
179     util_ldap_connection_t *ldc = param;
180
181     if (ldc) {
182
183         /* unbind and disconnect from the LDAP server */
184         uldap_connection_unbind(ldc);
185
186         /* free the username and password */
187         if (ldc->bindpw) {
188             free((void*)ldc->bindpw);
189         }
190         if (ldc->binddn) {
191             free((void*)ldc->binddn);
192         }
193
194         /* unlock this entry */
195         uldap_connection_close(ldc);
196
197     }
198
199     return APR_SUCCESS;
200 }
201
202
203 /*
204  * Connect to the LDAP server and binds. Does not connect if already
205  * connected (i.e. ldc->ldap is non-NULL.) Does not bind if already bound.
206  *
207  * Returns LDAP_SUCCESS on success; and an error code on failure
208  */
209 static int uldap_connection_open(request_rec *r,
210                                  util_ldap_connection_t *ldc)
211 {
212     int rc = 0;
213     int failures = 0;
214     int version  = LDAP_VERSION3;
215     apr_ldap_err_t *result = NULL;
216     struct timeval timeOut = {10,0};    /* 10 second connection timeout */
217     util_ldap_state_t *st =
218         (util_ldap_state_t *)ap_get_module_config(r->server->module_config,
219         &ldap_module);
220
221     /* sanity check for NULL */
222     if (!ldc) {
223         return -1;
224     }
225
226     /* If the connection is already bound, return
227     */
228     if (ldc->bound)
229     {
230         ldc->reason = "LDAP: connection open successful (already bound)";
231         return LDAP_SUCCESS;
232     }
233
234     /* create the ldap session handle
235     */
236     if (NULL == ldc->ldap)
237     {
238         /* Since the host will include a port if the default port is not used,
239          * always specify the default ports for the port parameter.  This will
240          * allow a host string that contains multiple hosts the ability to mix
241          * some hosts with ports and some without. All hosts which do not
242          * specify a port will use the default port.
243          */
244         apr_ldap_init(ldc->pool, &(ldc->ldap),
245                       ldc->host,
246                       APR_LDAP_SSL == ldc->secure ? LDAPS_PORT : LDAP_PORT,
247                       APR_LDAP_NONE,
248                       &(result));
249
250
251         if (result != NULL && result->rc) {
252             ldc->reason = result->reason;
253         }
254
255         if (NULL == ldc->ldap)
256         {
257             ldc->bound = 0;
258             if (NULL == ldc->reason) {
259                 ldc->reason = "LDAP: ldap initialization failed";
260             }
261             else {
262                 ldc->reason = result->reason;
263             }
264             return(result->rc);
265         }
266
267         /* always default to LDAP V3 */
268         ldap_set_option(ldc->ldap, LDAP_OPT_PROTOCOL_VERSION, &version);
269
270         /* set client certificates */
271         if (!apr_is_empty_array(ldc->client_certs)) {
272             apr_ldap_set_option(ldc->pool, ldc->ldap, APR_LDAP_OPT_TLS_CERT,
273                                 ldc->client_certs, &(result));
274             if (LDAP_SUCCESS != result->rc) {
275                 ldap_unbind_s(ldc->ldap);
276                 ldc->ldap = NULL;
277                 ldc->bound = 0;
278                 ldc->reason = result->reason;
279                 return(result->rc);
280             }
281         }
282
283         /* switch on SSL/TLS */
284         if (APR_LDAP_NONE != ldc->secure) {
285             apr_ldap_set_option(ldc->pool, ldc->ldap,
286                                 APR_LDAP_OPT_TLS, &ldc->secure, &(result));
287             if (LDAP_SUCCESS != result->rc) {
288                 ldap_unbind_s(ldc->ldap);
289                 ldc->ldap = NULL;
290                 ldc->bound = 0;
291                 ldc->reason = result->reason;
292                 return(result->rc);
293             }
294         }
295
296         /* Set the alias dereferencing option */
297         ldap_set_option(ldc->ldap, LDAP_OPT_DEREF, &(ldc->deref));
298
299 /*XXX All of the #ifdef's need to be removed once apr-util 1.2 is released */
300 #ifdef APR_LDAP_OPT_VERIFY_CERT
301         apr_ldap_set_option(ldc->pool, ldc->ldap,
302                             APR_LDAP_OPT_VERIFY_CERT, &(st->verify_svr_cert), &(result));
303 #else
304 #if defined(LDAPSSL_VERIFY_SERVER)
305         if (st->verify_svr_cert) {
306             result->rc = ldapssl_set_verify_mode(LDAPSSL_VERIFY_SERVER);
307         }
308         else {
309             result->rc = ldapssl_set_verify_mode(LDAPSSL_VERIFY_NONE);
310         }
311 #elif defined(LDAP_OPT_X_TLS_REQUIRE_CERT)
312                 /* This is not a per-connection setting so just pass NULL for the
313                    Ldap connection handle */
314         if (st->verify_svr_cert) {
315                         int i = LDAP_OPT_X_TLS_DEMAND;
316                         result->rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &i);
317         }
318         else {
319                         int i = LDAP_OPT_X_TLS_NEVER;
320                         result->rc = ldap_set_option(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, &i);
321         }
322 #endif
323 #endif
324
325 #ifdef LDAP_OPT_NETWORK_TIMEOUT
326         if (st->connectionTimeout > 0) {
327             timeOut.tv_sec = st->connectionTimeout;
328         }
329
330         if (st->connectionTimeout >= 0) {
331             rc = apr_ldap_set_option(ldc->pool, ldc->ldap, LDAP_OPT_NETWORK_TIMEOUT,
332                                      (void *)&timeOut, &(result));
333             if (APR_SUCCESS != rc) {
334                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
335                                  "LDAP: Could not set the connection timeout");
336             }
337         }
338 #endif
339
340
341     }
342
343
344     /* loop trying to bind up to 10 times if LDAP_SERVER_DOWN error is
345      * returned.  Break out of the loop on Success or any other error.
346      *
347      * NOTE: Looping is probably not a great idea. If the server isn't
348      * responding the chances it will respond after a few tries are poor.
349      * However, the original code looped and it only happens on
350      * the error condition.
351       */
352     for (failures=0; failures<10; failures++)
353     {
354         rc = ldap_simple_bind_s(ldc->ldap,
355                                 (char *)ldc->binddn,
356                                 (char *)ldc->bindpw);
357         if (LDAP_SERVER_DOWN != rc) {
358             break;
359         }
360     }
361
362     /* free the handle if there was an error
363     */
364     if (LDAP_SUCCESS != rc)
365     {
366         ldap_unbind_s(ldc->ldap);
367         ldc->ldap = NULL;
368         ldc->bound = 0;
369         ldc->reason = "LDAP: ldap_simple_bind_s() failed";
370     }
371     else {
372         ldc->bound = 1;
373         ldc->reason = "LDAP: connection open successful";
374     }
375
376     return(rc);
377 }
378
379
380 /*
381  * Compare client certificate arrays.
382  *
383  * Returns 1 on compare failure, 0 otherwise.
384  */
385 static int compare_client_certs(apr_array_header_t *srcs,
386                                 apr_array_header_t *dests)
387 {
388     int i = 0;
389     struct apr_ldap_opt_tls_cert_t *src, *dest;
390
391     /* arrays both NULL? if so, then equal */
392     if (srcs == NULL && dests == NULL) {
393         return 0;
394     }
395
396     /* arrays different length or either NULL? If so, then not equal */
397     if (srcs == NULL || dests == NULL || srcs->nelts != dests->nelts) {
398         return 1;
399     }
400
401     /* run an actual comparison */
402     src = (struct apr_ldap_opt_tls_cert_t *)srcs->elts;
403     dest = (struct apr_ldap_opt_tls_cert_t *)dests->elts;
404     for (i = 0; i < srcs->nelts; i++) {
405         if (strcmp(src[i].path, dest[i].path) ||
406             strcmp(src[i].password, dest[i].password) ||
407             src[i].type != dest[i].type) {
408             return 1;
409         }
410     }
411
412     /* if we got here, the cert arrays were identical */
413     return 0;
414
415 }
416
417
418 /*
419  * Find an existing ldap connection struct that matches the
420  * provided ldap connection parameters.
421  *
422  * If not found in the cache, a new ldc structure will be allocated
423  * from st->pool and returned to the caller.  If found in the cache,
424  * a pointer to the existing ldc structure will be returned.
425  */
426 static util_ldap_connection_t *
427             uldap_connection_find(request_rec *r,
428                                   const char *host, int port,
429                                   const char *binddn, const char *bindpw,
430                                   deref_options deref, int secure)
431 {
432     struct util_ldap_connection_t *l, *p; /* To traverse the linked list */
433     int secureflag = secure;
434
435     util_ldap_state_t *st =
436         (util_ldap_state_t *)ap_get_module_config(r->server->module_config,
437         &ldap_module);
438
439
440 #if APR_HAS_THREADS
441     /* mutex lock this function */
442     apr_thread_mutex_lock(st->mutex);
443 #endif
444
445     if (secure < APR_LDAP_NONE) {
446         secureflag = st->secure;
447     }
448
449     /* Search for an exact connection match in the list that is not
450      * being used.
451      */
452     for (l=st->connections,p=NULL; l; l=l->next) {
453 #if APR_HAS_THREADS
454         if (APR_SUCCESS == apr_thread_mutex_trylock(l->lock)) {
455 #endif
456         if (   (l->port == port) && (strcmp(l->host, host) == 0)
457             && ((!l->binddn && !binddn) || (l->binddn && binddn
458                                              && !strcmp(l->binddn, binddn)))
459             && ((!l->bindpw && !bindpw) || (l->bindpw && bindpw
460                                              && !strcmp(l->bindpw, bindpw)))
461             && (l->deref == deref) && (l->secure == secureflag)
462             && !compare_client_certs(st->client_certs, l->client_certs))
463         {
464             break;
465         }
466 #if APR_HAS_THREADS
467             /* If this connection didn't match the criteria, then we
468              * need to unlock the mutex so it is available to be reused.
469              */
470             apr_thread_mutex_unlock(l->lock);
471         }
472 #endif
473         p = l;
474     }
475
476     /* If nothing found, search again, but we don't care about the
477      * binddn and bindpw this time.
478      */
479     if (!l) {
480         for (l=st->connections,p=NULL; l; l=l->next) {
481 #if APR_HAS_THREADS
482             if (APR_SUCCESS == apr_thread_mutex_trylock(l->lock)) {
483
484 #endif
485             if ((l->port == port) && (strcmp(l->host, host) == 0) &&
486                 (l->deref == deref) && (l->secure == secureflag) &&
487                 !compare_client_certs(st->client_certs, l->client_certs))
488             {
489                 /* the bind credentials have changed */
490                 l->bound = 0;
491                 util_ldap_strdup((char**)&(l->binddn), binddn);
492                 util_ldap_strdup((char**)&(l->bindpw), bindpw);
493                 break;
494             }
495 #if APR_HAS_THREADS
496                 /* If this connection didn't match the criteria, then we
497                  * need to unlock the mutex so it is available to be reused.
498                  */
499                 apr_thread_mutex_unlock(l->lock);
500             }
501 #endif
502             p = l;
503         }
504     }
505
506 /* artificially disable cache */
507 /* l = NULL; */
508
509     /* If no connection what found after the second search, we
510      * must create one.
511      */
512     if (!l) {
513
514         /*
515          * Add the new connection entry to the linked list. Note that we
516          * don't actually establish an LDAP connection yet; that happens
517          * the first time authentication is requested.
518          */
519         /* create the details to the pool in st */
520         l = apr_pcalloc(st->pool, sizeof(util_ldap_connection_t));
521 #if APR_HAS_THREADS
522         apr_thread_mutex_create(&l->lock, APR_THREAD_MUTEX_DEFAULT, st->pool);
523         apr_thread_mutex_lock(l->lock);
524 #endif
525         l->pool = st->pool;
526         l->bound = 0;
527         l->host = apr_pstrdup(st->pool, host);
528         l->port = port;
529         l->deref = deref;
530         util_ldap_strdup((char**)&(l->binddn), binddn);
531         util_ldap_strdup((char**)&(l->bindpw), bindpw);
532
533         /* The security mode after parsing the URL will always be either
534          * APR_LDAP_NONE (ldap://) or APR_LDAP_SSL (ldaps://).
535          * If the security setting is NONE, override it to the security
536          * setting optionally supplied by the admin using LDAPTrustedMode
537          */
538         l->secure = secureflag;
539
540         /* save away a copy of the client cert list that is presently valid */
541         l->client_certs = apr_array_copy_hdr(l->pool, st->client_certs);
542
543         /* add the cleanup to the pool */
544         apr_pool_cleanup_register(l->pool, l,
545                                   uldap_connection_cleanup,
546                                   apr_pool_cleanup_null);
547
548         if (p) {
549             p->next = l;
550         }
551         else {
552             st->connections = l;
553         }
554     }
555
556 #if APR_HAS_THREADS
557     apr_thread_mutex_unlock(st->mutex);
558 #endif
559     return l;
560 }
561
562 /* ------------------------------------------------------------------ */
563
564 /*
565  * Compares two DNs to see if they're equal. The only way to do this correctly
566  * is to search for the dn and then do ldap_get_dn() on the result. This should
567  * match the initial dn, since it would have been also retrieved with
568  * ldap_get_dn(). This is expensive, so if the configuration value
569  * compare_dn_on_server is false, just does an ordinary strcmp.
570  *
571  * The lock for the ldap cache should already be acquired.
572  */
573 static int uldap_cache_comparedn(request_rec *r, util_ldap_connection_t *ldc,
574                                  const char *url, const char *dn,
575                                  const char *reqdn, int compare_dn_on_server)
576 {
577     int result = 0;
578     util_url_node_t *curl;
579     util_url_node_t curnode;
580     util_dn_compare_node_t *node;
581     util_dn_compare_node_t newnode;
582     int failures = 0;
583     LDAPMessage *res, *entry;
584     char *searchdn;
585
586     util_ldap_state_t *st = (util_ldap_state_t *)
587                             ap_get_module_config(r->server->module_config,
588                                                  &ldap_module);
589
590     /* get cache entry (or create one) */
591     LDAP_CACHE_LOCK();
592
593     curnode.url = url;
594     curl = util_ald_cache_fetch(st->util_ldap_cache, &curnode);
595     if (curl == NULL) {
596         curl = util_ald_create_caches(st, url);
597     }
598     LDAP_CACHE_UNLOCK();
599
600     /* a simple compare? */
601     if (!compare_dn_on_server) {
602         /* unlock this read lock */
603         if (strcmp(dn, reqdn)) {
604             ldc->reason = "DN Comparison FALSE (direct strcmp())";
605             return LDAP_COMPARE_FALSE;
606         }
607         else {
608             ldc->reason = "DN Comparison TRUE (direct strcmp())";
609             return LDAP_COMPARE_TRUE;
610         }
611     }
612
613     if (curl) {
614         /* no - it's a server side compare */
615         LDAP_CACHE_LOCK();
616
617         /* is it in the compare cache? */
618         newnode.reqdn = (char *)reqdn;
619         node = util_ald_cache_fetch(curl->dn_compare_cache, &newnode);
620         if (node != NULL) {
621             /* If it's in the cache, it's good */
622             /* unlock this read lock */
623             LDAP_CACHE_UNLOCK();
624             ldc->reason = "DN Comparison TRUE (cached)";
625             return LDAP_COMPARE_TRUE;
626         }
627
628         /* unlock this read lock */
629         LDAP_CACHE_UNLOCK();
630     }
631
632 start_over:
633     if (failures++ > 10) {
634         /* too many failures */
635         return result;
636     }
637
638     /* make a server connection */
639     if (LDAP_SUCCESS != (result = uldap_connection_open(r, ldc))) {
640         /* connect to server failed */
641         return result;
642     }
643
644     /* search for reqdn */
645     if ((result = ldap_search_ext_s(ldc->ldap, (char *)reqdn, LDAP_SCOPE_BASE,
646                                     "(objectclass=*)", NULL, 1,
647                                     NULL, NULL, NULL, -1, &res))
648             == LDAP_SERVER_DOWN)
649     {
650         ldc->reason = "DN Comparison ldap_search_ext_s() "
651                       "failed with server down";
652         uldap_connection_unbind(ldc);
653         goto start_over;
654     }
655     if (result != LDAP_SUCCESS) {
656         /* search for reqdn failed - no match */
657         ldc->reason = "DN Comparison ldap_search_ext_s() failed";
658         return result;
659     }
660
661     entry = ldap_first_entry(ldc->ldap, res);
662     searchdn = ldap_get_dn(ldc->ldap, entry);
663
664     ldap_msgfree(res);
665     if (strcmp(dn, searchdn) != 0) {
666         /* compare unsuccessful */
667         ldc->reason = "DN Comparison FALSE (checked on server)";
668         result = LDAP_COMPARE_FALSE;
669     }
670     else {
671         if (curl) {
672             /* compare successful - add to the compare cache */
673             LDAP_CACHE_LOCK();
674             newnode.reqdn = (char *)reqdn;
675             newnode.dn = (char *)dn;
676
677             node = util_ald_cache_fetch(curl->dn_compare_cache, &newnode);
678             if (   (node == NULL)
679                 || (strcmp(reqdn, node->reqdn) != 0)
680                 || (strcmp(dn, node->dn) != 0))
681             {
682                 util_ald_cache_insert(curl->dn_compare_cache, &newnode);
683             }
684             LDAP_CACHE_UNLOCK();
685         }
686         ldc->reason = "DN Comparison TRUE (checked on server)";
687         result = LDAP_COMPARE_TRUE;
688     }
689     ldap_memfree(searchdn);
690     return result;
691
692 }
693
694 /*
695  * Does an generic ldap_compare operation. It accepts a cache that it will use
696  * to lookup the compare in the cache. We cache two kinds of compares
697  * (require group compares) and (require user compares). Each compare has a different
698  * cache node: require group includes the DN; require user does not because the
699  * require user cache is owned by the
700  *
701  */
702 static int uldap_cache_compare(request_rec *r, util_ldap_connection_t *ldc,
703                                const char *url, const char *dn,
704                                const char *attrib, const char *value)
705 {
706     int result = 0;
707     util_url_node_t *curl;
708     util_url_node_t curnode;
709     util_compare_node_t *compare_nodep;
710     util_compare_node_t the_compare_node;
711     apr_time_t curtime = 0; /* silence gcc -Wall */
712     int failures = 0;
713
714     util_ldap_state_t *st = (util_ldap_state_t *)
715                             ap_get_module_config(r->server->module_config,
716                                                  &ldap_module);
717
718     /* get cache entry (or create one) */
719     LDAP_CACHE_LOCK();
720     curnode.url = url;
721     curl = util_ald_cache_fetch(st->util_ldap_cache, &curnode);
722     if (curl == NULL) {
723         curl = util_ald_create_caches(st, url);
724     }
725     LDAP_CACHE_UNLOCK();
726
727     if (curl) {
728         /* make a comparison to the cache */
729         LDAP_CACHE_LOCK();
730         curtime = apr_time_now();
731
732         the_compare_node.dn = (char *)dn;
733         the_compare_node.attrib = (char *)attrib;
734         the_compare_node.value = (char *)value;
735         the_compare_node.result = 0;
736
737         compare_nodep = util_ald_cache_fetch(curl->compare_cache,
738                                              &the_compare_node);
739
740         if (compare_nodep != NULL) {
741             /* found it... */
742             if (curtime - compare_nodep->lastcompare > st->compare_cache_ttl) {
743                 /* ...but it is too old */
744                 util_ald_cache_remove(curl->compare_cache, compare_nodep);
745             }
746             else {
747                 /* ...and it is good */
748                 /* unlock this read lock */
749                 LDAP_CACHE_UNLOCK();
750                 if (LDAP_COMPARE_TRUE == compare_nodep->result) {
751                     ldc->reason = "Comparison true (cached)";
752                     return compare_nodep->result;
753                 }
754                 else if (LDAP_COMPARE_FALSE == compare_nodep->result) {
755                     ldc->reason = "Comparison false (cached)";
756                     return compare_nodep->result;
757                 }
758                 else if (LDAP_NO_SUCH_ATTRIBUTE == compare_nodep->result) {
759                     ldc->reason = "Comparison no such attribute (cached)";
760                     return compare_nodep->result;
761                 }
762                 else {
763                     ldc->reason = "Comparison undefined (cached)";
764                     return compare_nodep->result;
765                 }
766             }
767         }
768         /* unlock this read lock */
769         LDAP_CACHE_UNLOCK();
770     }
771
772 start_over:
773     if (failures++ > 10) {
774         /* too many failures */
775         return result;
776     }
777     if (LDAP_SUCCESS != (result = uldap_connection_open(r, ldc))) {
778         /* connect failed */
779         return result;
780     }
781
782     if ((result = ldap_compare_s(ldc->ldap,
783                                  (char *)dn,
784                                  (char *)attrib,
785                                  (char *)value))
786                                                == LDAP_SERVER_DOWN) {
787         /* connection failed - try again */
788         ldc->reason = "ldap_compare_s() failed with server down";
789         uldap_connection_unbind(ldc);
790         goto start_over;
791     }
792
793     ldc->reason = "Comparison complete";
794     if ((LDAP_COMPARE_TRUE == result) ||
795         (LDAP_COMPARE_FALSE == result) ||
796         (LDAP_NO_SUCH_ATTRIBUTE == result)) {
797         if (curl) {
798             /* compare completed; caching result */
799             LDAP_CACHE_LOCK();
800             the_compare_node.lastcompare = curtime;
801             the_compare_node.result = result;
802
803             /* If the node doesn't exist then insert it, otherwise just update
804              * it with the last results
805              */
806             compare_nodep = util_ald_cache_fetch(curl->compare_cache,
807                                                  &the_compare_node);
808             if (   (compare_nodep == NULL)
809                 || (strcmp(the_compare_node.dn, compare_nodep->dn) != 0)
810                 || (strcmp(the_compare_node.attrib,compare_nodep->attrib) != 0)
811                 || (strcmp(the_compare_node.value, compare_nodep->value) != 0))
812             {
813                 util_ald_cache_insert(curl->compare_cache, &the_compare_node);
814             }
815             else {
816                 compare_nodep->lastcompare = curtime;
817                 compare_nodep->result = result;
818             }
819             LDAP_CACHE_UNLOCK();
820         }
821         if (LDAP_COMPARE_TRUE == result) {
822             ldc->reason = "Comparison true (adding to cache)";
823             return LDAP_COMPARE_TRUE;
824         }
825         else if (LDAP_COMPARE_FALSE == result) {
826             ldc->reason = "Comparison false (adding to cache)";
827             return LDAP_COMPARE_FALSE;
828         }
829         else {
830             ldc->reason = "Comparison no such attribute (adding to cache)";
831             return LDAP_NO_SUCH_ATTRIBUTE;
832         }
833     }
834     return result;
835 }
836
837 static int uldap_cache_checkuserid(request_rec *r, util_ldap_connection_t *ldc,
838                                    const char *url, const char *basedn,
839                                    int scope, char **attrs, const char *filter,
840                                    const char *bindpw, const char **binddn,
841                                    const char ***retvals)
842 {
843     const char **vals = NULL;
844     int numvals = 0;
845     int result = 0;
846     LDAPMessage *res, *entry;
847     char *dn;
848     int count;
849     int failures = 0;
850     util_url_node_t *curl;              /* Cached URL node */
851     util_url_node_t curnode;
852     util_search_node_t *search_nodep;   /* Cached search node */
853     util_search_node_t the_search_node;
854     apr_time_t curtime;
855
856     util_ldap_state_t *st =
857         (util_ldap_state_t *)ap_get_module_config(r->server->module_config,
858         &ldap_module);
859
860     /* Get the cache node for this url */
861     LDAP_CACHE_LOCK();
862     curnode.url = url;
863     curl = (util_url_node_t *)util_ald_cache_fetch(st->util_ldap_cache,
864                                                    &curnode);
865     if (curl == NULL) {
866         curl = util_ald_create_caches(st, url);
867     }
868     LDAP_CACHE_UNLOCK();
869
870     if (curl) {
871         LDAP_CACHE_LOCK();
872         the_search_node.username = filter;
873         search_nodep = util_ald_cache_fetch(curl->search_cache,
874                                             &the_search_node);
875         if (search_nodep != NULL) {
876
877             /* found entry in search cache... */
878             curtime = apr_time_now();
879
880             /*
881              * Remove this item from the cache if its expired. If the sent
882              * password doesn't match the storepassword, the entry will
883              * be removed and readded later if the credentials pass
884              * authentication.
885              */
886             if ((curtime - search_nodep->lastbind) > st->search_cache_ttl) {
887                 /* ...but entry is too old */
888                 util_ald_cache_remove(curl->search_cache, search_nodep);
889             }
890             else if (   (search_nodep->bindpw)
891                      && (search_nodep->bindpw[0] != '\0')
892                      && (strcmp(search_nodep->bindpw, bindpw) == 0))
893             {
894                 /* ...and entry is valid */
895                 *binddn = search_nodep->dn;
896                 *retvals = search_nodep->vals;
897                 LDAP_CACHE_UNLOCK();
898                 ldc->reason = "Authentication successful (cached)";
899                 return LDAP_SUCCESS;
900             }
901         }
902         /* unlock this read lock */
903         LDAP_CACHE_UNLOCK();
904     }
905
906     /*
907      * At this point, there is no valid cached search, so lets do the search.
908      */
909
910     /*
911      * If LDAP operation fails due to LDAP_SERVER_DOWN, control returns here.
912      */
913 start_over:
914     if (failures++ > 10) {
915         return result;
916     }
917     if (LDAP_SUCCESS != (result = uldap_connection_open(r, ldc))) {
918         return result;
919     }
920
921     /* try do the search */
922     if ((result = ldap_search_ext_s(ldc->ldap,
923                                     (char *)basedn, scope,
924                                     (char *)filter, attrs, 0,
925                                     NULL, NULL, NULL, -1, &res))
926             == LDAP_SERVER_DOWN)
927     {
928         ldc->reason = "ldap_search_ext_s() for user failed with server down";
929         uldap_connection_unbind(ldc);
930         goto start_over;
931     }
932
933     /* if there is an error (including LDAP_NO_SUCH_OBJECT) return now */
934     if (result != LDAP_SUCCESS) {
935         ldc->reason = "ldap_search_ext_s() for user failed";
936         return result;
937     }
938
939     /*
940      * We should have found exactly one entry; to find a different
941      * number is an error.
942      */
943     count = ldap_count_entries(ldc->ldap, res);
944     if (count != 1)
945     {
946         if (count == 0 )
947             ldc->reason = "User not found";
948         else
949             ldc->reason = "User is not unique (search found two "
950                           "or more matches)";
951         ldap_msgfree(res);
952         return LDAP_NO_SUCH_OBJECT;
953     }
954
955     entry = ldap_first_entry(ldc->ldap, res);
956
957     /* Grab the dn, copy it into the pool, and free it again */
958     dn = ldap_get_dn(ldc->ldap, entry);
959     *binddn = apr_pstrdup(r->pool, dn);
960     ldap_memfree(dn);
961
962     /*
963      * A bind to the server with an empty password always succeeds, so
964      * we check to ensure that the password is not empty. This implies
965      * that users who actually do have empty passwords will never be
966      * able to authenticate with this module. I don't see this as a big
967      * problem.
968      */
969     if (!bindpw || strlen(bindpw) <= 0) {
970         ldap_msgfree(res);
971         ldc->reason = "Empty password not allowed";
972         return LDAP_INVALID_CREDENTIALS;
973     }
974
975     /*
976      * Attempt to bind with the retrieved dn and the password. If the bind
977      * fails, it means that the password is wrong (the dn obviously
978      * exists, since we just retrieved it)
979      */
980     if ((result = ldap_simple_bind_s(ldc->ldap,
981                                      (char *)*binddn,
982                                      (char *)bindpw)) == LDAP_SERVER_DOWN) {
983         ldc->reason = "ldap_simple_bind_s() to check user credentials "
984                       "failed with server down";
985         ldap_msgfree(res);
986         uldap_connection_unbind(ldc);
987         goto start_over;
988     }
989
990     /* failure? if so - return */
991     if (result != LDAP_SUCCESS) {
992         ldc->reason = "ldap_simple_bind_s() to check user credentials failed";
993         ldap_msgfree(res);
994         uldap_connection_unbind(ldc);
995         return result;
996     }
997     else {
998         /*
999          * We have just bound the connection to a different user and password
1000          * combination, which might be reused unintentionally next time this
1001          * connection is used from the connection pool. To ensure no confusion,
1002          * we mark the connection as unbound.
1003          */
1004         ldc->bound = 0;
1005     }
1006
1007     /*
1008      * Get values for the provided attributes.
1009      */
1010     if (attrs) {
1011         int k = 0;
1012         int i = 0;
1013         while (attrs[k++]);
1014         vals = apr_pcalloc(r->pool, sizeof(char *) * (k+1));
1015         numvals = k;
1016         while (attrs[i]) {
1017             char **values;
1018             int j = 0;
1019             char *str = NULL;
1020             /* get values */
1021             values = ldap_get_values(ldc->ldap, entry, attrs[i]);
1022             while (values && values[j]) {
1023                 str = str ? apr_pstrcat(r->pool, str, "; ", values[j], NULL)
1024                           : apr_pstrdup(r->pool, values[j]);
1025                 j++;
1026             }
1027             ldap_value_free(values);
1028             vals[i] = str;
1029             i++;
1030         }
1031         *retvals = vals;
1032     }
1033
1034     /*
1035      * Add the new username to the search cache.
1036      */
1037     if (curl) {
1038         LDAP_CACHE_LOCK();
1039         the_search_node.username = filter;
1040         the_search_node.dn = *binddn;
1041         the_search_node.bindpw = bindpw;
1042         the_search_node.lastbind = apr_time_now();
1043         the_search_node.vals = vals;
1044         the_search_node.numvals = numvals;
1045
1046         /* Search again to make sure that another thread didn't ready insert
1047          * this node into the cache before we got here. If it does exist then
1048          * update the lastbind
1049          */
1050         search_nodep = util_ald_cache_fetch(curl->search_cache,
1051                                             &the_search_node);
1052         if ((search_nodep == NULL) ||
1053             (strcmp(*binddn, search_nodep->dn) != 0)) {
1054
1055             /* Nothing in cache, insert new entry */
1056             util_ald_cache_insert(curl->search_cache, &the_search_node);
1057         }
1058         else if ((!search_nodep->bindpw) ||
1059             (strcmp(bindpw, search_nodep->bindpw) != 0)) {
1060
1061             /* Entry in cache is invalid, remove it and insert new one */
1062             util_ald_cache_remove(curl->search_cache, search_nodep);
1063             util_ald_cache_insert(curl->search_cache, &the_search_node);
1064         }
1065         else {
1066             /* Cache entry is valid, update lastbind */
1067             search_nodep->lastbind = the_search_node.lastbind;
1068         }
1069         LDAP_CACHE_UNLOCK();
1070     }
1071     ldap_msgfree(res);
1072
1073     ldc->reason = "Authentication successful";
1074     return LDAP_SUCCESS;
1075 }
1076
1077 /*
1078  * This function will return the DN of the entry matching userid.
1079  * It is used to get the DN in case some other module than mod_auth_ldap
1080  * has authenticated the user.
1081  * The function is basically a copy of uldap_cache_checkuserid
1082  * with password checking removed.
1083  */
1084 static int uldap_cache_getuserdn(request_rec *r, util_ldap_connection_t *ldc,
1085                                  const char *url, const char *basedn,
1086                                  int scope, char **attrs, const char *filter,
1087                                  const char **binddn, const char ***retvals)
1088 {
1089     const char **vals = NULL;
1090     int numvals = 0;
1091     int result = 0;
1092     LDAPMessage *res, *entry;
1093     char *dn;
1094     int count;
1095     int failures = 0;
1096     util_url_node_t *curl;              /* Cached URL node */
1097     util_url_node_t curnode;
1098     util_search_node_t *search_nodep;   /* Cached search node */
1099     util_search_node_t the_search_node;
1100     apr_time_t curtime;
1101
1102     util_ldap_state_t *st =
1103         (util_ldap_state_t *)ap_get_module_config(r->server->module_config,
1104         &ldap_module);
1105
1106     /* Get the cache node for this url */
1107     LDAP_CACHE_LOCK();
1108     curnode.url = url;
1109     curl = (util_url_node_t *)util_ald_cache_fetch(st->util_ldap_cache,
1110                                                    &curnode);
1111     if (curl == NULL) {
1112         curl = util_ald_create_caches(st, url);
1113     }
1114     LDAP_CACHE_UNLOCK();
1115
1116     if (curl) {
1117         LDAP_CACHE_LOCK();
1118         the_search_node.username = filter;
1119         search_nodep = util_ald_cache_fetch(curl->search_cache,
1120                                             &the_search_node);
1121         if (search_nodep != NULL) {
1122
1123             /* found entry in search cache... */
1124             curtime = apr_time_now();
1125
1126             /*
1127              * Remove this item from the cache if its expired.
1128              */
1129             if ((curtime - search_nodep->lastbind) > st->search_cache_ttl) {
1130                 /* ...but entry is too old */
1131                 util_ald_cache_remove(curl->search_cache, search_nodep);
1132             }
1133             else {
1134                 /* ...and entry is valid */
1135                 *binddn = search_nodep->dn;
1136                 *retvals = search_nodep->vals;
1137                 LDAP_CACHE_UNLOCK();
1138                 ldc->reason = "Search successful (cached)";
1139                 return LDAP_SUCCESS;
1140             }
1141         }
1142         /* unlock this read lock */
1143         LDAP_CACHE_UNLOCK();
1144     }
1145
1146     /*
1147      * At this point, there is no valid cached search, so lets do the search.
1148      */
1149
1150     /*
1151      * If LDAP operation fails due to LDAP_SERVER_DOWN, control returns here.
1152      */
1153 start_over:
1154     if (failures++ > 10) {
1155         return result;
1156     }
1157     if (LDAP_SUCCESS != (result = uldap_connection_open(r, ldc))) {
1158         return result;
1159     }
1160
1161     /* try do the search */
1162     if ((result = ldap_search_ext_s(ldc->ldap,
1163                                     (char *)basedn, scope,
1164                                     (char *)filter, attrs, 0,
1165                                     NULL, NULL, NULL, -1, &res))
1166             == LDAP_SERVER_DOWN)
1167     {
1168         ldc->reason = "ldap_search_ext_s() for user failed with server down";
1169         uldap_connection_unbind(ldc);
1170         goto start_over;
1171     }
1172
1173     /* if there is an error (including LDAP_NO_SUCH_OBJECT) return now */
1174     if (result != LDAP_SUCCESS) {
1175         ldc->reason = "ldap_search_ext_s() for user failed";
1176         return result;
1177     }
1178
1179     /*
1180      * We should have found exactly one entry; to find a different
1181      * number is an error.
1182      */
1183     count = ldap_count_entries(ldc->ldap, res);
1184     if (count != 1)
1185     {
1186         if (count == 0 )
1187             ldc->reason = "User not found";
1188         else
1189             ldc->reason = "User is not unique (search found two "
1190                           "or more matches)";
1191         ldap_msgfree(res);
1192         return LDAP_NO_SUCH_OBJECT;
1193     }
1194
1195     entry = ldap_first_entry(ldc->ldap, res);
1196
1197     /* Grab the dn, copy it into the pool, and free it again */
1198     dn = ldap_get_dn(ldc->ldap, entry);
1199     *binddn = apr_pstrdup(r->pool, dn);
1200     ldap_memfree(dn);
1201
1202     /*
1203      * Get values for the provided attributes.
1204      */
1205     if (attrs) {
1206         int k = 0;
1207         int i = 0;
1208         while (attrs[k++]);
1209         vals = apr_pcalloc(r->pool, sizeof(char *) * (k+1));
1210         numvals = k;
1211         while (attrs[i]) {
1212             char **values;
1213             int j = 0;
1214             char *str = NULL;
1215             /* get values */
1216             values = ldap_get_values(ldc->ldap, entry, attrs[i]);
1217             while (values && values[j]) {
1218                 str = str ? apr_pstrcat(r->pool, str, "; ", values[j], NULL)
1219                           : apr_pstrdup(r->pool, values[j]);
1220                 j++;
1221             }
1222             ldap_value_free(values);
1223             vals[i] = str;
1224             i++;
1225         }
1226         *retvals = vals;
1227     }
1228
1229     /*
1230      * Add the new username to the search cache.
1231      */
1232     if (curl) {
1233         LDAP_CACHE_LOCK();
1234         the_search_node.username = filter;
1235         the_search_node.dn = *binddn;
1236         the_search_node.bindpw = NULL;
1237         the_search_node.lastbind = apr_time_now();
1238         the_search_node.vals = vals;
1239         the_search_node.numvals = numvals;
1240
1241         /* Search again to make sure that another thread didn't ready insert
1242          * this node into the cache before we got here. If it does exist then
1243          * update the lastbind
1244          */
1245         search_nodep = util_ald_cache_fetch(curl->search_cache,
1246                                             &the_search_node);
1247         if ((search_nodep == NULL) ||
1248             (strcmp(*binddn, search_nodep->dn) != 0)) {
1249
1250             /* Nothing in cache, insert new entry */
1251             util_ald_cache_insert(curl->search_cache, &the_search_node);
1252         }
1253         /*
1254          * Don't update lastbind on entries with bindpw because
1255          * we haven't verified that password. It's OK to update
1256          * the entry if there is no password in it.
1257          */
1258         else if (!search_nodep->bindpw) {
1259             /* Cache entry is valid, update lastbind */
1260             search_nodep->lastbind = the_search_node.lastbind;
1261         }
1262         LDAP_CACHE_UNLOCK();
1263     }
1264
1265     ldap_msgfree(res);
1266
1267     ldc->reason = "Search successful";
1268     return LDAP_SUCCESS;
1269 }
1270
1271 /*
1272  * Reports if ssl support is enabled
1273  *
1274  * 1 = enabled, 0 = not enabled
1275  */
1276 static int uldap_ssl_supported(request_rec *r)
1277 {
1278    util_ldap_state_t *st = (util_ldap_state_t *)ap_get_module_config(
1279                                 r->server->module_config, &ldap_module);
1280
1281    return(st->ssl_supported);
1282 }
1283
1284
1285 /* ---------------------------------------- */
1286 /* config directives */
1287
1288
1289 static const char *util_ldap_set_cache_bytes(cmd_parms *cmd, void *dummy,
1290                                              const char *bytes)
1291 {
1292     util_ldap_state_t *st =
1293         (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config,
1294                                                   &ldap_module);
1295     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1296
1297     if (err != NULL) {
1298         return err;
1299     }
1300
1301     st->cache_bytes = atol(bytes);
1302
1303     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server,
1304                  "[%" APR_PID_T_FMT "] ldap cache: Setting shared memory "
1305                  " cache size to %" APR_SIZE_T_FMT " bytes.",
1306                  getpid(), st->cache_bytes);
1307
1308     return NULL;
1309 }
1310
1311 static const char *util_ldap_set_cache_file(cmd_parms *cmd, void *dummy,
1312                                             const char *file)
1313 {
1314     util_ldap_state_t *st =
1315         (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config,
1316                                                   &ldap_module);
1317     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1318
1319     if (err != NULL) {
1320         return err;
1321     }
1322
1323     if (file) {
1324         st->cache_file = ap_server_root_relative(st->pool, file);
1325     }
1326     else {
1327         st->cache_file = NULL;
1328     }
1329
1330     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server,
1331                  "LDAP cache: Setting shared memory cache file to %s bytes.",
1332                  st->cache_file);
1333
1334     return NULL;
1335 }
1336
1337 static const char *util_ldap_set_cache_ttl(cmd_parms *cmd, void *dummy,
1338                                            const char *ttl)
1339 {
1340     util_ldap_state_t *st =
1341         (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config,
1342                                                   &ldap_module);
1343     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1344
1345     if (err != NULL) {
1346         return err;
1347     }
1348
1349     st->search_cache_ttl = atol(ttl) * 1000000;
1350
1351     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server,
1352                  "[%" APR_PID_T_FMT "] ldap cache: Setting cache TTL to %ld microseconds.",
1353                  getpid(), st->search_cache_ttl);
1354
1355     return NULL;
1356 }
1357
1358 static const char *util_ldap_set_cache_entries(cmd_parms *cmd, void *dummy,
1359                                                const char *size)
1360 {
1361     util_ldap_state_t *st =
1362         (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config,
1363                                                   &ldap_module);
1364     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1365
1366     if (err != NULL) {
1367         return err;
1368     }
1369
1370     st->search_cache_size = atol(size);
1371     if (st->search_cache_size < 0) {
1372         st->search_cache_size = 0;
1373     }
1374
1375     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server,
1376                  "[%" APR_PID_T_FMT "] ldap cache: Setting search cache size to %ld entries.",
1377                  getpid(), st->search_cache_size);
1378
1379     return NULL;
1380 }
1381
1382 static const char *util_ldap_set_opcache_ttl(cmd_parms *cmd, void *dummy,
1383                                              const char *ttl)
1384 {
1385     util_ldap_state_t *st =
1386         (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config,
1387                                                   &ldap_module);
1388     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1389
1390     if (err != NULL) {
1391         return err;
1392     }
1393
1394     st->compare_cache_ttl = atol(ttl) * 1000000;
1395
1396     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server,
1397                  "[%" APR_PID_T_FMT "] ldap cache: Setting operation cache TTL to %ld microseconds.",
1398                  getpid(), st->compare_cache_ttl);
1399
1400     return NULL;
1401 }
1402
1403 static const char *util_ldap_set_opcache_entries(cmd_parms *cmd, void *dummy,
1404                                                  const char *size)
1405 {
1406     util_ldap_state_t *st =
1407         (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config,
1408                                                   &ldap_module);
1409     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1410
1411     if (err != NULL) {
1412         return err;
1413     }
1414
1415     st->compare_cache_size = atol(size);
1416     if (st->compare_cache_size < 0) {
1417         st->compare_cache_size = 0;
1418     }
1419
1420     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server,
1421                  "[%" APR_PID_T_FMT "] ldap cache: Setting operation cache size to %ld "
1422                  "entries.", getpid(), st->compare_cache_size);
1423
1424     return NULL;
1425 }
1426
1427
1428 /**
1429  * Parse the certificate type.
1430  *
1431  * The type can be one of the following:
1432  * CA_DER, CA_BASE64, CA_CERT7_DB, CA_SECMOD, CERT_DER, CERT_BASE64,
1433  * CERT_KEY3_DB, CERT_NICKNAME, KEY_DER, KEY_BASE64
1434  *
1435  * If no matches are found, APR_LDAP_CA_TYPE_UNKNOWN is returned.
1436  */
1437 static int util_ldap_parse_cert_type(const char *type)
1438 {
1439     /* Authority file in binary DER format */
1440     if (0 == strcasecmp("CA_DER", type)) {
1441         return APR_LDAP_CA_TYPE_DER;
1442     }
1443
1444     /* Authority file in Base64 format */
1445     else if (0 == strcasecmp("CA_BASE64", type)) {
1446         return APR_LDAP_CA_TYPE_BASE64;
1447     }
1448
1449     /* Netscape certificate database file/directory */
1450     else if (0 == strcasecmp("CA_CERT7_DB", type)) {
1451         return APR_LDAP_CA_TYPE_CERT7_DB;
1452     }
1453
1454     /* Netscape secmod file/directory */
1455     else if (0 == strcasecmp("CA_SECMOD", type)) {
1456         return APR_LDAP_CA_TYPE_SECMOD;
1457     }
1458
1459     /* Client cert file in DER format */
1460     else if (0 == strcasecmp("CERT_DER", type)) {
1461         return APR_LDAP_CERT_TYPE_DER;
1462     }
1463
1464     /* Client cert file in Base64 format */
1465     else if (0 == strcasecmp("CERT_BASE64", type)) {
1466         return APR_LDAP_CERT_TYPE_BASE64;
1467     }
1468
1469     /* Client cert file in PKCS#12 format */
1470     else if (0 == strcasecmp("CERT_PFX", type)) {
1471         return APR_LDAP_CERT_TYPE_PFX;
1472     }
1473
1474     /* Netscape client cert database file/directory */
1475     else if (0 == strcasecmp("CERT_KEY3_DB", type)) {
1476         return APR_LDAP_CERT_TYPE_KEY3_DB;
1477     }
1478
1479     /* Netscape client cert nickname */
1480     else if (0 == strcasecmp("CERT_NICKNAME", type)) {
1481         return APR_LDAP_CERT_TYPE_NICKNAME;
1482     }
1483
1484     /* Client cert key file in DER format */
1485     else if (0 == strcasecmp("KEY_DER", type)) {
1486         return APR_LDAP_KEY_TYPE_DER;
1487     }
1488
1489     /* Client cert key file in Base64 format */
1490     else if (0 == strcasecmp("KEY_BASE64", type)) {
1491         return APR_LDAP_KEY_TYPE_BASE64;
1492     }
1493
1494     /* Client cert key file in PKCS#12 format */
1495     else if (0 == strcasecmp("KEY_PFX", type)) {
1496         return APR_LDAP_KEY_TYPE_PFX;
1497     }
1498
1499     else {
1500         return APR_LDAP_CA_TYPE_UNKNOWN;
1501     }
1502
1503 }
1504
1505
1506 /**
1507  * Set LDAPTrustedGlobalCert.
1508  *
1509  * This directive takes either two or three arguments:
1510  * - certificate type
1511  * - certificate file / directory / nickname
1512  * - certificate password (optional)
1513  *
1514  * This directive may only be used globally.
1515  */
1516 static const char *util_ldap_set_trusted_global_cert(cmd_parms *cmd,
1517                                                      void *dummy,
1518                                                      const char *type,
1519                                                      const char *file,
1520                                                      const char *password)
1521 {
1522     util_ldap_state_t *st =
1523         (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config,
1524                                                   &ldap_module);
1525     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1526     apr_finfo_t finfo;
1527     apr_status_t rv;
1528     int cert_type = 0;
1529     apr_ldap_opt_tls_cert_t *cert;
1530
1531     if (err != NULL) {
1532         return err;
1533     }
1534
1535     /* handle the certificate type */
1536     if (type) {
1537         cert_type = util_ldap_parse_cert_type(type);
1538         if (APR_LDAP_CA_TYPE_UNKNOWN == cert_type) {
1539            return apr_psprintf(cmd->pool, "The certificate type %s is "
1540                                           "not recognised. It should be one "
1541                                           "of CA_DER, CA_BASE64, CA_CERT7_DB, "
1542                                           "CA_SECMOD, CERT_DER, CERT_BASE64, "
1543                                           "CERT_KEY3_DB, CERT_NICKNAME, "
1544                                           "KEY_DER, KEY_BASE64", type);
1545         }
1546     }
1547     else {
1548         return "Certificate type was not specified.";
1549     }
1550
1551     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server,
1552                       "LDAP: SSL trusted global cert - %s (type %s)",
1553                        file, type);
1554
1555     /* add the certificate to the global array */
1556     cert = (apr_ldap_opt_tls_cert_t *)apr_array_push(st->global_certs);
1557     cert->type = cert_type;
1558     cert->path = file;
1559     cert->password = password;
1560
1561     /* if file is a file or path, fix the path */
1562     if (cert_type != APR_LDAP_CA_TYPE_UNKNOWN &&
1563         cert_type != APR_LDAP_CERT_TYPE_NICKNAME) {
1564
1565         cert->path = ap_server_root_relative(cmd->pool, file);
1566         if (cert->path &&
1567             ((rv = apr_stat (&finfo, cert->path, APR_FINFO_MIN, cmd->pool))
1568                 != APR_SUCCESS))
1569         {
1570             ap_log_error(APLOG_MARK, APLOG_ERR, rv, cmd->server,
1571                          "LDAP: Could not open SSL trusted certificate "
1572                          "authority file - %s",
1573                          cert->path == NULL ? file : cert->path);
1574             return "Invalid global certificate file path";
1575         }
1576     }
1577
1578     return(NULL);
1579 }
1580
1581
1582 /**
1583  * Set LDAPTrustedClientCert.
1584  *
1585  * This directive takes either two or three arguments:
1586  * - certificate type
1587  * - certificate file / directory / nickname
1588  * - certificate password (optional)
1589  */
1590 static const char *util_ldap_set_trusted_client_cert(cmd_parms *cmd,
1591                                                      void *config,
1592                                                      const char *type,
1593                                                      const char *file,
1594                                                      const char *password)
1595 {
1596     util_ldap_state_t *st =
1597         (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config,
1598                                                   &ldap_module);
1599     apr_finfo_t finfo;
1600     apr_status_t rv;
1601     int cert_type = 0;
1602     apr_ldap_opt_tls_cert_t *cert;
1603
1604     /* handle the certificate type */
1605     if (type) {
1606         cert_type = util_ldap_parse_cert_type(type);
1607         if (APR_LDAP_CA_TYPE_UNKNOWN == cert_type) {
1608             return apr_psprintf(cmd->pool, "The certificate type \"%s\" is "
1609                                            "not recognised. It should be one "
1610                                            "of CERT_DER, CERT_BASE64, "
1611                                            "CERT_NICKNAME, CERT_PFX,"
1612                                            "KEY_DER, KEY_BASE64, KEY_PFX",
1613                                            type);
1614         }
1615         else if (APR_LDAP_CA_TYPE_DER == cert_type ||
1616                  APR_LDAP_CA_TYPE_BASE64 == cert_type ||
1617                  APR_LDAP_CA_TYPE_CERT7_DB == cert_type ||
1618                  APR_LDAP_CA_TYPE_SECMOD == cert_type ||
1619                  APR_LDAP_CERT_TYPE_PFX == cert_type ||
1620                  APR_LDAP_CERT_TYPE_KEY3_DB == cert_type) {
1621             return apr_psprintf(cmd->pool, "The certificate type \"%s\" is "
1622                                            "only valid within a "
1623                                            "LDAPTrustedGlobalCert directive. "
1624                                            "Only CERT_DER, CERT_BASE64, "
1625                                            "CERT_NICKNAME, KEY_DER, and "
1626                                            "KEY_BASE64 may be used.", type);
1627         }
1628     }
1629     else {
1630         return "Certificate type was not specified.";
1631     }
1632
1633     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server,
1634                       "LDAP: SSL trusted client cert - %s (type %s)",
1635                        file, type);
1636
1637     /* add the certificate to the global array */
1638     cert = (apr_ldap_opt_tls_cert_t *)apr_array_push(st->global_certs);
1639     cert->type = cert_type;
1640     cert->path = file;
1641     cert->password = password;
1642
1643     /* if file is a file or path, fix the path */
1644     if (cert_type != APR_LDAP_CA_TYPE_UNKNOWN &&
1645         cert_type != APR_LDAP_CERT_TYPE_NICKNAME) {
1646
1647         cert->path = ap_server_root_relative(cmd->pool, file);
1648         if (cert->path &&
1649             ((rv = apr_stat (&finfo, cert->path, APR_FINFO_MIN, cmd->pool))
1650                 != APR_SUCCESS))
1651         {
1652             ap_log_error(APLOG_MARK, APLOG_ERR, rv, cmd->server,
1653                          "LDAP: Could not open SSL client certificate "
1654                          "file - %s",
1655                          cert->path == NULL ? file : cert->path);
1656             return "Invalid client certificate file path";
1657         }
1658
1659     }
1660
1661     return(NULL);
1662 }
1663
1664
1665 /**
1666  * Set LDAPTrustedMode.
1667  *
1668  * This directive sets what encryption mode to use on a connection:
1669  * - None (No encryption)
1670  * - SSL (SSL encryption)
1671  * - STARTTLS (TLS encryption)
1672  */
1673 static const char *util_ldap_set_trusted_mode(cmd_parms *cmd, void *dummy,
1674                                               const char *mode)
1675 {
1676     util_ldap_state_t *st =
1677     (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config,
1678                                               &ldap_module);
1679
1680     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server,
1681                       "LDAP: SSL trusted mode - %s",
1682                        mode);
1683
1684     if (0 == strcasecmp("NONE", mode)) {
1685         st->secure = APR_LDAP_NONE;
1686     }
1687     else if (0 == strcasecmp("SSL", mode)) {
1688         st->secure = APR_LDAP_SSL;
1689     }
1690     else if (   (0 == strcasecmp("TLS", mode))
1691              || (0 == strcasecmp("STARTTLS", mode))) {
1692         st->secure = APR_LDAP_STARTTLS;
1693     }
1694     else {
1695         return "Invalid LDAPTrustedMode setting: must be one of NONE, "
1696                "SSL, or TLS/STARTTLS";
1697     }
1698
1699     st->secure_set = 1;
1700     return(NULL);
1701 }
1702
1703 static const char *util_ldap_set_verify_srv_cert(cmd_parms *cmd,
1704                                                  void *dummy,
1705                                                  int mode)
1706 {
1707     util_ldap_state_t *st =
1708     (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config,
1709                                               &ldap_module);
1710
1711     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server,
1712                       "LDAP: SSL verify server certificate - %s",
1713                       mode?"TRUE":"FALSE");
1714
1715     st->verify_svr_cert = mode;
1716
1717     return(NULL);
1718 }
1719
1720
1721 static const char *util_ldap_set_connection_timeout(cmd_parms *cmd,
1722                                                     void *dummy,
1723                                                     const char *ttl)
1724 {
1725     util_ldap_state_t *st =
1726         (util_ldap_state_t *)ap_get_module_config(cmd->server->module_config,
1727                                                   &ldap_module);
1728
1729 #ifdef LDAP_OPT_NETWORK_TIMEOUT
1730     st->connectionTimeout = atol(ttl);
1731
1732     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server,
1733                  "[%" APR_PID_T_FMT "] ldap connection: Setting connection timeout to "
1734                  "%ld seconds.", getpid(), st->connectionTimeout);
1735 #else
1736     ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, cmd->server,
1737                  "LDAP: Connection timout option not supported by the "
1738                  "LDAP SDK in use." );
1739 #endif
1740
1741     return NULL;
1742 }
1743
1744
1745 static void *util_ldap_create_config(apr_pool_t *p, server_rec *s)
1746 {
1747     util_ldap_state_t *st =
1748         (util_ldap_state_t *)apr_pcalloc(p, sizeof(util_ldap_state_t));
1749
1750     /* Create a pool for mod_ldap to use */
1751     apr_pool_create(&st->pool, p);
1752 #if APR_HAS_THREADS
1753     apr_thread_mutex_create(&st->mutex, APR_THREAD_MUTEX_DEFAULT, st->pool);
1754 #endif
1755
1756     st->cache_bytes = 100000;
1757     st->search_cache_ttl = 600000000;
1758     st->search_cache_size = 1024;
1759     st->compare_cache_ttl = 600000000;
1760     st->compare_cache_size = 1024;
1761     st->connections = NULL;
1762     st->ssl_supported = 0;
1763     st->global_certs = apr_array_make(p, 10, sizeof(apr_ldap_opt_tls_cert_t));
1764     st->client_certs = apr_array_make(p, 10, sizeof(apr_ldap_opt_tls_cert_t));
1765     st->secure = APR_LDAP_NONE;
1766     st->secure_set = 0;
1767     st->connectionTimeout = 10;
1768     st->verify_svr_cert = 1;
1769
1770     return st;
1771 }
1772
1773 static void *util_ldap_merge_config(apr_pool_t *p, void *basev,
1774                                     void *overridesv)
1775 {
1776     util_ldap_state_t *st = apr_pcalloc(p, sizeof(util_ldap_state_t));
1777     util_ldap_state_t *base = (util_ldap_state_t *) basev;
1778     util_ldap_state_t *overrides = (util_ldap_state_t *) overridesv;
1779
1780     st->pool = overrides->pool;
1781 #if APR_HAS_THREADS
1782     st->mutex = overrides->mutex;
1783 #endif
1784
1785     /* The cache settings can not be modified in a 
1786         virtual host since all server use the same
1787         shared memory cache. */
1788     st->cache_bytes = base->cache_bytes;
1789     st->search_cache_ttl = base->search_cache_ttl;
1790     st->search_cache_size = base->search_cache_size;
1791     st->compare_cache_ttl = base->compare_cache_ttl;
1792     st->compare_cache_size = base->compare_cache_size;
1793
1794     st->connections = NULL;
1795     st->ssl_supported = 0;
1796     st->global_certs = apr_array_append(p, base->global_certs,
1797                                            overrides->global_certs);
1798     st->client_certs = apr_array_append(p, base->client_certs,
1799                                            overrides->client_certs);
1800     st->secure = (overrides->secure_set == 0) ? base->secure
1801                                               : overrides->secure;
1802
1803     /* LDAP connection settings can be overwritten in a virtual host */
1804     st->connectionTimeout = (overrides->connectionTimeout == 10) 
1805                                 ? base->connectionTimeout
1806                                 : overrides->connectionTimeout;
1807     st->verify_svr_cert = (overrides->verify_svr_cert == 1) 
1808                                 ? base->verify_svr_cert
1809                                 : overrides->verify_svr_cert;
1810
1811     return st;
1812 }
1813
1814 static apr_status_t util_ldap_cleanup_module(void *data)
1815 {
1816
1817     server_rec *s = data;
1818     util_ldap_state_t *st = (util_ldap_state_t *)ap_get_module_config(
1819         s->module_config, &ldap_module);
1820
1821     if (st->ssl_supported) {
1822         apr_ldap_ssl_deinit();
1823     }
1824
1825     return APR_SUCCESS;
1826
1827 }
1828
1829 static int util_ldap_post_config(apr_pool_t *p, apr_pool_t *plog,
1830                                  apr_pool_t *ptemp, server_rec *s)
1831 {
1832     apr_status_t result;
1833     server_rec *s_vhost;
1834     util_ldap_state_t *st_vhost;
1835
1836     util_ldap_state_t *st = (util_ldap_state_t *)
1837                             ap_get_module_config(s->module_config,
1838                                                  &ldap_module);
1839
1840     void *data;
1841     const char *userdata_key = "util_ldap_init";
1842     apr_ldap_err_t *result_err = NULL;
1843     int rc;
1844
1845     /* util_ldap_post_config() will be called twice. Don't bother
1846      * going through all of the initialization on the first call
1847      * because it will just be thrown away.*/
1848     apr_pool_userdata_get(&data, userdata_key, s->process->pool);
1849     if (!data) {
1850         apr_pool_userdata_set((const void *)1, userdata_key,
1851                                apr_pool_cleanup_null, s->process->pool);
1852
1853 #if APR_HAS_SHARED_MEMORY
1854         /* If the cache file already exists then delete it.  Otherwise we are
1855          * going to run into problems creating the shared memory. */
1856         if (st->cache_file) {
1857             char *lck_file = apr_pstrcat(ptemp, st->cache_file, ".lck",
1858                                          NULL);
1859             apr_file_remove(lck_file, ptemp);
1860         }
1861 #endif
1862         return OK;
1863     }
1864
1865 #if APR_HAS_SHARED_MEMORY
1866     /* initializing cache if shared memory size is not zero and we already
1867      * don't have shm address
1868      */
1869     if (!st->cache_shm && st->cache_bytes > 0) {
1870 #endif
1871         result = util_ldap_cache_init(p, st);
1872         if (result != APR_SUCCESS) {
1873             ap_log_error(APLOG_MARK, APLOG_ERR, result, s,
1874                          "LDAP cache: could not create shared memory segment");
1875             return DONE;
1876         }
1877
1878
1879 #if APR_HAS_SHARED_MEMORY
1880         if (st->cache_file) {
1881             st->lock_file = apr_pstrcat(st->pool, st->cache_file, ".lck",
1882                                         NULL);
1883         }
1884 #endif
1885
1886         result = apr_global_mutex_create(&st->util_ldap_cache_lock,
1887                                          st->lock_file, APR_LOCK_DEFAULT,
1888                                          st->pool);
1889         if (result != APR_SUCCESS) {
1890             return result;
1891         }
1892
1893 #ifdef AP_NEED_SET_MUTEX_PERMS
1894         result = unixd_set_global_mutex_perms(st->util_ldap_cache_lock);
1895         if (result != APR_SUCCESS) {
1896             ap_log_error(APLOG_MARK, APLOG_CRIT, result, s,
1897                          "LDAP cache: failed to set mutex permissions");
1898             return result;
1899         }
1900 #endif
1901
1902         /* merge config in all vhost */
1903         s_vhost = s->next;
1904         while (s_vhost) {
1905             st_vhost = (util_ldap_state_t *)
1906                        ap_get_module_config(s_vhost->module_config,
1907                                             &ldap_module);
1908
1909 #if APR_HAS_SHARED_MEMORY
1910             st_vhost->cache_shm = st->cache_shm;
1911             st_vhost->cache_rmm = st->cache_rmm;
1912             st_vhost->cache_file = st->cache_file;
1913             ap_log_error(APLOG_MARK, APLOG_DEBUG, result, s,
1914                          "LDAP merging Shared Cache conf: shm=0x%pp rmm=0x%pp "
1915                          "for VHOST: %s", st->cache_shm, st->cache_rmm,
1916                          s_vhost->server_hostname);
1917 #endif
1918             st_vhost->lock_file = st->lock_file;
1919             s_vhost = s_vhost->next;
1920         }
1921 #if APR_HAS_SHARED_MEMORY
1922     }
1923     else {
1924         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
1925                      "LDAP cache: LDAPSharedCacheSize is zero, disabling "
1926                      "shared memory cache");
1927     }
1928 #endif
1929
1930     /* log the LDAP SDK used
1931      */
1932     {
1933         apr_ldap_err_t *result = NULL;
1934         apr_ldap_info(p, &(result));
1935         if (result != NULL) {
1936             ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, "%s", result->reason);
1937         }
1938     }
1939
1940     apr_pool_cleanup_register(p, s, util_ldap_cleanup_module,
1941                               util_ldap_cleanup_module);
1942
1943     /*
1944      * Initialize SSL support, and log the result for the benefit of the admin.
1945      *
1946      * If SSL is not supported it is not necessarily an error, as the
1947      * application may not want to use it.
1948      */
1949     rc = apr_ldap_ssl_init(p,
1950                       NULL,
1951                       0,
1952                       &(result_err));
1953     if (APR_SUCCESS == rc) {
1954         rc = apr_ldap_set_option(p, NULL, APR_LDAP_OPT_TLS_CERT,
1955                                  (void *)st->global_certs, &(result_err));
1956     }
1957
1958     if (APR_SUCCESS == rc) {
1959         st->ssl_supported = 1;
1960         ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
1961                      "LDAP: SSL support available" );
1962     }
1963     else {
1964         st->ssl_supported = 0;
1965         ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
1966                      "LDAP: SSL support unavailable%s%s",
1967                      result_err ? ": " : "",
1968                      result_err ? result_err->reason : "");
1969     }
1970
1971     return(OK);
1972 }
1973
1974 static void util_ldap_child_init(apr_pool_t *p, server_rec *s)
1975 {
1976     apr_status_t sts;
1977     util_ldap_state_t *st = ap_get_module_config(s->module_config,
1978                                                  &ldap_module);
1979
1980     if (!st->util_ldap_cache_lock) return;
1981
1982     sts = apr_global_mutex_child_init(&st->util_ldap_cache_lock,
1983                                       st->lock_file, p);
1984     if (sts != APR_SUCCESS) {
1985         ap_log_error(APLOG_MARK, APLOG_CRIT, sts, s,
1986                      "Failed to initialise global mutex %s in child process %"
1987                      APR_PID_T_FMT ".",
1988                      st->lock_file, getpid());
1989     }
1990 }
1991
1992 static const command_rec util_ldap_cmds[] = {
1993     AP_INIT_TAKE1("LDAPSharedCacheSize", util_ldap_set_cache_bytes,
1994                   NULL, RSRC_CONF,
1995                   "Set the size of the shared memory cache (in bytes). Use "
1996                   "0 to disable the shared memory cache. (default: 100000)"),
1997
1998     AP_INIT_TAKE1("LDAPSharedCacheFile", util_ldap_set_cache_file,
1999                   NULL, RSRC_CONF,
2000                   "Set the file name for the shared memory cache."),
2001
2002     AP_INIT_TAKE1("LDAPCacheEntries", util_ldap_set_cache_entries,
2003                   NULL, RSRC_CONF,
2004                   "Set the maximum number of entries that are possible in the "
2005                   "LDAP search cache. Use 0 for no limit. "
2006                   "-1 disables the cache. (default: 1024)"),
2007
2008     AP_INIT_TAKE1("LDAPCacheTTL", util_ldap_set_cache_ttl,
2009                   NULL, RSRC_CONF,
2010                   "Set the maximum time (in seconds) that an item can be "
2011                   "cached in the LDAP search cache. Use 0 for no limit. "
2012                   "(default 600)"),
2013
2014     AP_INIT_TAKE1("LDAPOpCacheEntries", util_ldap_set_opcache_entries,
2015                   NULL, RSRC_CONF,
2016                   "Set the maximum number of entries that are possible "
2017                   "in the LDAP compare cache. Use 0 for no limit. "
2018                   "Use -1 to disable the cache. (default: 1024)"),
2019
2020     AP_INIT_TAKE1("LDAPOpCacheTTL", util_ldap_set_opcache_ttl,
2021                   NULL, RSRC_CONF,
2022                   "Set the maximum time (in seconds) that an item is cached "
2023                   "in the LDAP operation cache. Use 0 for no limit. "
2024                   "(default: 600)"),
2025
2026     AP_INIT_TAKE23("LDAPTrustedGlobalCert", util_ldap_set_trusted_global_cert,
2027                    NULL, RSRC_CONF,
2028                    "Takes three args; the file and/or directory containing "
2029                    "the trusted CA certificates (and global client certs "
2030                    "for Netware) used to validate the LDAP server.  Second "
2031                    "arg is the cert type for the first arg, one of CA_DER, "
2032                    "CA_BASE64, CA_CERT7_DB, CA_SECMOD, CERT_DER, CERT_BASE64, "
2033                    "CERT_KEY3_DB, CERT_NICKNAME, KEY_DER, or KEY_BASE64. "
2034                    "Third arg is an optional passphrase if applicable."),
2035
2036     AP_INIT_TAKE23("LDAPTrustedClientCert", util_ldap_set_trusted_client_cert,
2037                    NULL, RSRC_CONF,
2038                    "Takes three args; the file and/or directory containing "
2039                    "the client certificate, or certificate ID used to "
2040                    "validate this LDAP client.  Second arg is the cert type "
2041                    "for the first arg, one of CA_DER, CA_BASE64, CA_CERT7_DB, "
2042                    "CA_SECMOD, CERT_DER, CERT_BASE64, CERT_KEY3_DB, "
2043                    "CERT_NICKNAME, KEY_DER, or KEY_BASE64. Third arg is an "
2044                    "optional passphrase if applicable."),
2045
2046     AP_INIT_TAKE1("LDAPTrustedMode", util_ldap_set_trusted_mode,
2047                   NULL, RSRC_CONF,
2048                   "Specify the type of security that should be applied to "
2049                   "an LDAP connection. One of; NONE, SSL or STARTTLS."),
2050
2051     AP_INIT_FLAG("LDAPVerifyServerCert", util_ldap_set_verify_srv_cert,
2052                   NULL, RSRC_CONF,
2053                   "Set to 'ON' requires that the server certificate be verified "
2054                   "before a secure LDAP connection can be establish.  Default 'ON'"),
2055
2056     AP_INIT_TAKE1("LDAPConnectionTimeout", util_ldap_set_connection_timeout,
2057                   NULL, RSRC_CONF,
2058                   "Specify the LDAP socket connection timeout in seconds "
2059                   "(default: 10)"),
2060
2061     {NULL}
2062 };
2063
2064 static void util_ldap_register_hooks(apr_pool_t *p)
2065 {
2066     APR_REGISTER_OPTIONAL_FN(uldap_connection_open);
2067     APR_REGISTER_OPTIONAL_FN(uldap_connection_close);
2068     APR_REGISTER_OPTIONAL_FN(uldap_connection_unbind);
2069     APR_REGISTER_OPTIONAL_FN(uldap_connection_cleanup);
2070     APR_REGISTER_OPTIONAL_FN(uldap_connection_find);
2071     APR_REGISTER_OPTIONAL_FN(uldap_cache_comparedn);
2072     APR_REGISTER_OPTIONAL_FN(uldap_cache_compare);
2073     APR_REGISTER_OPTIONAL_FN(uldap_cache_checkuserid);
2074     APR_REGISTER_OPTIONAL_FN(uldap_cache_getuserdn);
2075     APR_REGISTER_OPTIONAL_FN(uldap_ssl_supported);
2076
2077     ap_hook_post_config(util_ldap_post_config,NULL,NULL,APR_HOOK_MIDDLE);
2078     ap_hook_handler(util_ldap_handler, NULL, NULL, APR_HOOK_MIDDLE);
2079     ap_hook_child_init(util_ldap_child_init, NULL, NULL, APR_HOOK_MIDDLE);
2080 }
2081
2082 module AP_MODULE_DECLARE_DATA ldap_module = {
2083    STANDARD20_MODULE_STUFF,
2084    NULL,                        /* create dir config */
2085    NULL,                        /* merge dir config */
2086    util_ldap_create_config,     /* create server config */
2087    util_ldap_merge_config,      /* merge server config */
2088    util_ldap_cmds,              /* command table */
2089    util_ldap_register_hooks,    /* set up request processing hooks */
2090 };