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