1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000-2001 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"
72 #define APR_WANT_STDIO /* for sscanf */
73 #define APR_WANT_STRFUNC
74 #define APR_WANT_MEMFUNC
78 #include "util_filter.h"
79 #include "ap_config.h"
81 #include "http_config.h"
82 #include "http_core.h"
83 #include "http_protocol.h"
84 #include "http_main.h"
85 #include "http_request.h"
86 #include "http_vhost.h"
87 #include "http_log.h" /* For errors detected in basic auth common
89 #include "util_charset.h"
90 #include "util_ebcdic.h"
101 APR_HOOK_LINK(post_read_request)
102 APR_HOOK_LINK(log_transaction)
103 APR_HOOK_LINK(http_method)
104 APR_HOOK_LINK(default_port)
107 AP_DECLARE_DATA ap_filter_rec_t *ap_old_write_func = NULL;
110 * Builds the content-type that should be sent to the client from the
111 * content-type specified. The following rules are followed:
112 * - if type is NULL, type is set to ap_default_type(r)
113 * - if charset adding is disabled, stop processing and return type.
114 * - then, if there are no parameters on type, add the default charset
117 AP_DECLARE(const char *)ap_make_content_type(request_rec *r, const char *type)
119 static const char *needcset[] = {
124 core_dir_config *conf =
125 (core_dir_config *)ap_get_module_config(r->per_dir_config,
129 type = ap_default_type(r);
131 if (conf->add_default_charset != ADD_DEFAULT_CHARSET_ON) {
135 if (ap_strcasestr(type, "charset=") != NULL) {
136 /* already has parameter, do nothing */
137 /* XXX we don't check the validity */
141 /* see if it makes sense to add the charset. At present,
142 * we only add it if the Content-type is one of needcset[]
144 for (pcset = needcset; *pcset ; pcset++) {
145 if (ap_strcasestr(type, *pcset) != NULL) {
146 type = apr_pstrcat(r->pool, type, "; charset=",
147 conf->add_default_charset_name, NULL);
155 AP_DECLARE(void) ap_set_content_length(request_rec *r, apr_off_t clength)
157 r->clength = clength;
158 apr_table_setn(r->headers_out, "Content-Length",
159 apr_off_t_toa(r->pool, clength));
163 * Return the latest rational time from a request/mtime (modification time)
164 * pair. We return the mtime unless it's in the future, in which case we
165 * return the current time. We use the request time as a reference in order
166 * to limit the number of calls to time(). We don't check for futurosity
167 * unless the mtime is at least as new as the reference.
169 AP_DECLARE(apr_time_t) ap_rationalize_mtime(request_rec *r, apr_time_t mtime)
173 /* For all static responses, it's almost certain that the file was
174 * last modified before the beginning of the request. So there's
175 * no reason to call time(NULL) again. But if the response has been
176 * created on demand, then it might be newer than the time the request
177 * started. In this event we really have to call time(NULL) again
178 * so that we can give the clients the most accurate Last-Modified. If we
179 * were given a time in the future, we return the current time - the
180 * Last-Modified can't be in the future.
182 now = (mtime < r->request_time) ? r->request_time : apr_time_now();
183 return (mtime > now) ? now : mtime;
186 /* Get a line of protocol input, including any continuation lines
187 * caused by MIME folding (or broken clients) if fold != 0, and place it
188 * in the buffer s, of size n bytes, without the ending newline.
190 * If s is NULL, ap_rgetline will allocate necessary memory from r->pool.
192 * Returns APR_SUCCESS if there are no problems and sets *read to be
193 * the full length of s.
195 * APR_ENOSPC is returned if there is not enough buffer space.
196 * Other errors may be returned on other errors.
198 * The LF is *not* returned in the buffer. Therefore, a *read of 0
199 * indicates that an empty line was read.
201 * Notes: Because the buffer uses 1 char for NUL, the most we can return is
202 * (n - 1) actual characters.
204 * If no LF is detected on the last line due to a dropped connection
205 * or a full buffer, that's considered an error.
207 AP_DECLARE(apr_status_t) ap_rgetline(char **s, apr_size_t n,
208 apr_size_t *read, request_rec *r,
212 apr_bucket_brigade *b;
214 apr_size_t bytes_handled = 0, current_alloc = 0;
215 char *pos, *last_char = *s;
216 int do_alloc = (*s == NULL), saw_eos = 0;
218 b = apr_brigade_create(r->pool);
219 rv = ap_get_brigade(r->input_filters, b, AP_MODE_GETLINE,
222 if (rv != APR_SUCCESS) {
223 apr_brigade_destroy(b);
227 /* Something horribly wrong happened. Someone didn't block! */
228 if (APR_BRIGADE_EMPTY(b)) {
229 apr_brigade_destroy(b);
233 APR_BRIGADE_FOREACH(e, b) {
237 /* If we see an EOS, don't bother doing anything more. */
238 if (APR_BUCKET_IS_EOS(e)) {
243 rv = apr_bucket_read(e, &str, &len, APR_BLOCK_READ);
245 if (rv != APR_SUCCESS) {
246 apr_brigade_destroy(b);
251 /* no use attempting a zero-byte alloc (hurts when
252 * using --with-efence --enable-pool-debug) or
253 * doing any of the other logic either
258 /* Would this overrun our buffer? If so, we'll die. */
259 if (n < bytes_handled + len) {
260 apr_brigade_destroy(b);
264 /* Do we have to handle the allocation ourselves? */
266 /* We'll assume the common case where one bucket is enough. */
269 *s = apr_palloc(r->pool, len);
271 else if (bytes_handled + len > current_alloc) {
272 /* We resize to the next power of 2. */
273 apr_size_t new_size = current_alloc;
277 } while (bytes_handled + len > new_size);
278 new_buffer = apr_palloc(r->pool, new_size);
279 /* Copy what we already had. */
280 memcpy(new_buffer, *s, bytes_handled);
281 current_alloc = new_size;
285 /* Just copy the rest of the data to the end of the old buffer. */
286 pos = *s + bytes_handled;
287 memcpy(pos, str, len);
288 last_char = pos + len - 1;
290 /* We've now processed that new data - update accordingly. */
291 bytes_handled += len;
294 /* We no longer need the returned brigade. */
295 apr_brigade_destroy(b);
297 /* We likely aborted early before reading anything or we read no
298 * data. Technically, this might be success condition. But,
299 * probably means something is horribly wrong. For now, we'll
300 * treat this as APR_SUCCESS, but it may be worth re-examining.
302 if (bytes_handled == 0) {
307 /* If we didn't get a full line of input, try again. */
308 if (*last_char != APR_ASCII_LF) {
309 /* Do we have enough space? We may be full now. */
310 if (bytes_handled < n) {
311 apr_size_t next_size, next_len;
314 /* If we're doing the allocations for them, we have to
315 * give ourselves a NULL and copy it on return.
320 /* We're not null terminated yet. */
324 next_size = n - bytes_handled;
326 rv = ap_rgetline(&tmp, next_size, &next_len, r, fold);
328 if (rv != APR_SUCCESS) {
332 if (do_alloc && next_len > 0) {
334 apr_size_t new_size = bytes_handled + next_len;
335 /* Again we need to alloc an extra two bytes for LF, null */
336 new_buffer = apr_palloc(r->pool, new_size);
337 /* Copy what we already had. */
338 memcpy(new_buffer, *s, bytes_handled);
339 memcpy(new_buffer + bytes_handled, tmp, next_len);
340 current_alloc = new_size;
344 bytes_handled += next_len;
345 last_char = *s + bytes_handled - 1;
352 /* We now go backwards over any CR (if present) or white spaces.
354 * Trim any extra trailing spaces or tabs except for the first
355 * space or tab at the beginning of a blank string. This makes
356 * it much easier to check field values for exact matches, and
357 * saves memory as well. Terminate string at end of line.
360 if (pos > *s && *(pos - 1) == APR_ASCII_CR) {
364 /* Trim any extra trailing spaces or tabs except for the first
365 * space or tab at the beginning of a blank string. This makes
366 * it much easier to check field values for exact matches, and
367 * saves memory as well.
369 while (pos > ((*s) + 1) &&
370 (*(pos - 1) == APR_ASCII_BLANK || *(pos - 1) == APR_ASCII_TAB)) {
374 /* Since we want to remove the LF from the line, we'll go ahead
375 * and set this last character to be the term NULL and reset
376 * bytes_handled accordingly.
380 bytes_handled = pos - *s;
382 /* If we're folding, we have more work to do.
384 * Note that if an EOS was seen, we know we can't have another line.
386 if (fold && bytes_handled && !saw_eos) {
388 apr_bucket_brigade *bb;
392 /* Create a brigade for this filter read. */
393 bb = apr_brigade_create(r->pool);
395 /* We only care about the first byte. */
396 rv = ap_get_brigade(r->input_filters, bb, AP_MODE_SPECULATIVE,
399 if (rv != APR_SUCCESS) {
400 apr_brigade_destroy(bb);
404 if (APR_BRIGADE_EMPTY(bb)) {
405 *read = bytes_handled;
406 apr_brigade_destroy(bb);
410 e = APR_BRIGADE_FIRST(bb);
412 /* If we see an EOS, don't bother doing anything more. */
413 if (APR_BUCKET_IS_EOS(e)) {
414 *read = bytes_handled;
415 apr_brigade_destroy(bb);
419 rv = apr_bucket_read(e, &str, &len, APR_BLOCK_READ);
421 if (rv != APR_SUCCESS) {
422 apr_brigade_destroy(bb);
426 /* When we call destroy, the buckets are deleted, so save that
427 * one character we need. This simplifies our execution paths
428 * at the cost of one character read.
432 /* We no longer need the returned brigade. */
433 apr_brigade_destroy(bb);
435 /* Found one, so call ourselves again to get the next line.
437 * FIXME: If the folding line is completely blank, should we
438 * stop folding? Does that require also looking at the next
441 if (c == APR_ASCII_BLANK || c == APR_ASCII_TAB) {
442 /* Do we have enough space? We may be full now. */
443 if (bytes_handled < n) {
444 apr_size_t next_size, next_len;
447 /* If we're doing the allocations for them, we have to
448 * give ourselves a NULL and copy it on return.
453 /* We're null terminated. */
457 next_size = n - bytes_handled;
459 rv = ap_rgetline(&tmp, next_size, &next_len, r, fold);
461 if (rv != APR_SUCCESS) {
465 if (do_alloc && next_len > 0) {
467 apr_size_t new_size = bytes_handled + next_len;
468 /* Again we need to alloc an extra two bytes for LF, null */
469 new_buffer = apr_palloc(r->pool, new_size);
470 /* Copy what we already had. */
471 memcpy(new_buffer, *s, bytes_handled);
472 memcpy(new_buffer + bytes_handled, tmp, next_len);
473 current_alloc = new_size;
477 *read = bytes_handled + next_len;
486 /* FIXME: Can we optimize this at all by placing it a different layer? */
487 ap_xlate_proto_from_ascii(*s, bytes_handled);
488 *read = bytes_handled;
492 AP_DECLARE(int) ap_getline(char *s, int n, request_rec *r, int fold)
498 rv = ap_rgetline(&tmp_s, n, &len, r, fold);
500 /* Map the out-of-space condition to the old API. */
501 if (rv == APR_ENOSPC) {
505 /* Anything else is just bad. */
506 if (rv != APR_SUCCESS) {
513 /* parse_uri: break apart the uri
515 * - sets r->args to rest after '?' (or NULL if no '?')
516 * - sets r->uri to request uri (without r->args part)
517 * - sets r->hostname (if not set already) from request (scheme://host:port)
519 AP_CORE_DECLARE(void) ap_parse_uri(request_rec *r, const char *uri)
521 int status = HTTP_OK;
523 r->unparsed_uri = apr_pstrdup(r->pool, uri);
525 if (r->method_number == M_CONNECT) {
526 status = apr_uri_parse_hostinfo(r->pool, uri, &r->parsed_uri);
529 /* Simple syntax Errors in URLs are trapped by parse_uri_components(). */
530 status = apr_uri_parse(r->pool, uri, &r->parsed_uri);
533 if (status == APR_SUCCESS) {
534 /* if it has a scheme we may need to do absoluteURI vhost stuff */
535 if (r->parsed_uri.scheme
536 && !strcasecmp(r->parsed_uri.scheme, ap_http_method(r))) {
537 r->hostname = r->parsed_uri.hostname;
539 else if (r->method_number == M_CONNECT) {
540 r->hostname = r->parsed_uri.hostname;
542 r->args = r->parsed_uri.query;
543 r->uri = r->parsed_uri.path ? r->parsed_uri.path
544 : apr_pstrdup(r->pool, "/");
545 #if defined(OS2) || defined(WIN32)
546 /* Handle path translations for OS/2 and plug security hole.
547 * This will prevent "http://www.wherever.com/..\..\/" from
548 * returning a directory for the root drive.
553 for (x = r->uri; (x = strchr(x, '\\')) != NULL; )
556 #endif /* OS2 || WIN32 */
561 r->status = HTTP_BAD_REQUEST; /* set error status */
562 r->uri = apr_pstrdup(r->pool, uri);
566 static int read_request_line(request_rec *r)
573 conn_rec *conn = r->connection;
575 int major = 1, minor = 0; /* Assume HTTP/1.0 if non-"HTTP" protocol */
578 /* Read past empty lines until we get a real request line,
579 * a read error, the connection closes (EOF), or we timeout.
581 * We skip empty lines because browsers have to tack a CRLF on to the end
582 * of POSTs to support old CERN webservers. But note that we may not
583 * have flushed any previous response completely to the client yet.
584 * We delay the flush as long as possible so that we can improve
585 * performance for clients that are pipelining requests. If a request
586 * is pipelined then we won't block during the (implicit) read() below.
587 * If the requests aren't pipelined, then the client is still waiting
588 * for the final buffer flush from us, and we will block in the implicit
589 * read(). B_SAFEREAD ensures that the BUFF layer flushes if it will
590 * have to block during a read.
596 /* insure ap_rgetline allocates memory each time thru the loop
597 * if there are empty lines
599 r->the_request = NULL;
600 rv = ap_rgetline(&(r->the_request), DEFAULT_LIMIT_REQUEST_LINE + 2,
603 if (rv != APR_SUCCESS) {
604 r->request_time = apr_time_now();
609 /* we've probably got something to do, ignore graceful restart requests */
611 r->request_time = apr_time_now();
613 r->method = ap_getword_white(r->pool, &ll);
616 /* XXX If we want to keep track of the Method, the protocol module should do
617 * it. That support isn't in the scoreboard yet. Hopefully next week
619 ap_update_connection_status(AP_CHILD_THREAD_FROM_ID(conn->id), "Method", r->method);
621 uri = ap_getword_white(r->pool, &ll);
623 /* Provide quick information about the request method as soon as known */
625 r->method_number = ap_method_number_of(r->method);
626 if (r->method_number == M_GET && r->method[0] == 'H') {
630 ap_parse_uri(r, uri);
632 /* ap_getline returns (size of max buffer - 1) if it fills up the
633 * buffer before finding the end-of-line. This is only going to
634 * happen if it exceeds the configured limit for a request-line.
636 if (len > r->server->limit_req_line) {
637 r->status = HTTP_REQUEST_URI_TOO_LARGE;
638 r->proto_num = HTTP_VERSION(1,0);
639 r->protocol = apr_pstrdup(r->pool, "HTTP/1.0");
652 r->protocol = apr_pstrmemdup(r->pool, pro, len);
654 /* XXX ap_update_connection_status(conn->id, "Protocol", r->protocol); */
656 /* Avoid sscanf in the common case */
658 pro[0] == 'H' && pro[1] == 'T' && pro[2] == 'T' && pro[3] == 'P' &&
659 pro[4] == '/' && apr_isdigit(pro[5]) && pro[6] == '.' &&
660 apr_isdigit(pro[7])) {
661 r->proto_num = HTTP_VERSION(pro[5] - '0', pro[7] - '0');
662 } else if (2 == sscanf(r->protocol, "HTTP/%u.%u", &major, &minor)
663 && minor < HTTP_VERSION(1,0)) /* don't allow HTTP/0.1000 */
664 r->proto_num = HTTP_VERSION(major, minor);
666 r->proto_num = HTTP_VERSION(1,0);
671 static void get_mime_headers(request_rec *r)
677 apr_table_t *tmp_headers;
679 /* We'll use apr_table_overlap later to merge these into r->headers_in. */
680 tmp_headers = apr_table_make(r->pool, 50);
683 * Read header lines until we get the empty separator line, a read error,
684 * the connection closes (EOF), reach the server limit, or we timeout.
690 rv = ap_rgetline(&field, DEFAULT_LIMIT_REQUEST_FIELDSIZE + 2,
693 /* ap_rgetline returns APR_ENOSPC if it fills up the buffer before
694 * finding the end-of-line. This is only going to happen if it
695 * exceeds the configured limit for a field size.
697 if (rv == APR_ENOSPC ||
698 (rv == APR_SUCCESS && len > r->server->limit_req_fieldsize)) {
699 r->status = HTTP_BAD_REQUEST;
700 apr_table_setn(r->notes, "error-notes",
702 "Size of a request header field "
703 "exceeds server limit.<br />\n"
705 ap_escape_html(r->pool, field),
710 if (rv != APR_SUCCESS) {
711 r->status = HTTP_BAD_REQUEST;
715 /* Found a blank line, stop. */
720 if (r->server->limit_req_fields &&
721 (++fields_read > r->server->limit_req_fields)) {
722 r->status = HTTP_BAD_REQUEST;
723 apr_table_setn(r->notes, "error-notes",
724 "The number of request header fields exceeds "
725 "this server's limit.");
729 if (!(value = strchr(field, ':'))) { /* Find the colon separator */
730 r->status = HTTP_BAD_REQUEST; /* or abort the bad request */
731 apr_table_setn(r->notes, "error-notes",
733 "Request header field is missing "
734 "colon separator.<br />\n"
736 ap_escape_html(r->pool, field),
743 while (*value == ' ' || *value == '\t') {
744 ++value; /* Skip to start of value */
747 apr_table_addn(tmp_headers, field, value);
750 apr_table_overlap(r->headers_in, tmp_headers, APR_OVERLAP_TABLES_MERGE);
753 request_rec *ap_read_request(conn_rec *conn)
760 apr_pool_create(&p, conn->pool);
761 r = apr_pcalloc(p, sizeof(request_rec));
763 r->connection = conn;
764 r->server = conn->base_server;
767 r->ap_auth_type = NULL;
769 r->allowed_methods = ap_make_method_list(p, 2);
771 r->headers_in = apr_table_make(r->pool, 25);
772 r->subprocess_env = apr_table_make(r->pool, 25);
773 r->headers_out = apr_table_make(r->pool, 12);
774 r->err_headers_out = apr_table_make(r->pool, 5);
775 r->notes = apr_table_make(r->pool, 5);
777 r->request_config = ap_create_request_config(r->pool);
778 /* Must be set before we run create request hook */
779 r->output_filters = conn->output_filters;
780 r->input_filters = conn->input_filters;
781 ap_run_create_request(r);
782 r->per_dir_config = r->server->lookup_defaults;
784 r->sent_bodyct = 0; /* bytect isn't for body */
787 r->read_body = REQUEST_NO_BODY;
789 r->status = HTTP_REQUEST_TIME_OUT; /* Until we get a request */
790 r->the_request = NULL;
792 /* Get the request... */
793 if (!read_request_line(r)) {
794 if (r->status == HTTP_REQUEST_URI_TOO_LARGE) {
795 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
796 "request failed: URI too long");
797 ap_send_error_response(r, 0);
798 ap_run_log_transaction(r);
804 if (!r->assbackwards) {
806 if (r->status != HTTP_REQUEST_TIME_OUT) {
807 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
808 "request failed: error reading the headers");
809 ap_send_error_response(r, 0);
810 ap_run_log_transaction(r);
815 if (r->header_only) {
817 * Client asked for headers only with HTTP/0.9, which doesn't send
818 * headers! Have to dink things just to make sure the error message
821 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
822 "client sent invalid HTTP/0.9 request: HEAD %s",
825 r->status = HTTP_BAD_REQUEST;
826 ap_send_error_response(r, 0);
827 ap_run_log_transaction(r);
832 r->status = HTTP_OK; /* Until further notice. */
834 /* update what we think the virtual host is based on the headers we've
835 * now read. may update status.
837 ap_update_vhost_from_headers(r);
839 /* we may have switched to another server */
840 r->per_dir_config = r->server->lookup_defaults;
842 if ((!r->hostname && (r->proto_num >= HTTP_VERSION(1,1))) ||
843 ((r->proto_num == HTTP_VERSION(1,1)) &&
844 !apr_table_get(r->headers_in, "Host"))) {
846 * Client sent us an HTTP/1.1 or later request without telling us the
847 * hostname, either with a full URL or a Host: header. We therefore
848 * need to (as per the 1.1 spec) send an error. As a special case,
849 * HTTP/1.1 mentions twice (S9, S14.23) that a request MUST contain
850 * a Host: header, and the server MUST respond with 400 if it doesn't.
852 r->status = HTTP_BAD_REQUEST;
853 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
854 "client sent HTTP/1.1 request without hostname "
855 "(see RFC2616 section 14.23): %s", r->uri);
857 if (r->status != HTTP_OK) {
858 ap_send_error_response(r, 0);
859 ap_run_log_transaction(r);
862 if (((expect = apr_table_get(r->headers_in, "Expect")) != NULL) &&
863 (expect[0] != '\0')) {
865 * The Expect header field was added to HTTP/1.1 after RFC 2068
866 * as a means to signal when a 100 response is desired and,
867 * unfortunately, to signal a poor man's mandatory extension that
868 * the server must understand or return 417 Expectation Failed.
870 if (strcasecmp(expect, "100-continue") == 0) {
871 r->expecting_100 = 1;
874 r->status = HTTP_EXPECTATION_FAILED;
875 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r,
876 "client sent an unrecognized expectation value of "
877 "Expect: %s", expect);
878 ap_send_error_response(r, 0);
879 (void) ap_discard_request_body(r);
880 ap_run_log_transaction(r);
885 ap_add_input_filter_handle(ap_http_input_filter_handle,
886 NULL, r, r->connection);
888 if ((access_status = ap_run_post_read_request(r))) {
889 ap_die(access_status, r);
890 ap_run_log_transaction(r);
898 * A couple of other functions which initialize some of the fields of
899 * a request structure, as appropriate for adjuncts of one kind or another
900 * to a request in progress. Best here, rather than elsewhere, since
901 * *someone* has to set the protocol-specific fields...
904 void ap_set_sub_req_protocol(request_rec *rnew, const request_rec *r)
906 rnew->the_request = r->the_request; /* Keep original request-line */
908 rnew->assbackwards = 1; /* Don't send headers from this. */
909 rnew->no_local_copy = 1; /* Don't try to send HTTP_NOT_MODIFIED for a
911 rnew->method = "GET";
912 rnew->method_number = M_GET;
913 rnew->protocol = "INCLUDED";
915 rnew->status = HTTP_OK;
917 rnew->headers_in = r->headers_in;
918 rnew->subprocess_env = apr_table_copy(rnew->pool, r->subprocess_env);
919 rnew->headers_out = apr_table_make(rnew->pool, 5);
920 rnew->err_headers_out = apr_table_make(rnew->pool, 5);
921 rnew->notes = apr_table_make(rnew->pool, 5);
923 rnew->expecting_100 = r->expecting_100;
924 rnew->read_length = r->read_length;
925 rnew->read_body = REQUEST_NO_BODY;
927 rnew->main = (request_rec *) r;
930 static void end_output_stream(request_rec *r)
932 apr_bucket_brigade *bb;
935 bb = apr_brigade_create(r->pool);
936 b = apr_bucket_eos_create();
937 APR_BRIGADE_INSERT_TAIL(bb, b);
938 ap_pass_brigade(r->output_filters, bb);
941 void ap_finalize_sub_req_protocol(request_rec *sub)
943 end_output_stream(sub);
946 /* finalize_request_protocol is called at completion of sending the
947 * response. Its sole purpose is to send the terminating protocol
948 * information for any wrappers around the response message body
949 * (i.e., transfer encodings). It should have been named finalize_response.
951 AP_DECLARE(void) ap_finalize_request_protocol(request_rec *r)
956 /* tell the filter chain there is no more content coming */
958 end_output_stream(r);
963 * Support for the Basic authentication protocol, and a bit for Digest.
966 AP_DECLARE(void) ap_note_auth_failure(request_rec *r)
968 const char *type = ap_auth_type(r);
970 if (!strcasecmp(type, "Basic"))
971 ap_note_basic_auth_failure(r);
972 else if (!strcasecmp(type, "Digest"))
973 ap_note_digest_auth_failure(r);
976 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR,
977 0, r, "need AuthType to note auth failure: %s", r->uri);
981 AP_DECLARE(void) ap_note_basic_auth_failure(request_rec *r)
983 const char *type = ap_auth_type(r);
984 /* if there is no AuthType configure or it is something other than
985 * Basic, let ap_note_auth_failure() deal with it
987 if (!type || strcasecmp(type, "Basic"))
988 ap_note_auth_failure(r);
990 apr_table_setn(r->err_headers_out,
991 (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authenticate" : "WWW-Authenticate",
992 apr_pstrcat(r->pool, "Basic realm=\"", ap_auth_name(r), "\"",
996 AP_DECLARE(void) ap_note_digest_auth_failure(request_rec *r)
998 apr_table_setn(r->err_headers_out,
999 (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authenticate" : "WWW-Authenticate",
1000 apr_psprintf(r->pool, "Digest realm=\"%s\", nonce=\"%llx\"",
1001 ap_auth_name(r), r->request_time));
1004 AP_DECLARE(int) ap_get_basic_auth_pw(request_rec *r, const char **pw)
1006 const char *auth_line = apr_table_get(r->headers_in,
1007 (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authorization"
1011 if (!(t = ap_auth_type(r)) || strcasecmp(t, "Basic"))
1014 if (!ap_auth_name(r)) {
1015 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR,
1016 0, r, "need AuthName: %s", r->uri);
1017 return HTTP_INTERNAL_SERVER_ERROR;
1021 ap_note_basic_auth_failure(r);
1022 return HTTP_UNAUTHORIZED;
1025 if (strcasecmp(ap_getword(r->pool, &auth_line, ' '), "Basic")) {
1026 /* Client tried to authenticate using wrong auth scheme */
1027 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1028 "client used wrong authentication scheme: %s", r->uri);
1029 ap_note_basic_auth_failure(r);
1030 return HTTP_UNAUTHORIZED;
1033 while (*auth_line== ' ' || *auth_line== '\t') {
1037 t = ap_pbase64decode(r->pool, auth_line);
1038 /* Note that this allocation has to be made from r->connection->pool
1039 * because it has the lifetime of the connection. The other allocations
1040 * are temporary and can be tossed away any time.
1042 r->user = ap_getword_nulls (r->pool, &t, ':');
1043 r->ap_auth_type = "Basic";
1050 struct content_length_ctx {
1051 apr_bucket_brigade *saved;
1053 apr_size_t curr_len;
1056 /* This filter computes the content length, but it also computes the number
1057 * of bytes sent to the client. This means that this filter will always run
1058 * through all of the buckets in all brigades
1060 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_content_length_filter(ap_filter_t *f,
1061 apr_bucket_brigade *b)
1063 request_rec *r = f->r;
1064 struct content_length_ctx *ctx;
1067 int eos = 0, flush = 0, partial_send_okay = 0;
1068 apr_bucket_brigade *more, *split;
1069 apr_read_type_e eblock = APR_NONBLOCK_READ;
1072 if (!ctx) { /* first time through */
1073 f->ctx = ctx = apr_pcalloc(r->pool, sizeof(struct content_length_ctx));
1074 ctx->compute_len = 1; /* Assume we will compute the length */
1077 /* Humm, is this check the best it can be?
1078 * - protocol >= HTTP/1.1 implies support for chunking
1079 * - non-keepalive implies the end of byte stream will be signaled
1080 * by a connection close
1081 * In both cases, we can send bytes to the client w/o needing to
1082 * compute content-length.
1084 * We should be able to force connection close from this filter
1085 * when we see we are buffering too much.
1087 if ((r->proto_num >= HTTP_VERSION(1,1)) ||
1088 (!f->r->connection->keepalive)) {
1089 partial_send_okay = 1;
1099 APR_BRIGADE_FOREACH(e, b) {
1100 const char *ignored;
1103 if (APR_BUCKET_IS_EOS(e)) {
1106 else if (APR_BUCKET_IS_FLUSH(e)) {
1107 if (partial_send_okay) {
1109 more = apr_brigade_split(b, APR_BUCKET_NEXT(e));
1113 else if ((ctx->curr_len > 4*AP_MIN_BYTES_TO_WRITE)) {
1114 /* If we've accumulated more than 4xAP_MIN_BYTES_TO_WRITE and
1115 * the client supports chunked encoding, send what we have
1116 * and come back for more.
1118 if (partial_send_okay) {
1120 more = apr_brigade_split(b, e);
1124 if (e->length == -1) { /* if length unknown */
1125 rv = apr_bucket_read(e, &ignored, &len, eblock);
1126 if (rv == APR_SUCCESS) {
1127 /* Attempt a nonblocking read next time through */
1128 eblock = APR_NONBLOCK_READ;
1130 else if (APR_STATUS_IS_EAGAIN(rv)) {
1131 /* Make the next read blocking. If the client supports chunked
1132 * encoding, flush the filter stack to the network.
1134 eblock = APR_BLOCK_READ;
1135 if (partial_send_okay) {
1137 more = apr_brigade_split(b, e);
1142 else if (rv != APR_EOF) {
1143 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1144 "ap_content_length_filter: apr_bucket_read() failed");
1151 ctx->curr_len += len;
1152 r->bytes_sent += len;
1156 ctx->compute_len = 0; /* Ooops, can't compute the length now */
1159 APR_BRIGADE_CONCAT(ctx->saved, split);
1160 apr_brigade_destroy(split);
1165 rv = ap_fflush(f->next, split);
1168 rv = ap_pass_brigade(f->next, split);
1170 if (rv != APR_SUCCESS)
1175 if ((ctx->curr_len < AP_MIN_BYTES_TO_WRITE) && !eos) {
1176 return ap_save_brigade(f, &ctx->saved, &b, (r->main) ? r->main->pool : r->pool);
1179 if (ctx->compute_len) {
1180 /* save the brigade; we can't pass any data to the next
1181 * filter until we have the entire content length
1184 return ap_save_brigade(f, &ctx->saved, &b, r->pool);
1186 ap_set_content_length(r, r->bytes_sent);
1189 APR_BRIGADE_CONCAT(ctx->saved, b);
1190 apr_brigade_destroy(b);
1196 return ap_pass_brigade(f->next, b);
1200 * Send the body of a response to the client.
1202 AP_DECLARE(apr_status_t) ap_send_fd(apr_file_t *fd, request_rec *r, apr_off_t offset,
1203 apr_size_t len, apr_size_t *nbytes)
1205 apr_bucket_brigade *bb = NULL;
1209 bb = apr_brigade_create(r->pool);
1210 b = apr_bucket_file_create(fd, offset, len, r->pool);
1211 APR_BRIGADE_INSERT_TAIL(bb, b);
1213 rv = ap_pass_brigade(r->output_filters, bb);
1214 if (rv != APR_SUCCESS) {
1215 *nbytes = 0; /* no way to tell how many were actually sent */
1225 /* send data from an in-memory buffer */
1226 AP_DECLARE(size_t) ap_send_mmap(apr_mmap_t *mm, request_rec *r, size_t offset,
1229 apr_bucket_brigade *bb = NULL;
1232 bb = apr_brigade_create(r->pool);
1233 b = apr_bucket_mmap_create(mm, offset, length);
1234 APR_BRIGADE_INSERT_TAIL(bb, b);
1235 ap_pass_brigade(r->output_filters, bb);
1237 return mm->size; /* XXX - change API to report apr_status_t? */
1239 #endif /* APR_HAS_MMAP */
1242 apr_bucket_brigade *bb;
1243 } old_write_filter_ctx;
1245 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_old_write_filter(
1246 ap_filter_t *f, apr_bucket_brigade *bb)
1248 old_write_filter_ctx *ctx = f->ctx;
1250 AP_DEBUG_ASSERT(ctx);
1253 /* whatever is coming down the pipe (we don't care), we
1254 * can simply insert our buffered data at the front and
1255 * pass the whole bundle down the chain.
1257 APR_BRIGADE_CONCAT(ctx->bb, bb);
1260 return ap_pass_brigade(f->next, ctx->bb);
1263 static apr_status_t buffer_output(request_rec *r,
1264 const char *str, apr_size_t len)
1267 old_write_filter_ctx *ctx;
1272 /* future optimization: record some flags in the request_rec to
1273 * say whether we've added our filter, and whether it is first.
1276 /* this will typically exit on the first test */
1277 for (f = r->output_filters; f != NULL; f = f->next)
1278 if (ap_old_write_func == f->frec)
1281 /* our filter hasn't been added yet */
1282 ctx = apr_pcalloc(r->pool, sizeof(*ctx));
1283 ap_add_output_filter("OLD_WRITE", ctx, r, r->connection);
1284 f = r->output_filters;
1287 /* if the first filter is not our buffering filter, then we have to
1288 * deliver the content through the normal filter chain */
1289 if (f != r->output_filters) {
1290 apr_bucket_brigade *bb = apr_brigade_create(r->pool);
1291 apr_bucket *b = apr_bucket_transient_create(str, len);
1292 APR_BRIGADE_INSERT_TAIL(bb, b);
1294 return ap_pass_brigade(r->output_filters, bb);
1297 /* grab the context from our filter */
1298 ctx = r->output_filters->ctx;
1300 if (ctx->bb == NULL) {
1301 ctx->bb = apr_brigade_create(r->pool);
1304 return ap_fwrite(f->next, ctx->bb, str, len);
1307 AP_DECLARE(int) ap_rputc(int c, request_rec *r)
1311 if (r->connection->aborted) {
1315 if (buffer_output(r, &c2, 1) != APR_SUCCESS)
1321 AP_DECLARE(int) ap_rputs(const char *str, request_rec *r)
1325 if (r->connection->aborted)
1328 if (buffer_output(r, str, len = strlen(str)) != APR_SUCCESS)
1334 AP_DECLARE(int) ap_rwrite(const void *buf, int nbyte, request_rec *r)
1336 if (r->connection->aborted)
1339 if (buffer_output(r, buf, nbyte) != APR_SUCCESS)
1345 struct ap_vrprintf_data {
1346 apr_vformatter_buff_t vbuff;
1351 static apr_status_t r_flush(apr_vformatter_buff_t *buff)
1353 /* callback function passed to ap_vformatter to be called when
1354 * vformatter needs to write into buff and buff.curpos > buff.endpos */
1356 /* ap_vrprintf_data passed as a apr_vformatter_buff_t, which is then
1357 * "downcast" to an ap_vrprintf_data */
1358 struct ap_vrprintf_data *vd = (struct ap_vrprintf_data*)buff;
1360 if (vd->r->connection->aborted)
1363 /* r_flush is called when vbuff is completely full */
1364 if (buffer_output(vd->r, vd->buff, AP_IOBUFSIZE)) {
1368 /* reset the buffer position */
1369 vd->vbuff.curpos = vd->buff;
1370 vd->vbuff.endpos = vd->buff + AP_IOBUFSIZE;
1375 AP_DECLARE(int) ap_vrprintf(request_rec *r, const char *fmt, va_list va)
1378 struct ap_vrprintf_data vd;
1379 char vrprintf_buf[AP_IOBUFSIZE];
1381 vd.vbuff.curpos = vrprintf_buf;
1382 vd.vbuff.endpos = vrprintf_buf + AP_IOBUFSIZE;
1384 vd.buff = vrprintf_buf;
1386 if (r->connection->aborted)
1389 written = apr_vformatter(r_flush, &vd.vbuff, fmt, va);
1390 /* tack on null terminator on remaining string */
1391 *(vd.vbuff.curpos) = '\0';
1393 if (written != -1) {
1394 int n = vd.vbuff.curpos - vrprintf_buf;
1396 /* last call to buffer_output, to finish clearing the buffer */
1397 if (buffer_output(r, vrprintf_buf,n) != APR_SUCCESS)
1406 AP_DECLARE_NONSTD(int) ap_rprintf(request_rec *r, const char *fmt, ...)
1411 if (r->connection->aborted)
1415 n = ap_vrprintf(r, fmt, va);
1421 AP_DECLARE_NONSTD(int) ap_rvputs(request_rec *r, ...)
1426 apr_size_t written = 0;
1428 if (r->connection->aborted)
1431 /* ### TODO: if the total output is large, put all the strings
1432 ### into a single brigade, rather than flushing each time we
1433 ### fill the buffer */
1436 s = va_arg(va, const char *);
1441 if (buffer_output(r, s, len) != APR_SUCCESS) {
1452 AP_DECLARE(int) ap_rflush(request_rec *r)
1454 apr_bucket_brigade *bb;
1457 bb = apr_brigade_create(r->pool);
1458 b = apr_bucket_flush_create();
1459 APR_BRIGADE_INSERT_TAIL(bb, b);
1460 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS)
1466 * This function sets the Last-Modified output header field to the value
1467 * of the mtime field in the request structure - rationalized to keep it from
1468 * being in the future.
1470 AP_DECLARE(void) ap_set_last_modified(request_rec *r)
1472 if (!r->assbackwards) {
1473 apr_time_t mod_time = ap_rationalize_mtime(r, r->mtime);
1474 char *datestr = apr_palloc(r->pool, APR_RFC822_DATE_LEN);
1475 apr_rfc822_date(datestr, mod_time);
1476 apr_table_setn(r->headers_out, "Last-Modified", datestr);
1480 AP_IMPLEMENT_HOOK_RUN_ALL(int,post_read_request,
1481 (request_rec *r),(r),OK,DECLINED)
1482 AP_IMPLEMENT_HOOK_RUN_ALL(int,log_transaction,
1483 (request_rec *r),(r),OK,DECLINED)
1484 AP_IMPLEMENT_HOOK_RUN_FIRST(const char *,http_method,
1485 (const request_rec *r),(r),NULL)
1486 AP_IMPLEMENT_HOOK_RUN_FIRST(unsigned short,default_port,
1487 (const request_rec *r),(r),0)