]> granicus.if.org Git - apache/blob - modules/proxy/mod_proxy_http.c
mod_proxy: add "nocanon" keyword to ProxyPass, to suppress
[apache] / modules / proxy / mod_proxy_http.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 /* HTTP routines for Apache proxy */
18
19 #include "mod_proxy.h"
20 #include "ap_regex.h"
21
22 module AP_MODULE_DECLARE_DATA proxy_http_module;
23
24 static apr_status_t ap_proxy_http_cleanup(const char *scheme,
25                                           request_rec *r,
26                                           proxy_conn_rec *backend);
27
28 /*
29  * Canonicalise http-like URLs.
30  *  scheme is the scheme for the URL
31  *  url    is the URL starting with the first '/'
32  *  def_port is the default port for this scheme.
33  */
34 static int proxy_http_canon(request_rec *r, char *url)
35 {
36     char *host, *path, *search, sport[7];
37     const char *err;
38     const char *scheme;
39     apr_port_t port, def_port;
40
41     /* ap_port_of_scheme() */
42     if (strncasecmp(url, "http:", 5) == 0) {
43         url += 5;
44         scheme = "http";
45     }
46     else if (strncasecmp(url, "https:", 6) == 0) {
47         url += 6;
48         scheme = "https";
49     }
50     else {
51         return DECLINED;
52     }
53     def_port = apr_uri_port_of_scheme(scheme);
54
55     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
56              "proxy: HTTP: canonicalising URL %s", url);
57
58     /* do syntatic check.
59      * We break the URL into host, port, path, search
60      */
61     port = def_port;
62     err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port);
63     if (err) {
64         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
65                       "error parsing URL %s: %s",
66                       url, err);
67         return HTTP_BAD_REQUEST;
68     }
69
70     /* now parse path/search args, according to rfc1738 */
71     /* N.B. if this isn't a true proxy request, then the URL _path_
72      * has already been decoded.  True proxy requests have r->uri
73      * == r->unparsed_uri, and no others have that property.
74      */
75     if (r->uri == r->unparsed_uri) {
76         search = strchr(url, '?');
77         if (search != NULL)
78             *(search++) = '\0';
79     }
80     else
81         search = r->args;
82
83     /* process path */
84     /* In a reverse proxy, our URL has been processed, so canonicalise
85      * unless proxy-nocanon is set to say it's raw
86      * In a forward proxy, we have and MUST NOT MANGLE the original.
87      */
88     switch (r->proxyreq) {
89     default: /* wtf are we doing here? */
90     case PROXYREQ_REVERSE:
91         if (apr_table_get(r->notes, "proxy-nocanon")) {
92             path = url;   /* this is the raw path */
93         }
94         else {
95             path = ap_proxy_canonenc(r->pool, url, strlen(url),
96                                      enc_path, 0, r->proxyreq);
97         }
98         break;
99     case PROXYREQ_PROXY:
100         path = url;
101         break;
102     }
103
104     if (path == NULL)
105         return HTTP_BAD_REQUEST;
106
107     if (port != def_port)
108         apr_snprintf(sport, sizeof(sport), ":%d", port);
109     else
110         sport[0] = '\0';
111
112     if (ap_strchr_c(host, ':')) { /* if literal IPv6 address */
113         host = apr_pstrcat(r->pool, "[", host, "]", NULL);
114     }
115     r->filename = apr_pstrcat(r->pool, "proxy:", scheme, "://", host, sport,
116             "/", path, (search) ? "?" : "", (search) ? search : "", NULL);
117     return OK;
118 }
119
120 /* Clear all connection-based headers from the incoming headers table */
121 typedef struct header_dptr {
122     apr_pool_t *pool;
123     apr_table_t *table;
124     apr_time_t time;
125 } header_dptr;
126 static ap_regex_t *warn_rx;
127 static int clean_warning_headers(void *data, const char *key, const char *val)
128 {
129     apr_table_t *headers = ((header_dptr*)data)->table;
130     apr_pool_t *pool = ((header_dptr*)data)->pool;
131     char *warning;
132     char *date;
133     apr_time_t warn_time;
134     const int nmatch = 3;
135     ap_regmatch_t pmatch[3];
136
137     if (headers == NULL) {
138         ((header_dptr*)data)->table = headers = apr_table_make(pool, 2);
139     }
140 /*
141  * Parse this, suckers!
142  *
143  *    Warning    = "Warning" ":" 1#warning-value
144  *
145  *    warning-value = warn-code SP warn-agent SP warn-text
146  *                                             [SP warn-date]
147  *
148  *    warn-code  = 3DIGIT
149  *    warn-agent = ( host [ ":" port ] ) | pseudonym
150  *                    ; the name or pseudonym of the server adding
151  *                    ; the Warning header, for use in debugging
152  *    warn-text  = quoted-string
153  *    warn-date  = <"> HTTP-date <">
154  *
155  * Buggrit, use a bloomin' regexp!
156  * (\d{3}\s+\S+\s+\".*?\"(\s+\"(.*?)\")?)  --> whole in $1, date in $3
157  */
158     while (!ap_regexec(warn_rx, val, nmatch, pmatch, 0)) {
159         warning = apr_pstrndup(pool, val+pmatch[0].rm_so,
160                                pmatch[0].rm_eo - pmatch[0].rm_so);
161         warn_time = 0;
162         if (pmatch[2].rm_eo > pmatch[2].rm_so) {
163             /* OK, we have a date here */
164             date = apr_pstrndup(pool, val+pmatch[2].rm_so,
165                                 pmatch[2].rm_eo - pmatch[2].rm_so);
166             warn_time = apr_date_parse_http(date);
167         }
168         if (!warn_time || (warn_time == ((header_dptr*)data)->time)) {
169             apr_table_addn(headers, key, warning);
170         }
171         val += pmatch[0].rm_eo;
172     }
173     return 1;
174 }
175 static apr_table_t *ap_proxy_clean_warnings(apr_pool_t *p, apr_table_t *headers)
176 {
177    header_dptr x;
178    x.pool = p;
179    x.table = NULL;
180    x.time = apr_date_parse_http(apr_table_get(headers, "Date"));
181    apr_table_do(clean_warning_headers, &x, headers, "Warning", NULL);
182    if (x.table != NULL) {
183        apr_table_unset(headers, "Warning");
184        return apr_table_overlay(p, headers, x.table);
185    }
186    else {
187         return headers;
188    }
189 }
190 static int clear_conn_headers(void *data, const char *key, const char *val)
191 {
192     apr_table_t *headers = ((header_dptr*)data)->table;
193     apr_pool_t *pool = ((header_dptr*)data)->pool;
194     const char *name;
195     char *next = apr_pstrdup(pool, val);
196     while (*next) {
197         name = next;
198         while (*next && !apr_isspace(*next) && (*next != ',')) {
199             ++next;
200         }
201         while (*next && (apr_isspace(*next) || (*next == ','))) {
202             *next++ = '\0';
203         }
204         apr_table_unset(headers, name);
205     }
206     return 1;
207 }
208 static void ap_proxy_clear_connection(apr_pool_t *p, apr_table_t *headers)
209 {
210     header_dptr x;
211     x.pool = p;
212     x.table = headers;
213     apr_table_unset(headers, "Proxy-Connection");
214     apr_table_do(clear_conn_headers, &x, headers, "Connection", NULL);
215     apr_table_unset(headers, "Connection");
216 }
217 static void add_te_chunked(apr_pool_t *p,
218                            apr_bucket_alloc_t *bucket_alloc,
219                            apr_bucket_brigade *header_brigade)
220 {
221     apr_bucket *e;
222     char *buf;
223     const char te_hdr[] = "Transfer-Encoding: chunked" CRLF;
224
225     buf = apr_pmemdup(p, te_hdr, sizeof(te_hdr)-1);
226     ap_xlate_proto_to_ascii(buf, sizeof(te_hdr)-1);
227
228     e = apr_bucket_pool_create(buf, sizeof(te_hdr)-1, p, bucket_alloc);
229     APR_BRIGADE_INSERT_TAIL(header_brigade, e);
230 }
231
232 static void add_cl(apr_pool_t *p,
233                    apr_bucket_alloc_t *bucket_alloc,
234                    apr_bucket_brigade *header_brigade,
235                    const char *cl_val)
236 {
237     apr_bucket *e;
238     char *buf;
239
240     buf = apr_pstrcat(p, "Content-Length: ",
241                       cl_val,
242                       CRLF,
243                       NULL);
244     ap_xlate_proto_to_ascii(buf, strlen(buf));
245     e = apr_bucket_pool_create(buf, strlen(buf), p, bucket_alloc);
246     APR_BRIGADE_INSERT_TAIL(header_brigade, e);
247 }
248
249 #define ASCII_CRLF  "\015\012"
250 #define ASCII_ZERO  "\060"
251
252 static void terminate_headers(apr_bucket_alloc_t *bucket_alloc,
253                               apr_bucket_brigade *header_brigade)
254 {
255     apr_bucket *e;
256
257     /* add empty line at the end of the headers */
258     e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
259     APR_BRIGADE_INSERT_TAIL(header_brigade, e);
260 }
261
262 static apr_status_t pass_brigade(apr_bucket_alloc_t *bucket_alloc,
263                                  request_rec *r, proxy_conn_rec *conn,
264                                  conn_rec *origin, apr_bucket_brigade *bb,
265                                  int flush)
266 {
267     apr_status_t status;
268     apr_off_t transferred;
269
270     if (flush) {
271         apr_bucket *e = apr_bucket_flush_create(bucket_alloc);
272         APR_BRIGADE_INSERT_TAIL(bb, e);
273     }
274     apr_brigade_length(bb, 0, &transferred);
275     if (transferred != -1)
276         conn->worker->s->transferred += transferred;
277     status = ap_pass_brigade(origin->output_filters, bb);
278     if (status != APR_SUCCESS) {
279         ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
280                      "proxy: pass request body failed to %pI (%s)",
281                      conn->addr, conn->hostname);
282         return status;
283     }
284     apr_brigade_cleanup(bb);
285     return APR_SUCCESS;
286 }
287
288 #define MAX_MEM_SPOOL 16384
289
290 static apr_status_t stream_reqbody_chunked(apr_pool_t *p,
291                                            request_rec *r,
292                                            proxy_conn_rec *p_conn,
293                                            conn_rec *origin,
294                                            apr_bucket_brigade *header_brigade,
295                                            apr_bucket_brigade *input_brigade)
296 {
297     int seen_eos = 0;
298     apr_size_t hdr_len;
299     apr_off_t bytes;
300     apr_status_t status;
301     apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
302     apr_bucket_brigade *bb;
303     apr_bucket *e;
304
305     add_te_chunked(p, bucket_alloc, header_brigade);
306     terminate_headers(bucket_alloc, header_brigade);
307
308     while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
309     {
310         char chunk_hdr[20];  /* must be here due to transient bucket. */
311
312         /* If this brigade contains EOS, either stop or remove it. */
313         if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
314             seen_eos = 1;
315
316             /* We can't pass this EOS to the output_filters. */
317             e = APR_BRIGADE_LAST(input_brigade);
318             apr_bucket_delete(e);
319         }
320
321         apr_brigade_length(input_brigade, 1, &bytes);
322
323         hdr_len = apr_snprintf(chunk_hdr, sizeof(chunk_hdr),
324                                "%" APR_UINT64_T_HEX_FMT CRLF,
325                                (apr_uint64_t)bytes);
326
327         ap_xlate_proto_to_ascii(chunk_hdr, hdr_len);
328         e = apr_bucket_transient_create(chunk_hdr, hdr_len,
329                                         bucket_alloc);
330         APR_BRIGADE_INSERT_HEAD(input_brigade, e);
331
332         /*
333          * Append the end-of-chunk CRLF
334          */
335         e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
336         APR_BRIGADE_INSERT_TAIL(input_brigade, e);
337
338         if (header_brigade) {
339             /* we never sent the header brigade, so go ahead and
340              * take care of that now
341              */
342             bb = header_brigade;
343
344             /*
345              * Save input_brigade in bb brigade. (At least) in the SSL case
346              * input_brigade contains transient buckets whose data would get
347              * overwritten during the next call of ap_get_brigade in the loop.
348              * ap_save_brigade ensures these buckets to be set aside.
349              * Calling ap_save_brigade with NULL as filter is OK, because
350              * bb brigade already has been created and does not need to get
351              * created by ap_save_brigade.
352              */
353             status = ap_save_brigade(NULL, &bb, &input_brigade, p);
354             if (status != APR_SUCCESS) {
355                 return status;
356             }
357
358             header_brigade = NULL;
359         }
360         else {
361             bb = input_brigade;
362         }
363
364         /* The request is flushed below this loop with chunk EOS header */
365         status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 0);
366         if (status != APR_SUCCESS) {
367             return status;
368         }
369
370         if (seen_eos) {
371             break;
372         }
373
374         status = ap_get_brigade(r->input_filters, input_brigade,
375                                 AP_MODE_READBYTES, APR_BLOCK_READ,
376                                 HUGE_STRING_LEN);
377
378         if (status != APR_SUCCESS) {
379             return status;
380         }
381     }
382
383     if (header_brigade) {
384         /* we never sent the header brigade because there was no request body;
385          * send it now
386          */
387         bb = header_brigade;
388     }
389     else {
390         if (!APR_BRIGADE_EMPTY(input_brigade)) {
391             /* input brigade still has an EOS which we can't pass to the output_filters. */
392             e = APR_BRIGADE_LAST(input_brigade);
393             AP_DEBUG_ASSERT(APR_BUCKET_IS_EOS(e));
394             apr_bucket_delete(e);
395         }
396         bb = input_brigade;
397     }
398
399     e = apr_bucket_immortal_create(ASCII_ZERO ASCII_CRLF
400                                    /* <trailers> */
401                                    ASCII_CRLF,
402                                    5, bucket_alloc);
403     APR_BRIGADE_INSERT_TAIL(bb, e);
404
405     if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
406         e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
407         APR_BRIGADE_INSERT_TAIL(bb, e);
408     }
409
410     /* Now we have headers-only, or the chunk EOS mark; flush it */
411     status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1);
412     return status;
413 }
414
415 static apr_status_t stream_reqbody_cl(apr_pool_t *p,
416                                       request_rec *r,
417                                       proxy_conn_rec *p_conn,
418                                       conn_rec *origin,
419                                       apr_bucket_brigade *header_brigade,
420                                       apr_bucket_brigade *input_brigade,
421                                       const char *old_cl_val)
422 {
423     int seen_eos = 0;
424     apr_status_t status = APR_SUCCESS;
425     apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
426     apr_bucket_brigade *bb;
427     apr_bucket *e;
428     apr_off_t cl_val = 0;
429     apr_off_t bytes;
430     apr_off_t bytes_streamed = 0;
431
432     if (old_cl_val) {
433         add_cl(p, bucket_alloc, header_brigade, old_cl_val);
434         if (APR_SUCCESS != (status = apr_strtoff(&cl_val, old_cl_val, NULL,
435                                                  0))) {
436             return status;
437         }
438     }
439     terminate_headers(bucket_alloc, header_brigade);
440
441     while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
442     {
443         apr_brigade_length(input_brigade, 1, &bytes);
444         bytes_streamed += bytes;
445
446         /* If this brigade contains EOS, either stop or remove it. */
447         if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
448             seen_eos = 1;
449
450             /* We can't pass this EOS to the output_filters. */
451             e = APR_BRIGADE_LAST(input_brigade);
452             apr_bucket_delete(e);
453
454             if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
455                 e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
456                 APR_BRIGADE_INSERT_TAIL(input_brigade, e);
457             }
458         }
459
460         /* C-L < bytes streamed?!?
461          * We will error out after the body is completely
462          * consumed, but we can't stream more bytes at the
463          * back end since they would in part be interpreted
464          * as another request!  If nothing is sent, then
465          * just send nothing.
466          *
467          * Prevents HTTP Response Splitting.
468          */
469         if (bytes_streamed > cl_val)
470              continue;
471
472         if (header_brigade) {
473             /* we never sent the header brigade, so go ahead and
474              * take care of that now
475              */
476             bb = header_brigade;
477
478             /*
479              * Save input_brigade in bb brigade. (At least) in the SSL case
480              * input_brigade contains transient buckets whose data would get
481              * overwritten during the next call of ap_get_brigade in the loop.
482              * ap_save_brigade ensures these buckets to be set aside.
483              * Calling ap_save_brigade with NULL as filter is OK, because
484              * bb brigade already has been created and does not need to get
485              * created by ap_save_brigade.
486              */
487             status = ap_save_brigade(NULL, &bb, &input_brigade, p);
488             if (status != APR_SUCCESS) {
489                 return status;
490             }
491
492             header_brigade = NULL;
493         }
494         else {
495             bb = input_brigade;
496         }
497
498         /* Once we hit EOS, we are ready to flush. */
499         status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, seen_eos);
500         if (status != APR_SUCCESS) {
501             return status;
502         }
503
504         if (seen_eos) {
505             break;
506         }
507
508         status = ap_get_brigade(r->input_filters, input_brigade,
509                                 AP_MODE_READBYTES, APR_BLOCK_READ,
510                                 HUGE_STRING_LEN);
511
512         if (status != APR_SUCCESS) {
513             return status;
514         }
515     }
516
517     if (bytes_streamed != cl_val) {
518         ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
519                      "proxy: client %s given Content-Length did not match"
520                      " number of body bytes read", r->connection->remote_ip);
521         return APR_EOF;
522     }
523
524     if (header_brigade) {
525         /* we never sent the header brigade since there was no request
526          * body; send it now with the flush flag
527          */
528         bb = header_brigade;
529         status = pass_brigade(bucket_alloc, r, p_conn, origin, bb, 1);
530     }
531     return status;
532 }
533
534 static apr_status_t spool_reqbody_cl(apr_pool_t *p,
535                                      request_rec *r,
536                                      proxy_conn_rec *p_conn,
537                                      conn_rec *origin,
538                                      apr_bucket_brigade *header_brigade,
539                                      apr_bucket_brigade *input_brigade,
540                                      int force_cl)
541 {
542     int seen_eos = 0;
543     apr_status_t status;
544     apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
545     apr_bucket_brigade *body_brigade;
546     apr_bucket *e;
547     apr_off_t bytes, bytes_spooled = 0, fsize = 0;
548     apr_file_t *tmpfile = NULL;
549
550     body_brigade = apr_brigade_create(p, bucket_alloc);
551
552     while (!APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade)))
553     {
554         /* If this brigade contains EOS, either stop or remove it. */
555         if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
556             seen_eos = 1;
557
558             /* We can't pass this EOS to the output_filters. */
559             e = APR_BRIGADE_LAST(input_brigade);
560             apr_bucket_delete(e);
561         }
562
563         apr_brigade_length(input_brigade, 1, &bytes);
564
565         if (bytes_spooled + bytes > MAX_MEM_SPOOL) {
566             /* can't spool any more in memory; write latest brigade to disk */
567             if (tmpfile == NULL) {
568                 const char *temp_dir;
569                 char *template;
570
571                 status = apr_temp_dir_get(&temp_dir, p);
572                 if (status != APR_SUCCESS) {
573                     ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
574                                  "proxy: search for temporary directory failed");
575                     return status;
576                 }
577                 apr_filepath_merge(&template, temp_dir,
578                                    "modproxy.tmp.XXXXXX",
579                                    APR_FILEPATH_NATIVE, p);
580                 status = apr_file_mktemp(&tmpfile, template, 0, p);
581                 if (status != APR_SUCCESS) {
582                     ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
583                                  "proxy: creation of temporary file in directory %s failed",
584                                  temp_dir);
585                     return status;
586                 }
587             }
588             for (e = APR_BRIGADE_FIRST(input_brigade);
589                  e != APR_BRIGADE_SENTINEL(input_brigade);
590                  e = APR_BUCKET_NEXT(e)) {
591                 const char *data;
592                 apr_size_t bytes_read, bytes_written;
593
594                 apr_bucket_read(e, &data, &bytes_read, APR_BLOCK_READ);
595                 status = apr_file_write_full(tmpfile, data, bytes_read, &bytes_written);
596                 if (status != APR_SUCCESS) {
597                     const char *tmpfile_name;
598
599                     if (apr_file_name_get(&tmpfile_name, tmpfile) != APR_SUCCESS) {
600                         tmpfile_name = "(unknown)";
601                     }
602                     ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
603                                  "proxy: write to temporary file %s failed",
604                                  tmpfile_name);
605                     return status;
606                 }
607                 AP_DEBUG_ASSERT(bytes_read == bytes_written);
608                 fsize += bytes_written;
609             }
610             apr_brigade_cleanup(input_brigade);
611         }
612         else {
613
614             /*
615              * Save input_brigade in body_brigade. (At least) in the SSL case
616              * input_brigade contains transient buckets whose data would get
617              * overwritten during the next call of ap_get_brigade in the loop.
618              * ap_save_brigade ensures these buckets to be set aside.
619              * Calling ap_save_brigade with NULL as filter is OK, because
620              * body_brigade already has been created and does not need to get
621              * created by ap_save_brigade.
622              */
623             status = ap_save_brigade(NULL, &body_brigade, &input_brigade, p);
624             if (status != APR_SUCCESS) {
625                 return status;
626             }
627
628         }
629
630         bytes_spooled += bytes;
631
632         if (seen_eos) {
633             break;
634         }
635
636         status = ap_get_brigade(r->input_filters, input_brigade,
637                                 AP_MODE_READBYTES, APR_BLOCK_READ,
638                                 HUGE_STRING_LEN);
639
640         if (status != APR_SUCCESS) {
641             return status;
642         }
643     }
644
645     if (bytes_spooled || force_cl) {
646         add_cl(p, bucket_alloc, header_brigade, apr_off_t_toa(p, bytes_spooled));
647     }
648     terminate_headers(bucket_alloc, header_brigade);
649     APR_BRIGADE_CONCAT(header_brigade, body_brigade);
650     if (tmpfile) {
651         apr_brigade_insert_file(header_brigade, tmpfile, 0, fsize, p);
652     }
653     if (apr_table_get(r->subprocess_env, "proxy-sendextracrlf")) {
654         e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
655         APR_BRIGADE_INSERT_TAIL(header_brigade, e);
656     }
657     /* This is all a single brigade, pass with flush flagged */
658     status = pass_brigade(bucket_alloc, r, p_conn, origin, header_brigade, 1);
659     return status;
660 }
661
662 static
663 apr_status_t ap_proxy_http_request(apr_pool_t *p, request_rec *r,
664                                    proxy_conn_rec *p_conn, conn_rec *origin,
665                                    proxy_server_conf *conf,
666                                    apr_uri_t *uri,
667                                    char *url, char *server_portstr)
668 {
669     conn_rec *c = r->connection;
670     apr_bucket_alloc_t *bucket_alloc = c->bucket_alloc;
671     apr_bucket_brigade *header_brigade;
672     apr_bucket_brigade *input_brigade;
673     apr_bucket_brigade *temp_brigade;
674     apr_bucket *e;
675     char *buf;
676     const apr_array_header_t *headers_in_array;
677     const apr_table_entry_t *headers_in;
678     int counter;
679     apr_status_t status;
680     enum rb_methods {RB_INIT, RB_STREAM_CL, RB_STREAM_CHUNKED, RB_SPOOL_CL};
681     enum rb_methods rb_method = RB_INIT;
682     const char *old_cl_val = NULL;
683     const char *old_te_val = NULL;
684     apr_off_t bytes_read = 0;
685     apr_off_t bytes;
686     int force10;
687     apr_table_t *headers_in_copy;
688
689     header_brigade = apr_brigade_create(p, origin->bucket_alloc);
690
691     /*
692      * Send the HTTP/1.1 request to the remote server
693      */
694
695     if (apr_table_get(r->subprocess_env, "force-proxy-request-1.0")) {
696         buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.0" CRLF, NULL);
697         force10 = 1;
698         p_conn->close++;
699     } else {
700         buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.1" CRLF, NULL);
701         force10 = 0;
702     }
703     if (apr_table_get(r->subprocess_env, "proxy-nokeepalive")) {
704         origin->keepalive = AP_CONN_CLOSE;
705         p_conn->close++;
706     }
707     ap_xlate_proto_to_ascii(buf, strlen(buf));
708     e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
709     APR_BRIGADE_INSERT_TAIL(header_brigade, e);
710     if (conf->preserve_host == 0) {
711         if (uri->port_str && uri->port != DEFAULT_HTTP_PORT) {
712             buf = apr_pstrcat(p, "Host: ", uri->hostname, ":", uri->port_str,
713                               CRLF, NULL);
714         } else {
715             buf = apr_pstrcat(p, "Host: ", uri->hostname, CRLF, NULL);
716         }
717     }
718     else {
719         /* don't want to use r->hostname, as the incoming header might have a
720          * port attached
721          */
722         const char* hostname = apr_table_get(r->headers_in,"Host");
723         if (!hostname) {
724             hostname =  r->server->server_hostname;
725             ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
726                           "proxy: no HTTP 0.9 request (with no host line) "
727                           "on incoming request and preserve host set "
728                           "forcing hostname to be %s for uri %s",
729                           hostname,
730                           r->uri );
731         }
732         buf = apr_pstrcat(p, "Host: ", hostname, CRLF, NULL);
733     }
734     ap_xlate_proto_to_ascii(buf, strlen(buf));
735     e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
736     APR_BRIGADE_INSERT_TAIL(header_brigade, e);
737
738     /* handle Via */
739     if (conf->viaopt == via_block) {
740         /* Block all outgoing Via: headers */
741         apr_table_unset(r->headers_in, "Via");
742     } else if (conf->viaopt != via_off) {
743         const char *server_name = ap_get_server_name(r);
744         /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
745          * then the server name returned by ap_get_server_name() is the
746          * origin server name (which does make too much sense with Via: headers)
747          * so we use the proxy vhost's name instead.
748          */
749         if (server_name == r->hostname)
750             server_name = r->server->server_hostname;
751         /* Create a "Via:" request header entry and merge it */
752         /* Generate outgoing Via: header with/without server comment: */
753         apr_table_mergen(r->headers_in, "Via",
754                          (conf->viaopt == via_full)
755                          ? apr_psprintf(p, "%d.%d %s%s (%s)",
756                                         HTTP_VERSION_MAJOR(r->proto_num),
757                                         HTTP_VERSION_MINOR(r->proto_num),
758                                         server_name, server_portstr,
759                                         AP_SERVER_BASEVERSION)
760                          : apr_psprintf(p, "%d.%d %s%s",
761                                         HTTP_VERSION_MAJOR(r->proto_num),
762                                         HTTP_VERSION_MINOR(r->proto_num),
763                                         server_name, server_portstr)
764         );
765     }
766
767     /* X-Forwarded-*: handling
768      *
769      * XXX Privacy Note:
770      * -----------------
771      *
772      * These request headers are only really useful when the mod_proxy
773      * is used in a reverse proxy configuration, so that useful info
774      * about the client can be passed through the reverse proxy and on
775      * to the backend server, which may require the information to
776      * function properly.
777      *
778      * In a forward proxy situation, these options are a potential
779      * privacy violation, as information about clients behind the proxy
780      * are revealed to arbitrary servers out there on the internet.
781      *
782      * The HTTP/1.1 Via: header is designed for passing client
783      * information through proxies to a server, and should be used in
784      * a forward proxy configuation instead of X-Forwarded-*. See the
785      * ProxyVia option for details.
786      */
787
788     if (PROXYREQ_REVERSE == r->proxyreq) {
789         const char *buf;
790
791         /* Add X-Forwarded-For: so that the upstream has a chance to
792          * determine, where the original request came from.
793          */
794         apr_table_mergen(r->headers_in, "X-Forwarded-For",
795                          c->remote_ip);
796
797         /* Add X-Forwarded-Host: so that upstream knows what the
798          * original request hostname was.
799          */
800         if ((buf = apr_table_get(r->headers_in, "Host"))) {
801             apr_table_mergen(r->headers_in, "X-Forwarded-Host", buf);
802         }
803
804         /* Add X-Forwarded-Server: so that upstream knows what the
805          * name of this proxy server is (if there are more than one)
806          * XXX: This duplicates Via: - do we strictly need it?
807          */
808         apr_table_mergen(r->headers_in, "X-Forwarded-Server",
809                          r->server->server_hostname);
810     }
811
812     proxy_run_fixups(r);
813     /*
814      * Make a copy of the headers_in table before clearing the connection
815      * headers as we need the connection headers later in the http output
816      * filter to prepare the correct response headers.
817      *
818      * Note: We need to take r->pool for apr_table_copy as the key / value
819      * pairs in r->headers_in have been created out of r->pool and
820      * p might be (and actually is) a longer living pool.
821      * This would trigger the bad pool ancestry abort in apr_table_copy if
822      * apr is compiled with APR_POOL_DEBUG.
823      */
824     headers_in_copy = apr_table_copy(r->pool, r->headers_in);
825     ap_proxy_clear_connection(p, headers_in_copy);
826     /* send request headers */
827     headers_in_array = apr_table_elts(headers_in_copy);
828     headers_in = (const apr_table_entry_t *) headers_in_array->elts;
829     for (counter = 0; counter < headers_in_array->nelts; counter++) {
830         if (headers_in[counter].key == NULL
831              || headers_in[counter].val == NULL
832
833             /* Already sent */
834              || !strcasecmp(headers_in[counter].key, "Host")
835
836             /* Clear out hop-by-hop request headers not to send
837              * RFC2616 13.5.1 says we should strip these headers
838              */
839              || !strcasecmp(headers_in[counter].key, "Keep-Alive")
840              || !strcasecmp(headers_in[counter].key, "TE")
841              || !strcasecmp(headers_in[counter].key, "Trailer")
842              || !strcasecmp(headers_in[counter].key, "Upgrade")
843
844              ) {
845             continue;
846         }
847         /* Do we want to strip Proxy-Authorization ?
848          * If we haven't used it, then NO
849          * If we have used it then MAYBE: RFC2616 says we MAY propagate it.
850          * So let's make it configurable by env.
851          */
852         if (!strcasecmp(headers_in[counter].key,"Proxy-Authorization")) {
853             if (r->user != NULL) { /* we've authenticated */
854                 if (!apr_table_get(r->subprocess_env, "Proxy-Chain-Auth")) {
855                     continue;
856                 }
857             }
858         }
859
860
861         /* Skip Transfer-Encoding and Content-Length for now.
862          */
863         if (!strcasecmp(headers_in[counter].key, "Transfer-Encoding")) {
864             old_te_val = headers_in[counter].val;
865             continue;
866         }
867         if (!strcasecmp(headers_in[counter].key, "Content-Length")) {
868             old_cl_val = headers_in[counter].val;
869             continue;
870         }
871
872         /* for sub-requests, ignore freshness/expiry headers */
873         if (r->main) {
874             if (    !strcasecmp(headers_in[counter].key, "If-Match")
875                  || !strcasecmp(headers_in[counter].key, "If-Modified-Since")
876                  || !strcasecmp(headers_in[counter].key, "If-Range")
877                  || !strcasecmp(headers_in[counter].key, "If-Unmodified-Since")
878                  || !strcasecmp(headers_in[counter].key, "If-None-Match")) {
879                 continue;
880             }
881         }
882
883         buf = apr_pstrcat(p, headers_in[counter].key, ": ",
884                           headers_in[counter].val, CRLF,
885                           NULL);
886         ap_xlate_proto_to_ascii(buf, strlen(buf));
887         e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
888         APR_BRIGADE_INSERT_TAIL(header_brigade, e);
889     }
890
891     /* We have headers, let's figure out our request body... */
892     input_brigade = apr_brigade_create(p, bucket_alloc);
893
894     /* sub-requests never use keepalives, and mustn't pass request bodies.
895      * Because the new logic looks at input_brigade, we will self-terminate
896      * input_brigade and jump past all of the request body logic...
897      * Reading anything with ap_get_brigade is likely to consume the
898      * main request's body or read beyond EOS - which would be unplesant.
899      */
900     if (r->main) {
901         /* XXX: Why DON'T sub-requests use keepalives? */
902         p_conn->close++;
903         if (old_cl_val) {
904             old_cl_val = NULL;
905             apr_table_unset(r->headers_in, "Content-Length");
906         }
907         if (old_te_val) {
908             old_te_val = NULL;
909             apr_table_unset(r->headers_in, "Transfer-Encoding");
910         }
911         rb_method = RB_STREAM_CL;
912         e = apr_bucket_eos_create(input_brigade->bucket_alloc);
913         APR_BRIGADE_INSERT_TAIL(input_brigade, e);
914         goto skip_body;
915     }
916
917     /* WE only understand chunked.  Other modules might inject
918      * (and therefore, decode) other flavors but we don't know
919      * that the can and have done so unless they they remove
920      * their decoding from the headers_in T-E list.
921      * XXX: Make this extensible, but in doing so, presume the
922      * encoding has been done by the extensions' handler, and
923      * do not modify add_te_chunked's logic
924      */
925     if (old_te_val && strcmp(old_te_val, "chunked") != 0) {
926         ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
927                      "proxy: %s Transfer-Encoding is not supported",
928                      old_te_val);
929         return APR_EINVAL;
930     }
931
932     if (old_cl_val && old_te_val) {
933         ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_ENOTIMPL, r->server,
934                      "proxy: client %s (%s) requested Transfer-Encoding "
935                      "chunked body with Content-Length (C-L ignored)",
936                      c->remote_ip, c->remote_host ? c->remote_host: "");
937         apr_table_unset(r->headers_in, "Content-Length");
938         old_cl_val = NULL;
939         origin->keepalive = AP_CONN_CLOSE;
940         p_conn->close++;
941     }
942
943     /* Prefetch MAX_MEM_SPOOL bytes
944      *
945      * This helps us avoid any election of C-L v.s. T-E
946      * request bodies, since we are willing to keep in
947      * memory this much data, in any case.  This gives
948      * us an instant C-L election if the body is of some
949      * reasonable size.
950      */
951     temp_brigade = apr_brigade_create(p, bucket_alloc);
952     do {
953         status = ap_get_brigade(r->input_filters, temp_brigade,
954                                 AP_MODE_READBYTES, APR_BLOCK_READ,
955                                 MAX_MEM_SPOOL - bytes_read);
956         if (status != APR_SUCCESS) {
957             ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
958                          "proxy: prefetch request body failed to %pI (%s)"
959                          " from %s (%s)",
960                          p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
961                          c->remote_ip, c->remote_host ? c->remote_host: "");
962             return status;
963         }
964
965         apr_brigade_length(temp_brigade, 1, &bytes);
966         bytes_read += bytes;
967
968         /*
969          * Save temp_brigade in input_brigade. (At least) in the SSL case
970          * temp_brigade contains transient buckets whose data would get
971          * overwritten during the next call of ap_get_brigade in the loop.
972          * ap_save_brigade ensures these buckets to be set aside.
973          * Calling ap_save_brigade with NULL as filter is OK, because
974          * input_brigade already has been created and does not need to get
975          * created by ap_save_brigade.
976          */
977         status = ap_save_brigade(NULL, &input_brigade, &temp_brigade, p);
978         if (status != APR_SUCCESS) {
979             ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
980                          "proxy: processing prefetched request body failed"
981                          " to %pI (%s) from %s (%s)",
982                          p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
983                          c->remote_ip, c->remote_host ? c->remote_host: "");
984             return status;
985         }
986
987     /* Ensure we don't hit a wall where we have a buffer too small
988      * for ap_get_brigade's filters to fetch us another bucket,
989      * surrender once we hit 80 bytes less than MAX_MEM_SPOOL
990      * (an arbitrary value.)
991      */
992     } while ((bytes_read < MAX_MEM_SPOOL - 80)
993               && !APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade)));
994
995     /* Use chunked request body encoding or send a content-length body?
996      *
997      * Prefer C-L when:
998      *
999      *   We have no request body (handled by RB_STREAM_CL)
1000      *
1001      *   We have a request body length <= MAX_MEM_SPOOL
1002      *
1003      *   The administrator has setenv force-proxy-request-1.0
1004      *
1005      *   The client sent a C-L body, and the administrator has
1006      *   not setenv proxy-sendchunked or has set setenv proxy-sendcl
1007      *
1008      *   The client sent a T-E body, and the administrator has
1009      *   setenv proxy-sendcl, and not setenv proxy-sendchunked
1010      *
1011      * If both proxy-sendcl and proxy-sendchunked are set, the
1012      * behavior is the same as if neither were set, large bodies
1013      * that can't be read will be forwarded in their original
1014      * form of C-L, or T-E.
1015      *
1016      * To ensure maximum compatibility, setenv proxy-sendcl
1017      * To reduce server resource use,   setenv proxy-sendchunked
1018      *
1019      * Then address specific servers with conditional setenv
1020      * options to restore the default behavior where desireable.
1021      *
1022      * We have to compute content length by reading the entire request
1023      * body; if request body is not small, we'll spool the remaining
1024      * input to a temporary file.  Chunked is always preferable.
1025      *
1026      * We can only trust the client-provided C-L if the T-E header
1027      * is absent, and the filters are unchanged (the body won't
1028      * be resized by another content filter).
1029      */
1030     if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
1031         /* The whole thing fit, so our decision is trivial, use
1032          * the filtered bytes read from the client for the request
1033          * body Content-Length.
1034          *
1035          * If we expected no body, and read no body, do not set
1036          * the Content-Length.
1037          */
1038         if (old_cl_val || old_te_val || bytes_read) {
1039             old_cl_val = apr_off_t_toa(r->pool, bytes_read);
1040         }
1041         rb_method = RB_STREAM_CL;
1042     }
1043     else if (old_te_val) {
1044         if (force10
1045              || (apr_table_get(r->subprocess_env, "proxy-sendcl")
1046                   && !apr_table_get(r->subprocess_env, "proxy-sendchunks")
1047                   && !apr_table_get(r->subprocess_env, "proxy-sendchunked"))) {
1048             rb_method = RB_SPOOL_CL;
1049         }
1050         else {
1051             rb_method = RB_STREAM_CHUNKED;
1052         }
1053     }
1054     else if (old_cl_val) {
1055         if (r->input_filters == r->proto_input_filters) {
1056             rb_method = RB_STREAM_CL;
1057         }
1058         else if (!force10
1059                   && (apr_table_get(r->subprocess_env, "proxy-sendchunks")
1060                       || apr_table_get(r->subprocess_env, "proxy-sendchunked"))
1061                   && !apr_table_get(r->subprocess_env, "proxy-sendcl")) {
1062             rb_method = RB_STREAM_CHUNKED;
1063         }
1064         else {
1065             rb_method = RB_SPOOL_CL;
1066         }
1067     }
1068     else {
1069         /* This is an appropriate default; very efficient for no-body
1070          * requests, and has the behavior that it will not add any C-L
1071          * when the old_cl_val is NULL.
1072          */
1073         rb_method = RB_SPOOL_CL;
1074     }
1075
1076 /* Yes I hate gotos.  This is the subrequest shortcut */
1077 skip_body:
1078     /*
1079      * Handle Connection: header if we do HTTP/1.1 request:
1080      * If we plan to close the backend connection sent Connection: close
1081      * otherwise sent Connection: Keep-Alive.
1082      */
1083     if (!force10) {
1084         if (p_conn->close) {
1085             buf = apr_pstrdup(p, "Connection: close" CRLF);
1086         }
1087         else {
1088             buf = apr_pstrdup(p, "Connection: Keep-Alive" CRLF);
1089         }
1090         ap_xlate_proto_to_ascii(buf, strlen(buf));
1091         e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
1092         APR_BRIGADE_INSERT_TAIL(header_brigade, e);
1093     }
1094
1095     /* send the request body, if any. */
1096     switch(rb_method) {
1097     case RB_STREAM_CHUNKED:
1098         status = stream_reqbody_chunked(p, r, p_conn, origin, header_brigade,
1099                                         input_brigade);
1100         break;
1101     case RB_STREAM_CL:
1102         status = stream_reqbody_cl(p, r, p_conn, origin, header_brigade,
1103                                    input_brigade, old_cl_val);
1104         break;
1105     case RB_SPOOL_CL:
1106         status = spool_reqbody_cl(p, r, p_conn, origin, header_brigade,
1107                                   input_brigade, (old_cl_val != NULL)
1108                                               || (old_te_val != NULL)
1109                                               || (bytes_read > 0));
1110         break;
1111     default:
1112         /* shouldn't be possible */
1113         status = APR_EINVAL;
1114         break;
1115     }
1116
1117     if (status != APR_SUCCESS) {
1118         ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
1119                      "proxy: pass request body failed to %pI (%s)"
1120                      " from %s (%s)",
1121                      p_conn->addr,
1122                      p_conn->hostname ? p_conn->hostname: "",
1123                      c->remote_ip,
1124                      c->remote_host ? c->remote_host: "");
1125         return status;
1126     }
1127
1128     return APR_SUCCESS;
1129 }
1130
1131 static void process_proxy_header(request_rec *r, proxy_dir_conf *c,
1132                                  const char *key, const char *value)
1133 {
1134     static const char *date_hdrs[]
1135         = { "Date", "Expires", "Last-Modified", NULL };
1136     static const struct {
1137         const char *name;
1138         ap_proxy_header_reverse_map_fn func;
1139     } transform_hdrs[] = {
1140         { "Location", ap_proxy_location_reverse_map },
1141         { "Content-Location", ap_proxy_location_reverse_map },
1142         { "URI", ap_proxy_location_reverse_map },
1143         { "Destination", ap_proxy_location_reverse_map },
1144         { "Set-Cookie", ap_proxy_cookie_reverse_map },
1145         { NULL, NULL }
1146     };
1147     int i;
1148     for (i = 0; date_hdrs[i]; ++i) {
1149         if (!strcasecmp(date_hdrs[i], key)) {
1150             apr_table_add(r->headers_out, key,
1151                           ap_proxy_date_canon(r->pool, value));
1152             return;
1153         }
1154     }
1155     for (i = 0; transform_hdrs[i].name; ++i) {
1156         if (!strcasecmp(transform_hdrs[i].name, key)) {
1157             apr_table_add(r->headers_out, key,
1158                           (*transform_hdrs[i].func)(r, c, value));
1159             return;
1160        }
1161     }
1162     apr_table_add(r->headers_out, key, value);
1163     return;
1164 }
1165
1166 /*
1167  * Note: pread_len is the length of the response that we've  mistakenly
1168  * read (assuming that we don't consider that an  error via
1169  * ProxyBadHeader StartBody). This depends on buffer actually being
1170  * local storage to the calling code in order for pread_len to make
1171  * any sense at all, since we depend on buffer still containing
1172  * what was read by ap_getline() upon return.
1173  */
1174 static void ap_proxy_read_headers(request_rec *r, request_rec *rr,
1175                                   char *buffer, int size,
1176                                   conn_rec *c, int *pread_len)
1177 {
1178     int len;
1179     char *value, *end;
1180     char field[MAX_STRING_LEN];
1181     int saw_headers = 0;
1182     void *sconf = r->server->module_config;
1183     proxy_server_conf *psc;
1184     proxy_dir_conf *dconf;
1185
1186     dconf = ap_get_module_config(r->per_dir_config, &proxy_module);
1187     psc = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
1188
1189     r->headers_out = apr_table_make(r->pool, 20);
1190     *pread_len = 0;
1191
1192     /*
1193      * Read header lines until we get the empty separator line, a read error,
1194      * the connection closes (EOF), or we timeout.
1195      */
1196     while ((len = ap_getline(buffer, size, rr, 1)) > 0) {
1197
1198         if (!(value = strchr(buffer, ':'))) {     /* Find the colon separator */
1199
1200             /* We may encounter invalid headers, usually from buggy
1201              * MS IIS servers, so we need to determine just how to handle
1202              * them. We can either ignore them, assume that they mark the
1203              * start-of-body (eg: a missing CRLF) or (the default) mark
1204              * the headers as totally bogus and return a 500. The sole
1205              * exception is an extra "HTTP/1.0 200, OK" line sprinkled
1206              * in between the usual MIME headers, which is a favorite
1207              * IIS bug.
1208              */
1209              /* XXX: The mask check is buggy if we ever see an HTTP/1.10 */
1210
1211             if (!apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1212                 if (psc->badopt == bad_error) {
1213                     /* Nope, it wasn't even an extra HTTP header. Give up. */
1214                     r->headers_out = NULL;
1215                     return ;
1216                 }
1217                 else if (psc->badopt == bad_body) {
1218                     /* if we've already started loading headers_out, then
1219                      * return what we've accumulated so far, in the hopes
1220                      * that they are useful; also note that we likely pre-read
1221                      * the first line of the response.
1222                      */
1223                     if (saw_headers) {
1224                         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1225                          "proxy: Starting body due to bogus non-header in headers "
1226                          "returned by %s (%s)", r->uri, r->method);
1227                         *pread_len = len;
1228                         return ;
1229                     } else {
1230                          ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1231                          "proxy: No HTTP headers "
1232                          "returned by %s (%s)", r->uri, r->method);
1233                         return ;
1234                     }
1235                 }
1236             }
1237             /* this is the psc->badopt == bad_ignore case */
1238             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1239                          "proxy: Ignoring bogus HTTP header "
1240                          "returned by %s (%s)", r->uri, r->method);
1241             continue;
1242         }
1243
1244         *value = '\0';
1245         ++value;
1246         /* XXX: RFC2068 defines only SP and HT as whitespace, this test is
1247          * wrong... and so are many others probably.
1248          */
1249         while (apr_isspace(*value))
1250             ++value;            /* Skip to start of value   */
1251
1252         /* should strip trailing whitespace as well */
1253         for (end = &value[strlen(value)-1]; end > value && apr_isspace(*end); --
1254 end)
1255             *end = '\0';
1256
1257         /* make sure we add so as not to destroy duplicated headers
1258          * Modify headers requiring canonicalisation and/or affected
1259          * by ProxyPassReverse and family with process_proxy_header
1260          */
1261         process_proxy_header(r, dconf, buffer, value) ;
1262         saw_headers = 1;
1263
1264         /* the header was too long; at the least we should skip extra data */
1265         if (len >= size - 1) {
1266             while ((len = ap_getline(field, MAX_STRING_LEN, rr, 1))
1267                     >= MAX_STRING_LEN - 1) {
1268                 /* soak up the extra data */
1269             }
1270             if (len == 0) /* time to exit the larger loop as well */
1271                 break;
1272         }
1273     }
1274 }
1275
1276
1277
1278 static int addit_dammit(void *v, const char *key, const char *val)
1279 {
1280     apr_table_addn(v, key, val);
1281     return 1;
1282 }
1283
1284 static
1285 apr_status_t ap_proxygetline(apr_bucket_brigade *bb, char *s, int n, request_rec *r,
1286                              int fold, int *writen)
1287 {
1288     char *tmp_s = s;
1289     apr_status_t rv;
1290     apr_size_t len;
1291
1292     rv = ap_rgetline(&tmp_s, n, &len, r, fold, bb);
1293     apr_brigade_cleanup(bb);
1294
1295     if (rv == APR_SUCCESS) {
1296         *writen = (int) len;
1297     } else if (rv == APR_ENOSPC) {
1298         *writen = n;
1299     } else {
1300         *writen = -1;
1301     }
1302
1303     return rv;
1304 }
1305
1306 static
1307 apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r,
1308                                             proxy_conn_rec *backend,
1309                                             conn_rec *origin,
1310                                             proxy_server_conf *conf,
1311                                             char *server_portstr) {
1312     conn_rec *c = r->connection;
1313     char buffer[HUGE_STRING_LEN];
1314     const char *buf;
1315     char keepchar;
1316     request_rec *rp;
1317     apr_bucket *e;
1318     apr_bucket_brigade *bb, *tmp_bb;
1319     int len, backasswards;
1320     int interim_response; /* non-zero whilst interim 1xx responses
1321                            * are being read. */
1322     int pread_len = 0;
1323     apr_table_t *save_table;
1324     int backend_broke = 0;
1325     static const char *hop_by_hop_hdrs[] =
1326         {"Keep-Alive", "Proxy-Authenticate", "TE", "Trailer", "Upgrade", NULL};
1327     int i;
1328
1329     bb = apr_brigade_create(p, c->bucket_alloc);
1330
1331     /* Get response from the remote server, and pass it up the
1332      * filter chain
1333      */
1334
1335     rp = ap_proxy_make_fake_req(origin, r);
1336     /* In case anyone needs to know, this is a fake request that is really a
1337      * response.
1338      */
1339     rp->proxyreq = PROXYREQ_RESPONSE;
1340     tmp_bb = apr_brigade_create(p, c->bucket_alloc);
1341     do {
1342         apr_status_t rc;
1343
1344         apr_brigade_cleanup(bb);
1345
1346         rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1347         if (len == 0) {
1348             /* handle one potential stray CRLF */
1349             rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1350         }
1351         if (len <= 0) {
1352             ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
1353                           "proxy: error reading status line from remote "
1354                           "server %s", backend->hostname);
1355             return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1356                                  "Error reading from remote server");
1357         }
1358         /* XXX: Is this a real headers length send from remote? */
1359         backend->worker->s->read += len;
1360
1361         /* Is it an HTTP/1 response?
1362          * This is buggy if we ever see an HTTP/1.10
1363          */
1364         if (apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1365             int major, minor;
1366
1367             if (2 != sscanf(buffer, "HTTP/%u.%u", &major, &minor)) {
1368                 major = 1;
1369                 minor = 1;
1370             }
1371             /* If not an HTTP/1 message or
1372              * if the status line was > 8192 bytes
1373              */
1374             else if ((buffer[5] != '1') || (len >= sizeof(buffer)-1)) {
1375                 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1376                 apr_pstrcat(p, "Corrupt status line returned by remote "
1377                             "server: ", buffer, NULL));
1378             }
1379             backasswards = 0;
1380
1381             keepchar = buffer[12];
1382             buffer[12] = '\0';
1383             r->status = atoi(&buffer[9]);
1384
1385             if (keepchar != '\0') {
1386                 buffer[12] = keepchar;
1387             } else {
1388                 /* 2616 requires the space in Status-Line; the origin
1389                  * server may have sent one but ap_rgetline_core will
1390                  * have stripped it. */
1391                 buffer[12] = ' ';
1392                 buffer[13] = '\0';
1393             }
1394             r->status_line = apr_pstrdup(p, &buffer[9]);
1395
1396
1397             /* read the headers. */
1398             /* N.B. for HTTP/1.0 clients, we have to fold line-wrapped headers*/
1399             /* Also, take care with headers with multiple occurences. */
1400
1401             /* First, tuck away all already existing cookies */
1402             save_table = apr_table_make(r->pool, 2);
1403             apr_table_do(addit_dammit, save_table, r->headers_out,
1404                          "Set-Cookie", NULL);
1405
1406             /* shove the headers direct into r->headers_out */
1407             ap_proxy_read_headers(r, rp, buffer, sizeof(buffer), origin,
1408                                   &pread_len);
1409
1410             if (r->headers_out == NULL) {
1411                 ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
1412                              r->server, "proxy: bad HTTP/%d.%d header "
1413                              "returned by %s (%s)", major, minor, r->uri,
1414                              r->method);
1415                 backend->close += 1;
1416                 /*
1417                  * ap_send_error relies on a headers_out to be present. we
1418                  * are in a bad position here.. so force everything we send out
1419                  * to have nothing to do with the incoming packet
1420                  */
1421                 r->headers_out = apr_table_make(r->pool,1);
1422                 r->status = HTTP_BAD_GATEWAY;
1423                 r->status_line = "bad gateway";
1424                 return r->status;
1425             }
1426
1427             /* Now, add in the just read cookies */
1428             apr_table_do(addit_dammit, save_table, r->headers_out,
1429                          "Set-Cookie", NULL);
1430
1431             /* and now load 'em all in */
1432             if (!apr_is_empty_table(save_table)) {
1433                 apr_table_unset(r->headers_out, "Set-Cookie");
1434                 r->headers_out = apr_table_overlay(r->pool,
1435                                                    r->headers_out,
1436                                                    save_table);
1437             }
1438
1439             /* can't have both Content-Length and Transfer-Encoding */
1440             if (apr_table_get(r->headers_out, "Transfer-Encoding")
1441                     && apr_table_get(r->headers_out, "Content-Length")) {
1442                 /*
1443                  * 2616 section 4.4, point 3: "if both Transfer-Encoding
1444                  * and Content-Length are received, the latter MUST be
1445                  * ignored";
1446                  *
1447                  * To help mitigate HTTP Splitting, unset Content-Length
1448                  * and shut down the backend server connection
1449                  * XXX: We aught to treat such a response as uncachable
1450                  */
1451                 apr_table_unset(r->headers_out, "Content-Length");
1452                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1453                              "proxy: server %s returned Transfer-Encoding"
1454                              " and Content-Length", backend->hostname);
1455                 backend->close += 1;
1456             }
1457
1458             /* strip connection listed hop-by-hop headers from response */
1459             backend->close += ap_proxy_liststr(apr_table_get(r->headers_out,
1460                                                              "Connection"),
1461                                               "close");
1462             ap_proxy_clear_connection(p, r->headers_out);
1463             if ((buf = apr_table_get(r->headers_out, "Content-Type"))) {
1464                 ap_set_content_type(r, apr_pstrdup(p, buf));
1465             }
1466             ap_proxy_pre_http_request(origin,rp);
1467
1468             /* Clear hop-by-hop headers */
1469             for (i=0; hop_by_hop_hdrs[i]; ++i) {
1470                 apr_table_unset(r->headers_out, hop_by_hop_hdrs[i]);
1471             }
1472             /* Delete warnings with wrong date */
1473             r->headers_out = ap_proxy_clean_warnings(p, r->headers_out);
1474
1475             /* handle Via header in response */
1476             if (conf->viaopt != via_off && conf->viaopt != via_block) {
1477                 const char *server_name = ap_get_server_name(r);
1478                 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
1479                  * then the server name returned by ap_get_server_name() is the
1480                  * origin server name (which does make too much sense with Via: headers)
1481                  * so we use the proxy vhost's name instead.
1482                  */
1483                 if (server_name == r->hostname)
1484                     server_name = r->server->server_hostname;
1485                 /* create a "Via:" response header entry and merge it */
1486                 apr_table_addn(r->headers_out, "Via",
1487                                (conf->viaopt == via_full)
1488                                      ? apr_psprintf(p, "%d.%d %s%s (%s)",
1489                                            HTTP_VERSION_MAJOR(r->proto_num),
1490                                            HTTP_VERSION_MINOR(r->proto_num),
1491                                            server_name,
1492                                            server_portstr,
1493                                            AP_SERVER_BASEVERSION)
1494                                      : apr_psprintf(p, "%d.%d %s%s",
1495                                            HTTP_VERSION_MAJOR(r->proto_num),
1496                                            HTTP_VERSION_MINOR(r->proto_num),
1497                                            server_name,
1498                                            server_portstr)
1499                 );
1500             }
1501
1502             /* cancel keepalive if HTTP/1.0 or less */
1503             if ((major < 1) || (minor < 1)) {
1504                 backend->close += 1;
1505                 origin->keepalive = AP_CONN_CLOSE;
1506             }
1507         } else {
1508             /* an http/0.9 response */
1509             backasswards = 1;
1510             r->status = 200;
1511             r->status_line = "200 OK";
1512             backend->close += 1;
1513         }
1514
1515         interim_response = ap_is_HTTP_INFO(r->status);
1516         if (interim_response) {
1517             /* RFC2616 tells us to forward this.
1518              *
1519              * OTOH, an interim response here may mean the backend
1520              * is playing sillybuggers.  The Client didn't ask for
1521              * it within the defined HTTP/1.1 mechanisms, and if
1522              * it's an extension, it may also be unsupported by us.
1523              *
1524              * There's also the possibility that changing existing
1525              * behaviour here might break something.
1526              *
1527              * So let's make it configurable.
1528              */
1529             const char *policy = apr_table_get(r->subprocess_env,
1530                                                "proxy-interim-response");
1531             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, NULL,
1532                          "proxy: HTTP: received interim %d response",
1533                          r->status);
1534             if (!policy || !strcasecmp(policy, "RFC")) {
1535                 ap_send_interim_response(r);
1536             }
1537             /* FIXME: refine this to be able to specify per-response-status
1538              * policies and maybe also add option to bail out with 502
1539              */
1540             else if (strcasecmp(policy, "Suppress")) {
1541                 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, NULL,
1542                              "undefined proxy interim response policy");
1543             }
1544         }
1545         /* Moved the fixups of Date headers and those affected by
1546          * ProxyPassReverse/etc from here to ap_proxy_read_headers
1547          */
1548
1549         if ((r->status == 401) && (conf->error_override)) {
1550             const char *buf;
1551             const char *wa = "WWW-Authenticate";
1552             if ((buf = apr_table_get(r->headers_out, wa))) {
1553                 apr_table_set(r->err_headers_out, wa, buf);
1554             } else {
1555                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1556                              "proxy: origin server sent 401 without WWW-Authenticate header");
1557             }
1558         }
1559
1560         r->sent_bodyct = 1;
1561         /*
1562          * Is it an HTTP/0.9 response or did we maybe preread the 1st line of
1563          * the response? If so, load the extra data. These are 2 mutually
1564          * exclusive possibilities, that just happen to require very
1565          * similar behavior.
1566          */
1567         if (backasswards || pread_len) {
1568             apr_ssize_t cntr = (apr_ssize_t)pread_len;
1569             if (backasswards) {
1570                 /*@@@FIXME:
1571                  * At this point in response processing of a 0.9 response,
1572                  * we don't know yet whether data is binary or not.
1573                  * mod_charset_lite will get control later on, so it cannot
1574                  * decide on the conversion of this buffer full of data.
1575                  * However, chances are that we are not really talking to an
1576                  * HTTP/0.9 server, but to some different protocol, therefore
1577                  * the best guess IMHO is to always treat the buffer as "text/x":
1578                  */
1579                 ap_xlate_proto_to_ascii(buffer, len);
1580                 cntr = (apr_ssize_t)len;
1581             }
1582             e = apr_bucket_heap_create(buffer, cntr, NULL, c->bucket_alloc);
1583             APR_BRIGADE_INSERT_TAIL(bb, e);
1584         }
1585
1586         /* send body - but only if a body is expected */
1587         if ((!r->header_only) &&                   /* not HEAD request */
1588             !interim_response &&                   /* not any 1xx response */
1589             (r->status != HTTP_NO_CONTENT) &&      /* not 204 */
1590             (r->status != HTTP_NOT_MODIFIED)) {    /* not 304 */
1591
1592             /* We need to copy the output headers and treat them as input
1593              * headers as well.  BUT, we need to do this before we remove
1594              * TE, so that they are preserved accordingly for
1595              * ap_http_filter to know where to end.
1596              */
1597             rp->headers_in = apr_table_copy(r->pool, r->headers_out);
1598
1599             apr_table_unset(r->headers_out,"Transfer-Encoding");
1600
1601             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1602                          "proxy: start body send");
1603
1604             /*
1605              * if we are overriding the errors, we can't put the content
1606              * of the page into the brigade
1607              */
1608             if (!conf->error_override || !ap_is_HTTP_ERROR(r->status)) {
1609                 /* read the body, pass it to the output filters */
1610                 apr_read_type_e mode = APR_NONBLOCK_READ;
1611                 int finish = FALSE;
1612
1613                 do {
1614                     apr_off_t readbytes;
1615                     apr_status_t rv;
1616
1617                     rv = ap_get_brigade(rp->input_filters, bb,
1618                                         AP_MODE_READBYTES, mode,
1619                                         conf->io_buffer_size);
1620
1621                     /* ap_get_brigade will return success with an empty brigade
1622                      * for a non-blocking read which would block: */
1623                     if (APR_STATUS_IS_EAGAIN(rv)
1624                         || (rv == APR_SUCCESS && APR_BRIGADE_EMPTY(bb))) {
1625                         /* flush to the client and switch to blocking mode */
1626                         e = apr_bucket_flush_create(c->bucket_alloc);
1627                         APR_BRIGADE_INSERT_TAIL(bb, e);
1628                         if (ap_pass_brigade(r->output_filters, bb)
1629                             || c->aborted) {
1630                             backend->close = 1;
1631                             break;
1632                         }
1633                         apr_brigade_cleanup(bb);
1634                         mode = APR_BLOCK_READ;
1635                         continue;
1636                     }
1637                     else if (rv == APR_EOF) {
1638                         break;
1639                     }
1640                     else if (rv != APR_SUCCESS) {
1641                         /* In this case, we are in real trouble because
1642                          * our backend bailed on us. Pass along a 502 error
1643                          * error bucket
1644                          */
1645                         ap_log_cerror(APLOG_MARK, APLOG_ERR, rv, c,
1646                                       "proxy: error reading response");
1647                         ap_proxy_backend_broke(r, bb);
1648                         ap_pass_brigade(r->output_filters, bb);
1649                         backend_broke = 1;
1650                         backend->close = 1;
1651                         break;
1652                     }
1653                     /* next time try a non-blocking read */
1654                     mode = APR_NONBLOCK_READ;
1655
1656                     apr_brigade_length(bb, 0, &readbytes);
1657                     backend->worker->s->read += readbytes;
1658 #if DEBUGGING
1659                     {
1660                     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
1661                                  r->server, "proxy (PID %d): readbytes: %#x",
1662                                  getpid(), readbytes);
1663                     }
1664 #endif
1665                     /* sanity check */
1666                     if (APR_BRIGADE_EMPTY(bb)) {
1667                         apr_brigade_cleanup(bb);
1668                         break;
1669                     }
1670
1671                     /* found the last brigade? */
1672                     if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
1673                         /* signal that we must leave */
1674                         finish = TRUE;
1675                     }
1676
1677                     /* try send what we read */
1678                     if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1679                         || c->aborted) {
1680                         /* Ack! Phbtt! Die! User aborted! */
1681                         backend->close = 1;  /* this causes socket close below */
1682                         finish = TRUE;
1683                     }
1684
1685                     /* make sure we always clean up after ourselves */
1686                     apr_brigade_cleanup(bb);
1687
1688                 } while (!finish);
1689             }
1690             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1691                          "proxy: end body send");
1692         }
1693         else if (!interim_response) {
1694             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1695                          "proxy: header only");
1696
1697             /* Pass EOS bucket down the filter chain. */
1698             e = apr_bucket_eos_create(c->bucket_alloc);
1699             APR_BRIGADE_INSERT_TAIL(bb, e);
1700             if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1701                 || c->aborted) {
1702                 /* Ack! Phbtt! Die! User aborted! */
1703                 backend->close = 1;  /* this causes socket close below */
1704             }
1705
1706             apr_brigade_cleanup(bb);
1707         }
1708     } while (interim_response);
1709
1710     /* If our connection with the client is to be aborted, return DONE. */
1711     if (c->aborted || backend_broke) {
1712         return DONE;
1713     }
1714
1715     if (conf->error_override) {
1716         /* the code above this checks for 'OK' which is what the hook expects */
1717         if (!ap_is_HTTP_ERROR(r->status))
1718             return OK;
1719         else {
1720             /* clear r->status for override error, otherwise ErrorDocument
1721              * thinks that this is a recursive error, and doesn't find the
1722              * custom error page
1723              */
1724             int status = r->status;
1725             r->status = HTTP_OK;
1726             /* Discard body, if one is expected */
1727             if (!r->header_only && /* not HEAD request */
1728                 (status != HTTP_NO_CONTENT) && /* not 204 */
1729                 (status != HTTP_NOT_MODIFIED)) { /* not 304 */
1730                ap_discard_request_body(rp);
1731            }
1732             return status;
1733         }
1734     } else
1735         return OK;
1736 }
1737
1738 static
1739 apr_status_t ap_proxy_http_cleanup(const char *scheme, request_rec *r,
1740                                    proxy_conn_rec *backend)
1741 {
1742     ap_proxy_release_connection(scheme, backend, r->server);
1743     return OK;
1744 }
1745
1746 /*
1747  * This handles http:// URLs, and other URLs using a remote proxy over http
1748  * If proxyhost is NULL, then contact the server directly, otherwise
1749  * go via the proxy.
1750  * Note that if a proxy is used, then URLs other than http: can be accessed,
1751  * also, if we have trouble which is clearly specific to the proxy, then
1752  * we return DECLINED so that we can try another proxy. (Or the direct
1753  * route.)
1754  */
1755 static int proxy_http_handler(request_rec *r, proxy_worker *worker,
1756                               proxy_server_conf *conf,
1757                               char *url, const char *proxyname,
1758                               apr_port_t proxyport)
1759 {
1760     int status;
1761     char server_portstr[32];
1762     char *scheme;
1763     const char *proxy_function;
1764     const char *u;
1765     proxy_conn_rec *backend = NULL;
1766     int is_ssl = 0;
1767
1768     /* Note: Memory pool allocation.
1769      * A downstream keepalive connection is always connected to the existence
1770      * (or not) of an upstream keepalive connection. If this is not done then
1771      * load balancing against multiple backend servers breaks (one backend
1772      * server ends up taking 100% of the load), and the risk is run of
1773      * downstream keepalive connections being kept open unnecessarily. This
1774      * keeps webservers busy and ties up resources.
1775      *
1776      * As a result, we allocate all sockets out of the upstream connection
1777      * pool, and when we want to reuse a socket, we check first whether the
1778      * connection ID of the current upstream connection is the same as that
1779      * of the connection when the socket was opened.
1780      */
1781     apr_pool_t *p = r->connection->pool;
1782     conn_rec *c = r->connection;
1783     apr_uri_t *uri = apr_palloc(r->connection->pool, sizeof(*uri));
1784
1785     /* find the scheme */
1786     u = strchr(url, ':');
1787     if (u == NULL || u[1] != '/' || u[2] != '/' || u[3] == '\0')
1788        return DECLINED;
1789     if ((u - url) > 14)
1790         return HTTP_BAD_REQUEST;
1791     scheme = apr_pstrndup(c->pool, url, u - url);
1792     /* scheme is lowercase */
1793     ap_str_tolower(scheme);
1794     /* is it for us? */
1795     if (strcmp(scheme, "https") == 0) {
1796         if (!ap_proxy_ssl_enable(NULL)) {
1797             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1798                          "proxy: HTTPS: declining URL %s"
1799                          " (mod_ssl not configured?)", url);
1800             return DECLINED;
1801         }
1802         is_ssl = 1;
1803         proxy_function = "HTTPS";
1804     }
1805     else if (!(strcmp(scheme, "http") == 0 || (strcmp(scheme, "ftp") == 0 && proxyname))) {
1806         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1807                      "proxy: HTTP: declining URL %s", url);
1808         return DECLINED; /* only interested in HTTP, or FTP via proxy */
1809     }
1810     else {
1811         if (*scheme == 'h')
1812             proxy_function = "HTTP";
1813         else
1814             proxy_function = "FTP";
1815     }
1816     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1817              "proxy: HTTP: serving URL %s", url);
1818
1819
1820     /* create space for state information */
1821     if ((status = ap_proxy_acquire_connection(proxy_function, &backend,
1822                                               worker, r->server)) != OK)
1823         goto cleanup;
1824
1825
1826     backend->is_ssl = is_ssl;
1827     /*
1828      * TODO: Currently we cannot handle persistent SSL backend connections,
1829      * because we recreate backend->connection for each request and thus
1830      * try to initialize an already existing SSL connection. This does
1831      * not work.
1832      */
1833     if (is_ssl)
1834         backend->close = 1;
1835
1836     /* Step One: Determine Who To Connect To */
1837     if ((status = ap_proxy_determine_connection(p, r, conf, worker, backend,
1838                                                 uri, &url, proxyname,
1839                                                 proxyport, server_portstr,
1840                                                 sizeof(server_portstr))) != OK)
1841         goto cleanup;
1842
1843     /* Step Two: Make the Connection */
1844     if (ap_proxy_connect_backend(proxy_function, backend, worker, r->server)) {
1845         if (r->proxyreq == PROXYREQ_PROXY)
1846             status = HTTP_NOT_FOUND;
1847         else
1848             status = HTTP_SERVICE_UNAVAILABLE;
1849         goto cleanup;
1850     }
1851
1852     /* Step Three: Create conn_rec */
1853     if (!backend->connection) {
1854         if ((status = ap_proxy_connection_create(proxy_function, backend,
1855                                                  c, r->server)) != OK)
1856             goto cleanup;
1857     }
1858
1859     /* Step Four: Send the Request */
1860     if ((status = ap_proxy_http_request(p, r, backend, backend->connection,
1861                                         conf, uri, url, server_portstr)) != OK)
1862         goto cleanup;
1863
1864     /* Step Five: Receive the Response */
1865     if ((status = ap_proxy_http_process_response(p, r, backend,
1866                                                  backend->connection,
1867                                                  conf, server_portstr)) != OK)
1868         goto cleanup;
1869
1870     /* Step Six: Clean Up */
1871
1872 cleanup:
1873     if (backend) {
1874         if (status != OK)
1875             backend->close = 1;
1876         ap_proxy_http_cleanup(proxy_function, r, backend);
1877     }
1878     return status;
1879 }
1880 static apr_status_t warn_rx_free(void *p)
1881 {
1882     ap_pregfree((apr_pool_t*)p, warn_rx);
1883     return APR_SUCCESS;
1884 }
1885 static void ap_proxy_http_register_hook(apr_pool_t *p)
1886 {
1887     proxy_hook_scheme_handler(proxy_http_handler, NULL, NULL, APR_HOOK_FIRST);
1888     proxy_hook_canon_handler(proxy_http_canon, NULL, NULL, APR_HOOK_FIRST);
1889     warn_rx = ap_pregcomp(p, "[0-9]{3}[ \t]+[^ \t]+[ \t]+\"[^\"]*\"([ \t]+\"([^\"]+)\")?", 0);
1890     apr_pool_cleanup_register(p, p, warn_rx_free, apr_pool_cleanup_null);
1891 }
1892
1893 module AP_MODULE_DECLARE_DATA proxy_http_module = {
1894     STANDARD20_MODULE_STUFF,
1895     NULL,              /* create per-directory config structure */
1896     NULL,              /* merge per-directory config structures */
1897     NULL,              /* create per-server config structure */
1898     NULL,              /* merge per-server config structures */
1899     NULL,              /* command apr_table_t */
1900     ap_proxy_http_register_hook/* register hooks */
1901 };
1902