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