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