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