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