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