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