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