]> granicus.if.org Git - apache/blob - modules/proxy/mod_proxy.c
Remove <Proxy ~ wildcard-url> syntax which:
[apache] / modules / proxy / mod_proxy.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  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 #include "mod_proxy.h"
18 #include "mod_core.h"
19 #include "apr_optional.h"
20 #include "scoreboard.h"
21 #include "mod_status.h"
22 #include "proxy_util.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 APR_DECLARE_OPTIONAL_FN(int, ssl_is_https, (conn_rec *));
30 APR_DECLARE_OPTIONAL_FN(char *, ssl_var_lookup,
31                         (apr_pool_t *, server_rec *,
32                          conn_rec *, request_rec *, char *));
33 #endif
34
35 #ifndef MAX
36 #define MAX(x,y) ((x) >= (y) ? (x) : (y))
37 #endif
38
39 static const char * const proxy_id = "proxy";
40 apr_global_mutex_t *proxy_mutex = NULL;
41
42 /*
43  * A Web proxy module. Stages:
44  *
45  *  translate_name: set filename to proxy:<URL>
46  *  map_to_storage: run proxy_walk (rather than directory_walk/file_walk)
47  *                  can't trust directory_walk/file_walk since these are
48  *                  not in our filesystem.  Prevents mod_http from serving
49  *                  the TRACE request we will set aside to handle later.
50  *  fix_ups:        convert the URL stored in the filename to the
51  *                  canonical form.
52  *  handler:        handle proxy requests
53  */
54
55 /* -------------------------------------------------------------- */
56 /* Translate the URL into a 'filename' */
57
58 static const char *set_worker_param(apr_pool_t *p,
59                                     proxy_worker *worker,
60                                     const char *key,
61                                     const char *val)
62 {
63
64     int ival;
65     apr_interval_time_t timeout;
66
67     if (!strcasecmp(key, "loadfactor")) {
68         /* Normalized load factor. Used with BalancerMamber,
69          * it is a number between 1 and 100.
70          */
71         worker->s->lbfactor = atoi(val);
72         if (worker->s->lbfactor < 1 || worker->s->lbfactor > 100)
73             return "LoadFactor must be a number between 1..100";
74     }
75     else if (!strcasecmp(key, "retry")) {
76         /* If set it will give the retry timeout for the worker
77          * The default value is 60 seconds, meaning that if
78          * in error state, it will be retried after that timeout.
79          */
80         ival = atoi(val);
81         if (ival < 0)
82             return "Retry must be a positive value";
83         worker->s->retry = apr_time_from_sec(ival);
84         worker->s->retry_set = 1;
85     }
86     else if (!strcasecmp(key, "ttl")) {
87         /* Time in seconds that will destroy all the connections
88          * that exceed the smax
89          */
90         ival = atoi(val);
91         if (ival < 1)
92             return "TTL must be at least one second";
93         worker->s->ttl = apr_time_from_sec(ival);
94     }
95     else if (!strcasecmp(key, "min")) {
96         /* Initial number of connections to remote
97          */
98         ival = atoi(val);
99         if (ival < 0)
100             return "Min must be a positive number";
101         worker->s->min = ival;
102     }
103     else if (!strcasecmp(key, "max")) {
104         /* Maximum number of connections to remote
105          */
106         ival = atoi(val);
107         if (ival < 0)
108             return "Max must be a positive number";
109         worker->s->hmax = ival;
110     }
111     /* XXX: More inteligent naming needed */
112     else if (!strcasecmp(key, "smax")) {
113         /* Maximum number of connections to remote that
114          * will not be destroyed
115          */
116         ival = atoi(val);
117         if (ival < 0)
118             return "Smax must be a positive number";
119         worker->s->smax = ival;
120     }
121     else if (!strcasecmp(key, "acquire")) {
122         /* Acquire timeout in given unit (default is milliseconds).
123          * If set this will be the maximum time to
124          * wait for a free connection.
125          */
126         if (ap_timeout_parameter_parse(val, &timeout, "ms") != APR_SUCCESS)
127             return "Acquire timeout has wrong format";
128         if (timeout < 1000)
129             return "Acquire must be at least one millisecond";
130         worker->s->acquire = timeout;
131         worker->s->acquire_set = 1;
132     }
133     else if (!strcasecmp(key, "timeout")) {
134         /* Connection timeout in seconds.
135          * Defaults to server timeout.
136          */
137         ival = atoi(val);
138         if (ival < 1)
139             return "Timeout must be at least one second";
140         worker->s->timeout = apr_time_from_sec(ival);
141         worker->s->timeout_set = 1;
142     }
143     else if (!strcasecmp(key, "iobuffersize")) {
144         long s = atol(val);
145         if (s < 512 && s) {
146             return "IOBufferSize must be >= 512 bytes, or 0 for system default.";
147         }
148         worker->s->io_buffer_size = (s ? s : AP_IOBUFSIZE);
149         worker->s->io_buffer_size_set = 1;
150     }
151     else if (!strcasecmp(key, "receivebuffersize")) {
152         ival = atoi(val);
153         if (ival < 512 && ival != 0) {
154             return "ReceiveBufferSize must be >= 512 bytes, or 0 for system default.";
155         }
156         worker->s->recv_buffer_size = ival;
157         worker->s->recv_buffer_size_set = 1;
158     }
159     else if (!strcasecmp(key, "keepalive")) {
160         if (!strcasecmp(val, "on"))
161             worker->s->keepalive = 1;
162         else if (!strcasecmp(val, "off"))
163             worker->s->keepalive = 0;
164         else
165             return "KeepAlive must be On|Off";
166         worker->s->keepalive_set = 1;
167     }
168     else if (!strcasecmp(key, "disablereuse")) {
169         if (!strcasecmp(val, "on"))
170             worker->s->disablereuse = 1;
171         else if (!strcasecmp(val, "off"))
172             worker->s->disablereuse = 0;
173         else
174             return "DisableReuse must be On|Off";
175         worker->s->disablereuse_set = 1;
176     }
177     else if (!strcasecmp(key, "route")) {
178         /* Worker route.
179          */
180         if (strlen(val) >= sizeof(worker->s->route))
181             return apr_psprintf(p, "Route length must be < %d characters",
182                     (int)sizeof(worker->s->route));
183         PROXY_STRNCPY(worker->s->route, val);
184     }
185     else if (!strcasecmp(key, "redirect")) {
186         /* Worker redirection route.
187          */
188         if (strlen(val) >= sizeof(worker->s->redirect))
189             return apr_psprintf(p, "Redirect length must be < %d characters",
190                     (int)sizeof(worker->s->redirect));
191         PROXY_STRNCPY(worker->s->redirect, val);
192     }
193     else if (!strcasecmp(key, "status")) {
194         const char *v;
195         int mode = 1;
196         apr_status_t rv;
197         /* Worker status.
198          */
199         for (v = val; *v; v++) {
200             if (*v == '+') {
201                 mode = 1;
202                 v++;
203             }
204             else if (*v == '-') {
205                 mode = 0;
206                 v++;
207             }
208             rv = ap_proxy_set_wstatus(*v, mode, worker);
209             if (rv != APR_SUCCESS)
210                 return "Unknown status parameter option";
211         }
212     }
213     else if (!strcasecmp(key, "flushpackets")) {
214         if (!strcasecmp(val, "on"))
215             worker->s->flush_packets = flush_on;
216         else if (!strcasecmp(val, "off"))
217             worker->s->flush_packets = flush_off;
218         else if (!strcasecmp(val, "auto"))
219             worker->s->flush_packets = flush_auto;
220         else
221             return "flushpackets must be on|off|auto";
222     }
223     else if (!strcasecmp(key, "flushwait")) {
224         ival = atoi(val);
225         if (ival > 1000 || ival < 0) {
226             return "flushwait must be <= 1000, or 0 for system default of 10 millseconds.";
227         }
228         if (ival == 0)
229             worker->s->flush_wait = PROXY_FLUSH_WAIT;
230         else
231             worker->s->flush_wait = ival * 1000;    /* change to microseconds */
232     }
233     else if (!strcasecmp(key, "ping")) {
234         /* Ping/Pong timeout in given unit (default is second).
235          */
236         if (ap_timeout_parameter_parse(val, &timeout, "s") != APR_SUCCESS)
237             return "Ping/Pong timeout has wrong format";
238         if (timeout < 1000 && timeout >= 0)
239             return "Ping/Pong timeout must be at least one millisecond";
240         worker->s->ping_timeout = timeout;
241         worker->s->ping_timeout_set = 1;
242     }
243     else if (!strcasecmp(key, "lbset")) {
244         ival = atoi(val);
245         if (ival < 0 || ival > 99)
246             return "lbset must be between 0 and 99";
247         worker->s->lbset = ival;
248     }
249     else if (!strcasecmp(key, "connectiontimeout")) {
250         /* Request timeout in given unit (default is second).
251          * Defaults to connection timeout
252          */
253         if (ap_timeout_parameter_parse(val, &timeout, "s") != APR_SUCCESS)
254             return "Connectiontimeout has wrong format";
255         if (timeout < 1000)
256             return "Connectiontimeout must be at least one millisecond.";
257         worker->s->conn_timeout = timeout;
258         worker->s->conn_timeout_set = 1;
259     }
260     else if (!strcasecmp(key, "flusher")) {
261         if (strlen(val) >= sizeof(worker->s->flusher))
262             apr_psprintf(p, "flusher name length must be < %d characters",
263                     (int)sizeof(worker->s->flusher));
264         PROXY_STRNCPY(worker->s->flusher, val);
265     }
266     else {
267         return "unknown Worker parameter";
268     }
269     return NULL;
270 }
271
272 static const char *set_balancer_param(proxy_server_conf *conf,
273                                       apr_pool_t *p,
274                                       proxy_balancer *balancer,
275                                       const char *key,
276                                       const char *val)
277 {
278
279     int ival;
280     if (!strcasecmp(key, "stickysession")) {
281         char *path;
282         /* Balancer sticky session name.
283          * Set to something like JSESSIONID or
284          * PHPSESSIONID, etc..,
285          */
286         if (strlen(val) >= sizeof(balancer->s->sticky_path))
287             apr_psprintf(p, "stickysession length must be < %d characters",
288                     (int)sizeof(balancer->s->sticky_path));
289         PROXY_STRNCPY(balancer->s->sticky_path, val);
290         PROXY_STRNCPY(balancer->s->sticky, val);
291
292         if ((path = strchr((char *)balancer->s->sticky, '|'))) {
293             *path++ = '\0';
294             PROXY_STRNCPY(balancer->s->sticky_path, path);
295         }
296     }
297     else if (!strcasecmp(key, "stickysessionsep")) {
298         /* separator/delimiter for sessionid and route,
299          * normally '.'
300          */
301         if (strlen(val) != 1) {
302             if (!strcasecmp(val, "off"))
303                 balancer->s->sticky_separator = 0;
304             else      
305                 return "stickysessionsep must be a single character or Off";
306         }
307         else
308             balancer->s->sticky_separator = *val;
309     }
310     else if (!strcasecmp(key, "nofailover")) {
311         /* If set to 'on' the session will break
312          * if the worker is in error state or
313          * disabled.
314          */
315         if (!strcasecmp(val, "on"))
316             balancer->s->sticky_force = 1;
317         else if (!strcasecmp(val, "off"))
318             balancer->s->sticky_force = 0;
319         else
320             return "failover must be On|Off";
321     }
322     else if (!strcasecmp(key, "timeout")) {
323         /* Balancer timeout in seconds.
324          * If set this will be the maximum time to
325          * wait for a free worker.
326          * Default is not to wait.
327          */
328         ival = atoi(val);
329         if (ival < 1)
330             return "timeout must be at least one second";
331         balancer->s->timeout = apr_time_from_sec(ival);
332     }
333     else if (!strcasecmp(key, "maxattempts")) {
334         /* Maximum number of failover attempts before
335          * giving up.
336          */
337         ival = atoi(val);
338         if (ival < 0)
339             return "maximum number of attempts must be a positive number";
340         balancer->s->max_attempts = ival;
341         balancer->s->max_attempts_set = 1;
342     }
343     else if (!strcasecmp(key, "lbmethod")) {
344         proxy_balancer_method *provider;
345         if (strlen(val) > (sizeof(balancer->s->lbpname)-1))
346             return "unknown lbmethod";
347         provider = ap_lookup_provider(PROXY_LBMETHOD, val, "0");
348         if (provider) {
349             balancer->lbmethod = provider;
350             if (PROXY_STRNCPY(balancer->s->lbpname, val) == APR_SUCCESS) {
351                 return NULL;
352             }
353             else {
354                 return "lbmethod name too large";
355             }
356         }
357         return "unknown lbmethod";
358     }
359     else if (!strcasecmp(key, "scolonpathdelim")) {
360         /* If set to 'on' then ';' will also be
361          * used as a session path separator/delim (ala
362          * mod_jk)
363          */
364         if (!strcasecmp(val, "on"))
365             balancer->s->scolonsep = 1;
366         else if (!strcasecmp(val, "off"))
367             balancer->s->scolonsep = 0;
368         else
369             return "scolonpathdelim must be On|Off";
370     }
371     else if (!strcasecmp(key, "failonstatus")) {
372         char *val_split;
373         char *status;
374         char *tok_state;
375
376         val_split = apr_pstrdup(p, val);
377
378         balancer->errstatuses = apr_array_make(p, 1, sizeof(int));
379
380         status = apr_strtok(val_split, ", ", &tok_state);
381         while (status != NULL) {
382             ival = atoi(status);
383             if (ap_is_HTTP_VALID_RESPONSE(ival)) {
384                 *(int *)apr_array_push(balancer->errstatuses) = ival;
385             }
386             else {
387                 return "failonstatus must be one or more HTTP response codes";
388             }
389             status = apr_strtok(NULL, ", ", &tok_state);
390         }
391
392     }
393     else if (!strcasecmp(key, "failontimeout")) {
394         if (!strcasecmp(val, "on"))
395             balancer->failontimeout = 1;
396         else if (!strcasecmp(val, "off"))
397             balancer->failontimeout = 0;
398         else
399             return "failontimeout must be On|Off";
400     }
401     else if (!strcasecmp(key, "nonce")) {
402         if (!strcasecmp(val, "None")) {
403             *balancer->s->nonce = '\0';
404         }
405         else {
406             if (PROXY_STRNCPY(balancer->s->nonce, val) != APR_SUCCESS) {
407                 return "Provided nonce is too large";
408             }
409         }
410     }
411     else if (!strcasecmp(key, "growth")) {
412         ival = atoi(val);
413         if (ival < 1 || ival > 100)   /* arbitrary limit here */
414             return "growth must be between 1 and 100";
415         balancer->growth = ival;
416     }
417     else if (!strcasecmp(key, "forcerecovery")) {
418         if (!strcasecmp(val, "on"))
419             balancer->s->forcerecovery = 1;
420         else if (!strcasecmp(val, "off"))
421             balancer->s->forcerecovery = 0;
422         else
423             return "forcerecovery must be On|Off";
424     }
425     else {
426         return "unknown Balancer parameter";
427     }
428     return NULL;
429 }
430
431 static int alias_match(const char *uri, const char *alias_fakename)
432 {
433     const char *end_fakename = alias_fakename + strlen(alias_fakename);
434     const char *aliasp = alias_fakename, *urip = uri;
435     const char *end_uri = uri + strlen(uri);
436
437     while (aliasp < end_fakename && urip < end_uri) {
438         if (*aliasp == '/') {
439             /* any number of '/' in the alias matches any number in
440              * the supplied URI, but there must be at least one...
441              */
442             if (*urip != '/')
443                 return 0;
444
445             while (*aliasp == '/')
446                 ++aliasp;
447             while (*urip == '/')
448                 ++urip;
449         }
450         else {
451             /* Other characters are compared literally */
452             if (*urip++ != *aliasp++)
453                 return 0;
454         }
455     }
456
457     /* fixup badly encoded stuff (e.g. % as last character) */
458     if (aliasp > end_fakename) {
459         aliasp = end_fakename;
460     }
461     if (urip > end_uri) {
462         urip = end_uri;
463     }
464
465    /* We reach the end of the uri before the end of "alias_fakename"
466     * for example uri is "/" and alias_fakename "/examples"
467     */
468    if (urip == end_uri && aliasp != end_fakename) {
469        return 0;
470    }
471
472     /* Check last alias path component matched all the way */
473     if (aliasp[-1] != '/' && *urip != '\0' && *urip != '/')
474         return 0;
475
476     /* Return number of characters from URI which matched (may be
477      * greater than length of alias, since we may have matched
478      * doubled slashes)
479      */
480
481     return urip - uri;
482 }
483
484 /* Detect if an absoluteURI should be proxied or not.  Note that we
485  * have to do this during this phase because later phases are
486  * "short-circuiting"... i.e. translate_names will end when the first
487  * module returns OK.  So for example, if the request is something like:
488  *
489  * GET http://othervhost/cgi-bin/printenv HTTP/1.0
490  *
491  * mod_alias will notice the /cgi-bin part and ScriptAlias it and
492  * short-circuit the proxy... just because of the ordering in the
493  * configuration file.
494  */
495 static int proxy_detect(request_rec *r)
496 {
497     void *sconf = r->server->module_config;
498     proxy_server_conf *conf =
499         (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
500
501     /* Ick... msvc (perhaps others) promotes ternary short results to int */
502
503     if (conf->req && r->parsed_uri.scheme) {
504         /* but it might be something vhosted */
505         if (!(r->parsed_uri.hostname
506               && !strcasecmp(r->parsed_uri.scheme, ap_http_scheme(r))
507               && ap_matches_request_vhost(r, r->parsed_uri.hostname,
508                                           (apr_port_t)(r->parsed_uri.port_str ? r->parsed_uri.port
509                                                        : ap_default_port(r))))) {
510             r->proxyreq = PROXYREQ_PROXY;
511             r->uri = r->unparsed_uri;
512             r->filename = apr_pstrcat(r->pool, "proxy:", r->uri, NULL);
513             r->handler = "proxy-server";
514         }
515     }
516     /* We need special treatment for CONNECT proxying: it has no scheme part */
517     else if (conf->req && r->method_number == M_CONNECT
518              && r->parsed_uri.hostname
519              && r->parsed_uri.port_str) {
520         r->proxyreq = PROXYREQ_PROXY;
521         r->uri = r->unparsed_uri;
522         r->filename = apr_pstrcat(r->pool, "proxy:", r->uri, NULL);
523         r->handler = "proxy-server";
524     }
525     return DECLINED;
526 }
527
528 static const char *proxy_interpolate(request_rec *r, const char *str)
529 {
530     /* Interpolate an env str in a configuration string
531      * Syntax ${var} --> value_of(var)
532      * Method: replace one var, and recurse on remainder of string
533      * Nothing clever here, and crap like nested vars may do silly things
534      * but we'll at least avoid sending the unwary into a loop
535      */
536     const char *start;
537     const char *end;
538     const char *var;
539     const char *val;
540     const char *firstpart;
541
542     start = ap_strstr_c(str, "${");
543     if (start == NULL) {
544         return str;
545     }
546     end = ap_strchr_c(start+2, '}');
547     if (end == NULL) {
548         return str;
549     }
550     /* OK, this is syntax we want to interpolate.  Is there such a var ? */
551     var = apr_pstrndup(r->pool, start+2, end-(start+2));
552     val = apr_table_get(r->subprocess_env, var);
553     firstpart = apr_pstrndup(r->pool, str, (start-str));
554
555     if (val == NULL) {
556         return apr_pstrcat(r->pool, firstpart,
557                            proxy_interpolate(r, end+1), NULL);
558     }
559     else {
560         return apr_pstrcat(r->pool, firstpart, val,
561                            proxy_interpolate(r, end+1), NULL);
562     }
563 }
564 static apr_array_header_t *proxy_vars(request_rec *r,
565                                       apr_array_header_t *hdr)
566 {
567     int i;
568     apr_array_header_t *ret = apr_array_make(r->pool, hdr->nelts,
569                                              sizeof (struct proxy_alias));
570     struct proxy_alias *old = (struct proxy_alias *) hdr->elts;
571
572     for (i = 0; i < hdr->nelts; ++i) {
573         struct proxy_alias *newcopy = apr_array_push(ret);
574         newcopy->fake = (old[i].flags & PROXYPASS_INTERPOLATE)
575                         ? proxy_interpolate(r, old[i].fake) : old[i].fake;
576         newcopy->real = (old[i].flags & PROXYPASS_INTERPOLATE)
577                         ? proxy_interpolate(r, old[i].real) : old[i].real;
578     }
579     return ret;
580 }
581
582 PROXY_DECLARE(int) ap_proxy_trans_match(request_rec *r, struct proxy_alias *ent,
583                                         proxy_dir_conf *dconf)
584 {
585     int len;
586     const char *fake;
587     const char *real;
588     ap_regmatch_t regm[AP_MAX_REG_MATCH];
589     ap_regmatch_t reg1[AP_MAX_REG_MATCH];
590     char *found = NULL;
591     int mismatch = 0;
592     unsigned int nocanon = ent->flags & PROXYPASS_NOCANON;
593     const char *use_uri = nocanon ? r->unparsed_uri : r->uri;
594
595     if (dconf && (dconf->interpolate_env == 1) && (ent->flags & PROXYPASS_INTERPOLATE)) {
596         fake = proxy_interpolate(r, ent->fake);
597         real = proxy_interpolate(r, ent->real);
598     }
599     else {
600         fake = ent->fake;
601         real = ent->real;
602     }
603     if (ent->regex) {
604         if (!ap_regexec(ent->regex, r->uri, AP_MAX_REG_MATCH, regm, 0)) {
605             if ((real[0] == '!') && (real[1] == '\0')) {
606                 return DECLINED;
607             }
608             /* test that we haven't reduced the URI */
609             if (nocanon && ap_regexec(ent->regex, r->unparsed_uri,
610                     AP_MAX_REG_MATCH, reg1, 0)) {
611                 mismatch = 1;
612                 use_uri = r->uri;
613             }
614             found = ap_pregsub(r->pool, real, use_uri, AP_MAX_REG_MATCH,
615                     (use_uri == r->uri) ? regm : reg1);
616             if (!found) {
617                 ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(01135)
618                               "Substitution in regular expression failed. "
619                               "Replacement too long?");
620                 return HTTP_INTERNAL_SERVER_ERROR;
621             }
622
623             /* Note: The strcmp() below catches cases where there
624              * was no regex substitution. This is so cases like:
625              *
626              *    ProxyPassMatch \.gif balancer://foo
627              *
628              * will work "as expected". The upshot is that the 2
629              * directives below act the exact same way (ie: $1 is implied):
630              *
631              *    ProxyPassMatch ^(/.*\.gif)$ balancer://foo
632              *    ProxyPassMatch ^(/.*\.gif)$ balancer://foo$1
633              *
634              * which may be confusing.
635              */
636             if (strcmp(found, real) != 0) {
637                 found = apr_pstrcat(r->pool, "proxy:", found, NULL);
638             }
639             else {
640                 found = apr_pstrcat(r->pool, "proxy:", real, use_uri, NULL);
641             }
642         }
643     }
644     else {
645         len = alias_match(r->uri, fake);
646
647         if (len != 0) {
648             if ((real[0] == '!') && (real[1] == '\0')) {
649                 return DECLINED;
650             }
651             if (nocanon && len != alias_match(r->unparsed_uri, ent->fake)) {
652                 mismatch = 1;
653                 use_uri = r->uri;
654             }
655             found = apr_pstrcat(r->pool, "proxy:", real, use_uri + len, NULL);
656         }
657     }
658     if (mismatch) {
659         /* We made a reducing transformation, so we can't safely use
660          * unparsed_uri.  Safe fallback is to ignore nocanon.
661          */
662         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01136)
663                 "Unescaped URL path matched ProxyPass; ignoring unsafe nocanon");
664     }
665
666     if (found) {
667         r->filename = found;
668         r->handler = "proxy-server";
669         r->proxyreq = PROXYREQ_REVERSE;
670         if (nocanon && !mismatch) {
671             /* mod_proxy_http needs to be told.  Different module. */
672             apr_table_setn(r->notes, "proxy-nocanon", "1");
673         }
674         if (ent->flags & PROXYPASS_NOQUERY) {
675             apr_table_setn(r->notes, "proxy-noquery", "1");
676         }
677         return OK;
678     }
679
680     return DONE;
681 }
682
683 static int proxy_trans(request_rec *r)
684 {
685     int i;
686     struct proxy_alias *ent;
687     proxy_dir_conf *dconf;
688     proxy_server_conf *conf;
689
690     if (r->proxyreq) {
691         /* someone has already set up the proxy, it was possibly ourselves
692          * in proxy_detect
693          */
694         return OK;
695     }
696
697     if ((r->unparsed_uri[0] == '*' && r->unparsed_uri[1] == '\0')
698         || !r->uri || r->uri[0] != '/') {
699         return DECLINED;
700     }
701
702     /* XXX: since r->uri has been manipulated already we're not really
703      * compliant with RFC1945 at this point.  But this probably isn't
704      * an issue because this is a hybrid proxy/origin server.
705      */
706
707     dconf = ap_get_module_config(r->per_dir_config, &proxy_module);
708
709     /* short way - this location is reverse proxied? */
710     if (dconf->alias) {
711         int rv = ap_proxy_trans_match(r, dconf->alias, dconf);
712         if (DONE != rv) {
713             return rv;
714         }
715     }
716
717     conf = (proxy_server_conf *) ap_get_module_config(r->server->module_config,
718                                                       &proxy_module);
719
720     /* long way - walk the list of aliases, find a match */
721     if (conf->aliases->nelts) {
722         ent = (struct proxy_alias *) conf->aliases->elts;
723         for (i = 0; i < conf->aliases->nelts; i++) {
724             int rv = ap_proxy_trans_match(r, &ent[i], dconf);
725             if (DONE != rv) {
726                 return rv;
727             }
728         }
729     }
730     return DECLINED;
731 }
732
733 static int proxy_walk(request_rec *r)
734 {
735     proxy_server_conf *sconf = ap_get_module_config(r->server->module_config,
736                                                     &proxy_module);
737     ap_conf_vector_t *per_dir_defaults = r->server->lookup_defaults;
738     ap_conf_vector_t **sec_proxy = (ap_conf_vector_t **) sconf->sec_proxy->elts;
739     ap_conf_vector_t *entry_config;
740     proxy_dir_conf *entry_proxy;
741     int num_sec = sconf->sec_proxy->nelts;
742     /* XXX: shouldn't we use URI here?  Canonicalize it first?
743      * Pass over "proxy:" prefix
744      */
745     const char *proxyname = r->filename + 6;
746     int j;
747
748     for (j = 0; j < num_sec; ++j)
749     {
750         entry_config = sec_proxy[j];
751         entry_proxy = ap_get_module_config(entry_config, &proxy_module);
752
753         /* XXX: What about case insensitive matching ???
754          * Compare regex, fnmatch or string as appropriate
755          * If the entry doesn't relate, then continue
756          */
757         if (entry_proxy->r
758               ? ap_regexec(entry_proxy->r, proxyname, 0, NULL, 0)
759               : (entry_proxy->p_is_fnmatch
760                    ? apr_fnmatch(entry_proxy->p, proxyname, 0)
761                    : strncmp(proxyname, entry_proxy->p,
762                                         strlen(entry_proxy->p)))) {
763             continue;
764         }
765         per_dir_defaults = ap_merge_per_dir_configs(r->pool, per_dir_defaults,
766                                                              entry_config);
767     }
768
769     r->per_dir_config = per_dir_defaults;
770
771     return OK;
772 }
773
774 static int proxy_map_location(request_rec *r)
775 {
776     int access_status;
777
778     if (!r->proxyreq || !r->filename || strncmp(r->filename, "proxy:", 6) != 0)
779         return DECLINED;
780
781     /* Don't let the core or mod_http map_to_storage hooks handle this,
782      * We don't need directory/file_walk, and we want to TRACE on our own.
783      */
784     if ((access_status = proxy_walk(r))) {
785         ap_die(access_status, r);
786         return access_status;
787     }
788
789     return OK;
790 }
791
792 /* -------------------------------------------------------------- */
793 /* Fixup the filename */
794
795 /*
796  * Canonicalise the URL
797  */
798 static int proxy_fixup(request_rec *r)
799 {
800     char *url, *p;
801     int access_status;
802     proxy_dir_conf *dconf = ap_get_module_config(r->per_dir_config,
803                                                  &proxy_module);
804
805     if (!r->proxyreq || !r->filename || strncmp(r->filename, "proxy:", 6) != 0)
806         return DECLINED;
807
808     /* XXX: Shouldn't we try this before we run the proxy_walk? */
809     url = &r->filename[6];
810
811     if ((dconf->interpolate_env == 1) && (r->proxyreq == PROXYREQ_REVERSE)) {
812         /* create per-request copy of reverse proxy conf,
813          * and interpolate vars in it
814          */
815         proxy_req_conf *rconf = apr_palloc(r->pool, sizeof(proxy_req_conf));
816         ap_set_module_config(r->request_config, &proxy_module, rconf);
817         rconf->raliases = proxy_vars(r, dconf->raliases);
818         rconf->cookie_paths = proxy_vars(r, dconf->cookie_paths);
819         rconf->cookie_domains = proxy_vars(r, dconf->cookie_domains);
820     }
821
822     /* canonicalise each specific scheme */
823     if ((access_status = proxy_run_canon_handler(r, url))) {
824         return access_status;
825     }
826
827     p = strchr(url, ':');
828     if (p == NULL || p == url)
829         return HTTP_BAD_REQUEST;
830
831     return OK;      /* otherwise; we've done the best we can */
832 }
833 /* Send a redirection if the request contains a hostname which is not */
834 /* fully qualified, i.e. doesn't have a domain name appended. Some proxy */
835 /* servers like Netscape's allow this and access hosts from the local */
836 /* domain in this case. I think it is better to redirect to a FQDN, since */
837 /* these will later be found in the bookmarks files. */
838 /* The "ProxyDomain" directive determines what domain will be appended */
839 static int proxy_needsdomain(request_rec *r, const char *url, const char *domain)
840 {
841     char *nuri;
842     const char *ref;
843
844     /* We only want to worry about GETs */
845     if (!r->proxyreq || r->method_number != M_GET || !r->parsed_uri.hostname)
846         return DECLINED;
847
848     /* If host does contain a dot already, or it is "localhost", decline */
849     if (strchr(r->parsed_uri.hostname, '.') != NULL /* has domain, or IPv4 literal */
850      || strchr(r->parsed_uri.hostname, ':') != NULL /* IPv6 literal */
851      || strcasecmp(r->parsed_uri.hostname, "localhost") == 0)
852         return DECLINED;    /* host name has a dot already */
853
854     ref = apr_table_get(r->headers_in, "Referer");
855
856     /* Reassemble the request, but insert the domain after the host name */
857     /* Note that the domain name always starts with a dot */
858     r->parsed_uri.hostname = apr_pstrcat(r->pool, r->parsed_uri.hostname,
859                                          domain, NULL);
860     nuri = apr_uri_unparse(r->pool,
861                            &r->parsed_uri,
862                            APR_URI_UNP_REVEALPASSWORD);
863
864     apr_table_setn(r->headers_out, "Location", nuri);
865     ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(01138)
866                   "Domain missing: %s sent to %s%s%s", r->uri,
867                   apr_uri_unparse(r->pool, &r->parsed_uri,
868                                   APR_URI_UNP_OMITUSERINFO),
869                   ref ? " from " : "", ref ? ref : "");
870
871     return HTTP_MOVED_PERMANENTLY;
872 }
873
874 /* -------------------------------------------------------------- */
875 /* Invoke handler */
876
877 static int proxy_handler(request_rec *r)
878 {
879     char *uri, *scheme, *p;
880     const char *p2;
881     void *sconf = r->server->module_config;
882     proxy_server_conf *conf = (proxy_server_conf *)
883         ap_get_module_config(sconf, &proxy_module);
884     apr_array_header_t *proxies = conf->proxies;
885     struct proxy_remote *ents = (struct proxy_remote *) proxies->elts;
886     int i, rc, access_status;
887     int direct_connect = 0;
888     const char *str;
889     apr_int64_t maxfwd;
890     proxy_balancer *balancer = NULL;
891     proxy_worker *worker = NULL;
892     int attempts = 0, max_attempts = 0;
893     struct dirconn_entry *list = (struct dirconn_entry *)conf->dirconn->elts;
894
895     /* is this for us? */
896     if (!r->proxyreq || !r->filename || strncmp(r->filename, "proxy:", 6) != 0)
897         return DECLINED;
898
899     /* handle max-forwards / OPTIONS / TRACE */
900     if ((str = apr_table_get(r->headers_in, "Max-Forwards"))) {
901         char *end;
902         maxfwd = apr_strtoi64(str, &end, 10);
903         if (maxfwd < 0 || maxfwd == APR_INT64_MAX || *end) {
904             return ap_proxyerror(r, HTTP_BAD_REQUEST,
905                     apr_psprintf(r->pool,
906                             "Max-Forwards value '%s' could not be parsed", str));
907         }
908         else if (maxfwd == 0) {
909             switch (r->method_number) {
910             case M_TRACE: {
911                 int access_status;
912                 r->proxyreq = PROXYREQ_NONE;
913                 if ((access_status = ap_send_http_trace(r)))
914                     ap_die(access_status, r);
915                 else
916                     ap_finalize_request_protocol(r);
917                 return OK;
918             }
919             case M_OPTIONS: {
920                 int access_status;
921                 r->proxyreq = PROXYREQ_NONE;
922                 if ((access_status = ap_send_http_options(r)))
923                     ap_die(access_status, r);
924                 else
925                     ap_finalize_request_protocol(r);
926                 return OK;
927             }
928             default: {
929                 return ap_proxyerror(r, HTTP_BAD_REQUEST,
930                                      "Max-Forwards has reached zero - proxy loop?");
931             }
932             }
933         }
934         maxfwd = (maxfwd > 0) ? maxfwd - 1 : 0;
935     }
936     else {
937         /* set configured max-forwards */
938         maxfwd = conf->maxfwd;
939     }
940     if (maxfwd >= 0) {
941         apr_table_setn(r->headers_in, "Max-Forwards",
942                        apr_psprintf(r->pool, "%" APR_INT64_T_FMT, maxfwd));
943     }
944
945     if (r->method_number == M_TRACE) {
946         core_server_config *coreconf = (core_server_config *)
947                                        ap_get_core_module_config(sconf);
948
949         if (coreconf->trace_enable == AP_TRACE_DISABLE)
950         {
951             /* Allow "error-notes" string to be printed by ap_send_error_response()
952              * Note; this goes nowhere, canned error response need an overhaul.
953              */
954             apr_table_setn(r->notes, "error-notes",
955                            "TRACE forbidden by server configuration");
956             apr_table_setn(r->notes, "verbose-error-to", "*");
957             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01139)
958                           "TRACE forbidden by server configuration");
959             return HTTP_METHOD_NOT_ALLOWED;
960         }
961
962         /* Can't test ap_should_client_block, we aren't ready to send
963          * the client a 100 Continue response till the connection has
964          * been established
965          */
966         if (coreconf->trace_enable != AP_TRACE_EXTENDED
967             && (r->read_length || r->read_chunked || r->remaining))
968         {
969             /* Allow "error-notes" string to be printed by ap_send_error_response()
970              * Note; this goes nowhere, canned error response need an overhaul.
971              */
972             apr_table_setn(r->notes, "error-notes",
973                            "TRACE with request body is not allowed");
974             apr_table_setn(r->notes, "verbose-error-to", "*");
975             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01140)
976                           "TRACE with request body is not allowed");
977             return HTTP_REQUEST_ENTITY_TOO_LARGE;
978         }
979     }
980
981     uri = r->filename + 6;
982     p = strchr(uri, ':');
983     if (p == NULL) {
984         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01141)
985                       "proxy_handler no URL in %s", r->filename);
986         return HTTP_BAD_REQUEST;
987     }
988
989     /* If the host doesn't have a domain name, add one and redirect. */
990     if (conf->domain != NULL) {
991         rc = proxy_needsdomain(r, uri, conf->domain);
992         if (ap_is_HTTP_REDIRECT(rc))
993             return HTTP_MOVED_PERMANENTLY;
994     }
995
996     scheme = apr_pstrndup(r->pool, uri, p - uri);
997     /* Check URI's destination host against NoProxy hosts */
998     /* Bypass ProxyRemote server lookup if configured as NoProxy */
999     for (direct_connect = i = 0; i < conf->dirconn->nelts &&
1000                                         !direct_connect; i++) {
1001         direct_connect = list[i].matcher(&list[i], r);
1002     }
1003 #if DEBUGGING
1004     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1005                 (direct_connect) ? "NoProxy for %s" : "UseProxy for %s",
1006                 r->uri);
1007 #endif
1008
1009     do {
1010         char *url = uri;
1011         /* Try to obtain the most suitable worker */
1012         access_status = ap_proxy_pre_request(&worker, &balancer, r, conf, &url);
1013         if (access_status != OK) {
1014             /*
1015              * Only return if access_status is not HTTP_SERVICE_UNAVAILABLE
1016              * This gives other modules the chance to hook into the
1017              * request_status hook and decide what to do in this situation.
1018              */
1019             if (access_status != HTTP_SERVICE_UNAVAILABLE)
1020                 return access_status;
1021             /*
1022              * Ensure that balancer is NULL if worker is NULL to prevent
1023              * potential problems in the post_request hook.
1024              */
1025             if (!worker)
1026                 balancer = NULL;
1027             goto cleanup;
1028         }
1029
1030         /* Initialise worker if needed, note the shared area must be initialized by the balancer logic */
1031         if (balancer) {
1032             ap_proxy_initialize_worker(worker, r->server, conf->pool);
1033         }
1034
1035         if (balancer && balancer->s->max_attempts_set && !max_attempts)
1036             max_attempts = balancer->s->max_attempts;
1037         /* firstly, try a proxy, unless a NoProxy directive is active */
1038         if (!direct_connect) {
1039             for (i = 0; i < proxies->nelts; i++) {
1040                 p2 = ap_strchr_c(ents[i].scheme, ':');  /* is it a partial URL? */
1041                 if (strcmp(ents[i].scheme, "*") == 0 ||
1042                     (ents[i].use_regex &&
1043                      ap_regexec(ents[i].regexp, url, 0, NULL, 0) == 0) ||
1044                     (p2 == NULL && strcasecmp(scheme, ents[i].scheme) == 0) ||
1045                     (p2 != NULL &&
1046                     strncasecmp(url, ents[i].scheme,
1047                                 strlen(ents[i].scheme)) == 0)) {
1048
1049                     /* handle the scheme */
1050                     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01142)
1051                                   "Trying to run scheme_handler against proxy");
1052                     access_status = proxy_run_scheme_handler(r, worker,
1053                                                              conf, url,
1054                                                              ents[i].hostname,
1055                                                              ents[i].port);
1056
1057                     /* Did the scheme handler process the request? */
1058                     if (access_status != DECLINED) {
1059                         const char *cl_a;
1060                         char *end;
1061                         apr_off_t cl;
1062
1063                         /*
1064                          * An fatal error or success, so no point in
1065                          * retrying with a direct connection.
1066                          */
1067                         if (access_status != HTTP_BAD_GATEWAY) {
1068                             goto cleanup;
1069                         }
1070                         cl_a = apr_table_get(r->headers_in, "Content-Length");
1071                         if (cl_a) {
1072                             apr_strtoff(&cl, cl_a, &end, 10);
1073                             /*
1074                              * The request body is of length > 0. We cannot
1075                              * retry with a direct connection since we already
1076                              * sent (parts of) the request body to the proxy
1077                              * and do not have any longer.
1078                              */
1079                             if (cl > 0) {
1080                                 goto cleanup;
1081                             }
1082                         }
1083                         /*
1084                          * Transfer-Encoding was set as input header, so we had
1085                          * a request body. We cannot retry with a direct
1086                          * connection for the same reason as above.
1087                          */
1088                         if (apr_table_get(r->headers_in, "Transfer-Encoding")) {
1089                             goto cleanup;
1090                         }
1091                     }
1092                 }
1093             }
1094         }
1095
1096         /* otherwise, try it direct */
1097         /* N.B. what if we're behind a firewall, where we must use a proxy or
1098         * give up??
1099         */
1100
1101         /* handle the scheme */
1102         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01143)
1103                       "Running scheme %s handler (attempt %d)",
1104                       scheme, attempts);
1105         AP_PROXY_RUN(r, worker, conf, url, attempts);
1106         access_status = proxy_run_scheme_handler(r, worker, conf,
1107                                                  url, NULL, 0);
1108         if (access_status == OK)
1109             break;
1110         else if (access_status == HTTP_INTERNAL_SERVER_ERROR) {
1111             /* Unrecoverable server error.
1112              * We can not failover to another worker.
1113              * Mark the worker as unusable if member of load balancer
1114              */
1115             if (balancer) {
1116                 worker->s->status |= PROXY_WORKER_IN_ERROR;
1117                 worker->s->error_time = apr_time_now();
1118             }
1119             break;
1120         }
1121         else if (access_status == HTTP_SERVICE_UNAVAILABLE) {
1122             /* Recoverable server error.
1123              * We can failover to another worker
1124              * Mark the worker as unusable if member of load balancer
1125              */
1126             if (balancer) {
1127                 worker->s->status |= PROXY_WORKER_IN_ERROR;
1128                 worker->s->error_time = apr_time_now();
1129             }
1130         }
1131         else {
1132             /* Unrecoverable error.
1133              * Return the origin status code to the client.
1134              */
1135             break;
1136         }
1137         /* Try again if the worker is unusable and the service is
1138          * unavailable.
1139          */
1140     } while (!PROXY_WORKER_IS_USABLE(worker) &&
1141              max_attempts > attempts++);
1142
1143     if (DECLINED == access_status) {
1144         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01144)
1145                       "No protocol handler was valid for the URL %s. "
1146                       "If you are using a DSO version of mod_proxy, make sure "
1147                       "the proxy submodules are included in the configuration "
1148                       "using LoadModule.", r->uri);
1149         access_status = HTTP_INTERNAL_SERVER_ERROR;
1150         goto cleanup;
1151     }
1152 cleanup:
1153     ap_proxy_post_request(worker, balancer, r, conf);
1154
1155     proxy_run_request_status(&access_status, r);
1156     AP_PROXY_RUN_FINISHED(r, attempts, access_status);
1157
1158     return access_status;
1159 }
1160
1161 /* -------------------------------------------------------------- */
1162 /* Setup configurable data */
1163
1164 static void * create_proxy_config(apr_pool_t *p, server_rec *s)
1165 {
1166     proxy_server_conf *ps = apr_pcalloc(p, sizeof(proxy_server_conf));
1167
1168     ps->sec_proxy = apr_array_make(p, 10, sizeof(ap_conf_vector_t *));
1169     ps->proxies = apr_array_make(p, 10, sizeof(struct proxy_remote));
1170     ps->aliases = apr_array_make(p, 10, sizeof(struct proxy_alias));
1171     ps->noproxies = apr_array_make(p, 10, sizeof(struct noproxy_entry));
1172     ps->dirconn = apr_array_make(p, 10, sizeof(struct dirconn_entry));
1173     ps->workers = apr_array_make(p, 10, sizeof(proxy_worker));
1174     ps->balancers = apr_array_make(p, 10, sizeof(proxy_balancer));
1175     ps->forward = NULL;
1176     ps->reverse = NULL;
1177     ps->domain = NULL;
1178     ps->id = apr_psprintf(p, "p%x", 1); /* simply for storage size */
1179     ps->viaopt = via_off; /* initially backward compatible with 1.3.1 */
1180     ps->viaopt_set = 0; /* 0 means default */
1181     ps->req = 0;
1182     ps->max_balancers = 0;
1183     ps->bal_persist = 0;
1184     ps->inherit = 1;
1185     ps->inherit_set = 0;
1186     ps->ppinherit = 1;
1187     ps->ppinherit_set = 0;
1188     ps->bgrowth = 5;
1189     ps->bgrowth_set = 0;
1190     ps->req_set = 0;
1191     ps->recv_buffer_size = 0; /* this default was left unset for some reason */
1192     ps->recv_buffer_size_set = 0;
1193     ps->io_buffer_size = AP_IOBUFSIZE;
1194     ps->io_buffer_size_set = 0;
1195     ps->maxfwd = DEFAULT_MAX_FORWARDS;
1196     ps->maxfwd_set = 0;
1197     ps->timeout = 0;
1198     ps->timeout_set = 0;
1199     ps->badopt = bad_error;
1200     ps->badopt_set = 0;
1201     ps->source_address = NULL;
1202     ps->source_address_set = 0;
1203     apr_pool_create_ex(&ps->pool, p, NULL, NULL);
1204
1205     return ps;
1206 }
1207
1208 static void * merge_proxy_config(apr_pool_t *p, void *basev, void *overridesv)
1209 {
1210     proxy_server_conf *ps = apr_pcalloc(p, sizeof(proxy_server_conf));
1211     proxy_server_conf *base = (proxy_server_conf *) basev;
1212     proxy_server_conf *overrides = (proxy_server_conf *) overridesv;
1213
1214     ps->inherit = (overrides->inherit_set == 0) ? base->inherit : overrides->inherit;
1215     ps->inherit_set = overrides->inherit_set || base->inherit_set;
1216
1217     ps->ppinherit = (overrides->ppinherit_set == 0) ? base->ppinherit : overrides->ppinherit;
1218     ps->ppinherit_set = overrides->ppinherit_set || base->ppinherit_set;
1219
1220     if (ps->ppinherit) {
1221         ps->proxies = apr_array_append(p, base->proxies, overrides->proxies);
1222     }
1223     else {
1224         ps->proxies = overrides->proxies;
1225     }
1226     ps->sec_proxy = apr_array_append(p, base->sec_proxy, overrides->sec_proxy);
1227     ps->aliases = apr_array_append(p, base->aliases, overrides->aliases);
1228     ps->noproxies = apr_array_append(p, base->noproxies, overrides->noproxies);
1229     ps->dirconn = apr_array_append(p, base->dirconn, overrides->dirconn);
1230     if (ps->inherit || ps->ppinherit) {
1231         ps->workers = apr_array_append(p, base->workers, overrides->workers);
1232         ps->balancers = apr_array_append(p, base->balancers, overrides->balancers);
1233     }
1234     else {
1235         ps->workers = overrides->workers;
1236         ps->balancers = overrides->balancers;
1237     }
1238     ps->forward = overrides->forward ? overrides->forward : base->forward;
1239     ps->reverse = overrides->reverse ? overrides->reverse : base->reverse;
1240
1241     ps->domain = (overrides->domain == NULL) ? base->domain : overrides->domain;
1242     ps->id = (overrides->id == NULL) ? base->id : overrides->id;
1243     ps->viaopt = (overrides->viaopt_set == 0) ? base->viaopt : overrides->viaopt;
1244     ps->viaopt_set = overrides->viaopt_set || base->viaopt_set;
1245     ps->req = (overrides->req_set == 0) ? base->req : overrides->req;
1246     ps->req_set = overrides->req_set || base->req_set;
1247     ps->bgrowth = (overrides->bgrowth_set == 0) ? base->bgrowth : overrides->bgrowth;
1248     ps->bgrowth_set = overrides->bgrowth_set || base->bgrowth_set;
1249     ps->max_balancers = overrides->max_balancers || base->max_balancers;
1250     ps->bal_persist = overrides->bal_persist;
1251     ps->recv_buffer_size = (overrides->recv_buffer_size_set == 0) ? base->recv_buffer_size : overrides->recv_buffer_size;
1252     ps->recv_buffer_size_set = overrides->recv_buffer_size_set || base->recv_buffer_size_set;
1253     ps->io_buffer_size = (overrides->io_buffer_size_set == 0) ? base->io_buffer_size : overrides->io_buffer_size;
1254     ps->io_buffer_size_set = overrides->io_buffer_size_set || base->io_buffer_size_set;
1255     ps->maxfwd = (overrides->maxfwd_set == 0) ? base->maxfwd : overrides->maxfwd;
1256     ps->maxfwd_set = overrides->maxfwd_set || base->maxfwd_set;
1257     ps->timeout = (overrides->timeout_set == 0) ? base->timeout : overrides->timeout;
1258     ps->timeout_set = overrides->timeout_set || base->timeout_set;
1259     ps->badopt = (overrides->badopt_set == 0) ? base->badopt : overrides->badopt;
1260     ps->badopt_set = overrides->badopt_set || base->badopt_set;
1261     ps->proxy_status = (overrides->proxy_status_set == 0) ? base->proxy_status : overrides->proxy_status;
1262     ps->proxy_status_set = overrides->proxy_status_set || base->proxy_status_set;
1263     ps->source_address = (overrides->source_address_set == 0) ? base->source_address : overrides->source_address;
1264     ps->source_address_set = overrides->source_address_set || base->source_address_set;
1265     ps->pool = base->pool;
1266     return ps;
1267 }
1268 static const char *set_source_address(cmd_parms *parms, void *dummy,
1269                                       const char *arg)
1270 {
1271     proxy_server_conf *psf =
1272         ap_get_module_config(parms->server->module_config, &proxy_module);
1273     struct apr_sockaddr_t *addr;
1274
1275     if (APR_SUCCESS == apr_sockaddr_info_get(&addr, arg, APR_UNSPEC, 0, 0,
1276                                              psf->pool)) {
1277         psf->source_address = addr;
1278         psf->source_address_set = 1;
1279     }
1280     else {
1281         return "ProxySourceAddress invalid value";
1282     }
1283
1284     return NULL;
1285 }
1286
1287 static void *create_proxy_dir_config(apr_pool_t *p, char *dummy)
1288 {
1289     proxy_dir_conf *new =
1290         (proxy_dir_conf *) apr_pcalloc(p, sizeof(proxy_dir_conf));
1291
1292     /* Filled in by proxysection, when applicable */
1293
1294     /* Put these in the dir config so they work inside <Location> */
1295     new->raliases = apr_array_make(p, 10, sizeof(struct proxy_alias));
1296     new->cookie_paths = apr_array_make(p, 10, sizeof(struct proxy_alias));
1297     new->cookie_domains = apr_array_make(p, 10, sizeof(struct proxy_alias));
1298     new->preserve_host_set = 0;
1299     new->preserve_host = 0;
1300     new->interpolate_env = -1; /* unset */
1301     new->error_override = 0;
1302     new->error_override_set = 0;
1303     new->add_forwarded_headers = 1;
1304
1305     return (void *) new;
1306 }
1307
1308 static void *merge_proxy_dir_config(apr_pool_t *p, void *basev, void *addv)
1309 {
1310     proxy_dir_conf *new = (proxy_dir_conf *) apr_pcalloc(p, sizeof(proxy_dir_conf));
1311     proxy_dir_conf *add = (proxy_dir_conf *) addv;
1312     proxy_dir_conf *base = (proxy_dir_conf *) basev;
1313
1314     new->p = add->p;
1315     new->p_is_fnmatch = add->p_is_fnmatch;
1316     new->r = add->r;
1317
1318     /* Put these in the dir config so they work inside <Location> */
1319     new->raliases = apr_array_append(p, base->raliases, add->raliases);
1320     new->cookie_paths
1321         = apr_array_append(p, base->cookie_paths, add->cookie_paths);
1322     new->cookie_domains
1323         = apr_array_append(p, base->cookie_domains, add->cookie_domains);
1324     new->interpolate_env = (add->interpolate_env == -1) ? base->interpolate_env
1325                                                         : add->interpolate_env;
1326     new->preserve_host = (add->preserve_host_set == 0) ? base->preserve_host
1327                                                         : add->preserve_host;
1328     new->preserve_host_set = add->preserve_host_set || base->preserve_host_set;
1329     new->error_override = (add->error_override_set == 0) ? base->error_override
1330                                                         : add->error_override;
1331     new->error_override_set = add->error_override_set || base->error_override_set;
1332     new->alias = (add->alias_set == 0) ? base->alias : add->alias;
1333     new->alias_set = add->alias_set || base->alias_set;
1334     new->add_forwarded_headers = add->add_forwarded_headers;
1335     return new;
1336 }
1337
1338 static const char *
1339     add_proxy(cmd_parms *cmd, void *dummy, const char *f1, const char *r1, int regex)
1340 {
1341     server_rec *s = cmd->server;
1342     proxy_server_conf *conf =
1343     (proxy_server_conf *) ap_get_module_config(s->module_config, &proxy_module);
1344     struct proxy_remote *new;
1345     char *p, *q;
1346     char *r, *f, *scheme;
1347     ap_regex_t *reg = NULL;
1348     int port;
1349
1350     r = apr_pstrdup(cmd->pool, r1);
1351     scheme = apr_pstrdup(cmd->pool, r1);
1352     f = apr_pstrdup(cmd->pool, f1);
1353     p = strchr(r, ':');
1354     if (p == NULL || p[1] != '/' || p[2] != '/' || p[3] == '\0') {
1355         if (regex)
1356             return "ProxyRemoteMatch: Bad syntax for a remote proxy server";
1357         else
1358             return "ProxyRemote: Bad syntax for a remote proxy server";
1359     }
1360     else {
1361         scheme[p-r] = 0;
1362     }
1363     q = strchr(p + 3, ':');
1364     if (q != NULL) {
1365         if (sscanf(q + 1, "%u", &port) != 1 || port > 65535) {
1366             if (regex)
1367                 return "ProxyRemoteMatch: Bad syntax for a remote proxy server (bad port number)";
1368             else
1369                 return "ProxyRemote: Bad syntax for a remote proxy server (bad port number)";
1370         }
1371         *q = '\0';
1372     }
1373     else
1374         port = -1;
1375     *p = '\0';
1376     if (regex) {
1377         reg = ap_pregcomp(cmd->pool, f, AP_REG_EXTENDED);
1378         if (!reg)
1379             return "Regular expression for ProxyRemoteMatch could not be compiled.";
1380     }
1381     else
1382         if (strchr(f, ':') == NULL)
1383             ap_str_tolower(f);      /* lowercase scheme */
1384     ap_str_tolower(p + 3);      /* lowercase hostname */
1385
1386     if (port == -1) {
1387         port = apr_uri_port_of_scheme(scheme);
1388     }
1389
1390     new = apr_array_push(conf->proxies);
1391     new->scheme = f;
1392     new->protocol = r;
1393     new->hostname = p + 3;
1394     new->port = port;
1395     new->regexp = reg;
1396     new->use_regex = regex;
1397     return NULL;
1398 }
1399
1400 static const char *
1401     add_proxy_noregex(cmd_parms *cmd, void *dummy, const char *f1, const char *r1)
1402 {
1403     return add_proxy(cmd, dummy, f1, r1, 0);
1404 }
1405
1406 static const char *
1407     add_proxy_regex(cmd_parms *cmd, void *dummy, const char *f1, const char *r1)
1408 {
1409     return add_proxy(cmd, dummy, f1, r1, 1);
1410 }
1411
1412 static char *de_socketfy(apr_pool_t *p, char *url)
1413 {
1414     char *ptr;
1415     /*
1416      * We could be passed a URL during the config stage that contains
1417      * the UDS path... ignore it
1418      */
1419     if (!strncasecmp(url, "unix:", 5) &&
1420         ((ptr = ap_strchr(url, '|')) != NULL)) {
1421         /* move past the 'unix:...|' UDS path info */
1422         char *ret, *c;
1423
1424         ret = ptr + 1;
1425         /* special case: "unix:....|scheme:" is OK, expand
1426          * to "unix:....|scheme://localhost"
1427          * */
1428         c = ap_strchr(ret, ':');
1429         if (c == NULL) {
1430             return NULL;
1431         }
1432         if (c[1] == '\0') {
1433             return apr_pstrcat(p, ret, "//localhost", NULL);
1434         }
1435         else {
1436             return ret;
1437         }
1438     }
1439     return url;
1440 }
1441
1442 static const char *
1443     add_pass(cmd_parms *cmd, void *dummy, const char *arg, int is_regex)
1444 {
1445     proxy_dir_conf *dconf = (proxy_dir_conf *)dummy;
1446     server_rec *s = cmd->server;
1447     proxy_server_conf *conf =
1448     (proxy_server_conf *) ap_get_module_config(s->module_config, &proxy_module);
1449     struct proxy_alias *new;
1450     char *f = cmd->path;
1451     char *r = NULL;
1452     char *word;
1453     apr_table_t *params = apr_table_make(cmd->pool, 5);
1454     const apr_array_header_t *arr;
1455     const apr_table_entry_t *elts;
1456     int i;
1457     int use_regex = is_regex;
1458     unsigned int flags = 0;
1459     const char *err;
1460
1461     err = ap_check_cmd_context(cmd, NOT_IN_DIRECTORY|NOT_IN_FILES);
1462     if (err) {
1463         return err;
1464     }
1465
1466     while (*arg) {
1467         word = ap_getword_conf(cmd->pool, &arg);
1468         if (!f) {
1469             if (!strcmp(word, "~")) {
1470                 if (is_regex) {
1471                     return "ProxyPassMatch invalid syntax ('~' usage).";
1472                 }
1473                 use_regex = 1;
1474                 continue;
1475             }
1476             f = word;
1477         }
1478         else if (!r) {
1479             r = word;
1480         }
1481         else if (!strcasecmp(word,"nocanon")) {
1482             flags |= PROXYPASS_NOCANON;
1483         }
1484         else if (!strcasecmp(word,"interpolate")) {
1485             flags |= PROXYPASS_INTERPOLATE;
1486         }
1487         else if (!strcasecmp(word,"noquery")) {
1488             flags |= PROXYPASS_NOQUERY;
1489         }
1490         else {
1491             char *val = strchr(word, '=');
1492             if (!val) {
1493                 if (cmd->path) {
1494                     if (*r == '/') {
1495                         return "ProxyPass|ProxyPassMatch can not have a path when defined in "
1496                                "a location.";
1497                     }
1498                     else {
1499                         return "Invalid ProxyPass|ProxyPassMatch parameter. Parameter must "
1500                                "be in the form 'key=value'.";
1501                     }
1502                 }
1503                 else {
1504                     return "Invalid ProxyPass|ProxyPassMatch parameter. Parameter must be "
1505                            "in the form 'key=value'.";
1506                 }
1507             }
1508             else
1509                 *val++ = '\0';
1510             apr_table_setn(params, word, val);
1511         }
1512     };
1513
1514     if (r == NULL) {
1515         return "ProxyPass|ProxyPassMatch needs a path when not defined in a location";
1516     }
1517
1518     /* if per directory, save away the single alias */
1519     if (cmd->path) {
1520         dconf->alias = apr_pcalloc(cmd->pool, sizeof(struct proxy_alias));
1521         dconf->alias_set = 1;
1522         new = dconf->alias;
1523         if (apr_fnmatch_test(f)) {
1524             use_regex = 1;
1525         }
1526     }
1527     /* if per server, add to the alias array */
1528     else {
1529         new = apr_array_push(conf->aliases);
1530     }
1531
1532     new->fake = apr_pstrdup(cmd->pool, f);
1533     new->real = apr_pstrdup(cmd->pool, de_socketfy(cmd->pool, r));
1534     new->flags = flags;
1535     if (use_regex) {
1536         new->regex = ap_pregcomp(cmd->pool, f, AP_REG_EXTENDED);
1537         if (new->regex == NULL)
1538             return "Regular expression could not be compiled.";
1539     }
1540     else {
1541         new->regex = NULL;
1542     }
1543
1544     if (r[0] == '!' && r[1] == '\0')
1545         return NULL;
1546
1547     arr = apr_table_elts(params);
1548     elts = (const apr_table_entry_t *)arr->elts;
1549     /* Distinguish the balancer from worker */
1550     if (ap_proxy_valid_balancer_name(r, 9)) {
1551         proxy_balancer *balancer = ap_proxy_get_balancer(cmd->pool, conf, r, 0);
1552         if (!balancer) {
1553             const char *err = ap_proxy_define_balancer(cmd->pool, &balancer, conf, r, f, 0);
1554             if (err)
1555                 return apr_pstrcat(cmd->temp_pool, "ProxyPass ", err, NULL);
1556         }
1557         else {
1558             ap_proxy_update_balancer(cmd->pool, balancer, f);
1559         }
1560         for (i = 0; i < arr->nelts; i++) {
1561             const char *err = set_balancer_param(conf, cmd->pool, balancer, elts[i].key,
1562                                                  elts[i].val);
1563             if (err)
1564                 return apr_pstrcat(cmd->temp_pool, "ProxyPass ", err, NULL);
1565         }
1566         new->balancer = balancer;
1567     }
1568     else {
1569         proxy_worker *worker = ap_proxy_get_worker(cmd->temp_pool, NULL, conf, de_socketfy(cmd->pool, r));
1570         int reuse = 0;
1571         if (!worker) {
1572             const char *err = ap_proxy_define_worker(cmd->pool, &worker, NULL, conf, r, 0);
1573             if (err)
1574                 return apr_pstrcat(cmd->temp_pool, "ProxyPass ", err, NULL);
1575
1576             PROXY_COPY_CONF_PARAMS(worker, conf);
1577         } else {
1578             reuse = 1;
1579             ap_log_error(APLOG_MARK, APLOG_INFO, 0, cmd->server, APLOGNO(01145)
1580                          "Sharing worker '%s' instead of creating new worker '%s'",
1581                          ap_proxy_worker_name(cmd->pool, worker), new->real);
1582         }
1583
1584         for (i = 0; i < arr->nelts; i++) {
1585             if (reuse) {
1586                 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server, APLOGNO(01146)
1587                              "Ignoring parameter '%s=%s' for worker '%s' because of worker sharing",
1588                              elts[i].key, elts[i].val, ap_proxy_worker_name(cmd->pool, worker));
1589             } else {
1590                 const char *err = set_worker_param(cmd->pool, worker, elts[i].key,
1591                                                    elts[i].val);
1592                 if (err)
1593                     return apr_pstrcat(cmd->temp_pool, "ProxyPass ", err, NULL);
1594             }
1595         }
1596     }
1597     return NULL;
1598 }
1599
1600 static const char *
1601     add_pass_noregex(cmd_parms *cmd, void *dummy, const char *arg)
1602 {
1603     return add_pass(cmd, dummy, arg, 0);
1604 }
1605
1606 static const char *
1607     add_pass_regex(cmd_parms *cmd, void *dummy, const char *arg)
1608 {
1609     return add_pass(cmd, dummy, arg, 1);
1610 }
1611
1612
1613 static const char * add_pass_reverse(cmd_parms *cmd, void *dconf, const char *f,
1614                                      const char *r, const char *i)
1615 {
1616     proxy_dir_conf *conf = dconf;
1617     struct proxy_alias *new;
1618     const char *fake;
1619     const char *real;
1620     const char *interp;
1621     const char *err;
1622
1623     err = ap_check_cmd_context(cmd, NOT_IN_DIRECTORY|NOT_IN_FILES);
1624     if (err) {
1625         return err;
1626     }
1627
1628     if (cmd->path == NULL) {
1629         if (r == NULL || !strcasecmp(r, "interpolate")) {
1630             return "ProxyPassReverse needs a path when not defined in a location";
1631         }
1632         fake = f;
1633         real = r;
1634         interp = i;
1635     }
1636     else {
1637         if (r && strcasecmp(r, "interpolate")) {
1638             return "ProxyPassReverse can not have a path when defined in a location";
1639         }
1640         fake = cmd->path;
1641         real = f;
1642         interp = r;
1643     }
1644
1645     new = apr_array_push(conf->raliases);
1646     new->fake = fake;
1647     new->real = real;
1648     new->flags = interp ? PROXYPASS_INTERPOLATE : 0;
1649
1650     return NULL;
1651 }
1652 static const char* cookie_path(cmd_parms *cmd, void *dconf, const char *f,
1653                                const char *r, const char *interp)
1654 {
1655     proxy_dir_conf *conf = dconf;
1656     struct proxy_alias *new;
1657
1658     new = apr_array_push(conf->cookie_paths);
1659     new->fake = f;
1660     new->real = r;
1661     new->flags = interp ? PROXYPASS_INTERPOLATE : 0;
1662
1663     return NULL;
1664 }
1665 static const char* cookie_domain(cmd_parms *cmd, void *dconf, const char *f,
1666                                  const char *r, const char *interp)
1667 {
1668     proxy_dir_conf *conf = dconf;
1669     struct proxy_alias *new;
1670
1671     new = apr_array_push(conf->cookie_domains);
1672     new->fake = f;
1673     new->real = r;
1674     new->flags = interp ? PROXYPASS_INTERPOLATE : 0;
1675     return NULL;
1676 }
1677
1678 static const char *
1679     set_proxy_exclude(cmd_parms *parms, void *dummy, const char *arg)
1680 {
1681     server_rec *s = parms->server;
1682     proxy_server_conf *conf =
1683     ap_get_module_config(s->module_config, &proxy_module);
1684     struct noproxy_entry *new;
1685     struct noproxy_entry *list = (struct noproxy_entry *) conf->noproxies->elts;
1686     struct apr_sockaddr_t *addr;
1687     int found = 0;
1688     int i;
1689
1690     /* Don't duplicate entries */
1691     for (i = 0; i < conf->noproxies->nelts; i++) {
1692         if (strcasecmp(arg, list[i].name) == 0) { /* ignore case for host names */
1693             found = 1;
1694         }
1695     }
1696
1697     if (!found) {
1698         new = apr_array_push(conf->noproxies);
1699         new->name = arg;
1700         if (APR_SUCCESS == apr_sockaddr_info_get(&addr, new->name, APR_UNSPEC, 0, 0, parms->pool)) {
1701             new->addr = addr;
1702         }
1703         else {
1704             new->addr = NULL;
1705         }
1706     }
1707     return NULL;
1708 }
1709
1710
1711 /* Similar to set_proxy_exclude(), but defining directly connected hosts,
1712  * which should never be accessed via the configured ProxyRemote servers
1713  */
1714 static const char *
1715     set_proxy_dirconn(cmd_parms *parms, void *dummy, const char *arg)
1716 {
1717     server_rec *s = parms->server;
1718     proxy_server_conf *conf =
1719     ap_get_module_config(s->module_config, &proxy_module);
1720     struct dirconn_entry *New;
1721     struct dirconn_entry *list = (struct dirconn_entry *) conf->dirconn->elts;
1722     int found = 0;
1723     int i;
1724
1725     /* Don't duplicate entries */
1726     for (i = 0; i < conf->dirconn->nelts; i++) {
1727         if (strcasecmp(arg, list[i].name) == 0)
1728             found = 1;
1729     }
1730
1731     if (!found) {
1732         New = apr_array_push(conf->dirconn);
1733         New->name = apr_pstrdup(parms->pool, arg);
1734         New->hostaddr = NULL;
1735
1736         if (ap_proxy_is_ipaddr(New, parms->pool)) {
1737 #if DEBUGGING
1738             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1739                          "Parsed addr %s", inet_ntoa(New->addr));
1740             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1741                          "Parsed mask %s", inet_ntoa(New->mask));
1742 #endif
1743         }
1744         else if (ap_proxy_is_domainname(New, parms->pool)) {
1745             ap_str_tolower(New->name);
1746 #if DEBUGGING
1747             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1748                          "Parsed domain %s", New->name);
1749 #endif
1750         }
1751         else if (ap_proxy_is_hostname(New, parms->pool)) {
1752             ap_str_tolower(New->name);
1753 #if DEBUGGING
1754             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1755                          "Parsed host %s", New->name);
1756 #endif
1757         }
1758         else {
1759             ap_proxy_is_word(New, parms->pool);
1760 #if DEBUGGING
1761             fprintf(stderr, "Parsed word %s\n", New->name);
1762 #endif
1763         }
1764     }
1765     return NULL;
1766 }
1767
1768 static const char *
1769     set_proxy_domain(cmd_parms *parms, void *dummy, const char *arg)
1770 {
1771     proxy_server_conf *psf =
1772     ap_get_module_config(parms->server->module_config, &proxy_module);
1773
1774     if (arg[0] != '.')
1775         return "ProxyDomain: domain name must start with a dot.";
1776
1777     psf->domain = arg;
1778     return NULL;
1779 }
1780
1781 static const char *
1782     set_proxy_req(cmd_parms *parms, void *dummy, int flag)
1783 {
1784     proxy_server_conf *psf =
1785     ap_get_module_config(parms->server->module_config, &proxy_module);
1786
1787     psf->req = flag;
1788     psf->req_set = 1;
1789     return NULL;
1790 }
1791
1792 static const char *
1793     set_proxy_error_override(cmd_parms *parms, void *dconf, int flag)
1794 {
1795     proxy_dir_conf *conf = dconf;
1796
1797     conf->error_override = flag;
1798     conf->error_override_set = 1;
1799     return NULL;
1800 }
1801 static const char *
1802    add_proxy_http_headers(cmd_parms *parms, void *dconf, int flag)
1803 {
1804    proxy_dir_conf *conf = dconf;
1805    conf->add_forwarded_headers = flag;
1806    return NULL;
1807 }
1808 static const char *
1809     set_preserve_host(cmd_parms *parms, void *dconf, int flag)
1810 {
1811     proxy_dir_conf *conf = dconf;
1812
1813     conf->preserve_host = flag;
1814     conf->preserve_host_set = 1;
1815     return NULL;
1816 }
1817
1818 static const char *
1819     set_recv_buffer_size(cmd_parms *parms, void *dummy, const char *arg)
1820 {
1821     proxy_server_conf *psf =
1822     ap_get_module_config(parms->server->module_config, &proxy_module);
1823     int s = atoi(arg);
1824     if (s < 512 && s != 0) {
1825         return "ProxyReceiveBufferSize must be >= 512 bytes, or 0 for system default.";
1826     }
1827
1828     psf->recv_buffer_size = s;
1829     psf->recv_buffer_size_set = 1;
1830     return NULL;
1831 }
1832
1833 static const char *
1834     set_io_buffer_size(cmd_parms *parms, void *dummy, const char *arg)
1835 {
1836     proxy_server_conf *psf =
1837     ap_get_module_config(parms->server->module_config, &proxy_module);
1838     long s = atol(arg);
1839     if (s < 512 && s) {
1840         return "ProxyIOBufferSize must be >= 512 bytes, or 0 for system default.";
1841     }
1842     psf->io_buffer_size = (s ? s : AP_IOBUFSIZE);
1843     psf->io_buffer_size_set = 1;
1844     return NULL;
1845 }
1846
1847 static const char *
1848     set_max_forwards(cmd_parms *parms, void *dummy, const char *arg)
1849 {
1850     proxy_server_conf *psf =
1851     ap_get_module_config(parms->server->module_config, &proxy_module);
1852     long s = atol(arg);
1853
1854     psf->maxfwd = s;
1855     psf->maxfwd_set = 1;
1856     return NULL;
1857 }
1858 static const char*
1859     set_proxy_timeout(cmd_parms *parms, void *dummy, const char *arg)
1860 {
1861     proxy_server_conf *psf =
1862     ap_get_module_config(parms->server->module_config, &proxy_module);
1863     int timeout;
1864
1865     timeout = atoi(arg);
1866     if (timeout<1) {
1867         return "Proxy Timeout must be at least 1 second.";
1868     }
1869     psf->timeout_set = 1;
1870     psf->timeout = apr_time_from_sec(timeout);
1871
1872     return NULL;
1873 }
1874
1875 static const char*
1876     set_via_opt(cmd_parms *parms, void *dummy, const char *arg)
1877 {
1878     proxy_server_conf *psf =
1879     ap_get_module_config(parms->server->module_config, &proxy_module);
1880
1881     if (strcasecmp(arg, "Off") == 0)
1882         psf->viaopt = via_off;
1883     else if (strcasecmp(arg, "On") == 0)
1884         psf->viaopt = via_on;
1885     else if (strcasecmp(arg, "Block") == 0)
1886         psf->viaopt = via_block;
1887     else if (strcasecmp(arg, "Full") == 0)
1888         psf->viaopt = via_full;
1889     else {
1890         return "ProxyVia must be one of: "
1891             "off | on | full | block";
1892     }
1893
1894     psf->viaopt_set = 1;
1895     return NULL;
1896 }
1897
1898 static const char*
1899     set_bad_opt(cmd_parms *parms, void *dummy, const char *arg)
1900 {
1901     proxy_server_conf *psf =
1902     ap_get_module_config(parms->server->module_config, &proxy_module);
1903
1904     if (strcasecmp(arg, "IsError") == 0)
1905         psf->badopt = bad_error;
1906     else if (strcasecmp(arg, "Ignore") == 0)
1907         psf->badopt = bad_ignore;
1908     else if (strcasecmp(arg, "StartBody") == 0)
1909         psf->badopt = bad_body;
1910     else {
1911         return "ProxyBadHeader must be one of: "
1912             "IsError | Ignore | StartBody";
1913     }
1914
1915     psf->badopt_set = 1;
1916     return NULL;
1917 }
1918
1919 static const char*
1920     set_status_opt(cmd_parms *parms, void *dummy, const char *arg)
1921 {
1922     proxy_server_conf *psf =
1923     ap_get_module_config(parms->server->module_config, &proxy_module);
1924
1925     if (strcasecmp(arg, "Off") == 0)
1926         psf->proxy_status = status_off;
1927     else if (strcasecmp(arg, "On") == 0)
1928         psf->proxy_status = status_on;
1929     else if (strcasecmp(arg, "Full") == 0)
1930         psf->proxy_status = status_full;
1931     else {
1932         return "ProxyStatus must be one of: "
1933             "off | on | full";
1934     }
1935
1936     psf->proxy_status_set = 1;
1937     return NULL;
1938 }
1939
1940 static const char *set_bgrowth(cmd_parms *parms, void *dummy, const char *arg)
1941 {
1942     proxy_server_conf *psf =
1943     ap_get_module_config(parms->server->module_config, &proxy_module);
1944
1945     int growth = atoi(arg);
1946     if (growth < 0 || growth > 1000) {
1947         return "BalancerGrowth must be between 0 and 1000";
1948     }
1949     psf->bgrowth = growth;
1950     psf->bgrowth_set = 1;
1951
1952     return NULL;
1953 }
1954
1955 static const char *set_persist(cmd_parms *parms, void *dummy, int flag)
1956 {
1957     proxy_server_conf *psf =
1958     ap_get_module_config(parms->server->module_config, &proxy_module);
1959
1960     psf->bal_persist = flag;
1961     return NULL;
1962 }
1963
1964 static const char *set_inherit(cmd_parms *parms, void *dummy, int flag)
1965 {
1966     proxy_server_conf *psf =
1967     ap_get_module_config(parms->server->module_config, &proxy_module);
1968
1969     psf->inherit = flag;
1970     psf->inherit_set = 1;
1971     return NULL;
1972 }
1973
1974 static const char *set_ppinherit(cmd_parms *parms, void *dummy, int flag)
1975 {
1976     proxy_server_conf *psf =
1977     ap_get_module_config(parms->server->module_config, &proxy_module);
1978
1979     psf->ppinherit = flag;
1980     psf->ppinherit_set = 1;
1981     return NULL;
1982 }
1983
1984 static const char *add_member(cmd_parms *cmd, void *dummy, const char *arg)
1985 {
1986     server_rec *s = cmd->server;
1987     proxy_server_conf *conf =
1988     ap_get_module_config(s->module_config, &proxy_module);
1989     proxy_balancer *balancer;
1990     proxy_worker *worker;
1991     char *path = cmd->path;
1992     char *name = NULL;
1993     char *word;
1994     apr_table_t *params = apr_table_make(cmd->pool, 5);
1995     const apr_array_header_t *arr;
1996     const apr_table_entry_t *elts;
1997     int reuse = 0;
1998     int i;
1999     /* XXX: Should this be NOT_IN_DIRECTORY|NOT_IN_FILES? */
2000     const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS);
2001     if (err)
2002         return err;
2003
2004     if (cmd->path)
2005         path = apr_pstrdup(cmd->pool, cmd->path);
2006
2007     while (*arg) {
2008         char *val;
2009         word = ap_getword_conf(cmd->pool, &arg);
2010         val = strchr(word, '=');
2011
2012         if (!val) {
2013             if (!path)
2014                 path = word;
2015             else if (!name)
2016                 name = word;
2017             else {
2018                 if (cmd->path)
2019                     return "BalancerMember can not have a balancer name when defined in a location";
2020                 else
2021                     return "Invalid BalancerMember parameter. Parameter must "
2022                            "be in the form 'key=value'";
2023             }
2024         } else {
2025             *val++ = '\0';
2026             apr_table_setn(params, word, val);
2027         }
2028     }
2029     if (!path)
2030         return "BalancerMember must define balancer name when outside <Proxy > section";
2031     if (!name)
2032         return "BalancerMember must define remote proxy server";
2033
2034     ap_str_tolower(path);   /* lowercase scheme://hostname */
2035
2036     /* Try to find the balancer */
2037     balancer = ap_proxy_get_balancer(cmd->temp_pool, conf, path, 0);
2038     if (!balancer) {
2039         err = ap_proxy_define_balancer(cmd->pool, &balancer, conf, path, "/", 0);
2040         if (err)
2041             return apr_pstrcat(cmd->temp_pool, "BalancerMember ", err, NULL);
2042     }
2043
2044     /* Try to find existing worker */
2045     worker = ap_proxy_get_worker(cmd->temp_pool, balancer, conf, de_socketfy(cmd->temp_pool, name));
2046     if (!worker) {
2047         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server, APLOGNO(01147)
2048                      "Defining worker '%s' for balancer '%s'",
2049                      name, balancer->s->name);
2050         if ((err = ap_proxy_define_worker(cmd->pool, &worker, balancer, conf, name, 0)) != NULL)
2051             return apr_pstrcat(cmd->temp_pool, "BalancerMember ", err, NULL);
2052         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server, APLOGNO(01148)
2053                      "Defined worker '%s' for balancer '%s'",
2054                      ap_proxy_worker_name(cmd->pool, worker), balancer->s->name);
2055         PROXY_COPY_CONF_PARAMS(worker, conf);
2056     } else {
2057         reuse = 1;
2058         ap_log_error(APLOG_MARK, APLOG_INFO, 0, cmd->server, APLOGNO(01149)
2059                      "Sharing worker '%s' instead of creating new worker '%s'",
2060                      ap_proxy_worker_name(cmd->pool, worker), name);
2061     }
2062
2063     arr = apr_table_elts(params);
2064     elts = (const apr_table_entry_t *)arr->elts;
2065     for (i = 0; i < arr->nelts; i++) {
2066         if (reuse) {
2067             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server, APLOGNO(01150)
2068                          "Ignoring parameter '%s=%s' for worker '%s' because of worker sharing",
2069                          elts[i].key, elts[i].val, ap_proxy_worker_name(cmd->pool, worker));
2070         } else {
2071             err = set_worker_param(cmd->pool, worker, elts[i].key,
2072                                                elts[i].val);
2073             if (err)
2074                 return apr_pstrcat(cmd->temp_pool, "BalancerMember ", err, NULL);
2075         }
2076     }
2077
2078     return NULL;
2079 }
2080
2081 static const char *
2082     set_proxy_param(cmd_parms *cmd, void *dummy, const char *arg)
2083 {
2084     server_rec *s = cmd->server;
2085     proxy_server_conf *conf =
2086     (proxy_server_conf *) ap_get_module_config(s->module_config, &proxy_module);
2087     char *name = NULL;
2088     char *word, *val;
2089     proxy_balancer *balancer = NULL;
2090     proxy_worker *worker = NULL;
2091     int in_proxy_section = 0;
2092     /* XXX: Should this be NOT_IN_DIRECTORY|NOT_IN_FILES? */
2093     const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS);
2094     if (err)
2095         return err;
2096
2097     if (cmd->directive->parent &&
2098         strncasecmp(cmd->directive->parent->directive,
2099                     "<Proxy", 6) == 0) {
2100         const char *pargs = cmd->directive->parent->args;
2101         /* Directive inside <Proxy section
2102          * Parent directive arg is the worker/balancer name.
2103          */
2104         name = ap_getword_conf(cmd->temp_pool, &pargs);
2105         if ((word = ap_strchr(name, '>')))
2106             *word = '\0';
2107         in_proxy_section = 1;
2108     }
2109     else {
2110         /* Standard set directive with worker/balancer
2111          * name as first param.
2112          */
2113         name = ap_getword_conf(cmd->temp_pool, &arg);
2114     }
2115
2116     if (ap_proxy_valid_balancer_name(name, 9)) {
2117         balancer = ap_proxy_get_balancer(cmd->pool, conf, name, 0);
2118         if (!balancer) {
2119             if (in_proxy_section) {
2120                 err = ap_proxy_define_balancer(cmd->pool, &balancer, conf, name, "/", 0);
2121                 if (err)
2122                     return apr_pstrcat(cmd->temp_pool, "ProxySet ",
2123                                        err, NULL);
2124             }
2125             else
2126                 return apr_pstrcat(cmd->temp_pool, "ProxySet can not find '",
2127                                    name, "' Balancer.", NULL);
2128         }
2129     }
2130     else {
2131         worker = ap_proxy_get_worker(cmd->temp_pool, NULL, conf, de_socketfy(cmd->temp_pool, name));
2132         if (!worker) {
2133             if (in_proxy_section) {
2134                 err = ap_proxy_define_worker(cmd->pool, &worker, NULL,
2135                                              conf, name, 0);
2136                 if (err)
2137                     return apr_pstrcat(cmd->temp_pool, "ProxySet ",
2138                                        err, NULL);
2139             }
2140             else
2141                 return apr_pstrcat(cmd->temp_pool, "ProxySet can not find '",
2142                                    name, "' Worker.", NULL);
2143         }
2144     }
2145
2146     while (*arg) {
2147         word = ap_getword_conf(cmd->pool, &arg);
2148         val = strchr(word, '=');
2149         if (!val) {
2150             return "Invalid ProxySet parameter. Parameter must be "
2151                    "in the form 'key=value'";
2152         }
2153         else
2154             *val++ = '\0';
2155         if (worker)
2156             err = set_worker_param(cmd->pool, worker, word, val);
2157         else
2158             err = set_balancer_param(conf, cmd->pool, balancer, word, val);
2159
2160         if (err)
2161             return apr_pstrcat(cmd->temp_pool, "ProxySet: ", err, " ", word, "=", val, "; ", name, NULL);
2162     }
2163
2164     return NULL;
2165 }
2166
2167 static void ap_add_per_proxy_conf(server_rec *s, ap_conf_vector_t *dir_config)
2168 {
2169     proxy_server_conf *sconf = ap_get_module_config(s->module_config,
2170                                                     &proxy_module);
2171     void **new_space = (void **)apr_array_push(sconf->sec_proxy);
2172
2173     *new_space = dir_config;
2174 }
2175
2176 static const char *proxysection(cmd_parms *cmd, void *mconfig, const char *arg)
2177 {
2178     const char *errmsg;
2179     const char *endp = ap_strrchr_c(arg, '>');
2180     int old_overrides = cmd->override;
2181     char *old_path = cmd->path;
2182     proxy_dir_conf *conf;
2183     ap_conf_vector_t *new_dir_conf = ap_create_per_dir_config(cmd->pool);
2184     ap_regex_t *r = NULL;
2185     const command_rec *thiscmd = cmd->cmd;
2186     char *word, *val;
2187     proxy_balancer *balancer = NULL;
2188     proxy_worker *worker = NULL;
2189
2190     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
2191     proxy_server_conf *sconf =
2192     (proxy_server_conf *) ap_get_module_config(cmd->server->module_config, &proxy_module);
2193
2194     if (err != NULL) {
2195         return err;
2196     }
2197
2198     if (endp == NULL) {
2199         return apr_pstrcat(cmd->pool, cmd->cmd->name,
2200                            "> directive missing closing '>'", NULL);
2201     }
2202
2203     arg = apr_pstrndup(cmd->pool, arg, endp-arg);
2204
2205     if (!arg) {
2206         if (thiscmd->cmd_data)
2207             return "<ProxyMatch > block must specify a path";
2208         else
2209             return "<Proxy > block must specify a path";
2210     }
2211
2212     cmd->path = ap_getword_conf(cmd->pool, &arg);
2213     cmd->override = OR_ALL|ACCESS_CONF;
2214
2215     if (!strncasecmp(cmd->path, "proxy:", 6))
2216         cmd->path += 6;
2217
2218     /* XXX Ignore case?  What if we proxy a case-insensitive server?!?
2219      * While we are at it, shouldn't we also canonicalize the entire
2220      * scheme?  See proxy_fixup()
2221      */
2222     if (thiscmd->cmd_data) { /* <ProxyMatch> */
2223         r = ap_pregcomp(cmd->pool, cmd->path, AP_REG_EXTENDED);
2224         if (!r) {
2225             return "Regex could not be compiled";
2226         }
2227     }
2228
2229     /* initialize our config and fetch it */
2230     conf = ap_set_config_vectors(cmd->server, new_dir_conf, cmd->path,
2231                                  &proxy_module, cmd->pool);
2232
2233     errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_dir_conf);
2234     if (errmsg != NULL)
2235         return errmsg;
2236
2237     conf->r = r;
2238     conf->p = cmd->path;
2239     conf->p_is_fnmatch = apr_fnmatch_test(conf->p);
2240
2241     ap_add_per_proxy_conf(cmd->server, new_dir_conf);
2242
2243     if (*arg != '\0') {
2244         if (thiscmd->cmd_data)
2245             return "Multiple <ProxyMatch> arguments not (yet) supported.";
2246         if (conf->p_is_fnmatch)
2247             return apr_pstrcat(cmd->pool, thiscmd->name,
2248                                "> arguments are not supported for wildchar url.",
2249                                NULL);
2250         if (!ap_strchr_c(conf->p, ':'))
2251             return apr_pstrcat(cmd->pool, thiscmd->name,
2252                                "> arguments are not supported for non url.",
2253                                NULL);
2254         if (ap_proxy_valid_balancer_name((char *)conf->p, 9)) {
2255             balancer = ap_proxy_get_balancer(cmd->pool, sconf, conf->p, 0);
2256             if (!balancer) {
2257                 err = ap_proxy_define_balancer(cmd->pool, &balancer,
2258                                                sconf, conf->p, "/", 0);
2259                 if (err)
2260                     return apr_pstrcat(cmd->temp_pool, thiscmd->name,
2261                                        " ", err, NULL);
2262             }
2263         }
2264         else {
2265             worker = ap_proxy_get_worker(cmd->temp_pool, NULL, sconf,
2266                                          de_socketfy(cmd->temp_pool, (char*)conf->p));
2267             if (!worker) {
2268                 err = ap_proxy_define_worker(cmd->pool, &worker, NULL,
2269                                           sconf, conf->p, 0);
2270                 if (err)
2271                     return apr_pstrcat(cmd->temp_pool, thiscmd->name,
2272                                        " ", err, NULL);
2273             }
2274         }
2275         if (worker == NULL && balancer == NULL) {
2276             return apr_pstrcat(cmd->pool, thiscmd->name,
2277                                "> arguments are supported only for workers.",
2278                                NULL);
2279         }
2280         while (*arg) {
2281             word = ap_getword_conf(cmd->pool, &arg);
2282             val = strchr(word, '=');
2283             if (!val) {
2284                 return "Invalid Proxy parameter. Parameter must be "
2285                        "in the form 'key=value'";
2286             }
2287             else
2288                 *val++ = '\0';
2289             if (worker)
2290                 err = set_worker_param(cmd->pool, worker, word, val);
2291             else
2292                 err = set_balancer_param(sconf, cmd->pool, balancer,
2293                                          word, val);
2294             if (err)
2295                 return apr_pstrcat(cmd->temp_pool, thiscmd->name, " ", err, " ",
2296                                    word, "=", val, "; ", conf->p, NULL);
2297         }
2298     }
2299
2300     cmd->path = old_path;
2301     cmd->override = old_overrides;
2302
2303     return NULL;
2304 }
2305
2306 static const command_rec proxy_cmds[] =
2307 {
2308     AP_INIT_RAW_ARGS("<Proxy", proxysection, NULL, RSRC_CONF,
2309     "Container for directives affecting resources located in the proxied "
2310     "location"),
2311     AP_INIT_RAW_ARGS("<ProxyMatch", proxysection, (void*)1, RSRC_CONF,
2312     "Container for directives affecting resources located in the proxied "
2313     "location, in regular expression syntax"),
2314     AP_INIT_FLAG("ProxyRequests", set_proxy_req, NULL, RSRC_CONF,
2315      "on if the true proxy requests should be accepted"),
2316     AP_INIT_TAKE2("ProxyRemote", add_proxy_noregex, NULL, RSRC_CONF,
2317      "a scheme, partial URL or '*' and a proxy server"),
2318     AP_INIT_TAKE2("ProxyRemoteMatch", add_proxy_regex, NULL, RSRC_CONF,
2319      "a regex pattern and a proxy server"),
2320     AP_INIT_FLAG("ProxyPassInterpolateEnv", ap_set_flag_slot_char,
2321         (void*)APR_OFFSETOF(proxy_dir_conf, interpolate_env),
2322         RSRC_CONF|ACCESS_CONF, "Interpolate Env Vars in reverse Proxy") ,
2323     AP_INIT_RAW_ARGS("ProxyPass", add_pass_noregex, NULL, RSRC_CONF|ACCESS_CONF,
2324      "a virtual path and a URL"),
2325     AP_INIT_RAW_ARGS("ProxyPassMatch", add_pass_regex, NULL, RSRC_CONF|ACCESS_CONF,
2326      "a virtual path and a URL"),
2327     AP_INIT_TAKE123("ProxyPassReverse", add_pass_reverse, NULL, RSRC_CONF|ACCESS_CONF,
2328      "a virtual path and a URL for reverse proxy behaviour"),
2329     AP_INIT_TAKE23("ProxyPassReverseCookiePath", cookie_path, NULL,
2330        RSRC_CONF|ACCESS_CONF, "Path rewrite rule for proxying cookies"),
2331     AP_INIT_TAKE23("ProxyPassReverseCookieDomain", cookie_domain, NULL,
2332        RSRC_CONF|ACCESS_CONF, "Domain rewrite rule for proxying cookies"),
2333     AP_INIT_ITERATE("ProxyBlock", set_proxy_exclude, NULL, RSRC_CONF,
2334      "A list of names, hosts or domains to which the proxy will not connect"),
2335     AP_INIT_TAKE1("ProxyReceiveBufferSize", set_recv_buffer_size, NULL, RSRC_CONF,
2336      "Receive buffer size for outgoing HTTP and FTP connections in bytes"),
2337     AP_INIT_TAKE1("ProxyIOBufferSize", set_io_buffer_size, NULL, RSRC_CONF,
2338      "IO buffer size for outgoing HTTP and FTP connections in bytes"),
2339     AP_INIT_TAKE1("ProxyMaxForwards", set_max_forwards, NULL, RSRC_CONF,
2340      "The maximum number of proxies a request may be forwarded through."),
2341     AP_INIT_ITERATE("NoProxy", set_proxy_dirconn, NULL, RSRC_CONF,
2342      "A list of domains, hosts, or subnets to which the proxy will connect directly"),
2343     AP_INIT_TAKE1("ProxyDomain", set_proxy_domain, NULL, RSRC_CONF,
2344      "The default intranet domain name (in absence of a domain in the URL)"),
2345     AP_INIT_TAKE1("ProxyVia", set_via_opt, NULL, RSRC_CONF,
2346      "Configure Via: proxy header header to one of: on | off | block | full"),
2347     AP_INIT_FLAG("ProxyErrorOverride", set_proxy_error_override, NULL, RSRC_CONF|ACCESS_CONF,
2348      "use our error handling pages instead of the servers' we are proxying"),
2349     AP_INIT_FLAG("ProxyPreserveHost", set_preserve_host, NULL, RSRC_CONF|ACCESS_CONF,
2350      "on if we should preserve host header while proxying"),
2351     AP_INIT_TAKE1("ProxyTimeout", set_proxy_timeout, NULL, RSRC_CONF,
2352      "Set the timeout (in seconds) for a proxied connection. "
2353      "This overrides the server timeout"),
2354     AP_INIT_TAKE1("ProxyBadHeader", set_bad_opt, NULL, RSRC_CONF,
2355      "How to handle bad header line in response: IsError | Ignore | StartBody"),
2356     AP_INIT_RAW_ARGS("BalancerMember", add_member, NULL, RSRC_CONF|ACCESS_CONF,
2357      "A balancer name and scheme with list of params"),
2358     AP_INIT_TAKE1("BalancerGrowth", set_bgrowth, NULL, RSRC_CONF,
2359      "Number of additional Balancers that can be added post-config"),
2360     AP_INIT_FLAG("BalancerPersist", set_persist, NULL, RSRC_CONF,
2361      "on if the balancer should persist changes on reboot/restart made via the Balancer Manager"),
2362     AP_INIT_FLAG("BalancerInherit", set_inherit, NULL, RSRC_CONF,
2363      "on if this server should inherit Balancers and Workers defined in the main server "
2364      "(Setting to off recommended if using the Balancer Manager)"),
2365     AP_INIT_FLAG("ProxyPassInherit", set_ppinherit, NULL, RSRC_CONF,
2366      "on if this server should inherit all ProxyPass directives defined in the main server "
2367      "(Setting to off recommended if using the Balancer Manager)"),
2368     AP_INIT_TAKE1("ProxyStatus", set_status_opt, NULL, RSRC_CONF,
2369      "Configure Status: proxy status to one of: on | off | full"),
2370     AP_INIT_RAW_ARGS("ProxySet", set_proxy_param, NULL, RSRC_CONF|ACCESS_CONF,
2371      "A balancer or worker name with list of params"),
2372     AP_INIT_TAKE1("ProxySourceAddress", set_source_address, NULL, RSRC_CONF,
2373      "Configure local source IP used for request forward"),
2374     AP_INIT_FLAG("ProxyAddHeaders", add_proxy_http_headers, NULL, RSRC_CONF|ACCESS_CONF,
2375      "on if X-Forwarded-* headers should be added or completed"),
2376     {NULL}
2377 };
2378
2379 static APR_OPTIONAL_FN_TYPE(ssl_proxy_enable) *proxy_ssl_enable = NULL;
2380 static APR_OPTIONAL_FN_TYPE(ssl_engine_disable) *proxy_ssl_disable = NULL;
2381 static APR_OPTIONAL_FN_TYPE(ssl_is_https) *proxy_is_https = NULL;
2382 static APR_OPTIONAL_FN_TYPE(ssl_var_lookup) *proxy_ssl_val = NULL;
2383
2384 PROXY_DECLARE(int) ap_proxy_ssl_enable(conn_rec *c)
2385 {
2386     /*
2387      * if c == NULL just check if the optional function was imported
2388      * else run the optional function so ssl filters are inserted
2389      */
2390     if (proxy_ssl_enable) {
2391         return c ? proxy_ssl_enable(c) : 1;
2392     }
2393
2394     return 0;
2395 }
2396
2397 PROXY_DECLARE(int) ap_proxy_ssl_disable(conn_rec *c)
2398 {
2399     if (proxy_ssl_disable) {
2400         return proxy_ssl_disable(c);
2401     }
2402
2403     return 0;
2404 }
2405
2406 PROXY_DECLARE(int) ap_proxy_conn_is_https(conn_rec *c)
2407 {
2408     if (proxy_is_https) {
2409         return proxy_is_https(c);
2410     }
2411     else
2412         return 0;
2413 }
2414
2415 PROXY_DECLARE(const char *) ap_proxy_ssl_val(apr_pool_t *p, server_rec *s,
2416                                              conn_rec *c, request_rec *r,
2417                                              const char *var)
2418 {
2419     if (proxy_ssl_val) {
2420         /* XXX Perhaps the casting useless */
2421         return (const char *)proxy_ssl_val(p, s, c, r, (char *)var);
2422     }
2423     else
2424         return NULL;
2425 }
2426
2427 static int proxy_post_config(apr_pool_t *pconf, apr_pool_t *plog,
2428                              apr_pool_t *ptemp, server_rec *s)
2429 {
2430     apr_status_t rv = ap_global_mutex_create(&proxy_mutex, NULL,
2431             proxy_id, NULL, s, pconf, 0);
2432     if (rv != APR_SUCCESS) {
2433         ap_log_perror(APLOG_MARK, APLOG_CRIT, rv, plog, APLOGNO(02478)
2434         "failed to create %s mutex", proxy_id);
2435         return rv;
2436     }
2437
2438     proxy_ssl_enable = APR_RETRIEVE_OPTIONAL_FN(ssl_proxy_enable);
2439     proxy_ssl_disable = APR_RETRIEVE_OPTIONAL_FN(ssl_engine_disable);
2440     proxy_is_https = APR_RETRIEVE_OPTIONAL_FN(ssl_is_https);
2441     proxy_ssl_val = APR_RETRIEVE_OPTIONAL_FN(ssl_var_lookup);
2442     ap_proxy_strmatch_path = apr_strmatch_precompile(pconf, "path=", 0);
2443     ap_proxy_strmatch_domain = apr_strmatch_precompile(pconf, "domain=", 0);
2444
2445     return OK;
2446 }
2447
2448 /*
2449  *  proxy Extension to mod_status
2450  */
2451 static int proxy_status_hook(request_rec *r, int flags)
2452 {
2453     int i, n;
2454     void *sconf = r->server->module_config;
2455     proxy_server_conf *conf = (proxy_server_conf *)
2456         ap_get_module_config(sconf, &proxy_module);
2457     proxy_balancer *balancer = NULL;
2458     proxy_worker **worker = NULL;
2459
2460     if ((flags & AP_STATUS_SHORT) || conf->balancers->nelts == 0 ||
2461         conf->proxy_status == status_off)
2462         return OK;
2463
2464     balancer = (proxy_balancer *)conf->balancers->elts;
2465     for (i = 0; i < conf->balancers->nelts; i++) {
2466         ap_rputs("<hr />\n<h1>Proxy LoadBalancer Status for ", r);
2467         ap_rvputs(r, balancer->s->name, "</h1>\n\n", NULL);
2468         ap_rputs("\n\n<table border=\"0\"><tr>"
2469                  "<th>SSes</th><th>Timeout</th><th>Method</th>"
2470                  "</tr>\n<tr>", r);
2471         if (*balancer->s->sticky) {
2472             if (strcmp(balancer->s->sticky, balancer->s->sticky_path)) {
2473                 ap_rvputs(r, "<td>", balancer->s->sticky, " | ",
2474                           balancer->s->sticky_path, NULL);
2475             }
2476             else {
2477                 ap_rvputs(r, "<td>", balancer->s->sticky, NULL);
2478             }
2479         }
2480         else {
2481             ap_rputs("<td> - ", r);
2482         }
2483         ap_rprintf(r, "</td><td>%" APR_TIME_T_FMT "</td>",
2484                    apr_time_sec(balancer->s->timeout));
2485         ap_rprintf(r, "<td>%s</td>\n",
2486                    balancer->lbmethod->name);
2487         ap_rputs("</table>\n", r);
2488         ap_rputs("\n\n<table border=\"0\"><tr>"
2489                  "<th>Sch</th><th>Host</th><th>Stat</th>"
2490                  "<th>Route</th><th>Redir</th>"
2491                  "<th>F</th><th>Set</th><th>Acc</th><th>Wr</th><th>Rd</th>"
2492                  "</tr>\n", r);
2493
2494         worker = (proxy_worker **)balancer->workers->elts;
2495         for (n = 0; n < balancer->workers->nelts; n++) {
2496             char fbuf[50];
2497             ap_rvputs(r, "<tr>\n<td>", (*worker)->s->scheme, "</td>", NULL);
2498             ap_rvputs(r, "<td>", (*worker)->s->hostname, "</td><td>", NULL);
2499             ap_rvputs(r, ap_proxy_parse_wstatus(r->pool, *worker), NULL);
2500             ap_rvputs(r, "</td><td>", (*worker)->s->route, NULL);
2501             ap_rvputs(r, "</td><td>", (*worker)->s->redirect, NULL);
2502             ap_rprintf(r, "</td><td>%d</td>", (*worker)->s->lbfactor);
2503             ap_rprintf(r, "<td>%d</td>", (*worker)->s->lbset);
2504             ap_rprintf(r, "<td>%" APR_SIZE_T_FMT "</td><td>", (*worker)->s->elected);
2505             ap_rputs(apr_strfsize((*worker)->s->transferred, fbuf), r);
2506             ap_rputs("</td><td>", r);
2507             ap_rputs(apr_strfsize((*worker)->s->read, fbuf), r);
2508             ap_rputs("</td>\n", r);
2509
2510             /* TODO: Add the rest of dynamic worker data */
2511             ap_rputs("</tr>\n", r);
2512
2513             ++worker;
2514         }
2515         ap_rputs("</table>\n", r);
2516         ++balancer;
2517     }
2518     ap_rputs("<hr /><table>\n"
2519              "<tr><th>SSes</th><td>Sticky session name</td></tr>\n"
2520              "<tr><th>Timeout</th><td>Balancer Timeout</td></tr>\n"
2521              "<tr><th>Sch</th><td>Connection scheme</td></tr>\n"
2522              "<tr><th>Host</th><td>Backend Hostname</td></tr>\n"
2523              "<tr><th>Stat</th><td>Worker status</td></tr>\n"
2524              "<tr><th>Route</th><td>Session Route</td></tr>\n"
2525              "<tr><th>Redir</th><td>Session Route Redirection</td></tr>\n"
2526              "<tr><th>F</th><td>Load Balancer Factor</td></tr>\n"
2527              "<tr><th>Acc</th><td>Number of uses</td></tr>\n"
2528              "<tr><th>Wr</th><td>Number of bytes transferred</td></tr>\n"
2529              "<tr><th>Rd</th><td>Number of bytes read</td></tr>\n"
2530              "</table>", r);
2531
2532     return OK;
2533 }
2534
2535 static void child_init(apr_pool_t *p, server_rec *s)
2536 {
2537     proxy_worker *reverse = NULL;
2538
2539     apr_status_t rv = apr_global_mutex_child_init(&proxy_mutex,
2540                                       apr_global_mutex_lockfile(proxy_mutex),
2541                                       p);
2542     if (rv != APR_SUCCESS) {
2543         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s, APLOGNO(02479)
2544                      "could not init proxy_mutex in child");
2545         exit(1); /* Ugly, but what else? */
2546     }
2547
2548     /* TODO */
2549     while (s) {
2550         void *sconf = s->module_config;
2551         proxy_server_conf *conf;
2552         proxy_worker *worker;
2553         int i;
2554
2555         conf = (proxy_server_conf *)ap_get_module_config(sconf, &proxy_module);
2556         /*
2557          * NOTE: non-balancer members don't use shm at all...
2558          *       after all, why should they?
2559          */
2560         worker = (proxy_worker *)conf->workers->elts;
2561         for (i = 0; i < conf->workers->nelts; i++, worker++) {
2562             ap_proxy_initialize_worker(worker, s, conf->pool);
2563         }
2564         /* Create and initialize forward worker if defined */
2565         if (conf->req_set && conf->req) {
2566             proxy_worker *forward;
2567             ap_proxy_define_worker(p, &forward, NULL, NULL, "http://www.apache.org", 0);
2568             conf->forward = forward;
2569             PROXY_STRNCPY(conf->forward->s->name,     "proxy:forward");
2570             PROXY_STRNCPY(conf->forward->s->hostname, "*");
2571             PROXY_STRNCPY(conf->forward->s->scheme,   "*");
2572             conf->forward->hash.def = conf->forward->s->hash.def =
2573                 ap_proxy_hashfunc(conf->forward->s->name, PROXY_HASHFUNC_DEFAULT);
2574              conf->forward->hash.fnv = conf->forward->s->hash.fnv =
2575                 ap_proxy_hashfunc(conf->forward->s->name, PROXY_HASHFUNC_FNV);
2576             /* Do not disable worker in case of errors */
2577             conf->forward->s->status |= PROXY_WORKER_IGNORE_ERRORS;
2578             ap_proxy_initialize_worker(conf->forward, s, conf->pool);
2579             /* Disable address cache for generic forward worker */
2580             conf->forward->s->is_address_reusable = 0;
2581         }
2582         if (!reverse) {
2583             ap_proxy_define_worker(p, &reverse, NULL, NULL, "http://www.apache.org", 0);
2584             PROXY_STRNCPY(reverse->s->name,     "proxy:reverse");
2585             PROXY_STRNCPY(reverse->s->hostname, "*");
2586             PROXY_STRNCPY(reverse->s->scheme,   "*");
2587             reverse->hash.def = reverse->s->hash.def =
2588                 ap_proxy_hashfunc(reverse->s->name, PROXY_HASHFUNC_DEFAULT);
2589             reverse->hash.fnv = reverse->s->hash.fnv =
2590                 ap_proxy_hashfunc(reverse->s->name, PROXY_HASHFUNC_FNV);
2591             /* Do not disable worker in case of errors */
2592             reverse->s->status |= PROXY_WORKER_IGNORE_ERRORS;
2593             conf->reverse = reverse;
2594             ap_proxy_initialize_worker(conf->reverse, s, conf->pool);
2595             /* Disable address cache for generic reverse worker */
2596             reverse->s->is_address_reusable = 0;
2597         }
2598         conf->reverse = reverse;
2599         s = s->next;
2600     }
2601 }
2602
2603 /*
2604  * This routine is called before the server processes the configuration
2605  * files.
2606  */
2607 static int proxy_pre_config(apr_pool_t *pconf, apr_pool_t *plog,
2608                             apr_pool_t *ptemp)
2609 {
2610     apr_status_t rv = ap_mutex_register(pconf, proxy_id, NULL,
2611             APR_LOCK_DEFAULT, 0);
2612     if (rv != APR_SUCCESS) {
2613         ap_log_perror(APLOG_MARK, APLOG_CRIT, rv, plog, APLOGNO(02480)
2614                 "failed to register %s mutex", proxy_id);
2615         return 500; /* An HTTP status would be a misnomer! */
2616     }
2617
2618     APR_OPTIONAL_HOOK(ap, status_hook, proxy_status_hook, NULL, NULL,
2619                       APR_HOOK_MIDDLE);
2620     /* Reset workers count on gracefull restart */
2621     proxy_lb_workers = 0;
2622     return OK;
2623 }
2624 static void register_hooks(apr_pool_t *p)
2625 {
2626     /* fixup before mod_rewrite, so that the proxied url will not
2627      * escaped accidentally by our fixup.
2628      */
2629     static const char * const aszSucc[] = { "mod_rewrite.c", NULL};
2630     /* Only the mpm_winnt has child init hook handler.
2631      * make sure that we are called after the mpm
2632      * initializes.
2633      */
2634     static const char *const aszPred[] = { "mpm_winnt.c", "mod_proxy_balancer.c", NULL};
2635
2636     /* handler */
2637     ap_hook_handler(proxy_handler, NULL, NULL, APR_HOOK_FIRST);
2638     /* filename-to-URI translation */
2639     ap_hook_translate_name(proxy_trans, aszSucc, NULL, APR_HOOK_FIRST);
2640     /* walk <Proxy > entries and suppress default TRACE behavior */
2641     ap_hook_map_to_storage(proxy_map_location, NULL,NULL, APR_HOOK_FIRST);
2642     /* fixups */
2643     ap_hook_fixups(proxy_fixup, NULL, aszSucc, APR_HOOK_FIRST);
2644     /* post read_request handling */
2645     ap_hook_post_read_request(proxy_detect, NULL, NULL, APR_HOOK_FIRST);
2646     /* pre config handling */
2647     ap_hook_pre_config(proxy_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
2648     /* post config handling */
2649     ap_hook_post_config(proxy_post_config, NULL, NULL, APR_HOOK_MIDDLE);
2650     /* child init handling */
2651     ap_hook_child_init(child_init, aszPred, NULL, APR_HOOK_MIDDLE);
2652
2653     /* register optional functions within proxy_util.c */
2654     proxy_util_register_hooks(p);
2655 }
2656
2657 AP_DECLARE_MODULE(proxy) =
2658 {
2659     STANDARD20_MODULE_STUFF,
2660     create_proxy_dir_config,    /* create per-directory config structure */
2661     merge_proxy_dir_config,     /* merge per-directory config structures */
2662     create_proxy_config,        /* create per-server config structure */
2663     merge_proxy_config,         /* merge per-server config structures */
2664     proxy_cmds,                 /* command table */
2665     register_hooks
2666 };
2667
2668 APR_HOOK_STRUCT(
2669     APR_HOOK_LINK(scheme_handler)
2670     APR_HOOK_LINK(canon_handler)
2671     APR_HOOK_LINK(pre_request)
2672     APR_HOOK_LINK(post_request)
2673     APR_HOOK_LINK(request_status)
2674 )
2675
2676 APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(proxy, PROXY, int, scheme_handler,
2677                                      (request_rec *r, proxy_worker *worker,
2678                                       proxy_server_conf *conf,
2679                                       char *url, const char *proxyhost,
2680                                       apr_port_t proxyport),(r,worker,conf,
2681                                       url,proxyhost,proxyport),DECLINED)
2682 APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(proxy, PROXY, int, canon_handler,
2683                                       (request_rec *r, char *url),(r,
2684                                       url),DECLINED)
2685 APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(proxy, PROXY, int, pre_request, (
2686                                       proxy_worker **worker,
2687                                       proxy_balancer **balancer,
2688                                       request_rec *r,
2689                                       proxy_server_conf *conf,
2690                                       char **url),(worker,balancer,
2691                                       r,conf,url),DECLINED)
2692 APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(proxy, PROXY, int, post_request,
2693                                       (proxy_worker *worker,
2694                                        proxy_balancer *balancer,
2695                                        request_rec *r,
2696                                        proxy_server_conf *conf),(worker,
2697                                        balancer,r,conf),DECLINED)
2698 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(proxy, PROXY, int, fixups,
2699                                     (request_rec *r), (r),
2700                                     OK, DECLINED)
2701 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(proxy, PROXY, int, request_status,
2702                                     (int *status, request_rec *r),
2703                                     (status, r),
2704                                     OK, DECLINED)