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