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