]> granicus.if.org Git - apache/blob - modules/proxy/mod_proxy.c
Clean up some bogus error messages.
[apache] / modules / proxy / mod_proxy.c
1 #define FIX_15207
2 /* Copyright 1999-2004 The Apache Software Foundation
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 #define CORE_PRIVATE
18
19 #include "mod_proxy.h"
20 #include "mod_core.h"
21 #include "apr_optional.h"
22 #include "mod_status.h"
23
24 #if (MODULE_MAGIC_NUMBER_MAJOR > 20020903)
25 #include "mod_ssl.h"
26 #else
27 APR_DECLARE_OPTIONAL_FN(int, ssl_proxy_enable, (conn_rec *));
28 APR_DECLARE_OPTIONAL_FN(int, ssl_engine_disable, (conn_rec *));
29 #endif
30
31 #ifndef MAX
32 #define MAX(x,y) ((x) >= (y) ? (x) : (y))
33 #endif
34
35 /*
36  * A Web proxy module. Stages:
37  *
38  *  translate_name: set filename to proxy:<URL>
39  *  map_to_storage: run proxy_walk (rather than directory_walk/file_walk)
40  *                  can't trust directory_walk/file_walk since these are
41  *                  not in our filesystem.  Prevents mod_http from serving
42  *                  the TRACE request we will set aside to handle later.
43  *  type_checker:   set type to PROXY_MAGIC_TYPE if filename begins proxy:
44  *  fix_ups:        convert the URL stored in the filename to the
45  *                  canonical form.
46  *  handler:        handle proxy requests
47  */
48
49 /* -------------------------------------------------------------- */
50 /* Translate the URL into a 'filename' */
51
52 #ifdef FIX_15207
53 /* XXX: EBCDIC safe? --nd */
54 #define x2c(x) (((x >= '0') && (x <= '9'))         \
55                    ? (x - '0')                     \
56                    : (((x >= 'a') && (x <= 'f'))   \
57                        ? (10 + x - 'a')            \
58                        : ((x >= 'A') && (x <='F')) \
59                            ? (10 + x - 'A')        \
60                            : 0                     \
61                      )                             \
62                )
63
64 static unsigned char hex2c(const char* p) {
65   const char c1 = p[1];
66   const char c2 = p[1] ? p[2]: '\0';
67   int i1 = c1 ? x2c(c1) : 0;
68   int i2 = c2 ? x2c(c2) : 0;
69   unsigned char ret = (i1 << 4) | i2;
70
71   return ret;
72 }
73 #endif
74
75 #define PROXY_COPY_CONF_PARAMS(w, c) \
76     do {                             \
77         (w)->timeout              = (c)->timeout;               \
78         (w)->timeout_set          = (c)->timeout_set;           \
79         (w)->recv_buffer_size     = (c)->recv_buffer_size;      \
80         (w)->recv_buffer_size_set = (c)->recv_buffer_size_set;  \
81         (w)->io_buffer_size       = (c)->io_buffer_size;        \
82         (w)->io_buffer_size_set   = (c)->io_buffer_size_set;    \
83     } while (0)
84
85 static const char *set_worker_param(apr_pool_t *p,
86                                     proxy_worker *worker,
87                                     const char *key,
88                                     const char *val)
89 {
90
91     int ival;
92     if (!strcasecmp(key, "loadfactor")) {
93         worker->lbfactor = atoi(val);
94         if (worker->lbfactor < 1 || worker->lbfactor > 100)
95             return "LoadFactor must be number between 1..100";
96     }
97     else if (!strcasecmp(key, "retry")) {
98         ival = atoi(val);
99         if (ival < 1)
100             return "Retry must be at least one second";
101         worker->retry = apr_time_from_sec(ival);
102     }
103     else if (!strcasecmp(key, "ttl")) {
104         ival = atoi(val);
105         if (ival < 1)
106             return "TTL must be at least one second";
107         worker->ttl = apr_time_from_sec(ival);
108     }
109     else if (!strcasecmp(key, "min")) {
110         ival = atoi(val);
111         if (ival < 0)
112             return "Min must be a positive number";
113         worker->min = ival;
114     }
115     else if (!strcasecmp(key, "max")) {
116         ival = atoi(val);
117         if (ival < 0)
118             return "Max must be a positive number";
119         worker->hmax = ival;
120     }
121     /* XXX: More inteligent naming needed */
122     else if (!strcasecmp(key, "smax")) {
123         ival = atoi(val);
124         if (ival < 0)
125             return "Smax must be a positive number";
126         worker->smax = ival;
127     }
128     else if (!strcasecmp(key, "acquire")) {
129         ival = atoi(val);
130         if (ival < 1)
131             return "Acquire must be at least one mili second";
132         worker->acquire = apr_time_make(0, ival * 1000);
133         worker->acquire_set = 1;
134     }
135     else if (!strcasecmp(key, "timeout")) {
136         ival = atoi(val);
137         if (ival < 1)
138             return "Timeout must be at least one second";
139         worker->timeout = apr_time_from_sec(ival);
140         worker->timeout_set = 1;
141     }
142     else if (!strcasecmp(key, "iobuffersize")) {
143         long s = atol(val);
144         worker->io_buffer_size = ((s > AP_IOBUFSIZE) ? s : AP_IOBUFSIZE);
145         worker->io_buffer_size_set = 1;
146     }
147     else if (!strcasecmp(key, "receivebuffersize")) {
148         ival = atoi(val);
149         if (ival < 512 && ival != 0) {
150             return "ReceiveBufferSize must be >= 512 bytes, or 0 for system default.";
151         }
152         worker->recv_buffer_size = ival;
153         worker->recv_buffer_size_set = 1;
154     }
155     else if (!strcasecmp(key, "keepalive")) {
156         if (!strcasecmp(val, "on"))
157             worker->keepalive = 1;
158         else if (!strcasecmp(val, "off"))
159             worker->keepalive = 0;
160         else
161             return "KeepAlive must be On|Off";
162         worker->keepalive_set = 1;
163     }    
164     else if (!strcasecmp(key, "route")) {
165         worker->route = apr_pstrdup(p, val);
166     }
167     else if (!strcasecmp(key, "redirect")) {
168         worker->redirect = apr_pstrdup(p, val);
169     }
170     else {
171         return "unknown parameter";
172     }
173     return NULL;
174 }
175
176 static const char *set_balancer_param(apr_pool_t *p,
177                                       proxy_balancer *balancer,
178                                       const char *key,
179                                       const char *val)
180 {
181
182     int ival;
183     if (!strcasecmp(key, "stickysession")) {
184         balancer->sticky = apr_pstrdup(p, val);
185     }
186     else if (!strcasecmp(key, "nofailover")) {
187         if (!strcasecmp(val, "on"))
188             balancer->sticky_force = 1;
189         else if (!strcasecmp(val, "off"))
190             balancer->sticky_force = 0;
191         else
192             return "failover must be On|Off";
193     }
194     else if (!strcasecmp(key, "timeout")) {
195         ival = atoi(val);
196         if (ival < 1)
197             return "timeout must be at least one second";
198         balancer->timeout = apr_time_from_sec(ival);
199     }
200     else {
201         return "unknown parameter";
202     }
203     return NULL;
204 }
205
206 static int alias_match(const char *uri, const char *alias_fakename)
207 {
208     const char *end_fakename = alias_fakename + strlen(alias_fakename);
209     const char *aliasp = alias_fakename, *urip = uri;
210     const char *end_uri = uri + strlen(uri);
211     unsigned char uric, aliasc;
212
213     while (aliasp < end_fakename && urip < end_uri) {
214         if (*aliasp == '/') {
215             /* any number of '/' in the alias matches any number in
216              * the supplied URI, but there must be at least one...
217              */
218             if (*urip != '/')
219                 return 0;
220
221             while (*aliasp == '/')
222                 ++aliasp;
223             while (*urip == '/')
224                 ++urip;
225         }
226         else {
227 #ifndef FIX_15207
228             /* Other characters are compared literally */
229             if (*urip++ != *aliasp++)
230                 return 0;
231 #else
232             /* Other characters are canonicalised and compared literally */
233             if (*urip == '%') {
234                 uric = hex2c(urip);
235                 urip += 3;
236             } else {
237                 uric = (unsigned char)*urip++;
238             }
239             if (*aliasp == '%') {
240                 aliasc = hex2c(aliasp);
241                 aliasp += 3;
242             } else {
243                 aliasc = (unsigned char)*aliasp++;
244             }
245             if (uric != aliasc) {
246                 return 0;
247             }
248 #endif
249         }
250     }
251
252     /* fixup badly encoded stuff (e.g. % as last character) */
253     if (aliasp > end_fakename) {
254         aliasp = end_fakename;
255     }
256     if (urip > end_uri) {
257         urip = end_uri;
258     }
259
260    /* We reach the end of the uri before the end of "alias_fakename"
261     * for example uri is "/" and alias_fakename "/examples"
262     */
263    if (urip == end_uri && aliasp!=end_fakename) {
264        return 0;
265    }
266
267     /* Check last alias path component matched all the way */
268     if (aliasp[-1] != '/' && *urip != '\0' && *urip != '/')
269         return 0;
270
271     /* Return number of characters from URI which matched (may be
272      * greater than length of alias, since we may have matched
273      * doubled slashes)
274      */
275
276     return urip - uri;
277 }
278
279 /* Detect if an absoluteURI should be proxied or not.  Note that we
280  * have to do this during this phase because later phases are
281  * "short-circuiting"... i.e. translate_names will end when the first
282  * module returns OK.  So for example, if the request is something like:
283  *
284  * GET http://othervhost/cgi-bin/printenv HTTP/1.0
285  *
286  * mod_alias will notice the /cgi-bin part and ScriptAlias it and
287  * short-circuit the proxy... just because of the ordering in the
288  * configuration file.
289  */
290 static int proxy_detect(request_rec *r)
291 {
292     void *sconf = r->server->module_config;
293     proxy_server_conf *conf =
294         (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
295 #ifdef FIX_15207
296     int i, len;
297     struct proxy_alias *ent = (struct proxy_alias *)conf->aliases->elts;
298 #endif
299
300     /* Ick... msvc (perhaps others) promotes ternary short results to int */
301
302     if (conf->req && r->parsed_uri.scheme) {
303         /* but it might be something vhosted */
304         if (!(r->parsed_uri.hostname
305               && !strcasecmp(r->parsed_uri.scheme, ap_http_method(r))
306               && ap_matches_request_vhost(r, r->parsed_uri.hostname,
307                                           (apr_port_t)(r->parsed_uri.port_str ? r->parsed_uri.port 
308                                                        : ap_default_port(r))))) {
309             r->proxyreq = PROXYREQ_PROXY;
310             r->uri = r->unparsed_uri;
311             r->filename = apr_pstrcat(r->pool, "proxy:", r->uri, NULL);
312             r->handler = "proxy-server";
313         }
314     }
315     /* We need special treatment for CONNECT proxying: it has no scheme part */
316     else if (conf->req && r->method_number == M_CONNECT
317              && r->parsed_uri.hostname
318              && r->parsed_uri.port_str) {
319         r->proxyreq = PROXYREQ_PROXY;
320         r->uri = r->unparsed_uri;
321         r->filename = apr_pstrcat(r->pool, "proxy:", r->uri, NULL);
322         r->handler = "proxy-server";
323 #ifdef FIX_15207
324     } else {
325         /* test for a ProxyPass */
326         for (i = 0; i < conf->aliases->nelts; i++) {
327             len = alias_match(r->unparsed_uri, ent[i].fake);
328             if (len > 0) {
329                 r->filename = apr_pstrcat(r->pool, "proxy:", ent[i].real,
330                                           r->unparsed_uri + len, NULL);
331                 r->handler = "proxy-server";
332                 r->proxyreq = PROXYREQ_REVERSE;
333                 r->uri = r->unparsed_uri;
334                 break;
335             }
336         }
337 #endif
338     }
339     return DECLINED;
340 }
341
342 static int proxy_trans(request_rec *r)
343 {
344 #ifndef FIX_15207
345     void *sconf = r->server->module_config;
346     proxy_server_conf *conf =
347     (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
348     int i, len;
349     struct proxy_alias *ent = (struct proxy_alias *) conf->aliases->elts;
350 #endif
351
352     if (r->proxyreq) {
353         /* someone has already set up the proxy, it was possibly ourselves
354          * in proxy_detect
355          */
356         return OK;
357     }
358
359 #ifndef FIX_15207
360     /* XXX: since r->uri has been manipulated already we're not really
361      * compliant with RFC1945 at this point.  But this probably isn't
362      * an issue because this is a hybrid proxy/origin server.
363      */
364
365     for (i = 0; i < conf->aliases->nelts; i++) {
366         len = alias_match(r->uri, ent[i].fake);
367
368        if (len > 0) {
369            if ((ent[i].real[0] == '!') && (ent[i].real[1] == 0)) {
370                return DECLINED;
371            }
372
373            r->filename = apr_pstrcat(r->pool, "proxy:", ent[i].real,
374                                      r->uri + len, NULL);
375            r->handler = "proxy-server";
376            r->proxyreq = PROXYREQ_REVERSE;
377            return OK;
378        }
379     }
380 #endif
381     return DECLINED;
382 }
383
384 static int proxy_walk(request_rec *r)
385 {
386     proxy_server_conf *sconf = ap_get_module_config(r->server->module_config,
387                                                     &proxy_module);
388     ap_conf_vector_t *per_dir_defaults = r->server->lookup_defaults;
389     ap_conf_vector_t **sec_proxy = (ap_conf_vector_t **) sconf->sec_proxy->elts;
390     ap_conf_vector_t *entry_config;
391     proxy_dir_conf *entry_proxy;
392     int num_sec = sconf->sec_proxy->nelts;
393     /* XXX: shouldn't we use URI here?  Canonicalize it first?
394      * Pass over "proxy:" prefix 
395      */
396     const char *proxyname = r->filename + 6;
397     int j;
398
399     for (j = 0; j < num_sec; ++j) 
400     {
401         entry_config = sec_proxy[j];
402         entry_proxy = ap_get_module_config(entry_config, &proxy_module);
403
404         /* XXX: What about case insensitive matching ???
405          * Compare regex, fnmatch or string as appropriate
406          * If the entry doesn't relate, then continue 
407          */
408         if (entry_proxy->r 
409               ? ap_regexec(entry_proxy->r, proxyname, 0, NULL, 0)
410               : (entry_proxy->p_is_fnmatch
411                    ? apr_fnmatch(entry_proxy->p, proxyname, 0)
412                    : strncmp(proxyname, entry_proxy->p, 
413                                         strlen(entry_proxy->p)))) {
414             continue;
415         }
416         per_dir_defaults = ap_merge_per_dir_configs(r->pool, per_dir_defaults,
417                                                              entry_config);
418     }
419
420     r->per_dir_config = per_dir_defaults;
421
422     return OK;
423 }
424
425 static int proxy_map_location(request_rec *r)
426 {
427     int access_status;
428
429     if (!r->proxyreq || !r->filename || strncmp(r->filename, "proxy:", 6) != 0)
430         return DECLINED;
431
432     /* Don't let the core or mod_http map_to_storage hooks handle this,
433      * We don't need directory/file_walk, and we want to TRACE on our own.
434      */
435     if ((access_status = proxy_walk(r))) {
436         ap_die(access_status, r);
437         return access_status;
438     }
439
440     return OK;
441 }
442 #ifndef FIX_15207
443 /* -------------------------------------------------------------- */
444 /* Fixup the filename */
445
446 /*
447  * Canonicalise the URL
448  */
449 static int proxy_fixup(request_rec *r)
450 {
451     char *url, *p;
452     int access_status;
453
454     if (!r->proxyreq || !r->filename || strncmp(r->filename, "proxy:", 6) != 0)
455         return DECLINED;
456
457 #ifdef FIX_15207
458 /* We definitely shouldn't canonicalize a proxy_pass.
459  * But should we really canonicalize a STD_PROXY??? -- Fahree
460  */
461     if (r->proxyreq == PROXYREQ_REVERSE) {
462         return OK;
463     }
464 #endif
465
466     /* XXX: Shouldn't we try this before we run the proxy_walk? */
467     url = &r->filename[6];
468
469     /* canonicalise each specific scheme */
470     if ((access_status = proxy_run_canon_handler(r, url))) {
471         return access_status;
472     }
473
474     p = strchr(url, ':');
475     if (p == NULL || p == url)
476         return HTTP_BAD_REQUEST;
477
478     return OK;          /* otherwise; we've done the best we can */
479 }
480 #endif
481 /* Send a redirection if the request contains a hostname which is not */
482 /* fully qualified, i.e. doesn't have a domain name appended. Some proxy */
483 /* servers like Netscape's allow this and access hosts from the local */
484 /* domain in this case. I think it is better to redirect to a FQDN, since */
485 /* these will later be found in the bookmarks files. */
486 /* The "ProxyDomain" directive determines what domain will be appended */
487 static int proxy_needsdomain(request_rec *r, const char *url, const char *domain)
488 {
489     char *nuri;
490     const char *ref;
491
492     /* We only want to worry about GETs */
493     if (!r->proxyreq || r->method_number != M_GET || !r->parsed_uri.hostname)
494         return DECLINED;
495
496     /* If host does contain a dot already, or it is "localhost", decline */
497     if (strchr(r->parsed_uri.hostname, '.') != NULL
498      || strcasecmp(r->parsed_uri.hostname, "localhost") == 0)
499         return DECLINED;        /* host name has a dot already */
500
501     ref = apr_table_get(r->headers_in, "Referer");
502
503     /* Reassemble the request, but insert the domain after the host name */
504     /* Note that the domain name always starts with a dot */
505     r->parsed_uri.hostname = apr_pstrcat(r->pool, r->parsed_uri.hostname,
506                                          domain, NULL);
507     nuri = apr_uri_unparse(r->pool,
508                            &r->parsed_uri,
509                            APR_URI_UNP_REVEALPASSWORD);
510
511     apr_table_set(r->headers_out, "Location", nuri);
512     ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
513                   "Domain missing: %s sent to %s%s%s", r->uri,
514                   apr_uri_unparse(r->pool, &r->parsed_uri,
515                                   APR_URI_UNP_OMITUSERINFO),
516                   ref ? " from " : "", ref ? ref : "");
517
518     return HTTP_MOVED_PERMANENTLY;
519 }
520
521 /* -------------------------------------------------------------- */
522 /* Invoke handler */
523
524 static int proxy_handler(request_rec *r)
525 {
526     char *url, *scheme, *p;
527     const char *p2;
528     void *sconf = r->server->module_config;
529     proxy_server_conf *conf = (proxy_server_conf *)
530         ap_get_module_config(sconf, &proxy_module);
531     apr_array_header_t *proxies = conf->proxies;
532     struct proxy_remote *ents = (struct proxy_remote *) proxies->elts;
533     int i, rc, access_status;
534     int direct_connect = 0;
535     const char *str;
536     long maxfwd;
537     proxy_balancer *balancer = NULL;
538     proxy_worker *worker = NULL;
539
540     /* is this for us? */
541     if (!r->proxyreq || !r->filename || strncmp(r->filename, "proxy:", 6) != 0)
542         return DECLINED;
543
544     /* handle max-forwards / OPTIONS / TRACE */
545     if ((str = apr_table_get(r->headers_in, "Max-Forwards"))) {
546         maxfwd = strtol(str, NULL, 10);
547         if (maxfwd < 1) {
548             switch (r->method_number) {
549             case M_TRACE: {
550                 int access_status;
551                 r->proxyreq = PROXYREQ_NONE;
552                 if ((access_status = ap_send_http_trace(r)))
553                     ap_die(access_status, r);
554                 else
555                     ap_finalize_request_protocol(r);
556                 return OK;
557             }
558             case M_OPTIONS: {
559                 int access_status;
560                 r->proxyreq = PROXYREQ_NONE;
561                 if ((access_status = ap_send_http_options(r)))
562                     ap_die(access_status, r);
563                 else
564                     ap_finalize_request_protocol(r);
565                 return OK;
566             }
567             default: {
568                 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
569                                      "Max-Forwards has reached zero - proxy loop?");
570             }
571             }
572         }
573         maxfwd = (maxfwd > 0) ? maxfwd - 1 : 0;
574     }
575     else {
576         /* set configured max-forwards */
577         maxfwd = conf->maxfwd;
578     }
579     apr_table_set(r->headers_in, "Max-Forwards", 
580                   apr_psprintf(r->pool, "%ld", (maxfwd > 0) ? maxfwd : 0));
581
582     url = r->filename + 6;
583     p = strchr(url, ':');
584     if (p == NULL) {
585         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
586                       "proxy_handler no URL in %s", r->filename);
587         return HTTP_BAD_REQUEST;
588     }
589
590     /* If the host doesn't have a domain name, add one and redirect. */
591     if (conf->domain != NULL) {
592         rc = proxy_needsdomain(r, url, conf->domain);
593         if (ap_is_HTTP_REDIRECT(rc))
594             return HTTP_MOVED_PERMANENTLY;
595     }
596
597     *p = '\0';
598     scheme = apr_pstrdup(r->pool, url);
599     *p = ':';
600
601     /* Check URI's destination host against NoProxy hosts */
602     /* Bypass ProxyRemote server lookup if configured as NoProxy */
603     /* we only know how to handle communication to a proxy via http */
604     /*if (strcasecmp(scheme, "http") == 0) */
605     {
606         int ii;
607         struct dirconn_entry *list = (struct dirconn_entry *) conf->dirconn->elts;
608
609         for (direct_connect = ii = 0; ii < conf->dirconn->nelts && !direct_connect; ii++) {
610             direct_connect = list[ii].matcher(&list[ii], r);
611         }
612 #if DEBUGGING
613         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
614                       (direct_connect) ? "NoProxy for %s" : "UseProxy for %s",
615                       r->uri);
616 #endif
617     }
618     
619     /* Try to obtain the most suitable worker */
620     access_status = ap_proxy_pre_request(&worker, &balancer, r, conf, &url);
621     if (access_status != OK)
622         return access_status;
623     
624     /* firstly, try a proxy, unless a NoProxy directive is active */
625     if (!direct_connect) {
626         for (i = 0; i < proxies->nelts; i++) {
627             p2 = ap_strchr_c(ents[i].scheme, ':');  /* is it a partial URL? */
628             if (strcmp(ents[i].scheme, "*") == 0 ||
629                 (ents[i].use_regex && ap_regexec(ents[i].regexp, url, 0,NULL, 0)) ||
630                 (p2 == NULL && strcasecmp(scheme, ents[i].scheme) == 0) ||
631                 (p2 != NULL &&
632                  strncasecmp(url, ents[i].scheme, strlen(ents[i].scheme)) == 0)) {
633
634                 /* handle the scheme */
635                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
636                              "Trying to run scheme_handler against proxy");
637                 access_status = proxy_run_scheme_handler(r, worker, conf, url, ents[i].hostname, ents[i].port);
638
639                 /* an error or success */
640                 if (access_status != DECLINED && access_status != HTTP_BAD_GATEWAY) {
641                     goto cleanup;
642                 }
643                 /* we failed to talk to the upstream proxy */
644             }
645         }
646     }
647
648     /* otherwise, try it direct */
649     /* N.B. what if we're behind a firewall, where we must use a proxy or
650      * give up??
651      */
652
653     /* handle the scheme */
654     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
655                  "Trying to run scheme_handler");
656     access_status = proxy_run_scheme_handler(r, worker, conf, url, NULL, 0);
657     if (DECLINED == access_status) {
658         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
659                     "proxy: No protocol handler was valid for the URL %s. "
660                     "If you are using a DSO version of mod_proxy, make sure "
661                     "the proxy submodules are included in the configuration "
662                     "using LoadModule.", r->uri);
663         access_status = HTTP_FORBIDDEN;
664         goto cleanup;
665     }
666
667 cleanup:
668     if (balancer) {
669         int post_status = proxy_run_post_request(worker, balancer, r, conf);
670         if (post_status == DECLINED) {
671             post_status = OK; /* no post_request handler available */
672             /* TODO: reclycle direct worker */
673         }
674     }
675     return access_status;
676 }
677
678 /* -------------------------------------------------------------- */
679 /* Setup configurable data */
680
681 static void * create_proxy_config(apr_pool_t *p, server_rec *s)
682 {
683     proxy_server_conf *ps = apr_pcalloc(p, sizeof(proxy_server_conf));
684
685     ps->sec_proxy = apr_array_make(p, 10, sizeof(ap_conf_vector_t *));
686     ps->proxies = apr_array_make(p, 10, sizeof(struct proxy_remote));
687     ps->aliases = apr_array_make(p, 10, sizeof(struct proxy_alias));
688     ps->raliases = apr_array_make(p, 10, sizeof(struct proxy_alias));
689     ps->cookie_paths = apr_array_make(p, 10, sizeof(struct proxy_alias));
690     ps->cookie_domains = apr_array_make(p, 10, sizeof(struct proxy_alias));
691     ps->cookie_path_str = apr_strmatch_precompile(p, "path=", 0);
692     ps->cookie_domain_str = apr_strmatch_precompile(p, "domain=", 0);
693     ps->noproxies = apr_array_make(p, 10, sizeof(struct noproxy_entry));
694     ps->dirconn = apr_array_make(p, 10, sizeof(struct dirconn_entry));
695     ps->allowed_connect_ports = apr_array_make(p, 10, sizeof(int));
696     ps->workers = apr_array_make(p, 10, sizeof(proxy_worker));
697     ps->balancers = apr_array_make(p, 10, sizeof(proxy_balancer));
698     ps->domain = NULL;
699     ps->viaopt = via_off; /* initially backward compatible with 1.3.1 */
700     ps->viaopt_set = 0; /* 0 means default */
701     ps->req = 0;
702     ps->req_set = 0;
703     ps->recv_buffer_size = 0; /* this default was left unset for some reason */
704     ps->recv_buffer_size_set = 0;
705     ps->io_buffer_size = AP_IOBUFSIZE;
706     ps->io_buffer_size_set = 0;
707     ps->maxfwd = DEFAULT_MAX_FORWARDS;
708     ps->maxfwd_set = 0;
709     ps->error_override = 0; 
710     ps->error_override_set = 0; 
711     ps->preserve_host_set = 0;
712     ps->preserve_host = 0;    
713     ps->timeout = 0;
714     ps->timeout_set = 0;
715     ps->badopt = bad_error;
716     ps->badopt_set = 0;
717     return ps;
718 }
719
720 static void * merge_proxy_config(apr_pool_t *p, void *basev, void *overridesv)
721 {
722     proxy_server_conf *ps = apr_pcalloc(p, sizeof(proxy_server_conf));
723     proxy_server_conf *base = (proxy_server_conf *) basev;
724     proxy_server_conf *overrides = (proxy_server_conf *) overridesv;
725
726     ps->proxies = apr_array_append(p, base->proxies, overrides->proxies);
727     ps->sec_proxy = apr_array_append(p, base->sec_proxy, overrides->sec_proxy);
728     ps->aliases = apr_array_append(p, base->aliases, overrides->aliases);
729     ps->raliases = apr_array_append(p, base->raliases, overrides->raliases);
730     ps->cookie_paths
731         = apr_array_append(p, base->cookie_paths, overrides->cookie_paths);
732     ps->cookie_domains
733         = apr_array_append(p, base->cookie_domains, overrides->cookie_domains);
734     ps->cookie_path_str = base->cookie_path_str;
735     ps->cookie_domain_str = base->cookie_domain_str;
736     ps->noproxies = apr_array_append(p, base->noproxies, overrides->noproxies);
737     ps->dirconn = apr_array_append(p, base->dirconn, overrides->dirconn);
738     ps->allowed_connect_ports = apr_array_append(p, base->allowed_connect_ports, overrides->allowed_connect_ports);
739     ps->workers = apr_array_append(p, base->workers, overrides->workers);
740     ps->balancers = apr_array_append(p, base->balancers, overrides->balancers);
741
742     ps->domain = (overrides->domain == NULL) ? base->domain : overrides->domain;
743     ps->viaopt = (overrides->viaopt_set == 0) ? base->viaopt : overrides->viaopt;
744     ps->req = (overrides->req_set == 0) ? base->req : overrides->req;
745     ps->recv_buffer_size = (overrides->recv_buffer_size_set == 0) ? base->recv_buffer_size : overrides->recv_buffer_size;
746     ps->io_buffer_size = (overrides->io_buffer_size_set == 0) ? base->io_buffer_size : overrides->io_buffer_size;
747     ps->maxfwd = (overrides->maxfwd_set == 0) ? base->maxfwd : overrides->maxfwd;
748     ps->error_override = (overrides->error_override_set == 0) ? base->error_override : overrides->error_override;
749     ps->preserve_host = (overrides->preserve_host_set == 0) ? base->preserve_host : overrides->preserve_host;
750     ps->timeout= (overrides->timeout_set == 0) ? base->timeout : overrides->timeout;
751     ps->badopt = (overrides->badopt_set == 0) ? base->badopt : overrides->badopt;
752
753     return ps;
754 }
755
756 static void *create_proxy_dir_config(apr_pool_t *p, char *dummy)
757 {
758     proxy_dir_conf *new =
759         (proxy_dir_conf *) apr_pcalloc(p, sizeof(proxy_dir_conf));
760
761     /* Filled in by proxysection, when applicable */
762
763     return (void *) new;
764 }
765
766 static void *merge_proxy_dir_config(apr_pool_t *p, void *basev, void *addv)
767 {
768     proxy_dir_conf *new = (proxy_dir_conf *) apr_pcalloc(p, sizeof(proxy_dir_conf));
769     proxy_dir_conf *add = (proxy_dir_conf *) addv;
770
771     new->p = add->p;
772     new->p_is_fnmatch = add->p_is_fnmatch;
773     new->r = add->r;
774     return new;
775 }
776
777
778 static const char *
779     add_proxy(cmd_parms *cmd, void *dummy, const char *f1, const char *r1, int regex)
780 {
781     server_rec *s = cmd->server;
782     proxy_server_conf *conf =
783     (proxy_server_conf *) ap_get_module_config(s->module_config, &proxy_module);
784     struct proxy_remote *new;
785     char *p, *q;
786     char *r, *f, *scheme;
787     regex_t *reg = NULL;
788     int port;
789
790     r = apr_pstrdup(cmd->pool, r1);
791     scheme = apr_pstrdup(cmd->pool, r1);
792     f = apr_pstrdup(cmd->pool, f1);
793     p = strchr(r, ':');
794     if (p == NULL || p[1] != '/' || p[2] != '/' || p[3] == '\0') {
795         if (regex)
796             return "ProxyRemoteMatch: Bad syntax for a remote proxy server";
797         else
798             return "ProxyRemote: Bad syntax for a remote proxy server";
799     }
800     else {
801         scheme[p-r] = 0;
802     }
803     q = strchr(p + 3, ':');
804     if (q != NULL) {
805         if (sscanf(q + 1, "%u", &port) != 1 || port > 65535) {
806             if (regex)
807                 return "ProxyRemoteMatch: Bad syntax for a remote proxy server (bad port number)";
808             else
809                 return "ProxyRemote: Bad syntax for a remote proxy server (bad port number)";
810         }
811         *q = '\0';
812     }
813     else
814         port = -1;
815     *p = '\0';
816     if (regex) {
817         reg = ap_pregcomp(cmd->pool, f, REG_EXTENDED);
818         if (!reg)
819             return "Regular expression for ProxyRemoteMatch could not be compiled.";
820     }
821     else
822         if (strchr(f, ':') == NULL)
823             ap_str_tolower(f);          /* lowercase scheme */
824     ap_str_tolower(p + 3);              /* lowercase hostname */
825
826     if (port == -1) {
827         port = apr_uri_port_of_scheme(scheme);
828     }
829
830     new = apr_array_push(conf->proxies);
831     new->scheme = f;
832     new->protocol = r;
833     new->hostname = p + 3;
834     new->port = port;
835     new->regexp = reg;
836     new->use_regex = regex;
837     return NULL;
838 }
839
840 static const char *
841     add_proxy_noregex(cmd_parms *cmd, void *dummy, const char *f1, const char *r1)
842 {
843     return add_proxy(cmd, dummy, f1, r1, 0);
844 }
845
846 static const char *
847     add_proxy_regex(cmd_parms *cmd, void *dummy, const char *f1, const char *r1)
848 {
849     return add_proxy(cmd, dummy, f1, r1, 1);
850 }
851
852 static const char *
853     add_pass(cmd_parms *cmd, void *dummy, const char *arg)
854 {
855     server_rec *s = cmd->server;
856     proxy_server_conf *conf =
857     (proxy_server_conf *) ap_get_module_config(s->module_config, &proxy_module);
858     struct proxy_alias *new;
859     char *f = cmd->path;
860     char *r = NULL;
861     char *word;
862     apr_table_t *params = apr_table_make(cmd->pool, 5);
863     const apr_array_header_t *arr;
864     const apr_table_entry_t *elts;
865     int i;
866     
867     while (*arg) {
868         word = ap_getword_conf(cmd->pool, &arg);
869         if (!f)
870             f = word;
871         else if (!r)
872             r = word;
873         else {
874             char *val = strchr(word, '=');
875             if (!val) {
876                 if (cmd->path)
877                     return "Invalid ProxyPass parameter.  Parameter must be "
878                            "in the form 'key=value'";
879                 else
880                     return "ProxyPass can not have a path when defined in a location"; 
881             }
882             else
883                 *val++ = '\0';
884             apr_table_setn(params, word, val);
885         }
886     };
887
888     if (r == NULL)
889         return "ProxyPass needs a path when not defined in a location";
890
891     new = apr_array_push(conf->aliases);
892     new->fake = apr_pstrdup(cmd->pool, f);
893     new->real = apr_pstrdup(cmd->pool, r);
894     
895     arr = apr_table_elts(params);
896     elts = (const apr_table_entry_t *)arr->elts;
897     /* Distinguish the balancer from woker */
898     if (strncasecmp(r, "balancer:", 9) == 0) {
899         proxy_balancer *balancer = ap_proxy_get_balancer(cmd->pool, conf, r);
900         if (!balancer) {
901             const char *err = ap_proxy_add_balancer(&balancer,
902                                                     cmd->pool,
903                                                     conf, r);
904             if (err)
905                 return apr_pstrcat(cmd->temp_pool, "ProxyPass ", err, NULL);
906         }        
907         for (i = 0; i < arr->nelts; i++) {
908             const char *err = set_balancer_param(cmd->pool, balancer, elts[i].key,
909                                                  elts[i].val);
910             if (err)
911                 return apr_pstrcat(cmd->temp_pool, "ProxyPass ", err, NULL);
912         }
913     }
914     else {
915         proxy_worker *worker = ap_proxy_get_worker(cmd->temp_pool, conf, r);
916         if (!worker) {
917             const char *err = ap_proxy_add_worker(&worker, cmd->pool, conf, r);
918             if (err)
919                 return apr_pstrcat(cmd->temp_pool, "ProxyPass ", err, NULL);
920         }
921         PROXY_COPY_CONF_PARAMS(worker, conf);
922
923         for (i = 0; i < arr->nelts; i++) {
924             const char *err = set_worker_param(cmd->pool, worker, elts[i].key,
925                                                elts[i].val);
926             if (err)
927                 return apr_pstrcat(cmd->temp_pool, "ProxyPass ", err, NULL);
928         }
929     }
930     return NULL;
931 }
932
933 static const char *
934     add_pass_reverse(cmd_parms *cmd, void *dummy, const char *f, const char *r)
935 {
936     server_rec *s = cmd->server;
937     proxy_server_conf *conf;
938     struct proxy_alias *new;
939
940     conf = (proxy_server_conf *)ap_get_module_config(s->module_config, 
941                                                      &proxy_module);
942     if (r!=NULL && cmd->path == NULL ) {
943         new = apr_array_push(conf->raliases);
944         new->fake = f;
945         new->real = r;
946     } else if (r==NULL && cmd->path != NULL) {
947         new = apr_array_push(conf->raliases);
948         new->fake = cmd->path;
949         new->real = f;
950     } else {
951         if ( r == NULL)
952             return "ProxyPassReverse needs a path when not defined in a location";
953         else 
954             return "ProxyPassReverse can not have a path when defined in a location";
955     }
956
957     return NULL;
958 }
959 static const char*
960     cookie_path(cmd_parms *cmd, void *dummy, const char *f, const char *r)
961 {
962     server_rec *s = cmd->server;
963     proxy_server_conf *conf;
964     struct proxy_alias *new;
965
966     conf = (proxy_server_conf *)ap_get_module_config(s->module_config,
967                                                      &proxy_module);
968     new = apr_array_push(conf->cookie_paths);
969     new->fake = f;
970     new->real = r;
971
972     return NULL;
973 }
974 static const char*
975     cookie_domain(cmd_parms *cmd, void *dummy, const char *f, const char *r)
976 {
977     server_rec *s = cmd->server;
978     proxy_server_conf *conf;
979     struct proxy_alias *new;
980
981     conf = (proxy_server_conf *)ap_get_module_config(s->module_config,
982                                                      &proxy_module);
983     new = apr_array_push(conf->cookie_domains);
984     new->fake = f;
985     new->real = r;
986
987     return NULL;
988 }
989
990 static const char *
991     set_proxy_exclude(cmd_parms *parms, void *dummy, const char *arg)
992 {
993     server_rec *s = parms->server;
994     proxy_server_conf *conf =
995     ap_get_module_config(s->module_config, &proxy_module);
996     struct noproxy_entry *new;
997     struct noproxy_entry *list = (struct noproxy_entry *) conf->noproxies->elts;
998     struct apr_sockaddr_t *addr;
999     int found = 0;
1000     int i;
1001
1002     /* Don't duplicate entries */
1003     for (i = 0; i < conf->noproxies->nelts; i++) {
1004         if (apr_strnatcasecmp(arg, list[i].name) == 0) { /* ignore case for host names */
1005             found = 1;
1006         }
1007     }
1008
1009     if (!found) {
1010         new = apr_array_push(conf->noproxies);
1011         new->name = arg;
1012         if (APR_SUCCESS == apr_sockaddr_info_get(&addr, new->name, APR_UNSPEC, 0, 0, parms->pool)) {
1013             new->addr = addr;
1014         }
1015         else {
1016             new->addr = NULL;
1017         }
1018     }
1019     return NULL;
1020 }
1021
1022 /*
1023  * Set the ports CONNECT can use
1024  */
1025 static const char *
1026     set_allowed_ports(cmd_parms *parms, void *dummy, const char *arg)
1027 {
1028     server_rec *s = parms->server;
1029     proxy_server_conf *conf =
1030         ap_get_module_config(s->module_config, &proxy_module);
1031     int *New;
1032
1033     if (!apr_isdigit(arg[0]))
1034         return "AllowCONNECT: port number must be numeric";
1035
1036     New = apr_array_push(conf->allowed_connect_ports);
1037     *New = atoi(arg);
1038     return NULL;
1039 }
1040
1041 /* Similar to set_proxy_exclude(), but defining directly connected hosts,
1042  * which should never be accessed via the configured ProxyRemote servers
1043  */
1044 static const char *
1045     set_proxy_dirconn(cmd_parms *parms, void *dummy, const char *arg)
1046 {
1047     server_rec *s = parms->server;
1048     proxy_server_conf *conf =
1049     ap_get_module_config(s->module_config, &proxy_module);
1050     struct dirconn_entry *New;
1051     struct dirconn_entry *list = (struct dirconn_entry *) conf->dirconn->elts;
1052     int found = 0;
1053     int i;
1054
1055     /* Don't duplicate entries */
1056     for (i = 0; i < conf->dirconn->nelts; i++) {
1057         if (strcasecmp(arg, list[i].name) == 0)
1058             found = 1;
1059     }
1060
1061     if (!found) {
1062         New = apr_array_push(conf->dirconn);
1063         New->name = apr_pstrdup(parms->pool, arg);
1064         New->hostaddr = NULL;
1065
1066         if (ap_proxy_is_ipaddr(New, parms->pool)) {
1067 #if DEBUGGING
1068             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1069                          "Parsed addr %s", inet_ntoa(New->addr));
1070             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1071                          "Parsed mask %s", inet_ntoa(New->mask));
1072 #endif
1073         }
1074         else if (ap_proxy_is_domainname(New, parms->pool)) {
1075             ap_str_tolower(New->name);
1076 #if DEBUGGING
1077             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1078                          "Parsed domain %s", New->name);
1079 #endif
1080         }
1081         else if (ap_proxy_is_hostname(New, parms->pool)) {
1082             ap_str_tolower(New->name);
1083 #if DEBUGGING
1084             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1085                          "Parsed host %s", New->name);
1086 #endif
1087         }
1088         else {
1089             ap_proxy_is_word(New, parms->pool);
1090 #if DEBUGGING
1091             fprintf(stderr, "Parsed word %s\n", New->name);
1092 #endif
1093         }
1094     }
1095     return NULL;
1096 }
1097
1098 static const char *
1099     set_proxy_domain(cmd_parms *parms, void *dummy, const char *arg)
1100 {
1101     proxy_server_conf *psf =
1102     ap_get_module_config(parms->server->module_config, &proxy_module);
1103
1104     if (arg[0] != '.')
1105         return "ProxyDomain: domain name must start with a dot.";
1106
1107     psf->domain = arg;
1108     return NULL;
1109 }
1110
1111 static const char *
1112     set_proxy_req(cmd_parms *parms, void *dummy, int flag)
1113 {
1114     proxy_server_conf *psf =
1115     ap_get_module_config(parms->server->module_config, &proxy_module);
1116
1117     psf->req = flag;
1118     psf->req_set = 1;
1119     return NULL;
1120 }
1121 static const char *
1122     set_proxy_error_override(cmd_parms *parms, void *dummy, int flag)
1123 {
1124     proxy_server_conf *psf =
1125     ap_get_module_config(parms->server->module_config, &proxy_module);
1126
1127     psf->error_override = flag;
1128     psf->error_override_set = 1;
1129     return NULL;
1130 }
1131 static const char *
1132     set_preserve_host(cmd_parms *parms, void *dummy, int flag)
1133 {
1134     proxy_server_conf *psf =
1135     ap_get_module_config(parms->server->module_config, &proxy_module);
1136
1137     psf->preserve_host = flag;
1138     psf->preserve_host_set = 1;
1139     return NULL;
1140 }
1141
1142 static const char *
1143     set_recv_buffer_size(cmd_parms *parms, void *dummy, const char *arg)
1144 {
1145     proxy_server_conf *psf =
1146     ap_get_module_config(parms->server->module_config, &proxy_module);
1147     int s = atoi(arg);
1148     if (s < 512 && s != 0) {
1149         return "ProxyReceiveBufferSize must be >= 512 bytes, or 0 for system default.";
1150     }
1151
1152     psf->recv_buffer_size = s;
1153     psf->recv_buffer_size_set = 1;
1154     return NULL;
1155 }
1156
1157 static const char *
1158     set_io_buffer_size(cmd_parms *parms, void *dummy, const char *arg)
1159 {
1160     proxy_server_conf *psf =
1161     ap_get_module_config(parms->server->module_config, &proxy_module);
1162     long s = atol(arg);
1163
1164     psf->io_buffer_size = ((s > AP_IOBUFSIZE) ? s : AP_IOBUFSIZE);
1165     psf->io_buffer_size_set = 1;
1166     return NULL;
1167 }
1168
1169 static const char *
1170     set_max_forwards(cmd_parms *parms, void *dummy, const char *arg)
1171 {
1172     proxy_server_conf *psf =
1173     ap_get_module_config(parms->server->module_config, &proxy_module);
1174     long s = atol(arg);
1175     if (s < 0) {
1176         return "ProxyMaxForwards must be greater or equal to zero..";
1177     }
1178
1179     psf->maxfwd = s;
1180     psf->maxfwd_set = 1;
1181     return NULL;
1182 }
1183 static const char*
1184     set_proxy_timeout(cmd_parms *parms, void *dummy, const char *arg)
1185 {
1186     proxy_server_conf *psf =
1187     ap_get_module_config(parms->server->module_config, &proxy_module);
1188     int timeout;
1189
1190     timeout=atoi(arg);
1191     if (timeout<1) {
1192         return "Proxy Timeout must be at least 1 second.";
1193     }
1194     psf->timeout_set=1;
1195     psf->timeout=apr_time_from_sec(timeout);
1196
1197     return NULL;    
1198 }
1199
1200 static const char*
1201     set_via_opt(cmd_parms *parms, void *dummy, const char *arg)
1202 {
1203     proxy_server_conf *psf =
1204     ap_get_module_config(parms->server->module_config, &proxy_module);
1205
1206     if (strcasecmp(arg, "Off") == 0)
1207         psf->viaopt = via_off;
1208     else if (strcasecmp(arg, "On") == 0)
1209         psf->viaopt = via_on;
1210     else if (strcasecmp(arg, "Block") == 0)
1211         psf->viaopt = via_block;
1212     else if (strcasecmp(arg, "Full") == 0)
1213         psf->viaopt = via_full;
1214     else {
1215         return "ProxyVia must be one of: "
1216             "off | on | full | block";
1217     }
1218
1219     psf->viaopt_set = 1;
1220     return NULL;    
1221 }
1222
1223 static const char*
1224     set_bad_opt(cmd_parms *parms, void *dummy, const char *arg)
1225 {
1226     proxy_server_conf *psf =
1227     ap_get_module_config(parms->server->module_config, &proxy_module);
1228
1229     if (strcasecmp(arg, "IsError") == 0)
1230         psf->badopt = bad_error;
1231     else if (strcasecmp(arg, "Ignore") == 0)
1232         psf->badopt = bad_ignore;
1233     else if (strcasecmp(arg, "StartBody") == 0)
1234         psf->badopt = bad_body;
1235     else {
1236         return "ProxyBadHeader must be one of: "
1237             "IsError | Ignore | StartBody";
1238     }
1239
1240     psf->badopt_set = 1;
1241     return NULL;    
1242 }
1243
1244 static const char*
1245     set_status_opt(cmd_parms *parms, void *dummy, const char *arg)
1246 {
1247     proxy_server_conf *psf =
1248     ap_get_module_config(parms->server->module_config, &proxy_module);
1249
1250     if (strcasecmp(arg, "Off") == 0)
1251         psf->proxy_status = status_off;
1252     else if (strcasecmp(arg, "On") == 0)
1253         psf->proxy_status = status_on;
1254     else if (strcasecmp(arg, "Full") == 0)
1255         psf->proxy_status = status_full;
1256     else {
1257         return "ProxyStatus must be one of: "
1258             "off | on | block";
1259     }
1260
1261     psf->proxy_status_set = 1;
1262     return NULL;    
1263 }
1264
1265 static const char *add_member(cmd_parms *cmd, void *dummy, const char *arg)
1266 {
1267     server_rec *s = cmd->server;
1268     proxy_server_conf *conf =
1269     ap_get_module_config(s->module_config, &proxy_module);
1270     proxy_balancer *balancer;
1271     proxy_worker *worker;
1272     char *path = cmd->path;
1273     char *name = NULL;
1274     char *word;
1275     apr_table_t *params = apr_table_make(cmd->pool, 5);
1276     const apr_array_header_t *arr;
1277     const apr_table_entry_t *elts;
1278     int i;
1279     
1280     if (cmd->path)
1281         path = apr_pstrdup(cmd->pool, cmd->path);
1282     while (*arg) {
1283         word = ap_getword_conf(cmd->pool, &arg);
1284         if (!path)
1285             path = word;
1286         else if (!name)
1287             name = word;
1288         else {
1289             char *val = strchr(word, '=');
1290             if (!val)
1291                 if (cmd->path)
1292                     return "BalancerMember can not have a balancer name when defined in a location";
1293                 else
1294                     return "Invalid BalancerMember parameter. Parameter must "
1295                            "be in the form 'key=value'";
1296             else
1297                 *val++ = '\0';
1298             apr_table_setn(params, word, val);
1299         }
1300     }
1301     if (!path)
1302         return "BalancerMember must define balancer name when outside <Proxy > section";
1303     if (!name)
1304         return "BalancerMember must define remote proxy server";
1305     
1306     ap_str_tolower(path);       /* lowercase scheme://hostname */
1307     ap_str_tolower(name);       /* lowercase scheme://hostname */
1308
1309     /* Try to find existing worker */
1310     worker = ap_proxy_get_worker(cmd->temp_pool, conf, name);
1311     if (!worker) {
1312         const char *err;
1313         if ((err = ap_proxy_add_worker(&worker, cmd->pool, conf, name)) != NULL)
1314             return apr_pstrcat(cmd->temp_pool, "BalancerMember ", err, NULL); 
1315     }
1316     PROXY_COPY_CONF_PARAMS(worker, conf);
1317     
1318     arr = apr_table_elts(params);
1319     elts = (const apr_table_entry_t *)arr->elts;
1320     for (i = 0; i < arr->nelts; i++) {
1321         const char *err = set_worker_param(cmd->pool, worker, elts[i].key,
1322                                            elts[i].val);
1323         if (err)
1324             return apr_pstrcat(cmd->temp_pool, "BalancerMember ", err, NULL);
1325     }
1326     /* Try to find the balancer */
1327     balancer = ap_proxy_get_balancer(cmd->temp_pool, conf, path); 
1328     if (!balancer) {
1329         const char *err = ap_proxy_add_balancer(&balancer,
1330                                                 cmd->pool,
1331                                                 conf, path);
1332         if (err)
1333             return apr_pstrcat(cmd->temp_pool, "BalancerMember ", err, NULL);
1334     }
1335     /* Add the worker to the load balancer */
1336     ap_proxy_add_worker_to_balancer(cmd->pool, balancer, worker);
1337
1338     return NULL;
1339 }
1340
1341 static const char *
1342     set_sticky_session(cmd_parms *cmd, void *dummy, const char *f, const char *r)
1343 {
1344     server_rec *s = cmd->server;
1345     proxy_server_conf *conf =
1346     ap_get_module_config(s->module_config, &proxy_module);
1347     proxy_balancer *balancer;
1348     const char *name, *sticky;
1349
1350     if (r != NULL && cmd->path == NULL ) {
1351         name = f;
1352         sticky = r;
1353     } else if (r == NULL && cmd->path != NULL) {
1354         name = cmd->path;
1355         sticky = f;
1356     } else {
1357         if (r == NULL)
1358             return "BalancerStickySession needs a path when not defined in a location";
1359         else 
1360             return "BalancerStickySession can not have a path when defined in a location";
1361     }
1362     /* Try to find the balancer */
1363     balancer = ap_proxy_get_balancer(cmd->temp_pool, conf, name);
1364     if (!balancer)
1365         return apr_pstrcat(cmd->temp_pool, "BalancerStickySession: can not find a load balancer '",
1366                            name, "'", NULL);
1367     if (!strcasecmp(sticky, "nofailover"))
1368         balancer->sticky_force = 1;   
1369     else
1370         balancer->sticky = sticky;
1371     return NULL;
1372 }
1373
1374 static void ap_add_per_proxy_conf(server_rec *s, ap_conf_vector_t *dir_config)
1375 {
1376     proxy_server_conf *sconf = ap_get_module_config(s->module_config,
1377                                                     &proxy_module);
1378     void **new_space = (void **)apr_array_push(sconf->sec_proxy);
1379     
1380     *new_space = dir_config;
1381 }
1382
1383 static const char *proxysection(cmd_parms *cmd, void *mconfig, const char *arg)
1384 {
1385     const char *errmsg;
1386     const char *endp = ap_strrchr_c(arg, '>');
1387     int old_overrides = cmd->override;
1388     char *old_path = cmd->path;
1389     proxy_dir_conf *conf;
1390     ap_conf_vector_t *new_dir_conf = ap_create_per_dir_config(cmd->pool);
1391     regex_t *r = NULL;
1392     const command_rec *thiscmd = cmd->cmd;
1393
1394     const char *err = ap_check_cmd_context(cmd,
1395                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1396     if (err != NULL) {
1397         return err;
1398     }
1399
1400     if (endp == NULL) {
1401         return apr_pstrcat(cmd->pool, cmd->cmd->name,
1402                            "> directive missing closing '>'", NULL);
1403     }
1404
1405     arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1406
1407     if (!arg) {
1408         if (thiscmd->cmd_data)
1409             return "<ProxyMatch > block must specify a path";
1410         else
1411             return "<Proxy > block must specify a path";
1412     }
1413
1414     cmd->path = ap_getword_conf(cmd->pool, &arg);
1415     cmd->override = OR_ALL|ACCESS_CONF;
1416
1417     if (!strncasecmp(cmd->path, "proxy:", 6))
1418         cmd->path += 6;
1419
1420     /* XXX Ignore case?  What if we proxy a case-insensitive server?!? 
1421      * While we are at it, shouldn't we also canonicalize the entire
1422      * scheme?  See proxy_fixup()
1423      */
1424     if (thiscmd->cmd_data) { /* <ProxyMatch> */
1425         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1426         if (!r) {
1427             return "Regex could not be compiled";
1428         }
1429     }
1430     else if (!strcmp(cmd->path, "~")) {
1431         cmd->path = ap_getword_conf(cmd->pool, &arg);
1432         if (!cmd->path)
1433             return "<Proxy ~ > block must specify a path";
1434         if (strncasecmp(cmd->path, "proxy:", 6))
1435             cmd->path += 6;
1436         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1437         if (!r) {
1438             return "Regex could not be compiled";
1439         }
1440     }
1441
1442     /* initialize our config and fetch it */
1443     conf = ap_set_config_vectors(cmd->server, new_dir_conf, cmd->path,
1444                                  &proxy_module, cmd->pool);
1445
1446     errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_dir_conf);
1447     if (errmsg != NULL)
1448         return errmsg;
1449
1450     conf->r = r;
1451     conf->p = cmd->path;
1452     conf->p_is_fnmatch = apr_fnmatch_test(conf->p);
1453
1454     ap_add_per_proxy_conf(cmd->server, new_dir_conf);
1455
1456     if (*arg != '\0') {
1457         return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1458                            "> arguments not (yet) supported.", NULL);
1459     }
1460
1461     cmd->path = old_path;
1462     cmd->override = old_overrides;
1463
1464     return NULL;
1465 }
1466
1467 static const command_rec proxy_cmds[] =
1468 {
1469     AP_INIT_RAW_ARGS("<Proxy", proxysection, NULL, RSRC_CONF, 
1470     "Container for directives affecting resources located in the proxied "
1471     "location"),
1472     AP_INIT_RAW_ARGS("<ProxyMatch", proxysection, (void*)1, RSRC_CONF,
1473     "Container for directives affecting resources located in the proxied "
1474     "location, in regular expression syntax"),
1475     AP_INIT_FLAG("ProxyRequests", set_proxy_req, NULL, RSRC_CONF,
1476      "on if the true proxy requests should be accepted"),
1477     AP_INIT_TAKE2("ProxyRemote", add_proxy_noregex, NULL, RSRC_CONF,
1478      "a scheme, partial URL or '*' and a proxy server"),
1479     AP_INIT_TAKE2("ProxyRemoteMatch", add_proxy_regex, NULL, RSRC_CONF,
1480      "a regex pattern and a proxy server"),
1481     AP_INIT_RAW_ARGS("ProxyPass", add_pass, NULL, RSRC_CONF|ACCESS_CONF,
1482      "a virtual path and a URL"),
1483     AP_INIT_TAKE12("ProxyPassReverse", add_pass_reverse, NULL, RSRC_CONF|ACCESS_CONF,
1484      "a virtual path and a URL for reverse proxy behaviour"),
1485     AP_INIT_TAKE2("ProxyPassReverseCookiePath", cookie_path, NULL,
1486        RSRC_CONF|ACCESS_CONF, "Path rewrite rule for proxying cookies"),
1487     AP_INIT_TAKE2("ProxyPassReverseCookieDomain", cookie_domain, NULL,
1488        RSRC_CONF|ACCESS_CONF, "Domain rewrite rule for proxying cookies"),
1489     AP_INIT_ITERATE("ProxyBlock", set_proxy_exclude, NULL, RSRC_CONF,
1490      "A list of names, hosts or domains to which the proxy will not connect"),
1491     AP_INIT_TAKE1("ProxyReceiveBufferSize", set_recv_buffer_size, NULL, RSRC_CONF,
1492      "Receive buffer size for outgoing HTTP and FTP connections in bytes"),
1493     AP_INIT_TAKE1("ProxyIOBufferSize", set_io_buffer_size, NULL, RSRC_CONF,
1494      "IO buffer size for outgoing HTTP and FTP connections in bytes"),
1495     AP_INIT_TAKE1("ProxyMaxForwards", set_max_forwards, NULL, RSRC_CONF,
1496      "The maximum number of proxies a request may be forwarded through."),
1497     AP_INIT_ITERATE("NoProxy", set_proxy_dirconn, NULL, RSRC_CONF,
1498      "A list of domains, hosts, or subnets to which the proxy will connect directly"),
1499     AP_INIT_TAKE1("ProxyDomain", set_proxy_domain, NULL, RSRC_CONF,
1500      "The default intranet domain name (in absence of a domain in the URL)"),
1501     AP_INIT_ITERATE("AllowCONNECT", set_allowed_ports, NULL, RSRC_CONF,
1502      "A list of ports which CONNECT may connect to"),
1503     AP_INIT_TAKE1("ProxyVia", set_via_opt, NULL, RSRC_CONF,
1504      "Configure Via: proxy header header to one of: on | off | block | full"),
1505     AP_INIT_FLAG("ProxyErrorOverride", set_proxy_error_override, NULL, RSRC_CONF,
1506      "use our error handling pages instead of the servers' we are proxying"),
1507     AP_INIT_FLAG("ProxyPreserveHost", set_preserve_host, NULL, RSRC_CONF,
1508      "on if we should preserve host header while proxying"),
1509     AP_INIT_TAKE1("ProxyTimeout", set_proxy_timeout, NULL, RSRC_CONF,
1510      "Set the timeout (in seconds) for a proxied connection. "
1511      "This overrides the server timeout"),
1512     AP_INIT_TAKE1("ProxyBadHeader", set_bad_opt, NULL, RSRC_CONF,
1513      "How to handle bad header line in response: IsError | Ignore | StartBody"),
1514     AP_INIT_RAW_ARGS("BalancerMember", add_member, NULL, RSRC_CONF|ACCESS_CONF,
1515      "A balancer name and scheme with list of params"), 
1516     AP_INIT_TAKE12("BalancerStickySession", set_sticky_session, NULL, RSRC_CONF|ACCESS_CONF,
1517      "A balancer and sticky session name"),
1518     AP_INIT_TAKE1("ProxyStatus", set_status_opt, NULL, RSRC_CONF,
1519      "Configure Status: proxy status to one of: on | off | full"),
1520     {NULL}
1521 };
1522
1523 static APR_OPTIONAL_FN_TYPE(ssl_proxy_enable) *proxy_ssl_enable = NULL;
1524 static APR_OPTIONAL_FN_TYPE(ssl_engine_disable) *proxy_ssl_disable = NULL;
1525
1526 PROXY_DECLARE(int) ap_proxy_ssl_enable(conn_rec *c)
1527 {
1528     /* 
1529      * if c == NULL just check if the optional function was imported
1530      * else run the optional function so ssl filters are inserted
1531      */
1532     if (proxy_ssl_enable) {
1533         return c ? proxy_ssl_enable(c) : 1;
1534     }
1535
1536     return 0;
1537 }
1538
1539 PROXY_DECLARE(int) ap_proxy_ssl_disable(conn_rec *c)
1540 {
1541     if (proxy_ssl_disable) {
1542         return proxy_ssl_disable(c);
1543     }
1544
1545     return 0;
1546 }
1547
1548 static int proxy_post_config(apr_pool_t *pconf, apr_pool_t *plog,
1549                              apr_pool_t *ptemp, server_rec *s)
1550 {
1551     proxy_ssl_enable = APR_RETRIEVE_OPTIONAL_FN(ssl_proxy_enable);
1552     proxy_ssl_disable = APR_RETRIEVE_OPTIONAL_FN(ssl_engine_disable);
1553
1554     return OK;
1555 }
1556
1557
1558 #define KBYTE 1024
1559 #define MBYTE 1048576L
1560 #define GBYTE 1073741824L
1561
1562 /* Format the number of bytes nicely */
1563 static void format_byte_out(request_rec *r, apr_off_t bytes)
1564 {
1565
1566     if (bytes < (5 * KBYTE))
1567         ap_rprintf(r, "%d B", (int) bytes);
1568     else if (bytes < (MBYTE / 2))
1569         ap_rprintf(r, "%.1f kB", (float) bytes / KBYTE);
1570     else if (bytes < (GBYTE / 2))
1571         ap_rprintf(r, "%.1f MB", (float) bytes / MBYTE);
1572     else
1573         ap_rprintf(r, "%.1f GB", (float) bytes / GBYTE);
1574 }
1575
1576 /*
1577  *  proxy Extension to mod_status
1578  */
1579 static int proxy_status_hook(request_rec *r, int flags)
1580 {
1581     int i, n;
1582     void *sconf = r->server->module_config;
1583     proxy_server_conf *conf = (proxy_server_conf *)
1584         ap_get_module_config(sconf, &proxy_module);
1585     proxy_balancer *balancer = NULL;
1586     proxy_runtime_worker *worker = NULL;
1587
1588     if (flags & AP_STATUS_SHORT || conf->balancers->nelts == 0 ||
1589         conf->proxy_status == status_off)
1590         return OK;
1591
1592     balancer = (proxy_balancer *)conf->balancers->elts;
1593     for (i = 0; i < conf->balancers->nelts; i++) {
1594         ap_rputs("<hr />\n<h1>Proxy LoadBalancer Status for ", r);
1595         ap_rvputs(r, balancer->name, "</h1>\n\n", NULL);
1596         ap_rputs("\n\n<table border=\"0\"><tr>"
1597                  "<th>SSes</th><th>Timeout</th>"
1598                  "</tr>\n<tr>", r);                
1599         ap_rvputs(r, "<td>", balancer->sticky, NULL);
1600         ap_rprintf(r, "</td><td>%" APR_TIME_T_FMT "</td>\n",
1601                    apr_time_sec(balancer->timeout));
1602         ap_rputs("</table>\n", r);
1603         ap_rputs("\n\n<table border=\"0\"><tr>"
1604                  "<th>Sch</th><th>Host</th>"
1605                  "<th>Route</th><th>Redir</th>"
1606                  "<th>F</th><th>Acc</th><th>Wr</th><th>Rd</th>"
1607                  "</tr>\n", r);
1608
1609         worker = (proxy_runtime_worker *)balancer->workers->elts;
1610         for (n = 0; n < balancer->workers->nelts; n++) {
1611
1612             ap_rvputs(r, "<tr>\n<td>", worker->w->scheme, "</td>", NULL);
1613             ap_rvputs(r, "<td>", worker->w->hostname, "</td>", NULL);
1614             ap_rvputs(r, "<td>", worker->w->route, NULL);
1615             ap_rvputs(r, "</td><td>", worker->w->redirect, NULL);
1616             ap_rprintf(r, "</td><td>%.2f</td>", worker->s->lbfactor);
1617             ap_rprintf(r, "<td>%d</td><td>", (int)(worker->s->elected));
1618             format_byte_out(r, worker->s->transfered);
1619             ap_rputs("</td><td>", r);
1620             format_byte_out(r, worker->s->transfered);
1621             ap_rputs("</td>\n", r);
1622
1623             /* TODO: Add the rest of dynamic worker data */
1624             ap_rputs("</tr>\n", r);
1625
1626             ++worker;
1627         }
1628         ap_rputs("</table>\n", r);
1629         ++balancer;
1630     }
1631     ap_rputs("<hr /><table>\n"
1632              "<tr><th>SSes</th><td>Sticky session name</td></tr>\n"
1633              "<tr><th>Timeout</th><td>Balancer Timeout</td></tr>\n"
1634              "<tr><th>Sch</th><td>Connection scheme</td></tr>\n"
1635              "<tr><th>Host</th><td>Backend Hostname</td></tr>\n"
1636              "<tr><th>Route</th><td>Session Route</td></tr>\n"
1637              "<tr><th>Redir</th><td>Session Route Redirection</td></tr>\n"
1638              "<tr><th>F</th><td>Load Balancer Factor in %</td></tr>\n"
1639              "<tr><th>Acc</th><td>Number of requests</td></tr>\n"
1640              "<tr><th>Wr</th><td>Number of bytes transfered</td></tr>\n"
1641              "<tr><th>Rd</th><td>Number of bytes readed</td></tr>\n"
1642              "</table>", r);
1643
1644     return OK;
1645 }
1646
1647 /*
1648  * This routine is called before the server processes the configuration
1649  * files.  There is no return value.
1650  */
1651 static int proxy_pre_config(apr_pool_t *pconf, apr_pool_t *plog,
1652                             apr_pool_t *ptemp)
1653 {
1654     APR_OPTIONAL_HOOK(ap, status_hook, proxy_status_hook, NULL, NULL,
1655                       APR_HOOK_MIDDLE);
1656     return OK;
1657 }
1658
1659 static void register_hooks(apr_pool_t *p)
1660 {
1661     /* fixup before mod_rewrite, so that the proxied url will not
1662      * escaped accidentally by our fixup.
1663      */
1664 #ifndef FIX_15207
1665     static const char * const aszSucc[]={ "mod_rewrite.c", NULL };
1666 #endif
1667
1668     /* handler */
1669     ap_hook_handler(proxy_handler, NULL, NULL, APR_HOOK_FIRST);
1670     /* filename-to-URI translation */
1671     ap_hook_translate_name(proxy_trans, NULL, NULL, APR_HOOK_FIRST);
1672     /* walk <Proxy > entries and suppress default TRACE behavior */
1673     ap_hook_map_to_storage(proxy_map_location, NULL,NULL, APR_HOOK_FIRST);
1674 #ifndef FIX_15207
1675     /* fixups */
1676     ap_hook_fixups(proxy_fixup, NULL, aszSucc, APR_HOOK_FIRST);
1677 #endif
1678     /* post read_request handling */
1679     ap_hook_post_read_request(proxy_detect, NULL, NULL, APR_HOOK_FIRST);
1680     /* pre config handling */
1681     ap_hook_pre_config(proxy_pre_config, NULL, NULL, APR_HOOK_MIDDLE); 
1682     /* post config handling */
1683     ap_hook_post_config(proxy_post_config, NULL, NULL, APR_HOOK_MIDDLE);
1684 }
1685
1686 module AP_MODULE_DECLARE_DATA proxy_module =
1687 {
1688     STANDARD20_MODULE_STUFF,
1689     create_proxy_dir_config,    /* create per-directory config structure */
1690     merge_proxy_dir_config,     /* merge per-directory config structures */
1691     create_proxy_config,        /* create per-server config structure */
1692     merge_proxy_config,         /* merge per-server config structures */
1693     proxy_cmds,                 /* command table */
1694     register_hooks
1695 };
1696
1697 APR_HOOK_STRUCT(
1698         APR_HOOK_LINK(scheme_handler)
1699         APR_HOOK_LINK(canon_handler)
1700         APR_HOOK_LINK(pre_request)
1701         APR_HOOK_LINK(post_request)
1702 )
1703
1704 APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(proxy, PROXY, int, scheme_handler, 
1705                                      (request_rec *r, proxy_worker *worker,
1706                                       proxy_server_conf *conf, 
1707                                       char *url, const char *proxyhost, 
1708                                       apr_port_t proxyport),(r,worker,conf,
1709                                       url,proxyhost,proxyport),DECLINED)
1710 APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(proxy, PROXY, int, canon_handler, 
1711                                       (request_rec *r, char *url),(r,
1712                                       url),DECLINED)
1713 APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(proxy, PROXY, int, pre_request, (
1714                                       proxy_worker **worker,
1715                                       proxy_balancer **balancer,
1716                                       request_rec *r, 
1717                                       proxy_server_conf *conf,
1718                                       char **url),(worker,balancer,
1719                                       r,conf,url),DECLINED)
1720 APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(proxy, PROXY, int, post_request,
1721                                       (proxy_worker *worker,
1722                                        proxy_balancer *balancer,
1723                                        request_rec *r,
1724                                        proxy_server_conf *conf),(worker,
1725                                        balancer,r,conf),DECLINED)
1726 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(proxy, PROXY, int, fixups,
1727                                     (request_rec *r), (r),
1728                                     OK, DECLINED)