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