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