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