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