1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000-2002 The Apache Software Foundation. All rights
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
19 * 3. The end-user documentation included with the redistribution,
20 * if any, must include the following acknowledgment:
21 * "This product includes software developed by the
22 * Apache Software Foundation (http://www.apache.org/)."
23 * Alternately, this acknowledgment may appear in the software itself,
24 * if and wherever such third-party acknowledgments normally appear.
26 * 4. The names "Apache" and "Apache Software Foundation" must
27 * not be used to endorse or promote products derived from this
28 * software without prior written permission. For written
29 * permission, please contact apache@apache.org.
31 * 5. Products derived from this software may not be called "Apache",
32 * nor may "Apache" appear in their name, without prior written
33 * permission of the Apache Software Foundation.
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation. For more
51 * information on the Apache Software Foundation, please see
52 * <http://www.apache.org/>.
54 * Portions of this software are based upon public domain software
55 * originally written at the National Center for Supercomputing Applications,
56 * University of Illinois, Urbana-Champaign.
60 * http_protocol.c --- routines which directly communicate with the client.
62 * Code originally by Rob McCool; much redone by Robert S. Thau
63 * and the Apache Software Foundation.
67 #include "apr_strings.h"
68 #include "apr_buckets.h"
70 #include "apr_signal.h"
71 #include "apr_strmatch.h"
73 #define APR_WANT_STDIO /* for sscanf */
74 #define APR_WANT_STRFUNC
75 #define APR_WANT_MEMFUNC
79 #include "util_filter.h"
80 #include "ap_config.h"
82 #include "http_config.h"
83 #include "http_core.h"
84 #include "http_protocol.h"
85 #include "http_main.h"
86 #include "http_request.h"
87 #include "http_vhost.h"
88 #include "http_log.h" /* For errors detected in basic auth common
91 #include "util_charset.h"
92 #include "util_ebcdic.h"
103 APR_HOOK_LINK(post_read_request)
104 APR_HOOK_LINK(log_transaction)
105 APR_HOOK_LINK(http_method)
106 APR_HOOK_LINK(default_port)
109 AP_DECLARE_DATA ap_filter_rec_t *ap_old_write_func = NULL;
112 /* Patterns to match in ap_make_content_type() */
113 static const char *needcset[] = {
118 static const apr_strmatch_pattern **needcset_patterns;
119 static const apr_strmatch_pattern *charset_pattern;
121 AP_DECLARE(void) ap_setup_make_content_type(apr_pool_t *pool)
124 for (i = 0; needcset[i]; i++) {
127 needcset_patterns = (const apr_strmatch_pattern **)
128 apr_palloc(pool, (i + 1) * sizeof(apr_strmatch_pattern *));
129 for (i = 0; needcset[i]; i++) {
130 needcset_patterns[i] = apr_strmatch_precompile(pool, needcset[i], 0);
132 needcset_patterns[i] = NULL;
133 charset_pattern = apr_strmatch_precompile(pool, "charset=", 0);
137 * Builds the content-type that should be sent to the client from the
138 * content-type specified. The following rules are followed:
139 * - if type is NULL, type is set to ap_default_type(r)
140 * - if charset adding is disabled, stop processing and return type.
141 * - then, if there are no parameters on type, add the default charset
144 AP_DECLARE(const char *)ap_make_content_type(request_rec *r, const char *type)
146 const apr_strmatch_pattern **pcset;
147 core_dir_config *conf =
148 (core_dir_config *)ap_get_module_config(r->per_dir_config,
153 type = ap_default_type(r);
156 if (conf->add_default_charset != ADD_DEFAULT_CHARSET_ON) {
160 type_len = strlen(type);
162 if (apr_strmatch(charset_pattern, type, type_len) != NULL) {
163 /* already has parameter, do nothing */
164 /* XXX we don't check the validity */
168 /* see if it makes sense to add the charset. At present,
169 * we only add it if the Content-type is one of needcset[]
171 for (pcset = needcset_patterns; *pcset ; pcset++) {
172 if (apr_strmatch(*pcset, type, type_len) != NULL) {
173 struct iovec concat[3];
174 concat[0].iov_base = (void *)type;
175 concat[0].iov_len = type_len;
176 concat[1].iov_base = (void *)"; charset=";
177 concat[1].iov_len = sizeof("; charset=") - 1;
178 concat[2].iov_base = (void *)(conf->add_default_charset_name);
179 concat[2].iov_len = strlen(conf->add_default_charset_name);
180 type = apr_pstrcatv(r->pool, concat, 3, NULL);
189 AP_DECLARE(void) ap_set_content_length(request_rec *r, apr_off_t clength)
191 r->clength = clength;
192 apr_table_setn(r->headers_out, "Content-Length",
193 apr_off_t_toa(r->pool, clength));
197 * Return the latest rational time from a request/mtime (modification time)
198 * pair. We return the mtime unless it's in the future, in which case we
199 * return the current time. We use the request time as a reference in order
200 * to limit the number of calls to time(). We don't check for futurosity
201 * unless the mtime is at least as new as the reference.
203 AP_DECLARE(apr_time_t) ap_rationalize_mtime(request_rec *r, apr_time_t mtime)
207 /* For all static responses, it's almost certain that the file was
208 * last modified before the beginning of the request. So there's
209 * no reason to call time(NULL) again. But if the response has been
210 * created on demand, then it might be newer than the time the request
211 * started. In this event we really have to call time(NULL) again
212 * so that we can give the clients the most accurate Last-Modified. If we
213 * were given a time in the future, we return the current time - the
214 * Last-Modified can't be in the future.
216 now = (mtime < r->request_time) ? r->request_time : apr_time_now();
217 return (mtime > now) ? now : mtime;
220 /* Get a line of protocol input, including any continuation lines
221 * caused by MIME folding (or broken clients) if fold != 0, and place it
222 * in the buffer s, of size n bytes, without the ending newline.
224 * If s is NULL, ap_rgetline_core will allocate necessary memory from r->pool.
226 * Returns APR_SUCCESS if there are no problems and sets *read to be
227 * the full length of s.
229 * APR_ENOSPC is returned if there is not enough buffer space.
230 * Other errors may be returned on other errors.
232 * The LF is *not* returned in the buffer. Therefore, a *read of 0
233 * indicates that an empty line was read.
235 * Notes: Because the buffer uses 1 char for NUL, the most we can return is
236 * (n - 1) actual characters.
238 * If no LF is detected on the last line due to a dropped connection
239 * or a full buffer, that's considered an error.
241 AP_DECLARE(apr_status_t) ap_rgetline_core(char **s, apr_size_t n,
242 apr_size_t *read, request_rec *r,
246 apr_bucket_brigade *b;
248 apr_size_t bytes_handled = 0, current_alloc = 0;
249 char *pos, *last_char = *s;
250 int do_alloc = (*s == NULL), saw_eos = 0;
252 b = apr_brigade_create(r->pool, r->connection->bucket_alloc);
253 rv = ap_get_brigade(r->input_filters, b, AP_MODE_GETLINE,
256 if (rv != APR_SUCCESS) {
257 apr_brigade_destroy(b);
261 /* Something horribly wrong happened. Someone didn't block! */
262 if (APR_BRIGADE_EMPTY(b)) {
263 apr_brigade_destroy(b);
267 APR_BRIGADE_FOREACH(e, b) {
271 /* If we see an EOS, don't bother doing anything more. */
272 if (APR_BUCKET_IS_EOS(e)) {
277 rv = apr_bucket_read(e, &str, &len, APR_BLOCK_READ);
279 if (rv != APR_SUCCESS) {
280 apr_brigade_destroy(b);
285 /* no use attempting a zero-byte alloc (hurts when
286 * using --with-efence --enable-pool-debug) or
287 * doing any of the other logic either
292 /* Would this overrun our buffer? If so, we'll die. */
293 if (n < bytes_handled + len) {
294 apr_brigade_destroy(b);
298 /* Do we have to handle the allocation ourselves? */
300 /* We'll assume the common case where one bucket is enough. */
303 *s = apr_palloc(r->pool, len);
305 else if (bytes_handled + len > current_alloc) {
306 /* We resize to the next power of 2. */
307 apr_size_t new_size = current_alloc;
312 } while (bytes_handled + len > new_size);
314 new_buffer = apr_palloc(r->pool, new_size);
316 /* Copy what we already had. */
317 memcpy(new_buffer, *s, bytes_handled);
318 current_alloc = new_size;
323 /* Just copy the rest of the data to the end of the old buffer. */
324 pos = *s + bytes_handled;
325 memcpy(pos, str, len);
326 last_char = pos + len - 1;
328 /* We've now processed that new data - update accordingly. */
329 bytes_handled += len;
332 /* We no longer need the returned brigade. */
333 apr_brigade_destroy(b);
335 /* We likely aborted early before reading anything or we read no
336 * data. Technically, this might be success condition. But,
337 * probably means something is horribly wrong. For now, we'll
338 * treat this as APR_SUCCESS, but it may be worth re-examining.
340 if (bytes_handled == 0) {
345 /* If we didn't get a full line of input, try again. */
346 if (*last_char != APR_ASCII_LF) {
347 /* Do we have enough space? We may be full now. */
348 if (bytes_handled < n) {
349 apr_size_t next_size, next_len;
352 /* If we're doing the allocations for them, we have to
353 * give ourselves a NULL and copy it on return.
358 /* We're not null terminated yet. */
362 next_size = n - bytes_handled;
364 rv = ap_rgetline_core(&tmp, next_size, &next_len, r, fold);
366 if (rv != APR_SUCCESS) {
370 /* XXX this code appears to be dead because the filter chain
371 * seems to read until it sees a LF or an error. If it ever
372 * comes back to life, we need to make sure that:
373 * - we really alloc enough space for the trailing null
374 * - we don't allow the tail trimming code to run more than
377 if (do_alloc && next_len > 0) {
379 apr_size_t new_size = bytes_handled + next_len;
381 /* Again we need to alloc an extra two bytes for LF, null */
382 new_buffer = apr_palloc(r->pool, new_size);
384 /* Copy what we already had. */
385 memcpy(new_buffer, *s, bytes_handled);
386 memcpy(new_buffer + bytes_handled, tmp, next_len);
387 current_alloc = new_size;
391 bytes_handled += next_len;
392 last_char = *s + bytes_handled - 1;
399 /* We now go backwards over any CR (if present) or white spaces.
401 * Trim any extra trailing spaces or tabs except for the first
402 * space or tab at the beginning of a blank string. This makes
403 * it much easier to check field values for exact matches, and
404 * saves memory as well. Terminate string at end of line.
407 if (pos > *s && *(pos - 1) == APR_ASCII_CR) {
411 /* Trim any extra trailing spaces or tabs except for the first
412 * space or tab at the beginning of a blank string. This makes
413 * it much easier to check field values for exact matches, and
414 * saves memory as well.
416 while (pos > ((*s) + 1)
417 && (*(pos - 1) == APR_ASCII_BLANK || *(pos - 1) == APR_ASCII_TAB)) {
421 /* Since we want to remove the LF from the line, we'll go ahead
422 * and set this last character to be the term NULL and reset
423 * bytes_handled accordingly.
427 bytes_handled = pos - *s;
429 /* If we're folding, we have more work to do.
431 * Note that if an EOS was seen, we know we can't have another line.
433 if (fold && bytes_handled && !saw_eos) {
435 apr_bucket_brigade *bb;
439 /* Create a brigade for this filter read. */
440 bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
442 /* We only care about the first byte. */
443 rv = ap_get_brigade(r->input_filters, bb, AP_MODE_SPECULATIVE,
446 if (rv != APR_SUCCESS) {
447 apr_brigade_destroy(bb);
451 if (APR_BRIGADE_EMPTY(bb)) {
452 *read = bytes_handled;
453 apr_brigade_destroy(bb);
457 e = APR_BRIGADE_FIRST(bb);
459 /* If we see an EOS, don't bother doing anything more. */
460 if (APR_BUCKET_IS_EOS(e)) {
461 *read = bytes_handled;
462 apr_brigade_destroy(bb);
466 rv = apr_bucket_read(e, &str, &len, APR_BLOCK_READ);
468 if (rv != APR_SUCCESS) {
469 apr_brigade_destroy(bb);
473 /* When we call destroy, the buckets are deleted, so save that
474 * one character we need. This simplifies our execution paths
475 * at the cost of one character read.
479 /* We no longer need the returned brigade. */
480 apr_brigade_destroy(bb);
482 /* Found one, so call ourselves again to get the next line.
484 * FIXME: If the folding line is completely blank, should we
485 * stop folding? Does that require also looking at the next
488 if (c == APR_ASCII_BLANK || c == APR_ASCII_TAB) {
489 /* Do we have enough space? We may be full now. */
490 if (bytes_handled < n) {
491 apr_size_t next_size, next_len;
494 /* If we're doing the allocations for them, we have to
495 * give ourselves a NULL and copy it on return.
500 /* We're null terminated. */
504 next_size = n - bytes_handled;
506 rv = ap_rgetline_core(&tmp, next_size, &next_len, r, fold);
508 if (rv != APR_SUCCESS) {
512 if (do_alloc && next_len > 0) {
514 apr_size_t new_size = bytes_handled + next_len + 1;
516 /* we need to alloc an extra byte for a null */
517 new_buffer = apr_palloc(r->pool, new_size);
519 /* Copy what we already had. */
520 memcpy(new_buffer, *s, bytes_handled);
522 /* copy the new line, including the trailing null */
523 memcpy(new_buffer + bytes_handled, tmp, next_len + 1);
527 *read = bytes_handled + next_len;
536 *read = bytes_handled;
540 #if APR_CHARSET_EBCDIC
541 AP_DECLARE(apr_status_t) ap_rgetline(char **s, apr_size_t n,
542 apr_size_t *read, request_rec *r,
545 /* on ASCII boxes, ap_rgetline is a macro which simply invokes
546 * ap_rgetline_core with the same parms
548 * on EBCDIC boxes, each complete http protocol input line needs to be
549 * translated into the code page used by the compiler. Since
550 * ap_rgetline_core uses recursion, we do the translation in a wrapper
551 * function to insure that each input character gets translated only once.
555 rv = ap_rgetline_core(s, n, read, r, fold);
556 if (rv == APR_SUCCESS) {
557 ap_xlate_proto_from_ascii(*s, *read);
563 AP_DECLARE(int) ap_getline(char *s, int n, request_rec *r, int fold)
569 rv = ap_rgetline(&tmp_s, n, &len, r, fold);
571 /* Map the out-of-space condition to the old API. */
572 if (rv == APR_ENOSPC) {
576 /* Anything else is just bad. */
577 if (rv != APR_SUCCESS) {
584 /* parse_uri: break apart the uri
586 * - sets r->args to rest after '?' (or NULL if no '?')
587 * - sets r->uri to request uri (without r->args part)
588 * - sets r->hostname (if not set already) from request (scheme://host:port)
590 AP_CORE_DECLARE(void) ap_parse_uri(request_rec *r, const char *uri)
592 int status = HTTP_OK;
594 r->unparsed_uri = apr_pstrdup(r->pool, uri);
596 if (r->method_number == M_CONNECT) {
597 status = apr_uri_parse_hostinfo(r->pool, uri, &r->parsed_uri);
600 /* Simple syntax Errors in URLs are trapped by
601 * parse_uri_components().
603 status = apr_uri_parse(r->pool, uri, &r->parsed_uri);
606 if (status == APR_SUCCESS) {
607 /* if it has a scheme we may need to do absoluteURI vhost stuff */
608 if (r->parsed_uri.scheme
609 && !strcasecmp(r->parsed_uri.scheme, ap_http_method(r))) {
610 r->hostname = r->parsed_uri.hostname;
612 else if (r->method_number == M_CONNECT) {
613 r->hostname = r->parsed_uri.hostname;
616 r->args = r->parsed_uri.query;
617 r->uri = r->parsed_uri.path ? r->parsed_uri.path
618 : apr_pstrdup(r->pool, "/");
620 #if defined(OS2) || defined(WIN32)
621 /* Handle path translations for OS/2 and plug security hole.
622 * This will prevent "http://www.wherever.com/..\..\/" from
623 * returning a directory for the root drive.
628 for (x = r->uri; (x = strchr(x, '\\')) != NULL; )
631 #endif /* OS2 || WIN32 */
636 r->status = HTTP_BAD_REQUEST; /* set error status */
637 r->uri = apr_pstrdup(r->pool, uri);
641 static int read_request_line(request_rec *r)
648 conn_rec *conn = r->connection;
650 int major = 1, minor = 0; /* Assume HTTP/1.0 if non-"HTTP" protocol */
653 /* Read past empty lines until we get a real request line,
654 * a read error, the connection closes (EOF), or we timeout.
656 * We skip empty lines because browsers have to tack a CRLF on to the end
657 * of POSTs to support old CERN webservers. But note that we may not
658 * have flushed any previous response completely to the client yet.
659 * We delay the flush as long as possible so that we can improve
660 * performance for clients that are pipelining requests. If a request
661 * is pipelined then we won't block during the (implicit) read() below.
662 * If the requests aren't pipelined, then the client is still waiting
663 * for the final buffer flush from us, and we will block in the implicit
664 * read(). B_SAFEREAD ensures that the BUFF layer flushes if it will
665 * have to block during a read.
671 /* insure ap_rgetline allocates memory each time thru the loop
672 * if there are empty lines
674 r->the_request = NULL;
675 rv = ap_rgetline(&(r->the_request), DEFAULT_LIMIT_REQUEST_LINE + 2,
678 if (rv != APR_SUCCESS) {
679 r->request_time = apr_time_now();
684 /* we've probably got something to do, ignore graceful restart requests */
686 r->request_time = apr_time_now();
688 r->method = ap_getword_white(r->pool, &ll);
691 /* XXX If we want to keep track of the Method, the protocol module should do
692 * it. That support isn't in the scoreboard yet. Hopefully next week
694 ap_update_connection_status(AP_CHILD_THREAD_FROM_ID(conn->id), "Method",
698 uri = ap_getword_white(r->pool, &ll);
700 /* Provide quick information about the request method as soon as known */
702 r->method_number = ap_method_number_of(r->method);
703 if (r->method_number == M_GET && r->method[0] == 'H') {
707 ap_parse_uri(r, uri);
709 /* ap_getline returns (size of max buffer - 1) if it fills up the
710 * buffer before finding the end-of-line. This is only going to
711 * happen if it exceeds the configured limit for a request-line.
712 * The cast is safe, limit_req_line cannot be negative
714 if (len > (apr_size_t)r->server->limit_req_line) {
715 r->status = HTTP_REQUEST_URI_TOO_LARGE;
716 r->proto_num = HTTP_VERSION(1,0);
717 r->protocol = apr_pstrdup(r->pool, "HTTP/1.0");
730 r->protocol = apr_pstrmemdup(r->pool, pro, len);
732 /* XXX ap_update_connection_status(conn->id, "Protocol", r->protocol); */
734 /* Avoid sscanf in the common case */
736 && pro[0] == 'H' && pro[1] == 'T' && pro[2] == 'T' && pro[3] == 'P'
737 && pro[4] == '/' && apr_isdigit(pro[5]) && pro[6] == '.'
738 && apr_isdigit(pro[7])) {
739 r->proto_num = HTTP_VERSION(pro[5] - '0', pro[7] - '0');
741 else if (2 == sscanf(r->protocol, "HTTP/%u.%u", &major, &minor)
742 && minor < HTTP_VERSION(1, 0)) /* don't allow HTTP/0.1000 */
743 r->proto_num = HTTP_VERSION(major, minor);
745 r->proto_num = HTTP_VERSION(1, 0);
750 void ap_get_mime_headers(request_rec *r)
756 apr_table_t *tmp_headers;
758 /* We'll use apr_table_overlap later to merge these into r->headers_in. */
759 tmp_headers = apr_table_make(r->pool, 50);
762 * Read header lines until we get the empty separator line, a read error,
763 * the connection closes (EOF), reach the server limit, or we timeout.
769 rv = ap_rgetline(&field, DEFAULT_LIMIT_REQUEST_FIELDSIZE + 2,
772 /* ap_rgetline returns APR_ENOSPC if it fills up the buffer before
773 * finding the end-of-line. This is only going to happen if it
774 * exceeds the configured limit for a field size.
775 * The cast is safe, limit_req_fieldsize cannot be negative
778 || (rv == APR_SUCCESS
779 && len > (apr_size_t)r->server->limit_req_fieldsize)) {
780 r->status = HTTP_BAD_REQUEST;
781 apr_table_setn(r->notes, "error-notes",
783 "Size of a request header field "
784 "exceeds server limit.<br />\n"
786 ap_escape_html(r->pool, field),
791 if (rv != APR_SUCCESS) {
792 r->status = HTTP_BAD_REQUEST;
796 /* Found a blank line, stop. */
801 if (r->server->limit_req_fields
802 && (++fields_read > r->server->limit_req_fields)) {
803 r->status = HTTP_BAD_REQUEST;
804 apr_table_setn(r->notes, "error-notes",
805 "The number of request header fields exceeds "
806 "this server's limit.");
810 if (!(value = strchr(field, ':'))) { /* Find the colon separator */
811 r->status = HTTP_BAD_REQUEST; /* or abort the bad request */
812 apr_table_setn(r->notes, "error-notes",
814 "Request header field is missing "
815 "colon separator.<br />\n"
817 ap_escape_html(r->pool, field),
824 while (*value == ' ' || *value == '\t') {
825 ++value; /* Skip to start of value */
828 apr_table_addn(tmp_headers, field, value);
831 apr_table_overlap(r->headers_in, tmp_headers, APR_OVERLAP_TABLES_MERGE);
834 request_rec *ap_read_request(conn_rec *conn)
841 apr_pool_create(&p, conn->pool);
842 r = apr_pcalloc(p, sizeof(request_rec));
844 r->connection = conn;
845 r->server = conn->base_server;
848 r->ap_auth_type = NULL;
850 r->allowed_methods = ap_make_method_list(p, 2);
852 r->headers_in = apr_table_make(r->pool, 25);
853 r->subprocess_env = apr_table_make(r->pool, 25);
854 r->headers_out = apr_table_make(r->pool, 12);
855 r->err_headers_out = apr_table_make(r->pool, 5);
856 r->notes = apr_table_make(r->pool, 5);
858 r->request_config = ap_create_request_config(r->pool);
859 /* Must be set before we run create request hook */
861 r->proto_output_filters = conn->output_filters;
862 r->output_filters = r->proto_output_filters;
863 r->proto_input_filters = conn->input_filters;
864 r->input_filters = r->proto_input_filters;
865 ap_run_create_request(r);
866 r->per_dir_config = r->server->lookup_defaults;
868 r->sent_bodyct = 0; /* bytect isn't for body */
871 r->read_body = REQUEST_NO_BODY;
873 r->status = HTTP_REQUEST_TIME_OUT; /* Until we get a request */
874 r->the_request = NULL;
876 /* Get the request... */
877 if (!read_request_line(r)) {
878 if (r->status == HTTP_REQUEST_URI_TOO_LARGE) {
879 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
880 "request failed: URI too long");
881 ap_send_error_response(r, 0);
882 ap_run_log_transaction(r);
889 if (!r->assbackwards) {
890 ap_get_mime_headers(r);
891 if (r->status != HTTP_REQUEST_TIME_OUT) {
892 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
893 "request failed: error reading the headers");
894 ap_send_error_response(r, 0);
895 ap_run_log_transaction(r);
900 if (r->header_only) {
902 * Client asked for headers only with HTTP/0.9, which doesn't send
903 * headers! Have to dink things just to make sure the error message
906 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
907 "client sent invalid HTTP/0.9 request: HEAD %s",
910 r->status = HTTP_BAD_REQUEST;
911 ap_send_error_response(r, 0);
912 ap_run_log_transaction(r);
917 r->status = HTTP_OK; /* Until further notice. */
919 /* update what we think the virtual host is based on the headers we've
920 * now read. may update status.
922 ap_update_vhost_from_headers(r);
924 /* we may have switched to another server */
925 r->per_dir_config = r->server->lookup_defaults;
927 if ((!r->hostname && (r->proto_num >= HTTP_VERSION(1, 1)))
928 || ((r->proto_num == HTTP_VERSION(1, 1))
929 && !apr_table_get(r->headers_in, "Host"))) {
931 * Client sent us an HTTP/1.1 or later request without telling us the
932 * hostname, either with a full URL or a Host: header. We therefore
933 * need to (as per the 1.1 spec) send an error. As a special case,
934 * HTTP/1.1 mentions twice (S9, S14.23) that a request MUST contain
935 * a Host: header, and the server MUST respond with 400 if it doesn't.
937 r->status = HTTP_BAD_REQUEST;
938 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
939 "client sent HTTP/1.1 request without hostname "
940 "(see RFC2616 section 14.23): %s", r->uri);
943 if (r->status != HTTP_OK) {
944 ap_send_error_response(r, 0);
945 ap_run_log_transaction(r);
949 if (((expect = apr_table_get(r->headers_in, "Expect")) != NULL)
950 && (expect[0] != '\0')) {
952 * The Expect header field was added to HTTP/1.1 after RFC 2068
953 * as a means to signal when a 100 response is desired and,
954 * unfortunately, to signal a poor man's mandatory extension that
955 * the server must understand or return 417 Expectation Failed.
957 if (strcasecmp(expect, "100-continue") == 0) {
958 r->expecting_100 = 1;
961 r->status = HTTP_EXPECTATION_FAILED;
962 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r,
963 "client sent an unrecognized expectation value of "
964 "Expect: %s", expect);
965 ap_send_error_response(r, 0);
966 (void) ap_discard_request_body(r);
967 ap_run_log_transaction(r);
972 ap_add_input_filter_handle(ap_http_input_filter_handle,
973 NULL, r, r->connection);
975 if ((access_status = ap_run_post_read_request(r))) {
976 ap_die(access_status, r);
977 ap_run_log_transaction(r);
985 * A couple of other functions which initialize some of the fields of
986 * a request structure, as appropriate for adjuncts of one kind or another
987 * to a request in progress. Best here, rather than elsewhere, since
988 * *someone* has to set the protocol-specific fields...
991 void ap_set_sub_req_protocol(request_rec *rnew, const request_rec *r)
993 rnew->the_request = r->the_request; /* Keep original request-line */
995 rnew->assbackwards = 1; /* Don't send headers from this. */
996 rnew->no_local_copy = 1; /* Don't try to send HTTP_NOT_MODIFIED for a
998 rnew->method = "GET";
999 rnew->method_number = M_GET;
1000 rnew->protocol = "INCLUDED";
1002 rnew->status = HTTP_OK;
1004 rnew->headers_in = r->headers_in;
1005 rnew->subprocess_env = apr_table_copy(rnew->pool, r->subprocess_env);
1006 rnew->headers_out = apr_table_make(rnew->pool, 5);
1007 rnew->err_headers_out = apr_table_make(rnew->pool, 5);
1008 rnew->notes = apr_table_make(rnew->pool, 5);
1010 rnew->expecting_100 = r->expecting_100;
1011 rnew->read_length = r->read_length;
1012 rnew->read_body = REQUEST_NO_BODY;
1014 rnew->main = (request_rec *) r;
1017 static void end_output_stream(request_rec *r)
1019 conn_rec *c = r->connection;
1020 apr_bucket_brigade *bb;
1023 bb = apr_brigade_create(r->pool, c->bucket_alloc);
1024 b = apr_bucket_eos_create(c->bucket_alloc);
1025 APR_BRIGADE_INSERT_TAIL(bb, b);
1026 ap_pass_brigade(r->output_filters, bb);
1029 void ap_finalize_sub_req_protocol(request_rec *sub)
1031 end_output_stream(sub);
1034 /* finalize_request_protocol is called at completion of sending the
1035 * response. Its sole purpose is to send the terminating protocol
1036 * information for any wrappers around the response message body
1037 * (i.e., transfer encodings). It should have been named finalize_response.
1039 AP_DECLARE(void) ap_finalize_request_protocol(request_rec *r)
1045 /* tell the filter chain there is no more content coming */
1047 end_output_stream(r);
1052 * Support for the Basic authentication protocol, and a bit for Digest.
1054 AP_DECLARE(void) ap_note_auth_failure(request_rec *r)
1056 const char *type = ap_auth_type(r);
1058 if (!strcasecmp(type, "Basic"))
1059 ap_note_basic_auth_failure(r);
1060 else if (!strcasecmp(type, "Digest"))
1061 ap_note_digest_auth_failure(r);
1064 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR,
1065 0, r, "need AuthType to note auth failure: %s", r->uri);
1069 AP_DECLARE(void) ap_note_basic_auth_failure(request_rec *r)
1071 const char *type = ap_auth_type(r);
1073 /* if there is no AuthType configure or it is something other than
1074 * Basic, let ap_note_auth_failure() deal with it
1076 if (!type || strcasecmp(type, "Basic"))
1077 ap_note_auth_failure(r);
1079 apr_table_setn(r->err_headers_out,
1080 (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authenticate"
1081 : "WWW-Authenticate",
1082 apr_pstrcat(r->pool, "Basic realm=\"", ap_auth_name(r),
1086 AP_DECLARE(void) ap_note_digest_auth_failure(request_rec *r)
1088 apr_table_setn(r->err_headers_out,
1089 (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authenticate"
1090 : "WWW-Authenticate",
1091 apr_psprintf(r->pool, "Digest realm=\"%s\", nonce=\"%llx\"",
1092 ap_auth_name(r), r->request_time));
1095 AP_DECLARE(int) ap_get_basic_auth_pw(request_rec *r, const char **pw)
1097 const char *auth_line = apr_table_get(r->headers_in,
1098 (PROXYREQ_PROXY == r->proxyreq)
1099 ? "Proxy-Authorization"
1103 if (!(t = ap_auth_type(r)) || strcasecmp(t, "Basic"))
1106 if (!ap_auth_name(r)) {
1107 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR,
1108 0, r, "need AuthName: %s", r->uri);
1109 return HTTP_INTERNAL_SERVER_ERROR;
1113 ap_note_basic_auth_failure(r);
1114 return HTTP_UNAUTHORIZED;
1117 if (strcasecmp(ap_getword(r->pool, &auth_line, ' '), "Basic")) {
1118 /* Client tried to authenticate using wrong auth scheme */
1119 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1120 "client used wrong authentication scheme: %s", r->uri);
1121 ap_note_basic_auth_failure(r);
1122 return HTTP_UNAUTHORIZED;
1125 while (*auth_line == ' ' || *auth_line == '\t') {
1129 t = ap_pbase64decode(r->pool, auth_line);
1130 /* Note that this allocation has to be made from r->connection->pool
1131 * because it has the lifetime of the connection. The other allocations
1132 * are temporary and can be tossed away any time.
1134 r->user = ap_getword_nulls (r->pool, &t, ':');
1135 r->ap_auth_type = "Basic";
1142 struct content_length_ctx {
1143 apr_bucket_brigade *saved;
1145 apr_size_t curr_len;
1148 /* This filter computes the content length, but it also computes the number
1149 * of bytes sent to the client. This means that this filter will always run
1150 * through all of the buckets in all brigades
1152 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_content_length_filter(ap_filter_t *f,
1153 apr_bucket_brigade *b)
1155 request_rec *r = f->r;
1156 struct content_length_ctx *ctx;
1159 int eos = 0, flush = 0, partial_send_okay = 0;
1160 apr_bucket_brigade *more, *split;
1161 apr_read_type_e eblock = APR_NONBLOCK_READ;
1164 if (!ctx) { /* first time through */
1165 f->ctx = ctx = apr_pcalloc(r->pool, sizeof(struct content_length_ctx));
1166 ctx->compute_len = 1; /* Assume we will compute the length */
1167 ctx->saved = apr_brigade_create(r->pool, f->c->bucket_alloc);
1170 /* Humm, is this check the best it can be?
1171 * - protocol >= HTTP/1.1 implies support for chunking
1172 * - non-keepalive implies the end of byte stream will be signaled
1173 * by a connection close
1174 * In both cases, we can send bytes to the client w/o needing to
1175 * compute content-length.
1177 * We should be able to force connection close from this filter
1178 * when we see we are buffering too much.
1180 if ((r->proto_num >= HTTP_VERSION(1, 1)) || (!r->connection->keepalive)) {
1181 partial_send_okay = 1;
1191 APR_BRIGADE_FOREACH(e, b) {
1192 const char *ignored;
1195 if (APR_BUCKET_IS_EOS(e)) {
1198 else if (APR_BUCKET_IS_FLUSH(e)) {
1199 if (partial_send_okay) {
1201 more = apr_brigade_split(b, APR_BUCKET_NEXT(e));
1205 else if ((ctx->curr_len > 4 * AP_MIN_BYTES_TO_WRITE)) {
1206 /* If we've accumulated more than 4xAP_MIN_BYTES_TO_WRITE and
1207 * the client supports chunked encoding, send what we have
1208 * and come back for more.
1210 if (partial_send_okay) {
1212 more = apr_brigade_split(b, e);
1216 if (e->length == -1) { /* if length unknown */
1217 rv = apr_bucket_read(e, &ignored, &len, eblock);
1218 if (rv == APR_SUCCESS) {
1219 /* Attempt a nonblocking read next time through */
1220 eblock = APR_NONBLOCK_READ;
1222 else if (APR_STATUS_IS_EAGAIN(rv)) {
1223 /* Make the next read blocking. If the client supports
1224 * chunked encoding, flush the filter stack to the network.
1226 eblock = APR_BLOCK_READ;
1227 if (partial_send_okay) {
1229 more = apr_brigade_split(b, e);
1234 else if (rv != APR_EOF) {
1235 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1236 "ap_content_length_filter: "
1237 "apr_bucket_read() failed");
1245 ctx->curr_len += len;
1246 r->bytes_sent += len;
1250 ctx->compute_len = 0; /* Ooops, can't compute the length now */
1253 APR_BRIGADE_PREPEND(split, ctx->saved);
1256 rv = ap_fflush(f->next, split);
1259 rv = ap_pass_brigade(f->next, split);
1262 if (rv != APR_SUCCESS)
1267 if ((ctx->curr_len < AP_MIN_BYTES_TO_WRITE) && !eos) {
1268 return ap_save_brigade(f, &ctx->saved, &b,
1269 (r->main) ? r->main->pool : r->pool);
1272 if (ctx->compute_len) {
1273 /* save the brigade; we can't pass any data to the next
1274 * filter until we have the entire content length
1277 return ap_save_brigade(f, &ctx->saved, &b, r->pool);
1280 ap_set_content_length(r, r->bytes_sent);
1283 APR_BRIGADE_PREPEND(b, ctx->saved);
1286 return ap_pass_brigade(f->next, b);
1290 * Send the body of a response to the client.
1292 AP_DECLARE(apr_status_t) ap_send_fd(apr_file_t *fd, request_rec *r,
1293 apr_off_t offset, apr_size_t len,
1296 conn_rec *c = r->connection;
1297 apr_bucket_brigade *bb = NULL;
1301 bb = apr_brigade_create(r->pool, c->bucket_alloc);
1302 b = apr_bucket_file_create(fd, offset, len, r->pool, c->bucket_alloc);
1303 APR_BRIGADE_INSERT_TAIL(bb, b);
1305 rv = ap_pass_brigade(r->output_filters, bb);
1306 if (rv != APR_SUCCESS) {
1307 *nbytes = 0; /* no way to tell how many were actually sent */
1317 /* send data from an in-memory buffer */
1318 AP_DECLARE(size_t) ap_send_mmap(apr_mmap_t *mm, request_rec *r, size_t offset,
1321 conn_rec *c = r->connection;
1322 apr_bucket_brigade *bb = NULL;
1325 bb = apr_brigade_create(r->pool, c->bucket_alloc);
1326 b = apr_bucket_mmap_create(mm, offset, length, c->bucket_alloc);
1327 APR_BRIGADE_INSERT_TAIL(bb, b);
1328 ap_pass_brigade(r->output_filters, bb);
1330 return mm->size; /* XXX - change API to report apr_status_t? */
1332 #endif /* APR_HAS_MMAP */
1335 apr_bucket_brigade *bb;
1336 } old_write_filter_ctx;
1338 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_old_write_filter(
1339 ap_filter_t *f, apr_bucket_brigade *bb)
1341 old_write_filter_ctx *ctx = f->ctx;
1343 AP_DEBUG_ASSERT(ctx);
1346 /* whatever is coming down the pipe (we don't care), we
1347 * can simply insert our buffered data at the front and
1348 * pass the whole bundle down the chain.
1350 APR_BRIGADE_CONCAT(ctx->bb, bb);
1355 return ap_pass_brigade(f->next, bb);
1358 static apr_status_t buffer_output(request_rec *r,
1359 const char *str, apr_size_t len)
1361 conn_rec *c = r->connection;
1363 old_write_filter_ctx *ctx;
1368 /* future optimization: record some flags in the request_rec to
1369 * say whether we've added our filter, and whether it is first.
1372 /* this will typically exit on the first test */
1373 for (f = r->output_filters; f != NULL; f = f->next) {
1374 if (ap_old_write_func == f->frec)
1379 /* our filter hasn't been added yet */
1380 ctx = apr_pcalloc(r->pool, sizeof(*ctx));
1381 ap_add_output_filter("OLD_WRITE", ctx, r, r->connection);
1382 f = r->output_filters;
1385 /* if the first filter is not our buffering filter, then we have to
1386 * deliver the content through the normal filter chain
1388 if (f != r->output_filters) {
1389 apr_bucket_brigade *bb = apr_brigade_create(r->pool, c->bucket_alloc);
1390 apr_bucket *b = apr_bucket_transient_create(str, len, c->bucket_alloc);
1391 APR_BRIGADE_INSERT_TAIL(bb, b);
1393 return ap_pass_brigade(r->output_filters, bb);
1396 /* grab the context from our filter */
1397 ctx = r->output_filters->ctx;
1399 if (ctx->bb == NULL) {
1400 ctx->bb = apr_brigade_create(r->pool, c->bucket_alloc);
1403 return ap_fwrite(f->next, ctx->bb, str, len);
1406 AP_DECLARE(int) ap_rputc(int c, request_rec *r)
1410 if (r->connection->aborted) {
1414 if (buffer_output(r, &c2, 1) != APR_SUCCESS)
1420 AP_DECLARE(int) ap_rputs(const char *str, request_rec *r)
1424 if (r->connection->aborted)
1427 if (buffer_output(r, str, len = strlen(str)) != APR_SUCCESS)
1433 AP_DECLARE(int) ap_rwrite(const void *buf, int nbyte, request_rec *r)
1435 if (r->connection->aborted)
1438 if (buffer_output(r, buf, nbyte) != APR_SUCCESS)
1444 struct ap_vrprintf_data {
1445 apr_vformatter_buff_t vbuff;
1450 static apr_status_t r_flush(apr_vformatter_buff_t *buff)
1452 /* callback function passed to ap_vformatter to be called when
1453 * vformatter needs to write into buff and buff.curpos > buff.endpos */
1455 /* ap_vrprintf_data passed as a apr_vformatter_buff_t, which is then
1456 * "downcast" to an ap_vrprintf_data */
1457 struct ap_vrprintf_data *vd = (struct ap_vrprintf_data*)buff;
1459 if (vd->r->connection->aborted)
1462 /* r_flush is called when vbuff is completely full */
1463 if (buffer_output(vd->r, vd->buff, AP_IOBUFSIZE)) {
1467 /* reset the buffer position */
1468 vd->vbuff.curpos = vd->buff;
1469 vd->vbuff.endpos = vd->buff + AP_IOBUFSIZE;
1474 AP_DECLARE(int) ap_vrprintf(request_rec *r, const char *fmt, va_list va)
1477 struct ap_vrprintf_data vd;
1478 char vrprintf_buf[AP_IOBUFSIZE];
1480 vd.vbuff.curpos = vrprintf_buf;
1481 vd.vbuff.endpos = vrprintf_buf + AP_IOBUFSIZE;
1483 vd.buff = vrprintf_buf;
1485 if (r->connection->aborted)
1488 written = apr_vformatter(r_flush, &vd.vbuff, fmt, va);
1490 /* tack on null terminator on remaining string */
1491 *(vd.vbuff.curpos) = '\0';
1493 if (written != -1) {
1494 int n = vd.vbuff.curpos - vrprintf_buf;
1496 /* last call to buffer_output, to finish clearing the buffer */
1497 if (buffer_output(r, vrprintf_buf,n) != APR_SUCCESS)
1506 AP_DECLARE_NONSTD(int) ap_rprintf(request_rec *r, const char *fmt, ...)
1511 if (r->connection->aborted)
1515 n = ap_vrprintf(r, fmt, va);
1521 AP_DECLARE_NONSTD(int) ap_rvputs(request_rec *r, ...)
1526 apr_size_t written = 0;
1528 if (r->connection->aborted)
1531 /* ### TODO: if the total output is large, put all the strings
1532 * ### into a single brigade, rather than flushing each time we
1533 * ### fill the buffer
1537 s = va_arg(va, const char *);
1542 if (buffer_output(r, s, len) != APR_SUCCESS) {
1553 AP_DECLARE(int) ap_rflush(request_rec *r)
1555 conn_rec *c = r->connection;
1556 apr_bucket_brigade *bb;
1559 bb = apr_brigade_create(r->pool, c->bucket_alloc);
1560 b = apr_bucket_flush_create(c->bucket_alloc);
1561 APR_BRIGADE_INSERT_TAIL(bb, b);
1562 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS)
1569 * This function sets the Last-Modified output header field to the value
1570 * of the mtime field in the request structure - rationalized to keep it from
1571 * being in the future.
1573 AP_DECLARE(void) ap_set_last_modified(request_rec *r)
1575 if (!r->assbackwards) {
1576 apr_time_t mod_time = ap_rationalize_mtime(r, r->mtime);
1577 char *datestr = apr_palloc(r->pool, APR_RFC822_DATE_LEN);
1579 apr_rfc822_date(datestr, mod_time);
1580 apr_table_setn(r->headers_out, "Last-Modified", datestr);
1584 AP_IMPLEMENT_HOOK_RUN_ALL(int,post_read_request,
1585 (request_rec *r), (r), OK, DECLINED)
1586 AP_IMPLEMENT_HOOK_RUN_ALL(int,log_transaction,
1587 (request_rec *r), (r), OK, DECLINED)
1588 AP_IMPLEMENT_HOOK_RUN_FIRST(const char *,http_method,
1589 (const request_rec *r), (r), NULL)
1590 AP_IMPLEMENT_HOOK_RUN_FIRST(unsigned short,default_port,
1591 (const request_rec *r), (r), 0)