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