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