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