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