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