]> granicus.if.org Git - apache/blob - server/protocol.c
7bc292cb162479fde6504a0d14e2a363018ee7f8
[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     APR_HOOK_LINK(protocol_propose)
71     APR_HOOK_LINK(protocol_switch)
72     APR_HOOK_LINK(protocol_get)
73 )
74
75 AP_DECLARE_DATA ap_filter_rec_t *ap_old_write_func = NULL;
76
77
78 /* Patterns to match in ap_make_content_type() */
79 static const char *needcset[] = {
80     "text/plain",
81     "text/html",
82     NULL
83 };
84 static const apr_strmatch_pattern **needcset_patterns;
85 static const apr_strmatch_pattern *charset_pattern;
86
87 AP_DECLARE(void) ap_setup_make_content_type(apr_pool_t *pool)
88 {
89     int i;
90     for (i = 0; needcset[i]; i++) {
91         continue;
92     }
93     needcset_patterns = (const apr_strmatch_pattern **)
94         apr_palloc(pool, (i + 1) * sizeof(apr_strmatch_pattern *));
95     for (i = 0; needcset[i]; i++) {
96         needcset_patterns[i] = apr_strmatch_precompile(pool, needcset[i], 0);
97     }
98     needcset_patterns[i] = NULL;
99     charset_pattern = apr_strmatch_precompile(pool, "charset=", 0);
100 }
101
102 /*
103  * Builds the content-type that should be sent to the client from the
104  * content-type specified.  The following rules are followed:
105  *    - if type is NULL or "", return NULL (do not set content-type).
106  *    - if charset adding is disabled, stop processing and return type.
107  *    - then, if there are no parameters on type, add the default charset
108  *    - return type
109  */
110 AP_DECLARE(const char *)ap_make_content_type(request_rec *r, const char *type)
111 {
112     const apr_strmatch_pattern **pcset;
113     core_dir_config *conf =
114         (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
115     core_request_config *request_conf;
116     apr_size_t type_len;
117
118     if (!type || *type == '\0') {
119         return NULL;
120     }
121
122     if (conf->add_default_charset != ADD_DEFAULT_CHARSET_ON) {
123         return type;
124     }
125
126     request_conf = ap_get_core_module_config(r->request_config);
127     if (request_conf->suppress_charset) {
128         return type;
129     }
130
131     type_len = strlen(type);
132
133     if (apr_strmatch(charset_pattern, type, type_len) != NULL) {
134         /* already has parameter, do nothing */
135         /* XXX we don't check the validity */
136         ;
137     }
138     else {
139         /* see if it makes sense to add the charset. At present,
140          * we only add it if the Content-type is one of needcset[]
141          */
142         for (pcset = needcset_patterns; *pcset ; pcset++) {
143             if (apr_strmatch(*pcset, type, type_len) != NULL) {
144                 struct iovec concat[3];
145                 concat[0].iov_base = (void *)type;
146                 concat[0].iov_len = type_len;
147                 concat[1].iov_base = (void *)"; charset=";
148                 concat[1].iov_len = sizeof("; charset=") - 1;
149                 concat[2].iov_base = (void *)(conf->add_default_charset_name);
150                 concat[2].iov_len = strlen(conf->add_default_charset_name);
151                 type = apr_pstrcatv(r->pool, concat, 3, NULL);
152                 break;
153             }
154         }
155     }
156
157     return type;
158 }
159
160 AP_DECLARE(void) ap_set_content_length(request_rec *r, apr_off_t clength)
161 {
162     r->clength = clength;
163     apr_table_setn(r->headers_out, "Content-Length",
164                    apr_off_t_toa(r->pool, clength));
165 }
166
167 /*
168  * Return the latest rational time from a request/mtime (modification time)
169  * pair.  We return the mtime unless it's in the future, in which case we
170  * return the current time.  We use the request time as a reference in order
171  * to limit the number of calls to time().  We don't check for futurosity
172  * unless the mtime is at least as new as the reference.
173  */
174 AP_DECLARE(apr_time_t) ap_rationalize_mtime(request_rec *r, apr_time_t mtime)
175 {
176     apr_time_t now;
177
178     /* For all static responses, it's almost certain that the file was
179      * last modified before the beginning of the request.  So there's
180      * no reason to call time(NULL) again.  But if the response has been
181      * created on demand, then it might be newer than the time the request
182      * started.  In this event we really have to call time(NULL) again
183      * so that we can give the clients the most accurate Last-Modified.  If we
184      * were given a time in the future, we return the current time - the
185      * Last-Modified can't be in the future.
186      */
187     now = (mtime < r->request_time) ? r->request_time : apr_time_now();
188     return (mtime > now) ? now : mtime;
189 }
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 [CR]LF are *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 flags, 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     int fold = flags & AP_GETLINE_FOLD;
226     int crlf = flags & AP_GETLINE_CRLF;
227
228     /*
229      * Initialize last_char as otherwise a random value will be compared
230      * against APR_ASCII_LF at the end of the loop if bb only contains
231      * zero-length buckets.
232      */
233     if (last_char)
234         *last_char = '\0';
235
236     for (;;) {
237         apr_brigade_cleanup(bb);
238         rv = ap_get_brigade(r->proto_input_filters, bb, AP_MODE_GETLINE,
239                             APR_BLOCK_READ, 0);
240         if (rv != APR_SUCCESS) {
241             return rv;
242         }
243
244         /* Something horribly wrong happened.  Someone didn't block! 
245          * (this also happens at the end of each keepalive connection)
246          */
247         if (APR_BRIGADE_EMPTY(bb)) {
248             return APR_EGENERAL;
249         }
250
251         for (e = APR_BRIGADE_FIRST(bb);
252              e != APR_BRIGADE_SENTINEL(bb);
253              e = APR_BUCKET_NEXT(e))
254         {
255             const char *str;
256             apr_size_t len;
257
258             /* If we see an EOS, don't bother doing anything more. */
259             if (APR_BUCKET_IS_EOS(e)) {
260                 saw_eos = 1;
261                 break;
262             }
263
264             rv = apr_bucket_read(e, &str, &len, APR_BLOCK_READ);
265             if (rv != APR_SUCCESS) {
266                 return rv;
267             }
268
269             if (len == 0) {
270                 /* no use attempting a zero-byte alloc (hurts when
271                  * using --with-efence --enable-pool-debug) or
272                  * doing any of the other logic either
273                  */
274                 continue;
275             }
276
277             /* Would this overrun our buffer?  If so, we'll die. */
278             if (n < bytes_handled + len) {
279                 *read = bytes_handled;
280                 if (*s) {
281                     /* ensure this string is NUL terminated */
282                     if (bytes_handled > 0) {
283                         (*s)[bytes_handled-1] = '\0';
284                     }
285                     else {
286                         (*s)[0] = '\0';
287                     }
288                 }
289                 return APR_ENOSPC;
290             }
291
292             /* Do we have to handle the allocation ourselves? */
293             if (do_alloc) {
294                 /* We'll assume the common case where one bucket is enough. */
295                 if (!*s) {
296                     current_alloc = len;
297                     *s = apr_palloc(r->pool, current_alloc);
298                 }
299                 else if (bytes_handled + len > current_alloc) {
300                     /* Increase the buffer size */
301                     apr_size_t new_size = current_alloc * 2;
302                     char *new_buffer;
303
304                     if (bytes_handled + len > new_size) {
305                         new_size = (bytes_handled + len) * 2;
306                     }
307
308                     new_buffer = apr_palloc(r->pool, new_size);
309
310                     /* Copy what we already had. */
311                     memcpy(new_buffer, *s, bytes_handled);
312                     current_alloc = new_size;
313                     *s = new_buffer;
314                 }
315             }
316
317             /* Just copy the rest of the data to the end of the old buffer. */
318             pos = *s + bytes_handled;
319             memcpy(pos, str, len);
320             last_char = pos + len - 1;
321
322             /* We've now processed that new data - update accordingly. */
323             bytes_handled += len;
324         }
325
326         /* If we got a full line of input, stop reading */
327         if (last_char && (*last_char == APR_ASCII_LF)) {
328             break;
329         }
330     }
331
332     if (crlf && (last_char <= *s || last_char[-1] != APR_ASCII_CR)) {
333         *last_char = '\0';
334         bytes_handled = last_char - *s;
335         *read = bytes_handled;
336         return APR_EINVAL;
337     }
338
339     /* Now NUL-terminate the string at the end of the line;
340      * if the last-but-one character is a CR, terminate there */
341     if (last_char > *s && last_char[-1] == APR_ASCII_CR) {
342         last_char--;
343     }
344     *last_char = '\0';
345     bytes_handled = last_char - *s;
346
347     /* If we're folding, we have more work to do.
348      *
349      * Note that if an EOS was seen, we know we can't have another line.
350      */
351     if (fold && bytes_handled && !saw_eos) {
352         for (;;) {
353             const char *str;
354             apr_size_t len;
355             char c;
356
357             /* Clear the temp brigade for this filter read. */
358             apr_brigade_cleanup(bb);
359
360             /* We only care about the first byte. */
361             rv = ap_get_brigade(r->proto_input_filters, bb, AP_MODE_SPECULATIVE,
362                                 APR_BLOCK_READ, 1);
363             if (rv != APR_SUCCESS) {
364                 return rv;
365             }
366
367             if (APR_BRIGADE_EMPTY(bb)) {
368                 break;
369             }
370
371             e = APR_BRIGADE_FIRST(bb);
372
373             /* If we see an EOS, don't bother doing anything more. */
374             if (APR_BUCKET_IS_EOS(e)) {
375                 break;
376             }
377
378             rv = apr_bucket_read(e, &str, &len, APR_BLOCK_READ);
379             if (rv != APR_SUCCESS) {
380                 apr_brigade_cleanup(bb);
381                 return rv;
382             }
383
384             /* Found one, so call ourselves again to get the next line.
385              *
386              * FIXME: If the folding line is completely blank, should we
387              * stop folding?  Does that require also looking at the next
388              * char?
389              */
390             /* When we call destroy, the buckets are deleted, so save that
391              * one character we need.  This simplifies our execution paths
392              * at the cost of one character read.
393              */
394             c = *str;
395             if (c == APR_ASCII_BLANK || c == APR_ASCII_TAB) {
396                 /* Do we have enough space? We may be full now. */
397                 if (bytes_handled >= n) {
398                     *read = n;
399                     /* ensure this string is terminated */
400                     (*s)[n-1] = '\0';
401                     return APR_ENOSPC;
402                 }
403                 else {
404                     apr_size_t next_size, next_len;
405                     char *tmp;
406
407                     /* If we're doing the allocations for them, we have to
408                      * give ourselves a NULL and copy it on return.
409                      */
410                     if (do_alloc) {
411                         tmp = NULL;
412                     }
413                     else {
414                         /* We're null terminated. */
415                         tmp = last_char;
416                     }
417
418                     next_size = n - bytes_handled;
419
420                     rv = ap_rgetline_core(&tmp, next_size,
421                                           &next_len, r, 0, bb);
422                     if (rv != APR_SUCCESS) {
423                         return rv;
424                     }
425
426                     if (do_alloc && next_len > 0) {
427                         char *new_buffer;
428                         apr_size_t new_size = bytes_handled + next_len + 1;
429
430                         /* we need to alloc an extra byte for a null */
431                         new_buffer = apr_palloc(r->pool, new_size);
432
433                         /* Copy what we already had. */
434                         memcpy(new_buffer, *s, bytes_handled);
435
436                         /* copy the new line, including the trailing null */
437                         memcpy(new_buffer + bytes_handled, tmp, next_len + 1);
438                         *s = new_buffer;
439                     }
440
441                     last_char += next_len;
442                     bytes_handled += next_len;
443                 }
444             }
445             else { /* next character is not tab or space */
446                 break;
447             }
448         }
449     }
450     *read = bytes_handled;
451
452     /* PR#43039: We shouldn't accept NULL bytes within the line */
453     if (strlen(*s) < bytes_handled) {
454         return APR_EINVAL;
455     }
456
457     return APR_SUCCESS;
458 }
459
460 #if APR_CHARSET_EBCDIC
461 AP_DECLARE(apr_status_t) ap_rgetline(char **s, apr_size_t n,
462                                      apr_size_t *read, request_rec *r,
463                                      int fold, apr_bucket_brigade *bb)
464 {
465     /* on ASCII boxes, ap_rgetline is a macro which simply invokes
466      * ap_rgetline_core with the same parms
467      *
468      * on EBCDIC boxes, each complete http protocol input line needs to be
469      * translated into the code page used by the compiler.  Since
470      * ap_rgetline_core uses recursion, we do the translation in a wrapper
471      * function to ensure that each input character gets translated only once.
472      */
473     apr_status_t rv;
474
475     rv = ap_rgetline_core(s, n, read, r, fold, bb);
476     if (rv == APR_SUCCESS) {
477         ap_xlate_proto_from_ascii(*s, *read);
478     }
479     return rv;
480 }
481 #endif
482
483 AP_DECLARE(int) ap_getline(char *s, int n, request_rec *r, int flags)
484 {
485     char *tmp_s = s;
486     apr_status_t rv;
487     apr_size_t len;
488     apr_bucket_brigade *tmp_bb;
489
490     tmp_bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
491     rv = ap_rgetline(&tmp_s, n, &len, r, flags, tmp_bb);
492     apr_brigade_destroy(tmp_bb);
493
494     /* Map the out-of-space condition to the old API. */
495     if (rv == APR_ENOSPC) {
496         return n;
497     }
498
499     /* Anything else is just bad. */
500     if (rv != APR_SUCCESS) {
501         return -1;
502     }
503
504     return (int)len;
505 }
506
507 /* parse_uri: break apart the uri
508  * Side Effects:
509  * - sets r->args to rest after '?' (or NULL if no '?')
510  * - sets r->uri to request uri (without r->args part)
511  * - sets r->hostname (if not set already) from request (scheme://host:port)
512  */
513 AP_CORE_DECLARE(void) ap_parse_uri(request_rec *r, const char *uri)
514 {
515     int status = HTTP_OK;
516
517     r->unparsed_uri = apr_pstrdup(r->pool, uri);
518
519     /* http://issues.apache.org/bugzilla/show_bug.cgi?id=31875
520      * http://issues.apache.org/bugzilla/show_bug.cgi?id=28450
521      *
522      * This is not in fact a URI, it's a path.  That matters in the
523      * case of a leading double-slash.  We need to resolve the issue
524      * by normalising that out before treating it as a URI.
525      */
526     while ((uri[0] == '/') && (uri[1] == '/')) {
527         ++uri ;
528     }
529     if (r->method_number == M_CONNECT) {
530         status = apr_uri_parse_hostinfo(r->pool, uri, &r->parsed_uri);
531     }
532     else {
533         status = apr_uri_parse(r->pool, uri, &r->parsed_uri);
534     }
535
536     if (status == APR_SUCCESS) {
537         /* if it has a scheme we may need to do absoluteURI vhost stuff */
538         if (r->parsed_uri.scheme
539             && !strcasecmp(r->parsed_uri.scheme, ap_http_scheme(r))) {
540             r->hostname = r->parsed_uri.hostname;
541         }
542         else if (r->method_number == M_CONNECT) {
543             r->hostname = r->parsed_uri.hostname;
544         }
545
546         r->args = r->parsed_uri.query;
547         r->uri = r->parsed_uri.path ? r->parsed_uri.path
548                  : apr_pstrdup(r->pool, "/");
549
550 #if defined(OS2) || defined(WIN32)
551         /* Handle path translations for OS/2 and plug security hole.
552          * This will prevent "http://www.wherever.com/..\..\/" from
553          * returning a directory for the root drive.
554          */
555         {
556             char *x;
557
558             for (x = r->uri; (x = strchr(x, '\\')) != NULL; )
559                 *x = '/';
560         }
561 #endif /* OS2 || WIN32 */
562     }
563     else {
564         r->args = NULL;
565         r->hostname = NULL;
566         r->status = HTTP_BAD_REQUEST;             /* set error status */
567         r->uri = apr_pstrdup(r->pool, uri);
568     }
569 }
570
571 /* get the length of the field name for logging, but no more than 80 bytes */
572 #define LOG_NAME_MAX_LEN 80
573 static int field_name_len(const char *field)
574 {
575     const char *end = ap_strchr_c(field, ':');
576     if (end == NULL || end - field > LOG_NAME_MAX_LEN)
577         return LOG_NAME_MAX_LEN;
578     return end - field;
579 }
580
581 static int read_request_line(request_rec *r, apr_bucket_brigade *bb)
582 {
583     enum {
584         rrl_none, rrl_badmethod, rrl_badwhitespace, rrl_excesswhitespace,
585         rrl_missinguri, rrl_baduri, rrl_badprotocol, rrl_trailingtext,
586         rrl_badmethod09, rrl_reject09
587     } deferred_error = rrl_none;
588     char *ll;
589     char *uri;
590     apr_size_t len;
591     int num_blank_lines = DEFAULT_LIMIT_BLANK_LINES;
592     core_server_config *conf = ap_get_core_module_config(r->server->module_config);
593     int strict = (conf->http_conformance != AP_HTTP_CONFORMANCE_UNSAFE);
594
595     /* Read past empty lines until we get a real request line,
596      * a read error, the connection closes (EOF), or we timeout.
597      *
598      * We skip empty lines because browsers have to tack a CRLF on to the end
599      * of POSTs to support old CERN webservers.  But note that we may not
600      * have flushed any previous response completely to the client yet.
601      * We delay the flush as long as possible so that we can improve
602      * performance for clients that are pipelining requests.  If a request
603      * is pipelined then we won't block during the (implicit) read() below.
604      * If the requests aren't pipelined, then the client is still waiting
605      * for the final buffer flush from us, and we will block in the implicit
606      * read().  B_SAFEREAD ensures that the BUFF layer flushes if it will
607      * have to block during a read.
608      */
609
610     do {
611         apr_status_t rv;
612
613         /* ensure ap_rgetline allocates memory each time thru the loop
614          * if there are empty lines
615          */
616         r->the_request = NULL;
617         rv = ap_rgetline(&(r->the_request), (apr_size_t)(r->server->limit_req_line + 2),
618                          &len, r, strict ? AP_GETLINE_CRLF : 0, bb);
619
620         if (rv != APR_SUCCESS) {
621             r->request_time = apr_time_now();
622
623             /* ap_rgetline returns APR_ENOSPC if it fills up the
624              * buffer before finding the end-of-line.  This is only going to
625              * happen if it exceeds the configured limit for a request-line.
626              */
627             if (APR_STATUS_IS_ENOSPC(rv)) {
628                 r->status = HTTP_REQUEST_URI_TOO_LARGE;
629             }
630             else if (APR_STATUS_IS_TIMEUP(rv)) {
631                 r->status = HTTP_REQUEST_TIME_OUT;
632             }
633             else if (APR_STATUS_IS_EINVAL(rv)) {
634                 r->status = HTTP_BAD_REQUEST;
635             }
636             r->proto_num = HTTP_VERSION(1,0);
637             r->protocol  = apr_pstrdup(r->pool, "HTTP/1.0");
638             return 0;
639         }
640     } while ((len <= 0) && (--num_blank_lines >= 0));
641
642     if (APLOGrtrace5(r)) {
643         ap_log_rerror(APLOG_MARK, APLOG_TRACE5, 0, r,
644                       "Request received from client: %s",
645                       ap_escape_logitem(r->pool, r->the_request));
646     }
647
648     r->request_time = apr_time_now();
649
650     r->method = r->the_request;
651
652     /* If there is whitespace before a method, skip it and mark in error */
653     if (apr_isspace(*r->method)) {
654         deferred_error = rrl_badwhitespace; 
655         for ( ; apr_isspace(*r->method); ++r->method)
656             ; 
657     }
658
659     /* Scan the method up to the next whitespace, ensure it contains only
660      * valid http-token characters, otherwise mark in error
661      */
662     if (strict) {
663         ll = (char*) ap_scan_http_token(r->method);
664     }
665     else {
666         ll = (char*) ap_scan_vchar_obstext(r->method);
667     }
668
669     if (((ll == r->method) || (*ll && !apr_isspace(*ll)))
670             && deferred_error == rrl_none) {
671         deferred_error = rrl_badmethod;
672         ll = strpbrk(ll, "\t\n\v\f\r ");
673     }
674
675     /* Verify method terminated with a single SP, or mark as specific error */
676     if (!ll) {
677         if (deferred_error == rrl_none)
678             deferred_error = rrl_missinguri;
679         r->protocol = uri = "";
680         len = 0;
681         goto rrl_done;
682     }
683     else if (strict && ll[0] && apr_isspace(ll[1])
684              && deferred_error == rrl_none) {
685         deferred_error = rrl_excesswhitespace; 
686     }
687
688     /* Advance uri pointer over leading whitespace, NUL terminate the method
689      * If non-SP whitespace is encountered, mark as specific error
690      */
691     for (uri = ll; apr_isspace(*uri); ++uri) 
692         if (*uri != ' ' && deferred_error == rrl_none)
693             deferred_error = rrl_badwhitespace; 
694     *ll = '\0';
695
696     if (!*uri && deferred_error == rrl_none)
697         deferred_error = rrl_missinguri;
698
699     /* Scan the URI up to the next whitespace, ensure it contains no raw
700      * control characters, otherwise mark in error
701      */
702     ll = (char*) ap_scan_vchar_obstext(uri);
703     if (ll == uri || (*ll && !apr_isspace(*ll))) {
704         deferred_error = rrl_baduri;
705         ll = strpbrk(ll, "\t\n\v\f\r ");
706     }
707
708     /* Verify URI terminated with a single SP, or mark as specific error */
709     if (!ll) {
710         r->protocol = "";
711         len = 0;
712         goto rrl_done;
713     }
714     else if (strict && ll[0] && apr_isspace(ll[1])
715              && deferred_error == rrl_none) {
716         deferred_error = rrl_excesswhitespace; 
717     }
718
719     /* Advance protocol pointer over leading whitespace, NUL terminate the uri
720      * If non-SP whitespace is encountered, mark as specific error
721      */
722     for (r->protocol = ll; apr_isspace(*r->protocol); ++r->protocol) 
723         if (*r->protocol != ' ' && deferred_error == rrl_none)
724             deferred_error = rrl_badwhitespace; 
725     *ll = '\0';
726
727     /* Scan the protocol up to the next whitespace, validation comes later */
728     if (!(ll = (char*) ap_scan_vchar_obstext(r->protocol))) {
729         len = strlen(r->protocol);
730         goto rrl_done;
731     }
732     len = ll - r->protocol;
733
734     /* Advance over trailing whitespace, if found mark in error,
735      * determine if trailing text is found, unconditionally mark in error,
736      * finally NUL terminate the protocol string
737      */
738     if (*ll && !apr_isspace(*ll)) {
739         deferred_error = rrl_badprotocol;
740     }
741     else if (strict && *ll) {
742         deferred_error = rrl_excesswhitespace;
743     }
744     else {
745         for ( ; apr_isspace(*ll); ++ll)
746             if (*ll != ' ' && deferred_error == rrl_none)
747                 deferred_error = rrl_badwhitespace; 
748         if (*ll && deferred_error == rrl_none)
749             deferred_error = rrl_trailingtext;
750     }
751     *((char *)r->protocol + len) = '\0';
752
753 rrl_done:
754     /* For internal integrety and palloc efficiency, reconstruct the_request
755      * in one palloc, using only single SP characters, per spec.
756      */
757     r->the_request = apr_pstrcat(r->pool, r->method, *uri ? " " : NULL, uri,
758                                  *r->protocol ? " " : NULL, r->protocol, NULL);
759
760     if (len == 8
761             && r->protocol[0] == 'H' && r->protocol[1] == 'T'
762             && r->protocol[2] == 'T' && r->protocol[3] == 'P'
763             && r->protocol[4] == '/' && apr_isdigit(r->protocol[5])
764             && r->protocol[6] == '.' && apr_isdigit(r->protocol[7])
765             && r->protocol[5] != '0') {
766         r->assbackwards = 0;
767         r->proto_num = HTTP_VERSION(r->protocol[5] - '0', r->protocol[7] - '0');
768     }
769     else if (len == 8
770                  && (r->protocol[0] == 'H' || r->protocol[0] == 'h')
771                  && (r->protocol[1] == 'T' || r->protocol[1] == 't')
772                  && (r->protocol[2] == 'T' || r->protocol[2] == 't')
773                  && (r->protocol[3] == 'P' || r->protocol[3] == 'p')
774                  && r->protocol[4] == '/' && apr_isdigit(r->protocol[5])
775                  && r->protocol[6] == '.' && apr_isdigit(r->protocol[7])
776                  && r->protocol[5] != '0') {
777         r->assbackwards = 0;
778         r->proto_num = HTTP_VERSION(r->protocol[5] - '0', r->protocol[7] - '0');
779         if (strict && deferred_error == rrl_none)
780             deferred_error = rrl_badprotocol;
781         else
782             memcpy((char*)r->protocol, "HTTP", 4);
783     }
784     else if (r->protocol[0]) {
785         r->assbackwards = 0;
786         r->proto_num = HTTP_VERSION(1,0);
787         /* Defer setting the r->protocol string till error msg is composed */
788         if (strict && deferred_error == rrl_none)
789             deferred_error = rrl_badprotocol;
790         else
791             r->protocol  = "HTTP/1.0";
792     }
793     else {
794         r->assbackwards = 1;
795         r->protocol = "HTTP/0.9";
796         r->proto_num = HTTP_VERSION(0, 9);
797     }
798
799     /* Determine the method_number and parse the uri prior to invoking error
800      * handling, such that these fields are available for subsitution
801      */
802     r->method_number = ap_method_number_of(r->method);
803     if (r->method_number == M_GET && r->method[0] == 'H')
804         r->header_only = 1;
805
806     ap_parse_uri(r, uri);
807
808     /* With the request understood, we can consider HTTP/0.9 specific errors */
809     if (r->proto_num == HTTP_VERSION(0, 9) && deferred_error == rrl_none) {
810         if (conf->http09_enable == AP_HTTP09_DISABLE)
811             deferred_error = rrl_reject09;
812         else if (strict && (r->method_number != M_GET || r->header_only))
813             deferred_error = rrl_badmethod09;
814     }
815
816     /* Now that the method, uri and protocol are all processed,
817      * we can safely resume any deferred error reporting
818      */
819     if (deferred_error != rrl_none) {
820         if (deferred_error == rrl_badmethod)
821             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03445)
822                           "HTTP Request Line; Invalid method token: '%.*s'",
823                           field_name_len(r->method), r->method);
824         else if (deferred_error == rrl_badmethod09)
825             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03444)
826                           "HTTP Request Line; Invalid method token: '%.*s'"
827                           " (only GET is allowed for HTTP/0.9 requests)",
828                           field_name_len(r->method), r->method);
829         else if (deferred_error == rrl_missinguri)
830             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03446)
831                           "HTTP Request Line; Missing URI");
832         else if (deferred_error == rrl_baduri)
833             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03454)
834                           "HTTP Request Line; URI incorrectly encoded: '%.*s'",
835                           field_name_len(r->uri), r->uri);
836         else if (deferred_error == rrl_badwhitespace)
837             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03447)
838                           "HTTP Request Line; Invalid whitespace");
839         else if (deferred_error == rrl_excesswhitespace)
840             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03448)
841                           "HTTP Request Line; Excess whitespace "
842                           "(disallowed by HttpProtocolOptions Strict");
843         else if (deferred_error == rrl_trailingtext)
844             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03449)
845                           "HTTP Request Line; Extraneous text found '%.*s' "
846                           "(perhaps whitespace was injected?)",
847                           field_name_len(ll), ll);
848         else if (deferred_error == rrl_reject09)
849             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02401)
850                           "HTTP Request Line; Rejected HTTP/0.9 request");
851         else if (deferred_error == rrl_badprotocol)
852             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02418)
853                           "HTTP Request Line; Unrecognized protocol '%.*s' "
854                           "(perhaps whitespace was injected?)",
855                           field_name_len(r->protocol), r->protocol);
856         r->status = HTTP_BAD_REQUEST;
857         goto rrl_failed;
858     }
859
860     if (conf->http_methods == AP_HTTP_METHODS_REGISTERED
861             && r->method_number == M_INVALID) {
862         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02423)
863                       "HTTP Request Line; Unrecognized HTTP method: '%.*s' "
864                       "(disallowed by RegisteredMethods)",
865                       field_name_len(r->method), r->method);
866         r->status = HTTP_NOT_IMPLEMENTED;
867         /* This can't happen in an HTTP/0.9 request, we verified GET above */
868         return 0;
869     }
870
871     if (r->status != HTTP_OK) {
872         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03450)
873                       "HTTP Request Line; Unable to parse URI: '%.*s'",
874                       field_name_len(r->uri), r->uri);
875         goto rrl_failed;
876     }
877
878     if (strict) {
879         if (r->parsed_uri.fragment) {
880             /* RFC3986 3.5: no fragment */
881             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02421)
882                           "HTTP Request Line; URI must not contain a fragment");
883             r->status = HTTP_BAD_REQUEST;
884             goto rrl_failed;
885         }
886         if (r->parsed_uri.user || r->parsed_uri.password) {
887             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02422)
888                           "HTTP Request Line; URI must not contain a "
889                           "username/password");
890             r->status = HTTP_BAD_REQUEST;
891             goto rrl_failed;
892         }
893     }
894
895     return 1;
896
897 rrl_failed:
898     if (r->proto_num == HTTP_VERSION(0, 9)) {
899         /* Send all parsing and protocol error response with 1.x behavior,
900          * and reserve 505 errors for actual HTTP protocols presented.
901          * As called out in RFC7230 3.5, any errors parsing the protocol
902          * from the request line are nearly always misencoded HTTP/1.x
903          * requests. Only a valid 0.9 request with no parsing errors
904          * at all may be treated as a simple request, if allowed.
905          */
906         r->assbackwards = 0;
907         r->connection->keepalive = AP_CONN_CLOSE;
908         r->proto_num = HTTP_VERSION(1, 0);
909         r->protocol  = "HTTP/1.0";
910     }
911     return 0;
912 }
913
914 static int table_do_fn_check_lengths(void *r_, const char *key,
915                                      const char *value)
916 {
917     request_rec *r = r_;
918     if (value == NULL || r->server->limit_req_fieldsize >= strlen(value) )
919         return 1;
920
921     r->status = HTTP_BAD_REQUEST;
922     apr_table_setn(r->notes, "error-notes",
923                    "Size of a request header field exceeds server limit.");
924     ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00560) "Request "
925                   "header exceeds LimitRequestFieldSize after merging: %.*s",
926                   field_name_len(key), key);
927     return 0;
928 }
929
930 AP_DECLARE(void) ap_get_mime_headers_core(request_rec *r, apr_bucket_brigade *bb)
931 {
932     char *last_field = NULL;
933     apr_size_t last_len = 0;
934     apr_size_t alloc_len = 0;
935     char *field;
936     char *value;
937     apr_size_t len;
938     int fields_read = 0;
939     char *tmp_field;
940     core_server_config *conf = ap_get_core_module_config(r->server->module_config);
941     int strict = (conf->http_conformance != AP_HTTP_CONFORMANCE_UNSAFE);
942
943     /*
944      * Read header lines until we get the empty separator line, a read error,
945      * the connection closes (EOF), reach the server limit, or we timeout.
946      */
947     while(1) {
948         apr_status_t rv;
949
950         field = NULL;
951         rv = ap_rgetline(&field, r->server->limit_req_fieldsize + 2,
952                          &len, r, strict ? AP_GETLINE_CRLF : 0, bb);
953
954         if (rv != APR_SUCCESS) {
955             if (APR_STATUS_IS_TIMEUP(rv)) {
956                 r->status = HTTP_REQUEST_TIME_OUT;
957             }
958             else {
959                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r, 
960                               "Failed to read request header line %s", field);
961                 r->status = HTTP_BAD_REQUEST;
962             }
963
964             /* ap_rgetline returns APR_ENOSPC if it fills up the buffer before
965              * finding the end-of-line.  This is only going to happen if it
966              * exceeds the configured limit for a field size.
967              */
968             if (rv == APR_ENOSPC) {
969                 apr_table_setn(r->notes, "error-notes",
970                                "Size of a request header field "
971                                "exceeds server limit.");
972                 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00561)
973                               "Request header exceeds LimitRequestFieldSize%s"
974                               "%.*s",
975                               (field && *field) ? ": " : "",
976                               (field) ? field_name_len(field) : 0,
977                               (field) ? field : "");
978             }
979             return;
980         }
981
982         /* For all header values, and all obs-fold lines, the presence of
983          * additional whitespace is a no-op, so collapse trailing whitespace
984          * to save buffer allocation and optimize copy operations.
985          * Do not remove the last single whitespace under any condition.
986          */
987         while (len > 1 && (field[len-1] == '\t' || field[len-1] == ' ')) {
988             field[--len] = '\0';
989         } 
990
991         if (*field == '\t' || *field == ' ') {
992
993             /* Append any newly-read obs-fold line onto the preceding
994              * last_field line we are processing
995              */
996             apr_size_t fold_len;
997
998             if (last_field == NULL) {
999                 r->status = HTTP_BAD_REQUEST;
1000                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03442)
1001                               "Line folding encountered before first"
1002                               " header line");
1003                 return;
1004             }
1005
1006             if (field[1] == '\0') {
1007                 r->status = HTTP_BAD_REQUEST;
1008                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03443)
1009                               "Empty folded line encountered");
1010                 return;
1011             }
1012
1013             /* Leading whitespace on an obs-fold line can be
1014              * similarly discarded */
1015             while (field[1] == '\t' || field[1] == ' ') {
1016                 ++field; --len;
1017             }
1018
1019             /* This line is a continuation of the preceding line(s),
1020              * so append it to the line that we've set aside.
1021              * Note: this uses a power-of-two allocator to avoid
1022              * doing O(n) allocs and using O(n^2) space for
1023              * continuations that span many many lines.
1024              */
1025             fold_len = last_len + len + 1; /* trailing null */
1026
1027             if (fold_len >= (apr_size_t)(r->server->limit_req_fieldsize)) {
1028                 r->status = HTTP_BAD_REQUEST;
1029                 /* report what we have accumulated so far before the
1030                  * overflow (last_field) as the field with the problem
1031                  */
1032                 apr_table_setn(r->notes, "error-notes",
1033                                "Size of a request header field "
1034                                "exceeds server limit.");
1035                 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00562)
1036                               "Request header exceeds LimitRequestFieldSize "
1037                               "after folding: %.*s",
1038                               field_name_len(last_field), last_field);
1039                 return;
1040             }
1041
1042             if (fold_len > alloc_len) {
1043                 char *fold_buf;
1044                 alloc_len += alloc_len;
1045                 if (fold_len > alloc_len) {
1046                     alloc_len = fold_len;
1047                 }
1048                 fold_buf = (char *)apr_palloc(r->pool, alloc_len);
1049                 memcpy(fold_buf, last_field, last_len);
1050                 last_field = fold_buf;
1051             }
1052             memcpy(last_field + last_len, field, len +1); /* +1 for nul */
1053             /* Replace obs-fold w/ SP per RFC 7230 3.2.4 */
1054             last_field[last_len] = ' ';
1055             last_len += len;
1056
1057             /* We've appended this obs-fold line to last_len, proceed to
1058              * read the next input line
1059              */
1060             continue;
1061         }
1062         else if (last_field != NULL) {
1063
1064             /* Process the previous last_field header line with all obs-folded
1065              * segments already concatinated (this is not operating on the
1066              * most recently read input line).
1067              */
1068
1069             if (r->server->limit_req_fields
1070                     && (++fields_read > r->server->limit_req_fields)) {
1071                 r->status = HTTP_BAD_REQUEST;
1072                 apr_table_setn(r->notes, "error-notes",
1073                                "The number of request header fields "
1074                                "exceeds this server's limit.");
1075                 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00563)
1076                               "Number of request headers exceeds "
1077                               "LimitRequestFields");
1078                 return;
1079             }
1080
1081             if (!strict)
1082             {
1083                 /* Not Strict ('Unsafe' mode), using the legacy parser */
1084
1085                 if (!(value = strchr(last_field, ':'))) { /* Find ':' or */
1086                     r->status = HTTP_BAD_REQUEST;   /* abort bad request */
1087                     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00564)
1088                                   "Request header field is missing ':' "
1089                                   "separator: %.*s", (int)LOG_NAME_MAX_LEN,
1090                                   last_field);
1091                     return;
1092                 }
1093
1094                 /* last character of field-name */
1095                 tmp_field = value - (value > last_field ? 1 : 0);
1096
1097                 *value++ = '\0'; /* NUL-terminate at colon */
1098
1099                 if (strpbrk(last_field, "\t\n\v\f\r ")) {
1100                     r->status = HTTP_BAD_REQUEST;
1101                     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03452)
1102                                   "Request header field name presented"
1103                                   " invalid whitespace");
1104                     return;
1105                 }
1106
1107                 while (*value == ' ' || *value == '\t') {
1108                      ++value;            /* Skip to start of value   */
1109                 }
1110
1111                 if (strpbrk(value, "\n\v\f\r")) {
1112                     r->status = HTTP_BAD_REQUEST;
1113                     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03451)
1114                                   "Request header field value presented"
1115                                   " bad whitespace");
1116                     return;
1117                 }
1118
1119                 if (tmp_field == last_field) {
1120                     r->status = HTTP_BAD_REQUEST;
1121                     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(03453)
1122                                   "Request header field name was empty");
1123                     return;
1124                 }
1125             }
1126             else /* Using strict RFC7230 parsing */
1127             {
1128                 /* Ensure valid token chars before ':' per RFC 7230 3.2.4 */
1129                 value = (char *)ap_scan_http_token(last_field);
1130                 if ((value == last_field) || *value != ':') {
1131                     r->status = HTTP_BAD_REQUEST;
1132                     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02426)
1133                                   "Request header field name is malformed: "
1134                                   "%.*s", (int)LOG_NAME_MAX_LEN, last_field);
1135                     return;
1136                 }
1137
1138                 *value++ = '\0'; /* NUL-terminate last_field name at ':' */
1139
1140                 while (*value == ' ' || *value == '\t') {
1141                     ++value;     /* Skip LWS of value */
1142                 }
1143
1144                 /* Find invalid, non-HT ctrl char, or the trailing NULL */
1145                 tmp_field = (char *)ap_scan_http_field_content(value);
1146
1147                 /* Reject value for all garbage input (CTRLs excluding HT)
1148                  * e.g. only VCHAR / SP / HT / obs-text are allowed per
1149                  * RFC7230 3.2.6 - leave all more explicit rule enforcement
1150                  * for specific header handler logic later in the cycle
1151                  */
1152                 if (*tmp_field != '\0') {
1153                     r->status = HTTP_BAD_REQUEST;
1154                     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02427)
1155                                   "Request header value is malformed: "
1156                                   "%.*s", (int)LOG_NAME_MAX_LEN, value);
1157                     return;
1158                 }
1159             }
1160
1161             apr_table_addn(r->headers_in, last_field, value);
1162
1163             /* This last_field header is now stored in headers_in,
1164              * resume processing of the current input line.
1165              */
1166         }
1167
1168         /* Found the terminating empty end-of-headers line, stop. */
1169         if (len == 0) {
1170             break;
1171         }
1172
1173         /* Keep track of this new header line so that we can extend it across
1174          * any obs-fold or parse it on the next loop iteration. We referenced
1175          * our previously allocated buffer in r->headers_in,
1176          * so allocate a fresh buffer if required.
1177          */
1178         alloc_len = 0;
1179         last_field = field;
1180         last_len = len;
1181     }
1182
1183     /* Combine multiple message-header fields with the same
1184      * field-name, following RFC 2616, 4.2.
1185      */
1186     apr_table_compress(r->headers_in, APR_OVERLAP_TABLES_MERGE);
1187
1188     /* enforce LimitRequestFieldSize for merged headers */
1189     apr_table_do(table_do_fn_check_lengths, r, r->headers_in, NULL);
1190 }
1191
1192 AP_DECLARE(void) ap_get_mime_headers(request_rec *r)
1193 {
1194     apr_bucket_brigade *tmp_bb;
1195     tmp_bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1196     ap_get_mime_headers_core(r, tmp_bb);
1197     apr_brigade_destroy(tmp_bb);
1198 }
1199
1200 request_rec *ap_read_request(conn_rec *conn)
1201 {
1202     request_rec *r;
1203     apr_pool_t *p;
1204     const char *expect;
1205     int access_status;
1206     apr_bucket_brigade *tmp_bb;
1207     apr_socket_t *csd;
1208     apr_interval_time_t cur_timeout;
1209
1210
1211     apr_pool_create(&p, conn->pool);
1212     apr_pool_tag(p, "request");
1213     r = apr_pcalloc(p, sizeof(request_rec));
1214     AP_READ_REQUEST_ENTRY((intptr_t)r, (uintptr_t)conn);
1215     r->pool            = p;
1216     r->connection      = conn;
1217     r->server          = conn->base_server;
1218
1219     r->user            = NULL;
1220     r->ap_auth_type    = NULL;
1221
1222     r->allowed_methods = ap_make_method_list(p, 2);
1223
1224     r->headers_in      = apr_table_make(r->pool, 25);
1225     r->trailers_in     = apr_table_make(r->pool, 5);
1226     r->subprocess_env  = apr_table_make(r->pool, 25);
1227     r->headers_out     = apr_table_make(r->pool, 12);
1228     r->err_headers_out = apr_table_make(r->pool, 5);
1229     r->trailers_out    = apr_table_make(r->pool, 5);
1230     r->notes           = apr_table_make(r->pool, 5);
1231
1232     r->request_config  = ap_create_request_config(r->pool);
1233     /* Must be set before we run create request hook */
1234
1235     r->proto_output_filters = conn->output_filters;
1236     r->output_filters  = r->proto_output_filters;
1237     r->proto_input_filters = conn->input_filters;
1238     r->input_filters   = r->proto_input_filters;
1239     ap_run_create_request(r);
1240     r->per_dir_config  = r->server->lookup_defaults;
1241
1242     r->sent_bodyct     = 0;                      /* bytect isn't for body */
1243
1244     r->read_length     = 0;
1245     r->read_body       = REQUEST_NO_BODY;
1246
1247     r->status          = HTTP_OK;  /* Until further notice */
1248     r->the_request     = NULL;
1249
1250     /* Begin by presuming any module can make its own path_info assumptions,
1251      * until some module interjects and changes the value.
1252      */
1253     r->used_path_info = AP_REQ_DEFAULT_PATH_INFO;
1254
1255     r->useragent_addr = conn->client_addr;
1256     r->useragent_ip = conn->client_ip;
1257
1258     tmp_bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1259
1260     ap_run_pre_read_request(r, conn);
1261
1262     /* Get the request... */
1263     if (!read_request_line(r, tmp_bb)) {
1264         switch (r->status) {
1265         case HTTP_REQUEST_URI_TOO_LARGE:
1266         case HTTP_BAD_REQUEST:
1267         case HTTP_VERSION_NOT_SUPPORTED:
1268         case HTTP_NOT_IMPLEMENTED:
1269             if (r->status == HTTP_REQUEST_URI_TOO_LARGE) {
1270                 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00565)
1271                               "request failed: client's request-line exceeds LimitRequestLine (longer than %d)",
1272                               r->server->limit_req_line);
1273             }
1274             else if (r->method == NULL) {
1275                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00566)
1276                               "request failed: malformed request line");
1277             }
1278             access_status = r->status;
1279             r->status = HTTP_OK;
1280             ap_die(access_status, r);
1281             ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
1282             ap_run_log_transaction(r);
1283             r = NULL;
1284             apr_brigade_destroy(tmp_bb);
1285             goto traceout;
1286         case HTTP_REQUEST_TIME_OUT:
1287             ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, NULL);
1288             if (!r->connection->keepalives)
1289                 ap_run_log_transaction(r);
1290             apr_brigade_destroy(tmp_bb);
1291             goto traceout;
1292         default:
1293             apr_brigade_destroy(tmp_bb);
1294             r = NULL;
1295             goto traceout;
1296         }
1297     }
1298
1299     /* We may have been in keep_alive_timeout mode, so toggle back
1300      * to the normal timeout mode as we fetch the header lines,
1301      * as necessary.
1302      */
1303     csd = ap_get_conn_socket(conn);
1304     apr_socket_timeout_get(csd, &cur_timeout);
1305     if (cur_timeout != conn->base_server->timeout) {
1306         apr_socket_timeout_set(csd, conn->base_server->timeout);
1307         cur_timeout = conn->base_server->timeout;
1308     }
1309
1310     if (!r->assbackwards) {
1311         const char *tenc;
1312
1313         ap_get_mime_headers_core(r, tmp_bb);
1314         if (r->status != HTTP_OK) {
1315             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00567)
1316                           "request failed: error reading the headers");
1317             ap_send_error_response(r, 0);
1318             ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
1319             ap_run_log_transaction(r);
1320             apr_brigade_destroy(tmp_bb);
1321             goto traceout;
1322         }
1323
1324         tenc = apr_table_get(r->headers_in, "Transfer-Encoding");
1325         if (tenc) {
1326             /* http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-23
1327              * Section 3.3.3.3: "If a Transfer-Encoding header field is
1328              * present in a request and the chunked transfer coding is not
1329              * the final encoding ...; the server MUST respond with the 400
1330              * (Bad Request) status code and then close the connection".
1331              */
1332             if (!(strcasecmp(tenc, "chunked") == 0 /* fast path */
1333                     || ap_find_last_token(r->pool, tenc, "chunked"))) {
1334                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02539)
1335                               "client sent unknown Transfer-Encoding "
1336                               "(%s): %s", tenc, r->uri);
1337                 r->status = HTTP_BAD_REQUEST;
1338                 conn->keepalive = AP_CONN_CLOSE;
1339                 ap_send_error_response(r, 0);
1340                 ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
1341                 ap_run_log_transaction(r);
1342                 apr_brigade_destroy(tmp_bb);
1343                 goto traceout;
1344             }
1345
1346             /* http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-23
1347              * Section 3.3.3.3: "If a message is received with both a
1348              * Transfer-Encoding and a Content-Length header field, the
1349              * Transfer-Encoding overrides the Content-Length. ... A sender
1350              * MUST remove the received Content-Length field".
1351              */
1352             apr_table_unset(r->headers_in, "Content-Length");
1353         }
1354     }
1355
1356     apr_brigade_destroy(tmp_bb);
1357
1358     /* update what we think the virtual host is based on the headers we've
1359      * now read. may update status.
1360      */
1361     ap_update_vhost_from_headers(r);
1362     access_status = r->status;
1363
1364     /* Toggle to the Host:-based vhost's timeout mode to fetch the
1365      * request body and send the response body, if needed.
1366      */
1367     if (cur_timeout != r->server->timeout) {
1368         apr_socket_timeout_set(csd, r->server->timeout);
1369         cur_timeout = r->server->timeout;
1370     }
1371
1372     /* we may have switched to another server */
1373     r->per_dir_config = r->server->lookup_defaults;
1374
1375     if ((!r->hostname && (r->proto_num >= HTTP_VERSION(1, 1)))
1376         || ((r->proto_num == HTTP_VERSION(1, 1))
1377             && !apr_table_get(r->headers_in, "Host"))) {
1378         /*
1379          * Client sent us an HTTP/1.1 or later request without telling us the
1380          * hostname, either with a full URL or a Host: header. We therefore
1381          * need to (as per the 1.1 spec) send an error.  As a special case,
1382          * HTTP/1.1 mentions twice (S9, S14.23) that a request MUST contain
1383          * a Host: header, and the server MUST respond with 400 if it doesn't.
1384          */
1385         access_status = HTTP_BAD_REQUEST;
1386         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00569)
1387                       "client sent HTTP/1.1 request without hostname "
1388                       "(see RFC2616 section 14.23): %s", r->uri);
1389     }
1390
1391     /*
1392      * Add the HTTP_IN filter here to ensure that ap_discard_request_body
1393      * called by ap_die and by ap_send_error_response works correctly on
1394      * status codes that do not cause the connection to be dropped and
1395      * in situations where the connection should be kept alive.
1396      */
1397
1398     ap_add_input_filter_handle(ap_http_input_filter_handle,
1399                                NULL, r, r->connection);
1400
1401     if (access_status != HTTP_OK
1402         || (access_status = ap_run_post_read_request(r))) {
1403         ap_die(access_status, r);
1404         ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
1405         ap_run_log_transaction(r);
1406         r = NULL;
1407         goto traceout;
1408     }
1409
1410     if (((expect = apr_table_get(r->headers_in, "Expect")) != NULL)
1411         && (expect[0] != '\0')) {
1412         /*
1413          * The Expect header field was added to HTTP/1.1 after RFC 2068
1414          * as a means to signal when a 100 response is desired and,
1415          * unfortunately, to signal a poor man's mandatory extension that
1416          * the server must understand or return 417 Expectation Failed.
1417          */
1418         if (strcasecmp(expect, "100-continue") == 0) {
1419             r->expecting_100 = 1;
1420         }
1421         else {
1422             r->status = HTTP_EXPECTATION_FAILED;
1423             ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00570)
1424                           "client sent an unrecognized expectation value of "
1425                           "Expect: %s", expect);
1426             ap_send_error_response(r, 0);
1427             ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
1428             ap_run_log_transaction(r);
1429             goto traceout;
1430         }
1431     }
1432
1433     AP_READ_REQUEST_SUCCESS((uintptr_t)r, (char *)r->method, (char *)r->uri, (char *)r->server->defn_name, r->status);
1434     return r;
1435     traceout:
1436     AP_READ_REQUEST_FAILURE((uintptr_t)r);
1437     return r;
1438 }
1439
1440 /* if a request with a body creates a subrequest, remove original request's
1441  * input headers which pertain to the body which has already been read.
1442  * out-of-line helper function for ap_set_sub_req_protocol.
1443  */
1444
1445 static void strip_headers_request_body(request_rec *rnew)
1446 {
1447     apr_table_unset(rnew->headers_in, "Content-Encoding");
1448     apr_table_unset(rnew->headers_in, "Content-Language");
1449     apr_table_unset(rnew->headers_in, "Content-Length");
1450     apr_table_unset(rnew->headers_in, "Content-Location");
1451     apr_table_unset(rnew->headers_in, "Content-MD5");
1452     apr_table_unset(rnew->headers_in, "Content-Range");
1453     apr_table_unset(rnew->headers_in, "Content-Type");
1454     apr_table_unset(rnew->headers_in, "Expires");
1455     apr_table_unset(rnew->headers_in, "Last-Modified");
1456     apr_table_unset(rnew->headers_in, "Transfer-Encoding");
1457 }
1458
1459 /*
1460  * A couple of other functions which initialize some of the fields of
1461  * a request structure, as appropriate for adjuncts of one kind or another
1462  * to a request in progress.  Best here, rather than elsewhere, since
1463  * *someone* has to set the protocol-specific fields...
1464  */
1465
1466 AP_DECLARE(void) ap_set_sub_req_protocol(request_rec *rnew,
1467                                          const request_rec *r)
1468 {
1469     rnew->the_request     = r->the_request;  /* Keep original request-line */
1470
1471     rnew->assbackwards    = 1;   /* Don't send headers from this. */
1472     rnew->no_local_copy   = 1;   /* Don't try to send HTTP_NOT_MODIFIED for a
1473                                   * fragment. */
1474     rnew->method          = "GET";
1475     rnew->method_number   = M_GET;
1476     rnew->protocol        = "INCLUDED";
1477
1478     rnew->status          = HTTP_OK;
1479
1480     rnew->headers_in      = apr_table_copy(rnew->pool, r->headers_in);
1481     rnew->trailers_in     = apr_table_copy(rnew->pool, r->trailers_in);
1482
1483     /* did the original request have a body?  (e.g. POST w/SSI tags)
1484      * if so, make sure the subrequest doesn't inherit body headers
1485      */
1486     if (!r->kept_body && (apr_table_get(r->headers_in, "Content-Length")
1487         || apr_table_get(r->headers_in, "Transfer-Encoding"))) {
1488         strip_headers_request_body(rnew);
1489     }
1490     rnew->subprocess_env  = apr_table_copy(rnew->pool, r->subprocess_env);
1491     rnew->headers_out     = apr_table_make(rnew->pool, 5);
1492     rnew->err_headers_out = apr_table_make(rnew->pool, 5);
1493     rnew->trailers_out    = apr_table_make(rnew->pool, 5);
1494     rnew->notes           = apr_table_make(rnew->pool, 5);
1495
1496     rnew->expecting_100   = r->expecting_100;
1497     rnew->read_length     = r->read_length;
1498     rnew->read_body       = REQUEST_NO_BODY;
1499
1500     rnew->main = (request_rec *) r;
1501 }
1502
1503 static void end_output_stream(request_rec *r)
1504 {
1505     conn_rec *c = r->connection;
1506     apr_bucket_brigade *bb;
1507     apr_bucket *b;
1508
1509     bb = apr_brigade_create(r->pool, c->bucket_alloc);
1510     b = apr_bucket_eos_create(c->bucket_alloc);
1511     APR_BRIGADE_INSERT_TAIL(bb, b);
1512     ap_pass_brigade(r->output_filters, bb);
1513 }
1514
1515 AP_DECLARE(void) ap_finalize_sub_req_protocol(request_rec *sub)
1516 {
1517     /* tell the filter chain there is no more content coming */
1518     if (!sub->eos_sent) {
1519         end_output_stream(sub);
1520     }
1521 }
1522
1523 /* finalize_request_protocol is called at completion of sending the
1524  * response.  Its sole purpose is to send the terminating protocol
1525  * information for any wrappers around the response message body
1526  * (i.e., transfer encodings).  It should have been named finalize_response.
1527  */
1528 AP_DECLARE(void) ap_finalize_request_protocol(request_rec *r)
1529 {
1530     (void) ap_discard_request_body(r);
1531
1532     /* tell the filter chain there is no more content coming */
1533     if (!r->eos_sent) {
1534         end_output_stream(r);
1535     }
1536 }
1537
1538 /*
1539  * Support for the Basic authentication protocol, and a bit for Digest.
1540  */
1541 AP_DECLARE(void) ap_note_auth_failure(request_rec *r)
1542 {
1543     const char *type = ap_auth_type(r);
1544     if (type) {
1545         ap_run_note_auth_failure(r, type);
1546     }
1547     else {
1548         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00571)
1549                       "need AuthType to note auth failure: %s", r->uri);
1550     }
1551 }
1552
1553 AP_DECLARE(void) ap_note_basic_auth_failure(request_rec *r)
1554 {
1555     ap_note_auth_failure(r);
1556 }
1557
1558 AP_DECLARE(void) ap_note_digest_auth_failure(request_rec *r)
1559 {
1560     ap_note_auth_failure(r);
1561 }
1562
1563 AP_DECLARE(int) ap_get_basic_auth_pw(request_rec *r, const char **pw)
1564 {
1565     const char *auth_line = apr_table_get(r->headers_in,
1566                                           (PROXYREQ_PROXY == r->proxyreq)
1567                                               ? "Proxy-Authorization"
1568                                               : "Authorization");
1569     const char *t;
1570
1571     if (!(t = ap_auth_type(r)) || strcasecmp(t, "Basic"))
1572         return DECLINED;
1573
1574     if (!ap_auth_name(r)) {
1575         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00572) 
1576                       "need AuthName: %s", r->uri);
1577         return HTTP_INTERNAL_SERVER_ERROR;
1578     }
1579
1580     if (!auth_line) {
1581         ap_note_auth_failure(r);
1582         return HTTP_UNAUTHORIZED;
1583     }
1584
1585     if (strcasecmp(ap_getword(r->pool, &auth_line, ' '), "Basic")) {
1586         /* Client tried to authenticate using wrong auth scheme */
1587         ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00573)
1588                       "client used wrong authentication scheme: %s", r->uri);
1589         ap_note_auth_failure(r);
1590         return HTTP_UNAUTHORIZED;
1591     }
1592
1593     while (*auth_line == ' ' || *auth_line == '\t') {
1594         auth_line++;
1595     }
1596
1597     t = ap_pbase64decode(r->pool, auth_line);
1598     r->user = ap_getword_nulls (r->pool, &t, ':');
1599     r->ap_auth_type = "Basic";
1600
1601     *pw = t;
1602
1603     return OK;
1604 }
1605
1606 struct content_length_ctx {
1607     int data_sent;  /* true if the C-L filter has already sent at
1608                      * least one bucket on to the next output filter
1609                      * for this request
1610                      */
1611     apr_bucket_brigade *tmpbb;
1612 };
1613
1614 /* This filter computes the content length, but it also computes the number
1615  * of bytes sent to the client.  This means that this filter will always run
1616  * through all of the buckets in all brigades
1617  */
1618 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_content_length_filter(
1619     ap_filter_t *f,
1620     apr_bucket_brigade *b)
1621 {
1622     request_rec *r = f->r;
1623     struct content_length_ctx *ctx;
1624     apr_bucket *e;
1625     int eos = 0;
1626     apr_read_type_e eblock = APR_NONBLOCK_READ;
1627
1628     ctx = f->ctx;
1629     if (!ctx) {
1630         f->ctx = ctx = apr_palloc(r->pool, sizeof(*ctx));
1631         ctx->data_sent = 0;
1632         ctx->tmpbb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1633     }
1634
1635     /* Loop through this set of buckets to compute their length
1636      */
1637     e = APR_BRIGADE_FIRST(b);
1638     while (e != APR_BRIGADE_SENTINEL(b)) {
1639         if (APR_BUCKET_IS_EOS(e)) {
1640             eos = 1;
1641             break;
1642         }
1643         if (e->length == (apr_size_t)-1) {
1644             apr_size_t len;
1645             const char *ignored;
1646             apr_status_t rv;
1647
1648             /* This is probably a pipe bucket.  Send everything
1649              * prior to this, and then read the data for this bucket.
1650              */
1651             rv = apr_bucket_read(e, &ignored, &len, eblock);
1652             if (rv == APR_SUCCESS) {
1653                 /* Attempt a nonblocking read next time through */
1654                 eblock = APR_NONBLOCK_READ;
1655                 r->bytes_sent += len;
1656             }
1657             else if (APR_STATUS_IS_EAGAIN(rv)) {
1658                 /* Output everything prior to this bucket, and then
1659                  * do a blocking read on the next batch.
1660                  */
1661                 if (e != APR_BRIGADE_FIRST(b)) {
1662                     apr_bucket *flush;
1663                     apr_brigade_split_ex(b, e, ctx->tmpbb);
1664                     flush = apr_bucket_flush_create(r->connection->bucket_alloc);
1665
1666                     APR_BRIGADE_INSERT_TAIL(b, flush);
1667                     rv = ap_pass_brigade(f->next, b);
1668                     if (rv != APR_SUCCESS || f->c->aborted) {
1669                         return rv;
1670                     }
1671                     apr_brigade_cleanup(b);
1672                     APR_BRIGADE_CONCAT(b, ctx->tmpbb);
1673                     e = APR_BRIGADE_FIRST(b);
1674
1675                     ctx->data_sent = 1;
1676                 }
1677                 eblock = APR_BLOCK_READ;
1678                 continue;
1679             }
1680             else {
1681                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(00574)
1682                               "ap_content_length_filter: "
1683                               "apr_bucket_read() failed");
1684                 return rv;
1685             }
1686         }
1687         else {
1688             r->bytes_sent += e->length;
1689         }
1690         e = APR_BUCKET_NEXT(e);
1691     }
1692
1693     /* If we've now seen the entire response and it's otherwise
1694      * okay to set the C-L in the response header, then do so now.
1695      *
1696      * We can only set a C-L in the response header if we haven't already
1697      * sent any buckets on to the next output filter for this request.
1698      */
1699     if (ctx->data_sent == 0 && eos &&
1700         /* don't whack the C-L if it has already been set for a HEAD
1701          * by something like proxy.  the brigade only has an EOS bucket
1702          * in this case, making r->bytes_sent zero.
1703          *
1704          * if r->bytes_sent > 0 we have a (temporary) body whose length may
1705          * have been changed by a filter.  the C-L header might not have been
1706          * updated so we do it here.  long term it would be cleaner to have
1707          * such filters update or remove the C-L header, and just use it
1708          * if present.
1709          */
1710         !(r->header_only && r->bytes_sent == 0 &&
1711             apr_table_get(r->headers_out, "Content-Length"))) {
1712         ap_set_content_length(r, r->bytes_sent);
1713     }
1714
1715     ctx->data_sent = 1;
1716     return ap_pass_brigade(f->next, b);
1717 }
1718
1719 /*
1720  * Send the body of a response to the client.
1721  */
1722 AP_DECLARE(apr_status_t) ap_send_fd(apr_file_t *fd, request_rec *r,
1723                                     apr_off_t offset, apr_size_t len,
1724                                     apr_size_t *nbytes)
1725 {
1726     conn_rec *c = r->connection;
1727     apr_bucket_brigade *bb = NULL;
1728     apr_status_t rv;
1729
1730     bb = apr_brigade_create(r->pool, c->bucket_alloc);
1731
1732     apr_brigade_insert_file(bb, fd, offset, len, r->pool);
1733
1734     rv = ap_pass_brigade(r->output_filters, bb);
1735     if (rv != APR_SUCCESS) {
1736         *nbytes = 0; /* no way to tell how many were actually sent */
1737     }
1738     else {
1739         *nbytes = len;
1740     }
1741
1742     return rv;
1743 }
1744
1745 #if APR_HAS_MMAP
1746 /* send data from an in-memory buffer */
1747 AP_DECLARE(apr_size_t) ap_send_mmap(apr_mmap_t *mm,
1748                                     request_rec *r,
1749                                     apr_size_t offset,
1750                                     apr_size_t length)
1751 {
1752     conn_rec *c = r->connection;
1753     apr_bucket_brigade *bb = NULL;
1754     apr_bucket *b;
1755
1756     bb = apr_brigade_create(r->pool, c->bucket_alloc);
1757     b = apr_bucket_mmap_create(mm, offset, length, c->bucket_alloc);
1758     APR_BRIGADE_INSERT_TAIL(bb, b);
1759     ap_pass_brigade(r->output_filters, bb);
1760
1761     return mm->size; /* XXX - change API to report apr_status_t? */
1762 }
1763 #endif /* APR_HAS_MMAP */
1764
1765 typedef struct {
1766     apr_bucket_brigade *bb;
1767     apr_bucket_brigade *tmpbb;
1768 } old_write_filter_ctx;
1769
1770 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_old_write_filter(
1771     ap_filter_t *f, apr_bucket_brigade *bb)
1772 {
1773     old_write_filter_ctx *ctx = f->ctx;
1774
1775     AP_DEBUG_ASSERT(ctx);
1776
1777     if (ctx->bb != NULL) {
1778         /* whatever is coming down the pipe (we don't care), we
1779          * can simply insert our buffered data at the front and
1780          * pass the whole bundle down the chain.
1781          */
1782         APR_BRIGADE_PREPEND(bb, ctx->bb);
1783     }
1784
1785     return ap_pass_brigade(f->next, bb);
1786 }
1787
1788 static ap_filter_t *insert_old_write_filter(request_rec *r)
1789 {
1790     ap_filter_t *f;
1791     old_write_filter_ctx *ctx;
1792
1793     /* future optimization: record some flags in the request_rec to
1794      * say whether we've added our filter, and whether it is first.
1795      */
1796
1797     /* this will typically exit on the first test */
1798     for (f = r->output_filters; f != NULL; f = f->next) {
1799         if (ap_old_write_func == f->frec)
1800             break;
1801     }
1802
1803     if (f == NULL) {
1804         /* our filter hasn't been added yet */
1805         ctx = apr_pcalloc(r->pool, sizeof(*ctx));
1806         ctx->tmpbb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1807
1808         ap_add_output_filter("OLD_WRITE", ctx, r, r->connection);
1809         f = r->output_filters;
1810     }
1811
1812     return f;
1813 }
1814
1815 static apr_status_t buffer_output(request_rec *r,
1816                                   const char *str, apr_size_t len)
1817 {
1818     conn_rec *c = r->connection;
1819     ap_filter_t *f;
1820     old_write_filter_ctx *ctx;
1821
1822     if (len == 0)
1823         return APR_SUCCESS;
1824
1825     f = insert_old_write_filter(r);
1826     ctx = f->ctx;
1827
1828     /* if the first filter is not our buffering filter, then we have to
1829      * deliver the content through the normal filter chain
1830      */
1831     if (f != r->output_filters) {
1832         apr_status_t rv;
1833         apr_bucket *b = apr_bucket_transient_create(str, len, c->bucket_alloc);
1834         APR_BRIGADE_INSERT_TAIL(ctx->tmpbb, b);
1835
1836         rv = ap_pass_brigade(r->output_filters, ctx->tmpbb);
1837         apr_brigade_cleanup(ctx->tmpbb);
1838         return rv;
1839     }
1840
1841     if (ctx->bb == NULL) {
1842         ctx->bb = apr_brigade_create(r->pool, c->bucket_alloc);
1843     }
1844
1845     return ap_fwrite(f->next, ctx->bb, str, len);
1846 }
1847
1848 AP_DECLARE(int) ap_rputc(int c, request_rec *r)
1849 {
1850     char c2 = (char)c;
1851
1852     if (r->connection->aborted) {
1853         return -1;
1854     }
1855
1856     if (buffer_output(r, &c2, 1) != APR_SUCCESS)
1857         return -1;
1858
1859     return c;
1860 }
1861
1862 AP_DECLARE(int) ap_rwrite(const void *buf, int nbyte, request_rec *r)
1863 {
1864     if (r->connection->aborted)
1865         return -1;
1866
1867     if (buffer_output(r, buf, nbyte) != APR_SUCCESS)
1868         return -1;
1869
1870     return nbyte;
1871 }
1872
1873 struct ap_vrprintf_data {
1874     apr_vformatter_buff_t vbuff;
1875     request_rec *r;
1876     char *buff;
1877 };
1878
1879 /* Flush callback for apr_vformatter; returns -1 on error. */
1880 static int r_flush(apr_vformatter_buff_t *buff)
1881 {
1882     /* callback function passed to ap_vformatter to be called when
1883      * vformatter needs to write into buff and buff.curpos > buff.endpos */
1884
1885     /* ap_vrprintf_data passed as a apr_vformatter_buff_t, which is then
1886      * "downcast" to an ap_vrprintf_data */
1887     struct ap_vrprintf_data *vd = (struct ap_vrprintf_data*)buff;
1888
1889     if (vd->r->connection->aborted)
1890         return -1;
1891
1892     /* r_flush is called when vbuff is completely full */
1893     if (buffer_output(vd->r, vd->buff, AP_IOBUFSIZE)) {
1894         return -1;
1895     }
1896
1897     /* reset the buffer position */
1898     vd->vbuff.curpos = vd->buff;
1899     vd->vbuff.endpos = vd->buff + AP_IOBUFSIZE;
1900
1901     return 0;
1902 }
1903
1904 AP_DECLARE(int) ap_vrprintf(request_rec *r, const char *fmt, va_list va)
1905 {
1906     apr_size_t written;
1907     struct ap_vrprintf_data vd;
1908     char vrprintf_buf[AP_IOBUFSIZE];
1909
1910     vd.vbuff.curpos = vrprintf_buf;
1911     vd.vbuff.endpos = vrprintf_buf + AP_IOBUFSIZE;
1912     vd.r = r;
1913     vd.buff = vrprintf_buf;
1914
1915     if (r->connection->aborted)
1916         return -1;
1917
1918     written = apr_vformatter(r_flush, &vd.vbuff, fmt, va);
1919
1920     if (written != -1) {
1921         int n = vd.vbuff.curpos - vrprintf_buf;
1922
1923         /* last call to buffer_output, to finish clearing the buffer */
1924         if (buffer_output(r, vrprintf_buf,n) != APR_SUCCESS)
1925             return -1;
1926
1927         written += n;
1928     }
1929
1930     return written;
1931 }
1932
1933 AP_DECLARE_NONSTD(int) ap_rprintf(request_rec *r, const char *fmt, ...)
1934 {
1935     va_list va;
1936     int n;
1937
1938     if (r->connection->aborted)
1939         return -1;
1940
1941     va_start(va, fmt);
1942     n = ap_vrprintf(r, fmt, va);
1943     va_end(va);
1944
1945     return n;
1946 }
1947
1948 AP_DECLARE_NONSTD(int) ap_rvputs(request_rec *r, ...)
1949 {
1950     va_list va;
1951     const char *s;
1952     apr_size_t len;
1953     apr_size_t written = 0;
1954
1955     if (r->connection->aborted)
1956         return -1;
1957
1958     /* ### TODO: if the total output is large, put all the strings
1959      * ### into a single brigade, rather than flushing each time we
1960      * ### fill the buffer
1961      */
1962     va_start(va, r);
1963     while (1) {
1964         s = va_arg(va, const char *);
1965         if (s == NULL)
1966             break;
1967
1968         len = strlen(s);
1969         if (buffer_output(r, s, len) != APR_SUCCESS) {
1970             return -1;
1971         }
1972
1973         written += len;
1974     }
1975     va_end(va);
1976
1977     return written;
1978 }
1979
1980 AP_DECLARE(int) ap_rflush(request_rec *r)
1981 {
1982     conn_rec *c = r->connection;
1983     apr_bucket *b;
1984     ap_filter_t *f;
1985     old_write_filter_ctx *ctx;
1986     apr_status_t rv;
1987
1988     f = insert_old_write_filter(r);
1989     ctx = f->ctx;
1990
1991     b = apr_bucket_flush_create(c->bucket_alloc);
1992     APR_BRIGADE_INSERT_TAIL(ctx->tmpbb, b);
1993
1994     rv = ap_pass_brigade(r->output_filters, ctx->tmpbb);
1995     apr_brigade_cleanup(ctx->tmpbb);
1996     if (rv != APR_SUCCESS)
1997         return -1;
1998
1999     return 0;
2000 }
2001
2002 /*
2003  * This function sets the Last-Modified output header field to the value
2004  * of the mtime field in the request structure - rationalized to keep it from
2005  * being in the future.
2006  */
2007 AP_DECLARE(void) ap_set_last_modified(request_rec *r)
2008 {
2009     if (!r->assbackwards) {
2010         apr_time_t mod_time = ap_rationalize_mtime(r, r->mtime);
2011         char *datestr = apr_palloc(r->pool, APR_RFC822_DATE_LEN);
2012
2013         apr_rfc822_date(datestr, mod_time);
2014         apr_table_setn(r->headers_out, "Last-Modified", datestr);
2015     }
2016 }
2017
2018 typedef struct hdr_ptr {
2019     ap_filter_t *f;
2020     apr_bucket_brigade *bb;
2021 } hdr_ptr;
2022 static int send_header(void *data, const char *key, const char *val)
2023 {
2024     ap_fputstrs(((hdr_ptr*)data)->f, ((hdr_ptr*)data)->bb,
2025                 key, ": ", val, CRLF, NULL);
2026     return 1;
2027 }
2028 AP_DECLARE(void) ap_send_interim_response(request_rec *r, int send_headers)
2029 {
2030     hdr_ptr x;
2031     char *status_line = NULL;
2032     request_rec *rr;
2033
2034     if (r->proto_num < HTTP_VERSION(1,1)) {
2035         /* don't send interim response to HTTP/1.0 Client */
2036         return;
2037     }
2038     if (!ap_is_HTTP_INFO(r->status)) {
2039         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00575)
2040                       "Status is %d - not sending interim response", r->status);
2041         return;
2042     }
2043     if ((r->status == HTTP_CONTINUE) && !r->expecting_100) {
2044         /*
2045          * Don't send 100-Continue when there was no Expect: 100-continue
2046          * in the request headers. For origin servers this is a SHOULD NOT
2047          * for proxies it is a MUST NOT according to RFC 2616 8.2.3
2048          */
2049         return;
2050     }
2051
2052     /* if we send an interim response, we're no longer in a state of
2053      * expecting one.  Also, this could feasibly be in a subrequest,
2054      * so we need to propagate the fact that we responded.
2055      */
2056     for (rr = r; rr != NULL; rr = rr->main) {
2057         rr->expecting_100 = 0;
2058     }
2059
2060     status_line = apr_pstrcat(r->pool, AP_SERVER_PROTOCOL, " ", r->status_line, CRLF, NULL);
2061     ap_xlate_proto_to_ascii(status_line, strlen(status_line));
2062
2063     x.f = r->connection->output_filters;
2064     x.bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
2065
2066     ap_fputs(x.f, x.bb, status_line);
2067     if (send_headers) {
2068         apr_table_do(send_header, &x, r->headers_out, NULL);
2069         apr_table_clear(r->headers_out);
2070     }
2071     ap_fputs(x.f, x.bb, CRLF_ASCII);
2072     ap_fflush(x.f, x.bb);
2073     apr_brigade_destroy(x.bb);
2074 }
2075
2076 /*
2077  * Compare two protocol identifier. Result is similar to strcmp():
2078  * 0 gives same precedence, >0 means proto1 is preferred.
2079  */
2080 static int protocol_cmp(const apr_array_header_t *preferences,
2081                         const char *proto1,
2082                         const char *proto2)
2083 {
2084     if (preferences && preferences->nelts > 0) {
2085         int index1 = ap_array_str_index(preferences, proto1, 0);
2086         int index2 = ap_array_str_index(preferences, proto2, 0);
2087         if (index2 > index1) {
2088             return (index1 >= 0) ? 1 : -1;
2089         }
2090         else if (index1 > index2) {
2091             return (index2 >= 0) ? -1 : 1;
2092         }
2093     }
2094     /* both have the same index (mabye -1 or no pref configured) and we compare
2095      * the names so that spdy3 gets precedence over spdy2. That makes
2096      * the outcome at least deterministic. */
2097     return strcmp(proto1, proto2);
2098 }
2099
2100 AP_DECLARE(const char *) ap_get_protocol(conn_rec *c)
2101 {
2102     const char *protocol = ap_run_protocol_get(c);
2103     return protocol? protocol : AP_PROTOCOL_HTTP1;
2104 }
2105
2106 AP_DECLARE(apr_status_t) ap_get_protocol_upgrades(conn_rec *c, request_rec *r, 
2107                                                   server_rec *s, int report_all, 
2108                                                   const apr_array_header_t **pupgrades)
2109 {
2110     apr_pool_t *pool = r? r->pool : c->pool;
2111     core_server_config *conf;
2112     const char *existing;
2113     apr_array_header_t *upgrades = NULL;
2114
2115     if (!s) {
2116         s = (r? r->server : c->base_server);
2117     }
2118     conf = ap_get_core_module_config(s->module_config);
2119     
2120     if (conf->protocols->nelts > 0) {
2121         existing = ap_get_protocol(c);
2122         if (conf->protocols->nelts > 1 
2123             || !ap_array_str_contains(conf->protocols, existing)) {
2124             int i;
2125             
2126             /* possibly more than one choice or one, but not the
2127              * existing. (TODO: maybe 426 and Upgrade then?) */
2128             upgrades = apr_array_make(pool, conf->protocols->nelts + 1, 
2129                                       sizeof(char *));
2130             for (i = 0; i < conf->protocols->nelts; i++) {
2131                 const char *p = APR_ARRAY_IDX(conf->protocols, i, char *);
2132                 if (strcmp(existing, p)) {
2133                     /* not the one we have and possible, add in this order */
2134                     APR_ARRAY_PUSH(upgrades, const char*) = p;
2135                 }
2136                 else if (!report_all) {
2137                     break;
2138                 }
2139             }
2140         }
2141     }
2142     
2143     *pupgrades = upgrades;
2144     return APR_SUCCESS;
2145 }
2146
2147 AP_DECLARE(const char *) ap_select_protocol(conn_rec *c, request_rec *r, 
2148                                             server_rec *s,
2149                                             const apr_array_header_t *choices)
2150 {
2151     apr_pool_t *pool = r? r->pool : c->pool;
2152     core_server_config *conf;
2153     const char *protocol = NULL, *existing;
2154     apr_array_header_t *proposals;
2155
2156     if (!s) {
2157         s = (r? r->server : c->base_server);
2158     }
2159     conf = ap_get_core_module_config(s->module_config);
2160     
2161     if (APLOGcdebug(c)) {
2162         const char *p = apr_array_pstrcat(pool, conf->protocols, ',');
2163         ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c, APLOGNO(03155) 
2164                       "select protocol from %s, choices=%s for server %s", 
2165                       p, apr_array_pstrcat(pool, choices, ','),
2166                       s->server_hostname);
2167     }
2168
2169     if (conf->protocols->nelts <= 0) {
2170         /* nothing configured, by default, we only allow http/1.1 here.
2171          * For now...
2172          */
2173         if (ap_array_str_contains(choices, AP_PROTOCOL_HTTP1)) {
2174             return AP_PROTOCOL_HTTP1;
2175         }
2176         else {
2177             return NULL;
2178         }
2179     }
2180
2181     proposals = apr_array_make(pool, choices->nelts + 1, sizeof(char *));
2182     ap_run_protocol_propose(c, r, s, choices, proposals);
2183
2184     /* If the existing protocol has not been proposed, but is a choice,
2185      * add it to the proposals implicitly.
2186      */
2187     existing = ap_get_protocol(c);
2188     if (!ap_array_str_contains(proposals, existing)
2189         && ap_array_str_contains(choices, existing)) {
2190         APR_ARRAY_PUSH(proposals, const char*) = existing;
2191     }
2192
2193     if (proposals->nelts > 0) {
2194         int i;
2195         const apr_array_header_t *prefs = NULL;
2196
2197         /* Default for protocols_honor_order is 'on' or != 0 */
2198         if (conf->protocols_honor_order == 0 && choices->nelts > 0) {
2199             prefs = choices;
2200         }
2201         else {
2202             prefs = conf->protocols;
2203         }
2204
2205         /* Select the most preferred protocol */
2206         if (APLOGcdebug(c)) {
2207             ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c, APLOGNO(03156) 
2208                           "select protocol, proposals=%s preferences=%s configured=%s", 
2209                           apr_array_pstrcat(pool, proposals, ','),
2210                           apr_array_pstrcat(pool, prefs, ','),
2211                           apr_array_pstrcat(pool, conf->protocols, ','));
2212         }
2213         for (i = 0; i < proposals->nelts; ++i) {
2214             const char *p = APR_ARRAY_IDX(proposals, i, const char *);
2215             if (!ap_array_str_contains(conf->protocols, p)) {
2216                 /* not a configured protocol here */
2217                 continue;
2218             }
2219             else if (!protocol 
2220                      || (protocol_cmp(prefs, protocol, p) < 0)) {
2221                 /* none selected yet or this one has preference */
2222                 protocol = p;
2223             }
2224         }
2225     }
2226     if (APLOGcdebug(c)) {
2227         ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c, APLOGNO(03157)
2228                       "selected protocol=%s", 
2229                       protocol? protocol : "(none)");
2230     }
2231
2232     return protocol;
2233 }
2234
2235 AP_DECLARE(apr_status_t) ap_switch_protocol(conn_rec *c, request_rec *r, 
2236                                             server_rec *s,
2237                                             const char *protocol)
2238 {
2239     const char *current = ap_get_protocol(c);
2240     int rc;
2241     
2242     if (!strcmp(current, protocol)) {
2243         ap_log_cerror(APLOG_MARK, APLOG_WARNING, 0, c, APLOGNO(02906)
2244                       "already at it, protocol_switch to %s", 
2245                       protocol);
2246         return APR_SUCCESS;
2247     }
2248     
2249     rc = ap_run_protocol_switch(c, r, s, protocol);
2250     switch (rc) {
2251         case DECLINED:
2252             ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, c, APLOGNO(02907)
2253                           "no implementation for protocol_switch to %s", 
2254                           protocol);
2255             return APR_ENOTIMPL;
2256         case OK:
2257         case DONE:
2258             return APR_SUCCESS;
2259         default:
2260             ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, c, APLOGNO(02905)
2261                           "unexpected return code %d from protocol_switch to %s"
2262                           , rc, protocol);
2263             return APR_EOF;
2264     }    
2265 }
2266
2267 AP_DECLARE(int) ap_is_allowed_protocol(conn_rec *c, request_rec *r,
2268                                        server_rec *s, const char *protocol)
2269 {
2270     core_server_config *conf;
2271
2272     if (!s) {
2273         s = (r? r->server : c->base_server);
2274     }
2275     conf = ap_get_core_module_config(s->module_config);
2276     
2277     if (conf->protocols->nelts > 0) {
2278         return ap_array_str_contains(conf->protocols, protocol);
2279     }
2280     return !strcmp(AP_PROTOCOL_HTTP1, protocol);
2281 }
2282
2283
2284 AP_IMPLEMENT_HOOK_VOID(pre_read_request,
2285                        (request_rec *r, conn_rec *c),
2286                        (r, c))
2287 AP_IMPLEMENT_HOOK_RUN_ALL(int,post_read_request,
2288                           (request_rec *r), (r), OK, DECLINED)
2289 AP_IMPLEMENT_HOOK_RUN_ALL(int,log_transaction,
2290                           (request_rec *r), (r), OK, DECLINED)
2291 AP_IMPLEMENT_HOOK_RUN_FIRST(const char *,http_scheme,
2292                             (const request_rec *r), (r), NULL)
2293 AP_IMPLEMENT_HOOK_RUN_FIRST(unsigned short,default_port,
2294                             (const request_rec *r), (r), 0)
2295 AP_IMPLEMENT_HOOK_RUN_FIRST(int, note_auth_failure,
2296                             (request_rec *r, const char *auth_type),
2297                             (r, auth_type), DECLINED)
2298 AP_IMPLEMENT_HOOK_RUN_ALL(int,protocol_propose,
2299                           (conn_rec *c, request_rec *r, server_rec *s,
2300                            const apr_array_header_t *offers,
2301                            apr_array_header_t *proposals), 
2302                           (c, r, s, offers, proposals), OK, DECLINED)
2303 AP_IMPLEMENT_HOOK_RUN_FIRST(int,protocol_switch,
2304                             (conn_rec *c, request_rec *r, server_rec *s,
2305                              const char *protocol), 
2306                             (c, r, s, protocol), DECLINED)
2307 AP_IMPLEMENT_HOOK_RUN_FIRST(const char *,protocol_get,
2308                             (const conn_rec *c), (c), NULL)