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