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