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