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