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