]> granicus.if.org Git - apache/blob - modules/proxy/mod_proxy.c
No crutches, people!
[apache] / modules / proxy / mod_proxy.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2002 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  *    if any, must include the following acknowledgment:
21  *       "This product includes software developed by the
22  *        Apache Software Foundation (http://www.apache.org/)."
23  *    Alternately, this acknowledgment may appear in the software itself,
24  *    if and wherever such third-party acknowledgments normally appear.
25  *
26  * 4. The names "Apache" and "Apache Software Foundation" must
27  *    not be used to endorse or promote products derived from this
28  *    software without prior written permission. For written
29  *    permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache",
32  *    nor may "Apache" appear in their name, without prior written
33  *    permission of the Apache Software Foundation.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation.  For more
51  * information on the Apache Software Foundation, please see
52  * <http://www.apache.org/>.
53  *
54  * Portions of this software are based upon public domain software
55  * originally written at the National Center for Supercomputing Applications,
56  * University of Illinois, Urbana-Champaign.
57  */
58
59 #define CORE_PRIVATE
60
61 #include "mod_proxy.h"
62 #include "mod_core.h"
63
64 #include "apr_optional.h"
65
66 extern module AP_MODULE_DECLARE_DATA proxy_module;
67
68 #ifndef MAX
69 #define MAX(x,y) ((x) >= (y) ? (x) : (y))
70 #endif
71
72 /*
73  * A Web proxy module. Stages:
74  *
75  *  translate_name: set filename to proxy:<URL>
76  *  map_to_storage: run proxy_walk (rather than directory_walk/file_walk)
77  *                  can't trust directory_walk/file_walk since these are
78  *                  not in our filesystem.  Prevents mod_http from serving
79  *                  the TRACE request we will set aside to handle later.
80  *  type_checker:   set type to PROXY_MAGIC_TYPE if filename begins proxy:
81  *  fix_ups:        convert the URL stored in the filename to the
82  *                  canonical form.
83  *  handler:        handle proxy requests
84  */
85
86 /* -------------------------------------------------------------- */
87 /* Translate the URL into a 'filename' */
88
89 static int alias_match(const char *uri, const char *alias_fakename)
90 {
91     const char *end_fakename = alias_fakename + strlen(alias_fakename);
92     const char *aliasp = alias_fakename, *urip = uri;
93
94     while (aliasp < end_fakename) {
95         if (*aliasp == '/') {
96             /* any number of '/' in the alias matches any number in
97              * the supplied URI, but there must be at least one...
98              */
99             if (*urip != '/')
100                 return 0;
101
102             while (*aliasp == '/')
103                 ++aliasp;
104             while (*urip == '/')
105                 ++urip;
106         }
107         else {
108             /* Other characters are compared literally */
109             if (*urip++ != *aliasp++)
110                 return 0;
111         }
112     }
113
114     /* Check last alias path component matched all the way */
115
116     if (aliasp[-1] != '/' && *urip != '\0' && *urip != '/')
117         return 0;
118
119     /* Return number of characters from URI which matched (may be
120      * greater than length of alias, since we may have matched
121      * doubled slashes)
122      */
123
124     return urip - uri;
125 }
126
127 /* Detect if an absoluteURI should be proxied or not.  Note that we
128  * have to do this during this phase because later phases are
129  * "short-circuiting"... i.e. translate_names will end when the first
130  * module returns OK.  So for example, if the request is something like:
131  *
132  * GET http://othervhost/cgi-bin/printenv HTTP/1.0
133  *
134  * mod_alias will notice the /cgi-bin part and ScriptAlias it and
135  * short-circuit the proxy... just because of the ordering in the
136  * configuration file.
137  */
138 static int proxy_detect(request_rec *r)
139 {
140     void *sconf = r->server->module_config;
141     proxy_server_conf *conf;
142
143     conf = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
144
145     /* Ick... msvc (perhaps others) promotes ternary short results to int */
146
147     if (conf->req && r->parsed_uri.scheme) {
148         /* but it might be something vhosted */
149         if (!(r->parsed_uri.hostname
150               && !strcasecmp(r->parsed_uri.scheme, ap_http_method(r))
151               && ap_matches_request_vhost(r, r->parsed_uri.hostname,
152                                           (apr_port_t)(r->parsed_uri.port_str ? r->parsed_uri.port 
153                                                        : ap_default_port(r))))) {
154             r->proxyreq = PROXYREQ_PROXY;
155             r->uri = r->unparsed_uri;
156             r->filename = apr_pstrcat(r->pool, "proxy:", r->uri, NULL);
157             r->handler = "proxy-server";
158         }
159     }
160     /* We need special treatment for CONNECT proxying: it has no scheme part */
161     else if (conf->req && r->method_number == M_CONNECT
162              && r->parsed_uri.hostname
163              && r->parsed_uri.port_str) {
164         r->proxyreq = PROXYREQ_PROXY;
165         r->uri = r->unparsed_uri;
166         r->filename = apr_pstrcat(r->pool, "proxy:", r->uri, NULL);
167         r->handler = "proxy-server";
168     }
169     return DECLINED;
170 }
171
172 static int proxy_trans(request_rec *r)
173 {
174     void *sconf = r->server->module_config;
175     proxy_server_conf *conf =
176     (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
177     int i, len;
178     struct proxy_alias *ent = (struct proxy_alias *) conf->aliases->elts;
179
180     if (r->proxyreq) {
181         /* someone has already set up the proxy, it was possibly ourselves
182          * in proxy_detect
183          */
184         return OK;
185     }
186
187     /* XXX: since r->uri has been manipulated already we're not really
188      * compliant with RFC1945 at this point.  But this probably isn't
189      * an issue because this is a hybrid proxy/origin server.
190      */
191
192     for (i = 0; i < conf->aliases->nelts; i++) {
193         len = alias_match(r->uri, ent[i].fake);
194
195        if (len > 0) {
196            if ((ent[i].real[0] == '!' ) && ( ent[i].real[1] == 0 )) {
197                return DECLINED;
198            }
199
200            r->filename = apr_pstrcat(r->pool, "proxy:", ent[i].real,
201                                  (r->uri + len ), NULL);
202            r->handler = "proxy-server";
203            r->proxyreq = PROXYREQ_REVERSE;
204            return OK;
205        }
206     }
207     return DECLINED;
208 }
209
210 static int proxy_walk(request_rec *r)
211 {
212     proxy_server_conf *sconf = ap_get_module_config(r->server->module_config,
213                                                     &proxy_module);
214     ap_conf_vector_t *per_dir_defaults = r->server->lookup_defaults;
215     ap_conf_vector_t **sec_proxy = (ap_conf_vector_t **) sconf->sec_proxy->elts;
216     ap_conf_vector_t *entry_config;
217     proxy_dir_conf *entry_proxy;
218     int num_sec = sconf->sec_proxy->nelts;
219     /* XXX: shouldn't we use URI here?  Canonicalize it first?
220      * Pass over "proxy:" prefix 
221      */
222     const char *proxyname = r->filename + 6;
223     int j;
224
225     for (j = 0; j < num_sec; ++j) 
226     {
227         entry_config = sec_proxy[j];
228         entry_proxy = ap_get_module_config(entry_config, &proxy_module);
229
230         /* XXX: What about case insensitive matching ???
231          * Compare regex, fnmatch or string as appropriate
232          * If the entry doesn't relate, then continue 
233          */
234         if (entry_proxy->r 
235               ? ap_regexec(entry_proxy->r, proxyname, 0, NULL, 0)
236               : (entry_proxy->p_is_fnmatch
237                    ? apr_fnmatch(entry_proxy->p, proxyname, 0)
238                    : strncmp(proxyname, entry_proxy->p, 
239                                         strlen(entry_proxy->p)))) {
240             continue;
241         }
242         per_dir_defaults = ap_merge_per_dir_configs(r->pool, per_dir_defaults,
243                                                              entry_config);
244     }
245
246     r->per_dir_config = per_dir_defaults;
247
248     return OK;
249 }
250
251 static int proxy_map_location(request_rec *r)
252 {
253     int access_status;
254
255     if (!r->proxyreq || strncmp(r->filename, "proxy:", 6) != 0)
256         return DECLINED;
257
258     /* Don't let the core or mod_http map_to_storage hooks handle this,
259      * We don't need directory/file_walk, and we want to TRACE on our own.
260      */
261     if ((access_status = proxy_walk(r))) {
262         ap_die(access_status, r);
263         return access_status;
264     }
265
266     return OK;
267 }
268
269 /* -------------------------------------------------------------- */
270 /* Fixup the filename */
271
272 /*
273  * Canonicalise the URL
274  */
275 static int proxy_fixup(request_rec *r)
276 {
277     char *url, *p;
278     int access_status;
279
280     if (!r->proxyreq || strncmp(r->filename, "proxy:", 6) != 0)
281         return DECLINED;
282
283     /* XXX: Shouldn't we try this before we run the proxy_walk? */
284     url = &r->filename[6];
285
286     /* canonicalise each specific scheme */
287     if ((access_status = proxy_run_canon_handler(r, url))) {
288         return access_status;
289     }
290
291     p = strchr(url, ':');
292     if (p == NULL || p == url)
293         return HTTP_BAD_REQUEST;
294
295     return OK;          /* otherwise; we've done the best we can */
296 }
297
298 /* Send a redirection if the request contains a hostname which is not */
299 /* fully qualified, i.e. doesn't have a domain name appended. Some proxy */
300 /* servers like Netscape's allow this and access hosts from the local */
301 /* domain in this case. I think it is better to redirect to a FQDN, since */
302 /* these will later be found in the bookmarks files. */
303 /* The "ProxyDomain" directive determines what domain will be appended */
304 static int proxy_needsdomain(request_rec *r, const char *url, const char *domain)
305 {
306     char *nuri;
307     const char *ref;
308
309     /* We only want to worry about GETs */
310     if (!r->proxyreq || r->method_number != M_GET || !r->parsed_uri.hostname)
311         return DECLINED;
312
313     /* If host does contain a dot already, or it is "localhost", decline */
314     if (strchr(r->parsed_uri.hostname, '.') != NULL
315      || strcasecmp(r->parsed_uri.hostname, "localhost") == 0)
316         return DECLINED;        /* host name has a dot already */
317
318     ref = apr_table_get(r->headers_in, "Referer");
319
320     /* Reassemble the request, but insert the domain after the host name */
321     /* Note that the domain name always starts with a dot */
322     r->parsed_uri.hostname = apr_pstrcat(r->pool, r->parsed_uri.hostname,
323                                          domain, NULL);
324     nuri = apr_uri_unparse(r->pool,
325                            &r->parsed_uri,
326                            APR_URI_UNP_REVEALPASSWORD);
327
328     apr_table_set(r->headers_out, "Location", nuri);
329     ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
330                   "Domain missing: %s sent to %s%s%s", r->uri,
331                   apr_uri_unparse(r->pool, &r->parsed_uri,
332                                   APR_URI_UNP_OMITUSERINFO),
333                   ref ? " from " : "", ref ? ref : "");
334
335     return HTTP_MOVED_PERMANENTLY;
336 }
337
338 /* -------------------------------------------------------------- */
339 /* Invoke handler */
340
341 static int proxy_handler(request_rec *r)
342 {
343     char *url, *scheme, *p;
344     const char *p2;
345     void *sconf = r->server->module_config;
346     proxy_server_conf *conf = (proxy_server_conf *)
347         ap_get_module_config(sconf, &proxy_module);
348     apr_array_header_t *proxies = conf->proxies;
349     struct proxy_remote *ents = (struct proxy_remote *) proxies->elts;
350     int i, rc, access_status;
351     int direct_connect = 0;
352     const char *str;
353     long maxfwd;
354
355     /* is this for us? */
356     if (!r->proxyreq || strncmp(r->filename, "proxy:", 6) != 0)
357         return DECLINED;
358
359     /* handle max-forwards / OPTIONS / TRACE */
360     if ((str = apr_table_get(r->headers_in, "Max-Forwards"))) {
361         maxfwd = strtol(str, NULL, 10);
362         if (maxfwd < 1) {
363             switch (r->method_number) {
364             case M_TRACE: {
365                 int access_status;
366                 r->proxyreq = PROXYREQ_NONE;
367                 if ((access_status = ap_send_http_trace(r)))
368                     ap_die(access_status, r);
369                 else
370                     ap_finalize_request_protocol(r);
371                 return OK;
372             }
373             case M_OPTIONS: {
374                 int access_status;
375                 r->proxyreq = PROXYREQ_NONE;
376                 if ((access_status = ap_send_http_options(r)))
377                     ap_die(access_status, r);
378                 else
379                     ap_finalize_request_protocol(r);
380                 return OK;
381             }
382             default: {
383                 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
384                                      "Max-Forwards has reached zero - proxy loop?");
385             }
386             }
387         }
388         maxfwd = (maxfwd > 0) ? maxfwd - 1 : 0;
389     }
390     else {
391         /* set configured max-forwards */
392         maxfwd = conf->maxfwd;
393     }
394     apr_table_set(r->headers_in, "Max-Forwards", 
395                   apr_psprintf(r->pool, "%ld", (maxfwd > 0) ? maxfwd : 0));
396
397     url = r->filename + 6;
398     p = strchr(url, ':');
399     if (p == NULL)
400         return HTTP_BAD_REQUEST;
401
402     /* If the host doesn't have a domain name, add one and redirect. */
403     if (conf->domain != NULL) {
404         rc = proxy_needsdomain(r, url, conf->domain);
405         if (ap_is_HTTP_REDIRECT(rc))
406             return HTTP_MOVED_PERMANENTLY;
407     }
408
409     *p = '\0';
410     scheme = apr_pstrdup(r->pool, url);
411     *p = ':';
412
413     /* Check URI's destination host against NoProxy hosts */
414     /* Bypass ProxyRemote server lookup if configured as NoProxy */
415     /* we only know how to handle communication to a proxy via http */
416     /*if (strcasecmp(scheme, "http") == 0) */
417     {
418         int ii;
419         struct dirconn_entry *list = (struct dirconn_entry *) conf->dirconn->elts;
420
421         for (direct_connect = ii = 0; ii < conf->dirconn->nelts && !direct_connect; ii++) {
422             direct_connect = list[ii].matcher(&list[ii], r);
423         }
424 #if DEBUGGING
425         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
426                       (direct_connect) ? "NoProxy for %s" : "UseProxy for %s",
427                       r->uri);
428 #endif
429     }
430
431     /* firstly, try a proxy, unless a NoProxy directive is active */
432     if (!direct_connect) {
433         for (i = 0; i < proxies->nelts; i++) {
434             p2 = ap_strchr_c(ents[i].scheme, ':');  /* is it a partial URL? */
435             if (strcmp(ents[i].scheme, "*") == 0 ||
436                 (ents[i].use_regex && ap_regexec(ents[i].regexp, url, 0,NULL, 0)) ||
437                 (p2 == NULL && strcasecmp(scheme, ents[i].scheme) == 0) ||
438                 (p2 != NULL &&
439                  strncasecmp(url, ents[i].scheme, strlen(ents[i].scheme)) == 0)) {
440
441                 /* handle the scheme */
442                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
443                              "Trying to run scheme_handler against proxy");
444                 access_status = proxy_run_scheme_handler(r, conf, url, ents[i].hostname, ents[i].port);
445
446                 /* an error or success */
447                 if (access_status != DECLINED && access_status != HTTP_BAD_GATEWAY) {
448                     return access_status;
449                 }
450                 /* we failed to talk to the upstream proxy */
451             }
452         }
453     }
454
455     /* otherwise, try it direct */
456     /* N.B. what if we're behind a firewall, where we must use a proxy or
457      * give up??
458      */
459
460     /* handle the scheme */
461     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
462                  "Trying to run scheme_handler");
463     access_status = proxy_run_scheme_handler(r, conf, url, NULL, 0);
464     if (DECLINED == access_status) {
465         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
466                     "proxy: No protocol handler was valid for the URL %s. "
467                     "If you are using a DSO version of mod_proxy, make sure "
468                     "the proxy submodules are included in the configuration "
469                     "using LoadModule.", r->uri);
470         return HTTP_FORBIDDEN;
471     }
472     return access_status;
473 }
474
475 /* -------------------------------------------------------------- */
476 /* Setup configurable data */
477
478 static void * create_proxy_config(apr_pool_t *p, server_rec *s)
479 {
480     proxy_server_conf *ps = apr_pcalloc(p, sizeof(proxy_server_conf));
481
482     ps->sec_proxy = apr_array_make(p, 10, sizeof(ap_conf_vector_t *));
483     ps->proxies = apr_array_make(p, 10, sizeof(struct proxy_remote));
484     ps->aliases = apr_array_make(p, 10, sizeof(struct proxy_alias));
485     ps->raliases = apr_array_make(p, 10, sizeof(struct proxy_alias));
486     ps->noproxies = apr_array_make(p, 10, sizeof(struct noproxy_entry));
487     ps->dirconn = apr_array_make(p, 10, sizeof(struct dirconn_entry));
488     ps->allowed_connect_ports = apr_array_make(p, 10, sizeof(int));
489     ps->domain = NULL;
490     ps->viaopt = via_off; /* initially backward compatible with 1.3.1 */
491     ps->viaopt_set = 0; /* 0 means default */
492     ps->req = 0;
493     ps->req_set = 0;
494     ps->recv_buffer_size = 0; /* this default was left unset for some reason */
495     ps->recv_buffer_size_set = 0;
496     ps->io_buffer_size = AP_IOBUFSIZE;
497     ps->io_buffer_size_set = 0;
498     ps->maxfwd = DEFAULT_MAX_FORWARDS;
499     ps->maxfwd_set = 0;
500     ps->error_override = 0; 
501     ps->error_override_set = 0; 
502     ps->preserve_host_set =0;
503     ps->preserve_host =0;    
504     ps->timeout=0;
505     ps->timeout_set=0;
506     return ps;
507 }
508
509 static void * merge_proxy_config(apr_pool_t *p, void *basev, void *overridesv)
510 {
511     proxy_server_conf *ps = apr_pcalloc(p, sizeof(proxy_server_conf));
512     proxy_server_conf *base = (proxy_server_conf *) basev;
513     proxy_server_conf *overrides = (proxy_server_conf *) overridesv;
514
515     ps->proxies = apr_array_append(p, base->proxies, overrides->proxies);
516     ps->sec_proxy = apr_array_append(p, base->sec_proxy, overrides->sec_proxy);
517     ps->aliases = apr_array_append(p, base->aliases, overrides->aliases);
518     ps->raliases = apr_array_append(p, base->raliases, overrides->raliases);
519     ps->noproxies = apr_array_append(p, base->noproxies, overrides->noproxies);
520     ps->dirconn = apr_array_append(p, base->dirconn, overrides->dirconn);
521     ps->allowed_connect_ports = apr_array_append(p, base->allowed_connect_ports, overrides->allowed_connect_ports);
522
523     ps->domain = (overrides->domain == NULL) ? base->domain : overrides->domain;
524     ps->viaopt = (overrides->viaopt_set == 0) ? base->viaopt : overrides->viaopt;
525     ps->req = (overrides->req_set == 0) ? base->req : overrides->req;
526     ps->recv_buffer_size = (overrides->recv_buffer_size_set == 0) ? base->recv_buffer_size : overrides->recv_buffer_size;
527     ps->io_buffer_size = (overrides->io_buffer_size_set == 0) ? base->io_buffer_size : overrides->io_buffer_size;
528     ps->maxfwd = (overrides->maxfwd_set == 0) ? base->maxfwd : overrides->maxfwd;
529     ps->error_override = (overrides->error_override_set == 0) ? base->error_override : overrides->error_override;
530     ps->preserve_host = (overrides->preserve_host_set == 0) ? base->preserve_host : overrides->preserve_host;
531     ps->timeout= (overrides->timeout_set == 0) ? base->timeout : overrides->timeout;
532
533     return ps;
534 }
535
536 static void *create_proxy_dir_config(apr_pool_t *p, char *dummy)
537 {
538     proxy_dir_conf *new =
539         (proxy_dir_conf *) apr_pcalloc(p, sizeof(proxy_dir_conf));
540
541     /* Filled in by proxysection, when applicable */
542
543     return (void *) new;
544 }
545
546 static void *merge_proxy_dir_config(apr_pool_t *p, void *basev, void *addv)
547 {
548     proxy_dir_conf *new = (proxy_dir_conf *) apr_pcalloc(p, sizeof(proxy_dir_conf));
549     proxy_dir_conf *add = (proxy_dir_conf *) addv;
550
551     new->p = add->p;
552     new->p_is_fnmatch = add->p_is_fnmatch;
553     new->r = add->r;
554     return new;
555 }
556
557
558 static const char *
559     add_proxy(cmd_parms *cmd, void *dummy, const char *f1, const char *r1, int regex)
560 {
561     server_rec *s = cmd->server;
562     proxy_server_conf *conf =
563     (proxy_server_conf *) ap_get_module_config(s->module_config, &proxy_module);
564     struct proxy_remote *new;
565     char *p, *q;
566     char *r, *f, *scheme;
567     regex_t *reg = NULL;
568     int port;
569
570     r = apr_pstrdup(cmd->pool, r1);
571     scheme = apr_pstrdup(cmd->pool, r1);
572     f = apr_pstrdup(cmd->pool, f1);
573     p = strchr(r, ':');
574     if (p == NULL || p[1] != '/' || p[2] != '/' || p[3] == '\0') {
575         if (regex)
576             return "ProxyRemoteMatch: Bad syntax for a remote proxy server";
577         else
578             return "ProxyRemote: Bad syntax for a remote proxy server";
579     }
580     else {
581         scheme[p-r] = 0;
582     }
583     q = strchr(p + 3, ':');
584     if (q != NULL) {
585         if (sscanf(q + 1, "%u", &port) != 1 || port > 65535) {
586             if (regex)
587                 return "ProxyRemoteMatch: Bad syntax for a remote proxy server (bad port number)";
588             else
589                 return "ProxyRemote: Bad syntax for a remote proxy server (bad port number)";
590         }
591         *q = '\0';
592     }
593     else
594         port = -1;
595     *p = '\0';
596     if (regex) {
597         reg = ap_pregcomp(cmd->pool, f, REG_EXTENDED);
598         if (!reg)
599             return "Regular expression for ProxyRemoteMatch could not be compiled.";
600     }
601     else
602         if (strchr(f, ':') == NULL)
603             ap_str_tolower(f);          /* lowercase scheme */
604     ap_str_tolower(p + 3);              /* lowercase hostname */
605
606     if (port == -1) {
607         port = apr_uri_default_port_for_scheme(scheme);
608     }
609
610     new = apr_array_push(conf->proxies);
611     new->scheme = f;
612     new->protocol = r;
613     new->hostname = p + 3;
614     new->port = port;
615     new->regexp = reg;
616     new->use_regex = regex;
617     return NULL;
618 }
619
620 static const char *
621     add_proxy_noregex(cmd_parms *cmd, void *dummy, const char *f1, const char *r1)
622 {
623     return add_proxy(cmd, dummy, f1, r1, 0);
624 }
625
626 static const char *
627     add_proxy_regex(cmd_parms *cmd, void *dummy, const char *f1, const char *r1)
628 {
629     return add_proxy(cmd, dummy, f1, r1, 1);
630 }
631
632 static const char *
633     add_pass(cmd_parms *cmd, void *dummy, const char *f, const char *r)
634 {
635     server_rec *s = cmd->server;
636     proxy_server_conf *conf =
637     (proxy_server_conf *) ap_get_module_config(s->module_config, &proxy_module);
638     struct proxy_alias *new;
639     if (r!=NULL && cmd->path == NULL ) {
640         new = apr_array_push(conf->aliases);
641         new->fake = f;
642         new->real = r;
643     } else if (r==NULL && cmd->path != NULL) {
644         new = apr_array_push(conf->aliases);
645         new->fake = cmd->path;
646         new->real = f;
647     } else {
648         if ( r== NULL)
649             return "ProxyPass needs a path when not defined in a location";
650         else 
651             return "ProxyPass can not have a path when defined in a location";
652     }
653
654      return NULL;
655 }
656
657 static const char *
658     add_pass_reverse(cmd_parms *cmd, void *dummy, const char *f, const char *r)
659 {
660     server_rec *s = cmd->server;
661     proxy_server_conf *conf;
662     struct proxy_alias *new;
663
664     conf = (proxy_server_conf *)ap_get_module_config(s->module_config, 
665                                                      &proxy_module);
666     if (r!=NULL && cmd->path == NULL ) {
667         new = apr_array_push(conf->raliases);
668         new->fake = f;
669         new->real = r;
670     } else if (r==NULL && cmd->path != NULL) {
671         new = apr_array_push(conf->raliases);
672         new->fake = cmd->path;
673         new->real = f;
674     } else {
675         if ( r == NULL)
676             return "ProxyPassReverse needs a path when not defined in a location";
677         else 
678             return "ProxyPassReverse can not have a path when defined in a location";
679     }
680
681     return NULL;
682 }
683
684 static const char *
685     set_proxy_exclude(cmd_parms *parms, void *dummy, const char *arg)
686 {
687     server_rec *s = parms->server;
688     proxy_server_conf *conf =
689     ap_get_module_config(s->module_config, &proxy_module);
690     struct noproxy_entry *new;
691     struct noproxy_entry *list = (struct noproxy_entry *) conf->noproxies->elts;
692     struct apr_sockaddr_t *addr;
693     int found = 0;
694     int i;
695
696     /* Don't duplicate entries */
697     for (i = 0; i < conf->noproxies->nelts; i++) {
698         if (apr_strnatcasecmp(arg, list[i].name) == 0) { /* ignore case for host names */
699             found = 1;
700         }
701     }
702
703     if (!found) {
704         new = apr_array_push(conf->noproxies);
705         new->name = arg;
706         if (APR_SUCCESS == apr_sockaddr_info_get(&addr, new->name, APR_UNSPEC, 0, 0, parms->pool)) {
707             new->addr = addr;
708         }
709         else {
710             new->addr = NULL;
711         }
712     }
713     return NULL;
714 }
715
716 /*
717  * Set the ports CONNECT can use
718  */
719 static const char *
720     set_allowed_ports(cmd_parms *parms, void *dummy, const char *arg)
721 {
722     server_rec *s = parms->server;
723     proxy_server_conf *conf =
724         ap_get_module_config(s->module_config, &proxy_module);
725     int *New;
726
727     if (!apr_isdigit(arg[0]))
728         return "AllowCONNECT: port number must be numeric";
729
730     New = apr_array_push(conf->allowed_connect_ports);
731     *New = atoi(arg);
732     return NULL;
733 }
734
735 /* Similar to set_proxy_exclude(), but defining directly connected hosts,
736  * which should never be accessed via the configured ProxyRemote servers
737  */
738 static const char *
739     set_proxy_dirconn(cmd_parms *parms, void *dummy, const char *arg)
740 {
741     server_rec *s = parms->server;
742     proxy_server_conf *conf =
743     ap_get_module_config(s->module_config, &proxy_module);
744     struct dirconn_entry *New;
745     struct dirconn_entry *list = (struct dirconn_entry *) conf->dirconn->elts;
746     int found = 0;
747     int i;
748
749     /* Don't duplicate entries */
750     for (i = 0; i < conf->dirconn->nelts; i++) {
751         if (strcasecmp(arg, list[i].name) == 0)
752             found = 1;
753     }
754
755     if (!found) {
756         New = apr_array_push(conf->dirconn);
757         New->name = apr_pstrdup(parms->pool, arg);
758         New->hostaddr = NULL;
759
760         if (ap_proxy_is_ipaddr(New, parms->pool)) {
761 #if DEBUGGING
762             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
763                          "Parsed addr %s", inet_ntoa(New->addr));
764             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
765                          "Parsed mask %s", inet_ntoa(New->mask));
766 #endif
767         }
768         else if (ap_proxy_is_domainname(New, parms->pool)) {
769             ap_str_tolower(New->name);
770 #if DEBUGGING
771             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
772                          "Parsed domain %s", New->name);
773 #endif
774         }
775         else if (ap_proxy_is_hostname(New, parms->pool)) {
776             ap_str_tolower(New->name);
777 #if DEBUGGING
778             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
779                          "Parsed host %s", New->name);
780 #endif
781         }
782         else {
783             ap_proxy_is_word(New, parms->pool);
784 #if DEBUGGING
785             fprintf(stderr, "Parsed word %s\n", New->name);
786 #endif
787         }
788     }
789     return NULL;
790 }
791
792 static const char *
793     set_proxy_domain(cmd_parms *parms, void *dummy, const char *arg)
794 {
795     proxy_server_conf *psf =
796     ap_get_module_config(parms->server->module_config, &proxy_module);
797
798     if (arg[0] != '.')
799         return "ProxyDomain: domain name must start with a dot.";
800
801     psf->domain = arg;
802     return NULL;
803 }
804
805 static const char *
806     set_proxy_req(cmd_parms *parms, void *dummy, int flag)
807 {
808     proxy_server_conf *psf =
809     ap_get_module_config(parms->server->module_config, &proxy_module);
810
811     psf->req = flag;
812     psf->req_set = 1;
813     return NULL;
814 }
815 static const char *
816     set_proxy_error_override(cmd_parms *parms, void *dummy, int flag)
817 {
818     proxy_server_conf *psf =
819     ap_get_module_config(parms->server->module_config, &proxy_module);
820
821     psf->error_override = flag;
822     psf->error_override_set = 1;
823     return NULL;
824 }
825 static const char *
826     set_preserve_host(cmd_parms *parms, void *dummy, int flag)
827 {
828     proxy_server_conf *psf =
829     ap_get_module_config(parms->server->module_config, &proxy_module);
830
831     psf->preserve_host = flag;
832     psf->preserve_host_set = 1;
833     return NULL;
834 }
835
836 static const char *
837     set_recv_buffer_size(cmd_parms *parms, void *dummy, const char *arg)
838 {
839     proxy_server_conf *psf =
840     ap_get_module_config(parms->server->module_config, &proxy_module);
841     int s = atoi(arg);
842     if (s < 512 && s != 0) {
843         return "ProxyReceiveBufferSize must be >= 512 bytes, or 0 for system default.";
844     }
845
846     psf->recv_buffer_size = s;
847     psf->recv_buffer_size_set = 1;
848     return NULL;
849 }
850
851 static const char *
852     set_io_buffer_size(cmd_parms *parms, void *dummy, const char *arg)
853 {
854     proxy_server_conf *psf =
855     ap_get_module_config(parms->server->module_config, &proxy_module);
856     long s = atol(arg);
857
858     psf->io_buffer_size = ((s > AP_IOBUFSIZE) ? s : AP_IOBUFSIZE);
859     psf->io_buffer_size_set = 1;
860     return NULL;
861 }
862
863 static const char *
864     set_max_forwards(cmd_parms *parms, void *dummy, const char *arg)
865 {
866     proxy_server_conf *psf =
867     ap_get_module_config(parms->server->module_config, &proxy_module);
868     long s = atol(arg);
869     if (s < 0) {
870         return "ProxyMaxForwards must be greater or equal to zero..";
871     }
872
873     psf->maxfwd = s;
874     psf->maxfwd_set = 1;
875     return NULL;
876 }
877 static const char*
878     set_proxy_timeout(cmd_parms *parms, void *dummy, const char *arg)
879 {
880     proxy_server_conf *psf =
881     ap_get_module_config(parms->server->module_config, &proxy_module);
882     int timeout;
883
884     timeout=atoi(arg);
885     if (timeout<1) {
886         return "Proxy Timeout must be at least 1 second.";
887     }
888     psf->timeout_set=1;
889     psf->timeout=apr_time_from_sec(timeout);
890
891     return NULL;    
892 }
893
894 static const char*
895     set_via_opt(cmd_parms *parms, void *dummy, const char *arg)
896 {
897     proxy_server_conf *psf =
898     ap_get_module_config(parms->server->module_config, &proxy_module);
899
900     if (strcasecmp(arg, "Off") == 0)
901         psf->viaopt = via_off;
902     else if (strcasecmp(arg, "On") == 0)
903         psf->viaopt = via_on;
904     else if (strcasecmp(arg, "Block") == 0)
905         psf->viaopt = via_block;
906     else if (strcasecmp(arg, "Full") == 0)
907         psf->viaopt = via_full;
908     else {
909         return "ProxyVia must be one of: "
910             "off | on | full | block";
911     }
912
913     psf->viaopt_set = 1;
914     return NULL;    
915 }
916
917 static void ap_add_per_proxy_conf(server_rec *s, ap_conf_vector_t *dir_config)
918 {
919     proxy_server_conf *sconf = ap_get_module_config(s->module_config,
920                                                     &proxy_module);
921     void **new_space = (void **)apr_array_push(sconf->sec_proxy);
922     
923     *new_space = dir_config;
924 }
925
926 static const char *proxysection(cmd_parms *cmd, void *mconfig, const char *arg)
927 {
928     const char *errmsg;
929     const char *endp = ap_strrchr_c(arg, '>');
930     int old_overrides = cmd->override;
931     char *old_path = cmd->path;
932     proxy_dir_conf *conf;
933     ap_conf_vector_t *new_dir_conf = ap_create_per_dir_config(cmd->pool);
934     regex_t *r = NULL;
935     const command_rec *thiscmd = cmd->cmd;
936
937     const char *err = ap_check_cmd_context(cmd,
938                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
939     if (err != NULL) {
940         return err;
941     }
942
943     if (endp == NULL) {
944         return apr_pstrcat(cmd->pool, cmd->cmd->name,
945                            "> directive missing closing '>'", NULL);
946     }
947
948     arg=apr_pstrndup(cmd->pool, arg, endp-arg);
949
950     if (!arg) {
951         if (thiscmd->cmd_data)
952             return "<ProxyMatch > block must specify a path";
953         else
954             return "<Proxy > block must specify a path";
955     }
956
957     cmd->path = ap_getword_conf(cmd->pool, &arg);
958     cmd->override = OR_ALL|ACCESS_CONF;
959
960     if (!strncasecmp(cmd->path, "proxy:", 6))
961         cmd->path += 6;
962
963     /* XXX Ignore case?  What if we proxy a case-insensitive server?!? 
964      * While we are at it, shouldn't we also canonicalize the entire
965      * scheme?  See proxy_fixup()
966      */
967     if (thiscmd->cmd_data) { /* <ProxyMatch> */
968         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
969     }
970     else if (!strcmp(cmd->path, "~")) {
971         cmd->path = ap_getword_conf(cmd->pool, &arg);
972         if (!cmd->path)
973             return "<Proxy ~ > block must specify a path";
974         if (strncasecmp(cmd->path, "proxy:", 6))
975             cmd->path += 6;
976         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
977     }
978
979     /* initialize our config and fetch it */
980     conf = ap_set_config_vectors(cmd->server, new_dir_conf, cmd->path,
981                                  &proxy_module, cmd->pool);
982
983     errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_dir_conf);
984     if (errmsg != NULL)
985         return errmsg;
986
987     conf->r = r;
988     conf->p = cmd->path;
989     conf->p_is_fnmatch = apr_is_fnmatch(conf->p);
990
991     ap_add_per_proxy_conf(cmd->server, new_dir_conf);
992
993     if (*arg != '\0') {
994         return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
995                            "> arguments not (yet) supported.", NULL);
996     }
997
998     cmd->path = old_path;
999     cmd->override = old_overrides;
1000
1001     return NULL;
1002 }
1003
1004 static const command_rec proxy_cmds[] =
1005 {
1006     AP_INIT_RAW_ARGS("<Proxy", proxysection, NULL, RSRC_CONF, 
1007     "Container for directives affecting resources located in the proxied "
1008     "location"),
1009     AP_INIT_RAW_ARGS("<ProxyMatch", proxysection, (void*)1, RSRC_CONF,
1010     "Container for directives affecting resources located in the proxied "
1011     "location, in regular expression syntax"),
1012     AP_INIT_FLAG("ProxyRequests", set_proxy_req, NULL, RSRC_CONF,
1013      "on if the true proxy requests should be accepted"),
1014     AP_INIT_TAKE2("ProxyRemote", add_proxy_noregex, NULL, RSRC_CONF,
1015      "a scheme, partial URL or '*' and a proxy server"),
1016     AP_INIT_TAKE2("ProxyRemoteMatch", add_proxy_regex, NULL, RSRC_CONF,
1017      "a regex pattern and a proxy server"),
1018     AP_INIT_TAKE12("ProxyPass", add_pass, NULL, RSRC_CONF|ACCESS_CONF,
1019      "a virtual path and a URL"),
1020     AP_INIT_TAKE12("ProxyPassReverse", add_pass_reverse, NULL, RSRC_CONF|ACCESS_CONF,
1021      "a virtual path and a URL for reverse proxy behaviour"),
1022     AP_INIT_ITERATE("ProxyBlock", set_proxy_exclude, NULL, RSRC_CONF,
1023      "A list of names, hosts or domains to which the proxy will not connect"),
1024     AP_INIT_TAKE1("ProxyReceiveBufferSize", set_recv_buffer_size, NULL, RSRC_CONF,
1025      "Receive buffer size for outgoing HTTP and FTP connections in bytes"),
1026     AP_INIT_TAKE1("ProxyIOBufferSize", set_io_buffer_size, NULL, RSRC_CONF,
1027      "IO buffer size for outgoing HTTP and FTP connections in bytes"),
1028     AP_INIT_TAKE1("ProxyMaxForwards", set_max_forwards, NULL, RSRC_CONF,
1029      "The maximum number of proxies a request may be forwarded through."),
1030     AP_INIT_ITERATE("NoProxy", set_proxy_dirconn, NULL, RSRC_CONF,
1031      "A list of domains, hosts, or subnets to which the proxy will connect directly"),
1032     AP_INIT_TAKE1("ProxyDomain", set_proxy_domain, NULL, RSRC_CONF,
1033      "The default intranet domain name (in absence of a domain in the URL)"),
1034     AP_INIT_ITERATE("AllowCONNECT", set_allowed_ports, NULL, RSRC_CONF,
1035      "A list of ports which CONNECT may connect to"),
1036     AP_INIT_TAKE1("ProxyVia", set_via_opt, NULL, RSRC_CONF,
1037      "Configure Via: proxy header header to one of: on | off | block | full"),
1038     AP_INIT_FLAG("ProxyErrorOverride", set_proxy_error_override, NULL, RSRC_CONF,
1039      "use our error handling pages instead of the servers' we are proxying"),
1040     AP_INIT_FLAG("ProxyPreserveHost", set_preserve_host, NULL, RSRC_CONF,
1041      "on if we should preserve host header while proxying"),
1042     AP_INIT_TAKE1("ProxyTimeout", set_proxy_timeout, NULL, RSRC_CONF,
1043      "Set the timeout (in seconds) for a proxied connection. "
1044      "This overrides the server timeout"),
1045  
1046     {NULL}
1047 };
1048
1049 APR_DECLARE_OPTIONAL_FN(int, ssl_proxy_enable, (conn_rec *));
1050 APR_DECLARE_OPTIONAL_FN(int, ssl_engine_disable, (conn_rec *));
1051
1052 static APR_OPTIONAL_FN_TYPE(ssl_proxy_enable) *proxy_ssl_enable = NULL;
1053 static APR_OPTIONAL_FN_TYPE(ssl_engine_disable) *proxy_ssl_disable = NULL;
1054
1055 PROXY_DECLARE(int) ap_proxy_ssl_enable(conn_rec *c)
1056 {
1057     /* 
1058      * if c == NULL just check if the optional function was imported
1059      * else run the optional function so ssl filters are inserted
1060      */
1061     if (proxy_ssl_enable) {
1062         return c ? proxy_ssl_enable(c) : 1;
1063     }
1064
1065     return 0;
1066 }
1067
1068 PROXY_DECLARE(int) ap_proxy_ssl_disable(conn_rec *c)
1069 {
1070     if (proxy_ssl_disable) {
1071         return proxy_ssl_disable(c);
1072     }
1073
1074     return 0;
1075 }
1076
1077 static int proxy_post_config(apr_pool_t *pconf, apr_pool_t *plog,
1078                              apr_pool_t *ptemp, server_rec *s)
1079 {
1080     proxy_ssl_enable = APR_RETRIEVE_OPTIONAL_FN(ssl_proxy_enable);
1081     proxy_ssl_disable = APR_RETRIEVE_OPTIONAL_FN(ssl_engine_disable);
1082
1083     return OK;
1084 }
1085
1086 static void register_hooks(apr_pool_t *p)
1087 {
1088     /* handler */
1089     ap_hook_handler(proxy_handler, NULL, NULL, APR_HOOK_FIRST);
1090     /* filename-to-URI translation */
1091     ap_hook_translate_name(proxy_trans, NULL, NULL, APR_HOOK_FIRST);
1092     /* walk <Proxy > entries and suppress default TRACE behavior */
1093     ap_hook_map_to_storage(proxy_map_location, NULL,NULL, APR_HOOK_FIRST);
1094     /* fixups */
1095     ap_hook_fixups(proxy_fixup, NULL, NULL, APR_HOOK_FIRST);
1096     /* post read_request handling */
1097     ap_hook_post_read_request(proxy_detect, NULL, NULL, APR_HOOK_FIRST);
1098     /* post config handling */
1099     ap_hook_post_config(proxy_post_config, NULL, NULL, APR_HOOK_MIDDLE);
1100 }
1101
1102 module AP_MODULE_DECLARE_DATA proxy_module =
1103 {
1104     STANDARD20_MODULE_STUFF,
1105     create_proxy_dir_config,    /* create per-directory config structure */
1106     merge_proxy_dir_config,     /* merge per-directory config structures */
1107     create_proxy_config,        /* create per-server config structure */
1108     merge_proxy_config,         /* merge per-server config structures */
1109     proxy_cmds,                 /* command table */
1110     register_hooks
1111 };
1112
1113 APR_HOOK_STRUCT(
1114         APR_HOOK_LINK(scheme_handler)
1115         APR_HOOK_LINK(canon_handler)
1116 )
1117
1118 APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(proxy, PROXY, int, scheme_handler, 
1119                                      (request_rec *r, proxy_server_conf *conf, 
1120                                      char *url, const char *proxyhost, 
1121                                      apr_port_t proxyport),(r,conf,url,
1122                                      proxyhost,proxyport),DECLINED)
1123 APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(proxy, PROXY, int, canon_handler, 
1124                                      (request_rec *r, char *url),(r,
1125                                      url),DECLINED)
1126 APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(proxy, PROXY, int, fixups,
1127                                     (request_rec *r), (r),
1128                                     OK, DECLINED)