]> granicus.if.org Git - apache/blob - modules/http/http_filters.c
http_filters: Don't send 100-continue when 4xx is due
[apache] / modules / http / http_filters.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * http_filter.c --- HTTP routines which either filters or deal with filters.
19  */
20
21 #include "apr.h"
22 #include "apr_strings.h"
23 #include "apr_buckets.h"
24 #include "apr_lib.h"
25 #include "apr_signal.h"
26
27 #define APR_WANT_STDIO          /* for sscanf */
28 #define APR_WANT_STRFUNC
29 #define APR_WANT_MEMFUNC
30 #include "apr_want.h"
31
32 #define CORE_PRIVATE
33 #include "util_filter.h"
34 #include "ap_config.h"
35 #include "httpd.h"
36 #include "http_config.h"
37 #include "http_core.h"
38 #include "http_protocol.h"
39 #include "http_main.h"
40 #include "http_request.h"
41 #include "http_vhost.h"
42 #include "http_log.h"           /* For errors detected in basic auth common
43                                  * support code... */
44 #include "apr_date.h"           /* For apr_date_parse_http and APR_DATE_BAD */
45 #include "util_charset.h"
46 #include "util_ebcdic.h"
47 #include "util_time.h"
48
49 #include "mod_core.h"
50
51 #if APR_HAVE_STDARG_H
52 #include <stdarg.h>
53 #endif
54 #if APR_HAVE_UNISTD_H
55 #include <unistd.h>
56 #endif
57
58 #define INVALID_CHAR -2
59
60 extern module AP_MODULE_DECLARE_DATA http_module;
61
62 static long get_chunk_size(char *);
63
64 typedef struct http_filter_ctx {
65     apr_off_t remaining;
66     apr_off_t limit;
67     apr_off_t limit_used;
68     enum {
69         BODY_NONE,
70         BODY_LENGTH,
71         BODY_CHUNK,
72         BODY_CHUNK_PART
73     } state;
74     int eos_sent;
75     char chunk_ln[32];
76     char *pos;
77     apr_off_t linesize;
78     apr_bucket_brigade *bb;
79 } http_ctx_t;
80
81 static apr_status_t bail_out_on_error(http_ctx_t *ctx,
82                                       ap_filter_t *f,
83                                       int http_error)
84 {
85     apr_bucket *e;
86     apr_bucket_brigade *bb = ctx->bb;
87
88     apr_brigade_cleanup(bb);
89     e = ap_bucket_error_create(http_error,
90                                NULL, f->r->pool,
91                                f->c->bucket_alloc);
92     APR_BRIGADE_INSERT_TAIL(bb, e);
93     e = apr_bucket_eos_create(f->c->bucket_alloc);
94     APR_BRIGADE_INSERT_TAIL(bb, e);
95     ctx->eos_sent = 1;
96     return ap_pass_brigade(f->r->output_filters, bb);
97 }
98
99 static apr_status_t get_remaining_chunk_line(http_ctx_t *ctx,
100                                              apr_bucket_brigade *b,
101                                              int linelimit)
102 {
103     apr_status_t rv;
104     apr_off_t brigade_length;
105     apr_bucket *e;
106     const char *lineend;
107     apr_size_t len;
108
109     /*
110      * As the brigade b should have been requested in mode AP_MODE_GETLINE
111      * all buckets in this brigade are already some type of memory
112      * buckets (due to the needed scanning for LF in mode AP_MODE_GETLINE)
113      * or META buckets.
114      */
115     rv = apr_brigade_length(b, 0, &brigade_length);
116     if (rv != APR_SUCCESS) {
117         return rv;
118     }
119     /* Sanity check. Should never happen. See above. */
120     if (brigade_length == -1) {
121         return APR_EGENERAL;
122     }
123     if (!brigade_length) {
124         return APR_EAGAIN;
125     }
126     ctx->linesize += brigade_length;
127     if (ctx->linesize > linelimit) {
128         return APR_ENOSPC;
129     }
130     /*
131      * As all buckets are already some type of memory buckets or META buckets
132      * (see above), we only need to check the last byte in the last data bucket.
133      */
134     for (e = APR_BRIGADE_LAST(b);
135          e != APR_BRIGADE_SENTINEL(b);
136          e = APR_BUCKET_PREV(e)) {
137
138         if (APR_BUCKET_IS_METADATA(e)) {
139             continue;
140         }
141         rv = apr_bucket_read(e, &lineend, &len, APR_BLOCK_READ);
142         if (rv != APR_SUCCESS) {
143             return rv;
144         }
145         if (len > 0) {
146             break;  /* we got the data we want */
147         }
148         /* If we got a zero-length data bucket, we try the next one */
149     }
150     /* We had no data in this brigade */
151     if (!len || e == APR_BRIGADE_SENTINEL(b)) {
152         return APR_EAGAIN;
153     }
154     if (lineend[len - 1] != APR_ASCII_LF) {
155         return APR_EAGAIN;
156     }
157     /* Line is complete. So reset ctx->linesize for next round. */
158     ctx->linesize = 0;
159     return APR_SUCCESS;
160 }
161
162 static apr_status_t get_chunk_line(http_ctx_t *ctx, apr_bucket_brigade *b,
163                                    int linelimit)
164 {
165     apr_size_t len;
166     int tmp_len;
167     apr_status_t rv;
168
169     tmp_len = sizeof(ctx->chunk_ln) - (ctx->pos - ctx->chunk_ln) - 1;
170     /* Saveguard ourselves against underflows */
171     if (tmp_len < 0) {
172         len = 0;
173     }
174     else {
175         len = (apr_size_t) tmp_len;
176     }
177     /*
178      * Check if there is space left in ctx->chunk_ln. If not, then either
179      * the chunk size is insane or we have chunk-extensions. Ignore both
180      * by discarding the remaining part of the line via
181      * get_remaining_chunk_line. Only bail out if the line is too long.
182      */
183     if (len > 0) {
184         rv = apr_brigade_flatten(b, ctx->pos, &len);
185         if (rv != APR_SUCCESS) {
186             return rv;
187         }
188         ctx->pos += len;
189         ctx->linesize += len;
190         *(ctx->pos) = '\0';
191         /*
192          * Check if we really got a full line. If yes the
193          * last char in the just read buffer must be LF.
194          * If not advance the buffer and return APR_EAGAIN.
195          * We do not start processing until we have the
196          * full line.
197          */
198         if (ctx->pos[-1] != APR_ASCII_LF) {
199             /* Check if the remaining data in the brigade has the LF */
200             return get_remaining_chunk_line(ctx, b, linelimit);
201         }
202         /* Line is complete. So reset ctx->pos for next round. */
203         ctx->pos = ctx->chunk_ln;
204         return APR_SUCCESS;
205     }
206     return get_remaining_chunk_line(ctx, b, linelimit);
207 }
208
209
210 /* This is the HTTP_INPUT filter for HTTP requests and responses from
211  * proxied servers (mod_proxy).  It handles chunked and content-length
212  * bodies.  This can only be inserted/used after the headers
213  * are successfully parsed.
214  */
215 apr_status_t ap_http_filter(ap_filter_t *f, apr_bucket_brigade *b,
216                             ap_input_mode_t mode, apr_read_type_e block,
217                             apr_off_t readbytes)
218 {
219     apr_bucket *e;
220     http_ctx_t *ctx = f->ctx;
221     apr_status_t rv;
222     apr_off_t totalread;
223     int http_error = HTTP_REQUEST_ENTITY_TOO_LARGE;
224     apr_bucket_brigade *bb;
225
226     /* just get out of the way of things we don't want. */
227     if (mode != AP_MODE_READBYTES && mode != AP_MODE_GETLINE) {
228         return ap_get_brigade(f->next, b, mode, block, readbytes);
229     }
230
231     if (!ctx) {
232         const char *tenc, *lenp;
233         f->ctx = ctx = apr_pcalloc(f->r->pool, sizeof(*ctx));
234         ctx->state = BODY_NONE;
235         ctx->pos = ctx->chunk_ln;
236         ctx->bb = apr_brigade_create(f->r->pool, f->c->bucket_alloc);
237         bb = ctx->bb;
238
239         /* LimitRequestBody does not apply to proxied responses.
240          * Consider implementing this check in its own filter.
241          * Would adding a directive to limit the size of proxied
242          * responses be useful?
243          */
244         if (!f->r->proxyreq) {
245             ctx->limit = ap_get_limit_req_body(f->r);
246         }
247         else {
248             ctx->limit = 0;
249         }
250
251         tenc = apr_table_get(f->r->headers_in, "Transfer-Encoding");
252         lenp = apr_table_get(f->r->headers_in, "Content-Length");
253
254         if (tenc) {
255             if (!strcasecmp(tenc, "chunked")) {
256                 ctx->state = BODY_CHUNK;
257             }
258             /* test lenp, because it gives another case we can handle */
259             else if (!lenp) {
260                 /* Something that isn't in HTTP, unless some future
261                  * edition defines new transfer ecodings, is unsupported.
262                  */
263                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, f->r,
264                               "Unknown Transfer-Encoding: %s", tenc);
265                 return bail_out_on_error(ctx, f, HTTP_NOT_IMPLEMENTED);
266             }
267             else {
268                 ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, f->r,
269                   "Unknown Transfer-Encoding: %s; using Content-Length", tenc);
270                 tenc = NULL;
271             }
272         }
273         if (lenp && !tenc) {
274             char *endstr;
275
276             ctx->state = BODY_LENGTH;
277             errno = 0;
278
279             /* Protects against over/underflow, non-digit chars in the
280              * string (excluding leading space) (the endstr checks)
281              * and a negative number. */
282             if (apr_strtoff(&ctx->remaining, lenp, &endstr, 10)
283                 || endstr == lenp || *endstr || ctx->remaining < 0) {
284
285                 ctx->remaining = 0;
286                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, f->r,
287                               "Invalid Content-Length");
288
289                 return bail_out_on_error(ctx, f, HTTP_REQUEST_ENTITY_TOO_LARGE);
290             }
291
292             /* If we have a limit in effect and we know the C-L ahead of
293              * time, stop it here if it is invalid.
294              */
295             if (ctx->limit && ctx->limit < ctx->remaining) {
296                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, f->r,
297                           "Requested content-length of %" APR_OFF_T_FMT
298                           " is larger than the configured limit"
299                           " of %" APR_OFF_T_FMT, ctx->remaining, ctx->limit);
300                 return bail_out_on_error(ctx, f, HTTP_REQUEST_ENTITY_TOO_LARGE);
301             }
302         }
303
304         /* If we don't have a request entity indicated by the headers, EOS.
305          * (BODY_NONE is a valid intermediate state due to trailers,
306          *  but it isn't a valid starting state.)
307          *
308          * RFC 2616 Section 4.4 note 5 states that connection-close
309          * is invalid for a request entity - request bodies must be
310          * denoted by C-L or T-E: chunked.
311          *
312          * Note that since the proxy uses this filter to handle the
313          * proxied *response*, proxy responses MUST be exempt.
314          */
315         if (ctx->state == BODY_NONE && f->r->proxyreq != PROXYREQ_RESPONSE) {
316             e = apr_bucket_eos_create(f->c->bucket_alloc);
317             APR_BRIGADE_INSERT_TAIL(b, e);
318             ctx->eos_sent = 1;
319             return APR_SUCCESS;
320         }
321
322         /* Since we're about to read data, send 100-Continue if needed.
323          * Only valid on chunked and C-L bodies where the C-L is > 0. */
324         if ((ctx->state == BODY_CHUNK ||
325             (ctx->state == BODY_LENGTH && ctx->remaining > 0)) &&
326             f->r->expecting_100 && f->r->proto_num >= HTTP_VERSION(1,1) &&
327             !(f->r->eos_sent || f->r->bytes_sent)) {
328             if (ap_is_HTTP_CLIENT_ERROR(f->r->status)) {
329                 ctx->state = BODY_NONE;
330                 ctx->eos_sent = 1;
331             } else {
332                 char *tmp;
333
334                 tmp = apr_pstrcat(f->r->pool, AP_SERVER_PROTOCOL, " ",
335                                   ap_get_status_line(100), CRLF CRLF, NULL);
336                 apr_brigade_cleanup(bb);
337                 e = apr_bucket_pool_create(tmp, strlen(tmp), f->r->pool,
338                                            f->c->bucket_alloc);
339                 APR_BRIGADE_INSERT_HEAD(bb, e);
340                 e = apr_bucket_flush_create(f->c->bucket_alloc);
341                 APR_BRIGADE_INSERT_TAIL(bb, e);
342
343                 ap_pass_brigade(f->c->output_filters, bb);
344             }
345         }
346
347         /* We can't read the chunk until after sending 100 if required. */
348         if (ctx->state == BODY_CHUNK) {
349             apr_brigade_cleanup(bb);
350
351             rv = ap_get_brigade(f->next, bb, AP_MODE_GETLINE,
352                                 block, 0);
353
354             /* for timeout */
355             if (block == APR_NONBLOCK_READ &&
356                 ( (rv == APR_SUCCESS && APR_BRIGADE_EMPTY(bb)) ||
357                   (APR_STATUS_IS_EAGAIN(rv)) )) {
358                 ctx->state = BODY_CHUNK_PART;
359                 return APR_EAGAIN;
360             }
361
362             if (rv == APR_SUCCESS) {
363                 rv = get_chunk_line(ctx, bb, f->r->server->limit_req_line);
364                 if (APR_STATUS_IS_EAGAIN(rv)) {
365                     apr_brigade_cleanup(bb);
366                     ctx->state = BODY_CHUNK_PART;
367                     return rv;
368                 }
369                 if (rv == APR_SUCCESS) {
370                     ctx->remaining = get_chunk_size(ctx->chunk_ln);
371                     if (ctx->remaining == INVALID_CHAR) {
372                         rv = APR_EGENERAL;
373                         http_error = HTTP_SERVICE_UNAVAILABLE;
374                     }
375                 }
376             }
377             apr_brigade_cleanup(bb);
378
379             /* Detect chunksize error (such as overflow) */
380             if (rv != APR_SUCCESS || ctx->remaining < 0) {
381                 ctx->remaining = 0; /* Reset it in case we have to
382                                      * come back here later */
383                 return bail_out_on_error(ctx, f, http_error);
384             }
385
386             if (!ctx->remaining) {
387                 /* Handle trailers by calling ap_get_mime_headers again! */
388                 ctx->state = BODY_NONE;
389                 ap_get_mime_headers(f->r);
390                 e = apr_bucket_eos_create(f->c->bucket_alloc);
391                 APR_BRIGADE_INSERT_TAIL(b, e);
392                 ctx->eos_sent = 1;
393                 return APR_SUCCESS;
394             }
395         }
396     }
397     else {
398         bb = ctx->bb;
399     }
400
401     if (ctx->eos_sent) {
402         e = apr_bucket_eos_create(f->c->bucket_alloc);
403         APR_BRIGADE_INSERT_TAIL(b, e);
404         return APR_SUCCESS;
405     }
406
407     if (!ctx->remaining) {
408         switch (ctx->state) {
409         case BODY_NONE:
410             break;
411         case BODY_LENGTH:
412             e = apr_bucket_eos_create(f->c->bucket_alloc);
413             APR_BRIGADE_INSERT_TAIL(b, e);
414             ctx->eos_sent = 1;
415             return APR_SUCCESS;
416         case BODY_CHUNK:
417         case BODY_CHUNK_PART:
418             {
419                 apr_brigade_cleanup(bb);
420
421                 /* We need to read the CRLF after the chunk.  */
422                 if (ctx->state == BODY_CHUNK) {
423                     rv = ap_get_brigade(f->next, bb, AP_MODE_GETLINE,
424                                         block, 0);
425                     if (block == APR_NONBLOCK_READ &&
426                         ( (rv == APR_SUCCESS && APR_BRIGADE_EMPTY(bb)) ||
427                           (APR_STATUS_IS_EAGAIN(rv)) )) {
428                         return APR_EAGAIN;
429                     }
430                     /*
431                      * We really don't care whats on this line. If it is RFC
432                      * compliant it should be only \r\n. If there is more
433                      * before we just ignore it as long as we do not get over
434                      * the limit for request lines.
435                      */
436                     rv = get_remaining_chunk_line(ctx, bb,
437                                                   f->r->server->limit_req_line);
438                     apr_brigade_cleanup(bb);
439                     if (APR_STATUS_IS_EAGAIN(rv)) {
440                         return rv;
441                     }
442                 } else {
443                     rv = APR_SUCCESS;
444                 }
445
446                 if (rv == APR_SUCCESS) {
447                     /* Read the real chunk line. */
448                     rv = ap_get_brigade(f->next, bb, AP_MODE_GETLINE,
449                                         block, 0);
450                     /* Test timeout */
451                     if (block == APR_NONBLOCK_READ &&
452                         ( (rv == APR_SUCCESS && APR_BRIGADE_EMPTY(bb)) ||
453                           (APR_STATUS_IS_EAGAIN(rv)) )) {
454                         ctx->state = BODY_CHUNK_PART;
455                         return APR_EAGAIN;
456                     }
457                     ctx->state = BODY_CHUNK;
458                     if (rv == APR_SUCCESS) {
459                         rv = get_chunk_line(ctx, bb, f->r->server->limit_req_line);
460                         if (APR_STATUS_IS_EAGAIN(rv)) {
461                             ctx->state = BODY_CHUNK_PART;
462                             apr_brigade_cleanup(bb);
463                             return rv;
464                         }
465                         if (rv == APR_SUCCESS) {
466                             ctx->remaining = get_chunk_size(ctx->chunk_ln);
467                             if (ctx->remaining == INVALID_CHAR) {
468                                 rv = APR_EGENERAL;
469                                 http_error = HTTP_SERVICE_UNAVAILABLE;
470                             }
471                         }
472                     }
473                     apr_brigade_cleanup(bb);
474                 }
475
476                 /* Detect chunksize error (such as overflow) */
477                 if (rv != APR_SUCCESS || ctx->remaining < 0) {
478                     ctx->remaining = 0; /* Reset it in case we have to
479                                          * come back here later */
480                     bail_out_on_error(ctx, f, http_error);
481                     return rv;
482                 }
483
484                 if (!ctx->remaining) {
485                     /* Handle trailers by calling ap_get_mime_headers again! */
486                     ctx->state = BODY_NONE;
487                     ap_get_mime_headers(f->r);
488                     e = apr_bucket_eos_create(f->c->bucket_alloc);
489                     APR_BRIGADE_INSERT_TAIL(b, e);
490                     ctx->eos_sent = 1;
491                     return APR_SUCCESS;
492                 }
493             }
494             break;
495         }
496     }
497
498     /* Ensure that the caller can not go over our boundary point. */
499     if (ctx->state == BODY_LENGTH || ctx->state == BODY_CHUNK) {
500         if (ctx->remaining < readbytes) {
501             readbytes = ctx->remaining;
502         }
503         AP_DEBUG_ASSERT(readbytes > 0);
504     }
505
506     rv = ap_get_brigade(f->next, b, mode, block, readbytes);
507
508     if (rv != APR_SUCCESS) {
509         return rv;
510     }
511
512     /* How many bytes did we just read? */
513     apr_brigade_length(b, 0, &totalread);
514
515     /* If this happens, we have a bucket of unknown length.  Die because
516      * it means our assumptions have changed. */
517     AP_DEBUG_ASSERT(totalread >= 0);
518
519     if (ctx->state != BODY_NONE) {
520         ctx->remaining -= totalread;
521     }
522
523     /* If we have no more bytes remaining on a C-L request,
524      * save the callter a roundtrip to discover EOS.
525      */
526     if (ctx->state == BODY_LENGTH && ctx->remaining == 0) {
527         e = apr_bucket_eos_create(f->c->bucket_alloc);
528         APR_BRIGADE_INSERT_TAIL(b, e);
529     }
530
531     /* We have a limit in effect. */
532     if (ctx->limit) {
533         /* FIXME: Note that we might get slightly confused on chunked inputs
534          * as we'd need to compensate for the chunk lengths which may not
535          * really count.  This seems to be up for interpretation.  */
536         ctx->limit_used += totalread;
537         if (ctx->limit < ctx->limit_used) {
538             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, f->r,
539                           "Read content-length of %" APR_OFF_T_FMT
540                           " is larger than the configured limit"
541                           " of %" APR_OFF_T_FMT, ctx->limit_used, ctx->limit);
542             apr_brigade_cleanup(bb);
543             e = ap_bucket_error_create(HTTP_REQUEST_ENTITY_TOO_LARGE, NULL,
544                                        f->r->pool,
545                                        f->c->bucket_alloc);
546             APR_BRIGADE_INSERT_TAIL(bb, e);
547             e = apr_bucket_eos_create(f->c->bucket_alloc);
548             APR_BRIGADE_INSERT_TAIL(bb, e);
549             ctx->eos_sent = 1;
550             return ap_pass_brigade(f->r->output_filters, bb);
551         }
552     }
553
554     return APR_SUCCESS;
555 }
556
557 /**
558  * Parse a chunk extension, detect overflow.
559  * There are two error cases:
560  *  1) If the conversion would require too many bits, a -1 is returned.
561  *  2) If the conversion used the correct number of bits, but an overflow
562  *     caused only the sign bit to flip, then that negative number is
563  *     returned.
564  * In general, any negative number can be considered an overflow error.
565  */
566 static long get_chunk_size(char *b)
567 {
568     long chunksize = 0;
569     size_t chunkbits = sizeof(long) * 8;
570
571     ap_xlate_proto_from_ascii(b, strlen(b));
572
573     if (!apr_isxdigit(*b)) {
574         /*
575          * Detect invalid character at beginning. This also works for empty
576          * chunk size lines.
577          */
578         return INVALID_CHAR;
579     }
580     /* Skip leading zeros */
581     while (*b == '0') {
582         ++b;
583     }
584
585     while (apr_isxdigit(*b) && (chunkbits > 0)) {
586         int xvalue = 0;
587
588         if (*b >= '0' && *b <= '9') {
589             xvalue = *b - '0';
590         }
591         else if (*b >= 'A' && *b <= 'F') {
592             xvalue = *b - 'A' + 0xa;
593         }
594         else if (*b >= 'a' && *b <= 'f') {
595             xvalue = *b - 'a' + 0xa;
596         }
597
598         chunksize = (chunksize << 4) | xvalue;
599         chunkbits -= 4;
600         ++b;
601     }
602     if (apr_isxdigit(*b) && (chunkbits <= 0)) {
603         /* overflow */
604         return -1;
605     }
606
607     return chunksize;
608 }
609
610 typedef struct header_struct {
611     apr_pool_t *pool;
612     apr_bucket_brigade *bb;
613 } header_struct;
614
615 /* Send a single HTTP header field to the client.  Note that this function
616  * is used in calls to table_do(), so their interfaces are co-dependent.
617  * In other words, don't change this one without checking table_do in alloc.c.
618  * It returns true unless there was a write error of some kind.
619  */
620 static int form_header_field(header_struct *h,
621                              const char *fieldname, const char *fieldval)
622 {
623 #if APR_CHARSET_EBCDIC
624     char *headfield;
625     apr_size_t len;
626     apr_size_t name_len;
627     apr_size_t val_len;
628     char *next;
629
630     name_len = strlen(fieldname);
631     val_len = strlen(fieldval);
632     len = name_len + val_len + 4; /* 4 for ": " plus CRLF */
633     headfield = (char *)apr_palloc(h->pool, len + 1);
634     memcpy(headfield, fieldname, name_len);
635     next = headfield + name_len;
636     *next++ = ':';
637     *next++ = ' ';
638     memcpy(next, fieldval, val_len);
639     next += val_len;
640     *next++ = CR;
641     *next++ = LF;
642     *next = 0;
643     ap_xlate_proto_to_ascii(headfield, len);
644     apr_brigade_write(h->bb, NULL, NULL, headfield, len);
645 #else
646     struct iovec vec[4];
647     struct iovec *v = vec;
648     v->iov_base = (void *)fieldname;
649     v->iov_len = strlen(fieldname);
650     v++;
651     v->iov_base = ": ";
652     v->iov_len = sizeof(": ") - 1;
653     v++;
654     v->iov_base = (void *)fieldval;
655     v->iov_len = strlen(fieldval);
656     v++;
657     v->iov_base = CRLF;
658     v->iov_len = sizeof(CRLF) - 1;
659     apr_brigade_writev(h->bb, NULL, NULL, vec, 4);
660 #endif /* !APR_CHARSET_EBCDIC */
661     return 1;
662 }
663
664 /* This routine is called by apr_table_do and merges all instances of
665  * the passed field values into a single array that will be further
666  * processed by some later routine.  Originally intended to help split
667  * and recombine multiple Vary fields, though it is generic to any field
668  * consisting of comma/space-separated tokens.
669  */
670 static int uniq_field_values(void *d, const char *key, const char *val)
671 {
672     apr_array_header_t *values;
673     char *start;
674     char *e;
675     char **strpp;
676     int  i;
677
678     values = (apr_array_header_t *)d;
679
680     e = apr_pstrdup(values->pool, val);
681
682     do {
683         /* Find a non-empty fieldname */
684
685         while (*e == ',' || apr_isspace(*e)) {
686             ++e;
687         }
688         if (*e == '\0') {
689             break;
690         }
691         start = e;
692         while (*e != '\0' && *e != ',' && !apr_isspace(*e)) {
693             ++e;
694         }
695         if (*e != '\0') {
696             *e++ = '\0';
697         }
698
699         /* Now add it to values if it isn't already represented.
700          * Could be replaced by a ap_array_strcasecmp() if we had one.
701          */
702         for (i = 0, strpp = (char **) values->elts; i < values->nelts;
703              ++i, ++strpp) {
704             if (*strpp && strcasecmp(*strpp, start) == 0) {
705                 break;
706             }
707         }
708         if (i == values->nelts) {  /* if not found */
709             *(char **)apr_array_push(values) = start;
710         }
711     } while (*e != '\0');
712
713     return 1;
714 }
715
716 /*
717  * Since some clients choke violently on multiple Vary fields, or
718  * Vary fields with duplicate tokens, combine any multiples and remove
719  * any duplicates.
720  */
721 static void fixup_vary(request_rec *r)
722 {
723     apr_array_header_t *varies;
724
725     varies = apr_array_make(r->pool, 5, sizeof(char *));
726
727     /* Extract all Vary fields from the headers_out, separate each into
728      * its comma-separated fieldname values, and then add them to varies
729      * if not already present in the array.
730      */
731     apr_table_do((int (*)(void *, const char *, const char *))uniq_field_values,
732                  (void *) varies, r->headers_out, "Vary", NULL);
733
734     /* If we found any, replace old Vary fields with unique-ified value */
735
736     if (varies->nelts > 0) {
737         apr_table_setn(r->headers_out, "Vary",
738                        apr_array_pstrcat(r->pool, varies, ','));
739     }
740 }
741
742 /* Send a request's HTTP response headers to the client.
743  */
744 static apr_status_t send_all_header_fields(header_struct *h,
745                                            const request_rec *r)
746 {
747     const apr_array_header_t *elts;
748     const apr_table_entry_t *t_elt;
749     const apr_table_entry_t *t_end;
750     struct iovec *vec;
751     struct iovec *vec_next;
752
753     elts = apr_table_elts(r->headers_out);
754     if (elts->nelts == 0) {
755         return APR_SUCCESS;
756     }
757     t_elt = (const apr_table_entry_t *)(elts->elts);
758     t_end = t_elt + elts->nelts;
759     vec = (struct iovec *)apr_palloc(h->pool, 4 * elts->nelts *
760                                      sizeof(struct iovec));
761     vec_next = vec;
762
763     /* For each field, generate
764      *    name ": " value CRLF
765      */
766     do {
767         vec_next->iov_base = (void*)(t_elt->key);
768         vec_next->iov_len = strlen(t_elt->key);
769         vec_next++;
770         vec_next->iov_base = ": ";
771         vec_next->iov_len = sizeof(": ") - 1;
772         vec_next++;
773         vec_next->iov_base = (void*)(t_elt->val);
774         vec_next->iov_len = strlen(t_elt->val);
775         vec_next++;
776         vec_next->iov_base = CRLF;
777         vec_next->iov_len = sizeof(CRLF) - 1;
778         vec_next++;
779         t_elt++;
780     } while (t_elt < t_end);
781
782 #if APR_CHARSET_EBCDIC
783     {
784         apr_size_t len;
785         char *tmp = apr_pstrcatv(r->pool, vec, vec_next - vec, &len);
786         ap_xlate_proto_to_ascii(tmp, len);
787         return apr_brigade_write(h->bb, NULL, NULL, tmp, len);
788     }
789 #else
790     return apr_brigade_writev(h->bb, NULL, NULL, vec, vec_next - vec);
791 #endif
792 }
793
794 /* Confirm that the status line is well-formed and matches r->status.
795  * If they don't match, a filter may have negated the status line set by a
796  * handler.
797  * Zap r->status_line if bad.
798  */
799 static void validate_status_line(request_rec *r)
800 {
801     char *end;
802
803     if (r->status_line
804         && (strlen(r->status_line) <= 4
805             || apr_strtoi64(r->status_line, &end, 10) != r->status
806             || *end != ' '
807             || (end - 3) != r->status_line)) {
808         r->status_line = NULL;
809     }
810 }
811
812 /*
813  * Determine the protocol to use for the response. Potentially downgrade
814  * to HTTP/1.0 in some situations and/or turn off keepalives.
815  *
816  * also prepare r->status_line.
817  */
818 static void basic_http_header_check(request_rec *r,
819                                     const char **protocol)
820 {
821     if (r->assbackwards) {
822         /* no such thing as a response protocol */
823         return;
824     }
825
826     validate_status_line(r);
827
828     if (!r->status_line) {
829         r->status_line = ap_get_status_line(r->status);
830     }
831
832     /* Note that we must downgrade before checking for force responses. */
833     if (r->proto_num > HTTP_VERSION(1,0)
834         && apr_table_get(r->subprocess_env, "downgrade-1.0")) {
835         r->proto_num = HTTP_VERSION(1,0);
836     }
837
838     /* kludge around broken browsers when indicated by force-response-1.0
839      */
840     if (r->proto_num == HTTP_VERSION(1,0)
841         && apr_table_get(r->subprocess_env, "force-response-1.0")) {
842         *protocol = "HTTP/1.0";
843         r->connection->keepalive = AP_CONN_CLOSE;
844     }
845     else {
846         *protocol = AP_SERVER_PROTOCOL;
847     }
848
849 }
850
851 /* fill "bb" with a barebones/initial HTTP response header */
852 static void basic_http_header(request_rec *r, apr_bucket_brigade *bb,
853                               const char *protocol)
854 {
855     char *date;
856     const char *server;
857     header_struct h;
858     struct iovec vec[4];
859
860     if (r->assbackwards) {
861         /* there are no headers to send */
862         return;
863     }
864
865     /* Output the HTTP/1.x Status-Line and the Date and Server fields */
866
867     vec[0].iov_base = (void *)protocol;
868     vec[0].iov_len  = strlen(protocol);
869     vec[1].iov_base = (void *)" ";
870     vec[1].iov_len  = sizeof(" ") - 1;
871     vec[2].iov_base = (void *)(r->status_line);
872     vec[2].iov_len  = strlen(r->status_line);
873     vec[3].iov_base = (void *)CRLF;
874     vec[3].iov_len  = sizeof(CRLF) - 1;
875 #if APR_CHARSET_EBCDIC
876     {
877         char *tmp;
878         apr_size_t len;
879         tmp = apr_pstrcatv(r->pool, vec, 4, &len);
880         ap_xlate_proto_to_ascii(tmp, len);
881         apr_brigade_write(bb, NULL, NULL, tmp, len);
882     }
883 #else
884     apr_brigade_writev(bb, NULL, NULL, vec, 4);
885 #endif
886
887     h.pool = r->pool;
888     h.bb = bb;
889
890     /*
891      * keep the set-by-proxy server and date headers, otherwise
892      * generate a new server header / date header
893      */
894     if (r->proxyreq != PROXYREQ_NONE) {
895         const char *proxy_date;
896
897         proxy_date = apr_table_get(r->headers_out, "Date");
898         if (!proxy_date) {
899             /*
900              * proxy_date needs to be const. So use date for the creation of
901              * our own Date header and pass it over to proxy_date later to
902              * avoid a compiler warning.
903              */
904             date = apr_palloc(r->pool, APR_RFC822_DATE_LEN);
905             ap_recent_rfc822_date(date, r->request_time);
906             proxy_date = date;
907         }
908         form_header_field(&h, "Date", proxy_date);
909         server = apr_table_get(r->headers_out, "Server");
910         if (server) {
911             form_header_field(&h, "Server", server);
912         } else {
913             form_header_field(&h, "Server", ap_get_server_banner());
914         }
915     }
916     else {
917         date = apr_palloc(r->pool, APR_RFC822_DATE_LEN);
918         ap_recent_rfc822_date(date, r->request_time);
919         form_header_field(&h, "Date", date);
920         form_header_field(&h, "Server", ap_get_server_banner());
921     }
922
923     /* unset so we don't send them again */
924     apr_table_unset(r->headers_out, "Date");        /* Avoid bogosity */
925     apr_table_unset(r->headers_out, "Server");
926 }
927
928 AP_DECLARE(void) ap_basic_http_header(request_rec *r, apr_bucket_brigade *bb)
929 {
930     const char *protocol;
931
932     basic_http_header_check(r, &protocol);
933     basic_http_header(r, bb, protocol);
934 }
935
936 /* Navigator versions 2.x, 3.x and 4.0 betas up to and including 4.0b2
937  * have a header parsing bug.  If the terminating \r\n occur starting
938  * at offset 256, 257 or 258 of output then it will not properly parse
939  * the headers.  Curiously it doesn't exhibit this problem at 512, 513.
940  * We are guessing that this is because their initial read of a new request
941  * uses a 256 byte buffer, and subsequent reads use a larger buffer.
942  * So the problem might exist at different offsets as well.
943  *
944  * This should also work on keepalive connections assuming they use the
945  * same small buffer for the first read of each new request.
946  *
947  * At any rate, we check the bytes written so far and, if we are about to
948  * tickle the bug, we instead insert a bogus padding header.  Since the bug
949  * manifests as a broken image in Navigator, users blame the server.  :(
950  * It is more expensive to check the User-Agent than it is to just add the
951  * bytes, so we haven't used the BrowserMatch feature here.
952  */
953 static void terminate_header(apr_bucket_brigade *bb)
954 {
955     char tmp[] = "X-Pad: avoid browser bug" CRLF;
956     char crlf[] = CRLF;
957     apr_off_t len;
958     apr_size_t buflen;
959
960     (void) apr_brigade_length(bb, 1, &len);
961
962     if (len >= 255 && len <= 257) {
963         buflen = strlen(tmp);
964         ap_xlate_proto_to_ascii(tmp, buflen);
965         apr_brigade_write(bb, NULL, NULL, tmp, buflen);
966     }
967     buflen = strlen(crlf);
968     ap_xlate_proto_to_ascii(crlf, buflen);
969     apr_brigade_write(bb, NULL, NULL, crlf, buflen);
970 }
971
972 AP_DECLARE_NONSTD(int) ap_send_http_trace(request_rec *r)
973 {
974     core_server_config *conf;
975     int rv;
976     apr_bucket_brigade *bb;
977     header_struct h;
978     apr_bucket *b;
979     int body;
980     char *bodyread = NULL, *bodyoff;
981     apr_size_t bodylen = 0;
982     apr_size_t bodybuf;
983     long res = -1; /* init to avoid gcc -Wall warning */
984
985     if (r->method_number != M_TRACE) {
986         return DECLINED;
987     }
988
989     /* Get the original request */
990     while (r->prev) {
991         r = r->prev;
992     }
993     conf = (core_server_config *)ap_get_module_config(r->server->module_config,
994                                                       &core_module);
995
996     if (conf->trace_enable == AP_TRACE_DISABLE) {
997         apr_table_setn(r->notes, "error-notes",
998                       "TRACE denied by server configuration");
999         return HTTP_METHOD_NOT_ALLOWED;
1000     }
1001
1002     if (conf->trace_enable == AP_TRACE_EXTENDED)
1003         /* XX should be = REQUEST_CHUNKED_PASS */
1004         body = REQUEST_CHUNKED_DECHUNK;
1005     else
1006         body = REQUEST_NO_BODY;
1007
1008     if ((rv = ap_setup_client_block(r, body))) {
1009         if (rv == HTTP_REQUEST_ENTITY_TOO_LARGE)
1010             apr_table_setn(r->notes, "error-notes",
1011                           "TRACE with a request body is not allowed");
1012         return rv;
1013     }
1014
1015     if (ap_should_client_block(r)) {
1016
1017         if (r->remaining > 0) {
1018             if (r->remaining > 65536) {
1019                 apr_table_setn(r->notes, "error-notes",
1020                        "Extended TRACE request bodies cannot exceed 64k\n");
1021                 return HTTP_REQUEST_ENTITY_TOO_LARGE;
1022             }
1023             /* always 32 extra bytes to catch chunk header exceptions */
1024             bodybuf = (apr_size_t)r->remaining + 32;
1025         }
1026         else {
1027             /* Add an extra 8192 for chunk headers */
1028             bodybuf = 73730;
1029         }
1030
1031         bodyoff = bodyread = apr_palloc(r->pool, bodybuf);
1032
1033         /* only while we have enough for a chunked header */
1034         while ((!bodylen || bodybuf >= 32) &&
1035                (res = ap_get_client_block(r, bodyoff, bodybuf)) > 0) {
1036             bodylen += res;
1037             bodybuf -= res;
1038             bodyoff += res;
1039         }
1040         if (res > 0 && bodybuf < 32) {
1041             /* discard_rest_of_request_body into our buffer */
1042             while (ap_get_client_block(r, bodyread, bodylen) > 0)
1043                 ;
1044             apr_table_setn(r->notes, "error-notes",
1045                    "Extended TRACE request bodies cannot exceed 64k\n");
1046             return HTTP_REQUEST_ENTITY_TOO_LARGE;
1047         }
1048
1049         if (res < 0) {
1050             return HTTP_BAD_REQUEST;
1051         }
1052     }
1053
1054     ap_set_content_type(r, "message/http");
1055
1056     /* Now we recreate the request, and echo it back */
1057
1058     bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1059     apr_brigade_putstrs(bb, NULL, NULL, r->the_request, CRLF, NULL);
1060     h.pool = r->pool;
1061     h.bb = bb;
1062     apr_table_do((int (*) (void *, const char *, const char *))
1063                  form_header_field, (void *) &h, r->headers_in, NULL);
1064     apr_brigade_puts(bb, NULL, NULL, CRLF);
1065
1066     /* If configured to accept a body, echo the body */
1067     if (bodylen) {
1068         b = apr_bucket_pool_create(bodyread, bodylen,
1069                                    r->pool, bb->bucket_alloc);
1070         APR_BRIGADE_INSERT_TAIL(bb, b);
1071     }
1072
1073     ap_pass_brigade(r->output_filters,  bb);
1074
1075     return DONE;
1076 }
1077
1078 typedef struct header_filter_ctx {
1079     int headers_sent;
1080 } header_filter_ctx;
1081
1082 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_http_header_filter(ap_filter_t *f,
1083                                                            apr_bucket_brigade *b)
1084 {
1085     request_rec *r = f->r;
1086     conn_rec *c = r->connection;
1087     const char *clheader;
1088     const char *protocol;
1089     apr_bucket *e;
1090     apr_bucket_brigade *b2;
1091     header_struct h;
1092     header_filter_ctx *ctx = f->ctx;
1093     const char *ctype;
1094
1095     AP_DEBUG_ASSERT(!r->main);
1096
1097     if (r->header_only) {
1098         if (!ctx) {
1099             ctx = f->ctx = apr_pcalloc(r->pool, sizeof(header_filter_ctx));
1100         }
1101         else if (ctx->headers_sent) {
1102             apr_brigade_destroy(b);
1103             return OK;
1104         }
1105     }
1106
1107     for (e = APR_BRIGADE_FIRST(b);
1108          e != APR_BRIGADE_SENTINEL(b);
1109          e = APR_BUCKET_NEXT(e))
1110     {
1111         if (AP_BUCKET_IS_ERROR(e)) {
1112             ap_bucket_error *eb = e->data;
1113
1114             ap_die(eb->status, r);
1115             return AP_FILTER_ERROR;
1116         }
1117     }
1118
1119     if (r->assbackwards) {
1120         r->sent_bodyct = 1;
1121         ap_remove_output_filter(f);
1122         return ap_pass_brigade(f->next, b);
1123     }
1124
1125     /*
1126      * Now that we are ready to send a response, we need to combine the two
1127      * header field tables into a single table.  If we don't do this, our
1128      * later attempts to set or unset a given fieldname might be bypassed.
1129      */
1130     if (!apr_is_empty_table(r->err_headers_out)) {
1131         r->headers_out = apr_table_overlay(r->pool, r->err_headers_out,
1132                                            r->headers_out);
1133     }
1134
1135     /*
1136      * Remove the 'Vary' header field if the client can't handle it.
1137      * Since this will have nasty effects on HTTP/1.1 caches, force
1138      * the response into HTTP/1.0 mode.
1139      *
1140      * Note: the force-response-1.0 should come before the call to
1141      *       basic_http_header_check()
1142      */
1143     if (apr_table_get(r->subprocess_env, "force-no-vary") != NULL) {
1144         apr_table_unset(r->headers_out, "Vary");
1145         r->proto_num = HTTP_VERSION(1,0);
1146         apr_table_set(r->subprocess_env, "force-response-1.0", "1");
1147     }
1148     else {
1149         fixup_vary(r);
1150     }
1151
1152     /*
1153      * Now remove any ETag response header field if earlier processing
1154      * says so (such as a 'FileETag None' directive).
1155      */
1156     if (apr_table_get(r->notes, "no-etag") != NULL) {
1157         apr_table_unset(r->headers_out, "ETag");
1158     }
1159
1160     /* determine the protocol and whether we should use keepalives. */
1161     basic_http_header_check(r, &protocol);
1162     ap_set_keepalive(r);
1163
1164     if (r->chunked) {
1165         apr_table_mergen(r->headers_out, "Transfer-Encoding", "chunked");
1166         apr_table_unset(r->headers_out, "Content-Length");
1167     }
1168
1169     ctype = ap_make_content_type(r, r->content_type);
1170     if (strcasecmp(ctype, NO_CONTENT_TYPE)) {
1171         apr_table_setn(r->headers_out, "Content-Type", ctype);
1172     }
1173
1174     if (r->content_encoding) {
1175         apr_table_setn(r->headers_out, "Content-Encoding",
1176                        r->content_encoding);
1177     }
1178
1179     if (!apr_is_empty_array(r->content_languages)) {
1180         int i;
1181         char *token;
1182         char **languages = (char **)(r->content_languages->elts);
1183         const char *field = apr_table_get(r->headers_out, "Content-Language");
1184
1185         while (field && (token = ap_get_list_item(r->pool, &field)) != NULL) {
1186             for (i = 0; i < r->content_languages->nelts; ++i) {
1187                 if (!strcasecmp(token, languages[i]))
1188                     break;
1189             }
1190             if (i == r->content_languages->nelts) {
1191                 *((char **) apr_array_push(r->content_languages)) = token;
1192             }
1193         }
1194
1195         field = apr_array_pstrcat(r->pool, r->content_languages, ',');
1196         apr_table_setn(r->headers_out, "Content-Language", field);
1197     }
1198
1199     /*
1200      * Control cachability for non-cachable responses if not already set by
1201      * some other part of the server configuration.
1202      */
1203     if (r->no_cache && !apr_table_get(r->headers_out, "Expires")) {
1204         char *date = apr_palloc(r->pool, APR_RFC822_DATE_LEN);
1205         ap_recent_rfc822_date(date, r->request_time);
1206         apr_table_addn(r->headers_out, "Expires", date);
1207     }
1208
1209     /* This is a hack, but I can't find anyway around it.  The idea is that
1210      * we don't want to send out 0 Content-Lengths if it is a head request.
1211      * This happens when modules try to outsmart the server, and return
1212      * if they see a HEAD request.  Apache 1.3 handlers were supposed to
1213      * just return in that situation, and the core handled the HEAD.  In
1214      * 2.0, if a handler returns, then the core sends an EOS bucket down
1215      * the filter stack, and the content-length filter computes a C-L of
1216      * zero and that gets put in the headers, and we end up sending a
1217      * zero C-L to the client.  We can't just remove the C-L filter,
1218      * because well behaved 2.0 handlers will send their data down the stack,
1219      * and we will compute a real C-L for the head request. RBB
1220      */
1221     if (r->header_only
1222         && (clheader = apr_table_get(r->headers_out, "Content-Length"))
1223         && !strcmp(clheader, "0")) {
1224         apr_table_unset(r->headers_out, "Content-Length");
1225     }
1226
1227     b2 = apr_brigade_create(r->pool, c->bucket_alloc);
1228     basic_http_header(r, b2, protocol);
1229
1230     h.pool = r->pool;
1231     h.bb = b2;
1232
1233     if (r->status == HTTP_NOT_MODIFIED) {
1234         apr_table_do((int (*)(void *, const char *, const char *)) form_header_field,
1235                      (void *) &h, r->headers_out,
1236                      "Connection",
1237                      "Keep-Alive",
1238                      "ETag",
1239                      "Content-Location",
1240                      "Expires",
1241                      "Cache-Control",
1242                      "Vary",
1243                      "Warning",
1244                      "WWW-Authenticate",
1245                      "Proxy-Authenticate",
1246                      "Set-Cookie",
1247                      "Set-Cookie2",
1248                      NULL);
1249     }
1250     else {
1251         send_all_header_fields(&h, r);
1252     }
1253
1254     terminate_header(b2);
1255
1256     ap_pass_brigade(f->next, b2);
1257
1258     if (r->header_only) {
1259         apr_brigade_destroy(b);
1260         ctx->headers_sent = 1;
1261         return OK;
1262     }
1263
1264     r->sent_bodyct = 1;         /* Whatever follows is real body stuff... */
1265
1266     if (r->chunked) {
1267         /* We can't add this filter until we have already sent the headers.
1268          * If we add it before this point, then the headers will be chunked
1269          * as well, and that is just wrong.
1270          */
1271         ap_add_output_filter("CHUNK", NULL, r, r->connection);
1272     }
1273
1274     /* Don't remove this filter until after we have added the CHUNK filter.
1275      * Otherwise, f->next won't be the CHUNK filter and thus the first
1276      * brigade won't be chunked properly.
1277      */
1278     ap_remove_output_filter(f);
1279     return ap_pass_brigade(f->next, b);
1280 }
1281
1282 /* In HTTP/1.1, any method can have a body.  However, most GET handlers
1283  * wouldn't know what to do with a request body if they received one.
1284  * This helper routine tests for and reads any message body in the request,
1285  * simply discarding whatever it receives.  We need to do this because
1286  * failing to read the request body would cause it to be interpreted
1287  * as the next request on a persistent connection.
1288  *
1289  * Since we return an error status if the request is malformed, this
1290  * routine should be called at the beginning of a no-body handler, e.g.,
1291  *
1292  *    if ((retval = ap_discard_request_body(r)) != OK) {
1293  *        return retval;
1294  *    }
1295  */
1296 AP_DECLARE(int) ap_discard_request_body(request_rec *r)
1297 {
1298     apr_bucket_brigade *bb, *kept_body = NULL;
1299     apr_bucket *e;
1300     int rv, seen_eos;
1301     core_dir_conf *dconf;
1302     apr_off_t left = 0;
1303
1304     /* Sometimes we'll get in a state where the input handling has
1305      * detected an error where we want to drop the connection, so if
1306      * that's the case, don't read the data as that is what we're trying
1307      * to avoid.
1308      *
1309      * This function is also a no-op on a subrequest.
1310      */
1311     if (r->main || r->connection->keepalive == AP_CONN_CLOSE ||
1312         ap_status_drops_connection(r->status)) {
1313         return OK;
1314     }
1315
1316     /* We may want to save this body away if the administrator has
1317      * asked us to do so for this directory. This allows the body
1318      * to be reexamined by filters such as mod_include, even though
1319      * the main request has no need for this body.
1320      */
1321     if (!r->kept_body) {
1322         dconf = ap_get_module_config(r->per_dir_config,
1323                                      &http_module);
1324         if (dconf->keep_body > 0) {
1325             left = dconf->keep_body;
1326             kept_body = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1327         }
1328     }
1329
1330     bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1331     seen_eos = 0;
1332     do {
1333         apr_bucket *bucket;
1334
1335         rv = ap_get_brigade(r->input_filters, bb, AP_MODE_READBYTES,
1336                             APR_BLOCK_READ, HUGE_STRING_LEN);
1337
1338         if (rv != APR_SUCCESS) {
1339             /* FIXME: If we ever have a mapping from filters (apr_status_t)
1340              * to HTTP error codes, this would be a good place for them.
1341              *
1342              * If we received the special case AP_FILTER_ERROR, it means
1343              * that the filters have already handled this error.
1344              * Otherwise, we should assume we have a bad request.
1345              */
1346             if (rv == AP_FILTER_ERROR) {
1347                 apr_brigade_destroy(bb);
1348                 return rv;
1349             }
1350             else {
1351                 apr_brigade_destroy(bb);
1352                 return HTTP_BAD_REQUEST;
1353             }
1354         }
1355
1356         for (bucket = APR_BRIGADE_FIRST(bb);
1357              bucket != APR_BRIGADE_SENTINEL(bb);
1358              bucket = APR_BUCKET_NEXT(bucket))
1359         {
1360             const char *data;
1361             apr_size_t len;
1362
1363             if (APR_BUCKET_IS_EOS(bucket)) {
1364                 seen_eos = 1;
1365                 break;
1366             }
1367
1368             /* These are metadata buckets. */
1369             if (bucket->length == 0) {
1370                 continue;
1371             }
1372
1373             /* We MUST read because in case we have an unknown-length
1374              * bucket or one that morphs, we want to exhaust it.
1375              */
1376             rv = apr_bucket_read(bucket, &data, &len, APR_BLOCK_READ);
1377             if (rv != APR_SUCCESS) {
1378                 apr_brigade_destroy(bb);
1379                 return HTTP_BAD_REQUEST;
1380             }
1381
1382             /* If we have been asked to, keep the data up until the
1383              * configured limit. If the limit is exceeded, we return an
1384              * HTTP_REQUEST_ENTITY_TOO_LARGE response so the caller is
1385              * clear the server couldn't handle their request.
1386              */
1387             if (kept_body) {
1388                 if (len <= left) {
1389                     apr_bucket_copy(bucket, &e);
1390                     APR_BRIGADE_INSERT_TAIL(kept_body, e);
1391                     left -= len;
1392                 }
1393                 else {
1394                     apr_brigade_destroy(bb);
1395                     apr_brigade_destroy(kept_body);
1396                     return HTTP_REQUEST_ENTITY_TOO_LARGE;
1397                 }
1398             }
1399             
1400         }
1401         apr_brigade_cleanup(bb);
1402     } while (!seen_eos);
1403
1404     if (kept_body) {
1405         r->kept_body = kept_body;
1406     }
1407
1408     return OK;
1409 }
1410
1411 /* Here we deal with getting the request message body from the client.
1412  * Whether or not the request contains a body is signaled by the presence
1413  * of a non-zero Content-Length or by a Transfer-Encoding: chunked.
1414  *
1415  * Note that this is more complicated than it was in Apache 1.1 and prior
1416  * versions, because chunked support means that the module does less.
1417  *
1418  * The proper procedure is this:
1419  *
1420  * 1. Call ap_setup_client_block() near the beginning of the request
1421  *    handler. This will set up all the necessary properties, and will
1422  *    return either OK, or an error code. If the latter, the module should
1423  *    return that error code. The second parameter selects the policy to
1424  *    apply if the request message indicates a body, and how a chunked
1425  *    transfer-coding should be interpreted. Choose one of
1426  *
1427  *    REQUEST_NO_BODY          Send 413 error if message has any body
1428  *    REQUEST_CHUNKED_ERROR    Send 411 error if body without Content-Length
1429  *    REQUEST_CHUNKED_DECHUNK  If chunked, remove the chunks for me.
1430  *    REQUEST_CHUNKED_PASS     If chunked, pass the chunk headers with body.
1431  *
1432  *    In order to use the last two options, the caller MUST provide a buffer
1433  *    large enough to hold a chunk-size line, including any extensions.
1434  *
1435  * 2. When you are ready to read a body (if any), call ap_should_client_block().
1436  *    This will tell the module whether or not to read input. If it is 0,
1437  *    the module should assume that there is no message body to read.
1438  *
1439  * 3. Finally, call ap_get_client_block in a loop. Pass it a buffer and its size.
1440  *    It will put data into the buffer (not necessarily a full buffer), and
1441  *    return the length of the input block. When it is done reading, it will
1442  *    return 0 if EOF, or -1 if there was an error.
1443  *    If an error occurs on input, we force an end to keepalive.
1444  *
1445  *    This step also sends a 100 Continue response to HTTP/1.1 clients if appropriate.
1446  */
1447
1448 AP_DECLARE(int) ap_setup_client_block(request_rec *r, int read_policy)
1449 {
1450     const char *tenc = apr_table_get(r->headers_in, "Transfer-Encoding");
1451     const char *lenp = apr_table_get(r->headers_in, "Content-Length");
1452
1453     r->read_body = read_policy;
1454     r->read_chunked = 0;
1455     r->remaining = 0;
1456
1457     if (tenc) {
1458         if (strcasecmp(tenc, "chunked")) {
1459             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1460                           "Unknown Transfer-Encoding %s", tenc);
1461             return HTTP_NOT_IMPLEMENTED;
1462         }
1463         if (r->read_body == REQUEST_CHUNKED_ERROR) {
1464             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1465                           "chunked Transfer-Encoding forbidden: %s", r->uri);
1466             return (lenp) ? HTTP_BAD_REQUEST : HTTP_LENGTH_REQUIRED;
1467         }
1468
1469         r->read_chunked = 1;
1470     }
1471     else if (lenp) {
1472         char *endstr;
1473
1474         if (apr_strtoff(&r->remaining, lenp, &endstr, 10)
1475             || *endstr || r->remaining < 0) {
1476             r->remaining = 0;
1477             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1478                           "Invalid Content-Length");
1479             return HTTP_BAD_REQUEST;
1480         }
1481     }
1482
1483     if ((r->read_body == REQUEST_NO_BODY)
1484         && (r->read_chunked || (r->remaining > 0))) {
1485         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1486                       "%s with body is not allowed for %s", r->method, r->uri);
1487         return HTTP_REQUEST_ENTITY_TOO_LARGE;
1488     }
1489
1490 #ifdef AP_DEBUG
1491     {
1492         /* Make sure ap_getline() didn't leave any droppings. */
1493         core_request_config *req_cfg =
1494             (core_request_config *)ap_get_module_config(r->request_config,
1495                                                         &core_module);
1496         AP_DEBUG_ASSERT(APR_BRIGADE_EMPTY(req_cfg->bb));
1497     }
1498 #endif
1499
1500     return OK;
1501 }
1502
1503 AP_DECLARE(int) ap_should_client_block(request_rec *r)
1504 {
1505     /* First check if we have already read the request body */
1506
1507     if (r->read_length || (!r->read_chunked && (r->remaining <= 0))) {
1508         return 0;
1509     }
1510
1511     return 1;
1512 }
1513
1514 /* get_client_block is called in a loop to get the request message body.
1515  * This is quite simple if the client includes a content-length
1516  * (the normal case), but gets messy if the body is chunked. Note that
1517  * r->remaining is used to maintain state across calls and that
1518  * r->read_length is the total number of bytes given to the caller
1519  * across all invocations.  It is messy because we have to be careful not
1520  * to read past the data provided by the client, since these reads block.
1521  * Returns 0 on End-of-body, -1 on error or premature chunk end.
1522  *
1523  */
1524 AP_DECLARE(long) ap_get_client_block(request_rec *r, char *buffer,
1525                                      apr_size_t bufsiz)
1526 {
1527     apr_status_t rv;
1528     apr_bucket_brigade *bb;
1529
1530     if (r->remaining < 0 || (!r->read_chunked && r->remaining == 0)) {
1531         return 0;
1532     }
1533
1534     bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1535     if (bb == NULL) {
1536         r->connection->keepalive = AP_CONN_CLOSE;
1537         return -1;
1538     }
1539
1540     rv = ap_get_brigade(r->input_filters, bb, AP_MODE_READBYTES,
1541                         APR_BLOCK_READ, bufsiz);
1542
1543     /* We lose the failure code here.  This is why ap_get_client_block should
1544      * not be used.
1545      */
1546     if (rv != APR_SUCCESS) {
1547         /* if we actually fail here, we want to just return and
1548          * stop trying to read data from the client.
1549          */
1550         r->connection->keepalive = AP_CONN_CLOSE;
1551         apr_brigade_destroy(bb);
1552         return -1;
1553     }
1554
1555     /* If this fails, it means that a filter is written incorrectly and that
1556      * it needs to learn how to properly handle APR_BLOCK_READ requests by
1557      * returning data when requested.
1558      */
1559     AP_DEBUG_ASSERT(!APR_BRIGADE_EMPTY(bb));
1560
1561     /* Check to see if EOS in the brigade.
1562      *
1563      * If so, we have to leave a nugget for the *next* ap_get_client_block
1564      * call to return 0.
1565      */
1566     if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
1567         if (r->read_chunked) {
1568             r->remaining = -1;
1569         }
1570         else {
1571             r->remaining = 0;
1572         }
1573     }
1574
1575     rv = apr_brigade_flatten(bb, buffer, &bufsiz);
1576     if (rv != APR_SUCCESS) {
1577         apr_brigade_destroy(bb);
1578         return -1;
1579     }
1580
1581     /* XXX yank me? */
1582     r->read_length += bufsiz;
1583
1584     apr_brigade_destroy(bb);
1585     return bufsiz;
1586 }
1587
1588 /* Filter to handle any error buckets on output */
1589 apr_status_t ap_http_outerror_filter(ap_filter_t *f,
1590                                      apr_bucket_brigade *b)
1591 {
1592     request_rec *r = f->r;
1593     apr_bucket *e;
1594
1595     for (e = APR_BRIGADE_FIRST(b);
1596          e != APR_BRIGADE_SENTINEL(b);
1597          e = APR_BUCKET_NEXT(e))
1598     {
1599         if (AP_BUCKET_IS_ERROR(e)) {
1600             /*
1601              * Start of error handling state tree. Just one condition
1602              * right now :)
1603              */
1604             if (((ap_bucket_error *)(e->data))->status == HTTP_BAD_GATEWAY) {
1605                 /* stream aborted and we have not ended it yet */
1606                 r->connection->keepalive = AP_CONN_CLOSE;
1607             }
1608         }
1609     }
1610
1611     return ap_pass_brigade(f->next,  b);
1612 }
1613
1614 typedef struct kept_body_filter_ctx {
1615     apr_off_t offset;
1616     apr_off_t remaining;
1617 } kept_body_ctx_t;
1618
1619 /**
1620  * Initialisation of filter to handle a kept body on subrequests.
1621  * 
1622  * If a body is to be reinserted into a subrequest, any chunking will have
1623  * been removed from the body during storage. We need to change the request
1624  * from Transfer-Encoding: chunked to an explicit Content-Length.
1625  */
1626 int ap_kept_body_filter_init(ap_filter_t *f) {
1627     apr_off_t length = 0;
1628     request_rec *r = f->r;
1629     apr_bucket_brigade *kept_body = r->kept_body;
1630
1631     if (kept_body) {
1632         apr_table_unset(r->headers_in, "Transfer-Encoding");
1633         apr_brigade_length(kept_body, 1, &length);
1634         apr_table_set(r->headers_in, "Content-Length", apr_off_t_toa(r->pool, length));
1635     }
1636
1637     return OK;
1638 }
1639
1640 /**
1641  * Filter to handle a kept body on subrequests.
1642  * 
1643  * If a body has been previously kept by the request, and if a subrequest wants
1644  * to re-insert the body into the request, this input filter makes it happen.
1645  */
1646 apr_status_t ap_kept_body_filter(ap_filter_t *f, apr_bucket_brigade *b,
1647                                  ap_input_mode_t mode, apr_read_type_e block,
1648                                  apr_off_t readbytes) {
1649     request_rec *r = f->r;
1650     apr_bucket_brigade *kept_body = r->kept_body;
1651     kept_body_ctx_t *ctx = f->ctx;
1652     apr_bucket *ec, *e2;
1653     apr_status_t rv;
1654
1655     /* just get out of the way of things we don't want. */
1656     if (!kept_body || (mode != AP_MODE_READBYTES && mode != AP_MODE_GETLINE)) {
1657         return ap_get_brigade(f->next, b, mode, block, readbytes);
1658     }
1659
1660     /* set up the context if it does not already exist */
1661     if (!ctx) {
1662         f->ctx = ctx = apr_palloc(f->r->pool, sizeof(*ctx));
1663         ctx->offset = 0;
1664         apr_brigade_length(kept_body, 1, &ctx->remaining);
1665     }
1666
1667     /* kept_body is finished, send next filter */
1668     if (ctx->remaining <= 0) {
1669         return ap_get_brigade(f->next, b, mode, block, readbytes);
1670     }
1671
1672     /* send all of the kept_body, but no more */
1673     if (readbytes > ctx->remaining) {
1674         readbytes = ctx->remaining;
1675     }
1676
1677     /* send part of the kept_body */
1678     if ((rv = apr_brigade_partition(kept_body, ctx->offset, &ec)) != APR_SUCCESS) {
1679         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1680                       "apr_brigade_partition() failed on kept_body at %" APR_OFF_T_FMT, ctx->offset);
1681         return rv;
1682     }
1683     if ((rv = apr_brigade_partition(kept_body, ctx->offset + readbytes, &e2)) != APR_SUCCESS) {
1684         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1685                       "apr_brigade_partition() failed on kept_body at %" APR_OFF_T_FMT, ctx->offset + readbytes);
1686         return rv;
1687     }
1688  
1689     do {
1690         apr_bucket *foo;
1691         const char *str;
1692         apr_size_t len;
1693
1694         if (apr_bucket_copy(ec, &foo) != APR_SUCCESS) {
1695             /* As above; this should not fail since the bucket has
1696              * a known length, but just to be sure, this takes
1697              * care of uncopyable buckets that do somehow manage
1698              * to slip through.  */
1699             /* XXX: check for failure? */
1700             apr_bucket_read(ec, &str, &len, APR_BLOCK_READ);
1701             apr_bucket_copy(ec, &foo);
1702         }
1703         APR_BRIGADE_INSERT_TAIL(b, foo);
1704         ec = APR_BUCKET_NEXT(ec);
1705     } while (ec != e2);
1706
1707     ctx->remaining -= readbytes;
1708     ctx->offset += readbytes;
1709     return APR_SUCCESS;
1710
1711 }