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