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