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