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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "mod_proxy.h"
19 #include "apr_optional.h"
20 #include "scoreboard.h"
21 #include "mod_status.h"
22 #include "proxy_util.h"
24 #if (MODULE_MAGIC_NUMBER_MAJOR > 20020903)
27 APR_DECLARE_OPTIONAL_FN(int, ssl_proxy_enable, (conn_rec *));
28 APR_DECLARE_OPTIONAL_FN(int, ssl_engine_disable, (conn_rec *));
29 APR_DECLARE_OPTIONAL_FN(int, ssl_is_https, (conn_rec *));
30 APR_DECLARE_OPTIONAL_FN(char *, ssl_var_lookup,
31 (apr_pool_t *, server_rec *,
32 conn_rec *, request_rec *, char *));
36 #define MAX(x,y) ((x) >= (y) ? (x) : (y))
39 static const char * const proxy_id = "proxy";
40 apr_global_mutex_t *proxy_mutex = NULL;
43 * A Web proxy module. Stages:
45 * translate_name: set filename to proxy:<URL>
46 * map_to_storage: run proxy_walk (rather than directory_walk/file_walk)
47 * can't trust directory_walk/file_walk since these are
48 * not in our filesystem. Prevents mod_http from serving
49 * the TRACE request we will set aside to handle later.
50 * fix_ups: convert the URL stored in the filename to the
52 * handler: handle proxy requests
55 /* -------------------------------------------------------------- */
56 /* Translate the URL into a 'filename' */
58 static const char *set_worker_param(apr_pool_t *p,
65 apr_interval_time_t timeout;
67 if (!strcasecmp(key, "loadfactor")) {
68 /* Normalized load factor. Used with BalancerMamber,
69 * it is a number between 1 and 100.
71 worker->s->lbfactor = atoi(val);
72 if (worker->s->lbfactor < 1 || worker->s->lbfactor > 100)
73 return "LoadFactor must be a number between 1..100";
75 else if (!strcasecmp(key, "retry")) {
76 /* If set it will give the retry timeout for the worker
77 * The default value is 60 seconds, meaning that if
78 * in error state, it will be retried after that timeout.
82 return "Retry must be a positive value";
83 worker->s->retry = apr_time_from_sec(ival);
84 worker->s->retry_set = 1;
86 else if (!strcasecmp(key, "ttl")) {
87 /* Time in seconds that will destroy all the connections
88 * that exceed the smax
92 return "TTL must be at least one second";
93 worker->s->ttl = apr_time_from_sec(ival);
95 else if (!strcasecmp(key, "min")) {
96 /* Initial number of connections to remote
100 return "Min must be a positive number";
101 worker->s->min = ival;
103 else if (!strcasecmp(key, "max")) {
104 /* Maximum number of connections to remote
108 return "Max must be a positive number";
109 worker->s->hmax = ival;
111 /* XXX: More inteligent naming needed */
112 else if (!strcasecmp(key, "smax")) {
113 /* Maximum number of connections to remote that
114 * will not be destroyed
118 return "Smax must be a positive number";
119 worker->s->smax = ival;
121 else if (!strcasecmp(key, "acquire")) {
122 /* Acquire timeout in given unit (default is milliseconds).
123 * If set this will be the maximum time to
124 * wait for a free connection.
126 if (ap_timeout_parameter_parse(val, &timeout, "ms") != APR_SUCCESS)
127 return "Acquire timeout has wrong format";
129 return "Acquire must be at least one millisecond";
130 worker->s->acquire = timeout;
131 worker->s->acquire_set = 1;
133 else if (!strcasecmp(key, "timeout")) {
134 /* Connection timeout in seconds.
135 * Defaults to server timeout.
139 return "Timeout must be at least one second";
140 worker->s->timeout = apr_time_from_sec(ival);
141 worker->s->timeout_set = 1;
143 else if (!strcasecmp(key, "iobuffersize")) {
146 return "IOBufferSize must be >= 512 bytes, or 0 for system default.";
148 worker->s->io_buffer_size = (s ? s : AP_IOBUFSIZE);
149 worker->s->io_buffer_size_set = 1;
151 else if (!strcasecmp(key, "receivebuffersize")) {
153 if (ival < 512 && ival != 0) {
154 return "ReceiveBufferSize must be >= 512 bytes, or 0 for system default.";
156 worker->s->recv_buffer_size = ival;
157 worker->s->recv_buffer_size_set = 1;
159 else if (!strcasecmp(key, "keepalive")) {
160 if (!strcasecmp(val, "on"))
161 worker->s->keepalive = 1;
162 else if (!strcasecmp(val, "off"))
163 worker->s->keepalive = 0;
165 return "KeepAlive must be On|Off";
166 worker->s->keepalive_set = 1;
168 else if (!strcasecmp(key, "disablereuse")) {
169 if (!strcasecmp(val, "on"))
170 worker->s->disablereuse = 1;
171 else if (!strcasecmp(val, "off"))
172 worker->s->disablereuse = 0;
174 return "DisableReuse must be On|Off";
175 worker->s->disablereuse_set = 1;
177 else if (!strcasecmp(key, "route")) {
180 if (strlen(val) >= sizeof(worker->s->route))
181 return apr_psprintf(p, "Route length must be < %d characters",
182 (int)sizeof(worker->s->route));
183 PROXY_STRNCPY(worker->s->route, val);
185 else if (!strcasecmp(key, "redirect")) {
186 /* Worker redirection route.
188 if (strlen(val) >= sizeof(worker->s->redirect))
189 return apr_psprintf(p, "Redirect length must be < %d characters",
190 (int)sizeof(worker->s->redirect));
191 PROXY_STRNCPY(worker->s->redirect, val);
193 else if (!strcasecmp(key, "status")) {
199 for (v = val; *v; v++) {
204 else if (*v == '-') {
208 rv = ap_proxy_set_wstatus(*v, mode, worker);
209 if (rv != APR_SUCCESS)
210 return "Unknown status parameter option";
213 else if (!strcasecmp(key, "flushpackets")) {
214 if (!strcasecmp(val, "on"))
215 worker->s->flush_packets = flush_on;
216 else if (!strcasecmp(val, "off"))
217 worker->s->flush_packets = flush_off;
218 else if (!strcasecmp(val, "auto"))
219 worker->s->flush_packets = flush_auto;
221 return "flushpackets must be on|off|auto";
223 else if (!strcasecmp(key, "flushwait")) {
225 if (ival > 1000 || ival < 0) {
226 return "flushwait must be <= 1000, or 0 for system default of 10 millseconds.";
229 worker->s->flush_wait = PROXY_FLUSH_WAIT;
231 worker->s->flush_wait = ival * 1000; /* change to microseconds */
233 else if (!strcasecmp(key, "ping")) {
234 /* Ping/Pong timeout in given unit (default is second).
236 if (ap_timeout_parameter_parse(val, &timeout, "s") != APR_SUCCESS)
237 return "Ping/Pong timeout has wrong format";
238 if (timeout < 1000 && timeout >= 0)
239 return "Ping/Pong timeout must be at least one millisecond";
240 worker->s->ping_timeout = timeout;
241 worker->s->ping_timeout_set = 1;
243 else if (!strcasecmp(key, "lbset")) {
245 if (ival < 0 || ival > 99)
246 return "lbset must be between 0 and 99";
247 worker->s->lbset = ival;
249 else if (!strcasecmp(key, "connectiontimeout")) {
250 /* Request timeout in given unit (default is second).
251 * Defaults to connection timeout
253 if (ap_timeout_parameter_parse(val, &timeout, "s") != APR_SUCCESS)
254 return "Connectiontimeout has wrong format";
256 return "Connectiontimeout must be at least one millisecond.";
257 worker->s->conn_timeout = timeout;
258 worker->s->conn_timeout_set = 1;
260 else if (!strcasecmp(key, "flusher")) {
261 if (strlen(val) >= sizeof(worker->s->flusher))
262 apr_psprintf(p, "flusher name length must be < %d characters",
263 (int)sizeof(worker->s->flusher));
264 PROXY_STRNCPY(worker->s->flusher, val);
267 return "unknown Worker parameter";
272 static const char *set_balancer_param(proxy_server_conf *conf,
274 proxy_balancer *balancer,
280 if (!strcasecmp(key, "stickysession")) {
282 /* Balancer sticky session name.
283 * Set to something like JSESSIONID or
284 * PHPSESSIONID, etc..,
286 if (strlen(val) >= sizeof(balancer->s->sticky_path))
287 apr_psprintf(p, "stickysession length must be < %d characters",
288 (int)sizeof(balancer->s->sticky_path));
289 PROXY_STRNCPY(balancer->s->sticky_path, val);
290 PROXY_STRNCPY(balancer->s->sticky, val);
292 if ((path = strchr((char *)balancer->s->sticky, '|'))) {
294 PROXY_STRNCPY(balancer->s->sticky_path, path);
297 else if (!strcasecmp(key, "stickysessionsep")) {
298 /* separator/delimiter for sessionid and route,
301 if (strlen(val) != 1) {
302 if (!strcasecmp(val, "off"))
303 balancer->s->sticky_separator = 0;
305 return "stickysessionsep must be a single character or Off";
308 balancer->s->sticky_separator = *val;
310 else if (!strcasecmp(key, "nofailover")) {
311 /* If set to 'on' the session will break
312 * if the worker is in error state or
315 if (!strcasecmp(val, "on"))
316 balancer->s->sticky_force = 1;
317 else if (!strcasecmp(val, "off"))
318 balancer->s->sticky_force = 0;
320 return "failover must be On|Off";
322 else if (!strcasecmp(key, "timeout")) {
323 /* Balancer timeout in seconds.
324 * If set this will be the maximum time to
325 * wait for a free worker.
326 * Default is not to wait.
330 return "timeout must be at least one second";
331 balancer->s->timeout = apr_time_from_sec(ival);
333 else if (!strcasecmp(key, "maxattempts")) {
334 /* Maximum number of failover attempts before
339 return "maximum number of attempts must be a positive number";
340 balancer->s->max_attempts = ival;
341 balancer->s->max_attempts_set = 1;
343 else if (!strcasecmp(key, "lbmethod")) {
344 proxy_balancer_method *provider;
345 if (strlen(val) > (sizeof(balancer->s->lbpname)-1))
346 return "unknown lbmethod";
347 provider = ap_lookup_provider(PROXY_LBMETHOD, val, "0");
349 balancer->lbmethod = provider;
350 if (PROXY_STRNCPY(balancer->s->lbpname, val) == APR_SUCCESS) {
354 return "lbmethod name too large";
357 return "unknown lbmethod";
359 else if (!strcasecmp(key, "scolonpathdelim")) {
360 /* If set to 'on' then ';' will also be
361 * used as a session path separator/delim (ala
364 if (!strcasecmp(val, "on"))
365 balancer->s->scolonsep = 1;
366 else if (!strcasecmp(val, "off"))
367 balancer->s->scolonsep = 0;
369 return "scolonpathdelim must be On|Off";
371 else if (!strcasecmp(key, "failonstatus")) {
376 val_split = apr_pstrdup(p, val);
378 balancer->errstatuses = apr_array_make(p, 1, sizeof(int));
380 status = apr_strtok(val_split, ", ", &tok_state);
381 while (status != NULL) {
383 if (ap_is_HTTP_VALID_RESPONSE(ival)) {
384 *(int *)apr_array_push(balancer->errstatuses) = ival;
387 return "failonstatus must be one or more HTTP response codes";
389 status = apr_strtok(NULL, ", ", &tok_state);
393 else if (!strcasecmp(key, "failontimeout")) {
394 if (!strcasecmp(val, "on"))
395 balancer->failontimeout = 1;
396 else if (!strcasecmp(val, "off"))
397 balancer->failontimeout = 0;
399 return "failontimeout must be On|Off";
401 else if (!strcasecmp(key, "nonce")) {
402 if (!strcasecmp(val, "None")) {
403 *balancer->s->nonce = '\0';
406 if (PROXY_STRNCPY(balancer->s->nonce, val) != APR_SUCCESS) {
407 return "Provided nonce is too large";
411 else if (!strcasecmp(key, "growth")) {
413 if (ival < 1 || ival > 100) /* arbitrary limit here */
414 return "growth must be between 1 and 100";
415 balancer->growth = ival;
417 else if (!strcasecmp(key, "forcerecovery")) {
418 if (!strcasecmp(val, "on"))
419 balancer->s->forcerecovery = 1;
420 else if (!strcasecmp(val, "off"))
421 balancer->s->forcerecovery = 0;
423 return "forcerecovery must be On|Off";
426 return "unknown Balancer parameter";
431 static int alias_match(const char *uri, const char *alias_fakename)
433 const char *end_fakename = alias_fakename + strlen(alias_fakename);
434 const char *aliasp = alias_fakename, *urip = uri;
435 const char *end_uri = uri + strlen(uri);
437 while (aliasp < end_fakename && urip < end_uri) {
438 if (*aliasp == '/') {
439 /* any number of '/' in the alias matches any number in
440 * the supplied URI, but there must be at least one...
445 while (*aliasp == '/')
451 /* Other characters are compared literally */
452 if (*urip++ != *aliasp++)
457 /* fixup badly encoded stuff (e.g. % as last character) */
458 if (aliasp > end_fakename) {
459 aliasp = end_fakename;
461 if (urip > end_uri) {
465 /* We reach the end of the uri before the end of "alias_fakename"
466 * for example uri is "/" and alias_fakename "/examples"
468 if (urip == end_uri && aliasp != end_fakename) {
472 /* Check last alias path component matched all the way */
473 if (aliasp[-1] != '/' && *urip != '\0' && *urip != '/')
476 /* Return number of characters from URI which matched (may be
477 * greater than length of alias, since we may have matched
484 /* Detect if an absoluteURI should be proxied or not. Note that we
485 * have to do this during this phase because later phases are
486 * "short-circuiting"... i.e. translate_names will end when the first
487 * module returns OK. So for example, if the request is something like:
489 * GET http://othervhost/cgi-bin/printenv HTTP/1.0
491 * mod_alias will notice the /cgi-bin part and ScriptAlias it and
492 * short-circuit the proxy... just because of the ordering in the
493 * configuration file.
495 static int proxy_detect(request_rec *r)
497 void *sconf = r->server->module_config;
498 proxy_server_conf *conf =
499 (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
501 /* Ick... msvc (perhaps others) promotes ternary short results to int */
503 if (conf->req && r->parsed_uri.scheme) {
504 /* but it might be something vhosted */
505 if (!(r->parsed_uri.hostname
506 && !strcasecmp(r->parsed_uri.scheme, ap_http_scheme(r))
507 && ap_matches_request_vhost(r, r->parsed_uri.hostname,
508 (apr_port_t)(r->parsed_uri.port_str ? r->parsed_uri.port
509 : ap_default_port(r))))) {
510 r->proxyreq = PROXYREQ_PROXY;
511 r->uri = r->unparsed_uri;
512 r->filename = apr_pstrcat(r->pool, "proxy:", r->uri, NULL);
513 r->handler = "proxy-server";
516 /* We need special treatment for CONNECT proxying: it has no scheme part */
517 else if (conf->req && r->method_number == M_CONNECT
518 && r->parsed_uri.hostname
519 && r->parsed_uri.port_str) {
520 r->proxyreq = PROXYREQ_PROXY;
521 r->uri = r->unparsed_uri;
522 r->filename = apr_pstrcat(r->pool, "proxy:", r->uri, NULL);
523 r->handler = "proxy-server";
528 static const char *proxy_interpolate(request_rec *r, const char *str)
530 /* Interpolate an env str in a configuration string
531 * Syntax ${var} --> value_of(var)
532 * Method: replace one var, and recurse on remainder of string
533 * Nothing clever here, and crap like nested vars may do silly things
534 * but we'll at least avoid sending the unwary into a loop
540 const char *firstpart;
542 start = ap_strstr_c(str, "${");
546 end = ap_strchr_c(start+2, '}');
550 /* OK, this is syntax we want to interpolate. Is there such a var ? */
551 var = apr_pstrndup(r->pool, start+2, end-(start+2));
552 val = apr_table_get(r->subprocess_env, var);
553 firstpart = apr_pstrndup(r->pool, str, (start-str));
556 return apr_pstrcat(r->pool, firstpart,
557 proxy_interpolate(r, end+1), NULL);
560 return apr_pstrcat(r->pool, firstpart, val,
561 proxy_interpolate(r, end+1), NULL);
564 static apr_array_header_t *proxy_vars(request_rec *r,
565 apr_array_header_t *hdr)
568 apr_array_header_t *ret = apr_array_make(r->pool, hdr->nelts,
569 sizeof (struct proxy_alias));
570 struct proxy_alias *old = (struct proxy_alias *) hdr->elts;
572 for (i = 0; i < hdr->nelts; ++i) {
573 struct proxy_alias *newcopy = apr_array_push(ret);
574 newcopy->fake = (old[i].flags & PROXYPASS_INTERPOLATE)
575 ? proxy_interpolate(r, old[i].fake) : old[i].fake;
576 newcopy->real = (old[i].flags & PROXYPASS_INTERPOLATE)
577 ? proxy_interpolate(r, old[i].real) : old[i].real;
582 PROXY_DECLARE(int) ap_proxy_trans_match(request_rec *r, struct proxy_alias *ent,
583 proxy_dir_conf *dconf)
588 ap_regmatch_t regm[AP_MAX_REG_MATCH];
589 ap_regmatch_t reg1[AP_MAX_REG_MATCH];
592 unsigned int nocanon = ent->flags & PROXYPASS_NOCANON;
593 const char *use_uri = nocanon ? r->unparsed_uri : r->uri;
595 if (dconf && (dconf->interpolate_env == 1) && (ent->flags & PROXYPASS_INTERPOLATE)) {
596 fake = proxy_interpolate(r, ent->fake);
597 real = proxy_interpolate(r, ent->real);
604 if (!ap_regexec(ent->regex, r->uri, AP_MAX_REG_MATCH, regm, 0)) {
605 if ((real[0] == '!') && (real[1] == '\0')) {
608 /* test that we haven't reduced the URI */
609 if (nocanon && ap_regexec(ent->regex, r->unparsed_uri,
610 AP_MAX_REG_MATCH, reg1, 0)) {
614 found = ap_pregsub(r->pool, real, use_uri, AP_MAX_REG_MATCH,
615 (use_uri == r->uri) ? regm : reg1);
617 ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(01135)
618 "Substitution in regular expression failed. "
619 "Replacement too long?");
620 return HTTP_INTERNAL_SERVER_ERROR;
623 /* Note: The strcmp() below catches cases where there
624 * was no regex substitution. This is so cases like:
626 * ProxyPassMatch \.gif balancer://foo
628 * will work "as expected". The upshot is that the 2
629 * directives below act the exact same way (ie: $1 is implied):
631 * ProxyPassMatch ^(/.*\.gif)$ balancer://foo
632 * ProxyPassMatch ^(/.*\.gif)$ balancer://foo$1
634 * which may be confusing.
636 if (strcmp(found, real) != 0) {
637 found = apr_pstrcat(r->pool, "proxy:", found, NULL);
640 found = apr_pstrcat(r->pool, "proxy:", real, use_uri, NULL);
645 len = alias_match(r->uri, fake);
648 if ((real[0] == '!') && (real[1] == '\0')) {
651 if (nocanon && len != alias_match(r->unparsed_uri, ent->fake)) {
655 found = apr_pstrcat(r->pool, "proxy:", real, use_uri + len, NULL);
659 /* We made a reducing transformation, so we can't safely use
660 * unparsed_uri. Safe fallback is to ignore nocanon.
662 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01136)
663 "Unescaped URL path matched ProxyPass; ignoring unsafe nocanon");
668 r->handler = "proxy-server";
669 r->proxyreq = PROXYREQ_REVERSE;
670 if (nocanon && !mismatch) {
671 /* mod_proxy_http needs to be told. Different module. */
672 apr_table_setn(r->notes, "proxy-nocanon", "1");
674 if (ent->flags & PROXYPASS_NOQUERY) {
675 apr_table_setn(r->notes, "proxy-noquery", "1");
683 static int proxy_trans(request_rec *r)
686 struct proxy_alias *ent;
687 proxy_dir_conf *dconf;
688 proxy_server_conf *conf;
691 /* someone has already set up the proxy, it was possibly ourselves
697 if ((r->unparsed_uri[0] == '*' && r->unparsed_uri[1] == '\0')
698 || !r->uri || r->uri[0] != '/') {
702 /* XXX: since r->uri has been manipulated already we're not really
703 * compliant with RFC1945 at this point. But this probably isn't
704 * an issue because this is a hybrid proxy/origin server.
707 dconf = ap_get_module_config(r->per_dir_config, &proxy_module);
709 /* short way - this location is reverse proxied? */
711 int rv = ap_proxy_trans_match(r, dconf->alias, dconf);
717 conf = (proxy_server_conf *) ap_get_module_config(r->server->module_config,
720 /* long way - walk the list of aliases, find a match */
721 if (conf->aliases->nelts) {
722 ent = (struct proxy_alias *) conf->aliases->elts;
723 for (i = 0; i < conf->aliases->nelts; i++) {
724 int rv = ap_proxy_trans_match(r, &ent[i], dconf);
733 static int proxy_walk(request_rec *r)
735 proxy_server_conf *sconf = ap_get_module_config(r->server->module_config,
737 ap_conf_vector_t *per_dir_defaults = r->server->lookup_defaults;
738 ap_conf_vector_t **sec_proxy = (ap_conf_vector_t **) sconf->sec_proxy->elts;
739 ap_conf_vector_t *entry_config;
740 proxy_dir_conf *entry_proxy;
741 int num_sec = sconf->sec_proxy->nelts;
742 /* XXX: shouldn't we use URI here? Canonicalize it first?
743 * Pass over "proxy:" prefix
745 const char *proxyname = r->filename + 6;
748 for (j = 0; j < num_sec; ++j)
750 entry_config = sec_proxy[j];
751 entry_proxy = ap_get_module_config(entry_config, &proxy_module);
753 /* XXX: What about case insensitive matching ???
754 * Compare regex, fnmatch or string as appropriate
755 * If the entry doesn't relate, then continue
758 ? ap_regexec(entry_proxy->r, proxyname, 0, NULL, 0)
759 : (entry_proxy->p_is_fnmatch
760 ? apr_fnmatch(entry_proxy->p, proxyname, 0)
761 : strncmp(proxyname, entry_proxy->p,
762 strlen(entry_proxy->p)))) {
765 per_dir_defaults = ap_merge_per_dir_configs(r->pool, per_dir_defaults,
769 r->per_dir_config = per_dir_defaults;
774 static int proxy_map_location(request_rec *r)
778 if (!r->proxyreq || !r->filename || strncmp(r->filename, "proxy:", 6) != 0)
781 /* Don't let the core or mod_http map_to_storage hooks handle this,
782 * We don't need directory/file_walk, and we want to TRACE on our own.
784 if ((access_status = proxy_walk(r))) {
785 ap_die(access_status, r);
786 return access_status;
792 /* -------------------------------------------------------------- */
793 /* Fixup the filename */
796 * Canonicalise the URL
798 static int proxy_fixup(request_rec *r)
802 proxy_dir_conf *dconf = ap_get_module_config(r->per_dir_config,
805 if (!r->proxyreq || !r->filename || strncmp(r->filename, "proxy:", 6) != 0)
808 /* XXX: Shouldn't we try this before we run the proxy_walk? */
809 url = &r->filename[6];
811 if ((dconf->interpolate_env == 1) && (r->proxyreq == PROXYREQ_REVERSE)) {
812 /* create per-request copy of reverse proxy conf,
813 * and interpolate vars in it
815 proxy_req_conf *rconf = apr_palloc(r->pool, sizeof(proxy_req_conf));
816 ap_set_module_config(r->request_config, &proxy_module, rconf);
817 rconf->raliases = proxy_vars(r, dconf->raliases);
818 rconf->cookie_paths = proxy_vars(r, dconf->cookie_paths);
819 rconf->cookie_domains = proxy_vars(r, dconf->cookie_domains);
822 /* canonicalise each specific scheme */
823 if ((access_status = proxy_run_canon_handler(r, url))) {
824 return access_status;
827 p = strchr(url, ':');
828 if (p == NULL || p == url)
829 return HTTP_BAD_REQUEST;
831 return OK; /* otherwise; we've done the best we can */
833 /* Send a redirection if the request contains a hostname which is not */
834 /* fully qualified, i.e. doesn't have a domain name appended. Some proxy */
835 /* servers like Netscape's allow this and access hosts from the local */
836 /* domain in this case. I think it is better to redirect to a FQDN, since */
837 /* these will later be found in the bookmarks files. */
838 /* The "ProxyDomain" directive determines what domain will be appended */
839 static int proxy_needsdomain(request_rec *r, const char *url, const char *domain)
844 /* We only want to worry about GETs */
845 if (!r->proxyreq || r->method_number != M_GET || !r->parsed_uri.hostname)
848 /* If host does contain a dot already, or it is "localhost", decline */
849 if (strchr(r->parsed_uri.hostname, '.') != NULL /* has domain, or IPv4 literal */
850 || strchr(r->parsed_uri.hostname, ':') != NULL /* IPv6 literal */
851 || strcasecmp(r->parsed_uri.hostname, "localhost") == 0)
852 return DECLINED; /* host name has a dot already */
854 ref = apr_table_get(r->headers_in, "Referer");
856 /* Reassemble the request, but insert the domain after the host name */
857 /* Note that the domain name always starts with a dot */
858 r->parsed_uri.hostname = apr_pstrcat(r->pool, r->parsed_uri.hostname,
860 nuri = apr_uri_unparse(r->pool,
862 APR_URI_UNP_REVEALPASSWORD);
864 apr_table_setn(r->headers_out, "Location", nuri);
865 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(01138)
866 "Domain missing: %s sent to %s%s%s", r->uri,
867 apr_uri_unparse(r->pool, &r->parsed_uri,
868 APR_URI_UNP_OMITUSERINFO),
869 ref ? " from " : "", ref ? ref : "");
871 return HTTP_MOVED_PERMANENTLY;
874 /* -------------------------------------------------------------- */
877 static int proxy_handler(request_rec *r)
879 char *uri, *scheme, *p;
881 void *sconf = r->server->module_config;
882 proxy_server_conf *conf = (proxy_server_conf *)
883 ap_get_module_config(sconf, &proxy_module);
884 apr_array_header_t *proxies = conf->proxies;
885 struct proxy_remote *ents = (struct proxy_remote *) proxies->elts;
886 int i, rc, access_status;
887 int direct_connect = 0;
890 proxy_balancer *balancer = NULL;
891 proxy_worker *worker = NULL;
892 int attempts = 0, max_attempts = 0;
893 struct dirconn_entry *list = (struct dirconn_entry *)conf->dirconn->elts;
895 /* is this for us? */
896 if (!r->proxyreq || !r->filename || strncmp(r->filename, "proxy:", 6) != 0)
899 /* handle max-forwards / OPTIONS / TRACE */
900 if ((str = apr_table_get(r->headers_in, "Max-Forwards"))) {
902 maxfwd = apr_strtoi64(str, &end, 10);
903 if (maxfwd < 0 || maxfwd == APR_INT64_MAX || *end) {
904 return ap_proxyerror(r, HTTP_BAD_REQUEST,
905 apr_psprintf(r->pool,
906 "Max-Forwards value '%s' could not be parsed", str));
908 else if (maxfwd == 0) {
909 switch (r->method_number) {
912 r->proxyreq = PROXYREQ_NONE;
913 if ((access_status = ap_send_http_trace(r)))
914 ap_die(access_status, r);
916 ap_finalize_request_protocol(r);
921 r->proxyreq = PROXYREQ_NONE;
922 if ((access_status = ap_send_http_options(r)))
923 ap_die(access_status, r);
925 ap_finalize_request_protocol(r);
929 return ap_proxyerror(r, HTTP_BAD_REQUEST,
930 "Max-Forwards has reached zero - proxy loop?");
934 maxfwd = (maxfwd > 0) ? maxfwd - 1 : 0;
937 /* set configured max-forwards */
938 maxfwd = conf->maxfwd;
941 apr_table_setn(r->headers_in, "Max-Forwards",
942 apr_psprintf(r->pool, "%" APR_INT64_T_FMT, maxfwd));
945 if (r->method_number == M_TRACE) {
946 core_server_config *coreconf = (core_server_config *)
947 ap_get_core_module_config(sconf);
949 if (coreconf->trace_enable == AP_TRACE_DISABLE)
951 /* Allow "error-notes" string to be printed by ap_send_error_response()
952 * Note; this goes nowhere, canned error response need an overhaul.
954 apr_table_setn(r->notes, "error-notes",
955 "TRACE forbidden by server configuration");
956 apr_table_setn(r->notes, "verbose-error-to", "*");
957 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01139)
958 "TRACE forbidden by server configuration");
959 return HTTP_METHOD_NOT_ALLOWED;
962 /* Can't test ap_should_client_block, we aren't ready to send
963 * the client a 100 Continue response till the connection has
966 if (coreconf->trace_enable != AP_TRACE_EXTENDED
967 && (r->read_length || r->read_chunked || r->remaining))
969 /* Allow "error-notes" string to be printed by ap_send_error_response()
970 * Note; this goes nowhere, canned error response need an overhaul.
972 apr_table_setn(r->notes, "error-notes",
973 "TRACE with request body is not allowed");
974 apr_table_setn(r->notes, "verbose-error-to", "*");
975 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01140)
976 "TRACE with request body is not allowed");
977 return HTTP_REQUEST_ENTITY_TOO_LARGE;
981 uri = r->filename + 6;
982 p = strchr(uri, ':');
984 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01141)
985 "proxy_handler no URL in %s", r->filename);
986 return HTTP_BAD_REQUEST;
989 /* If the host doesn't have a domain name, add one and redirect. */
990 if (conf->domain != NULL) {
991 rc = proxy_needsdomain(r, uri, conf->domain);
992 if (ap_is_HTTP_REDIRECT(rc))
993 return HTTP_MOVED_PERMANENTLY;
996 scheme = apr_pstrndup(r->pool, uri, p - uri);
997 /* Check URI's destination host against NoProxy hosts */
998 /* Bypass ProxyRemote server lookup if configured as NoProxy */
999 for (direct_connect = i = 0; i < conf->dirconn->nelts &&
1000 !direct_connect; i++) {
1001 direct_connect = list[i].matcher(&list[i], r);
1004 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1005 (direct_connect) ? "NoProxy for %s" : "UseProxy for %s",
1011 /* Try to obtain the most suitable worker */
1012 access_status = ap_proxy_pre_request(&worker, &balancer, r, conf, &url);
1013 if (access_status != OK) {
1015 * Only return if access_status is not HTTP_SERVICE_UNAVAILABLE
1016 * This gives other modules the chance to hook into the
1017 * request_status hook and decide what to do in this situation.
1019 if (access_status != HTTP_SERVICE_UNAVAILABLE)
1020 return access_status;
1022 * Ensure that balancer is NULL if worker is NULL to prevent
1023 * potential problems in the post_request hook.
1030 /* Initialise worker if needed, note the shared area must be initialized by the balancer logic */
1032 ap_proxy_initialize_worker(worker, r->server, conf->pool);
1035 if (balancer && balancer->s->max_attempts_set && !max_attempts)
1036 max_attempts = balancer->s->max_attempts;
1037 /* firstly, try a proxy, unless a NoProxy directive is active */
1038 if (!direct_connect) {
1039 for (i = 0; i < proxies->nelts; i++) {
1040 p2 = ap_strchr_c(ents[i].scheme, ':'); /* is it a partial URL? */
1041 if (strcmp(ents[i].scheme, "*") == 0 ||
1042 (ents[i].use_regex &&
1043 ap_regexec(ents[i].regexp, url, 0, NULL, 0) == 0) ||
1044 (p2 == NULL && strcasecmp(scheme, ents[i].scheme) == 0) ||
1046 strncasecmp(url, ents[i].scheme,
1047 strlen(ents[i].scheme)) == 0)) {
1049 /* handle the scheme */
1050 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01142)
1051 "Trying to run scheme_handler against proxy");
1052 access_status = proxy_run_scheme_handler(r, worker,
1057 /* Did the scheme handler process the request? */
1058 if (access_status != DECLINED) {
1064 * An fatal error or success, so no point in
1065 * retrying with a direct connection.
1067 if (access_status != HTTP_BAD_GATEWAY) {
1070 cl_a = apr_table_get(r->headers_in, "Content-Length");
1072 apr_strtoff(&cl, cl_a, &end, 10);
1074 * The request body is of length > 0. We cannot
1075 * retry with a direct connection since we already
1076 * sent (parts of) the request body to the proxy
1077 * and do not have any longer.
1084 * Transfer-Encoding was set as input header, so we had
1085 * a request body. We cannot retry with a direct
1086 * connection for the same reason as above.
1088 if (apr_table_get(r->headers_in, "Transfer-Encoding")) {
1096 /* otherwise, try it direct */
1097 /* N.B. what if we're behind a firewall, where we must use a proxy or
1101 /* handle the scheme */
1102 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01143)
1103 "Running scheme %s handler (attempt %d)",
1105 AP_PROXY_RUN(r, worker, conf, url, attempts);
1106 access_status = proxy_run_scheme_handler(r, worker, conf,
1108 if (access_status == OK)
1110 else if (access_status == HTTP_INTERNAL_SERVER_ERROR) {
1111 /* Unrecoverable server error.
1112 * We can not failover to another worker.
1113 * Mark the worker as unusable if member of load balancer
1116 worker->s->status |= PROXY_WORKER_IN_ERROR;
1117 worker->s->error_time = apr_time_now();
1121 else if (access_status == HTTP_SERVICE_UNAVAILABLE) {
1122 /* Recoverable server error.
1123 * We can failover to another worker
1124 * Mark the worker as unusable if member of load balancer
1127 worker->s->status |= PROXY_WORKER_IN_ERROR;
1128 worker->s->error_time = apr_time_now();
1132 /* Unrecoverable error.
1133 * Return the origin status code to the client.
1137 /* Try again if the worker is unusable and the service is
1140 } while (!PROXY_WORKER_IS_USABLE(worker) &&
1141 max_attempts > attempts++);
1143 if (DECLINED == access_status) {
1144 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01144)
1145 "No protocol handler was valid for the URL %s. "
1146 "If you are using a DSO version of mod_proxy, make sure "
1147 "the proxy submodules are included in the configuration "
1148 "using LoadModule.", r->uri);
1149 access_status = HTTP_INTERNAL_SERVER_ERROR;
1153 ap_proxy_post_request(worker, balancer, r, conf);
1155 proxy_run_request_status(&access_status, r);
1156 AP_PROXY_RUN_FINISHED(r, attempts, access_status);
1158 return access_status;
1161 /* -------------------------------------------------------------- */
1162 /* Setup configurable data */
1164 static void * create_proxy_config(apr_pool_t *p, server_rec *s)
1166 proxy_server_conf *ps = apr_pcalloc(p, sizeof(proxy_server_conf));
1168 ps->sec_proxy = apr_array_make(p, 10, sizeof(ap_conf_vector_t *));
1169 ps->proxies = apr_array_make(p, 10, sizeof(struct proxy_remote));
1170 ps->aliases = apr_array_make(p, 10, sizeof(struct proxy_alias));
1171 ps->noproxies = apr_array_make(p, 10, sizeof(struct noproxy_entry));
1172 ps->dirconn = apr_array_make(p, 10, sizeof(struct dirconn_entry));
1173 ps->workers = apr_array_make(p, 10, sizeof(proxy_worker));
1174 ps->balancers = apr_array_make(p, 10, sizeof(proxy_balancer));
1178 ps->id = apr_psprintf(p, "p%x", 1); /* simply for storage size */
1179 ps->viaopt = via_off; /* initially backward compatible with 1.3.1 */
1180 ps->viaopt_set = 0; /* 0 means default */
1182 ps->max_balancers = 0;
1183 ps->bal_persist = 0;
1185 ps->inherit_set = 0;
1187 ps->ppinherit_set = 0;
1189 ps->bgrowth_set = 0;
1191 ps->recv_buffer_size = 0; /* this default was left unset for some reason */
1192 ps->recv_buffer_size_set = 0;
1193 ps->io_buffer_size = AP_IOBUFSIZE;
1194 ps->io_buffer_size_set = 0;
1195 ps->maxfwd = DEFAULT_MAX_FORWARDS;
1198 ps->timeout_set = 0;
1199 ps->badopt = bad_error;
1201 ps->source_address = NULL;
1202 ps->source_address_set = 0;
1203 apr_pool_create_ex(&ps->pool, p, NULL, NULL);
1208 static void * merge_proxy_config(apr_pool_t *p, void *basev, void *overridesv)
1210 proxy_server_conf *ps = apr_pcalloc(p, sizeof(proxy_server_conf));
1211 proxy_server_conf *base = (proxy_server_conf *) basev;
1212 proxy_server_conf *overrides = (proxy_server_conf *) overridesv;
1214 ps->inherit = (overrides->inherit_set == 0) ? base->inherit : overrides->inherit;
1215 ps->inherit_set = overrides->inherit_set || base->inherit_set;
1217 ps->ppinherit = (overrides->ppinherit_set == 0) ? base->ppinherit : overrides->ppinherit;
1218 ps->ppinherit_set = overrides->ppinherit_set || base->ppinherit_set;
1220 if (ps->ppinherit) {
1221 ps->proxies = apr_array_append(p, base->proxies, overrides->proxies);
1224 ps->proxies = overrides->proxies;
1226 ps->sec_proxy = apr_array_append(p, base->sec_proxy, overrides->sec_proxy);
1227 ps->aliases = apr_array_append(p, base->aliases, overrides->aliases);
1228 ps->noproxies = apr_array_append(p, base->noproxies, overrides->noproxies);
1229 ps->dirconn = apr_array_append(p, base->dirconn, overrides->dirconn);
1230 if (ps->inherit || ps->ppinherit) {
1231 ps->workers = apr_array_append(p, base->workers, overrides->workers);
1232 ps->balancers = apr_array_append(p, base->balancers, overrides->balancers);
1235 ps->workers = overrides->workers;
1236 ps->balancers = overrides->balancers;
1238 ps->forward = overrides->forward ? overrides->forward : base->forward;
1239 ps->reverse = overrides->reverse ? overrides->reverse : base->reverse;
1241 ps->domain = (overrides->domain == NULL) ? base->domain : overrides->domain;
1242 ps->id = (overrides->id == NULL) ? base->id : overrides->id;
1243 ps->viaopt = (overrides->viaopt_set == 0) ? base->viaopt : overrides->viaopt;
1244 ps->viaopt_set = overrides->viaopt_set || base->viaopt_set;
1245 ps->req = (overrides->req_set == 0) ? base->req : overrides->req;
1246 ps->req_set = overrides->req_set || base->req_set;
1247 ps->bgrowth = (overrides->bgrowth_set == 0) ? base->bgrowth : overrides->bgrowth;
1248 ps->bgrowth_set = overrides->bgrowth_set || base->bgrowth_set;
1249 ps->max_balancers = overrides->max_balancers || base->max_balancers;
1250 ps->bal_persist = overrides->bal_persist;
1251 ps->recv_buffer_size = (overrides->recv_buffer_size_set == 0) ? base->recv_buffer_size : overrides->recv_buffer_size;
1252 ps->recv_buffer_size_set = overrides->recv_buffer_size_set || base->recv_buffer_size_set;
1253 ps->io_buffer_size = (overrides->io_buffer_size_set == 0) ? base->io_buffer_size : overrides->io_buffer_size;
1254 ps->io_buffer_size_set = overrides->io_buffer_size_set || base->io_buffer_size_set;
1255 ps->maxfwd = (overrides->maxfwd_set == 0) ? base->maxfwd : overrides->maxfwd;
1256 ps->maxfwd_set = overrides->maxfwd_set || base->maxfwd_set;
1257 ps->timeout = (overrides->timeout_set == 0) ? base->timeout : overrides->timeout;
1258 ps->timeout_set = overrides->timeout_set || base->timeout_set;
1259 ps->badopt = (overrides->badopt_set == 0) ? base->badopt : overrides->badopt;
1260 ps->badopt_set = overrides->badopt_set || base->badopt_set;
1261 ps->proxy_status = (overrides->proxy_status_set == 0) ? base->proxy_status : overrides->proxy_status;
1262 ps->proxy_status_set = overrides->proxy_status_set || base->proxy_status_set;
1263 ps->source_address = (overrides->source_address_set == 0) ? base->source_address : overrides->source_address;
1264 ps->source_address_set = overrides->source_address_set || base->source_address_set;
1265 ps->pool = base->pool;
1268 static const char *set_source_address(cmd_parms *parms, void *dummy,
1271 proxy_server_conf *psf =
1272 ap_get_module_config(parms->server->module_config, &proxy_module);
1273 struct apr_sockaddr_t *addr;
1275 if (APR_SUCCESS == apr_sockaddr_info_get(&addr, arg, APR_UNSPEC, 0, 0,
1277 psf->source_address = addr;
1278 psf->source_address_set = 1;
1281 return "ProxySourceAddress invalid value";
1287 static void *create_proxy_dir_config(apr_pool_t *p, char *dummy)
1289 proxy_dir_conf *new =
1290 (proxy_dir_conf *) apr_pcalloc(p, sizeof(proxy_dir_conf));
1292 /* Filled in by proxysection, when applicable */
1294 /* Put these in the dir config so they work inside <Location> */
1295 new->raliases = apr_array_make(p, 10, sizeof(struct proxy_alias));
1296 new->cookie_paths = apr_array_make(p, 10, sizeof(struct proxy_alias));
1297 new->cookie_domains = apr_array_make(p, 10, sizeof(struct proxy_alias));
1298 new->preserve_host_set = 0;
1299 new->preserve_host = 0;
1300 new->interpolate_env = -1; /* unset */
1301 new->error_override = 0;
1302 new->error_override_set = 0;
1303 new->add_forwarded_headers = 1;
1305 return (void *) new;
1308 static void *merge_proxy_dir_config(apr_pool_t *p, void *basev, void *addv)
1310 proxy_dir_conf *new = (proxy_dir_conf *) apr_pcalloc(p, sizeof(proxy_dir_conf));
1311 proxy_dir_conf *add = (proxy_dir_conf *) addv;
1312 proxy_dir_conf *base = (proxy_dir_conf *) basev;
1315 new->p_is_fnmatch = add->p_is_fnmatch;
1318 /* Put these in the dir config so they work inside <Location> */
1319 new->raliases = apr_array_append(p, base->raliases, add->raliases);
1321 = apr_array_append(p, base->cookie_paths, add->cookie_paths);
1323 = apr_array_append(p, base->cookie_domains, add->cookie_domains);
1324 new->interpolate_env = (add->interpolate_env == -1) ? base->interpolate_env
1325 : add->interpolate_env;
1326 new->preserve_host = (add->preserve_host_set == 0) ? base->preserve_host
1327 : add->preserve_host;
1328 new->preserve_host_set = add->preserve_host_set || base->preserve_host_set;
1329 new->error_override = (add->error_override_set == 0) ? base->error_override
1330 : add->error_override;
1331 new->error_override_set = add->error_override_set || base->error_override_set;
1332 new->alias = (add->alias_set == 0) ? base->alias : add->alias;
1333 new->alias_set = add->alias_set || base->alias_set;
1334 new->add_forwarded_headers = add->add_forwarded_headers;
1339 add_proxy(cmd_parms *cmd, void *dummy, const char *f1, const char *r1, int regex)
1341 server_rec *s = cmd->server;
1342 proxy_server_conf *conf =
1343 (proxy_server_conf *) ap_get_module_config(s->module_config, &proxy_module);
1344 struct proxy_remote *new;
1346 char *r, *f, *scheme;
1347 ap_regex_t *reg = NULL;
1350 r = apr_pstrdup(cmd->pool, r1);
1351 scheme = apr_pstrdup(cmd->pool, r1);
1352 f = apr_pstrdup(cmd->pool, f1);
1354 if (p == NULL || p[1] != '/' || p[2] != '/' || p[3] == '\0') {
1356 return "ProxyRemoteMatch: Bad syntax for a remote proxy server";
1358 return "ProxyRemote: Bad syntax for a remote proxy server";
1363 q = strchr(p + 3, ':');
1365 if (sscanf(q + 1, "%u", &port) != 1 || port > 65535) {
1367 return "ProxyRemoteMatch: Bad syntax for a remote proxy server (bad port number)";
1369 return "ProxyRemote: Bad syntax for a remote proxy server (bad port number)";
1377 reg = ap_pregcomp(cmd->pool, f, AP_REG_EXTENDED);
1379 return "Regular expression for ProxyRemoteMatch could not be compiled.";
1382 if (strchr(f, ':') == NULL)
1383 ap_str_tolower(f); /* lowercase scheme */
1384 ap_str_tolower(p + 3); /* lowercase hostname */
1387 port = apr_uri_port_of_scheme(scheme);
1390 new = apr_array_push(conf->proxies);
1393 new->hostname = p + 3;
1396 new->use_regex = regex;
1401 add_proxy_noregex(cmd_parms *cmd, void *dummy, const char *f1, const char *r1)
1403 return add_proxy(cmd, dummy, f1, r1, 0);
1407 add_proxy_regex(cmd_parms *cmd, void *dummy, const char *f1, const char *r1)
1409 return add_proxy(cmd, dummy, f1, r1, 1);
1412 static char *de_socketfy(apr_pool_t *p, char *url)
1416 * We could be passed a URL during the config stage that contains
1417 * the UDS path... ignore it
1419 if (!strncasecmp(url, "unix:", 5) &&
1420 ((ptr = ap_strchr(url, '|')) != NULL)) {
1421 /* move past the 'unix:...|' UDS path info */
1425 /* special case: "unix:....|scheme:" is OK, expand
1426 * to "unix:....|scheme://localhost"
1428 c = ap_strchr(ret, ':');
1433 return apr_pstrcat(p, ret, "//localhost", NULL);
1443 add_pass(cmd_parms *cmd, void *dummy, const char *arg, int is_regex)
1445 proxy_dir_conf *dconf = (proxy_dir_conf *)dummy;
1446 server_rec *s = cmd->server;
1447 proxy_server_conf *conf =
1448 (proxy_server_conf *) ap_get_module_config(s->module_config, &proxy_module);
1449 struct proxy_alias *new;
1450 char *f = cmd->path;
1453 apr_table_t *params = apr_table_make(cmd->pool, 5);
1454 const apr_array_header_t *arr;
1455 const apr_table_entry_t *elts;
1457 int use_regex = is_regex;
1458 unsigned int flags = 0;
1461 err = ap_check_cmd_context(cmd, NOT_IN_DIRECTORY|NOT_IN_FILES);
1467 word = ap_getword_conf(cmd->pool, &arg);
1469 if (!strcmp(word, "~")) {
1471 return "ProxyPassMatch invalid syntax ('~' usage).";
1481 else if (!strcasecmp(word,"nocanon")) {
1482 flags |= PROXYPASS_NOCANON;
1484 else if (!strcasecmp(word,"interpolate")) {
1485 flags |= PROXYPASS_INTERPOLATE;
1487 else if (!strcasecmp(word,"noquery")) {
1488 flags |= PROXYPASS_NOQUERY;
1491 char *val = strchr(word, '=');
1495 return "ProxyPass|ProxyPassMatch can not have a path when defined in "
1499 return "Invalid ProxyPass|ProxyPassMatch parameter. Parameter must "
1500 "be in the form 'key=value'.";
1504 return "Invalid ProxyPass|ProxyPassMatch parameter. Parameter must be "
1505 "in the form 'key=value'.";
1510 apr_table_setn(params, word, val);
1515 return "ProxyPass|ProxyPassMatch needs a path when not defined in a location";
1518 /* if per directory, save away the single alias */
1520 dconf->alias = apr_pcalloc(cmd->pool, sizeof(struct proxy_alias));
1521 dconf->alias_set = 1;
1523 if (apr_fnmatch_test(f)) {
1527 /* if per server, add to the alias array */
1529 new = apr_array_push(conf->aliases);
1532 new->fake = apr_pstrdup(cmd->pool, f);
1533 new->real = apr_pstrdup(cmd->pool, de_socketfy(cmd->pool, r));
1536 new->regex = ap_pregcomp(cmd->pool, f, AP_REG_EXTENDED);
1537 if (new->regex == NULL)
1538 return "Regular expression could not be compiled.";
1544 if (r[0] == '!' && r[1] == '\0')
1547 arr = apr_table_elts(params);
1548 elts = (const apr_table_entry_t *)arr->elts;
1549 /* Distinguish the balancer from worker */
1550 if (ap_proxy_valid_balancer_name(r, 9)) {
1551 proxy_balancer *balancer = ap_proxy_get_balancer(cmd->pool, conf, r, 0);
1553 const char *err = ap_proxy_define_balancer(cmd->pool, &balancer, conf, r, f, 0);
1555 return apr_pstrcat(cmd->temp_pool, "ProxyPass ", err, NULL);
1558 ap_proxy_update_balancer(cmd->pool, balancer, f);
1560 for (i = 0; i < arr->nelts; i++) {
1561 const char *err = set_balancer_param(conf, cmd->pool, balancer, elts[i].key,
1564 return apr_pstrcat(cmd->temp_pool, "ProxyPass ", err, NULL);
1566 new->balancer = balancer;
1569 proxy_worker *worker = ap_proxy_get_worker(cmd->temp_pool, NULL, conf, de_socketfy(cmd->pool, r));
1572 const char *err = ap_proxy_define_worker(cmd->pool, &worker, NULL, conf, r, 0);
1574 return apr_pstrcat(cmd->temp_pool, "ProxyPass ", err, NULL);
1576 PROXY_COPY_CONF_PARAMS(worker, conf);
1579 ap_log_error(APLOG_MARK, APLOG_INFO, 0, cmd->server, APLOGNO(01145)
1580 "Sharing worker '%s' instead of creating new worker '%s'",
1581 ap_proxy_worker_name(cmd->pool, worker), new->real);
1584 for (i = 0; i < arr->nelts; i++) {
1586 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server, APLOGNO(01146)
1587 "Ignoring parameter '%s=%s' for worker '%s' because of worker sharing",
1588 elts[i].key, elts[i].val, ap_proxy_worker_name(cmd->pool, worker));
1590 const char *err = set_worker_param(cmd->pool, worker, elts[i].key,
1593 return apr_pstrcat(cmd->temp_pool, "ProxyPass ", err, NULL);
1601 add_pass_noregex(cmd_parms *cmd, void *dummy, const char *arg)
1603 return add_pass(cmd, dummy, arg, 0);
1607 add_pass_regex(cmd_parms *cmd, void *dummy, const char *arg)
1609 return add_pass(cmd, dummy, arg, 1);
1613 static const char * add_pass_reverse(cmd_parms *cmd, void *dconf, const char *f,
1614 const char *r, const char *i)
1616 proxy_dir_conf *conf = dconf;
1617 struct proxy_alias *new;
1623 err = ap_check_cmd_context(cmd, NOT_IN_DIRECTORY|NOT_IN_FILES);
1628 if (cmd->path == NULL) {
1629 if (r == NULL || !strcasecmp(r, "interpolate")) {
1630 return "ProxyPassReverse needs a path when not defined in a location";
1637 if (r && strcasecmp(r, "interpolate")) {
1638 return "ProxyPassReverse can not have a path when defined in a location";
1645 new = apr_array_push(conf->raliases);
1648 new->flags = interp ? PROXYPASS_INTERPOLATE : 0;
1652 static const char* cookie_path(cmd_parms *cmd, void *dconf, const char *f,
1653 const char *r, const char *interp)
1655 proxy_dir_conf *conf = dconf;
1656 struct proxy_alias *new;
1658 new = apr_array_push(conf->cookie_paths);
1661 new->flags = interp ? PROXYPASS_INTERPOLATE : 0;
1665 static const char* cookie_domain(cmd_parms *cmd, void *dconf, const char *f,
1666 const char *r, const char *interp)
1668 proxy_dir_conf *conf = dconf;
1669 struct proxy_alias *new;
1671 new = apr_array_push(conf->cookie_domains);
1674 new->flags = interp ? PROXYPASS_INTERPOLATE : 0;
1679 set_proxy_exclude(cmd_parms *parms, void *dummy, const char *arg)
1681 server_rec *s = parms->server;
1682 proxy_server_conf *conf =
1683 ap_get_module_config(s->module_config, &proxy_module);
1684 struct noproxy_entry *new;
1685 struct noproxy_entry *list = (struct noproxy_entry *) conf->noproxies->elts;
1686 struct apr_sockaddr_t *addr;
1690 /* Don't duplicate entries */
1691 for (i = 0; i < conf->noproxies->nelts; i++) {
1692 if (strcasecmp(arg, list[i].name) == 0) { /* ignore case for host names */
1698 new = apr_array_push(conf->noproxies);
1700 if (APR_SUCCESS == apr_sockaddr_info_get(&addr, new->name, APR_UNSPEC, 0, 0, parms->pool)) {
1711 /* Similar to set_proxy_exclude(), but defining directly connected hosts,
1712 * which should never be accessed via the configured ProxyRemote servers
1715 set_proxy_dirconn(cmd_parms *parms, void *dummy, const char *arg)
1717 server_rec *s = parms->server;
1718 proxy_server_conf *conf =
1719 ap_get_module_config(s->module_config, &proxy_module);
1720 struct dirconn_entry *New;
1721 struct dirconn_entry *list = (struct dirconn_entry *) conf->dirconn->elts;
1725 /* Don't duplicate entries */
1726 for (i = 0; i < conf->dirconn->nelts; i++) {
1727 if (strcasecmp(arg, list[i].name) == 0)
1732 New = apr_array_push(conf->dirconn);
1733 New->name = apr_pstrdup(parms->pool, arg);
1734 New->hostaddr = NULL;
1736 if (ap_proxy_is_ipaddr(New, parms->pool)) {
1738 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1739 "Parsed addr %s", inet_ntoa(New->addr));
1740 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1741 "Parsed mask %s", inet_ntoa(New->mask));
1744 else if (ap_proxy_is_domainname(New, parms->pool)) {
1745 ap_str_tolower(New->name);
1747 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1748 "Parsed domain %s", New->name);
1751 else if (ap_proxy_is_hostname(New, parms->pool)) {
1752 ap_str_tolower(New->name);
1754 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1755 "Parsed host %s", New->name);
1759 ap_proxy_is_word(New, parms->pool);
1761 fprintf(stderr, "Parsed word %s\n", New->name);
1769 set_proxy_domain(cmd_parms *parms, void *dummy, const char *arg)
1771 proxy_server_conf *psf =
1772 ap_get_module_config(parms->server->module_config, &proxy_module);
1775 return "ProxyDomain: domain name must start with a dot.";
1782 set_proxy_req(cmd_parms *parms, void *dummy, int flag)
1784 proxy_server_conf *psf =
1785 ap_get_module_config(parms->server->module_config, &proxy_module);
1793 set_proxy_error_override(cmd_parms *parms, void *dconf, int flag)
1795 proxy_dir_conf *conf = dconf;
1797 conf->error_override = flag;
1798 conf->error_override_set = 1;
1802 add_proxy_http_headers(cmd_parms *parms, void *dconf, int flag)
1804 proxy_dir_conf *conf = dconf;
1805 conf->add_forwarded_headers = flag;
1809 set_preserve_host(cmd_parms *parms, void *dconf, int flag)
1811 proxy_dir_conf *conf = dconf;
1813 conf->preserve_host = flag;
1814 conf->preserve_host_set = 1;
1819 set_recv_buffer_size(cmd_parms *parms, void *dummy, const char *arg)
1821 proxy_server_conf *psf =
1822 ap_get_module_config(parms->server->module_config, &proxy_module);
1824 if (s < 512 && s != 0) {
1825 return "ProxyReceiveBufferSize must be >= 512 bytes, or 0 for system default.";
1828 psf->recv_buffer_size = s;
1829 psf->recv_buffer_size_set = 1;
1834 set_io_buffer_size(cmd_parms *parms, void *dummy, const char *arg)
1836 proxy_server_conf *psf =
1837 ap_get_module_config(parms->server->module_config, &proxy_module);
1840 return "ProxyIOBufferSize must be >= 512 bytes, or 0 for system default.";
1842 psf->io_buffer_size = (s ? s : AP_IOBUFSIZE);
1843 psf->io_buffer_size_set = 1;
1848 set_max_forwards(cmd_parms *parms, void *dummy, const char *arg)
1850 proxy_server_conf *psf =
1851 ap_get_module_config(parms->server->module_config, &proxy_module);
1855 psf->maxfwd_set = 1;
1859 set_proxy_timeout(cmd_parms *parms, void *dummy, const char *arg)
1861 proxy_server_conf *psf =
1862 ap_get_module_config(parms->server->module_config, &proxy_module);
1865 timeout = atoi(arg);
1867 return "Proxy Timeout must be at least 1 second.";
1869 psf->timeout_set = 1;
1870 psf->timeout = apr_time_from_sec(timeout);
1876 set_via_opt(cmd_parms *parms, void *dummy, const char *arg)
1878 proxy_server_conf *psf =
1879 ap_get_module_config(parms->server->module_config, &proxy_module);
1881 if (strcasecmp(arg, "Off") == 0)
1882 psf->viaopt = via_off;
1883 else if (strcasecmp(arg, "On") == 0)
1884 psf->viaopt = via_on;
1885 else if (strcasecmp(arg, "Block") == 0)
1886 psf->viaopt = via_block;
1887 else if (strcasecmp(arg, "Full") == 0)
1888 psf->viaopt = via_full;
1890 return "ProxyVia must be one of: "
1891 "off | on | full | block";
1894 psf->viaopt_set = 1;
1899 set_bad_opt(cmd_parms *parms, void *dummy, const char *arg)
1901 proxy_server_conf *psf =
1902 ap_get_module_config(parms->server->module_config, &proxy_module);
1904 if (strcasecmp(arg, "IsError") == 0)
1905 psf->badopt = bad_error;
1906 else if (strcasecmp(arg, "Ignore") == 0)
1907 psf->badopt = bad_ignore;
1908 else if (strcasecmp(arg, "StartBody") == 0)
1909 psf->badopt = bad_body;
1911 return "ProxyBadHeader must be one of: "
1912 "IsError | Ignore | StartBody";
1915 psf->badopt_set = 1;
1920 set_status_opt(cmd_parms *parms, void *dummy, const char *arg)
1922 proxy_server_conf *psf =
1923 ap_get_module_config(parms->server->module_config, &proxy_module);
1925 if (strcasecmp(arg, "Off") == 0)
1926 psf->proxy_status = status_off;
1927 else if (strcasecmp(arg, "On") == 0)
1928 psf->proxy_status = status_on;
1929 else if (strcasecmp(arg, "Full") == 0)
1930 psf->proxy_status = status_full;
1932 return "ProxyStatus must be one of: "
1936 psf->proxy_status_set = 1;
1940 static const char *set_bgrowth(cmd_parms *parms, void *dummy, const char *arg)
1942 proxy_server_conf *psf =
1943 ap_get_module_config(parms->server->module_config, &proxy_module);
1945 int growth = atoi(arg);
1946 if (growth < 0 || growth > 1000) {
1947 return "BalancerGrowth must be between 0 and 1000";
1949 psf->bgrowth = growth;
1950 psf->bgrowth_set = 1;
1955 static const char *set_persist(cmd_parms *parms, void *dummy, int flag)
1957 proxy_server_conf *psf =
1958 ap_get_module_config(parms->server->module_config, &proxy_module);
1960 psf->bal_persist = flag;
1964 static const char *set_inherit(cmd_parms *parms, void *dummy, int flag)
1966 proxy_server_conf *psf =
1967 ap_get_module_config(parms->server->module_config, &proxy_module);
1969 psf->inherit = flag;
1970 psf->inherit_set = 1;
1974 static const char *set_ppinherit(cmd_parms *parms, void *dummy, int flag)
1976 proxy_server_conf *psf =
1977 ap_get_module_config(parms->server->module_config, &proxy_module);
1979 psf->ppinherit = flag;
1980 psf->ppinherit_set = 1;
1984 static const char *add_member(cmd_parms *cmd, void *dummy, const char *arg)
1986 server_rec *s = cmd->server;
1987 proxy_server_conf *conf =
1988 ap_get_module_config(s->module_config, &proxy_module);
1989 proxy_balancer *balancer;
1990 proxy_worker *worker;
1991 char *path = cmd->path;
1994 apr_table_t *params = apr_table_make(cmd->pool, 5);
1995 const apr_array_header_t *arr;
1996 const apr_table_entry_t *elts;
1999 /* XXX: Should this be NOT_IN_DIRECTORY|NOT_IN_FILES? */
2000 const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS);
2005 path = apr_pstrdup(cmd->pool, cmd->path);
2009 word = ap_getword_conf(cmd->pool, &arg);
2010 val = strchr(word, '=');
2019 return "BalancerMember can not have a balancer name when defined in a location";
2021 return "Invalid BalancerMember parameter. Parameter must "
2022 "be in the form 'key=value'";
2026 apr_table_setn(params, word, val);
2030 return "BalancerMember must define balancer name when outside <Proxy > section";
2032 return "BalancerMember must define remote proxy server";
2034 ap_str_tolower(path); /* lowercase scheme://hostname */
2036 /* Try to find the balancer */
2037 balancer = ap_proxy_get_balancer(cmd->temp_pool, conf, path, 0);
2039 err = ap_proxy_define_balancer(cmd->pool, &balancer, conf, path, "/", 0);
2041 return apr_pstrcat(cmd->temp_pool, "BalancerMember ", err, NULL);
2044 /* Try to find existing worker */
2045 worker = ap_proxy_get_worker(cmd->temp_pool, balancer, conf, de_socketfy(cmd->temp_pool, name));
2047 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server, APLOGNO(01147)
2048 "Defining worker '%s' for balancer '%s'",
2049 name, balancer->s->name);
2050 if ((err = ap_proxy_define_worker(cmd->pool, &worker, balancer, conf, name, 0)) != NULL)
2051 return apr_pstrcat(cmd->temp_pool, "BalancerMember ", err, NULL);
2052 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server, APLOGNO(01148)
2053 "Defined worker '%s' for balancer '%s'",
2054 ap_proxy_worker_name(cmd->pool, worker), balancer->s->name);
2055 PROXY_COPY_CONF_PARAMS(worker, conf);
2058 ap_log_error(APLOG_MARK, APLOG_INFO, 0, cmd->server, APLOGNO(01149)
2059 "Sharing worker '%s' instead of creating new worker '%s'",
2060 ap_proxy_worker_name(cmd->pool, worker), name);
2063 arr = apr_table_elts(params);
2064 elts = (const apr_table_entry_t *)arr->elts;
2065 for (i = 0; i < arr->nelts; i++) {
2067 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server, APLOGNO(01150)
2068 "Ignoring parameter '%s=%s' for worker '%s' because of worker sharing",
2069 elts[i].key, elts[i].val, ap_proxy_worker_name(cmd->pool, worker));
2071 err = set_worker_param(cmd->pool, worker, elts[i].key,
2074 return apr_pstrcat(cmd->temp_pool, "BalancerMember ", err, NULL);
2082 set_proxy_param(cmd_parms *cmd, void *dummy, const char *arg)
2084 server_rec *s = cmd->server;
2085 proxy_server_conf *conf =
2086 (proxy_server_conf *) ap_get_module_config(s->module_config, &proxy_module);
2089 proxy_balancer *balancer = NULL;
2090 proxy_worker *worker = NULL;
2091 int in_proxy_section = 0;
2092 /* XXX: Should this be NOT_IN_DIRECTORY|NOT_IN_FILES? */
2093 const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS);
2097 if (cmd->directive->parent &&
2098 strncasecmp(cmd->directive->parent->directive,
2099 "<Proxy", 6) == 0) {
2100 const char *pargs = cmd->directive->parent->args;
2101 /* Directive inside <Proxy section
2102 * Parent directive arg is the worker/balancer name.
2104 name = ap_getword_conf(cmd->temp_pool, &pargs);
2105 if ((word = ap_strchr(name, '>')))
2107 in_proxy_section = 1;
2110 /* Standard set directive with worker/balancer
2111 * name as first param.
2113 name = ap_getword_conf(cmd->temp_pool, &arg);
2116 if (ap_proxy_valid_balancer_name(name, 9)) {
2117 balancer = ap_proxy_get_balancer(cmd->pool, conf, name, 0);
2119 if (in_proxy_section) {
2120 err = ap_proxy_define_balancer(cmd->pool, &balancer, conf, name, "/", 0);
2122 return apr_pstrcat(cmd->temp_pool, "ProxySet ",
2126 return apr_pstrcat(cmd->temp_pool, "ProxySet can not find '",
2127 name, "' Balancer.", NULL);
2131 worker = ap_proxy_get_worker(cmd->temp_pool, NULL, conf, de_socketfy(cmd->temp_pool, name));
2133 if (in_proxy_section) {
2134 err = ap_proxy_define_worker(cmd->pool, &worker, NULL,
2137 return apr_pstrcat(cmd->temp_pool, "ProxySet ",
2141 return apr_pstrcat(cmd->temp_pool, "ProxySet can not find '",
2142 name, "' Worker.", NULL);
2147 word = ap_getword_conf(cmd->pool, &arg);
2148 val = strchr(word, '=');
2150 return "Invalid ProxySet parameter. Parameter must be "
2151 "in the form 'key=value'";
2156 err = set_worker_param(cmd->pool, worker, word, val);
2158 err = set_balancer_param(conf, cmd->pool, balancer, word, val);
2161 return apr_pstrcat(cmd->temp_pool, "ProxySet: ", err, " ", word, "=", val, "; ", name, NULL);
2167 static void ap_add_per_proxy_conf(server_rec *s, ap_conf_vector_t *dir_config)
2169 proxy_server_conf *sconf = ap_get_module_config(s->module_config,
2171 void **new_space = (void **)apr_array_push(sconf->sec_proxy);
2173 *new_space = dir_config;
2176 static const char *proxysection(cmd_parms *cmd, void *mconfig, const char *arg)
2179 const char *endp = ap_strrchr_c(arg, '>');
2180 int old_overrides = cmd->override;
2181 char *old_path = cmd->path;
2182 proxy_dir_conf *conf;
2183 ap_conf_vector_t *new_dir_conf = ap_create_per_dir_config(cmd->pool);
2184 ap_regex_t *r = NULL;
2185 const command_rec *thiscmd = cmd->cmd;
2187 proxy_balancer *balancer = NULL;
2188 proxy_worker *worker = NULL;
2190 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
2191 proxy_server_conf *sconf =
2192 (proxy_server_conf *) ap_get_module_config(cmd->server->module_config, &proxy_module);
2199 return apr_pstrcat(cmd->pool, cmd->cmd->name,
2200 "> directive missing closing '>'", NULL);
2203 arg = apr_pstrndup(cmd->pool, arg, endp-arg);
2206 if (thiscmd->cmd_data)
2207 return "<ProxyMatch > block must specify a path";
2209 return "<Proxy > block must specify a path";
2212 cmd->path = ap_getword_conf(cmd->pool, &arg);
2213 cmd->override = OR_ALL|ACCESS_CONF;
2215 if (!strncasecmp(cmd->path, "proxy:", 6))
2218 /* XXX Ignore case? What if we proxy a case-insensitive server?!?
2219 * While we are at it, shouldn't we also canonicalize the entire
2220 * scheme? See proxy_fixup()
2222 if (thiscmd->cmd_data) { /* <ProxyMatch> */
2223 r = ap_pregcomp(cmd->pool, cmd->path, AP_REG_EXTENDED);
2225 return "Regex could not be compiled";
2229 /* initialize our config and fetch it */
2230 conf = ap_set_config_vectors(cmd->server, new_dir_conf, cmd->path,
2231 &proxy_module, cmd->pool);
2233 errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_dir_conf);
2238 conf->p = cmd->path;
2239 conf->p_is_fnmatch = apr_fnmatch_test(conf->p);
2241 ap_add_per_proxy_conf(cmd->server, new_dir_conf);
2244 if (thiscmd->cmd_data)
2245 return "Multiple <ProxyMatch> arguments not (yet) supported.";
2246 if (conf->p_is_fnmatch)
2247 return apr_pstrcat(cmd->pool, thiscmd->name,
2248 "> arguments are not supported for wildchar url.",
2250 if (!ap_strchr_c(conf->p, ':'))
2251 return apr_pstrcat(cmd->pool, thiscmd->name,
2252 "> arguments are not supported for non url.",
2254 if (ap_proxy_valid_balancer_name((char *)conf->p, 9)) {
2255 balancer = ap_proxy_get_balancer(cmd->pool, sconf, conf->p, 0);
2257 err = ap_proxy_define_balancer(cmd->pool, &balancer,
2258 sconf, conf->p, "/", 0);
2260 return apr_pstrcat(cmd->temp_pool, thiscmd->name,
2265 worker = ap_proxy_get_worker(cmd->temp_pool, NULL, sconf,
2266 de_socketfy(cmd->temp_pool, (char*)conf->p));
2268 err = ap_proxy_define_worker(cmd->pool, &worker, NULL,
2271 return apr_pstrcat(cmd->temp_pool, thiscmd->name,
2275 if (worker == NULL && balancer == NULL) {
2276 return apr_pstrcat(cmd->pool, thiscmd->name,
2277 "> arguments are supported only for workers.",
2281 word = ap_getword_conf(cmd->pool, &arg);
2282 val = strchr(word, '=');
2284 return "Invalid Proxy parameter. Parameter must be "
2285 "in the form 'key=value'";
2290 err = set_worker_param(cmd->pool, worker, word, val);
2292 err = set_balancer_param(sconf, cmd->pool, balancer,
2295 return apr_pstrcat(cmd->temp_pool, thiscmd->name, " ", err, " ",
2296 word, "=", val, "; ", conf->p, NULL);
2300 cmd->path = old_path;
2301 cmd->override = old_overrides;
2306 static const command_rec proxy_cmds[] =
2308 AP_INIT_RAW_ARGS("<Proxy", proxysection, NULL, RSRC_CONF,
2309 "Container for directives affecting resources located in the proxied "
2311 AP_INIT_RAW_ARGS("<ProxyMatch", proxysection, (void*)1, RSRC_CONF,
2312 "Container for directives affecting resources located in the proxied "
2313 "location, in regular expression syntax"),
2314 AP_INIT_FLAG("ProxyRequests", set_proxy_req, NULL, RSRC_CONF,
2315 "on if the true proxy requests should be accepted"),
2316 AP_INIT_TAKE2("ProxyRemote", add_proxy_noregex, NULL, RSRC_CONF,
2317 "a scheme, partial URL or '*' and a proxy server"),
2318 AP_INIT_TAKE2("ProxyRemoteMatch", add_proxy_regex, NULL, RSRC_CONF,
2319 "a regex pattern and a proxy server"),
2320 AP_INIT_FLAG("ProxyPassInterpolateEnv", ap_set_flag_slot_char,
2321 (void*)APR_OFFSETOF(proxy_dir_conf, interpolate_env),
2322 RSRC_CONF|ACCESS_CONF, "Interpolate Env Vars in reverse Proxy") ,
2323 AP_INIT_RAW_ARGS("ProxyPass", add_pass_noregex, NULL, RSRC_CONF|ACCESS_CONF,
2324 "a virtual path and a URL"),
2325 AP_INIT_RAW_ARGS("ProxyPassMatch", add_pass_regex, NULL, RSRC_CONF|ACCESS_CONF,
2326 "a virtual path and a URL"),
2327 AP_INIT_TAKE123("ProxyPassReverse", add_pass_reverse, NULL, RSRC_CONF|ACCESS_CONF,
2328 "a virtual path and a URL for reverse proxy behaviour"),
2329 AP_INIT_TAKE23("ProxyPassReverseCookiePath", cookie_path, NULL,
2330 RSRC_CONF|ACCESS_CONF, "Path rewrite rule for proxying cookies"),
2331 AP_INIT_TAKE23("ProxyPassReverseCookieDomain", cookie_domain, NULL,
2332 RSRC_CONF|ACCESS_CONF, "Domain rewrite rule for proxying cookies"),
2333 AP_INIT_ITERATE("ProxyBlock", set_proxy_exclude, NULL, RSRC_CONF,
2334 "A list of names, hosts or domains to which the proxy will not connect"),
2335 AP_INIT_TAKE1("ProxyReceiveBufferSize", set_recv_buffer_size, NULL, RSRC_CONF,
2336 "Receive buffer size for outgoing HTTP and FTP connections in bytes"),
2337 AP_INIT_TAKE1("ProxyIOBufferSize", set_io_buffer_size, NULL, RSRC_CONF,
2338 "IO buffer size for outgoing HTTP and FTP connections in bytes"),
2339 AP_INIT_TAKE1("ProxyMaxForwards", set_max_forwards, NULL, RSRC_CONF,
2340 "The maximum number of proxies a request may be forwarded through."),
2341 AP_INIT_ITERATE("NoProxy", set_proxy_dirconn, NULL, RSRC_CONF,
2342 "A list of domains, hosts, or subnets to which the proxy will connect directly"),
2343 AP_INIT_TAKE1("ProxyDomain", set_proxy_domain, NULL, RSRC_CONF,
2344 "The default intranet domain name (in absence of a domain in the URL)"),
2345 AP_INIT_TAKE1("ProxyVia", set_via_opt, NULL, RSRC_CONF,
2346 "Configure Via: proxy header header to one of: on | off | block | full"),
2347 AP_INIT_FLAG("ProxyErrorOverride", set_proxy_error_override, NULL, RSRC_CONF|ACCESS_CONF,
2348 "use our error handling pages instead of the servers' we are proxying"),
2349 AP_INIT_FLAG("ProxyPreserveHost", set_preserve_host, NULL, RSRC_CONF|ACCESS_CONF,
2350 "on if we should preserve host header while proxying"),
2351 AP_INIT_TAKE1("ProxyTimeout", set_proxy_timeout, NULL, RSRC_CONF,
2352 "Set the timeout (in seconds) for a proxied connection. "
2353 "This overrides the server timeout"),
2354 AP_INIT_TAKE1("ProxyBadHeader", set_bad_opt, NULL, RSRC_CONF,
2355 "How to handle bad header line in response: IsError | Ignore | StartBody"),
2356 AP_INIT_RAW_ARGS("BalancerMember", add_member, NULL, RSRC_CONF|ACCESS_CONF,
2357 "A balancer name and scheme with list of params"),
2358 AP_INIT_TAKE1("BalancerGrowth", set_bgrowth, NULL, RSRC_CONF,
2359 "Number of additional Balancers that can be added post-config"),
2360 AP_INIT_FLAG("BalancerPersist", set_persist, NULL, RSRC_CONF,
2361 "on if the balancer should persist changes on reboot/restart made via the Balancer Manager"),
2362 AP_INIT_FLAG("BalancerInherit", set_inherit, NULL, RSRC_CONF,
2363 "on if this server should inherit Balancers and Workers defined in the main server "
2364 "(Setting to off recommended if using the Balancer Manager)"),
2365 AP_INIT_FLAG("ProxyPassInherit", set_ppinherit, NULL, RSRC_CONF,
2366 "on if this server should inherit all ProxyPass directives defined in the main server "
2367 "(Setting to off recommended if using the Balancer Manager)"),
2368 AP_INIT_TAKE1("ProxyStatus", set_status_opt, NULL, RSRC_CONF,
2369 "Configure Status: proxy status to one of: on | off | full"),
2370 AP_INIT_RAW_ARGS("ProxySet", set_proxy_param, NULL, RSRC_CONF|ACCESS_CONF,
2371 "A balancer or worker name with list of params"),
2372 AP_INIT_TAKE1("ProxySourceAddress", set_source_address, NULL, RSRC_CONF,
2373 "Configure local source IP used for request forward"),
2374 AP_INIT_FLAG("ProxyAddHeaders", add_proxy_http_headers, NULL, RSRC_CONF|ACCESS_CONF,
2375 "on if X-Forwarded-* headers should be added or completed"),
2379 static APR_OPTIONAL_FN_TYPE(ssl_proxy_enable) *proxy_ssl_enable = NULL;
2380 static APR_OPTIONAL_FN_TYPE(ssl_engine_disable) *proxy_ssl_disable = NULL;
2381 static APR_OPTIONAL_FN_TYPE(ssl_is_https) *proxy_is_https = NULL;
2382 static APR_OPTIONAL_FN_TYPE(ssl_var_lookup) *proxy_ssl_val = NULL;
2384 PROXY_DECLARE(int) ap_proxy_ssl_enable(conn_rec *c)
2387 * if c == NULL just check if the optional function was imported
2388 * else run the optional function so ssl filters are inserted
2390 if (proxy_ssl_enable) {
2391 return c ? proxy_ssl_enable(c) : 1;
2397 PROXY_DECLARE(int) ap_proxy_ssl_disable(conn_rec *c)
2399 if (proxy_ssl_disable) {
2400 return proxy_ssl_disable(c);
2406 PROXY_DECLARE(int) ap_proxy_conn_is_https(conn_rec *c)
2408 if (proxy_is_https) {
2409 return proxy_is_https(c);
2415 PROXY_DECLARE(const char *) ap_proxy_ssl_val(apr_pool_t *p, server_rec *s,
2416 conn_rec *c, request_rec *r,
2419 if (proxy_ssl_val) {
2420 /* XXX Perhaps the casting useless */
2421 return (const char *)proxy_ssl_val(p, s, c, r, (char *)var);
2427 static int proxy_post_config(apr_pool_t *pconf, apr_pool_t *plog,
2428 apr_pool_t *ptemp, server_rec *s)
2430 apr_status_t rv = ap_global_mutex_create(&proxy_mutex, NULL,
2431 proxy_id, NULL, s, pconf, 0);
2432 if (rv != APR_SUCCESS) {
2433 ap_log_perror(APLOG_MARK, APLOG_CRIT, rv, plog, APLOGNO(02478)
2434 "failed to create %s mutex", proxy_id);
2438 proxy_ssl_enable = APR_RETRIEVE_OPTIONAL_FN(ssl_proxy_enable);
2439 proxy_ssl_disable = APR_RETRIEVE_OPTIONAL_FN(ssl_engine_disable);
2440 proxy_is_https = APR_RETRIEVE_OPTIONAL_FN(ssl_is_https);
2441 proxy_ssl_val = APR_RETRIEVE_OPTIONAL_FN(ssl_var_lookup);
2442 ap_proxy_strmatch_path = apr_strmatch_precompile(pconf, "path=", 0);
2443 ap_proxy_strmatch_domain = apr_strmatch_precompile(pconf, "domain=", 0);
2449 * proxy Extension to mod_status
2451 static int proxy_status_hook(request_rec *r, int flags)
2454 void *sconf = r->server->module_config;
2455 proxy_server_conf *conf = (proxy_server_conf *)
2456 ap_get_module_config(sconf, &proxy_module);
2457 proxy_balancer *balancer = NULL;
2458 proxy_worker **worker = NULL;
2460 if ((flags & AP_STATUS_SHORT) || conf->balancers->nelts == 0 ||
2461 conf->proxy_status == status_off)
2464 balancer = (proxy_balancer *)conf->balancers->elts;
2465 for (i = 0; i < conf->balancers->nelts; i++) {
2466 ap_rputs("<hr />\n<h1>Proxy LoadBalancer Status for ", r);
2467 ap_rvputs(r, balancer->s->name, "</h1>\n\n", NULL);
2468 ap_rputs("\n\n<table border=\"0\"><tr>"
2469 "<th>SSes</th><th>Timeout</th><th>Method</th>"
2471 if (*balancer->s->sticky) {
2472 if (strcmp(balancer->s->sticky, balancer->s->sticky_path)) {
2473 ap_rvputs(r, "<td>", balancer->s->sticky, " | ",
2474 balancer->s->sticky_path, NULL);
2477 ap_rvputs(r, "<td>", balancer->s->sticky, NULL);
2481 ap_rputs("<td> - ", r);
2483 ap_rprintf(r, "</td><td>%" APR_TIME_T_FMT "</td>",
2484 apr_time_sec(balancer->s->timeout));
2485 ap_rprintf(r, "<td>%s</td>\n",
2486 balancer->lbmethod->name);
2487 ap_rputs("</table>\n", r);
2488 ap_rputs("\n\n<table border=\"0\"><tr>"
2489 "<th>Sch</th><th>Host</th><th>Stat</th>"
2490 "<th>Route</th><th>Redir</th>"
2491 "<th>F</th><th>Set</th><th>Acc</th><th>Wr</th><th>Rd</th>"
2494 worker = (proxy_worker **)balancer->workers->elts;
2495 for (n = 0; n < balancer->workers->nelts; n++) {
2497 ap_rvputs(r, "<tr>\n<td>", (*worker)->s->scheme, "</td>", NULL);
2498 ap_rvputs(r, "<td>", (*worker)->s->hostname, "</td><td>", NULL);
2499 ap_rvputs(r, ap_proxy_parse_wstatus(r->pool, *worker), NULL);
2500 ap_rvputs(r, "</td><td>", (*worker)->s->route, NULL);
2501 ap_rvputs(r, "</td><td>", (*worker)->s->redirect, NULL);
2502 ap_rprintf(r, "</td><td>%d</td>", (*worker)->s->lbfactor);
2503 ap_rprintf(r, "<td>%d</td>", (*worker)->s->lbset);
2504 ap_rprintf(r, "<td>%" APR_SIZE_T_FMT "</td><td>", (*worker)->s->elected);
2505 ap_rputs(apr_strfsize((*worker)->s->transferred, fbuf), r);
2506 ap_rputs("</td><td>", r);
2507 ap_rputs(apr_strfsize((*worker)->s->read, fbuf), r);
2508 ap_rputs("</td>\n", r);
2510 /* TODO: Add the rest of dynamic worker data */
2511 ap_rputs("</tr>\n", r);
2515 ap_rputs("</table>\n", r);
2518 ap_rputs("<hr /><table>\n"
2519 "<tr><th>SSes</th><td>Sticky session name</td></tr>\n"
2520 "<tr><th>Timeout</th><td>Balancer Timeout</td></tr>\n"
2521 "<tr><th>Sch</th><td>Connection scheme</td></tr>\n"
2522 "<tr><th>Host</th><td>Backend Hostname</td></tr>\n"
2523 "<tr><th>Stat</th><td>Worker status</td></tr>\n"
2524 "<tr><th>Route</th><td>Session Route</td></tr>\n"
2525 "<tr><th>Redir</th><td>Session Route Redirection</td></tr>\n"
2526 "<tr><th>F</th><td>Load Balancer Factor</td></tr>\n"
2527 "<tr><th>Acc</th><td>Number of uses</td></tr>\n"
2528 "<tr><th>Wr</th><td>Number of bytes transferred</td></tr>\n"
2529 "<tr><th>Rd</th><td>Number of bytes read</td></tr>\n"
2535 static void child_init(apr_pool_t *p, server_rec *s)
2537 proxy_worker *reverse = NULL;
2539 apr_status_t rv = apr_global_mutex_child_init(&proxy_mutex,
2540 apr_global_mutex_lockfile(proxy_mutex),
2542 if (rv != APR_SUCCESS) {
2543 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s, APLOGNO(02479)
2544 "could not init proxy_mutex in child");
2545 exit(1); /* Ugly, but what else? */
2550 void *sconf = s->module_config;
2551 proxy_server_conf *conf;
2552 proxy_worker *worker;
2555 conf = (proxy_server_conf *)ap_get_module_config(sconf, &proxy_module);
2557 * NOTE: non-balancer members don't use shm at all...
2558 * after all, why should they?
2560 worker = (proxy_worker *)conf->workers->elts;
2561 for (i = 0; i < conf->workers->nelts; i++, worker++) {
2562 ap_proxy_initialize_worker(worker, s, conf->pool);
2564 /* Create and initialize forward worker if defined */
2565 if (conf->req_set && conf->req) {
2566 proxy_worker *forward;
2567 ap_proxy_define_worker(p, &forward, NULL, NULL, "http://www.apache.org", 0);
2568 conf->forward = forward;
2569 PROXY_STRNCPY(conf->forward->s->name, "proxy:forward");
2570 PROXY_STRNCPY(conf->forward->s->hostname, "*");
2571 PROXY_STRNCPY(conf->forward->s->scheme, "*");
2572 conf->forward->hash.def = conf->forward->s->hash.def =
2573 ap_proxy_hashfunc(conf->forward->s->name, PROXY_HASHFUNC_DEFAULT);
2574 conf->forward->hash.fnv = conf->forward->s->hash.fnv =
2575 ap_proxy_hashfunc(conf->forward->s->name, PROXY_HASHFUNC_FNV);
2576 /* Do not disable worker in case of errors */
2577 conf->forward->s->status |= PROXY_WORKER_IGNORE_ERRORS;
2578 ap_proxy_initialize_worker(conf->forward, s, conf->pool);
2579 /* Disable address cache for generic forward worker */
2580 conf->forward->s->is_address_reusable = 0;
2583 ap_proxy_define_worker(p, &reverse, NULL, NULL, "http://www.apache.org", 0);
2584 PROXY_STRNCPY(reverse->s->name, "proxy:reverse");
2585 PROXY_STRNCPY(reverse->s->hostname, "*");
2586 PROXY_STRNCPY(reverse->s->scheme, "*");
2587 reverse->hash.def = reverse->s->hash.def =
2588 ap_proxy_hashfunc(reverse->s->name, PROXY_HASHFUNC_DEFAULT);
2589 reverse->hash.fnv = reverse->s->hash.fnv =
2590 ap_proxy_hashfunc(reverse->s->name, PROXY_HASHFUNC_FNV);
2591 /* Do not disable worker in case of errors */
2592 reverse->s->status |= PROXY_WORKER_IGNORE_ERRORS;
2593 conf->reverse = reverse;
2594 ap_proxy_initialize_worker(conf->reverse, s, conf->pool);
2595 /* Disable address cache for generic reverse worker */
2596 reverse->s->is_address_reusable = 0;
2598 conf->reverse = reverse;
2604 * This routine is called before the server processes the configuration
2607 static int proxy_pre_config(apr_pool_t *pconf, apr_pool_t *plog,
2610 apr_status_t rv = ap_mutex_register(pconf, proxy_id, NULL,
2611 APR_LOCK_DEFAULT, 0);
2612 if (rv != APR_SUCCESS) {
2613 ap_log_perror(APLOG_MARK, APLOG_CRIT, rv, plog, APLOGNO(02480)
2614 "failed to register %s mutex", proxy_id);
2615 return 500; /* An HTTP status would be a misnomer! */
2618 APR_OPTIONAL_HOOK(ap, status_hook, proxy_status_hook, NULL, NULL,
2620 /* Reset workers count on gracefull restart */
2621 proxy_lb_workers = 0;
2624 static void register_hooks(apr_pool_t *p)
2626 /* fixup before mod_rewrite, so that the proxied url will not
2627 * escaped accidentally by our fixup.
2629 static const char * const aszSucc[] = { "mod_rewrite.c", NULL};
2630 /* Only the mpm_winnt has child init hook handler.
2631 * make sure that we are called after the mpm
2634 static const char *const aszPred[] = { "mpm_winnt.c", "mod_proxy_balancer.c", NULL};
2637 ap_hook_handler(proxy_handler, NULL, NULL, APR_HOOK_FIRST);
2638 /* filename-to-URI translation */
2639 ap_hook_translate_name(proxy_trans, aszSucc, NULL, APR_HOOK_FIRST);
2640 /* walk <Proxy > entries and suppress default TRACE behavior */
2641 ap_hook_map_to_storage(proxy_map_location, NULL,NULL, APR_HOOK_FIRST);
2643 ap_hook_fixups(proxy_fixup, NULL, aszSucc, APR_HOOK_FIRST);
2644 /* post read_request handling */
2645 ap_hook_post_read_request(proxy_detect, NULL, NULL, APR_HOOK_FIRST);
2646 /* pre config handling */
2647 ap_hook_pre_config(proxy_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
2648 /* post config handling */
2649 ap_hook_post_config(proxy_post_config, NULL, NULL, APR_HOOK_MIDDLE);
2650 /* child init handling */
2651 ap_hook_child_init(child_init, aszPred, NULL, APR_HOOK_MIDDLE);
2653 /* register optional functions within proxy_util.c */
2654 proxy_util_register_hooks(p);
2657 AP_DECLARE_MODULE(proxy) =
2659 STANDARD20_MODULE_STUFF,
2660 create_proxy_dir_config, /* create per-directory config structure */
2661 merge_proxy_dir_config, /* merge per-directory config structures */
2662 create_proxy_config, /* create per-server config structure */
2663 merge_proxy_config, /* merge per-server config structures */
2664 proxy_cmds, /* command table */
2669 APR_HOOK_LINK(scheme_handler)
2670 APR_HOOK_LINK(canon_handler)
2671 APR_HOOK_LINK(pre_request)
2672 APR_HOOK_LINK(post_request)
2673 APR_HOOK_LINK(request_status)
2676 APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(proxy, PROXY, int, scheme_handler,
2677 (request_rec *r, proxy_worker *worker,
2678 proxy_server_conf *conf,
2679 char *url, const char *proxyhost,
2680 apr_port_t proxyport),(r,worker,conf,
2681 url,proxyhost,proxyport),DECLINED)
2682 APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(proxy, PROXY, int, canon_handler,
2683 (request_rec *r, char *url),(r,
2685 APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(proxy, PROXY, int, pre_request, (
2686 proxy_worker **worker,
2687 proxy_balancer **balancer,
2689 proxy_server_conf *conf,
2690 char **url),(worker,balancer,
2691 r,conf,url),DECLINED)
2692 APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(proxy, PROXY, int, post_request,
2693 (proxy_worker *worker,
2694 proxy_balancer *balancer,
2696 proxy_server_conf *conf),(worker,
2697 balancer,r,conf),DECLINED)
2698 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(proxy, PROXY, int, fixups,
2699 (request_rec *r), (r),
2701 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(proxy, PROXY, int, request_status,
2702 (int *status, request_rec *r),