1 /* Copyright 2001-2004 The Apache Software Foundation
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
17 * http_protocol.c --- routines which directly communicate with the client.
19 * Code originally by Rob McCool; much redone by Robert S. Thau
20 * and the Apache Software Foundation.
24 #include "apr_strings.h"
25 #include "apr_buckets.h"
27 #include "apr_signal.h"
28 #include "apr_strmatch.h"
30 #define APR_WANT_STDIO /* for sscanf */
31 #define APR_WANT_STRFUNC
32 #define APR_WANT_MEMFUNC
36 #include "util_filter.h"
37 #include "ap_config.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
48 #include "util_charset.h"
49 #include "util_ebcdic.h"
50 #include "scoreboard.h"
61 APR_HOOK_LINK(post_read_request)
62 APR_HOOK_LINK(log_transaction)
63 APR_HOOK_LINK(http_method)
64 APR_HOOK_LINK(default_port)
67 AP_DECLARE_DATA ap_filter_rec_t *ap_old_write_func = NULL;
70 /* Patterns to match in ap_make_content_type() */
71 static const char *needcset[] = {
76 static const apr_strmatch_pattern **needcset_patterns;
77 static const apr_strmatch_pattern *charset_pattern;
79 AP_DECLARE(void) ap_setup_make_content_type(apr_pool_t *pool)
82 for (i = 0; needcset[i]; i++) {
85 needcset_patterns = (const apr_strmatch_pattern **)
86 apr_palloc(pool, (i + 1) * sizeof(apr_strmatch_pattern *));
87 for (i = 0; needcset[i]; i++) {
88 needcset_patterns[i] = apr_strmatch_precompile(pool, needcset[i], 0);
90 needcset_patterns[i] = NULL;
91 charset_pattern = apr_strmatch_precompile(pool, "charset=", 0);
95 * Builds the content-type that should be sent to the client from the
96 * content-type specified. The following rules are followed:
97 * - if type is NULL, type is set to ap_default_type(r)
98 * - if charset adding is disabled, stop processing and return type.
99 * - then, if there are no parameters on type, add the default charset
102 AP_DECLARE(const char *)ap_make_content_type(request_rec *r, const char *type)
104 const apr_strmatch_pattern **pcset;
105 core_dir_config *conf =
106 (core_dir_config *)ap_get_module_config(r->per_dir_config,
111 type = ap_default_type(r);
114 if (conf->add_default_charset != ADD_DEFAULT_CHARSET_ON) {
118 type_len = strlen(type);
120 if (apr_strmatch(charset_pattern, type, type_len) != NULL) {
121 /* already has parameter, do nothing */
122 /* XXX we don't check the validity */
126 /* see if it makes sense to add the charset. At present,
127 * we only add it if the Content-type is one of needcset[]
129 for (pcset = needcset_patterns; *pcset ; pcset++) {
130 if (apr_strmatch(*pcset, type, type_len) != NULL) {
131 struct iovec concat[3];
132 concat[0].iov_base = (void *)type;
133 concat[0].iov_len = type_len;
134 concat[1].iov_base = (void *)"; charset=";
135 concat[1].iov_len = sizeof("; charset=") - 1;
136 concat[2].iov_base = (void *)(conf->add_default_charset_name);
137 concat[2].iov_len = strlen(conf->add_default_charset_name);
138 type = apr_pstrcatv(r->pool, concat, 3, NULL);
147 AP_DECLARE(void) ap_set_content_length(request_rec *r, apr_off_t clength)
149 r->clength = clength;
150 apr_table_setn(r->headers_out, "Content-Length",
151 apr_off_t_toa(r->pool, clength));
155 * Return the latest rational time from a request/mtime (modification time)
156 * pair. We return the mtime unless it's in the future, in which case we
157 * return the current time. We use the request time as a reference in order
158 * to limit the number of calls to time(). We don't check for futurosity
159 * unless the mtime is at least as new as the reference.
161 AP_DECLARE(apr_time_t) ap_rationalize_mtime(request_rec *r, apr_time_t mtime)
165 /* For all static responses, it's almost certain that the file was
166 * last modified before the beginning of the request. So there's
167 * no reason to call time(NULL) again. But if the response has been
168 * created on demand, then it might be newer than the time the request
169 * started. In this event we really have to call time(NULL) again
170 * so that we can give the clients the most accurate Last-Modified. If we
171 * were given a time in the future, we return the current time - the
172 * Last-Modified can't be in the future.
174 now = (mtime < r->request_time) ? r->request_time : apr_time_now();
175 return (mtime > now) ? now : mtime;
178 /* Min # of bytes to allocate when reading a request line */
179 #define MIN_LINE_ALLOC 80
181 /* Get a line of protocol input, including any continuation lines
182 * caused by MIME folding (or broken clients) if fold != 0, and place it
183 * in the buffer s, of size n bytes, without the ending newline.
185 * If s is NULL, ap_rgetline_core will allocate necessary memory from r->pool.
187 * Returns APR_SUCCESS if there are no problems and sets *read to be
188 * the full length of s.
190 * APR_ENOSPC is returned if there is not enough buffer space.
191 * Other errors may be returned on other errors.
193 * The LF is *not* returned in the buffer. Therefore, a *read of 0
194 * indicates that an empty line was read.
196 * Notes: Because the buffer uses 1 char for NUL, the most we can return is
197 * (n - 1) actual characters.
199 * If no LF is detected on the last line due to a dropped connection
200 * or a full buffer, that's considered an error.
202 AP_DECLARE(apr_status_t) ap_rgetline_core(char **s, apr_size_t n,
203 apr_size_t *read, request_rec *r,
204 int fold, apr_bucket_brigade *bb)
208 apr_size_t bytes_handled = 0, current_alloc = 0;
209 char *pos, *last_char = *s;
210 int do_alloc = (*s == NULL), saw_eos = 0;
213 apr_brigade_cleanup(bb);
214 rv = ap_get_brigade(r->input_filters, bb, AP_MODE_GETLINE,
216 if (rv != APR_SUCCESS) {
220 /* Something horribly wrong happened. Someone didn't block! */
221 if (APR_BRIGADE_EMPTY(bb)) {
225 for (e = APR_BRIGADE_FIRST(bb);
226 e != APR_BRIGADE_SENTINEL(bb);
227 e = APR_BUCKET_NEXT(e))
232 /* If we see an EOS, don't bother doing anything more. */
233 if (APR_BUCKET_IS_EOS(e)) {
238 rv = apr_bucket_read(e, &str, &len, APR_BLOCK_READ);
239 if (rv != APR_SUCCESS) {
244 /* no use attempting a zero-byte alloc (hurts when
245 * using --with-efence --enable-pool-debug) or
246 * doing any of the other logic either
251 /* Would this overrun our buffer? If so, we'll die. */
252 if (n < bytes_handled + len) {
253 *read = bytes_handled;
255 /* ensure this string is terminated */
256 if (bytes_handled < n) {
257 (*s)[bytes_handled] = '\0';
266 /* Do we have to handle the allocation ourselves? */
268 /* We'll assume the common case where one bucket is enough. */
271 if (current_alloc < MIN_LINE_ALLOC) {
272 current_alloc = MIN_LINE_ALLOC;
274 *s = apr_palloc(r->pool, current_alloc);
276 else if (bytes_handled + len > current_alloc) {
277 /* Increase the buffer size */
278 apr_size_t new_size = current_alloc * 2;
281 if (bytes_handled + len > new_size) {
282 new_size = (bytes_handled + len) * 2;
285 new_buffer = apr_palloc(r->pool, new_size);
287 /* Copy what we already had. */
288 memcpy(new_buffer, *s, bytes_handled);
289 current_alloc = new_size;
294 /* Just copy the rest of the data to the end of the old buffer. */
295 pos = *s + bytes_handled;
296 memcpy(pos, str, len);
297 last_char = pos + len - 1;
299 /* We've now processed that new data - update accordingly. */
300 bytes_handled += len;
303 /* If we got a full line of input, stop reading */
304 if (last_char && (*last_char == APR_ASCII_LF)) {
309 /* We now go backwards over any CR (if present) or white spaces.
311 * Trim any extra trailing spaces or tabs except for the first
312 * space or tab at the beginning of a blank string. This makes
313 * it much easier to check field values for exact matches, and
314 * saves memory as well. Terminate string at end of line.
317 if (pos > *s && *(pos - 1) == APR_ASCII_CR) {
321 /* Trim any extra trailing spaces or tabs except for the first
322 * space or tab at the beginning of a blank string. This makes
323 * it much easier to check field values for exact matches, and
324 * saves memory as well.
326 while (pos > ((*s) + 1)
327 && (*(pos - 1) == APR_ASCII_BLANK || *(pos - 1) == APR_ASCII_TAB)) {
331 /* Since we want to remove the LF from the line, we'll go ahead
332 * and set this last character to be the term NULL and reset
333 * bytes_handled accordingly.
337 bytes_handled = pos - *s;
339 /* If we're folding, we have more work to do.
341 * Note that if an EOS was seen, we know we can't have another line.
343 if (fold && bytes_handled && !saw_eos) {
349 /* Clear the temp brigade for this filter read. */
350 apr_brigade_cleanup(bb);
352 /* We only care about the first byte. */
353 rv = ap_get_brigade(r->input_filters, bb, AP_MODE_SPECULATIVE,
355 if (rv != APR_SUCCESS) {
359 if (APR_BRIGADE_EMPTY(bb)) {
363 e = APR_BRIGADE_FIRST(bb);
365 /* If we see an EOS, don't bother doing anything more. */
366 if (APR_BUCKET_IS_EOS(e)) {
370 rv = apr_bucket_read(e, &str, &len, APR_BLOCK_READ);
371 if (rv != APR_SUCCESS) {
372 apr_brigade_cleanup(bb);
376 /* Found one, so call ourselves again to get the next line.
378 * FIXME: If the folding line is completely blank, should we
379 * stop folding? Does that require also looking at the next
382 /* When we call destroy, the buckets are deleted, so save that
383 * one character we need. This simplifies our execution paths
384 * at the cost of one character read.
387 if (c == APR_ASCII_BLANK || c == APR_ASCII_TAB) {
388 /* Do we have enough space? We may be full now. */
389 if (bytes_handled >= n) {
391 /* ensure this string is terminated */
396 apr_size_t next_size, next_len;
399 /* If we're doing the allocations for them, we have to
400 * give ourselves a NULL and copy it on return.
405 /* We're null terminated. */
409 next_size = n - bytes_handled;
411 rv = ap_rgetline_core(&tmp, next_size,
412 &next_len, r, 0, bb);
413 if (rv != APR_SUCCESS) {
417 if (do_alloc && next_len > 0) {
419 apr_size_t new_size = bytes_handled + next_len + 1;
421 /* we need to alloc an extra byte for a null */
422 new_buffer = apr_palloc(r->pool, new_size);
424 /* Copy what we already had. */
425 memcpy(new_buffer, *s, bytes_handled);
427 /* copy the new line, including the trailing null */
428 memcpy(new_buffer + bytes_handled, tmp, next_len + 1);
432 last_char += next_len;
433 bytes_handled += next_len;
436 else { /* next character is not tab or space */
442 *read = bytes_handled;
446 #if APR_CHARSET_EBCDIC
447 AP_DECLARE(apr_status_t) ap_rgetline(char **s, apr_size_t n,
448 apr_size_t *read, request_rec *r,
449 int fold, apr_bucket_brigade *bb)
451 /* on ASCII boxes, ap_rgetline is a macro which simply invokes
452 * ap_rgetline_core with the same parms
454 * on EBCDIC boxes, each complete http protocol input line needs to be
455 * translated into the code page used by the compiler. Since
456 * ap_rgetline_core uses recursion, we do the translation in a wrapper
457 * function to insure that each input character gets translated only once.
461 rv = ap_rgetline_core(s, n, read, r, fold, bb);
462 if (rv == APR_SUCCESS) {
463 ap_xlate_proto_from_ascii(*s, *read);
469 AP_DECLARE(int) ap_getline(char *s, int n, request_rec *r, int fold)
474 apr_bucket_brigade *tmp_bb;
476 tmp_bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
477 rv = ap_rgetline(&tmp_s, n, &len, r, fold, tmp_bb);
478 apr_brigade_destroy(tmp_bb);
480 /* Map the out-of-space condition to the old API. */
481 if (rv == APR_ENOSPC) {
485 /* Anything else is just bad. */
486 if (rv != APR_SUCCESS) {
493 /* parse_uri: break apart the uri
495 * - sets r->args to rest after '?' (or NULL if no '?')
496 * - sets r->uri to request uri (without r->args part)
497 * - sets r->hostname (if not set already) from request (scheme://host:port)
499 AP_CORE_DECLARE(void) ap_parse_uri(request_rec *r, const char *uri)
501 int status = HTTP_OK;
503 r->unparsed_uri = apr_pstrdup(r->pool, uri);
505 if (r->method_number == M_CONNECT) {
506 status = apr_uri_parse_hostinfo(r->pool, uri, &r->parsed_uri);
509 /* Simple syntax Errors in URLs are trapped by
510 * parse_uri_components().
512 status = apr_uri_parse(r->pool, uri, &r->parsed_uri);
515 if (status == APR_SUCCESS) {
516 /* if it has a scheme we may need to do absoluteURI vhost stuff */
517 if (r->parsed_uri.scheme
518 && !strcasecmp(r->parsed_uri.scheme, ap_http_method(r))) {
519 r->hostname = r->parsed_uri.hostname;
521 else if (r->method_number == M_CONNECT) {
522 r->hostname = r->parsed_uri.hostname;
525 r->args = r->parsed_uri.query;
526 r->uri = r->parsed_uri.path ? r->parsed_uri.path
527 : apr_pstrdup(r->pool, "/");
529 #if defined(OS2) || defined(WIN32)
530 /* Handle path translations for OS/2 and plug security hole.
531 * This will prevent "http://www.wherever.com/..\..\/" from
532 * returning a directory for the root drive.
537 for (x = r->uri; (x = strchr(x, '\\')) != NULL; )
540 #endif /* OS2 || WIN32 */
545 r->status = HTTP_BAD_REQUEST; /* set error status */
546 r->uri = apr_pstrdup(r->pool, uri);
550 static int read_request_line(request_rec *r, apr_bucket_brigade *bb)
557 conn_rec *conn = r->connection;
559 int major = 1, minor = 0; /* Assume HTTP/1.0 if non-"HTTP" protocol */
562 int num_blank_lines = 0;
563 int max_blank_lines = r->server->limit_req_fields;
565 if (max_blank_lines <= 0) {
566 max_blank_lines = DEFAULT_LIMIT_REQUEST_FIELDS;
569 /* Read past empty lines until we get a real request line,
570 * a read error, the connection closes (EOF), or we timeout.
572 * We skip empty lines because browsers have to tack a CRLF on to the end
573 * of POSTs to support old CERN webservers. But note that we may not
574 * have flushed any previous response completely to the client yet.
575 * We delay the flush as long as possible so that we can improve
576 * performance for clients that are pipelining requests. If a request
577 * is pipelined then we won't block during the (implicit) read() below.
578 * If the requests aren't pipelined, then the client is still waiting
579 * for the final buffer flush from us, and we will block in the implicit
580 * read(). B_SAFEREAD ensures that the BUFF layer flushes if it will
581 * have to block during a read.
587 /* insure ap_rgetline allocates memory each time thru the loop
588 * if there are empty lines
590 r->the_request = NULL;
591 rv = ap_rgetline(&(r->the_request), (apr_size_t)(r->server->limit_req_line + 2),
594 if (rv != APR_SUCCESS) {
595 r->request_time = apr_time_now();
597 /* ap_rgetline returns APR_ENOSPC if it fills up the
598 * buffer before finding the end-of-line. This is only going to
599 * happen if it exceeds the configured limit for a request-line.
601 if (rv == APR_ENOSPC) {
602 r->status = HTTP_REQUEST_URI_TOO_LARGE;
603 r->proto_num = HTTP_VERSION(1,0);
604 r->protocol = apr_pstrdup(r->pool, "HTTP/1.0");
609 } while ((len <= 0) && (++num_blank_lines < max_blank_lines));
611 /* we've probably got something to do, ignore graceful restart requests */
613 r->request_time = apr_time_now();
615 r->method = ap_getword_white(r->pool, &ll);
618 /* XXX If we want to keep track of the Method, the protocol module should do
619 * it. That support isn't in the scoreboard yet. Hopefully next week
621 ap_update_connection_status(AP_CHILD_THREAD_FROM_ID(conn->id), "Method",
625 uri = ap_getword_white(r->pool, &ll);
627 /* Provide quick information about the request method as soon as known */
629 r->method_number = ap_method_number_of(r->method);
630 if (r->method_number == M_GET && r->method[0] == 'H') {
634 ap_parse_uri(r, uri);
645 r->protocol = apr_pstrmemdup(r->pool, pro, len);
647 /* XXX ap_update_connection_status(conn->id, "Protocol", r->protocol); */
649 /* Avoid sscanf in the common case */
651 && pro[0] == 'H' && pro[1] == 'T' && pro[2] == 'T' && pro[3] == 'P'
652 && pro[4] == '/' && apr_isdigit(pro[5]) && pro[6] == '.'
653 && apr_isdigit(pro[7])) {
654 r->proto_num = HTTP_VERSION(pro[5] - '0', pro[7] - '0');
656 else if (3 == sscanf(r->protocol, "%4s/%u.%u", http, &major, &minor)
657 && (strcasecmp("http", http) == 0)
658 && (minor < HTTP_VERSION(1, 0)) ) /* don't allow HTTP/0.1000 */
659 r->proto_num = HTTP_VERSION(major, minor);
661 r->proto_num = HTTP_VERSION(1, 0);
666 AP_DECLARE(void) ap_get_mime_headers_core(request_rec *r, apr_bucket_brigade *bb)
668 char *last_field = NULL;
669 apr_size_t last_len = 0;
670 apr_size_t alloc_len = 0;
678 * Read header lines until we get the empty separator line, a read error,
679 * the connection closes (EOF), reach the server limit, or we timeout.
686 rv = ap_rgetline(&field, r->server->limit_req_fieldsize + 2,
689 if (rv != APR_SUCCESS) {
690 r->status = HTTP_BAD_REQUEST;
692 /* ap_rgetline returns APR_ENOSPC if it fills up the buffer before
693 * finding the end-of-line. This is only going to happen if it
694 * exceeds the configured limit for a field size.
696 if (rv == APR_ENOSPC && field) {
697 /* insure ap_escape_html will terminate correctly */
698 field[len - 1] = '\0';
699 apr_table_setn(r->notes, "error-notes",
701 "Size of a request header field "
702 "exceeds server limit.<br />\n"
704 ap_escape_html(r->pool, field),
710 if (last_field != NULL) {
711 if ((len > 0) && ((*field == '\t') || *field == ' ')) {
712 /* This line is a continuation of the preceding line(s),
713 * so append it to the line that we've set aside.
714 * Note: this uses a power-of-two allocator to avoid
715 * doing O(n) allocs and using O(n^2) space for
716 * continuations that span many many lines.
718 apr_size_t fold_len = last_len + len + 1; /* trailing null */
719 if (fold_len > alloc_len) {
721 alloc_len += alloc_len;
722 if (fold_len > alloc_len) {
723 alloc_len = fold_len;
725 fold_buf = (char *)apr_palloc(r->pool, alloc_len);
726 memcpy(fold_buf, last_field, last_len);
727 last_field = fold_buf;
729 memcpy(last_field + last_len, field, len +1); /* +1 for nul */
735 if (r->server->limit_req_fields
736 && (++fields_read > r->server->limit_req_fields)) {
737 r->status = HTTP_BAD_REQUEST;
738 apr_table_setn(r->notes, "error-notes",
739 "The number of request header fields "
740 "exceeds this server's limit.");
744 if (!(value = strchr(last_field, ':'))) { /* Find ':' or */
745 r->status = HTTP_BAD_REQUEST; /* abort bad request */
746 apr_table_setn(r->notes, "error-notes",
748 "Request header field is "
749 "missing ':' separator.<br />\n"
751 ap_escape_html(r->pool,
758 tmp_field = value; /* used to trim the whitespace between key
759 * token and separator
762 while (*value == ' ' || *value == '\t') {
763 ++value; /* Skip to start of value */
766 /* This check is to avoid any invalid memory reference while
767 * traversing backwards in the key. To avoid a case where
768 * the header starts with ':' (or with just some white
769 * space and the ':') followed by the value
771 if (tmp_field > last_field) {
773 while ((tmp_field > last_field) &&
774 (*tmp_field == ' ' || *tmp_field == '\t')) {
775 --tmp_field; /* Removing LWS between key and ':' */
781 apr_table_addn(r->headers_in, last_field, value);
783 /* reset the alloc_len so that we'll allocate a new
784 * buffer if we have to do any more folding: we can't
785 * use the previous buffer because its contents are
786 * now part of r->headers_in
790 } /* end if current line is not a continuation starting with tab */
793 /* Found a blank line, stop. */
798 /* Keep track of this line so that we can parse it on
799 * the next loop iteration. (In the folded case, last_field
800 * has been updated already.)
808 apr_table_compress(r->headers_in, APR_OVERLAP_TABLES_MERGE);
811 AP_DECLARE(void) ap_get_mime_headers(request_rec *r)
813 apr_bucket_brigade *tmp_bb;
814 tmp_bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
815 ap_get_mime_headers_core(r, tmp_bb);
816 apr_brigade_destroy(tmp_bb);
819 request_rec *ap_read_request(conn_rec *conn)
825 apr_bucket_brigade *tmp_bb;
827 apr_pool_create(&p, conn->pool);
828 apr_pool_tag(p, "request");
829 r = apr_pcalloc(p, sizeof(request_rec));
831 r->connection = conn;
832 r->server = conn->base_server;
835 r->ap_auth_type = NULL;
837 r->allowed_methods = ap_make_method_list(p, 2);
839 r->headers_in = apr_table_make(r->pool, 25);
840 r->subprocess_env = apr_table_make(r->pool, 25);
841 r->headers_out = apr_table_make(r->pool, 12);
842 r->err_headers_out = apr_table_make(r->pool, 5);
843 r->notes = apr_table_make(r->pool, 5);
845 r->request_config = ap_create_request_config(r->pool);
846 /* Must be set before we run create request hook */
848 r->proto_output_filters = conn->output_filters;
849 r->output_filters = r->proto_output_filters;
850 r->proto_input_filters = conn->input_filters;
851 r->input_filters = r->proto_input_filters;
852 ap_run_create_request(r);
853 r->per_dir_config = r->server->lookup_defaults;
855 r->sent_bodyct = 0; /* bytect isn't for body */
858 r->read_body = REQUEST_NO_BODY;
860 r->status = HTTP_REQUEST_TIME_OUT; /* Until we get a request */
861 r->the_request = NULL;
863 tmp_bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
865 /* Get the request... */
866 if (!read_request_line(r, tmp_bb)) {
867 if (r->status == HTTP_REQUEST_URI_TOO_LARGE) {
868 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
869 "request failed: URI too long (longer than %d)", r->server->limit_req_line);
870 ap_send_error_response(r, 0);
871 ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
872 ap_run_log_transaction(r);
873 apr_brigade_destroy(tmp_bb);
877 apr_brigade_destroy(tmp_bb);
881 if (!r->assbackwards) {
882 ap_get_mime_headers_core(r, tmp_bb);
883 if (r->status != HTTP_REQUEST_TIME_OUT) {
884 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
885 "request failed: error reading the headers");
886 ap_send_error_response(r, 0);
887 ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
888 ap_run_log_transaction(r);
889 apr_brigade_destroy(tmp_bb);
894 if (r->header_only) {
896 * Client asked for headers only with HTTP/0.9, which doesn't send
897 * headers! Have to dink things just to make sure the error message
900 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
901 "client sent invalid HTTP/0.9 request: HEAD %s",
904 r->status = HTTP_BAD_REQUEST;
905 ap_send_error_response(r, 0);
906 ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
907 ap_run_log_transaction(r);
908 apr_brigade_destroy(tmp_bb);
913 apr_brigade_destroy(tmp_bb);
915 r->status = HTTP_OK; /* Until further notice. */
917 /* update what we think the virtual host is based on the headers we've
918 * now read. may update status.
920 ap_update_vhost_from_headers(r);
922 /* we may have switched to another server */
923 r->per_dir_config = r->server->lookup_defaults;
925 if ((!r->hostname && (r->proto_num >= HTTP_VERSION(1, 1)))
926 || ((r->proto_num == HTTP_VERSION(1, 1))
927 && !apr_table_get(r->headers_in, "Host"))) {
929 * Client sent us an HTTP/1.1 or later request without telling us the
930 * hostname, either with a full URL or a Host: header. We therefore
931 * need to (as per the 1.1 spec) send an error. As a special case,
932 * HTTP/1.1 mentions twice (S9, S14.23) that a request MUST contain
933 * a Host: header, and the server MUST respond with 400 if it doesn't.
935 r->status = HTTP_BAD_REQUEST;
936 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
937 "client sent HTTP/1.1 request without hostname "
938 "(see RFC2616 section 14.23): %s", r->uri);
941 if (r->status != HTTP_OK) {
942 ap_send_error_response(r, 0);
943 ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
944 ap_run_log_transaction(r);
948 if ((access_status = ap_run_post_read_request(r))) {
949 ap_die(access_status, r);
950 ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
951 ap_run_log_transaction(r);
955 if (((expect = apr_table_get(r->headers_in, "Expect")) != NULL)
956 && (expect[0] != '\0')) {
958 * The Expect header field was added to HTTP/1.1 after RFC 2068
959 * as a means to signal when a 100 response is desired and,
960 * unfortunately, to signal a poor man's mandatory extension that
961 * the server must understand or return 417 Expectation Failed.
963 if (strcasecmp(expect, "100-continue") == 0) {
964 r->expecting_100 = 1;
967 r->status = HTTP_EXPECTATION_FAILED;
968 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
969 "client sent an unrecognized expectation value of "
970 "Expect: %s", expect);
971 ap_send_error_response(r, 0);
972 ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
973 ap_run_log_transaction(r);
978 ap_add_input_filter_handle(ap_http_input_filter_handle,
979 NULL, r, r->connection);
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 AP_DECLARE(void) ap_set_sub_req_protocol(request_rec *rnew,
992 const request_rec *r)
994 rnew->the_request = r->the_request; /* Keep original request-line */
996 rnew->assbackwards = 1; /* Don't send headers from this. */
997 rnew->no_local_copy = 1; /* Don't try to send HTTP_NOT_MODIFIED for a
999 rnew->method = "GET";
1000 rnew->method_number = M_GET;
1001 rnew->protocol = "INCLUDED";
1003 rnew->status = HTTP_OK;
1005 rnew->headers_in = r->headers_in;
1006 rnew->subprocess_env = apr_table_copy(rnew->pool, r->subprocess_env);
1007 rnew->headers_out = apr_table_make(rnew->pool, 5);
1008 rnew->err_headers_out = apr_table_make(rnew->pool, 5);
1009 rnew->notes = apr_table_make(rnew->pool, 5);
1011 rnew->expecting_100 = r->expecting_100;
1012 rnew->read_length = r->read_length;
1013 rnew->read_body = REQUEST_NO_BODY;
1015 rnew->main = (request_rec *) r;
1018 static void end_output_stream(request_rec *r)
1020 conn_rec *c = r->connection;
1021 apr_bucket_brigade *bb;
1024 bb = apr_brigade_create(r->pool, c->bucket_alloc);
1025 b = apr_bucket_eos_create(c->bucket_alloc);
1026 APR_BRIGADE_INSERT_TAIL(bb, b);
1027 ap_pass_brigade(r->output_filters, bb);
1030 AP_DECLARE(void) ap_finalize_sub_req_protocol(request_rec *sub)
1032 /* tell the filter chain there is no more content coming */
1033 if (!sub->eos_sent) {
1034 end_output_stream(sub);
1038 /* finalize_request_protocol is called at completion of sending the
1039 * response. Its sole purpose is to send the terminating protocol
1040 * information for any wrappers around the response message body
1041 * (i.e., transfer encodings). It should have been named finalize_response.
1043 AP_DECLARE(void) ap_finalize_request_protocol(request_rec *r)
1045 (void) ap_discard_request_body(r);
1047 /* tell the filter chain there is no more content coming */
1049 end_output_stream(r);
1054 * Support for the Basic authentication protocol, and a bit for Digest.
1056 AP_DECLARE(void) ap_note_auth_failure(request_rec *r)
1058 const char *type = ap_auth_type(r);
1060 if (!strcasecmp(type, "Basic"))
1061 ap_note_basic_auth_failure(r);
1062 else if (!strcasecmp(type, "Digest"))
1063 ap_note_digest_auth_failure(r);
1066 ap_log_rerror(APLOG_MARK, APLOG_ERR,
1067 0, r, "need AuthType to note auth failure: %s", r->uri);
1071 AP_DECLARE(void) ap_note_basic_auth_failure(request_rec *r)
1073 const char *type = ap_auth_type(r);
1075 /* if there is no AuthType configure or it is something other than
1076 * Basic, let ap_note_auth_failure() deal with it
1078 if (!type || strcasecmp(type, "Basic"))
1079 ap_note_auth_failure(r);
1081 apr_table_setn(r->err_headers_out,
1082 (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authenticate"
1083 : "WWW-Authenticate",
1084 apr_pstrcat(r->pool, "Basic realm=\"", ap_auth_name(r),
1088 AP_DECLARE(void) ap_note_digest_auth_failure(request_rec *r)
1090 apr_table_setn(r->err_headers_out,
1091 (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authenticate"
1092 : "WWW-Authenticate",
1093 apr_psprintf(r->pool, "Digest realm=\"%s\", nonce=\""
1094 "%" APR_UINT64_T_HEX_FMT "\"",
1095 ap_auth_name(r), (apr_uint64_t)r->request_time));
1098 AP_DECLARE(int) ap_get_basic_auth_pw(request_rec *r, const char **pw)
1100 const char *auth_line = apr_table_get(r->headers_in,
1101 (PROXYREQ_PROXY == r->proxyreq)
1102 ? "Proxy-Authorization"
1106 if (!(t = ap_auth_type(r)) || strcasecmp(t, "Basic"))
1109 if (!ap_auth_name(r)) {
1110 ap_log_rerror(APLOG_MARK, APLOG_ERR,
1111 0, r, "need AuthName: %s", r->uri);
1112 return HTTP_INTERNAL_SERVER_ERROR;
1116 ap_note_basic_auth_failure(r);
1117 return HTTP_UNAUTHORIZED;
1120 if (strcasecmp(ap_getword(r->pool, &auth_line, ' '), "Basic")) {
1121 /* Client tried to authenticate using wrong auth scheme */
1122 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1123 "client used wrong authentication scheme: %s", r->uri);
1124 ap_note_basic_auth_failure(r);
1125 return HTTP_UNAUTHORIZED;
1128 while (*auth_line == ' ' || *auth_line == '\t') {
1132 t = ap_pbase64decode(r->pool, auth_line);
1133 r->user = ap_getword_nulls (r->pool, &t, ':');
1134 r->ap_auth_type = "Basic";
1141 struct content_length_ctx {
1142 int data_sent; /* true if the C-L filter has already sent at
1143 * least one bucket on to the next output filter
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(
1154 apr_bucket_brigade *b)
1156 request_rec *r = f->r;
1157 struct content_length_ctx *ctx;
1160 apr_read_type_e eblock = APR_NONBLOCK_READ;
1164 f->ctx = ctx = apr_palloc(r->pool, sizeof(*ctx));
1168 /* Loop through this set of buckets to compute their length
1170 e = APR_BRIGADE_FIRST(b);
1171 while (e != APR_BRIGADE_SENTINEL(b)) {
1172 if (APR_BUCKET_IS_EOS(e)) {
1176 if (e->length == (apr_size_t)-1) {
1178 const char *ignored;
1181 /* This is probably a pipe bucket. Send everything
1182 * prior to this, and then read the data for this bucket.
1184 rv = apr_bucket_read(e, &ignored, &len, eblock);
1185 if (rv == APR_SUCCESS) {
1186 /* Attempt a nonblocking read next time through */
1187 eblock = APR_NONBLOCK_READ;
1188 r->bytes_sent += len;
1190 else if (APR_STATUS_IS_EAGAIN(rv)) {
1191 /* Output everything prior to this bucket, and then
1192 * do a blocking read on the next batch.
1194 if (e != APR_BRIGADE_FIRST(b)) {
1195 apr_bucket_brigade *split = apr_brigade_split(b, e);
1196 apr_bucket *flush = apr_bucket_flush_create(r->connection->bucket_alloc);
1198 APR_BRIGADE_INSERT_TAIL(b, flush);
1199 rv = ap_pass_brigade(f->next, b);
1200 if (rv != APR_SUCCESS || f->c->aborted) {
1201 apr_brigade_destroy(split);
1205 e = APR_BRIGADE_FIRST(b);
1209 eblock = APR_BLOCK_READ;
1213 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
1214 "ap_content_length_filter: "
1215 "apr_bucket_read() failed");
1220 r->bytes_sent += e->length;
1222 e = APR_BUCKET_NEXT(e);
1225 /* If we've now seen the entire response and it's otherwise
1226 * okay to set the C-L in the response header, then do so now.
1228 * We can only set a C-L in the response header if we haven't already
1229 * sent any buckets on to the next output filter for this request.
1231 if (ctx->data_sent == 0 && eos) {
1232 ap_set_content_length(r, r->bytes_sent);
1236 return ap_pass_brigade(f->next, b);
1240 * Send the body of a response to the client.
1242 AP_DECLARE(apr_status_t) ap_send_fd(apr_file_t *fd, request_rec *r,
1243 apr_off_t offset, apr_size_t len,
1246 conn_rec *c = r->connection;
1247 apr_bucket_brigade *bb = NULL;
1251 bb = apr_brigade_create(r->pool, c->bucket_alloc);
1252 b = apr_bucket_file_create(fd, offset, len, r->pool, c->bucket_alloc);
1253 APR_BRIGADE_INSERT_TAIL(bb, b);
1255 rv = ap_pass_brigade(r->output_filters, bb);
1256 if (rv != APR_SUCCESS) {
1257 *nbytes = 0; /* no way to tell how many were actually sent */
1267 /* send data from an in-memory buffer */
1268 AP_DECLARE(size_t) ap_send_mmap(apr_mmap_t *mm, request_rec *r, size_t offset,
1271 conn_rec *c = r->connection;
1272 apr_bucket_brigade *bb = NULL;
1275 bb = apr_brigade_create(r->pool, c->bucket_alloc);
1276 b = apr_bucket_mmap_create(mm, offset, length, c->bucket_alloc);
1277 APR_BRIGADE_INSERT_TAIL(bb, b);
1278 ap_pass_brigade(r->output_filters, bb);
1280 return mm->size; /* XXX - change API to report apr_status_t? */
1282 #endif /* APR_HAS_MMAP */
1285 apr_bucket_brigade *bb;
1286 } old_write_filter_ctx;
1288 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_old_write_filter(
1289 ap_filter_t *f, apr_bucket_brigade *bb)
1291 old_write_filter_ctx *ctx = f->ctx;
1293 AP_DEBUG_ASSERT(ctx);
1296 /* whatever is coming down the pipe (we don't care), we
1297 * can simply insert our buffered data at the front and
1298 * pass the whole bundle down the chain.
1300 APR_BRIGADE_CONCAT(ctx->bb, bb);
1305 return ap_pass_brigade(f->next, bb);
1308 static apr_status_t buffer_output(request_rec *r,
1309 const char *str, apr_size_t len)
1311 conn_rec *c = r->connection;
1313 old_write_filter_ctx *ctx;
1318 /* future optimization: record some flags in the request_rec to
1319 * say whether we've added our filter, and whether it is first.
1322 /* this will typically exit on the first test */
1323 for (f = r->output_filters; f != NULL; f = f->next) {
1324 if (ap_old_write_func == f->frec)
1329 /* our filter hasn't been added yet */
1330 ctx = apr_pcalloc(r->pool, sizeof(*ctx));
1331 ap_add_output_filter("OLD_WRITE", ctx, r, r->connection);
1332 f = r->output_filters;
1335 /* if the first filter is not our buffering filter, then we have to
1336 * deliver the content through the normal filter chain
1338 if (f != r->output_filters) {
1339 apr_bucket_brigade *bb = apr_brigade_create(r->pool, c->bucket_alloc);
1340 apr_bucket *b = apr_bucket_transient_create(str, len, c->bucket_alloc);
1341 APR_BRIGADE_INSERT_TAIL(bb, b);
1343 return ap_pass_brigade(r->output_filters, bb);
1346 /* grab the context from our filter */
1347 ctx = r->output_filters->ctx;
1349 if (ctx->bb == NULL) {
1350 ctx->bb = apr_brigade_create(r->pool, c->bucket_alloc);
1353 return ap_fwrite(f->next, ctx->bb, str, len);
1356 AP_DECLARE(int) ap_rputc(int c, request_rec *r)
1360 if (r->connection->aborted) {
1364 if (buffer_output(r, &c2, 1) != APR_SUCCESS)
1370 AP_DECLARE(int) ap_rputs(const char *str, request_rec *r)
1374 if (r->connection->aborted)
1377 if (buffer_output(r, str, len = strlen(str)) != APR_SUCCESS)
1383 AP_DECLARE(int) ap_rwrite(const void *buf, int nbyte, request_rec *r)
1385 if (r->connection->aborted)
1388 if (buffer_output(r, buf, nbyte) != APR_SUCCESS)
1394 struct ap_vrprintf_data {
1395 apr_vformatter_buff_t vbuff;
1400 static apr_status_t r_flush(apr_vformatter_buff_t *buff)
1402 /* callback function passed to ap_vformatter to be called when
1403 * vformatter needs to write into buff and buff.curpos > buff.endpos */
1405 /* ap_vrprintf_data passed as a apr_vformatter_buff_t, which is then
1406 * "downcast" to an ap_vrprintf_data */
1407 struct ap_vrprintf_data *vd = (struct ap_vrprintf_data*)buff;
1409 if (vd->r->connection->aborted)
1412 /* r_flush is called when vbuff is completely full */
1413 if (buffer_output(vd->r, vd->buff, AP_IOBUFSIZE)) {
1417 /* reset the buffer position */
1418 vd->vbuff.curpos = vd->buff;
1419 vd->vbuff.endpos = vd->buff + AP_IOBUFSIZE;
1424 AP_DECLARE(int) ap_vrprintf(request_rec *r, const char *fmt, va_list va)
1427 struct ap_vrprintf_data vd;
1428 char vrprintf_buf[AP_IOBUFSIZE];
1430 vd.vbuff.curpos = vrprintf_buf;
1431 vd.vbuff.endpos = vrprintf_buf + AP_IOBUFSIZE;
1433 vd.buff = vrprintf_buf;
1435 if (r->connection->aborted)
1438 written = apr_vformatter(r_flush, &vd.vbuff, fmt, va);
1440 /* tack on null terminator on remaining string */
1441 *(vd.vbuff.curpos) = '\0';
1443 if (written != -1) {
1444 int n = vd.vbuff.curpos - vrprintf_buf;
1446 /* last call to buffer_output, to finish clearing the buffer */
1447 if (buffer_output(r, vrprintf_buf,n) != APR_SUCCESS)
1456 AP_DECLARE_NONSTD(int) ap_rprintf(request_rec *r, const char *fmt, ...)
1461 if (r->connection->aborted)
1465 n = ap_vrprintf(r, fmt, va);
1471 AP_DECLARE_NONSTD(int) ap_rvputs(request_rec *r, ...)
1476 apr_size_t written = 0;
1478 if (r->connection->aborted)
1481 /* ### TODO: if the total output is large, put all the strings
1482 * ### into a single brigade, rather than flushing each time we
1483 * ### fill the buffer
1487 s = va_arg(va, const char *);
1492 if (buffer_output(r, s, len) != APR_SUCCESS) {
1503 AP_DECLARE(int) ap_rflush(request_rec *r)
1505 conn_rec *c = r->connection;
1506 apr_bucket_brigade *bb;
1509 bb = apr_brigade_create(r->pool, c->bucket_alloc);
1510 b = apr_bucket_flush_create(c->bucket_alloc);
1511 APR_BRIGADE_INSERT_TAIL(bb, b);
1512 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS)
1519 * This function sets the Last-Modified output header field to the value
1520 * of the mtime field in the request structure - rationalized to keep it from
1521 * being in the future.
1523 AP_DECLARE(void) ap_set_last_modified(request_rec *r)
1525 if (!r->assbackwards) {
1526 apr_time_t mod_time = ap_rationalize_mtime(r, r->mtime);
1527 char *datestr = apr_palloc(r->pool, APR_RFC822_DATE_LEN);
1529 apr_rfc822_date(datestr, mod_time);
1530 apr_table_setn(r->headers_out, "Last-Modified", datestr);
1534 AP_IMPLEMENT_HOOK_RUN_ALL(int,post_read_request,
1535 (request_rec *r), (r), OK, DECLINED)
1536 AP_IMPLEMENT_HOOK_RUN_ALL(int,log_transaction,
1537 (request_rec *r), (r), OK, DECLINED)
1538 AP_IMPLEMENT_HOOK_RUN_FIRST(const char *,http_method,
1539 (const request_rec *r), (r), NULL)
1540 AP_IMPLEMENT_HOOK_RUN_FIRST(unsigned short,default_port,
1541 (const request_rec *r), (r), 0)