]> granicus.if.org Git - apache/blob - server/protocol.c
* Only log a 408 if it is no keepalive timeout.
[apache] / server / protocol.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  * protocol.c --- routines which directly communicate with the client.
19  *
20  * Code originally by Rob McCool; much redone by Robert S. Thau
21  * and the Apache Software Foundation.
22  */
23
24 #include "apr.h"
25 #include "apr_strings.h"
26 #include "apr_buckets.h"
27 #include "apr_lib.h"
28 #include "apr_signal.h"
29 #include "apr_strmatch.h"
30
31 #define APR_WANT_STDIO          /* for sscanf */
32 #define APR_WANT_STRFUNC
33 #define APR_WANT_MEMFUNC
34 #include "apr_want.h"
35
36 #include "util_filter.h"
37 #include "ap_config.h"
38 #include "httpd.h"
39 #include "http_config.h"
40 #include "http_core.h"
41 #include "http_protocol.h"
42 #include "http_main.h"
43 #include "http_request.h"
44 #include "http_vhost.h"
45 #include "http_log.h"           /* For errors detected in basic auth common
46                                  * support code... */
47 #include "mod_core.h"
48 #include "util_charset.h"
49 #include "util_ebcdic.h"
50 #include "scoreboard.h"
51
52 #if APR_HAVE_STDARG_H
53 #include <stdarg.h>
54 #endif
55 #if APR_HAVE_UNISTD_H
56 #include <unistd.h>
57 #endif
58
59
60 APR_HOOK_STRUCT(
61     APR_HOOK_LINK(post_read_request)
62     APR_HOOK_LINK(log_transaction)
63     APR_HOOK_LINK(http_scheme)
64     APR_HOOK_LINK(default_port)
65 )
66
67 AP_DECLARE_DATA ap_filter_rec_t *ap_old_write_func = NULL;
68
69
70 /* Patterns to match in ap_make_content_type() */
71 static const char *needcset[] = {
72     "text/plain",
73     "text/html",
74     NULL
75 };
76 static const apr_strmatch_pattern **needcset_patterns;
77 static const apr_strmatch_pattern *charset_pattern;
78
79 AP_DECLARE(void) ap_setup_make_content_type(apr_pool_t *pool)
80 {
81     int i;
82     for (i = 0; needcset[i]; i++) {
83         continue;
84     }
85     needcset_patterns = (const apr_strmatch_pattern **)
86         apr_palloc(pool, (i + 1) * sizeof(apr_strmatch_pattern *));
87     for (i = 0; needcset[i]; i++) {
88         needcset_patterns[i] = apr_strmatch_precompile(pool, needcset[i], 0);
89     }
90     needcset_patterns[i] = NULL;
91     charset_pattern = apr_strmatch_precompile(pool, "charset=", 0);
92 }
93
94 /*
95  * Builds the content-type that should be sent to the client from the
96  * content-type specified.  The following rules are followed:
97  *    - if type is NULL or "", return NULL (do not set content-type).
98  *    - if charset adding is disabled, stop processing and return type.
99  *    - then, if there are no parameters on type, add the default charset
100  *    - return type
101  */
102 AP_DECLARE(const char *)ap_make_content_type(request_rec *r, const char *type)
103 {
104     const apr_strmatch_pattern **pcset;
105     core_dir_config *conf =
106         (core_dir_config *)ap_get_module_config(r->per_dir_config,
107                                                 &core_module);
108     core_request_config *request_conf;
109     apr_size_t type_len;
110
111     if (!type || *type == '\0') {
112         return NULL;
113     }
114
115     if (conf->add_default_charset != ADD_DEFAULT_CHARSET_ON) {
116         return type;
117     }
118
119     request_conf =
120         ap_get_module_config(r->request_config, &core_module);
121     if (request_conf->suppress_charset) {
122         return type;
123     }
124
125     type_len = strlen(type);
126
127     if (apr_strmatch(charset_pattern, type, type_len) != NULL) {
128         /* already has parameter, do nothing */
129         /* XXX we don't check the validity */
130         ;
131     }
132     else {
133         /* see if it makes sense to add the charset. At present,
134          * we only add it if the Content-type is one of needcset[]
135          */
136         for (pcset = needcset_patterns; *pcset ; pcset++) {
137             if (apr_strmatch(*pcset, type, type_len) != NULL) {
138                 struct iovec concat[3];
139                 concat[0].iov_base = (void *)type;
140                 concat[0].iov_len = type_len;
141                 concat[1].iov_base = (void *)"; charset=";
142                 concat[1].iov_len = sizeof("; charset=") - 1;
143                 concat[2].iov_base = (void *)(conf->add_default_charset_name);
144                 concat[2].iov_len = strlen(conf->add_default_charset_name);
145                 type = apr_pstrcatv(r->pool, concat, 3, NULL);
146                 break;
147             }
148         }
149     }
150
151     return type;
152 }
153
154 AP_DECLARE(void) ap_set_content_length(request_rec *r, apr_off_t clength)
155 {
156     r->clength = clength;
157     apr_table_setn(r->headers_out, "Content-Length",
158                    apr_off_t_toa(r->pool, clength));
159 }
160
161 /*
162  * Return the latest rational time from a request/mtime (modification time)
163  * pair.  We return the mtime unless it's in the future, in which case we
164  * return the current time.  We use the request time as a reference in order
165  * to limit the number of calls to time().  We don't check for futurosity
166  * unless the mtime is at least as new as the reference.
167  */
168 AP_DECLARE(apr_time_t) ap_rationalize_mtime(request_rec *r, apr_time_t mtime)
169 {
170     apr_time_t now;
171
172     /* For all static responses, it's almost certain that the file was
173      * last modified before the beginning of the request.  So there's
174      * no reason to call time(NULL) again.  But if the response has been
175      * created on demand, then it might be newer than the time the request
176      * started.  In this event we really have to call time(NULL) again
177      * so that we can give the clients the most accurate Last-Modified.  If we
178      * were given a time in the future, we return the current time - the
179      * Last-Modified can't be in the future.
180      */
181     now = (mtime < r->request_time) ? r->request_time : apr_time_now();
182     return (mtime > now) ? now : mtime;
183 }
184
185 /* Min # of bytes to allocate when reading a request line */
186 #define MIN_LINE_ALLOC 80
187
188 /* Get a line of protocol input, including any continuation lines
189  * caused by MIME folding (or broken clients) if fold != 0, and place it
190  * in the buffer s, of size n bytes, without the ending newline.
191  *
192  * If s is NULL, ap_rgetline_core will allocate necessary memory from r->pool.
193  *
194  * Returns APR_SUCCESS if there are no problems and sets *read to be
195  * the full length of s.
196  *
197  * APR_ENOSPC is returned if there is not enough buffer space.
198  * Other errors may be returned on other errors.
199  *
200  * The LF is *not* returned in the buffer.  Therefore, a *read of 0
201  * indicates that an empty line was read.
202  *
203  * Notes: Because the buffer uses 1 char for NUL, the most we can return is
204  *        (n - 1) actual characters.
205  *
206  *        If no LF is detected on the last line due to a dropped connection
207  *        or a full buffer, that's considered an error.
208  */
209 AP_DECLARE(apr_status_t) ap_rgetline_core(char **s, apr_size_t n,
210                                           apr_size_t *read, request_rec *r,
211                                           int fold, apr_bucket_brigade *bb)
212 {
213     apr_status_t rv;
214     apr_bucket *e;
215     apr_size_t bytes_handled = 0, current_alloc = 0;
216     char *pos, *last_char = *s;
217     int do_alloc = (*s == NULL), saw_eos = 0;
218
219     /*
220      * Initialize last_char as otherwise a random value will be compared
221      * against APR_ASCII_LF at the end of the loop if bb only contains
222      * zero-length buckets.
223      */
224     if (last_char)
225         *last_char = '\0';
226
227     for (;;) {
228         apr_brigade_cleanup(bb);
229         rv = ap_get_brigade(r->input_filters, bb, AP_MODE_GETLINE,
230                             APR_BLOCK_READ, 0);
231         if (rv != APR_SUCCESS) {
232             return rv;
233         }
234
235         /* Something horribly wrong happened.  Someone didn't block! */
236         if (APR_BRIGADE_EMPTY(bb)) {
237             return APR_EGENERAL;
238         }
239
240         for (e = APR_BRIGADE_FIRST(bb);
241              e != APR_BRIGADE_SENTINEL(bb);
242              e = APR_BUCKET_NEXT(e))
243         {
244             const char *str;
245             apr_size_t len;
246
247             /* If we see an EOS, don't bother doing anything more. */
248             if (APR_BUCKET_IS_EOS(e)) {
249                 saw_eos = 1;
250                 break;
251             }
252
253             rv = apr_bucket_read(e, &str, &len, APR_BLOCK_READ);
254             if (rv != APR_SUCCESS) {
255                 return rv;
256             }
257
258             if (len == 0) {
259                 /* no use attempting a zero-byte alloc (hurts when
260                  * using --with-efence --enable-pool-debug) or
261                  * doing any of the other logic either
262                  */
263                 continue;
264             }
265
266             /* Would this overrun our buffer?  If so, we'll die. */
267             if (n < bytes_handled + len) {
268                 *read = bytes_handled;
269                 if (*s) {
270                     /* ensure this string is NUL terminated */
271                     if (bytes_handled > 0) {
272                         (*s)[bytes_handled-1] = '\0';
273                     }
274                     else {
275                         (*s)[0] = '\0';
276                     }
277                 }
278                 return APR_ENOSPC;
279             }
280
281             /* Do we have to handle the allocation ourselves? */
282             if (do_alloc) {
283                 /* We'll assume the common case where one bucket is enough. */
284                 if (!*s) {
285                     current_alloc = len;
286                     if (current_alloc < MIN_LINE_ALLOC) {
287                         current_alloc = MIN_LINE_ALLOC;
288                     }
289                     *s = apr_palloc(r->pool, current_alloc);
290                 }
291                 else if (bytes_handled + len > current_alloc) {
292                     /* Increase the buffer size */
293                     apr_size_t new_size = current_alloc * 2;
294                     char *new_buffer;
295
296                     if (bytes_handled + len > new_size) {
297                         new_size = (bytes_handled + len) * 2;
298                     }
299
300                     new_buffer = apr_palloc(r->pool, new_size);
301
302                     /* Copy what we already had. */
303                     memcpy(new_buffer, *s, bytes_handled);
304                     current_alloc = new_size;
305                     *s = new_buffer;
306                 }
307             }
308
309             /* Just copy the rest of the data to the end of the old buffer. */
310             pos = *s + bytes_handled;
311             memcpy(pos, str, len);
312             last_char = pos + len - 1;
313
314             /* We've now processed that new data - update accordingly. */
315             bytes_handled += len;
316         }
317
318         /* If we got a full line of input, stop reading */
319         if (last_char && (*last_char == APR_ASCII_LF)) {
320             break;
321         }
322     }
323
324     /* Now NUL-terminate the string at the end of the line;
325      * if the last-but-one character is a CR, terminate there */
326     if (last_char > *s && last_char[-1] == APR_ASCII_CR) {
327         last_char--;
328     }
329     *last_char = '\0';
330     bytes_handled = last_char - *s;
331
332     /* If we're folding, we have more work to do.
333      *
334      * Note that if an EOS was seen, we know we can't have another line.
335      */
336     if (fold && bytes_handled && !saw_eos) {
337         for (;;) {
338             const char *str;
339             apr_size_t len;
340             char c;
341
342             /* Clear the temp brigade for this filter read. */
343             apr_brigade_cleanup(bb);
344
345             /* We only care about the first byte. */
346             rv = ap_get_brigade(r->input_filters, bb, AP_MODE_SPECULATIVE,
347                                 APR_BLOCK_READ, 1);
348             if (rv != APR_SUCCESS) {
349                 return rv;
350             }
351
352             if (APR_BRIGADE_EMPTY(bb)) {
353                 break;
354             }
355
356             e = APR_BRIGADE_FIRST(bb);
357
358             /* If we see an EOS, don't bother doing anything more. */
359             if (APR_BUCKET_IS_EOS(e)) {
360                 break;
361             }
362
363             rv = apr_bucket_read(e, &str, &len, APR_BLOCK_READ);
364             if (rv != APR_SUCCESS) {
365                 apr_brigade_cleanup(bb);
366                 return rv;
367             }
368
369             /* Found one, so call ourselves again to get the next line.
370              *
371              * FIXME: If the folding line is completely blank, should we
372              * stop folding?  Does that require also looking at the next
373              * char?
374              */
375             /* When we call destroy, the buckets are deleted, so save that
376              * one character we need.  This simplifies our execution paths
377              * at the cost of one character read.
378              */
379             c = *str;
380             if (c == APR_ASCII_BLANK || c == APR_ASCII_TAB) {
381                 /* Do we have enough space? We may be full now. */
382                 if (bytes_handled >= n) {
383                     *read = n;
384                     /* ensure this string is terminated */
385                     (*s)[n-1] = '\0';
386                     return APR_ENOSPC;
387                 }
388                 else {
389                     apr_size_t next_size, next_len;
390                     char *tmp;
391
392                     /* If we're doing the allocations for them, we have to
393                      * give ourselves a NULL and copy it on return.
394                      */
395                     if (do_alloc) {
396                         tmp = NULL;
397                     } else {
398                         /* We're null terminated. */
399                         tmp = last_char;
400                     }
401
402                     next_size = n - bytes_handled;
403
404                     rv = ap_rgetline_core(&tmp, next_size,
405                                           &next_len, r, 0, bb);
406                     if (rv != APR_SUCCESS) {
407                         return rv;
408                     }
409
410                     if (do_alloc && next_len > 0) {
411                         char *new_buffer;
412                         apr_size_t new_size = bytes_handled + next_len + 1;
413
414                         /* we need to alloc an extra byte for a null */
415                         new_buffer = apr_palloc(r->pool, new_size);
416
417                         /* Copy what we already had. */
418                         memcpy(new_buffer, *s, bytes_handled);
419
420                         /* copy the new line, including the trailing null */
421                         memcpy(new_buffer + bytes_handled, tmp, next_len + 1);
422                         *s = new_buffer;
423                     }
424
425                     last_char += next_len;
426                     bytes_handled += next_len;
427                 }
428             }
429             else { /* next character is not tab or space */
430                 break;
431             }
432         }
433     }
434     *read = bytes_handled;
435
436     /* PR#43039: We shouldn't accept NULL bytes within the line */
437     if (strlen(*s) < bytes_handled) {
438         return APR_EINVAL;
439     }
440
441     return APR_SUCCESS;
442 }
443
444 #if APR_CHARSET_EBCDIC
445 AP_DECLARE(apr_status_t) ap_rgetline(char **s, apr_size_t n,
446                                      apr_size_t *read, request_rec *r,
447                                      int fold, apr_bucket_brigade *bb)
448 {
449     /* on ASCII boxes, ap_rgetline is a macro which simply invokes
450      * ap_rgetline_core with the same parms
451      *
452      * on EBCDIC boxes, each complete http protocol input line needs to be
453      * translated into the code page used by the compiler.  Since
454      * ap_rgetline_core uses recursion, we do the translation in a wrapper
455      * function to insure that each input character gets translated only once.
456      */
457     apr_status_t rv;
458
459     rv = ap_rgetline_core(s, n, read, r, fold, bb);
460     if (rv == APR_SUCCESS) {
461         ap_xlate_proto_from_ascii(*s, *read);
462     }
463     return rv;
464 }
465 #endif
466
467 AP_DECLARE(int) ap_getline(char *s, int n, request_rec *r, int fold)
468 {
469     char *tmp_s = s;
470     apr_status_t rv;
471     apr_size_t len;
472     apr_bucket_brigade *tmp_bb;
473
474     tmp_bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
475     rv = ap_rgetline(&tmp_s, n, &len, r, fold, tmp_bb);
476     apr_brigade_destroy(tmp_bb);
477
478     /* Map the out-of-space condition to the old API. */
479     if (rv == APR_ENOSPC) {
480         return n;
481     }
482
483     /* Anything else is just bad. */
484     if (rv != APR_SUCCESS) {
485         return -1;
486     }
487
488     return (int)len;
489 }
490
491 /* parse_uri: break apart the uri
492  * Side Effects:
493  * - sets r->args to rest after '?' (or NULL if no '?')
494  * - sets r->uri to request uri (without r->args part)
495  * - sets r->hostname (if not set already) from request (scheme://host:port)
496  */
497 AP_CORE_DECLARE(void) ap_parse_uri(request_rec *r, const char *uri)
498 {
499     int status = HTTP_OK;
500
501     r->unparsed_uri = apr_pstrdup(r->pool, uri);
502
503     /* http://issues.apache.org/bugzilla/show_bug.cgi?id=31875
504      * http://issues.apache.org/bugzilla/show_bug.cgi?id=28450
505      *
506      * This is not in fact a URI, it's a path.  That matters in the
507      * case of a leading double-slash.  We need to resolve the issue
508      * by normalising that out before treating it as a URI.
509      */
510     while ((uri[0] == '/') && (uri[1] == '/')) {
511         ++uri ;
512     }
513     if (r->method_number == M_CONNECT) {
514         status = apr_uri_parse_hostinfo(r->pool, uri, &r->parsed_uri);
515     }
516     else {
517         /* Simple syntax Errors in URLs are trapped by
518          * parse_uri_components().
519          */
520         status = apr_uri_parse(r->pool, uri, &r->parsed_uri);
521     }
522
523     if (status == APR_SUCCESS) {
524         /* if it has a scheme we may need to do absoluteURI vhost stuff */
525         if (r->parsed_uri.scheme
526             && !strcasecmp(r->parsed_uri.scheme, ap_http_scheme(r))) {
527             r->hostname = r->parsed_uri.hostname;
528         }
529         else if (r->method_number == M_CONNECT) {
530             r->hostname = r->parsed_uri.hostname;
531         }
532
533         r->args = r->parsed_uri.query;
534         r->uri = r->parsed_uri.path ? r->parsed_uri.path
535                  : apr_pstrdup(r->pool, "/");
536
537 #if defined(OS2) || defined(WIN32)
538         /* Handle path translations for OS/2 and plug security hole.
539          * This will prevent "http://www.wherever.com/..\..\/" from
540          * returning a directory for the root drive.
541          */
542         {
543             char *x;
544
545             for (x = r->uri; (x = strchr(x, '\\')) != NULL; )
546                 *x = '/';
547         }
548 #endif /* OS2 || WIN32 */
549     }
550     else {
551         r->args = NULL;
552         r->hostname = NULL;
553         r->status = HTTP_BAD_REQUEST;             /* set error status */
554         r->uri = apr_pstrdup(r->pool, uri);
555     }
556 }
557
558 static int read_request_line(request_rec *r, apr_bucket_brigade *bb)
559 {
560     const char *ll;
561     const char *uri;
562     const char *pro;
563
564 #if 0
565     conn_rec *conn = r->connection;
566 #endif
567     int major = 1, minor = 0;   /* Assume HTTP/1.0 if non-"HTTP" protocol */
568     char http[5];
569     apr_size_t len;
570     int num_blank_lines = 0;
571     int max_blank_lines = r->server->limit_req_fields;
572
573     if (max_blank_lines <= 0) {
574         max_blank_lines = DEFAULT_LIMIT_REQUEST_FIELDS;
575     }
576
577     /* Read past empty lines until we get a real request line,
578      * a read error, the connection closes (EOF), or we timeout.
579      *
580      * We skip empty lines because browsers have to tack a CRLF on to the end
581      * of POSTs to support old CERN webservers.  But note that we may not
582      * have flushed any previous response completely to the client yet.
583      * We delay the flush as long as possible so that we can improve
584      * performance for clients that are pipelining requests.  If a request
585      * is pipelined then we won't block during the (implicit) read() below.
586      * If the requests aren't pipelined, then the client is still waiting
587      * for the final buffer flush from us, and we will block in the implicit
588      * read().  B_SAFEREAD ensures that the BUFF layer flushes if it will
589      * have to block during a read.
590      */
591
592     do {
593         apr_status_t rv;
594
595         /* insure ap_rgetline allocates memory each time thru the loop
596          * if there are empty lines
597          */
598         r->the_request = NULL;
599         rv = ap_rgetline(&(r->the_request), (apr_size_t)(r->server->limit_req_line + 2),
600                          &len, r, 0, bb);
601
602         if (rv != APR_SUCCESS) {
603             r->request_time = apr_time_now();
604
605             /* ap_rgetline returns APR_ENOSPC if it fills up the
606              * buffer before finding the end-of-line.  This is only going to
607              * happen if it exceeds the configured limit for a request-line.
608              */
609             if (rv == APR_ENOSPC) {
610                 r->status    = HTTP_REQUEST_URI_TOO_LARGE;
611                 r->proto_num = HTTP_VERSION(1,0);
612                 r->protocol  = apr_pstrdup(r->pool, "HTTP/1.0");
613             }
614             else if (rv == APR_TIMEUP) {
615                 r->status = HTTP_REQUEST_TIME_OUT;
616             }
617             else if (rv == APR_EINVAL) {
618                 r->status = HTTP_BAD_REQUEST;
619             }
620             return 0;
621         }
622     } while ((len <= 0) && (++num_blank_lines < max_blank_lines));
623
624     /* we've probably got something to do, ignore graceful restart requests */
625
626     r->request_time = apr_time_now();
627     ll = r->the_request;
628     r->method = ap_getword_white(r->pool, &ll);
629
630 #if 0
631 /* XXX If we want to keep track of the Method, the protocol module should do
632  * it.  That support isn't in the scoreboard yet.  Hopefully next week
633  * sometime.   rbb */
634     ap_update_connection_status(AP_CHILD_THREAD_FROM_ID(conn->id), "Method",
635                                 r->method);
636 #endif
637
638     uri = ap_getword_white(r->pool, &ll);
639
640     /* Provide quick information about the request method as soon as known */
641
642     r->method_number = ap_method_number_of(r->method);
643     if (r->method_number == M_GET && r->method[0] == 'H') {
644         r->header_only = 1;
645     }
646
647     ap_parse_uri(r, uri);
648
649     if (ll[0]) {
650         r->assbackwards = 0;
651         pro = ll;
652         len = strlen(ll);
653     } else {
654         r->assbackwards = 1;
655         pro = "HTTP/0.9";
656         len = 8;
657     }
658     r->protocol = apr_pstrmemdup(r->pool, pro, len);
659
660     /* XXX ap_update_connection_status(conn->id, "Protocol", r->protocol); */
661
662     /* Avoid sscanf in the common case */
663     if (len == 8
664         && pro[0] == 'H' && pro[1] == 'T' && pro[2] == 'T' && pro[3] == 'P'
665         && pro[4] == '/' && apr_isdigit(pro[5]) && pro[6] == '.'
666         && apr_isdigit(pro[7])) {
667         r->proto_num = HTTP_VERSION(pro[5] - '0', pro[7] - '0');
668     }
669     else if (3 == sscanf(r->protocol, "%4s/%u.%u", http, &major, &minor)
670              && (strcasecmp("http", http) == 0)
671              && (minor < HTTP_VERSION(1, 0)) ) /* don't allow HTTP/0.1000 */
672         r->proto_num = HTTP_VERSION(major, minor);
673     else
674         r->proto_num = HTTP_VERSION(1, 0);
675
676     return 1;
677 }
678
679 AP_DECLARE(void) ap_get_mime_headers_core(request_rec *r, apr_bucket_brigade *bb)
680 {
681     char *last_field = NULL;
682     apr_size_t last_len = 0;
683     apr_size_t alloc_len = 0;
684     char *field;
685     char *value;
686     apr_size_t len;
687     int fields_read = 0;
688     char *tmp_field;
689
690     /*
691      * Read header lines until we get the empty separator line, a read error,
692      * the connection closes (EOF), reach the server limit, or we timeout.
693      */
694     while(1) {
695         apr_status_t rv;
696         int folded = 0;
697
698         field = NULL;
699         rv = ap_rgetline(&field, r->server->limit_req_fieldsize + 2,
700                          &len, r, 0, bb);
701
702         if (rv != APR_SUCCESS) {
703             if (rv == APR_TIMEUP) {
704                 r->status = HTTP_REQUEST_TIME_OUT;
705             }
706             else {
707                 r->status = HTTP_BAD_REQUEST;
708             }
709
710             /* ap_rgetline returns APR_ENOSPC if it fills up the buffer before
711              * finding the end-of-line.  This is only going to happen if it
712              * exceeds the configured limit for a field size.
713              */
714             if (rv == APR_ENOSPC && field) {
715                 /* insure ap_escape_html will terminate correctly */
716                 field[len - 1] = '\0';
717                 apr_table_setn(r->notes, "error-notes",
718                                apr_pstrcat(r->pool,
719                                            "Size of a request header field "
720                                            "exceeds server limit.<br />\n"
721                                            "<pre>\n",
722                                            ap_escape_html(r->pool, field),
723                                            "</pre>\n", NULL));
724             }
725             return;
726         }
727
728         if (last_field != NULL) {
729             if ((len > 0) && ((*field == '\t') || *field == ' ')) {
730                 /* This line is a continuation of the preceding line(s),
731                  * so append it to the line that we've set aside.
732                  * Note: this uses a power-of-two allocator to avoid
733                  * doing O(n) allocs and using O(n^2) space for
734                  * continuations that span many many lines.
735                  */
736                 apr_size_t fold_len = last_len + len + 1; /* trailing null */
737
738                 if (fold_len >= (apr_size_t)(r->server->limit_req_fieldsize)) {
739                     r->status = HTTP_BAD_REQUEST;
740                     /* report what we have accumulated so far before the
741                      * overflow (last_field) as the field with the problem
742                      */
743                     apr_table_setn(r->notes, "error-notes",
744                                    apr_pstrcat(r->pool,
745                                                "Size of a request header field "
746                                                "after folding "
747                                                "exceeds server limit.<br />\n"
748                                                "<pre>\n",
749                                                ap_escape_html(r->pool, last_field),
750                                                "</pre>\n", NULL));
751                     return;
752                 }
753
754                 if (fold_len > alloc_len) {
755                     char *fold_buf;
756                     alloc_len += alloc_len;
757                     if (fold_len > alloc_len) {
758                         alloc_len = fold_len;
759                     }
760                     fold_buf = (char *)apr_palloc(r->pool, alloc_len);
761                     memcpy(fold_buf, last_field, last_len);
762                     last_field = fold_buf;
763                 }
764                 memcpy(last_field + last_len, field, len +1); /* +1 for nul */
765                 last_len += len;
766                 folded = 1;
767             }
768             else /* not a continuation line */ {
769
770                 if (r->server->limit_req_fields
771                     && (++fields_read > r->server->limit_req_fields)) {
772                     r->status = HTTP_BAD_REQUEST;
773                     apr_table_setn(r->notes, "error-notes",
774                                    "The number of request header fields "
775                                    "exceeds this server's limit.");
776                     return;
777                 }
778
779                 if (!(value = strchr(last_field, ':'))) { /* Find ':' or    */
780                     r->status = HTTP_BAD_REQUEST;      /* abort bad request */
781                     apr_table_setn(r->notes, "error-notes",
782                                    apr_pstrcat(r->pool,
783                                                "Request header field is "
784                                                "missing ':' separator.<br />\n"
785                                                "<pre>\n",
786                                                ap_escape_html(r->pool,
787                                                               last_field),
788                                                "</pre>\n", NULL));
789                     return;
790                 }
791
792                 tmp_field = value - 1; /* last character of field-name */
793
794                 *value++ = '\0'; /* NUL-terminate at colon */
795
796                 while (*value == ' ' || *value == '\t') {
797                     ++value;            /* Skip to start of value   */
798                 }
799
800                 /* Strip LWS after field-name: */
801                 while (tmp_field > last_field
802                        && (*tmp_field == ' ' || *tmp_field == '\t')) {
803                     *tmp_field-- = '\0';
804                 }
805
806                 /* Strip LWS after field-value: */
807                 tmp_field = last_field + last_len - 1;
808                 while (tmp_field > value
809                        && (*tmp_field == ' ' || *tmp_field == '\t')) {
810                     *tmp_field-- = '\0';
811                 }
812
813                 apr_table_addn(r->headers_in, last_field, value);
814
815                 /* reset the alloc_len so that we'll allocate a new
816                  * buffer if we have to do any more folding: we can't
817                  * use the previous buffer because its contents are
818                  * now part of r->headers_in
819                  */
820                 alloc_len = 0;
821
822             } /* end if current line is not a continuation starting with tab */
823         }
824
825         /* Found a blank line, stop. */
826         if (len == 0) {
827             break;
828         }
829
830         /* Keep track of this line so that we can parse it on
831          * the next loop iteration.  (In the folded case, last_field
832          * has been updated already.)
833          */
834         if (!folded) {
835             last_field = field;
836             last_len = len;
837         }
838     }
839
840     apr_table_compress(r->headers_in, APR_OVERLAP_TABLES_MERGE);
841 }
842
843 AP_DECLARE(void) ap_get_mime_headers(request_rec *r)
844 {
845     apr_bucket_brigade *tmp_bb;
846     tmp_bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
847     ap_get_mime_headers_core(r, tmp_bb);
848     apr_brigade_destroy(tmp_bb);
849 }
850
851 request_rec *ap_read_request(conn_rec *conn)
852 {
853     request_rec *r;
854     apr_pool_t *p;
855     const char *expect;
856     int access_status;
857     apr_bucket_brigade *tmp_bb;
858     apr_socket_t *csd;
859     apr_interval_time_t cur_timeout;
860
861
862     apr_pool_create(&p, conn->pool);
863     apr_pool_tag(p, "request");
864     r = apr_pcalloc(p, sizeof(request_rec));
865     AP_READ_REQUEST_ENTRY((intptr_t)r, (uintptr_t)conn);
866     r->pool            = p;
867     r->connection      = conn;
868     r->server          = conn->base_server;
869
870     r->user            = NULL;
871     r->ap_auth_type    = NULL;
872
873     r->allowed_methods = ap_make_method_list(p, 2);
874
875     r->headers_in      = apr_table_make(r->pool, 25);
876     r->subprocess_env  = apr_table_make(r->pool, 25);
877     r->headers_out     = apr_table_make(r->pool, 12);
878     r->err_headers_out = apr_table_make(r->pool, 5);
879     r->notes           = apr_table_make(r->pool, 5);
880
881     r->request_config  = ap_create_request_config(r->pool);
882     /* Must be set before we run create request hook */
883
884     r->proto_output_filters = conn->output_filters;
885     r->output_filters  = r->proto_output_filters;
886     r->proto_input_filters = conn->input_filters;
887     r->input_filters   = r->proto_input_filters;
888     ap_run_create_request(r);
889     r->per_dir_config  = r->server->lookup_defaults;
890
891     r->sent_bodyct     = 0;                      /* bytect isn't for body */
892
893     r->read_length     = 0;
894     r->read_body       = REQUEST_NO_BODY;
895
896     r->status          = HTTP_OK;  /* Until further notice */
897     r->the_request     = NULL;
898
899     /* Begin by presuming any module can make its own path_info assumptions,
900      * until some module interjects and changes the value.
901      */
902     r->used_path_info = AP_REQ_DEFAULT_PATH_INFO;
903
904     tmp_bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
905
906     /* Get the request... */
907     if (!read_request_line(r, tmp_bb)) {
908         if (r->status == HTTP_REQUEST_URI_TOO_LARGE
909             || r->status == HTTP_BAD_REQUEST) {
910             if (r->status == HTTP_BAD_REQUEST) {
911                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
912                               "request failed: invalid characters in URI");
913             }
914             else {
915                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
916                               "request failed: URI too long (longer than %d)", r->server->limit_req_line);
917             }
918             ap_send_error_response(r, 0);
919             ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
920             ap_run_log_transaction(r);
921             apr_brigade_destroy(tmp_bb);
922             goto traceout;
923         }
924         else if (r->status == HTTP_REQUEST_TIME_OUT) {
925             ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
926             if (!r->connection->keepalives) {
927                 ap_run_log_transaction(r);
928             }
929             apr_brigade_destroy(tmp_bb);
930             goto traceout;
931         }
932
933         apr_brigade_destroy(tmp_bb);
934         r = NULL;
935         goto traceout;
936     }
937
938     /* We may have been in keep_alive_timeout mode, so toggle back
939      * to the normal timeout mode as we fetch the header lines,
940      * as necessary.
941      */
942     csd = ap_get_module_config(conn->conn_config, &core_module);
943     apr_socket_timeout_get(csd, &cur_timeout);
944     if (cur_timeout != conn->base_server->timeout) {
945         apr_socket_timeout_set(csd, conn->base_server->timeout);
946         cur_timeout = conn->base_server->timeout;
947     }
948
949     if (!r->assbackwards) {
950         ap_get_mime_headers_core(r, tmp_bb);
951         if (r->status != HTTP_OK) {
952             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
953                           "request failed: error reading the headers");
954             ap_send_error_response(r, 0);
955             ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
956             ap_run_log_transaction(r);
957             apr_brigade_destroy(tmp_bb);
958             goto traceout;
959         }
960
961         if (apr_table_get(r->headers_in, "Transfer-Encoding")
962             && apr_table_get(r->headers_in, "Content-Length")) {
963             /* 2616 section 4.4, point 3: "if both Transfer-Encoding
964              * and Content-Length are received, the latter MUST be
965              * ignored"; so unset it here to prevent any confusion
966              * later. */
967             apr_table_unset(r->headers_in, "Content-Length");
968         }
969     }
970     else {
971         if (r->header_only) {
972             /*
973              * Client asked for headers only with HTTP/0.9, which doesn't send
974              * headers! Have to dink things just to make sure the error message
975              * comes through...
976              */
977             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
978                           "client sent invalid HTTP/0.9 request: HEAD %s",
979                           r->uri);
980             r->header_only = 0;
981             r->status = HTTP_BAD_REQUEST;
982             ap_send_error_response(r, 0);
983             ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
984             ap_run_log_transaction(r);
985             apr_brigade_destroy(tmp_bb);
986             goto traceout;
987         }
988     }
989
990     apr_brigade_destroy(tmp_bb);
991
992     /* update what we think the virtual host is based on the headers we've
993      * now read. may update status.
994      */
995     ap_update_vhost_from_headers(r);
996
997     /* Toggle to the Host:-based vhost's timeout mode to fetch the
998      * request body and send the response body, if needed.
999      */
1000     if (cur_timeout != r->server->timeout) {
1001         apr_socket_timeout_set(csd, r->server->timeout);
1002         cur_timeout = r->server->timeout;
1003     }
1004
1005     /* we may have switched to another server */
1006     r->per_dir_config = r->server->lookup_defaults;
1007
1008     if ((!r->hostname && (r->proto_num >= HTTP_VERSION(1, 1)))
1009         || ((r->proto_num == HTTP_VERSION(1, 1))
1010             && !apr_table_get(r->headers_in, "Host"))) {
1011         /*
1012          * Client sent us an HTTP/1.1 or later request without telling us the
1013          * hostname, either with a full URL or a Host: header. We therefore
1014          * need to (as per the 1.1 spec) send an error.  As a special case,
1015          * HTTP/1.1 mentions twice (S9, S14.23) that a request MUST contain
1016          * a Host: header, and the server MUST respond with 400 if it doesn't.
1017          */
1018         r->status = HTTP_BAD_REQUEST;
1019         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1020                       "client sent HTTP/1.1 request without hostname "
1021                       "(see RFC2616 section 14.23): %s", r->uri);
1022     }
1023
1024     /*
1025      * Add the HTTP_IN filter here to ensure that ap_discard_request_body
1026      * called by ap_die and by ap_send_error_response works correctly on
1027      * status codes that do not cause the connection to be dropped and
1028      * in situations where the connection should be kept alive.
1029      */
1030
1031     ap_add_input_filter_handle(ap_http_input_filter_handle,
1032                                NULL, r, r->connection);
1033
1034     if (r->status != HTTP_OK) {
1035         ap_send_error_response(r, 0);
1036         ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
1037         ap_run_log_transaction(r);
1038         goto traceout;
1039     }
1040
1041     if ((access_status = ap_run_post_read_request(r))) {
1042         ap_die(access_status, r);
1043         ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
1044         ap_run_log_transaction(r);
1045         r = NULL;
1046         goto traceout;
1047     }
1048
1049     if (((expect = apr_table_get(r->headers_in, "Expect")) != NULL)
1050         && (expect[0] != '\0')) {
1051         /*
1052          * The Expect header field was added to HTTP/1.1 after RFC 2068
1053          * as a means to signal when a 100 response is desired and,
1054          * unfortunately, to signal a poor man's mandatory extension that
1055          * the server must understand or return 417 Expectation Failed.
1056          */
1057         if (strcasecmp(expect, "100-continue") == 0) {
1058             r->expecting_100 = 1;
1059         }
1060         else {
1061             r->status = HTTP_EXPECTATION_FAILED;
1062             ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
1063                           "client sent an unrecognized expectation value of "
1064                           "Expect: %s", expect);
1065             ap_send_error_response(r, 0);
1066             ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
1067             ap_run_log_transaction(r);
1068             goto traceout;
1069         }
1070     }
1071
1072     AP_READ_REQUEST_SUCCESS((uintptr_t)r, (char *)r->method, (char *)r->uri, (char *)r->server->defn_name, r->status);
1073     return r;
1074     traceout:
1075     AP_READ_REQUEST_FAILURE((uintptr_t)r);
1076     return r;
1077 }
1078
1079 /* if a request with a body creates a subrequest, remove original request's
1080  * input headers which pertain to the body which has already been read.
1081  * out-of-line helper function for ap_set_sub_req_protocol.
1082  */
1083
1084 static void strip_headers_request_body(request_rec *rnew)
1085 {
1086     apr_table_unset(rnew->headers_in, "Content-Encoding");
1087     apr_table_unset(rnew->headers_in, "Content-Language");
1088     apr_table_unset(rnew->headers_in, "Content-Length");
1089     apr_table_unset(rnew->headers_in, "Content-Location");
1090     apr_table_unset(rnew->headers_in, "Content-MD5");
1091     apr_table_unset(rnew->headers_in, "Content-Range");
1092     apr_table_unset(rnew->headers_in, "Content-Type");
1093     apr_table_unset(rnew->headers_in, "Expires");
1094     apr_table_unset(rnew->headers_in, "Last-Modified");
1095     apr_table_unset(rnew->headers_in, "Transfer-Encoding");
1096 }
1097
1098 /*
1099  * A couple of other functions which initialize some of the fields of
1100  * a request structure, as appropriate for adjuncts of one kind or another
1101  * to a request in progress.  Best here, rather than elsewhere, since
1102  * *someone* has to set the protocol-specific fields...
1103  */
1104
1105 AP_DECLARE(void) ap_set_sub_req_protocol(request_rec *rnew,
1106                                          const request_rec *r)
1107 {
1108     rnew->the_request     = r->the_request;  /* Keep original request-line */
1109
1110     rnew->assbackwards    = 1;   /* Don't send headers from this. */
1111     rnew->no_local_copy   = 1;   /* Don't try to send HTTP_NOT_MODIFIED for a
1112                                   * fragment. */
1113     rnew->method          = "GET";
1114     rnew->method_number   = M_GET;
1115     rnew->protocol        = "INCLUDED";
1116
1117     rnew->status          = HTTP_OK;
1118
1119     rnew->headers_in = apr_table_copy(rnew->pool, r->headers_in);
1120
1121     /* did the original request have a body?  (e.g. POST w/SSI tags)
1122      * if so, make sure the subrequest doesn't inherit body headers
1123      */
1124     if (!r->kept_body && (apr_table_get(r->headers_in, "Content-Length")
1125         || apr_table_get(r->headers_in, "Transfer-Encoding"))) {
1126         strip_headers_request_body(rnew);
1127     }
1128     rnew->subprocess_env  = apr_table_copy(rnew->pool, r->subprocess_env);
1129     rnew->headers_out     = apr_table_make(rnew->pool, 5);
1130     rnew->err_headers_out = apr_table_make(rnew->pool, 5);
1131     rnew->notes           = apr_table_make(rnew->pool, 5);
1132
1133     rnew->expecting_100   = r->expecting_100;
1134     rnew->read_length     = r->read_length;
1135     rnew->read_body       = REQUEST_NO_BODY;
1136
1137     rnew->main = (request_rec *) r;
1138 }
1139
1140 static void end_output_stream(request_rec *r)
1141 {
1142     conn_rec *c = r->connection;
1143     apr_bucket_brigade *bb;
1144     apr_bucket *b;
1145
1146     bb = apr_brigade_create(r->pool, c->bucket_alloc);
1147     b = apr_bucket_eos_create(c->bucket_alloc);
1148     APR_BRIGADE_INSERT_TAIL(bb, b);
1149     ap_pass_brigade(r->output_filters, bb);
1150 }
1151
1152 AP_DECLARE(void) ap_finalize_sub_req_protocol(request_rec *sub)
1153 {
1154     /* tell the filter chain there is no more content coming */
1155     if (!sub->eos_sent) {
1156         end_output_stream(sub);
1157     }
1158 }
1159
1160 /* finalize_request_protocol is called at completion of sending the
1161  * response.  Its sole purpose is to send the terminating protocol
1162  * information for any wrappers around the response message body
1163  * (i.e., transfer encodings).  It should have been named finalize_response.
1164  */
1165 AP_DECLARE(void) ap_finalize_request_protocol(request_rec *r)
1166 {
1167     (void) ap_discard_request_body(r);
1168
1169     /* tell the filter chain there is no more content coming */
1170     if (!r->eos_sent) {
1171         end_output_stream(r);
1172     }
1173 }
1174
1175 /*
1176  * Support for the Basic authentication protocol, and a bit for Digest.
1177  */
1178 AP_DECLARE(void) ap_note_auth_failure(request_rec *r)
1179 {
1180     const char *type = ap_auth_type(r);
1181     if (type) {
1182         if (!strcasecmp(type, "Basic"))
1183             ap_note_basic_auth_failure(r);
1184         else if (!strcasecmp(type, "Digest"))
1185             ap_note_digest_auth_failure(r);
1186     }
1187     else {
1188         ap_log_rerror(APLOG_MARK, APLOG_ERR,
1189                       0, r, "need AuthType to note auth failure: %s", r->uri);
1190     }
1191 }
1192
1193 AP_DECLARE(void) ap_note_basic_auth_failure(request_rec *r)
1194 {
1195     const char *type = ap_auth_type(r);
1196
1197     /* if there is no AuthType configure or it is something other than
1198      * Basic, let ap_note_auth_failure() deal with it
1199      */
1200     if (!type || strcasecmp(type, "Basic"))
1201         ap_note_auth_failure(r);
1202     else
1203         apr_table_setn(r->err_headers_out,
1204                        (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authenticate"
1205                                                        : "WWW-Authenticate",
1206                        apr_pstrcat(r->pool, "Basic realm=\"", ap_auth_name(r),
1207                                    "\"", NULL));
1208 }
1209
1210 AP_DECLARE(void) ap_note_digest_auth_failure(request_rec *r)
1211 {
1212     apr_table_setn(r->err_headers_out,
1213                    (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authenticate"
1214                                                    : "WWW-Authenticate",
1215                    apr_psprintf(r->pool, "Digest realm=\"%s\", nonce=\""
1216                                 "%" APR_UINT64_T_HEX_FMT "\"",
1217                                 ap_auth_name(r), (apr_uint64_t)r->request_time));
1218 }
1219
1220 AP_DECLARE(int) ap_get_basic_auth_pw(request_rec *r, const char **pw)
1221 {
1222     const char *auth_line = apr_table_get(r->headers_in,
1223                                           (PROXYREQ_PROXY == r->proxyreq)
1224                                               ? "Proxy-Authorization"
1225                                               : "Authorization");
1226     const char *t;
1227
1228     if (!(t = ap_auth_type(r)) || strcasecmp(t, "Basic"))
1229         return DECLINED;
1230
1231     if (!ap_auth_name(r)) {
1232         ap_log_rerror(APLOG_MARK, APLOG_ERR,
1233                       0, r, "need AuthName: %s", r->uri);
1234         return HTTP_INTERNAL_SERVER_ERROR;
1235     }
1236
1237     if (!auth_line) {
1238         ap_note_basic_auth_failure(r);
1239         return HTTP_UNAUTHORIZED;
1240     }
1241
1242     if (strcasecmp(ap_getword(r->pool, &auth_line, ' '), "Basic")) {
1243         /* Client tried to authenticate using wrong auth scheme */
1244         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1245                       "client used wrong authentication scheme: %s", r->uri);
1246         ap_note_basic_auth_failure(r);
1247         return HTTP_UNAUTHORIZED;
1248     }
1249
1250     while (*auth_line == ' ' || *auth_line == '\t') {
1251         auth_line++;
1252     }
1253
1254     t = ap_pbase64decode(r->pool, auth_line);
1255     r->user = ap_getword_nulls (r->pool, &t, ':');
1256     r->ap_auth_type = "Basic";
1257
1258     *pw = t;
1259
1260     return OK;
1261 }
1262
1263 struct content_length_ctx {
1264     int data_sent;  /* true if the C-L filter has already sent at
1265                      * least one bucket on to the next output filter
1266                      * for this request
1267                      */
1268     apr_bucket_brigade *tmpbb;
1269 };
1270
1271 /* This filter computes the content length, but it also computes the number
1272  * of bytes sent to the client.  This means that this filter will always run
1273  * through all of the buckets in all brigades
1274  */
1275 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_content_length_filter(
1276     ap_filter_t *f,
1277     apr_bucket_brigade *b)
1278 {
1279     request_rec *r = f->r;
1280     struct content_length_ctx *ctx;
1281     apr_bucket *e;
1282     int eos = 0;
1283     apr_read_type_e eblock = APR_NONBLOCK_READ;
1284
1285     ctx = f->ctx;
1286     if (!ctx) {
1287         f->ctx = ctx = apr_palloc(r->pool, sizeof(*ctx));
1288         ctx->data_sent = 0;
1289         ctx->tmpbb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1290     }
1291
1292     /* Loop through this set of buckets to compute their length
1293      */
1294     e = APR_BRIGADE_FIRST(b);
1295     while (e != APR_BRIGADE_SENTINEL(b)) {
1296         if (APR_BUCKET_IS_EOS(e)) {
1297             eos = 1;
1298             break;
1299         }
1300         if (e->length == (apr_size_t)-1) {
1301             apr_size_t len;
1302             const char *ignored;
1303             apr_status_t rv;
1304
1305             /* This is probably a pipe bucket.  Send everything
1306              * prior to this, and then read the data for this bucket.
1307              */
1308             rv = apr_bucket_read(e, &ignored, &len, eblock);
1309             if (rv == APR_SUCCESS) {
1310                 /* Attempt a nonblocking read next time through */
1311                 eblock = APR_NONBLOCK_READ;
1312                 r->bytes_sent += len;
1313             }
1314             else if (APR_STATUS_IS_EAGAIN(rv)) {
1315                 /* Output everything prior to this bucket, and then
1316                  * do a blocking read on the next batch.
1317                  */
1318                 if (e != APR_BRIGADE_FIRST(b)) {
1319                     apr_bucket *flush;
1320                     apr_brigade_split_ex(b, e, ctx->tmpbb);
1321                     flush = apr_bucket_flush_create(r->connection->bucket_alloc);
1322
1323                     APR_BRIGADE_INSERT_TAIL(b, flush);
1324                     rv = ap_pass_brigade(f->next, b);
1325                     if (rv != APR_SUCCESS || f->c->aborted) {
1326                         return rv;
1327                     }
1328                     apr_brigade_cleanup(b);
1329                     APR_BRIGADE_CONCAT(b, ctx->tmpbb);
1330                     e = APR_BRIGADE_FIRST(b);
1331
1332                     ctx->data_sent = 1;
1333                 }
1334                 eblock = APR_BLOCK_READ;
1335                 continue;
1336             }
1337             else {
1338                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1339                               "ap_content_length_filter: "
1340                               "apr_bucket_read() failed");
1341                 return rv;
1342             }
1343         }
1344         else {
1345             r->bytes_sent += e->length;
1346         }
1347         e = APR_BUCKET_NEXT(e);
1348     }
1349
1350     /* If we've now seen the entire response and it's otherwise
1351      * okay to set the C-L in the response header, then do so now.
1352      *
1353      * We can only set a C-L in the response header if we haven't already
1354      * sent any buckets on to the next output filter for this request.
1355      */
1356     if (ctx->data_sent == 0 && eos &&
1357         /* don't whack the C-L if it has already been set for a HEAD
1358          * by something like proxy.  the brigade only has an EOS bucket
1359          * in this case, making r->bytes_sent zero.
1360          *
1361          * if r->bytes_sent > 0 we have a (temporary) body whose length may
1362          * have been changed by a filter.  the C-L header might not have been
1363          * updated so we do it here.  long term it would be cleaner to have
1364          * such filters update or remove the C-L header, and just use it
1365          * if present.
1366          */
1367         !(r->header_only && r->bytes_sent == 0 &&
1368             apr_table_get(r->headers_out, "Content-Length"))) {
1369         ap_set_content_length(r, r->bytes_sent);
1370     }
1371
1372     ctx->data_sent = 1;
1373     return ap_pass_brigade(f->next, b);
1374 }
1375
1376 /*
1377  * Send the body of a response to the client.
1378  */
1379 AP_DECLARE(apr_status_t) ap_send_fd(apr_file_t *fd, request_rec *r,
1380                                     apr_off_t offset, apr_size_t len,
1381                                     apr_size_t *nbytes)
1382 {
1383     conn_rec *c = r->connection;
1384     apr_bucket_brigade *bb = NULL;
1385     apr_status_t rv;
1386
1387     bb = apr_brigade_create(r->pool, c->bucket_alloc);
1388     
1389     apr_brigade_insert_file(bb, fd, 0, len, r->pool);
1390
1391     rv = ap_pass_brigade(r->output_filters, bb);
1392     if (rv != APR_SUCCESS) {
1393         *nbytes = 0; /* no way to tell how many were actually sent */
1394     }
1395     else {
1396         *nbytes = len;
1397     }
1398
1399     return rv;
1400 }
1401
1402 #if APR_HAS_MMAP
1403 /* send data from an in-memory buffer */
1404 AP_DECLARE(size_t) ap_send_mmap(apr_mmap_t *mm, request_rec *r, size_t offset,
1405                                 size_t length)
1406 {
1407     conn_rec *c = r->connection;
1408     apr_bucket_brigade *bb = NULL;
1409     apr_bucket *b;
1410
1411     bb = apr_brigade_create(r->pool, c->bucket_alloc);
1412     b = apr_bucket_mmap_create(mm, offset, length, c->bucket_alloc);
1413     APR_BRIGADE_INSERT_TAIL(bb, b);
1414     ap_pass_brigade(r->output_filters, bb);
1415
1416     return mm->size; /* XXX - change API to report apr_status_t? */
1417 }
1418 #endif /* APR_HAS_MMAP */
1419
1420 typedef struct {
1421     apr_bucket_brigade *bb;
1422     apr_bucket_brigade *tmpbb;
1423 } old_write_filter_ctx;
1424
1425 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_old_write_filter(
1426     ap_filter_t *f, apr_bucket_brigade *bb)
1427 {
1428     old_write_filter_ctx *ctx = f->ctx;
1429
1430     AP_DEBUG_ASSERT(ctx);
1431
1432     if (ctx->bb != NULL) {
1433         /* whatever is coming down the pipe (we don't care), we
1434          * can simply insert our buffered data at the front and
1435          * pass the whole bundle down the chain.
1436          */
1437         APR_BRIGADE_PREPEND(bb, ctx->bb);
1438     }
1439
1440     return ap_pass_brigade(f->next, bb);
1441 }
1442
1443 static ap_filter_t *insert_old_write_filter(request_rec *r)
1444 {
1445     ap_filter_t *f;
1446     old_write_filter_ctx *ctx;
1447
1448     /* future optimization: record some flags in the request_rec to
1449      * say whether we've added our filter, and whether it is first.
1450      */
1451
1452     /* this will typically exit on the first test */
1453     for (f = r->output_filters; f != NULL; f = f->next) {
1454         if (ap_old_write_func == f->frec)
1455             break;
1456     }
1457
1458     if (f == NULL) {
1459         /* our filter hasn't been added yet */
1460         ctx = apr_pcalloc(r->pool, sizeof(*ctx));
1461         ctx->tmpbb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1462
1463         ap_add_output_filter("OLD_WRITE", ctx, r, r->connection);
1464         f = r->output_filters;
1465     }
1466
1467     return f;
1468 }
1469
1470 static apr_status_t buffer_output(request_rec *r,
1471                                   const char *str, apr_size_t len)
1472 {
1473     conn_rec *c = r->connection;
1474     ap_filter_t *f;
1475     old_write_filter_ctx *ctx;
1476
1477     if (len == 0)
1478         return APR_SUCCESS;
1479
1480     f = insert_old_write_filter(r);
1481     ctx = f->ctx;
1482
1483     /* if the first filter is not our buffering filter, then we have to
1484      * deliver the content through the normal filter chain
1485      */
1486     if (f != r->output_filters) {
1487         apr_status_t rv;
1488         apr_bucket *b = apr_bucket_transient_create(str, len, c->bucket_alloc);
1489         APR_BRIGADE_INSERT_TAIL(ctx->tmpbb, b);
1490
1491         rv = ap_pass_brigade(r->output_filters, ctx->tmpbb);
1492         apr_brigade_cleanup(ctx->tmpbb);
1493         return rv;
1494     }
1495
1496     if (ctx->bb == NULL) {
1497         ctx->bb = apr_brigade_create(r->pool, c->bucket_alloc);
1498     }
1499
1500     return ap_fwrite(f->next, ctx->bb, str, len);
1501 }
1502
1503 AP_DECLARE(int) ap_rputc(int c, request_rec *r)
1504 {
1505     char c2 = (char)c;
1506
1507     if (r->connection->aborted) {
1508         return -1;
1509     }
1510
1511     if (buffer_output(r, &c2, 1) != APR_SUCCESS)
1512         return -1;
1513
1514     return c;
1515 }
1516
1517 AP_DECLARE(int) ap_rputs(const char *str, request_rec *r)
1518 {
1519     apr_size_t len;
1520
1521     if (r->connection->aborted)
1522         return -1;
1523
1524     if (buffer_output(r, str, len = strlen(str)) != APR_SUCCESS)
1525         return -1;
1526
1527     return len;
1528 }
1529
1530 AP_DECLARE(int) ap_rwrite(const void *buf, int nbyte, request_rec *r)
1531 {
1532     if (r->connection->aborted)
1533         return -1;
1534
1535     if (buffer_output(r, buf, nbyte) != APR_SUCCESS)
1536         return -1;
1537
1538     return nbyte;
1539 }
1540
1541 struct ap_vrprintf_data {
1542     apr_vformatter_buff_t vbuff;
1543     request_rec *r;
1544     char *buff;
1545 };
1546
1547 static apr_status_t r_flush(apr_vformatter_buff_t *buff)
1548 {
1549     /* callback function passed to ap_vformatter to be called when
1550      * vformatter needs to write into buff and buff.curpos > buff.endpos */
1551
1552     /* ap_vrprintf_data passed as a apr_vformatter_buff_t, which is then
1553      * "downcast" to an ap_vrprintf_data */
1554     struct ap_vrprintf_data *vd = (struct ap_vrprintf_data*)buff;
1555
1556     if (vd->r->connection->aborted)
1557         return -1;
1558
1559     /* r_flush is called when vbuff is completely full */
1560     if (buffer_output(vd->r, vd->buff, AP_IOBUFSIZE)) {
1561         return -1;
1562     }
1563
1564     /* reset the buffer position */
1565     vd->vbuff.curpos = vd->buff;
1566     vd->vbuff.endpos = vd->buff + AP_IOBUFSIZE;
1567
1568     return APR_SUCCESS;
1569 }
1570
1571 AP_DECLARE(int) ap_vrprintf(request_rec *r, const char *fmt, va_list va)
1572 {
1573     apr_size_t written;
1574     struct ap_vrprintf_data vd;
1575     char vrprintf_buf[AP_IOBUFSIZE];
1576
1577     vd.vbuff.curpos = vrprintf_buf;
1578     vd.vbuff.endpos = vrprintf_buf + AP_IOBUFSIZE;
1579     vd.r = r;
1580     vd.buff = vrprintf_buf;
1581
1582     if (r->connection->aborted)
1583         return -1;
1584
1585     written = apr_vformatter(r_flush, &vd.vbuff, fmt, va);
1586
1587     if (written != -1) {
1588         int n = vd.vbuff.curpos - vrprintf_buf;
1589
1590         /* last call to buffer_output, to finish clearing the buffer */
1591         if (buffer_output(r, vrprintf_buf,n) != APR_SUCCESS)
1592             return -1;
1593
1594         written += n;
1595     }
1596
1597     return written;
1598 }
1599
1600 AP_DECLARE_NONSTD(int) ap_rprintf(request_rec *r, const char *fmt, ...)
1601 {
1602     va_list va;
1603     int n;
1604
1605     if (r->connection->aborted)
1606         return -1;
1607
1608     va_start(va, fmt);
1609     n = ap_vrprintf(r, fmt, va);
1610     va_end(va);
1611
1612     return n;
1613 }
1614
1615 AP_DECLARE_NONSTD(int) ap_rvputs(request_rec *r, ...)
1616 {
1617     va_list va;
1618     const char *s;
1619     apr_size_t len;
1620     apr_size_t written = 0;
1621
1622     if (r->connection->aborted)
1623         return -1;
1624
1625     /* ### TODO: if the total output is large, put all the strings
1626      * ### into a single brigade, rather than flushing each time we
1627      * ### fill the buffer
1628      */
1629     va_start(va, r);
1630     while (1) {
1631         s = va_arg(va, const char *);
1632         if (s == NULL)
1633             break;
1634
1635         len = strlen(s);
1636         if (buffer_output(r, s, len) != APR_SUCCESS) {
1637             return -1;
1638         }
1639
1640         written += len;
1641     }
1642     va_end(va);
1643
1644     return written;
1645 }
1646
1647 AP_DECLARE(int) ap_rflush(request_rec *r)
1648 {
1649     conn_rec *c = r->connection;
1650     apr_bucket *b;
1651     ap_filter_t *f;
1652     old_write_filter_ctx *ctx;
1653     apr_status_t rv;
1654
1655     f = insert_old_write_filter(r);
1656     ctx = f->ctx;
1657
1658     b = apr_bucket_flush_create(c->bucket_alloc);
1659     APR_BRIGADE_INSERT_TAIL(ctx->tmpbb, b);
1660
1661     rv = ap_pass_brigade(r->output_filters, ctx->tmpbb);
1662     apr_brigade_cleanup(ctx->tmpbb);
1663     if (rv != APR_SUCCESS)
1664         return -1;
1665
1666     return 0;
1667 }
1668
1669 /*
1670  * This function sets the Last-Modified output header field to the value
1671  * of the mtime field in the request structure - rationalized to keep it from
1672  * being in the future.
1673  */
1674 AP_DECLARE(void) ap_set_last_modified(request_rec *r)
1675 {
1676     if (!r->assbackwards) {
1677         apr_time_t mod_time = ap_rationalize_mtime(r, r->mtime);
1678         char *datestr = apr_palloc(r->pool, APR_RFC822_DATE_LEN);
1679
1680         apr_rfc822_date(datestr, mod_time);
1681         apr_table_setn(r->headers_out, "Last-Modified", datestr);
1682     }
1683 }
1684
1685 typedef struct hdr_ptr {
1686     ap_filter_t *f;
1687     apr_bucket_brigade *bb;
1688 } hdr_ptr;
1689 static int send_header(void *data, const char *key, const char *val)
1690 {
1691     ap_fputstrs(((hdr_ptr*)data)->f, ((hdr_ptr*)data)->bb,
1692                 key, ": ", val, CRLF, NULL);
1693     return 1;
1694 }
1695 AP_DECLARE(void) ap_send_interim_response(request_rec *r, int send_headers)
1696 {
1697     hdr_ptr x;
1698     char *status_line = NULL;
1699     request_rec *rr;
1700
1701     if (r->proto_num < 1001) {
1702         /* don't send interim response to HTTP/1.0 Client */
1703         return;
1704     }
1705     if (!ap_is_HTTP_INFO(r->status)) {
1706         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
1707                       "Status is %d - not sending interim response", r->status);
1708         return;
1709     }
1710     if ((r->status == HTTP_CONTINUE) && !r->expecting_100) {
1711         /*
1712          * Don't send 100-Continue when there was no Expect: 100-continue
1713          * in the request headers. For origin servers this is a SHOULD NOT
1714          * for proxies it is a MUST NOT according to RFC 2616 8.2.3
1715          */
1716         return;
1717     }
1718
1719     /* if we send an interim response, we're no longer in a state of
1720      * expecting one.  Also, this could feasibly be in a subrequest,
1721      * so we need to propagate the fact that we responded.
1722      */
1723     for (rr = r; rr != NULL; rr = rr->main) {
1724         rr->expecting_100 = 0;
1725     }
1726
1727     status_line = apr_pstrcat(r->pool, AP_SERVER_PROTOCOL, " ", r->status_line, CRLF, NULL);
1728     ap_xlate_proto_to_ascii(status_line, strlen(status_line));
1729
1730     x.f = r->connection->output_filters;
1731     x.bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1732
1733     ap_fputs(x.f, x.bb, status_line);
1734     if (send_headers) {
1735         apr_table_do(send_header, &x, r->headers_out, NULL);
1736         apr_table_clear(r->headers_out);
1737     }
1738     ap_fputs(x.f, x.bb, CRLF_ASCII);
1739     ap_fflush(x.f, x.bb);
1740     apr_brigade_destroy(x.bb);
1741 }
1742
1743
1744 AP_IMPLEMENT_HOOK_RUN_ALL(int,post_read_request,
1745                           (request_rec *r), (r), OK, DECLINED)
1746 AP_IMPLEMENT_HOOK_RUN_ALL(int,log_transaction,
1747                           (request_rec *r), (r), OK, DECLINED)
1748 AP_IMPLEMENT_HOOK_RUN_FIRST(const char *,http_scheme,
1749                             (const request_rec *r), (r), NULL)
1750 AP_IMPLEMENT_HOOK_RUN_FIRST(unsigned short,default_port,
1751                             (const request_rec *r), (r), 0)