]> granicus.if.org Git - apache/blob - modules/proxy/mod_proxy_http.c
Use the new APLOG_USE_MODULE/AP_DECLARE_MODULE macros everywhere to take
[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     proxy_dir_conf *dconf;
697
698     dconf = ap_get_module_config(r->per_dir_config, &proxy_module);
699     header_brigade = apr_brigade_create(p, origin->bucket_alloc);
700
701     /*
702      * Send the HTTP/1.1 request to the remote server
703      */
704
705     if (apr_table_get(r->subprocess_env, "force-proxy-request-1.0")) {
706         /*
707          * According to RFC 2616 8.2.3 we are not allowed to forward an
708          * Expect: 100-continue to an HTTP/1.0 server. Instead we MUST return
709          * a HTTP_EXPECTATION_FAILED
710          */
711         if (r->expecting_100) {
712             return HTTP_EXPECTATION_FAILED;
713         }
714         buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.0" CRLF, NULL);
715         force10 = 1;
716         p_conn->close++;
717     } else {
718         buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.1" CRLF, NULL);
719         force10 = 0;
720     }
721     if (apr_table_get(r->subprocess_env, "proxy-nokeepalive")) {
722         origin->keepalive = AP_CONN_CLOSE;
723         p_conn->close++;
724     }
725     ap_xlate_proto_to_ascii(buf, strlen(buf));
726     e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
727     APR_BRIGADE_INSERT_TAIL(header_brigade, e);
728     if (dconf->preserve_host == 0) {
729         if (ap_strchr_c(uri->hostname, ':')) { /* if literal IPv6 address */
730             if (uri->port_str && uri->port != DEFAULT_HTTP_PORT) {
731                 buf = apr_pstrcat(p, "Host: [", uri->hostname, "]:", 
732                                   uri->port_str, CRLF, NULL);
733             } else {
734                 buf = apr_pstrcat(p, "Host: [", uri->hostname, "]", CRLF, NULL);
735             }
736         } else {
737             if (uri->port_str && uri->port != DEFAULT_HTTP_PORT) {
738                 buf = apr_pstrcat(p, "Host: ", uri->hostname, ":", 
739                                   uri->port_str, CRLF, NULL);
740             } else {
741                 buf = apr_pstrcat(p, "Host: ", uri->hostname, CRLF, NULL);
742             }
743         }
744     }
745     else {
746         /* don't want to use r->hostname, as the incoming header might have a
747          * port attached
748          */
749         const char* hostname = apr_table_get(r->headers_in,"Host");
750         if (!hostname) {
751             hostname =  r->server->server_hostname;
752             ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
753                           "proxy: no HTTP 0.9 request (with no host line) "
754                           "on incoming request and preserve host set "
755                           "forcing hostname to be %s for uri %s",
756                           hostname,
757                           r->uri );
758         }
759         buf = apr_pstrcat(p, "Host: ", hostname, CRLF, NULL);
760     }
761     ap_xlate_proto_to_ascii(buf, strlen(buf));
762     e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
763     APR_BRIGADE_INSERT_TAIL(header_brigade, e);
764
765     /* handle Via */
766     if (conf->viaopt == via_block) {
767         /* Block all outgoing Via: headers */
768         apr_table_unset(r->headers_in, "Via");
769     } else if (conf->viaopt != via_off) {
770         const char *server_name = ap_get_server_name(r);
771         /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
772          * then the server name returned by ap_get_server_name() is the
773          * origin server name (which does make too much sense with Via: headers)
774          * so we use the proxy vhost's name instead.
775          */
776         if (server_name == r->hostname)
777             server_name = r->server->server_hostname;
778         /* Create a "Via:" request header entry and merge it */
779         /* Generate outgoing Via: header with/without server comment: */
780         apr_table_mergen(r->headers_in, "Via",
781                          (conf->viaopt == via_full)
782                          ? apr_psprintf(p, "%d.%d %s%s (%s)",
783                                         HTTP_VERSION_MAJOR(r->proto_num),
784                                         HTTP_VERSION_MINOR(r->proto_num),
785                                         server_name, server_portstr,
786                                         AP_SERVER_BASEVERSION)
787                          : apr_psprintf(p, "%d.%d %s%s",
788                                         HTTP_VERSION_MAJOR(r->proto_num),
789                                         HTTP_VERSION_MINOR(r->proto_num),
790                                         server_name, server_portstr)
791         );
792     }
793
794     /* X-Forwarded-*: handling
795      *
796      * XXX Privacy Note:
797      * -----------------
798      *
799      * These request headers are only really useful when the mod_proxy
800      * is used in a reverse proxy configuration, so that useful info
801      * about the client can be passed through the reverse proxy and on
802      * to the backend server, which may require the information to
803      * function properly.
804      *
805      * In a forward proxy situation, these options are a potential
806      * privacy violation, as information about clients behind the proxy
807      * are revealed to arbitrary servers out there on the internet.
808      *
809      * The HTTP/1.1 Via: header is designed for passing client
810      * information through proxies to a server, and should be used in
811      * a forward proxy configuation instead of X-Forwarded-*. See the
812      * ProxyVia option for details.
813      */
814
815     if (PROXYREQ_REVERSE == r->proxyreq) {
816         const char *buf;
817
818         /* Add X-Forwarded-For: so that the upstream has a chance to
819          * determine, where the original request came from.
820          */
821         apr_table_mergen(r->headers_in, "X-Forwarded-For",
822                          c->remote_ip);
823
824         /* Add X-Forwarded-Host: so that upstream knows what the
825          * original request hostname was.
826          */
827         if ((buf = apr_table_get(r->headers_in, "Host"))) {
828             apr_table_mergen(r->headers_in, "X-Forwarded-Host", buf);
829         }
830
831         /* Add X-Forwarded-Server: so that upstream knows what the
832          * name of this proxy server is (if there are more than one)
833          * XXX: This duplicates Via: - do we strictly need it?
834          */
835         apr_table_mergen(r->headers_in, "X-Forwarded-Server",
836                          r->server->server_hostname);
837     }
838
839     proxy_run_fixups(r);
840     /*
841      * Make a copy of the headers_in table before clearing the connection
842      * headers as we need the connection headers later in the http output
843      * filter to prepare the correct response headers.
844      *
845      * Note: We need to take r->pool for apr_table_copy as the key / value
846      * pairs in r->headers_in have been created out of r->pool and
847      * p might be (and actually is) a longer living pool.
848      * This would trigger the bad pool ancestry abort in apr_table_copy if
849      * apr is compiled with APR_POOL_DEBUG.
850      */
851     headers_in_copy = apr_table_copy(r->pool, r->headers_in);
852     ap_proxy_clear_connection(p, headers_in_copy);
853     /* send request headers */
854     headers_in_array = apr_table_elts(headers_in_copy);
855     headers_in = (const apr_table_entry_t *) headers_in_array->elts;
856     for (counter = 0; counter < headers_in_array->nelts; counter++) {
857         if (headers_in[counter].key == NULL
858              || headers_in[counter].val == NULL
859
860             /* Already sent */
861              || !strcasecmp(headers_in[counter].key, "Host")
862
863             /* Clear out hop-by-hop request headers not to send
864              * RFC2616 13.5.1 says we should strip these headers
865              */
866              || !strcasecmp(headers_in[counter].key, "Keep-Alive")
867              || !strcasecmp(headers_in[counter].key, "TE")
868              || !strcasecmp(headers_in[counter].key, "Trailer")
869              || !strcasecmp(headers_in[counter].key, "Upgrade")
870
871              ) {
872             continue;
873         }
874         /* Do we want to strip Proxy-Authorization ?
875          * If we haven't used it, then NO
876          * If we have used it then MAYBE: RFC2616 says we MAY propagate it.
877          * So let's make it configurable by env.
878          */
879         if (!strcasecmp(headers_in[counter].key,"Proxy-Authorization")) {
880             if (r->user != NULL) { /* we've authenticated */
881                 if (!apr_table_get(r->subprocess_env, "Proxy-Chain-Auth")) {
882                     continue;
883                 }
884             }
885         }
886
887
888         /* Skip Transfer-Encoding and Content-Length for now.
889          */
890         if (!strcasecmp(headers_in[counter].key, "Transfer-Encoding")) {
891             old_te_val = headers_in[counter].val;
892             continue;
893         }
894         if (!strcasecmp(headers_in[counter].key, "Content-Length")) {
895             old_cl_val = headers_in[counter].val;
896             continue;
897         }
898
899         /* for sub-requests, ignore freshness/expiry headers */
900         if (r->main) {
901             if (    !strcasecmp(headers_in[counter].key, "If-Match")
902                  || !strcasecmp(headers_in[counter].key, "If-Modified-Since")
903                  || !strcasecmp(headers_in[counter].key, "If-Range")
904                  || !strcasecmp(headers_in[counter].key, "If-Unmodified-Since")
905                  || !strcasecmp(headers_in[counter].key, "If-None-Match")) {
906                 continue;
907             }
908         }
909
910         buf = apr_pstrcat(p, headers_in[counter].key, ": ",
911                           headers_in[counter].val, CRLF,
912                           NULL);
913         ap_xlate_proto_to_ascii(buf, strlen(buf));
914         e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
915         APR_BRIGADE_INSERT_TAIL(header_brigade, e);
916     }
917
918     /* We have headers, let's figure out our request body... */
919     input_brigade = apr_brigade_create(p, bucket_alloc);
920
921     /* sub-requests never use keepalives, and mustn't pass request bodies.
922      * Because the new logic looks at input_brigade, we will self-terminate
923      * input_brigade and jump past all of the request body logic...
924      * Reading anything with ap_get_brigade is likely to consume the
925      * main request's body or read beyond EOS - which would be unplesant.
926      * 
927      * An exception: when a kept_body is present, then subrequest CAN use
928      * pass request bodies, and we DONT skip the body.
929      */
930     if (!r->kept_body && r->main) {
931         /* XXX: Why DON'T sub-requests use keepalives? */
932         p_conn->close++;
933         if (old_cl_val) {
934             old_cl_val = NULL;
935             apr_table_unset(r->headers_in, "Content-Length");
936         }
937         if (old_te_val) {
938             old_te_val = NULL;
939             apr_table_unset(r->headers_in, "Transfer-Encoding");
940         }
941         rb_method = RB_STREAM_CL;
942         e = apr_bucket_eos_create(input_brigade->bucket_alloc);
943         APR_BRIGADE_INSERT_TAIL(input_brigade, e);
944         goto skip_body;
945     }
946
947     /* WE only understand chunked.  Other modules might inject
948      * (and therefore, decode) other flavors but we don't know
949      * that the can and have done so unless they they remove
950      * their decoding from the headers_in T-E list.
951      * XXX: Make this extensible, but in doing so, presume the
952      * encoding has been done by the extensions' handler, and
953      * do not modify add_te_chunked's logic
954      */
955     if (old_te_val && strcasecmp(old_te_val, "chunked") != 0) {
956         ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
957                      "proxy: %s Transfer-Encoding is not supported",
958                      old_te_val);
959         return HTTP_INTERNAL_SERVER_ERROR;
960     }
961
962     if (old_cl_val && old_te_val) {
963         ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_ENOTIMPL, r->server,
964                      "proxy: client %s (%s) requested Transfer-Encoding "
965                      "chunked body with Content-Length (C-L ignored)",
966                      c->remote_ip, c->remote_host ? c->remote_host: "");
967         apr_table_unset(r->headers_in, "Content-Length");
968         old_cl_val = NULL;
969         origin->keepalive = AP_CONN_CLOSE;
970         p_conn->close++;
971     }
972
973     /* Prefetch MAX_MEM_SPOOL bytes
974      *
975      * This helps us avoid any election of C-L v.s. T-E
976      * request bodies, since we are willing to keep in
977      * memory this much data, in any case.  This gives
978      * us an instant C-L election if the body is of some
979      * reasonable size.
980      */
981     temp_brigade = apr_brigade_create(p, bucket_alloc);
982     do {
983         status = ap_get_brigade(r->input_filters, temp_brigade,
984                                 AP_MODE_READBYTES, APR_BLOCK_READ,
985                                 MAX_MEM_SPOOL - bytes_read);
986         if (status != APR_SUCCESS) {
987             ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
988                          "proxy: prefetch request body failed to %pI (%s)"
989                          " from %s (%s)",
990                          p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
991                          c->remote_ip, c->remote_host ? c->remote_host: "");
992             return HTTP_BAD_REQUEST;
993         }
994
995         apr_brigade_length(temp_brigade, 1, &bytes);
996         bytes_read += bytes;
997
998         /*
999          * Save temp_brigade in input_brigade. (At least) in the SSL case
1000          * temp_brigade contains transient buckets whose data would get
1001          * overwritten during the next call of ap_get_brigade in the loop.
1002          * ap_save_brigade ensures these buckets to be set aside.
1003          * Calling ap_save_brigade with NULL as filter is OK, because
1004          * input_brigade already has been created and does not need to get
1005          * created by ap_save_brigade.
1006          */
1007         status = ap_save_brigade(NULL, &input_brigade, &temp_brigade, p);
1008         if (status != APR_SUCCESS) {
1009             ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
1010                          "proxy: processing prefetched request body failed"
1011                          " to %pI (%s) from %s (%s)",
1012                          p_conn->addr, p_conn->hostname ? p_conn->hostname: "",
1013                          c->remote_ip, c->remote_host ? c->remote_host: "");
1014             return HTTP_INTERNAL_SERVER_ERROR;
1015         }
1016
1017     /* Ensure we don't hit a wall where we have a buffer too small
1018      * for ap_get_brigade's filters to fetch us another bucket,
1019      * surrender once we hit 80 bytes less than MAX_MEM_SPOOL
1020      * (an arbitrary value.)
1021      */
1022     } while ((bytes_read < MAX_MEM_SPOOL - 80)
1023               && !APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade)));
1024
1025     /* Use chunked request body encoding or send a content-length body?
1026      *
1027      * Prefer C-L when:
1028      *
1029      *   We have no request body (handled by RB_STREAM_CL)
1030      *
1031      *   We have a request body length <= MAX_MEM_SPOOL
1032      *
1033      *   The administrator has setenv force-proxy-request-1.0
1034      *
1035      *   The client sent a C-L body, and the administrator has
1036      *   not setenv proxy-sendchunked or has set setenv proxy-sendcl
1037      *
1038      *   The client sent a T-E body, and the administrator has
1039      *   setenv proxy-sendcl, and not setenv proxy-sendchunked
1040      *
1041      * If both proxy-sendcl and proxy-sendchunked are set, the
1042      * behavior is the same as if neither were set, large bodies
1043      * that can't be read will be forwarded in their original
1044      * form of C-L, or T-E.
1045      *
1046      * To ensure maximum compatibility, setenv proxy-sendcl
1047      * To reduce server resource use,   setenv proxy-sendchunked
1048      *
1049      * Then address specific servers with conditional setenv
1050      * options to restore the default behavior where desireable.
1051      *
1052      * We have to compute content length by reading the entire request
1053      * body; if request body is not small, we'll spool the remaining
1054      * input to a temporary file.  Chunked is always preferable.
1055      *
1056      * We can only trust the client-provided C-L if the T-E header
1057      * is absent, and the filters are unchanged (the body won't
1058      * be resized by another content filter).
1059      */
1060     if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
1061         /* The whole thing fit, so our decision is trivial, use
1062          * the filtered bytes read from the client for the request
1063          * body Content-Length.
1064          *
1065          * If we expected no body, and read no body, do not set
1066          * the Content-Length.
1067          */
1068         if (old_cl_val || old_te_val || bytes_read) {
1069             old_cl_val = apr_off_t_toa(r->pool, bytes_read);
1070         }
1071         rb_method = RB_STREAM_CL;
1072     }
1073     else if (old_te_val) {
1074         if (force10
1075              || (apr_table_get(r->subprocess_env, "proxy-sendcl")
1076                   && !apr_table_get(r->subprocess_env, "proxy-sendchunks")
1077                   && !apr_table_get(r->subprocess_env, "proxy-sendchunked"))) {
1078             rb_method = RB_SPOOL_CL;
1079         }
1080         else {
1081             rb_method = RB_STREAM_CHUNKED;
1082         }
1083     }
1084     else if (old_cl_val) {
1085         if (r->input_filters == r->proto_input_filters) {
1086             rb_method = RB_STREAM_CL;
1087         }
1088         else if (!force10
1089                   && (apr_table_get(r->subprocess_env, "proxy-sendchunks")
1090                       || apr_table_get(r->subprocess_env, "proxy-sendchunked"))
1091                   && !apr_table_get(r->subprocess_env, "proxy-sendcl")) {
1092             rb_method = RB_STREAM_CHUNKED;
1093         }
1094         else {
1095             rb_method = RB_SPOOL_CL;
1096         }
1097     }
1098     else {
1099         /* This is an appropriate default; very efficient for no-body
1100          * requests, and has the behavior that it will not add any C-L
1101          * when the old_cl_val is NULL.
1102          */
1103         rb_method = RB_SPOOL_CL;
1104     }
1105
1106 /* Yes I hate gotos.  This is the subrequest shortcut */
1107 skip_body:
1108     /*
1109      * Handle Connection: header if we do HTTP/1.1 request:
1110      * If we plan to close the backend connection sent Connection: close
1111      * otherwise sent Connection: Keep-Alive.
1112      */
1113     if (!force10) {
1114         if (p_conn->close) {
1115             buf = apr_pstrdup(p, "Connection: close" CRLF);
1116         }
1117         else {
1118             buf = apr_pstrdup(p, "Connection: Keep-Alive" CRLF);
1119         }
1120         ap_xlate_proto_to_ascii(buf, strlen(buf));
1121         e = apr_bucket_pool_create(buf, strlen(buf), p, c->bucket_alloc);
1122         APR_BRIGADE_INSERT_TAIL(header_brigade, e);
1123     }
1124
1125     /* send the request body, if any. */
1126     switch(rb_method) {
1127     case RB_STREAM_CHUNKED:
1128         rv = stream_reqbody_chunked(p, r, p_conn, origin, header_brigade,
1129                                         input_brigade);
1130         break;
1131     case RB_STREAM_CL:
1132         rv = stream_reqbody_cl(p, r, p_conn, origin, header_brigade,
1133                                    input_brigade, old_cl_val);
1134         break;
1135     case RB_SPOOL_CL:
1136         rv = spool_reqbody_cl(p, r, p_conn, origin, header_brigade,
1137                                   input_brigade, (old_cl_val != NULL)
1138                                               || (old_te_val != NULL)
1139                                               || (bytes_read > 0));
1140         break;
1141     default:
1142         /* shouldn't be possible */
1143         rv = HTTP_INTERNAL_SERVER_ERROR ;
1144         break;
1145     }
1146
1147     if (rv != OK) {
1148         /* apr_status_t value has been logged in lower level method */
1149         ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
1150                      "proxy: pass request body failed to %pI (%s)"
1151                      " from %s (%s)",
1152                      p_conn->addr,
1153                      p_conn->hostname ? p_conn->hostname: "",
1154                      c->remote_ip,
1155                      c->remote_host ? c->remote_host: "");
1156         return rv;
1157     }
1158
1159     return OK;
1160 }
1161
1162 static void process_proxy_header(request_rec *r, proxy_dir_conf *c,
1163                                  const char *key, const char *value)
1164 {
1165     static const char *date_hdrs[]
1166         = { "Date", "Expires", "Last-Modified", NULL };
1167     static const struct {
1168         const char *name;
1169         ap_proxy_header_reverse_map_fn func;
1170     } transform_hdrs[] = {
1171         { "Location", ap_proxy_location_reverse_map },
1172         { "Content-Location", ap_proxy_location_reverse_map },
1173         { "URI", ap_proxy_location_reverse_map },
1174         { "Destination", ap_proxy_location_reverse_map },
1175         { "Set-Cookie", ap_proxy_cookie_reverse_map },
1176         { NULL, NULL }
1177     };
1178     int i;
1179     for (i = 0; date_hdrs[i]; ++i) {
1180         if (!strcasecmp(date_hdrs[i], key)) {
1181             apr_table_add(r->headers_out, key,
1182                           ap_proxy_date_canon(r->pool, value));
1183             return;
1184         }
1185     }
1186     for (i = 0; transform_hdrs[i].name; ++i) {
1187         if (!strcasecmp(transform_hdrs[i].name, key)) {
1188             apr_table_add(r->headers_out, key,
1189                           (*transform_hdrs[i].func)(r, c, value));
1190             return;
1191        }
1192     }
1193     apr_table_add(r->headers_out, key, value);
1194     return;
1195 }
1196
1197 /*
1198  * Note: pread_len is the length of the response that we've  mistakenly
1199  * read (assuming that we don't consider that an  error via
1200  * ProxyBadHeader StartBody). This depends on buffer actually being
1201  * local storage to the calling code in order for pread_len to make
1202  * any sense at all, since we depend on buffer still containing
1203  * what was read by ap_getline() upon return.
1204  */
1205 static void ap_proxy_read_headers(request_rec *r, request_rec *rr,
1206                                   char *buffer, int size,
1207                                   conn_rec *c, int *pread_len)
1208 {
1209     int len;
1210     char *value, *end;
1211     char field[MAX_STRING_LEN];
1212     int saw_headers = 0;
1213     void *sconf = r->server->module_config;
1214     proxy_server_conf *psc;
1215     proxy_dir_conf *dconf;
1216
1217     dconf = ap_get_module_config(r->per_dir_config, &proxy_module);
1218     psc = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module);
1219
1220     r->headers_out = apr_table_make(r->pool, 20);
1221     *pread_len = 0;
1222
1223     /*
1224      * Read header lines until we get the empty separator line, a read error,
1225      * the connection closes (EOF), or we timeout.
1226      */
1227     while ((len = ap_getline(buffer, size, rr, 1)) > 0) {
1228
1229         if (!(value = strchr(buffer, ':'))) {     /* Find the colon separator */
1230
1231             /* We may encounter invalid headers, usually from buggy
1232              * MS IIS servers, so we need to determine just how to handle
1233              * them. We can either ignore them, assume that they mark the
1234              * start-of-body (eg: a missing CRLF) or (the default) mark
1235              * the headers as totally bogus and return a 500. The sole
1236              * exception is an extra "HTTP/1.0 200, OK" line sprinkled
1237              * in between the usual MIME headers, which is a favorite
1238              * IIS bug.
1239              */
1240              /* XXX: The mask check is buggy if we ever see an HTTP/1.10 */
1241
1242             if (!apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1243                 if (psc->badopt == bad_error) {
1244                     /* Nope, it wasn't even an extra HTTP header. Give up. */
1245                     r->headers_out = NULL;
1246                     return ;
1247                 }
1248                 else if (psc->badopt == bad_body) {
1249                     /* if we've already started loading headers_out, then
1250                      * return what we've accumulated so far, in the hopes
1251                      * that they are useful; also note that we likely pre-read
1252                      * the first line of the response.
1253                      */
1254                     if (saw_headers) {
1255                         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1256                          "proxy: Starting body due to bogus non-header in headers "
1257                          "returned by %s (%s)", r->uri, r->method);
1258                         *pread_len = len;
1259                         return ;
1260                     } else {
1261                          ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1262                          "proxy: No HTTP headers "
1263                          "returned by %s (%s)", r->uri, r->method);
1264                         return ;
1265                     }
1266                 }
1267             }
1268             /* this is the psc->badopt == bad_ignore case */
1269             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, r->server,
1270                          "proxy: Ignoring bogus HTTP header "
1271                          "returned by %s (%s)", r->uri, r->method);
1272             continue;
1273         }
1274
1275         *value = '\0';
1276         ++value;
1277         /* XXX: RFC2068 defines only SP and HT as whitespace, this test is
1278          * wrong... and so are many others probably.
1279          */
1280         while (apr_isspace(*value))
1281             ++value;            /* Skip to start of value   */
1282
1283         /* should strip trailing whitespace as well */
1284         for (end = &value[strlen(value)-1]; end > value && apr_isspace(*end); --
1285 end)
1286             *end = '\0';
1287
1288         /* make sure we add so as not to destroy duplicated headers
1289          * Modify headers requiring canonicalisation and/or affected
1290          * by ProxyPassReverse and family with process_proxy_header
1291          */
1292         process_proxy_header(r, dconf, buffer, value) ;
1293         saw_headers = 1;
1294
1295         /* the header was too long; at the least we should skip extra data */
1296         if (len >= size - 1) {
1297             while ((len = ap_getline(field, MAX_STRING_LEN, rr, 1))
1298                     >= MAX_STRING_LEN - 1) {
1299                 /* soak up the extra data */
1300             }
1301             if (len == 0) /* time to exit the larger loop as well */
1302                 break;
1303         }
1304     }
1305 }
1306
1307
1308
1309 static int addit_dammit(void *v, const char *key, const char *val)
1310 {
1311     apr_table_addn(v, key, val);
1312     return 1;
1313 }
1314
1315 static
1316 apr_status_t ap_proxygetline(apr_bucket_brigade *bb, char *s, int n, request_rec *r,
1317                              int fold, int *writen)
1318 {
1319     char *tmp_s = s;
1320     apr_status_t rv;
1321     apr_size_t len;
1322
1323     rv = ap_rgetline(&tmp_s, n, &len, r, fold, bb);
1324     apr_brigade_cleanup(bb);
1325
1326     if (rv == APR_SUCCESS) {
1327         *writen = (int) len;
1328     } else if (rv == APR_ENOSPC) {
1329         *writen = n;
1330     } else {
1331         *writen = -1;
1332     }
1333
1334     return rv;
1335 }
1336
1337 /*
1338  * Limit the number of interim respones we sent back to the client. Otherwise
1339  * we suffer from a memory build up. Besides there is NO sense in sending back
1340  * an unlimited number of interim responses to the client. Thus if we cross
1341  * this limit send back a 502 (Bad Gateway).
1342  */
1343 #ifndef AP_MAX_INTERIM_RESPONSES
1344 #define AP_MAX_INTERIM_RESPONSES 10
1345 #endif
1346
1347 static
1348 apr_status_t ap_proxy_http_process_response(apr_pool_t * p, request_rec *r,
1349                                             proxy_conn_rec *backend,
1350                                             conn_rec *origin,
1351                                             proxy_server_conf *conf,
1352                                             char *server_portstr) {
1353     conn_rec *c = r->connection;
1354     char buffer[HUGE_STRING_LEN];
1355     const char *buf;
1356     char keepchar;
1357     request_rec *rp;
1358     apr_bucket *e;
1359     apr_bucket_brigade *bb, *tmp_bb;
1360     apr_bucket_brigade *pass_bb;
1361     int len, backasswards;
1362     int interim_response = 0; /* non-zero whilst interim 1xx responses
1363                                * are being read. */
1364     int pread_len = 0;
1365     apr_table_t *save_table;
1366     int backend_broke = 0;
1367     static const char *hop_by_hop_hdrs[] =
1368         {"Keep-Alive", "Proxy-Authenticate", "TE", "Trailer", "Upgrade", NULL};
1369     int i;
1370     const char *te = NULL;
1371     int original_status = r->status;
1372     int proxy_status = OK;
1373     const char *original_status_line = r->status_line;
1374     const char *proxy_status_line = NULL;
1375
1376     bb = apr_brigade_create(p, c->bucket_alloc);
1377     pass_bb = apr_brigade_create(p, c->bucket_alloc);
1378
1379     /* Get response from the remote server, and pass it up the
1380      * filter chain
1381      */
1382
1383     rp = ap_proxy_make_fake_req(origin, r);
1384     /* In case anyone needs to know, this is a fake request that is really a
1385      * response.
1386      */
1387     rp->proxyreq = PROXYREQ_RESPONSE;
1388     tmp_bb = apr_brigade_create(p, c->bucket_alloc);
1389     do {
1390         apr_status_t rc;
1391
1392         apr_brigade_cleanup(bb);
1393
1394         rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1395         if (len == 0) {
1396             /* handle one potential stray CRLF */
1397             rc = ap_proxygetline(tmp_bb, buffer, sizeof(buffer), rp, 0, &len);
1398         }
1399         if (len <= 0) {
1400             ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, r,
1401                           "proxy: error reading status line from remote "
1402                           "server %s:%d", backend->hostname, backend->port);
1403             if (rc == APR_TIMEUP) {
1404                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1405                               "proxy: read timeout");
1406             }
1407             /*
1408              * If we are a reverse proxy request shutdown the connection
1409              * WITHOUT ANY response to trigger a retry by the client
1410              * if allowed (as for idempotent requests).
1411              * BUT currently we should not do this if the request is the
1412              * first request on a keepalive connection as browsers like
1413              * seamonkey only display an empty page in this case and do
1414              * not do a retry. We should also not do this on a
1415              * connection which times out; instead handle as
1416              * we normally would handle timeouts
1417              */
1418             if (r->proxyreq == PROXYREQ_REVERSE && c->keepalives &&
1419                 rc != APR_TIMEUP) {
1420                 apr_bucket *eos;
1421
1422                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1423                               "proxy: Closing connection to client because"
1424                               " reading from backend server %s:%d failed."
1425                               " Number of keepalives %i", backend->hostname, 
1426                               backend->port, c->keepalives);
1427                 ap_proxy_backend_broke(r, bb);
1428                 /*
1429                  * Add an EOC bucket to signal the ap_http_header_filter
1430                  * that it should get out of our way, BUT ensure that the
1431                  * EOC bucket is inserted BEFORE an EOS bucket in bb as
1432                  * some resource filters like mod_deflate pass everything
1433                  * up to the EOS down the chain immediately and sent the
1434                  * remainder of the brigade later (or even never). But in
1435                  * this case the ap_http_header_filter does not get out of
1436                  * our way soon enough.
1437                  */
1438                 e = ap_bucket_eoc_create(c->bucket_alloc);
1439                 eos = APR_BRIGADE_LAST(bb);
1440                 while ((APR_BRIGADE_SENTINEL(bb) != eos)
1441                        && !APR_BUCKET_IS_EOS(eos)) {
1442                     eos = APR_BUCKET_PREV(eos);
1443                 }
1444                 if (eos == APR_BRIGADE_SENTINEL(bb)) {
1445                     APR_BRIGADE_INSERT_TAIL(bb, e);
1446                 }
1447                 else {
1448                     APR_BUCKET_INSERT_BEFORE(eos, e);
1449                 }
1450                 ap_pass_brigade(r->output_filters, bb);
1451                 /* Need to return OK to avoid sending an error message */
1452                 return OK;
1453             }
1454             else if (!c->keepalives) {
1455                      ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1456                                    "proxy: NOT Closing connection to client"
1457                                    " although reading from backend server %s:%d"
1458                                    " failed.", backend->hostname,
1459                                    backend->port);
1460             }
1461             return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1462                                  "Error reading from remote server");
1463         }
1464         /* XXX: Is this a real headers length send from remote? */
1465         backend->worker->s->read += len;
1466
1467         /* Is it an HTTP/1 response?
1468          * This is buggy if we ever see an HTTP/1.10
1469          */
1470         if (apr_date_checkmask(buffer, "HTTP/#.# ###*")) {
1471             int major, minor;
1472
1473             if (2 != sscanf(buffer, "HTTP/%u.%u", &major, &minor)) {
1474                 major = 1;
1475                 minor = 1;
1476             }
1477             /* If not an HTTP/1 message or
1478              * if the status line was > 8192 bytes
1479              */
1480             else if ((buffer[5] != '1') || (len >= sizeof(buffer)-1)) {
1481                 return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1482                 apr_pstrcat(p, "Corrupt status line returned by remote "
1483                             "server: ", buffer, NULL));
1484             }
1485             backasswards = 0;
1486
1487             keepchar = buffer[12];
1488             buffer[12] = '\0';
1489             proxy_status = atoi(&buffer[9]);
1490
1491             if (keepchar != '\0') {
1492                 buffer[12] = keepchar;
1493             } else {
1494                 /* 2616 requires the space in Status-Line; the origin
1495                  * server may have sent one but ap_rgetline_core will
1496                  * have stripped it. */
1497                 buffer[12] = ' ';
1498                 buffer[13] = '\0';
1499             }
1500             proxy_status_line = apr_pstrdup(p, &buffer[9]);
1501
1502             /* The status out of the front is the same as the status coming in
1503              * from the back, until further notice.
1504              */
1505             r->status = proxy_status;
1506             r->status_line = proxy_status_line;
1507
1508             /* read the headers. */
1509             /* N.B. for HTTP/1.0 clients, we have to fold line-wrapped headers*/
1510             /* Also, take care with headers with multiple occurences. */
1511
1512             /* First, tuck away all already existing cookies */
1513             save_table = apr_table_make(r->pool, 2);
1514             apr_table_do(addit_dammit, save_table, r->headers_out,
1515                          "Set-Cookie", NULL);
1516
1517             /* shove the headers direct into r->headers_out */
1518             ap_proxy_read_headers(r, rp, buffer, sizeof(buffer), origin,
1519                                   &pread_len);
1520
1521             if (r->headers_out == NULL) {
1522                 ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
1523                              r->server, "proxy: bad HTTP/%d.%d header "
1524                              "returned by %s (%s)", major, minor, r->uri,
1525                              r->method);
1526                 backend->close += 1;
1527                 /*
1528                  * ap_send_error relies on a headers_out to be present. we
1529                  * are in a bad position here.. so force everything we send out
1530                  * to have nothing to do with the incoming packet
1531                  */
1532                 r->headers_out = apr_table_make(r->pool,1);
1533                 r->status = HTTP_BAD_GATEWAY;
1534                 r->status_line = "bad gateway";
1535                 return r->status;
1536             }
1537
1538             /* Now, add in the just read cookies */
1539             apr_table_do(addit_dammit, save_table, r->headers_out,
1540                          "Set-Cookie", NULL);
1541
1542             /* and now load 'em all in */
1543             if (!apr_is_empty_table(save_table)) {
1544                 apr_table_unset(r->headers_out, "Set-Cookie");
1545                 r->headers_out = apr_table_overlay(r->pool,
1546                                                    r->headers_out,
1547                                                    save_table);
1548             }
1549
1550             /* can't have both Content-Length and Transfer-Encoding */
1551             if (apr_table_get(r->headers_out, "Transfer-Encoding")
1552                     && apr_table_get(r->headers_out, "Content-Length")) {
1553                 /*
1554                  * 2616 section 4.4, point 3: "if both Transfer-Encoding
1555                  * and Content-Length are received, the latter MUST be
1556                  * ignored";
1557                  *
1558                  * To help mitigate HTTP Splitting, unset Content-Length
1559                  * and shut down the backend server connection
1560                  * XXX: We aught to treat such a response as uncachable
1561                  */
1562                 apr_table_unset(r->headers_out, "Content-Length");
1563                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1564                              "proxy: server %s:%d returned Transfer-Encoding"
1565                              " and Content-Length", backend->hostname,
1566                              backend->port);
1567                 backend->close += 1;
1568             }
1569
1570             /*
1571              * Save a possible Transfer-Encoding header as we need it later for
1572              * ap_http_filter to know where to end.
1573              */
1574             te = apr_table_get(r->headers_out, "Transfer-Encoding");
1575             /* strip connection listed hop-by-hop headers from response */
1576             backend->close += ap_proxy_liststr(apr_table_get(r->headers_out,
1577                                                              "Connection"),
1578                                               "close");
1579             ap_proxy_clear_connection(p, r->headers_out);
1580             if ((buf = apr_table_get(r->headers_out, "Content-Type"))) {
1581                 ap_set_content_type(r, apr_pstrdup(p, buf));
1582             }
1583             if (!ap_is_HTTP_INFO(proxy_status)) {
1584                 ap_proxy_pre_http_request(origin, rp);
1585             }
1586
1587             /* Clear hop-by-hop headers */
1588             for (i=0; hop_by_hop_hdrs[i]; ++i) {
1589                 apr_table_unset(r->headers_out, hop_by_hop_hdrs[i]);
1590             }
1591             /* Delete warnings with wrong date */
1592             r->headers_out = ap_proxy_clean_warnings(p, r->headers_out);
1593
1594             /* handle Via header in response */
1595             if (conf->viaopt != via_off && conf->viaopt != via_block) {
1596                 const char *server_name = ap_get_server_name(r);
1597                 /* If USE_CANONICAL_NAME_OFF was configured for the proxy virtual host,
1598                  * then the server name returned by ap_get_server_name() is the
1599                  * origin server name (which does make too much sense with Via: headers)
1600                  * so we use the proxy vhost's name instead.
1601                  */
1602                 if (server_name == r->hostname)
1603                     server_name = r->server->server_hostname;
1604                 /* create a "Via:" response header entry and merge it */
1605                 apr_table_addn(r->headers_out, "Via",
1606                                (conf->viaopt == via_full)
1607                                      ? apr_psprintf(p, "%d.%d %s%s (%s)",
1608                                            HTTP_VERSION_MAJOR(r->proto_num),
1609                                            HTTP_VERSION_MINOR(r->proto_num),
1610                                            server_name,
1611                                            server_portstr,
1612                                            AP_SERVER_BASEVERSION)
1613                                      : apr_psprintf(p, "%d.%d %s%s",
1614                                            HTTP_VERSION_MAJOR(r->proto_num),
1615                                            HTTP_VERSION_MINOR(r->proto_num),
1616                                            server_name,
1617                                            server_portstr)
1618                 );
1619             }
1620
1621             /* cancel keepalive if HTTP/1.0 or less */
1622             if ((major < 1) || (minor < 1)) {
1623                 backend->close += 1;
1624                 origin->keepalive = AP_CONN_CLOSE;
1625             }
1626         } else {
1627             /* an http/0.9 response */
1628             backasswards = 1;
1629             r->status = 200;
1630             r->status_line = "200 OK";
1631             backend->close += 1;
1632         }
1633
1634         if (ap_is_HTTP_INFO(proxy_status)) {
1635             interim_response++;
1636         }
1637         else {
1638             interim_response = 0;
1639         }
1640         if (interim_response) {
1641             /* RFC2616 tells us to forward this.
1642              *
1643              * OTOH, an interim response here may mean the backend
1644              * is playing sillybuggers.  The Client didn't ask for
1645              * it within the defined HTTP/1.1 mechanisms, and if
1646              * it's an extension, it may also be unsupported by us.
1647              *
1648              * There's also the possibility that changing existing
1649              * behaviour here might break something.
1650              *
1651              * So let's make it configurable.
1652              */
1653             const char *policy = apr_table_get(r->subprocess_env,
1654                                                "proxy-interim-response");
1655             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1656                          "proxy: HTTP: received interim %d response",
1657                          r->status);
1658             if (!policy || !strcasecmp(policy, "RFC")) {
1659                 ap_send_interim_response(r, 1);
1660             }
1661             /* FIXME: refine this to be able to specify per-response-status
1662              * policies and maybe also add option to bail out with 502
1663              */
1664             else if (strcasecmp(policy, "Suppress")) {
1665                 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
1666                              "undefined proxy interim response policy");
1667             }
1668         }
1669         /* Moved the fixups of Date headers and those affected by
1670          * ProxyPassReverse/etc from here to ap_proxy_read_headers
1671          */
1672
1673         if ((proxy_status == 401) && (conf->error_override)) {
1674             const char *buf;
1675             const char *wa = "WWW-Authenticate";
1676             if ((buf = apr_table_get(r->headers_out, wa))) {
1677                 apr_table_set(r->err_headers_out, wa, buf);
1678             } else {
1679                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1680                              "proxy: origin server sent 401 without WWW-Authenticate header");
1681             }
1682         }
1683
1684         r->sent_bodyct = 1;
1685         /*
1686          * Is it an HTTP/0.9 response or did we maybe preread the 1st line of
1687          * the response? If so, load the extra data. These are 2 mutually
1688          * exclusive possibilities, that just happen to require very
1689          * similar behavior.
1690          */
1691         if (backasswards || pread_len) {
1692             apr_ssize_t cntr = (apr_ssize_t)pread_len;
1693             if (backasswards) {
1694                 /*@@@FIXME:
1695                  * At this point in response processing of a 0.9 response,
1696                  * we don't know yet whether data is binary or not.
1697                  * mod_charset_lite will get control later on, so it cannot
1698                  * decide on the conversion of this buffer full of data.
1699                  * However, chances are that we are not really talking to an
1700                  * HTTP/0.9 server, but to some different protocol, therefore
1701                  * the best guess IMHO is to always treat the buffer as "text/x":
1702                  */
1703                 ap_xlate_proto_to_ascii(buffer, len);
1704                 cntr = (apr_ssize_t)len;
1705             }
1706             e = apr_bucket_heap_create(buffer, cntr, NULL, c->bucket_alloc);
1707             APR_BRIGADE_INSERT_TAIL(bb, e);
1708         }
1709         /* PR 41646: get HEAD right with ProxyErrorOverride */
1710         if (ap_is_HTTP_ERROR(r->status) && conf->error_override) {
1711             /* clear r->status for override error, otherwise ErrorDocument
1712              * thinks that this is a recursive error, and doesn't find the
1713              * custom error page
1714              */
1715             r->status = HTTP_OK;
1716             /* Discard body, if one is expected */
1717             if (!r->header_only && /* not HEAD request */
1718                 (proxy_status != HTTP_NO_CONTENT) && /* not 204 */
1719                 (proxy_status != HTTP_NOT_MODIFIED)) { /* not 304 */
1720                 ap_discard_request_body(rp);
1721             }
1722             return proxy_status;
1723         }
1724
1725         /* send body - but only if a body is expected */
1726         if ((!r->header_only) &&                   /* not HEAD request */
1727             !interim_response &&                   /* not any 1xx response */
1728             (proxy_status != HTTP_NO_CONTENT) &&      /* not 204 */
1729             (proxy_status != HTTP_NOT_MODIFIED)) {    /* not 304 */
1730
1731             /* We need to copy the output headers and treat them as input
1732              * headers as well.  BUT, we need to do this before we remove
1733              * TE, so that they are preserved accordingly for
1734              * ap_http_filter to know where to end.
1735              */
1736             rp->headers_in = apr_table_copy(r->pool, r->headers_out);
1737             /*
1738              * Restore Transfer-Encoding header from response if we saved
1739              * one before and there is none left. We need it for the
1740              * ap_http_filter. See above.
1741              */
1742             if (te && !apr_table_get(rp->headers_in, "Transfer-Encoding")) {
1743                 apr_table_add(rp->headers_in, "Transfer-Encoding", te);
1744             }
1745
1746             apr_table_unset(r->headers_out,"Transfer-Encoding");
1747
1748             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1749                          "proxy: start body send");
1750
1751             /*
1752              * if we are overriding the errors, we can't put the content
1753              * of the page into the brigade
1754              */
1755             if (!conf->error_override || !ap_is_HTTP_ERROR(proxy_status)) {
1756                 /* read the body, pass it to the output filters */
1757                 apr_read_type_e mode = APR_NONBLOCK_READ;
1758                 int finish = FALSE;
1759
1760                 /* Handle the case where the error document is itself reverse
1761                  * proxied and was successful. We must maintain any previous
1762                  * error status so that an underlying error (eg HTTP_NOT_FOUND)
1763                  * doesn't become an HTTP_OK.
1764                  */
1765                 if (conf->error_override && !ap_is_HTTP_ERROR(proxy_status)
1766                         && ap_is_HTTP_ERROR(original_status)) {
1767                     r->status = original_status;
1768                     r->status_line = original_status_line;
1769                 }
1770
1771                 do {
1772                     apr_off_t readbytes;
1773                     apr_status_t rv;
1774
1775                     rv = ap_get_brigade(rp->input_filters, bb,
1776                                         AP_MODE_READBYTES, mode,
1777                                         conf->io_buffer_size);
1778
1779                     /* ap_get_brigade will return success with an empty brigade
1780                      * for a non-blocking read which would block: */
1781                     if (APR_STATUS_IS_EAGAIN(rv)
1782                         || (rv == APR_SUCCESS && APR_BRIGADE_EMPTY(bb))) {
1783                         /* flush to the client and switch to blocking mode */
1784                         e = apr_bucket_flush_create(c->bucket_alloc);
1785                         APR_BRIGADE_INSERT_TAIL(bb, e);
1786                         if (ap_pass_brigade(r->output_filters, bb)
1787                             || c->aborted) {
1788                             backend->close = 1;
1789                             break;
1790                         }
1791                         apr_brigade_cleanup(bb);
1792                         mode = APR_BLOCK_READ;
1793                         continue;
1794                     }
1795                     else if (rv == APR_EOF) {
1796                         break;
1797                     }
1798                     else if (rv != APR_SUCCESS) {
1799                         /* In this case, we are in real trouble because
1800                          * our backend bailed on us. Pass along a 502 error
1801                          * error bucket
1802                          */
1803                         ap_log_cerror(APLOG_MARK, APLOG_ERR, rv, c,
1804                                       "proxy: error reading response");
1805                         ap_proxy_backend_broke(r, bb);
1806                         ap_pass_brigade(r->output_filters, bb);
1807                         backend_broke = 1;
1808                         backend->close = 1;
1809                         break;
1810                     }
1811                     /* next time try a non-blocking read */
1812                     mode = APR_NONBLOCK_READ;
1813
1814                     apr_brigade_length(bb, 0, &readbytes);
1815                     backend->worker->s->read += readbytes;
1816 #if DEBUGGING
1817                     {
1818                     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
1819                                  r->server, "proxy (PID %d): readbytes: %#x",
1820                                  getpid(), readbytes);
1821                     }
1822 #endif
1823                     /* sanity check */
1824                     if (APR_BRIGADE_EMPTY(bb)) {
1825                         apr_brigade_cleanup(bb);
1826                         break;
1827                     }
1828
1829                     /* Switch the allocator lifetime of the buckets */
1830                     ap_proxy_buckets_lifetime_transform(r, bb, pass_bb);
1831
1832                     /* found the last brigade? */
1833                     if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
1834                         /* signal that we must leave */
1835                         finish = TRUE;
1836                     }
1837
1838                     /* try send what we read */
1839                     if (ap_pass_brigade(r->output_filters, pass_bb) != APR_SUCCESS
1840                         || c->aborted) {
1841                         /* Ack! Phbtt! Die! User aborted! */
1842                         backend->close = 1;  /* this causes socket close below */
1843                         finish = TRUE;
1844                     }
1845
1846                     /* make sure we always clean up after ourselves */
1847                     apr_brigade_cleanup(bb);
1848                     apr_brigade_cleanup(pass_bb);
1849
1850                 } while (!finish);
1851             }
1852             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1853                          "proxy: end body send");
1854         }
1855         else if (!interim_response) {
1856             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1857                          "proxy: header only");
1858
1859             /* Pass EOS bucket down the filter chain. */
1860             e = apr_bucket_eos_create(c->bucket_alloc);
1861             APR_BRIGADE_INSERT_TAIL(bb, e);
1862             if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
1863                 || c->aborted) {
1864                 /* Ack! Phbtt! Die! User aborted! */
1865                 backend->close = 1;  /* this causes socket close below */
1866             }
1867
1868             apr_brigade_cleanup(bb);
1869         }
1870     } while (interim_response && (interim_response < AP_MAX_INTERIM_RESPONSES));
1871
1872     /* See define of AP_MAX_INTERIM_RESPONSES for why */
1873     if (interim_response >= AP_MAX_INTERIM_RESPONSES) {
1874         return ap_proxyerror(r, HTTP_BAD_GATEWAY,
1875                              apr_psprintf(p, 
1876                              "Too many (%d) interim responses from origin server",
1877                              interim_response));
1878     }
1879
1880     /* If our connection with the client is to be aborted, return DONE. */
1881     if (c->aborted || backend_broke) {
1882         return DONE;
1883     }
1884
1885     return OK;
1886 }
1887
1888 static
1889 apr_status_t ap_proxy_http_cleanup(const char *scheme, request_rec *r,
1890                                    proxy_conn_rec *backend)
1891 {
1892     ap_proxy_release_connection(scheme, backend, r->server);
1893     return OK;
1894 }
1895
1896 /*
1897  * This handles http:// URLs, and other URLs using a remote proxy over http
1898  * If proxyhost is NULL, then contact the server directly, otherwise
1899  * go via the proxy.
1900  * Note that if a proxy is used, then URLs other than http: can be accessed,
1901  * also, if we have trouble which is clearly specific to the proxy, then
1902  * we return DECLINED so that we can try another proxy. (Or the direct
1903  * route.)
1904  */
1905 static int proxy_http_handler(request_rec *r, proxy_worker *worker,
1906                               proxy_server_conf *conf,
1907                               char *url, const char *proxyname,
1908                               apr_port_t proxyport)
1909 {
1910     int status;
1911     char server_portstr[32];
1912     char *scheme;
1913     const char *proxy_function;
1914     const char *u;
1915     proxy_conn_rec *backend = NULL;
1916     int is_ssl = 0;
1917     conn_rec *c = r->connection;
1918     /*
1919      * Use a shorter-lived pool to reduce memory usage
1920      * and avoid a memory leak
1921      */
1922     apr_pool_t *p = r->pool;
1923     apr_uri_t *uri = apr_palloc(p, sizeof(*uri));
1924
1925     /* find the scheme */
1926     u = strchr(url, ':');
1927     if (u == NULL || u[1] != '/' || u[2] != '/' || u[3] == '\0')
1928        return DECLINED;
1929     if ((u - url) > 14)
1930         return HTTP_BAD_REQUEST;
1931     scheme = apr_pstrndup(p, url, u - url);
1932     /* scheme is lowercase */
1933     ap_str_tolower(scheme);
1934     /* is it for us? */
1935     if (strcmp(scheme, "https") == 0) {
1936         if (!ap_proxy_ssl_enable(NULL)) {
1937             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1938                          "proxy: HTTPS: declining URL %s"
1939                          " (mod_ssl not configured?)", url);
1940             return DECLINED;
1941         }
1942         is_ssl = 1;
1943         proxy_function = "HTTPS";
1944     }
1945     else if (!(strcmp(scheme, "http") == 0 || (strcmp(scheme, "ftp") == 0 && proxyname))) {
1946         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1947                      "proxy: HTTP: declining URL %s", url);
1948         return DECLINED; /* only interested in HTTP, or FTP via proxy */
1949     }
1950     else {
1951         if (*scheme == 'h')
1952             proxy_function = "HTTP";
1953         else
1954             proxy_function = "FTP";
1955     }
1956     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
1957              "proxy: HTTP: serving URL %s", url);
1958
1959
1960     /* create space for state information */
1961     if ((status = ap_proxy_acquire_connection(proxy_function, &backend,
1962                                               worker, r->server)) != OK)
1963         goto cleanup;
1964
1965
1966     backend->is_ssl = is_ssl;
1967
1968     if (is_ssl) {
1969         ap_proxy_ssl_connection_cleanup(backend, r);
1970     }
1971
1972     /*
1973      * In the case that we are handling a reverse proxy connection and this
1974      * is not a request that is coming over an already kept alive connection
1975      * with the client, do NOT reuse the connection to the backend, because
1976      * we cannot forward a failure to the client in this case as the client
1977      * does NOT expect this in this situation.
1978      * Yes, this creates a performance penalty.
1979      */
1980     if ((r->proxyreq == PROXYREQ_REVERSE) && (!c->keepalives)
1981         && (apr_table_get(r->subprocess_env, "proxy-initial-not-pooled"))) {
1982         backend->close = 1;
1983     }
1984
1985     /* Step One: Determine Who To Connect To */
1986     if ((status = ap_proxy_determine_connection(p, r, conf, worker, backend,
1987                                                 uri, &url, proxyname,
1988                                                 proxyport, server_portstr,
1989                                                 sizeof(server_portstr))) != OK)
1990         goto cleanup;
1991
1992     /* Step Two: Make the Connection */
1993     if (ap_proxy_connect_backend(proxy_function, backend, worker, r->server)) {
1994         status = HTTP_SERVICE_UNAVAILABLE;
1995         goto cleanup;
1996     }
1997
1998     /* Step Three: Create conn_rec */
1999     if (!backend->connection) {
2000         if ((status = ap_proxy_connection_create(proxy_function, backend,
2001                                                  c, r->server)) != OK)
2002             goto cleanup;
2003         /*
2004          * On SSL connections set a note on the connection what CN is
2005          * requested, such that mod_ssl can check if it is requested to do
2006          * so.
2007          */
2008         if (is_ssl) {
2009             apr_table_set(backend->connection->notes, "proxy-request-hostname",
2010                           uri->hostname);
2011         }
2012     }
2013
2014     /* Step Four: Send the Request */
2015     if ((status = ap_proxy_http_request(p, r, backend, backend->connection,
2016                                         conf, uri, url, server_portstr)) != OK)
2017         goto cleanup;
2018
2019     /* Step Five: Receive the Response */
2020     if ((status = ap_proxy_http_process_response(p, r, backend,
2021                                                  backend->connection,
2022                                                  conf, server_portstr)) != OK)
2023         goto cleanup;
2024
2025     /* Step Six: Clean Up */
2026
2027 cleanup:
2028     if (backend) {
2029         if (status != OK)
2030             backend->close = 1;
2031         ap_proxy_http_cleanup(proxy_function, r, backend);
2032     }
2033     return status;
2034 }
2035 static apr_status_t warn_rx_free(void *p)
2036 {
2037     ap_pregfree((apr_pool_t*)p, warn_rx);
2038     return APR_SUCCESS;
2039 }
2040 static void ap_proxy_http_register_hook(apr_pool_t *p)
2041 {
2042     proxy_hook_scheme_handler(proxy_http_handler, NULL, NULL, APR_HOOK_FIRST);
2043     proxy_hook_canon_handler(proxy_http_canon, NULL, NULL, APR_HOOK_FIRST);
2044     warn_rx = ap_pregcomp(p, "[0-9]{3}[ \t]+[^ \t]+[ \t]+\"[^\"]*\"([ \t]+\"([^\"]+)\")?", 0);
2045     apr_pool_cleanup_register(p, p, warn_rx_free, apr_pool_cleanup_null);
2046 }
2047
2048 AP_DECLARE_MODULE(proxy_http) = {
2049     STANDARD20_MODULE_STUFF,
2050     NULL,              /* create per-directory config structure */
2051     NULL,              /* merge per-directory config structures */
2052     NULL,              /* create per-server config structure */
2053     NULL,              /* merge per-server config structures */
2054     NULL,              /* command apr_table_t */
2055     ap_proxy_http_register_hook/* register hooks */
2056 };
2057