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