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;
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.
191 * the length of s (normal case),
195 * Notes: Because the buffer uses 1 char for NUL, the most we can return is
196 * (n - 1) actual characters.
198 * If no LF is detected on the last line due to a dropped connection
199 * or a full buffer, that's considered an error.
201 AP_DECLARE(int) ap_rgetline(char **s, int n, request_rec *r, int fold)
208 int looking_ahead = 0;
210 core_request_config *req_cfg;
211 apr_bucket_brigade *b;
214 req_cfg = (core_request_config *)
215 ap_get_module_config(r->request_config, &core_module);
217 /* make sure it's empty unless we're folding */
218 AP_DEBUG_ASSERT(fold || APR_BRIGADE_EMPTY(b));
221 if (APR_BRIGADE_EMPTY(b)) {
223 if ((retval = ap_get_brigade(r->input_filters, b,
225 &zero /* readline */)) != APR_SUCCESS ||
226 APR_BRIGADE_EMPTY(b)) {
227 apr_brigade_destroy(b);
231 e = APR_BRIGADE_FIRST(b);
232 if (APR_BUCKET_IS_EOS(e)) {
233 apr_brigade_destroy(b);
236 if (e->length == 0) {
237 apr_bucket_delete(e);
240 retval = apr_bucket_read(e, &temp, &length, APR_BLOCK_READ);
241 if (retval != APR_SUCCESS) {
242 apr_brigade_destroy(b);
243 ap_log_rerror(APLOG_MARK, APLOG_ERR, retval, r, "apr_bucket_read() failed");
245 break; /* report previously-read data to caller, do ap_xlate_proto_to_ascii() */
252 if ((looking_ahead) && (*temp != APR_ASCII_BLANK) && (*temp != APR_ASCII_TAB)) {
253 /* can't fold because next line isn't indented,
254 * so return what we have. lookahead brigade is
255 * stashed on req_cfg->bb
257 AP_DEBUG_ASSERT(!APR_BRIGADE_EMPTY(req_cfg->bb));
260 if (total + length - 1 < n) {
262 *s = apr_palloc(r->pool, length + 2); /* +2 for LF, null */
265 last_char = pos + length - 1;
266 memcpy(pos, temp, length);
267 apr_bucket_delete(e);
270 /* input line was larger than the caller's buffer */
271 apr_brigade_destroy(b);
273 /* don't need to worry about req_cfg->bb being bogus.
274 * the request is about to die, and ErrorDocument
275 * redirects get a new req_cfg->bb
281 pos = last_char; /* Point at the last character */
283 if (*pos == APR_ASCII_LF) { /* Did we get a full line of input? */
285 if (pos > *s && *(pos - 1) == APR_ASCII_CR) {
286 --pos; /* zap optional CR before LF */
290 * Trim any extra trailing spaces or tabs except for the first
291 * space or tab at the beginning of a blank string. This makes
292 * it much easier to check field values for exact matches, and
293 * saves memory as well. Terminate string at end of line.
295 while (pos > ((*s) + 1) &&
296 (*(pos - 1) == APR_ASCII_BLANK || *(pos - 1) == APR_ASCII_TAB)) {
297 --pos; /* trim extra trailing spaces or tabs */
299 *pos = '\0'; /* zap end of string */
300 total = pos - *s; /* update total string length */
302 /* look ahead another line if line folding is desired
303 * and this line isn't empty
309 AP_DEBUG_ASSERT(APR_BRIGADE_EMPTY(req_cfg->bb));
314 /* no LF yet...character mode client (telnet)...keep going
315 * bump past last character read,
316 * and set total in case we bail before finding a LF
319 looking_ahead = 0; /* only appropriate right after LF */
322 ap_xlate_proto_from_ascii(*s, total);
326 AP_DECLARE(int) ap_getline(char *s, int n, request_rec *r, int fold)
329 return ap_rgetline(&tmp_s, n, r, fold);
332 /* parse_uri: break apart the uri
334 * - sets r->args to rest after '?' (or NULL if no '?')
335 * - sets r->uri to request uri (without r->args part)
336 * - sets r->hostname (if not set already) from request (scheme://host:port)
338 AP_CORE_DECLARE(void) ap_parse_uri(request_rec *r, const char *uri)
340 int status = HTTP_OK;
342 r->unparsed_uri = apr_pstrdup(r->pool, uri);
344 if (r->method_number == M_CONNECT) {
345 status = apr_uri_parse_hostinfo(r->pool, uri, &r->parsed_uri);
348 /* Simple syntax Errors in URLs are trapped by parse_uri_components(). */
349 status = apr_uri_parse(r->pool, uri, &r->parsed_uri);
352 if (status == APR_SUCCESS) {
353 /* if it has a scheme we may need to do absoluteURI vhost stuff */
354 if (r->parsed_uri.scheme
355 && !strcasecmp(r->parsed_uri.scheme, ap_http_method(r))) {
356 r->hostname = r->parsed_uri.hostname;
358 else if (r->method_number == M_CONNECT) {
359 r->hostname = r->parsed_uri.hostname;
361 r->args = r->parsed_uri.query;
362 r->uri = r->parsed_uri.path ? r->parsed_uri.path
363 : apr_pstrdup(r->pool, "/");
364 #if defined(OS2) || defined(WIN32)
365 /* Handle path translations for OS/2 and plug security hole.
366 * This will prevent "http://www.wherever.com/..\..\/" from
367 * returning a directory for the root drive.
372 for (x = r->uri; (x = strchr(x, '\\')) != NULL; )
375 #endif /* OS2 || WIN32 */
380 r->status = HTTP_BAD_REQUEST; /* set error status */
381 r->uri = apr_pstrdup(r->pool, uri);
385 static int read_request_line(request_rec *r)
392 conn_rec *conn = r->connection;
394 int major = 1, minor = 0; /* Assume HTTP/1.0 if non-"HTTP" protocol */
397 /* Read past empty lines until we get a real request line,
398 * a read error, the connection closes (EOF), or we timeout.
400 * We skip empty lines because browsers have to tack a CRLF on to the end
401 * of POSTs to support old CERN webservers. But note that we may not
402 * have flushed any previous response completely to the client yet.
403 * We delay the flush as long as possible so that we can improve
404 * performance for clients that are pipelining requests. If a request
405 * is pipelined then we won't block during the (implicit) read() below.
406 * If the requests aren't pipelined, then the client is still waiting
407 * for the final buffer flush from us, and we will block in the implicit
408 * read(). B_SAFEREAD ensures that the BUFF layer flushes if it will
409 * have to block during a read.
412 while ((len = ap_rgetline(&(r->the_request),
413 DEFAULT_LIMIT_REQUEST_LINE + 2, r, 0)) <= 0) {
414 if (len < 0) { /* includes EOF */
415 /* this is a hack to make sure that request time is set,
416 * it's not perfect, but it's better than nothing
418 r->request_time = apr_time_now();
422 /* we've probably got something to do, ignore graceful restart requests */
424 r->request_time = apr_time_now();
426 r->method = ap_getword_white(r->pool, &ll);
429 /* XXX If we want to keep track of the Method, the protocol module should do
430 * it. That support isn't in the scoreboard yet. Hopefully next week
432 ap_update_connection_status(AP_CHILD_THREAD_FROM_ID(conn->id), "Method", r->method);
434 uri = ap_getword_white(r->pool, &ll);
436 /* Provide quick information about the request method as soon as known */
438 r->method_number = ap_method_number_of(r->method);
439 if (r->method_number == M_GET && r->method[0] == 'H') {
443 ap_parse_uri(r, uri);
445 /* ap_getline returns (size of max buffer - 1) if it fills up the
446 * buffer before finding the end-of-line. This is only going to
447 * happen if it exceeds the configured limit for a request-line.
449 if (len > r->server->limit_req_line) {
450 r->status = HTTP_REQUEST_URI_TOO_LARGE;
451 r->proto_num = HTTP_VERSION(1,0);
452 r->protocol = apr_pstrdup(r->pool, "HTTP/1.0");
465 r->protocol = apr_pstrmemdup(r->pool, pro, len);
467 /* XXX ap_update_connection_status(conn->id, "Protocol", r->protocol); */
469 /* Avoid sscanf in the common case */
471 pro[0] == 'H' && pro[1] == 'T' && pro[2] == 'T' && pro[3] == 'P' &&
472 pro[4] == '/' && apr_isdigit(pro[5]) && pro[6] == '.' &&
473 apr_isdigit(pro[7])) {
474 r->proto_num = HTTP_VERSION(pro[5] - '0', pro[7] - '0');
475 } else if (2 == sscanf(r->protocol, "HTTP/%u.%u", &major, &minor)
476 && minor < HTTP_VERSION(1,0)) /* don't allow HTTP/0.1000 */
477 r->proto_num = HTTP_VERSION(major, minor);
479 r->proto_num = HTTP_VERSION(1,0);
484 static void get_mime_headers(request_rec *r)
490 apr_table_t *tmp_headers;
492 /* We'll use apr_table_overlap later to merge these into r->headers_in. */
493 tmp_headers = apr_table_make(r->pool, 50);
496 * Read header lines until we get the empty separator line, a read error,
497 * the connection closes (EOF), reach the server limit, or we timeout.
500 while ((len = ap_rgetline(&field, DEFAULT_LIMIT_REQUEST_FIELDSIZE + 2,
503 if (r->server->limit_req_fields &&
504 (++fields_read > r->server->limit_req_fields)) {
505 r->status = HTTP_BAD_REQUEST;
506 apr_table_setn(r->notes, "error-notes",
507 "The number of request header fields exceeds "
508 "this server's limit.");
511 /* ap_getline returns (size of max buffer - 1) if it fills up the
512 * buffer before finding the end-of-line. This is only going to
513 * happen if it exceeds the configured limit for a field size.
515 if (len > r->server->limit_req_fieldsize) {
516 r->status = HTTP_BAD_REQUEST;
517 apr_table_setn(r->notes, "error-notes",
519 "Size of a request header field "
520 "exceeds server limit.<br />\n"
522 ap_escape_html(r->pool, field),
527 if (!(value = strchr(field, ':'))) { /* Find the colon separator */
528 r->status = HTTP_BAD_REQUEST; /* or abort the bad request */
529 apr_table_setn(r->notes, "error-notes",
531 "Request header field is missing "
532 "colon separator.<br />\n"
534 ap_escape_html(r->pool, field),
541 while (*value == ' ' || *value == '\t') {
542 ++value; /* Skip to start of value */
545 apr_table_addn(tmp_headers, field, value);
546 field = NULL; /* to cause ap_rgetline to allocate a new one */
549 apr_table_overlap(r->headers_in, tmp_headers, APR_OVERLAP_TABLES_MERGE);
552 request_rec *ap_read_request(conn_rec *conn)
559 apr_pool_create(&p, conn->pool);
560 r = apr_pcalloc(p, sizeof(request_rec));
562 r->connection = conn;
563 r->server = conn->base_server;
566 r->ap_auth_type = NULL;
568 r->allowed_methods = ap_make_method_list(p, 2);
570 r->headers_in = apr_table_make(r->pool, 50);
571 r->subprocess_env = apr_table_make(r->pool, 50);
572 r->headers_out = apr_table_make(r->pool, 12);
573 r->err_headers_out = apr_table_make(r->pool, 5);
574 r->notes = apr_table_make(r->pool, 5);
576 r->request_config = ap_create_request_config(r->pool);
577 /* Must be set before we run create request hook */
578 r->output_filters = conn->output_filters;
579 r->input_filters = conn->input_filters;
580 ap_run_create_request(r);
581 r->per_dir_config = r->server->lookup_defaults;
583 r->sent_bodyct = 0; /* bytect isn't for body */
586 r->read_body = REQUEST_NO_BODY;
588 r->status = HTTP_REQUEST_TIME_OUT; /* Until we get a request */
589 r->the_request = NULL;
591 /* Get the request... */
592 if (!read_request_line(r)) {
593 if (r->status == HTTP_REQUEST_URI_TOO_LARGE) {
594 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
595 "request failed: URI too long");
596 ap_send_error_response(r, 0);
597 ap_run_log_transaction(r);
603 if (!r->assbackwards) {
605 if (r->status != HTTP_REQUEST_TIME_OUT) {
606 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
607 "request failed: error reading the headers");
608 ap_send_error_response(r, 0);
609 ap_run_log_transaction(r);
614 if (r->header_only) {
616 * Client asked for headers only with HTTP/0.9, which doesn't send
617 * headers! Have to dink things just to make sure the error message
620 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
621 "client sent invalid HTTP/0.9 request: HEAD %s",
624 r->status = HTTP_BAD_REQUEST;
625 ap_send_error_response(r, 0);
626 ap_run_log_transaction(r);
631 r->status = HTTP_OK; /* Until further notice. */
633 /* update what we think the virtual host is based on the headers we've
634 * now read. may update status.
636 ap_update_vhost_from_headers(r);
638 /* we may have switched to another server */
639 r->per_dir_config = r->server->lookup_defaults;
641 if ((!r->hostname && (r->proto_num >= HTTP_VERSION(1,1))) ||
642 ((r->proto_num == HTTP_VERSION(1,1)) &&
643 !apr_table_get(r->headers_in, "Host"))) {
645 * Client sent us an HTTP/1.1 or later request without telling us the
646 * hostname, either with a full URL or a Host: header. We therefore
647 * need to (as per the 1.1 spec) send an error. As a special case,
648 * HTTP/1.1 mentions twice (S9, S14.23) that a request MUST contain
649 * a Host: header, and the server MUST respond with 400 if it doesn't.
651 r->status = HTTP_BAD_REQUEST;
652 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
653 "client sent HTTP/1.1 request without hostname "
654 "(see RFC2616 section 14.23): %s", r->uri);
656 if (r->status != HTTP_OK) {
657 ap_send_error_response(r, 0);
658 ap_run_log_transaction(r);
661 if (((expect = apr_table_get(r->headers_in, "Expect")) != NULL) &&
662 (expect[0] != '\0')) {
664 * The Expect header field was added to HTTP/1.1 after RFC 2068
665 * as a means to signal when a 100 response is desired and,
666 * unfortunately, to signal a poor man's mandatory extension that
667 * the server must understand or return 417 Expectation Failed.
669 if (strcasecmp(expect, "100-continue") == 0) {
670 r->expecting_100 = 1;
673 r->status = HTTP_EXPECTATION_FAILED;
674 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r,
675 "client sent an unrecognized expectation value of "
676 "Expect: %s", expect);
677 ap_send_error_response(r, 0);
678 (void) ap_discard_request_body(r);
679 ap_run_log_transaction(r);
684 ap_add_input_filter("HTTP_IN", NULL, r, r->connection);
686 if ((access_status = ap_run_post_read_request(r))) {
687 ap_die(access_status, r);
688 ap_run_log_transaction(r);
696 * A couple of other functions which initialize some of the fields of
697 * a request structure, as appropriate for adjuncts of one kind or another
698 * to a request in progress. Best here, rather than elsewhere, since
699 * *someone* has to set the protocol-specific fields...
702 void ap_set_sub_req_protocol(request_rec *rnew, const request_rec *r)
704 rnew->the_request = r->the_request; /* Keep original request-line */
706 rnew->assbackwards = 1; /* Don't send headers from this. */
707 rnew->no_local_copy = 1; /* Don't try to send HTTP_NOT_MODIFIED for a
709 rnew->method = "GET";
710 rnew->method_number = M_GET;
711 rnew->protocol = "INCLUDED";
713 rnew->status = HTTP_OK;
715 rnew->headers_in = r->headers_in;
716 rnew->subprocess_env = apr_table_copy(rnew->pool, r->subprocess_env);
717 rnew->headers_out = apr_table_make(rnew->pool, 5);
718 rnew->err_headers_out = apr_table_make(rnew->pool, 5);
719 rnew->notes = apr_table_make(rnew->pool, 5);
721 rnew->expecting_100 = r->expecting_100;
722 rnew->read_length = r->read_length;
723 rnew->read_body = REQUEST_NO_BODY;
725 rnew->main = (request_rec *) r;
728 static void end_output_stream(request_rec *r)
730 apr_bucket_brigade *bb;
733 bb = apr_brigade_create(r->pool);
734 b = apr_bucket_eos_create();
735 APR_BRIGADE_INSERT_TAIL(bb, b);
736 ap_pass_brigade(r->output_filters, bb);
739 void ap_finalize_sub_req_protocol(request_rec *sub)
741 end_output_stream(sub);
744 /* finalize_request_protocol is called at completion of sending the
745 * response. Its sole purpose is to send the terminating protocol
746 * information for any wrappers around the response message body
747 * (i.e., transfer encodings). It should have been named finalize_response.
749 AP_DECLARE(void) ap_finalize_request_protocol(request_rec *r)
754 /* tell the filter chain there is no more content coming */
756 end_output_stream(r);
761 * Support for the Basic authentication protocol, and a bit for Digest.
764 AP_DECLARE(void) ap_note_auth_failure(request_rec *r)
766 const char *type = ap_auth_type(r);
768 if (!strcasecmp(type, "Basic"))
769 ap_note_basic_auth_failure(r);
770 else if (!strcasecmp(type, "Digest"))
771 ap_note_digest_auth_failure(r);
774 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR,
775 0, r, "need AuthType to note auth failure: %s", r->uri);
779 AP_DECLARE(void) ap_note_basic_auth_failure(request_rec *r)
781 const char *type = ap_auth_type(r);
782 /* if there is no AuthType configure or it is something other than
783 * Basic, let ap_note_auth_failure() deal with it
785 if (!type || strcasecmp(type, "Basic"))
786 ap_note_auth_failure(r);
788 apr_table_setn(r->err_headers_out,
789 (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authenticate" : "WWW-Authenticate",
790 apr_pstrcat(r->pool, "Basic realm=\"", ap_auth_name(r), "\"",
794 AP_DECLARE(void) ap_note_digest_auth_failure(request_rec *r)
796 apr_table_setn(r->err_headers_out,
797 (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authenticate" : "WWW-Authenticate",
798 apr_psprintf(r->pool, "Digest realm=\"%s\", nonce=\"%llx\"",
799 ap_auth_name(r), r->request_time));
802 AP_DECLARE(int) ap_get_basic_auth_pw(request_rec *r, const char **pw)
804 const char *auth_line = apr_table_get(r->headers_in,
805 (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authorization"
809 if (!(t = ap_auth_type(r)) || strcasecmp(t, "Basic"))
812 if (!ap_auth_name(r)) {
813 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR,
814 0, r, "need AuthName: %s", r->uri);
815 return HTTP_INTERNAL_SERVER_ERROR;
819 ap_note_basic_auth_failure(r);
820 return HTTP_UNAUTHORIZED;
823 if (strcasecmp(ap_getword(r->pool, &auth_line, ' '), "Basic")) {
824 /* Client tried to authenticate using wrong auth scheme */
825 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
826 "client used wrong authentication scheme: %s", r->uri);
827 ap_note_basic_auth_failure(r);
828 return HTTP_UNAUTHORIZED;
831 while (*auth_line== ' ' || *auth_line== '\t') {
835 t = ap_pbase64decode(r->pool, auth_line);
836 /* Note that this allocation has to be made from r->connection->pool
837 * because it has the lifetime of the connection. The other allocations
838 * are temporary and can be tossed away any time.
840 r->user = ap_getword_nulls (r->pool, &t, ':');
841 r->ap_auth_type = "Basic";
848 struct content_length_ctx {
849 apr_bucket_brigade *saved;
854 /* This filter computes the content length, but it also computes the number
855 * of bytes sent to the client. This means that this filter will always run
856 * through all of the buckets in all brigades
858 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_content_length_filter(ap_filter_t *f,
859 apr_bucket_brigade *b)
861 request_rec *r = f->r;
862 struct content_length_ctx *ctx;
865 int eos = 0, flush = 0, partial_send_okay = 0;
866 apr_bucket_brigade *more, *split;
867 apr_read_type_e eblock = APR_NONBLOCK_READ;
870 if (!ctx) { /* first time through */
871 f->ctx = ctx = apr_pcalloc(r->pool, sizeof(struct content_length_ctx));
872 ctx->compute_len = 1; /* Assume we will compute the length */
875 /* Humm, is this check the best it can be?
876 * - protocol >= HTTP/1.1 implies support for chunking
877 * - non-keepalive implies the end of byte stream will be signaled
878 * by a connection close
879 * In both cases, we can send bytes to the client w/o needing to
880 * compute content-length.
882 * We should be able to force connection close from this filter
883 * when we see we are buffering too much.
885 if ((r->proto_num >= HTTP_VERSION(1,1)) ||
886 (!f->r->connection->keepalive)) {
887 partial_send_okay = 1;
897 APR_BRIGADE_FOREACH(e, b) {
901 if (APR_BUCKET_IS_EOS(e)) {
904 else if (APR_BUCKET_IS_FLUSH(e)) {
905 if (partial_send_okay) {
907 more = apr_brigade_split(b, APR_BUCKET_NEXT(e));
911 else if ((ctx->curr_len > 4*AP_MIN_BYTES_TO_WRITE)) {
912 /* If we've accumulated more than 4xAP_MIN_BYTES_TO_WRITE and
913 * the client supports chunked encoding, send what we have
914 * and come back for more.
916 if (partial_send_okay) {
918 more = apr_brigade_split(b, e);
922 if (e->length == -1) { /* if length unknown */
923 rv = apr_bucket_read(e, &ignored, &len, eblock);
924 if (rv == APR_SUCCESS) {
925 /* Attempt a nonblocking read next time through */
926 eblock = APR_NONBLOCK_READ;
928 else if (APR_STATUS_IS_EAGAIN(rv)) {
929 /* Make the next read blocking. If the client supports chunked
930 * encoding, flush the filter stack to the network.
932 eblock = APR_BLOCK_READ;
933 if (partial_send_okay) {
935 more = apr_brigade_split(b, e);
940 else if (rv != APR_EOF) {
941 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
942 "ap_content_length_filter: apr_bucket_read() failed");
949 ctx->curr_len += len;
950 r->bytes_sent += len;
954 ctx->compute_len = 0; /* Ooops, can't compute the length now */
957 APR_BRIGADE_CONCAT(ctx->saved, split);
958 apr_brigade_destroy(split);
963 rv = ap_fflush(f->next, split);
966 rv = ap_pass_brigade(f->next, split);
968 if (rv != APR_SUCCESS)
973 if ((ctx->curr_len < AP_MIN_BYTES_TO_WRITE) && !eos) {
974 return ap_save_brigade(f, &ctx->saved, &b, (r->main) ? r->main->pool : r->pool);
977 if (ctx->compute_len) {
978 /* save the brigade; we can't pass any data to the next
979 * filter until we have the entire content length
982 return ap_save_brigade(f, &ctx->saved, &b, r->pool);
984 ap_set_content_length(r, r->bytes_sent);
987 APR_BRIGADE_CONCAT(ctx->saved, b);
988 apr_brigade_destroy(b);
994 return ap_pass_brigade(f->next, b);
998 * Send the body of a response to the client.
1000 AP_DECLARE(apr_status_t) ap_send_fd(apr_file_t *fd, request_rec *r, apr_off_t offset,
1001 apr_size_t len, apr_size_t *nbytes)
1003 apr_bucket_brigade *bb = NULL;
1007 bb = apr_brigade_create(r->pool);
1008 b = apr_bucket_file_create(fd, offset, len, r->pool);
1009 APR_BRIGADE_INSERT_TAIL(bb, b);
1011 rv = ap_pass_brigade(r->output_filters, bb);
1012 if (rv != APR_SUCCESS) {
1013 *nbytes = 0; /* no way to tell how many were actually sent */
1023 /* send data from an in-memory buffer */
1024 AP_DECLARE(size_t) ap_send_mmap(apr_mmap_t *mm, request_rec *r, size_t offset,
1027 apr_bucket_brigade *bb = NULL;
1030 bb = apr_brigade_create(r->pool);
1031 b = apr_bucket_mmap_create(mm, offset, length);
1032 APR_BRIGADE_INSERT_TAIL(bb, b);
1033 ap_pass_brigade(r->output_filters, bb);
1035 return mm->size; /* XXX - change API to report apr_status_t? */
1037 #endif /* APR_HAS_MMAP */
1040 apr_bucket_brigade *bb;
1041 } old_write_filter_ctx;
1043 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_old_write_filter(
1044 ap_filter_t *f, apr_bucket_brigade *bb)
1046 old_write_filter_ctx *ctx = f->ctx;
1048 AP_DEBUG_ASSERT(ctx);
1051 /* whatever is coming down the pipe (we don't care), we
1052 * can simply insert our buffered data at the front and
1053 * pass the whole bundle down the chain.
1055 APR_BRIGADE_CONCAT(ctx->bb, bb);
1058 return ap_pass_brigade(f->next, ctx->bb);
1061 static apr_status_t buffer_output(request_rec *r,
1062 const char *str, apr_size_t len)
1065 old_write_filter_ctx *ctx;
1070 /* future optimization: record some flags in the request_rec to
1071 * say whether we've added our filter, and whether it is first.
1074 /* this will typically exit on the first test */
1075 for (f = r->output_filters; f != NULL; f = f->next)
1076 if (ap_old_write_func == f->frec)
1079 /* our filter hasn't been added yet */
1080 ctx = apr_pcalloc(r->pool, sizeof(*ctx));
1081 ap_add_output_filter("OLD_WRITE", ctx, r, r->connection);
1082 f = r->output_filters;
1085 /* if the first filter is not our buffering filter, then we have to
1086 * deliver the content through the normal filter chain */
1087 if (f != r->output_filters) {
1088 apr_bucket_brigade *bb = apr_brigade_create(r->pool);
1089 apr_bucket *b = apr_bucket_transient_create(str, len);
1090 APR_BRIGADE_INSERT_TAIL(bb, b);
1092 return ap_pass_brigade(r->output_filters, bb);
1095 /* grab the context from our filter */
1096 ctx = r->output_filters->ctx;
1098 if (ctx->bb == NULL) {
1099 ctx->bb = apr_brigade_create(r->pool);
1102 return ap_fwrite(f->next, ctx->bb, str, len);
1105 AP_DECLARE(int) ap_rputc(int c, request_rec *r)
1109 if (r->connection->aborted) {
1113 if (buffer_output(r, &c2, 1) != APR_SUCCESS)
1119 AP_DECLARE(int) ap_rputs(const char *str, request_rec *r)
1123 if (r->connection->aborted)
1126 if (buffer_output(r, str, len = strlen(str)) != APR_SUCCESS)
1132 AP_DECLARE(int) ap_rwrite(const void *buf, int nbyte, request_rec *r)
1134 if (r->connection->aborted)
1137 if (buffer_output(r, buf, nbyte) != APR_SUCCESS)
1143 struct ap_vrprintf_data {
1144 apr_vformatter_buff_t vbuff;
1149 static apr_status_t r_flush(apr_vformatter_buff_t *buff)
1151 /* callback function passed to ap_vformatter to be called when
1152 * vformatter needs to write into buff and buff.curpos > buff.endpos */
1154 /* ap_vrprintf_data passed as a apr_vformatter_buff_t, which is then
1155 * "downcast" to an ap_vrprintf_data */
1156 struct ap_vrprintf_data *vd = (struct ap_vrprintf_data*)buff;
1158 if (vd->r->connection->aborted)
1161 /* r_flush is called when vbuff is completely full */
1162 if (buffer_output(vd->r, vd->buff, AP_IOBUFSIZE)) {
1166 /* reset the buffer position */
1167 vd->vbuff.curpos = vd->buff;
1168 vd->vbuff.endpos = vd->buff + AP_IOBUFSIZE;
1173 AP_DECLARE(int) ap_vrprintf(request_rec *r, const char *fmt, va_list va)
1176 struct ap_vrprintf_data vd;
1177 char vrprintf_buf[AP_IOBUFSIZE];
1179 vd.vbuff.curpos = vrprintf_buf;
1180 vd.vbuff.endpos = vrprintf_buf + AP_IOBUFSIZE;
1182 vd.buff = vrprintf_buf;
1184 if (r->connection->aborted)
1187 written = apr_vformatter(r_flush, &vd.vbuff, fmt, va);
1188 /* tack on null terminator on remaining string */
1189 *(vd.vbuff.curpos) = '\0';
1191 if (written != -1) {
1192 int n = vd.vbuff.curpos - vrprintf_buf;
1194 /* last call to buffer_output, to finish clearing the buffer */
1195 if (buffer_output(r, vrprintf_buf,n) != APR_SUCCESS)
1204 AP_DECLARE_NONSTD(int) ap_rprintf(request_rec *r, const char *fmt, ...)
1209 if (r->connection->aborted)
1213 n = ap_vrprintf(r, fmt, va);
1219 AP_DECLARE_NONSTD(int) ap_rvputs(request_rec *r, ...)
1224 apr_size_t written = 0;
1226 if (r->connection->aborted)
1229 /* ### TODO: if the total output is large, put all the strings
1230 ### into a single brigade, rather than flushing each time we
1231 ### fill the buffer */
1234 s = va_arg(va, const char *);
1239 if (buffer_output(r, s, len) != APR_SUCCESS) {
1250 AP_DECLARE(int) ap_rflush(request_rec *r)
1252 apr_bucket_brigade *bb;
1255 bb = apr_brigade_create(r->pool);
1256 b = apr_bucket_flush_create();
1257 APR_BRIGADE_INSERT_TAIL(bb, b);
1258 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS)
1264 * This function sets the Last-Modified output header field to the value
1265 * of the mtime field in the request structure - rationalized to keep it from
1266 * being in the future.
1268 AP_DECLARE(void) ap_set_last_modified(request_rec *r)
1270 apr_time_t mod_time = ap_rationalize_mtime(r, r->mtime);
1271 char *datestr = apr_palloc(r->pool, APR_RFC822_DATE_LEN);
1272 apr_rfc822_date(datestr, mod_time);
1273 apr_table_setn(r->headers_out, "Last-Modified", datestr);
1276 AP_IMPLEMENT_HOOK_RUN_ALL(int,post_read_request,
1277 (request_rec *r),(r),OK,DECLINED)
1278 AP_IMPLEMENT_HOOK_RUN_ALL(int,log_transaction,
1279 (request_rec *r),(r),OK,DECLINED)
1280 AP_IMPLEMENT_HOOK_RUN_FIRST(const char *,http_method,
1281 (const request_rec *r),(r),NULL)
1282 AP_IMPLEMENT_HOOK_RUN_FIRST(unsigned short,default_port,
1283 (const request_rec *r),(r),0)