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