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