]> granicus.if.org Git - apache/blob - modules/proxy/mod_proxy.c
import ssl_proxy_enable in the post config phase, otherwise LoadModule
[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|APLOG_NOERRNO, 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     if ((rc = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR)))
398         return rc;
399
400     url = r->filename + 6;
401     p = strchr(url, ':');
402     if (p == NULL)
403         return HTTP_BAD_REQUEST;
404
405     /* If the host doesn't have a domain name, add one and redirect. */
406     if (conf->domain != NULL) {
407         rc = proxy_needsdomain(r, url, conf->domain);
408         if (ap_is_HTTP_REDIRECT(rc))
409             return HTTP_MOVED_PERMANENTLY;
410     }
411
412     *p = '\0';
413     scheme = apr_pstrdup(r->pool, url);
414     *p = ':';
415
416     /* Check URI's destination host against NoProxy hosts */
417     /* Bypass ProxyRemote server lookup if configured as NoProxy */
418     /* we only know how to handle communication to a proxy via http */
419     /*if (strcasecmp(scheme, "http") == 0) */
420     {
421         int ii;
422         struct dirconn_entry *list = (struct dirconn_entry *) conf->dirconn->elts;
423
424         for (direct_connect = ii = 0; ii < conf->dirconn->nelts && !direct_connect; ii++) {
425             direct_connect = list[ii].matcher(&list[ii], r);
426         }
427 #if DEBUGGING
428         ap_log_rerror(APLOG_MARK, APLOG_DEBUG|APLOG_NOERRNO, 0, r,
429                       (direct_connect) ? "NoProxy for %s" : "UseProxy for %s",
430                       r->uri);
431 #endif
432     }
433
434     /* firstly, try a proxy, unless a NoProxy directive is active */
435     if (!direct_connect) {
436         for (i = 0; i < proxies->nelts; i++) {
437             p2 = ap_strchr_c(ents[i].scheme, ':');  /* is it a partial URL? */
438             if (strcmp(ents[i].scheme, "*") == 0 ||
439                 (ents[i].use_regex && ap_regexec(ents[i].regexp, url, 0,NULL, 0)) ||
440                 (p2 == NULL && strcasecmp(scheme, ents[i].scheme) == 0) ||
441                 (p2 != NULL &&
442                  strncasecmp(url, ents[i].scheme, strlen(ents[i].scheme)) == 0)) {
443
444                 /* handle the scheme */
445                 ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, r->server,
446                              "Trying to run scheme_handler against proxy");
447                 access_status = proxy_run_scheme_handler(r, conf, url, ents[i].hostname, ents[i].port);
448
449                 /* an error or success */
450                 if (access_status != DECLINED && access_status != HTTP_BAD_GATEWAY) {
451                     return access_status;
452                 }
453                 /* we failed to talk to the upstream proxy */
454             }
455         }
456     }
457
458     /* otherwise, try it direct */
459     /* N.B. what if we're behind a firewall, where we must use a proxy or
460      * give up??
461      */
462
463     /* handle the scheme */
464     ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, r->server,
465                  "Trying to run scheme_handler");
466     access_status = proxy_run_scheme_handler(r, conf, url, NULL, 0);
467     if (DECLINED == access_status) {
468         ap_log_error(APLOG_MARK, APLOG_DEBUG | APLOG_NOERRNO, 0, r->server,
469                      "Neither CONNECT, HTTP or FTP for %s",
470                      r->uri);
471         return HTTP_FORBIDDEN;
472     }
473     return access_status;
474 }
475
476 /* -------------------------------------------------------------- */
477 /* Setup configurable data */
478
479 static void * create_proxy_config(apr_pool_t *p, server_rec *s)
480 {
481     proxy_server_conf *ps = ap_pcalloc(p, sizeof(proxy_server_conf));
482
483     ps->sec_proxy = ap_make_array(p, 10, sizeof(ap_conf_vector_t *));
484     ps->proxies = ap_make_array(p, 10, sizeof(struct proxy_remote));
485     ps->aliases = ap_make_array(p, 10, sizeof(struct proxy_alias));
486     ps->raliases = ap_make_array(p, 10, sizeof(struct proxy_alias));
487     ps->noproxies = ap_make_array(p, 10, sizeof(struct noproxy_entry));
488     ps->dirconn = ap_make_array(p, 10, sizeof(struct dirconn_entry));
489     ps->allowed_connect_ports = ap_make_array(p, 10, sizeof(int));
490     ps->domain = NULL;
491     ps->viaopt = via_off; /* initially backward compatible with 1.3.1 */
492     ps->viaopt_set = 0; /* 0 means default */
493     ps->req = 0;
494     ps->req_set = 0;
495     ps->recv_buffer_size = 0; /* this default was left unset for some reason */
496     ps->recv_buffer_size_set = 0;
497     ps->io_buffer_size = AP_IOBUFSIZE;
498     ps->io_buffer_size_set = 0;
499     ps->maxfwd = DEFAULT_MAX_FORWARDS;
500     ps->maxfwd_set = 0;
501     ps->error_override = 0; 
502     ps->error_override_set = 0; 
503     ps->preserve_host_set =0;
504     ps->preserve_host =0;    
505     ps->timeout=0;
506     ps->timeout_set=0;
507     return ps;
508 }
509
510 static void * merge_proxy_config(apr_pool_t *p, void *basev, void *overridesv)
511 {
512     proxy_server_conf *ps = ap_pcalloc(p, sizeof(proxy_server_conf));
513     proxy_server_conf *base = (proxy_server_conf *) basev;
514     proxy_server_conf *overrides = (proxy_server_conf *) overridesv;
515
516     ps->proxies = apr_array_append(p, base->proxies, overrides->proxies);
517     ps->sec_proxy = apr_array_append(p, base->sec_proxy, overrides->sec_proxy);
518     ps->aliases = apr_array_append(p, base->aliases, overrides->aliases);
519     ps->raliases = apr_array_append(p, base->raliases, overrides->raliases);
520     ps->noproxies = apr_array_append(p, base->noproxies, overrides->noproxies);
521     ps->dirconn = apr_array_append(p, base->dirconn, overrides->dirconn);
522     ps->allowed_connect_ports = apr_array_append(p, base->allowed_connect_ports, overrides->allowed_connect_ports);
523
524     ps->domain = (overrides->domain == NULL) ? base->domain : overrides->domain;
525     ps->viaopt = (overrides->viaopt_set == 0) ? base->viaopt : overrides->viaopt;
526     ps->req = (overrides->req_set == 0) ? base->req : overrides->req;
527     ps->recv_buffer_size = (overrides->recv_buffer_size_set == 0) ? base->recv_buffer_size : overrides->recv_buffer_size;
528     ps->io_buffer_size = (overrides->io_buffer_size_set == 0) ? base->io_buffer_size : overrides->io_buffer_size;
529     ps->maxfwd = (overrides->maxfwd_set == 0) ? base->maxfwd : overrides->maxfwd;
530     ps->error_override = (overrides->error_override_set == 0) ? base->error_override : overrides->error_override;
531     ps->preserve_host = (overrides->preserve_host_set == 0) ? base->preserve_host : overrides->preserve_host;
532     ps->timeout= (overrides->timeout_set == 0) ? base->timeout : overrides->timeout;
533
534     return ps;
535 }
536
537 static void *create_proxy_dir_config(apr_pool_t *p, char *dummy)
538 {
539     proxy_dir_conf *new =
540         (proxy_dir_conf *) apr_pcalloc(p, sizeof(proxy_dir_conf));
541
542     /* Filled in by proxysection, when applicable */
543
544     return (void *) new;
545 }
546
547 static void *merge_proxy_dir_config(apr_pool_t *p, void *basev, void *addv)
548 {
549     proxy_dir_conf *new = (proxy_dir_conf *) apr_pcalloc(p, sizeof(proxy_dir_conf));
550     proxy_dir_conf *add = (proxy_dir_conf *) addv;
551
552     new->p = add->p;
553     new->p_is_fnmatch = add->p_is_fnmatch;
554     new->r = add->r;
555     return new;
556 }
557
558
559 static const char *
560     add_proxy(cmd_parms *cmd, void *dummy, const char *f1, const char *r1, int regex)
561 {
562     server_rec *s = cmd->server;
563     proxy_server_conf *conf =
564     (proxy_server_conf *) ap_get_module_config(s->module_config, &proxy_module);
565     struct proxy_remote *new;
566     char *p, *q;
567     char *r, *f, *scheme;
568     regex_t *reg = NULL;
569     int port;
570
571     r = apr_pstrdup(cmd->pool, r1);
572     scheme = apr_pstrdup(cmd->pool, r1);
573     f = apr_pstrdup(cmd->pool, f1);
574     p = strchr(r, ':');
575     if (p == NULL || p[1] != '/' || p[2] != '/' || p[3] == '\0') {
576         if (regex)
577             return "ProxyRemoteMatch: Bad syntax for a remote proxy server";
578         else
579             return "ProxyRemote: Bad syntax for a remote proxy server";
580     }
581     else {
582         scheme[p-r] = 0;
583     }
584     q = strchr(p + 3, ':');
585     if (q != NULL) {
586         if (sscanf(q + 1, "%u", &port) != 1 || port > 65535) {
587             if (regex)
588                 return "ProxyRemoteMatch: Bad syntax for a remote proxy server (bad port number)";
589             else
590                 return "ProxyRemote: Bad syntax for a remote proxy server (bad port number)";
591         }
592         *q = '\0';
593     }
594     else
595         port = -1;
596     *p = '\0';
597     if (regex) {
598         reg = ap_pregcomp(cmd->pool, f, REG_EXTENDED);
599         if (!reg)
600             return "Regular expression for ProxyRemoteMatch could not be compiled.";
601     }
602     else
603         if (strchr(f, ':') == NULL)
604             ap_str_tolower(f);          /* lowercase scheme */
605     ap_str_tolower(p + 3);              /* lowercase hostname */
606
607     if (port == -1) {
608         port = apr_uri_default_port_for_scheme(scheme);
609     }
610
611     new = apr_array_push(conf->proxies);
612     new->scheme = f;
613     new->protocol = r;
614     new->hostname = p + 3;
615     new->port = port;
616     new->regexp = reg;
617     new->use_regex = regex;
618     return NULL;
619 }
620
621 static const char *
622     add_proxy_noregex(cmd_parms *cmd, void *dummy, const char *f1, const char *r1)
623 {
624     return add_proxy(cmd, dummy, f1, r1, 0);
625 }
626
627 static const char *
628     add_proxy_regex(cmd_parms *cmd, void *dummy, const char *f1, const char *r1)
629 {
630     return add_proxy(cmd, dummy, f1, r1, 1);
631 }
632
633 static const char *
634     add_pass(cmd_parms *cmd, void *dummy, const char *f, const char *r)
635 {
636     server_rec *s = cmd->server;
637     proxy_server_conf *conf =
638     (proxy_server_conf *) ap_get_module_config(s->module_config, &proxy_module);
639     struct proxy_alias *new;
640     if (r!=NULL && cmd->path == NULL ) {
641         new = apr_array_push(conf->aliases);
642         new->fake = f;
643         new->real = r;
644     } else if (r==NULL && cmd->path != NULL) {
645         new = apr_array_push(conf->aliases);
646         new->fake = cmd->path;
647         new->real = f;
648     } else {
649         if ( r== NULL)
650             return "ProxyPass needs a path when not defined in a location";
651         else 
652             return "ProxyPass can not have a path when defined in a location";
653     }
654
655      return NULL;
656 }
657
658 static const char *
659     add_pass_reverse(cmd_parms *cmd, void *dummy, const char *f, const char *r)
660 {
661     server_rec *s = cmd->server;
662     proxy_server_conf *conf;
663     struct proxy_alias *new;
664
665     conf = (proxy_server_conf *)ap_get_module_config(s->module_config, 
666                                                      &proxy_module);
667     if (r!=NULL && cmd->path == NULL ) {
668         new = apr_array_push(conf->raliases);
669         new->fake = f;
670         new->real = r;
671     } else if (r==NULL && cmd->path != NULL) {
672         new = apr_array_push(conf->raliases);
673         new->fake = cmd->path;
674         new->real = f;
675     } else {
676         if ( r == NULL)
677             return "ProxyPassReverse needs a path when not defined in a location";
678         else 
679             return "ProxyPassReverse can not have a path when defined in a location";
680     }
681
682     return NULL;
683 }
684
685 static const char *
686     set_proxy_exclude(cmd_parms *parms, void *dummy, const char *arg)
687 {
688     server_rec *s = parms->server;
689     proxy_server_conf *conf =
690     ap_get_module_config(s->module_config, &proxy_module);
691     struct noproxy_entry *new;
692     struct noproxy_entry *list = (struct noproxy_entry *) conf->noproxies->elts;
693     struct apr_sockaddr_t *addr;
694     int found = 0;
695     int i;
696
697     /* Don't duplicate entries */
698     for (i = 0; i < conf->noproxies->nelts; i++) {
699         if (apr_strnatcasecmp(arg, list[i].name) == 0) { /* ignore case for host names */
700             found = 1;
701         }
702     }
703
704     if (!found) {
705         new = apr_array_push(conf->noproxies);
706         new->name = arg;
707         if (APR_SUCCESS == apr_sockaddr_info_get(&addr, new->name, APR_UNSPEC, 0, 0, parms->pool)) {
708             new->addr = addr;
709         }
710         else {
711             new->addr = NULL;
712         }
713     }
714     return NULL;
715 }
716
717 /*
718  * Set the ports CONNECT can use
719  */
720 static const char *
721     set_allowed_ports(cmd_parms *parms, void *dummy, const char *arg)
722 {
723     server_rec *s = parms->server;
724     proxy_server_conf *conf =
725         ap_get_module_config(s->module_config, &proxy_module);
726     int *New;
727
728     if (!apr_isdigit(arg[0]))
729         return "AllowCONNECT: port number must be numeric";
730
731     New = apr_array_push(conf->allowed_connect_ports);
732     *New = atoi(arg);
733     return NULL;
734 }
735
736 /* Similar to set_proxy_exclude(), but defining directly connected hosts,
737  * which should never be accessed via the configured ProxyRemote servers
738  */
739 static const char *
740     set_proxy_dirconn(cmd_parms *parms, void *dummy, const char *arg)
741 {
742     server_rec *s = parms->server;
743     proxy_server_conf *conf =
744     ap_get_module_config(s->module_config, &proxy_module);
745     struct dirconn_entry *New;
746     struct dirconn_entry *list = (struct dirconn_entry *) conf->dirconn->elts;
747     int found = 0;
748     int i;
749
750     /* Don't duplicate entries */
751     for (i = 0; i < conf->dirconn->nelts; i++) {
752         if (strcasecmp(arg, list[i].name) == 0)
753             found = 1;
754     }
755
756     if (!found) {
757         New = apr_array_push(conf->dirconn);
758         New->name = apr_pstrdup(parms->pool, arg);
759         New->hostaddr = NULL;
760
761         if (ap_proxy_is_ipaddr(New, parms->pool)) {
762 #if DEBUGGING
763             ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
764                          "Parsed addr %s", inet_ntoa(New->addr));
765             ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
766                          "Parsed mask %s", inet_ntoa(New->mask));
767 #endif
768         }
769         else if (ap_proxy_is_domainname(New, parms->pool)) {
770             ap_str_tolower(New->name);
771 #if DEBUGGING
772             ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
773                          "Parsed domain %s", New->name);
774 #endif
775         }
776         else if (ap_proxy_is_hostname(New, parms->pool)) {
777             ap_str_tolower(New->name);
778 #if DEBUGGING
779             ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
780                          "Parsed host %s", New->name);
781 #endif
782         }
783         else {
784             ap_proxy_is_word(New, parms->pool);
785 #if DEBUGGING
786             fprintf(stderr, "Parsed word %s\n", New->name);
787 #endif
788         }
789     }
790     return NULL;
791 }
792
793 static const char *
794     set_proxy_domain(cmd_parms *parms, void *dummy, const char *arg)
795 {
796     proxy_server_conf *psf =
797     ap_get_module_config(parms->server->module_config, &proxy_module);
798
799     if (arg[0] != '.')
800         return "ProxyDomain: domain name must start with a dot.";
801
802     psf->domain = arg;
803     return NULL;
804 }
805
806 static const char *
807     set_proxy_req(cmd_parms *parms, void *dummy, int flag)
808 {
809     proxy_server_conf *psf =
810     ap_get_module_config(parms->server->module_config, &proxy_module);
811
812     psf->req = flag;
813     psf->req_set = 1;
814     return NULL;
815 }
816 static const char *
817     set_proxy_error_override(cmd_parms *parms, void *dummy, int flag)
818 {
819     proxy_server_conf *psf =
820     ap_get_module_config(parms->server->module_config, &proxy_module);
821
822     psf->error_override = flag;
823     psf->error_override_set = 1;
824     return NULL;
825 }
826 static const char *
827     set_preserve_host(cmd_parms *parms, void *dummy, int flag)
828 {
829     proxy_server_conf *psf =
830     ap_get_module_config(parms->server->module_config, &proxy_module);
831
832     psf->preserve_host = flag;
833     psf->preserve_host_set = 1;
834     return NULL;
835 }
836
837 static const char *
838     set_recv_buffer_size(cmd_parms *parms, void *dummy, const char *arg)
839 {
840     proxy_server_conf *psf =
841     ap_get_module_config(parms->server->module_config, &proxy_module);
842     int s = atoi(arg);
843     if (s < 512 && s != 0) {
844         return "ProxyReceiveBufferSize must be >= 512 bytes, or 0 for system default.";
845     }
846
847     psf->recv_buffer_size = s;
848     psf->recv_buffer_size_set = 1;
849     return NULL;
850 }
851
852 static const char *
853     set_io_buffer_size(cmd_parms *parms, void *dummy, const char *arg)
854 {
855     proxy_server_conf *psf =
856     ap_get_module_config(parms->server->module_config, &proxy_module);
857     long s = atol(arg);
858
859     psf->io_buffer_size = ((s > AP_IOBUFSIZE) ? s : AP_IOBUFSIZE);
860     psf->io_buffer_size_set = 1;
861     return NULL;
862 }
863
864 static const char *
865     set_max_forwards(cmd_parms *parms, void *dummy, const char *arg)
866 {
867     proxy_server_conf *psf =
868     ap_get_module_config(parms->server->module_config, &proxy_module);
869     long s = atol(arg);
870     if (s < 0) {
871         return "ProxyMaxForwards must be greater or equal to zero..";
872     }
873
874     psf->maxfwd = s;
875     psf->maxfwd_set = 1;
876     return NULL;
877 }
878 static const char*
879     set_proxy_timeout(cmd_parms *parms, void *dummy, const char *arg)
880 {
881     proxy_server_conf *psf =
882     ap_get_module_config(parms->server->module_config, &proxy_module);
883     int timeout;
884
885     timeout=atoi(arg);
886     if (timeout<1) {
887         return "Proxy Timeout must be at least 1 second.";
888     }
889     psf->timeout_set=1;
890     psf->timeout=timeout;
891
892     return NULL;    
893 }
894
895 static const char*
896     set_via_opt(cmd_parms *parms, void *dummy, const char *arg)
897 {
898     proxy_server_conf *psf =
899     ap_get_module_config(parms->server->module_config, &proxy_module);
900
901     if (strcasecmp(arg, "Off") == 0)
902         psf->viaopt = via_off;
903     else if (strcasecmp(arg, "On") == 0)
904         psf->viaopt = via_on;
905     else if (strcasecmp(arg, "Block") == 0)
906         psf->viaopt = via_block;
907     else if (strcasecmp(arg, "Full") == 0)
908         psf->viaopt = via_full;
909     else {
910         return "ProxyVia must be one of: "
911             "off | on | full | block";
912     }
913
914     psf->viaopt_set = 1;
915     return NULL;    
916 }
917
918 static void ap_add_per_proxy_conf(server_rec *s, ap_conf_vector_t *dir_config)
919 {
920     proxy_server_conf *sconf = ap_get_module_config(s->module_config,
921                                                     &proxy_module);
922     void **new_space = (void **)apr_array_push(sconf->sec_proxy);
923     
924     *new_space = dir_config;
925 }
926
927 static const char *proxysection(cmd_parms *cmd, void *mconfig, const char *arg)
928 {
929     const char *errmsg;
930     const char *endp = ap_strrchr_c(arg, '>');
931     int old_overrides = cmd->override;
932     char *old_path = cmd->path;
933     proxy_dir_conf *conf;
934     ap_conf_vector_t *new_dir_conf = ap_create_per_dir_config(cmd->pool);
935     regex_t *r = NULL;
936     const command_rec *thiscmd = cmd->cmd;
937
938     const char *err = ap_check_cmd_context(cmd,
939                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
940     if (err != NULL) {
941         return err;
942     }
943
944     if (endp == NULL) {
945         return apr_pstrcat(cmd->pool, cmd->cmd->name,
946                            "> directive missing closing '>'", NULL);
947     }
948
949     arg=apr_pstrndup(cmd->pool, arg, endp-arg);
950
951     if (!arg) {
952         if (thiscmd->cmd_data)
953             return "<ProxyMatch > block must specify a path";
954         else
955             return "<Proxy > block must specify a path";
956     }
957
958     cmd->path = ap_getword_conf(cmd->pool, &arg);
959     cmd->override = OR_ALL|ACCESS_CONF;
960
961     if (!strncasecmp(cmd->path, "proxy:", 6))
962         cmd->path += 6;
963
964     /* XXX Ignore case?  What if we proxy a case-insensitive server?!? 
965      * While we are at it, shouldn't we also canonicalize the entire
966      * scheme?  See proxy_fixup()
967      */
968     if (thiscmd->cmd_data) { /* <ProxyMatch> */
969         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
970     }
971     else if (!strcmp(cmd->path, "~")) {
972         cmd->path = ap_getword_conf(cmd->pool, &arg);
973         if (!cmd->path)
974             return "<Proxy ~ > block must specify a path";
975         if (strncasecmp(cmd->path, "proxy:", 6))
976             cmd->path += 6;
977         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
978     }
979
980     /* initialize our config and fetch it */
981     conf = ap_set_config_vectors(cmd->server, new_dir_conf, cmd->path,
982                                  &proxy_module, cmd->pool);
983
984     errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_dir_conf);
985     if (errmsg != NULL)
986         return errmsg;
987
988     conf->r = r;
989     conf->p = cmd->path;
990     conf->p_is_fnmatch = apr_is_fnmatch(conf->p);
991
992     ap_add_per_proxy_conf(cmd->server, new_dir_conf);
993
994     if (*arg != '\0') {
995         return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
996                            "> arguments not (yet) supported.", NULL);
997     }
998
999     cmd->path = old_path;
1000     cmd->override = old_overrides;
1001
1002     return NULL;
1003 }
1004
1005 static const command_rec proxy_cmds[] =
1006 {
1007     AP_INIT_RAW_ARGS("<Proxy", proxysection, NULL, RSRC_CONF, 
1008     "Container for directives affecting resources located in the proxied "
1009     "location"),
1010     AP_INIT_RAW_ARGS("<ProxyMatch", proxysection, (void*)1, RSRC_CONF,
1011     "Container for directives affecting resources located in the proxied "
1012     "location, in regular expression syntax"),
1013     AP_INIT_FLAG("ProxyRequests", set_proxy_req, NULL, RSRC_CONF,
1014      "on if the true proxy requests should be accepted"),
1015     AP_INIT_TAKE2("ProxyRemote", add_proxy_noregex, NULL, RSRC_CONF,
1016      "a scheme, partial URL or '*' and a proxy server"),
1017     AP_INIT_TAKE2("ProxyRemoteMatch", add_proxy_regex, NULL, RSRC_CONF,
1018      "a regex pattern and a proxy server"),
1019     AP_INIT_TAKE12("ProxyPass", add_pass, NULL, RSRC_CONF|ACCESS_CONF,
1020      "a virtual path and a URL"),
1021     AP_INIT_TAKE12("ProxyPassReverse", add_pass_reverse, NULL, RSRC_CONF|ACCESS_CONF,
1022      "a virtual path and a URL for reverse proxy behaviour"),
1023     AP_INIT_ITERATE("ProxyBlock", set_proxy_exclude, NULL, RSRC_CONF,
1024      "A list of names, hosts or domains to which the proxy will not connect"),
1025     AP_INIT_TAKE1("ProxyReceiveBufferSize", set_recv_buffer_size, NULL, RSRC_CONF,
1026      "Receive buffer size for outgoing HTTP and FTP connections in bytes"),
1027     AP_INIT_TAKE1("ProxyIOBufferSize", set_io_buffer_size, NULL, RSRC_CONF,
1028      "IO buffer size for outgoing HTTP and FTP connections in bytes"),
1029     AP_INIT_TAKE1("ProxyMaxForwards", set_max_forwards, NULL, RSRC_CONF,
1030      "The maximum number of proxies a request may be forwarded through."),
1031     AP_INIT_ITERATE("NoProxy", set_proxy_dirconn, NULL, RSRC_CONF,
1032      "A list of domains, hosts, or subnets to which the proxy will connect directly"),
1033     AP_INIT_TAKE1("ProxyDomain", set_proxy_domain, NULL, RSRC_CONF,
1034      "The default intranet domain name (in absence of a domain in the URL)"),
1035     AP_INIT_ITERATE("AllowCONNECT", set_allowed_ports, NULL, RSRC_CONF,
1036      "A list of ports which CONNECT may connect to"),
1037     AP_INIT_TAKE1("ProxyVia", set_via_opt, NULL, RSRC_CONF,
1038      "Configure Via: proxy header header to one of: on | off | block | full"),
1039     AP_INIT_FLAG("ProxyErrorOverride", set_proxy_error_override, NULL, RSRC_CONF,
1040      "use our error handling pages instead of the servers' we are proxying"),
1041     AP_INIT_FLAG("ProxyPreserveHost", set_preserve_host, NULL, RSRC_CONF,
1042      "on if we should preserve host header while proxying"),
1043     AP_INIT_TAKE1("ProxyTimeout", set_proxy_timeout, NULL, RSRC_CONF,
1044      "Set the timeout (in seconds) for a proxied connection. "
1045      "This overrides the server timeout"),
1046  
1047     {NULL}
1048 };
1049
1050 APR_DECLARE_OPTIONAL_FN(int, ssl_proxy_enable, (conn_rec *));
1051
1052 static APR_OPTIONAL_FN_TYPE(ssl_proxy_enable) *proxy_ssl_enable = NULL;
1053
1054 int ap_proxy_ssl_enable(conn_rec *c)
1055 {
1056     /* 
1057      * if c == NULL just check if the optional function was imported
1058      * else run the optional function so ssl filters are inserted
1059      */
1060     if (proxy_ssl_enable) {
1061         return c ? proxy_ssl_enable(c) : 1;
1062     }
1063
1064     return 0;
1065 }
1066
1067 static int proxy_post_config(apr_pool_t *pconf, apr_pool_t *plog,
1068                              apr_pool_t *ptemp, server_rec *s)
1069 {
1070     proxy_ssl_enable = APR_RETRIEVE_OPTIONAL_FN(ssl_proxy_enable);
1071
1072     return OK;
1073 }
1074
1075 static void register_hooks(apr_pool_t *p)
1076 {
1077     /* handler */
1078     ap_hook_handler(proxy_handler, NULL, NULL, APR_HOOK_FIRST);
1079     /* filename-to-URI translation */
1080     ap_hook_translate_name(proxy_trans, NULL, NULL, APR_HOOK_FIRST);
1081     /* walk <Proxy > entries and suppress default TRACE behavior */
1082     ap_hook_map_to_storage(proxy_map_location, NULL,NULL, APR_HOOK_FIRST);
1083     /* fixups */
1084     ap_hook_fixups(proxy_fixup, NULL, NULL, APR_HOOK_FIRST);
1085     /* post read_request handling */
1086     ap_hook_post_read_request(proxy_detect, NULL, NULL, APR_HOOK_FIRST);
1087     /* post config handling */
1088     ap_hook_post_config(proxy_post_config, NULL, NULL, APR_HOOK_MIDDLE);
1089 }
1090
1091 module AP_MODULE_DECLARE_DATA proxy_module =
1092 {
1093     STANDARD20_MODULE_STUFF,
1094     create_proxy_dir_config,    /* create per-directory config structure */
1095     merge_proxy_dir_config,     /* merge per-directory config structures */
1096     create_proxy_config,        /* create per-server config structure */
1097     merge_proxy_config,         /* merge per-server config structures */
1098     proxy_cmds,                 /* command table */
1099     register_hooks
1100 };
1101
1102 APR_HOOK_STRUCT(
1103         APR_HOOK_LINK(scheme_handler)
1104         APR_HOOK_LINK(canon_handler)
1105 )
1106
1107 APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(proxy, PROXY, int, scheme_handler, 
1108                                      (request_rec *r, proxy_server_conf *conf, 
1109                                      char *url, const char *proxyhost, 
1110                                      apr_port_t proxyport),(r,conf,url,
1111                                      proxyhost,proxyport),DECLINED)
1112 APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(proxy, PROXY, int, canon_handler, 
1113                                      (request_rec *r, char *url),(r,
1114                                      url),DECLINED)