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_date.h" /* For parseHTTPdate and BAD_DATE */
90 #include "util_charset.h"
91 #include "util_ebcdic.h"
102 APR_HOOK_LINK(post_read_request)
103 APR_HOOK_LINK(log_transaction)
104 APR_HOOK_LINK(http_method)
105 APR_HOOK_LINK(default_port)
109 * Builds the content-type that should be sent to the client from the
110 * content-type specified. The following rules are followed:
111 * - if type is NULL, type is set to ap_default_type(r)
112 * - if charset adding is disabled, stop processing and return type.
113 * - then, if there are no parameters on type, add the default charset
116 AP_DECLARE(const char *)ap_make_content_type(request_rec *r, const char *type)
118 static const char *needcset[] = {
123 core_dir_config *conf =
124 (core_dir_config *)ap_get_module_config(r->per_dir_config,
128 type = ap_default_type(r);
130 if (conf->add_default_charset != ADD_DEFAULT_CHARSET_ON) {
134 if (ap_strcasestr(type, "charset=") != NULL) {
135 /* already has parameter, do nothing */
136 /* XXX we don't check the validity */
140 /* see if it makes sense to add the charset. At present,
141 * we only add it if the Content-type is one of needcset[]
143 for (pcset = needcset; *pcset ; pcset++) {
144 if (ap_strcasestr(type, *pcset) != NULL) {
145 type = apr_pstrcat(r->pool, type, "; charset=",
146 conf->add_default_charset_name, NULL);
154 AP_DECLARE(void) ap_set_content_length(request_rec *r, apr_off_t clength)
156 r->clength = clength;
157 apr_table_setn(r->headers_out, "Content-Length",
158 apr_psprintf(r->pool, "%" APR_OFF_T_FMT, clength));
162 * Return the latest rational time from a request/mtime (modification time)
163 * pair. We return the mtime unless it's in the future, in which case we
164 * return the current time. We use the request time as a reference in order
165 * to limit the number of calls to time(). We don't check for futurosity
166 * unless the mtime is at least as new as the reference.
168 AP_DECLARE(apr_time_t) ap_rationalize_mtime(request_rec *r, apr_time_t mtime)
172 /* For all static responses, it's almost certain that the file was
173 * last modified before the beginning of the request. So there's
174 * no reason to call time(NULL) again. But if the response has been
175 * created on demand, then it might be newer than the time the request
176 * started. In this event we really have to call time(NULL) again
177 * so that we can give the clients the most accurate Last-Modified. If we
178 * were given a time in the future, we return the current time - the
179 * Last-Modified can't be in the future.
181 now = (mtime < r->request_time) ? r->request_time : apr_time_now();
182 return (mtime > now) ? now : mtime;
185 /* Get a line of protocol input, including any continuation lines
186 * caused by MIME folding (or broken clients) if fold != 0, and place it
187 * in the buffer s, of size n bytes, without the ending newline.
189 * Returns -1 on error, or the length of s.
191 * Notes: Because the buffer uses 1 char for NUL, the most we can return is
192 * (n - 1) actual characters.
194 * If no LF is detected on the last line due to a dropped connection
195 * or a full buffer, that's considered an error.
197 AP_CORE_DECLARE(int) ap_getline(char *s, int n, request_rec *r, int fold)
201 char *beyond_buff = s + n;
205 int looking_ahead = 0;
207 conn_rec *c = r->connection;
208 core_request_config *req_cfg;
209 apr_bucket_brigade *b;
212 req_cfg = (core_request_config *)
213 ap_get_module_config(r->request_config, &core_module);
215 /* make sure it's empty unless we're folding */
216 AP_DEBUG_ASSERT(fold || APR_BRIGADE_EMPTY(b));
219 if (APR_BRIGADE_EMPTY(b)) {
221 if ((retval = ap_get_brigade(c->input_filters, b,
223 &zero /* readline */)) != APR_SUCCESS ||
224 APR_BRIGADE_EMPTY(b)) {
225 apr_brigade_destroy(b);
229 e = APR_BRIGADE_FIRST(b);
230 if (e->length == 0) {
231 apr_bucket_delete(e);
234 retval = apr_bucket_read(e, &temp, &length, APR_BLOCK_READ);
235 if (retval != APR_SUCCESS) {
236 apr_brigade_destroy(b);
237 ap_log_rerror(APLOG_MARK, APLOG_ERR, retval, r, "apr_bucket_read() failed");
239 break; /* report previously-read data to caller, do ap_xlate_proto_to_ascii() */
246 if ((looking_ahead) && (*temp != APR_ASCII_BLANK) && (*temp != APR_ASCII_TAB)) {
247 /* can't fold because next line isn't indented,
248 * so return what we have. lookahead brigade is
249 * stashed on req_cfg->bb
251 AP_DEBUG_ASSERT(!APR_BRIGADE_EMPTY(req_cfg->bb));
254 last_char = pos + length - 1;
255 if (last_char < beyond_buff) {
256 memcpy(pos, temp, length);
257 apr_bucket_delete(e);
260 /* input line was larger than the caller's buffer */
261 apr_brigade_destroy(b);
263 /* don't need to worry about req_cfg->bb being bogus.
264 * the request is about to die, and ErrorDocument
265 * redirects get a new req_cfg->bb
271 pos = last_char; /* Point at the last character */
273 if (*pos == APR_ASCII_LF) { /* Did we get a full line of input? */
275 if (pos > s && *(pos - 1) == APR_ASCII_CR) {
276 --pos; /* zap optional CR before LF */
280 * Trim any extra trailing spaces or tabs except for the first
281 * space or tab at the beginning of a blank string. This makes
282 * it much easier to check field values for exact matches, and
283 * saves memory as well. Terminate string at end of line.
285 while (pos > (s + 1) &&
286 (*(pos - 1) == APR_ASCII_BLANK || *(pos - 1) == APR_ASCII_TAB)) {
287 --pos; /* trim extra trailing spaces or tabs */
289 *pos = '\0'; /* zap end of string */
290 total = pos - s; /* update total string length */
292 /* look ahead another line if line folding is desired
293 * and this line isn't empty
299 AP_DEBUG_ASSERT(APR_BRIGADE_EMPTY(req_cfg->bb));
304 /* no LF yet...character mode client (telnet)...keep going
305 * bump past last character read,
306 * and set total in case we bail before finding a LF
309 looking_ahead = 0; /* only appropriate right after LF */
312 ap_xlate_proto_from_ascii(s, total);
316 /* parse_uri: break apart the uri
318 * - sets r->args to rest after '?' (or NULL if no '?')
319 * - sets r->uri to request uri (without r->args part)
320 * - sets r->hostname (if not set already) from request (scheme://host:port)
322 AP_CORE_DECLARE(void) ap_parse_uri(request_rec *r, const char *uri)
324 int status = HTTP_OK;
326 r->unparsed_uri = apr_pstrdup(r->pool, uri);
328 if (r->method_number == M_CONNECT) {
329 status = apr_uri_parse_hostinfo_components(r->pool, uri, &r->parsed_uri);
332 /* Simple syntax Errors in URLs are trapped by parse_uri_components(). */
333 status = apr_uri_parse_components(r->pool, uri, &r->parsed_uri);
336 if (status == APR_SUCCESS) {
337 /* if it has a scheme we may need to do absoluteURI vhost stuff */
338 if (r->parsed_uri.scheme
339 && !strcasecmp(r->parsed_uri.scheme, ap_http_method(r))) {
340 r->hostname = r->parsed_uri.hostname;
342 else if (r->method_number == M_CONNECT) {
343 r->hostname = r->parsed_uri.hostname;
345 r->args = r->parsed_uri.query;
346 r->uri = r->parsed_uri.path ? r->parsed_uri.path
347 : apr_pstrdup(r->pool, "/");
348 #if defined(OS2) || defined(WIN32)
349 /* Handle path translations for OS/2 and plug security hole.
350 * This will prevent "http://www.wherever.com/..\..\/" from
351 * returning a directory for the root drive.
356 for (x = r->uri; (x = strchr(x, '\\')) != NULL; )
359 #endif /* OS2 || WIN32 */
364 r->status = HTTP_BAD_REQUEST; /* set error status */
365 r->uri = apr_pstrdup(r->pool, uri);
369 static int read_request_line(request_rec *r)
371 char l[DEFAULT_LIMIT_REQUEST_LINE + 2]; /* getline's two extra for \n\0 */
377 conn_rec *conn = r->connection;
379 int major = 1, minor = 0; /* Assume HTTP/1.0 if non-"HTTP" protocol */
382 /* Read past empty lines until we get a real request line,
383 * a read error, the connection closes (EOF), or we timeout.
385 * We skip empty lines because browsers have to tack a CRLF on to the end
386 * of POSTs to support old CERN webservers. But note that we may not
387 * have flushed any previous response completely to the client yet.
388 * We delay the flush as long as possible so that we can improve
389 * performance for clients that are pipelining requests. If a request
390 * is pipelined then we won't block during the (implicit) read() below.
391 * If the requests aren't pipelined, then the client is still waiting
392 * for the final buffer flush from us, and we will block in the implicit
393 * read(). B_SAFEREAD ensures that the BUFF layer flushes if it will
394 * have to block during a read.
397 while ((len = ap_getline(l, sizeof(l), r, 0)) <= 0) {
398 if (len < 0) { /* includes EOF */
399 /* this is a hack to make sure that request time is set,
400 * it's not perfect, but it's better than nothing
402 r->request_time = apr_time_now();
406 /* we've probably got something to do, ignore graceful restart requests */
408 /* XXX - sigwait doesn't work if the signal has been SIG_IGNed (under
409 * linux 2.0 w/ glibc 2.0, anyway), and this step isn't necessary when
410 * we're running a sigwait thread anyway. If/when unthreaded mode is
411 * put back in, we should make sure to ignore this signal iff a sigwait
412 * thread isn't used. - mvsk
415 apr_signal(SIGWINCH, SIG_IGN);
419 r->request_time = apr_time_now();
420 r->the_request = apr_pstrdup(r->pool, l);
421 r->method = ap_getword_white(r->pool, &ll);
424 /* XXX If we want to keep track of the Method, the protocol module should do
425 * it. That support isn't in the scoreboard yet. Hopefully next week
427 ap_update_connection_status(AP_CHILD_THREAD_FROM_ID(conn->id), "Method", r->method);
429 uri = ap_getword_white(r->pool, &ll);
431 /* Provide quick information about the request method as soon as known */
433 r->method_number = ap_method_number_of(r->method);
434 if (r->method_number == M_GET && r->method[0] == 'H') {
438 ap_parse_uri(r, uri);
440 /* ap_getline returns (size of max buffer - 1) if it fills up the
441 * buffer before finding the end-of-line. This is only going to
442 * happen if it exceeds the configured limit for a request-line.
444 if (len > r->server->limit_req_line) {
445 r->status = HTTP_REQUEST_URI_TOO_LARGE;
446 r->proto_num = HTTP_VERSION(1,0);
447 r->protocol = apr_pstrdup(r->pool, "HTTP/1.0");
460 r->protocol = apr_pstrndup(r->pool, pro, len);
462 /* XXX ap_update_connection_status(conn->id, "Protocol", r->protocol); */
464 /* Avoid sscanf in the common case */
466 pro[0] == 'H' && pro[1] == 'T' && pro[2] == 'T' && pro[3] == 'P' &&
467 pro[4] == '/' && apr_isdigit(pro[5]) && pro[6] == '.' &&
468 apr_isdigit(pro[7])) {
469 r->proto_num = HTTP_VERSION(pro[5] - '0', pro[7] - '0');
470 } else if (2 == sscanf(r->protocol, "HTTP/%u.%u", &major, &minor)
471 && minor < HTTP_VERSION(1,0)) /* don't allow HTTP/0.1000 */
472 r->proto_num = HTTP_VERSION(major, minor);
474 r->proto_num = HTTP_VERSION(1,0);
479 static void get_mime_headers(request_rec *r)
481 char field[DEFAULT_LIMIT_REQUEST_FIELDSIZE + 2]; /* getline's two extra */
486 apr_table_t *tmp_headers;
488 /* We'll use apr_table_overlap later to merge these into r->headers_in. */
489 tmp_headers = apr_table_make(r->pool, 50);
492 * Read header lines until we get the empty separator line, a read error,
493 * the connection closes (EOF), reach the server limit, or we timeout.
495 while ((len = ap_getline(field, sizeof(field), r, 1)) > 0) {
497 if (r->server->limit_req_fields &&
498 (++fields_read > r->server->limit_req_fields)) {
499 r->status = HTTP_BAD_REQUEST;
500 apr_table_setn(r->notes, "error-notes",
501 "The number of request header fields exceeds "
502 "this server's limit.<P>\n");
505 /* ap_getline returns (size of max buffer - 1) if it fills up the
506 * buffer before finding the end-of-line. This is only going to
507 * happen if it exceeds the configured limit for a field size.
509 if (len > r->server->limit_req_fieldsize) {
510 r->status = HTTP_BAD_REQUEST;
511 apr_table_setn(r->notes, "error-notes",
513 "Size of a request header field "
514 "exceeds server limit.<P>\n"
516 ap_escape_html(r->pool, field),
520 copy = apr_palloc(r->pool, len + 1);
521 memcpy(copy, field, len + 1);
523 if (!(value = strchr(copy, ':'))) { /* Find the colon separator */
524 r->status = HTTP_BAD_REQUEST; /* or abort the bad request */
525 apr_table_setn(r->notes, "error-notes",
527 "Request header field is missing "
528 "colon separator.<P>\n"
530 ap_escape_html(r->pool, copy),
537 while (*value == ' ' || *value == '\t') {
538 ++value; /* Skip to start of value */
541 apr_table_addn(tmp_headers, copy, value);
544 apr_table_overlap(r->headers_in, tmp_headers, APR_OVERLAP_TABLES_MERGE);
547 request_rec *ap_read_request(conn_rec *conn)
552 int access_status, keptalive;
554 apr_pool_create(&p, conn->pool);
555 r = apr_pcalloc(p, sizeof(request_rec));
557 r->connection = conn;
558 r->server = conn->base_server;
560 keptalive = conn->keepalive == 1;
564 r->ap_auth_type = NULL;
566 r->allowed_methods = ap_make_method_list(p, 2);
568 r->headers_in = apr_table_make(r->pool, 50);
569 r->subprocess_env = apr_table_make(r->pool, 50);
570 r->headers_out = apr_table_make(r->pool, 12);
571 r->err_headers_out = apr_table_make(r->pool, 5);
572 r->notes = apr_table_make(r->pool, 5);
574 r->request_config = ap_create_request_config(r->pool);
575 ap_run_create_request(r);
576 r->per_dir_config = r->server->lookup_defaults;
578 r->sent_bodyct = 0; /* bytect isn't for body */
581 r->read_body = REQUEST_NO_BODY;
583 r->status = HTTP_REQUEST_TIME_OUT; /* Until we get a request */
584 r->the_request = NULL;
585 r->output_filters = conn->output_filters;
586 r->input_filters = conn->input_filters;
588 apr_setsocketopt(conn->client_socket, APR_SO_TIMEOUT,
590 ? r->server->keep_alive_timeout * APR_USEC_PER_SEC
591 : r->server->timeout * APR_USEC_PER_SEC));
593 ap_add_output_filter("BYTERANGE", NULL, r, r->connection);
594 ap_add_output_filter("CONTENT_LENGTH", NULL, r, r->connection);
595 ap_add_output_filter("HTTP_HEADER", NULL, r, r->connection);
598 /* Get the request... */
599 if (!read_request_line(r)) {
600 if (r->status == HTTP_REQUEST_URI_TOO_LARGE) {
601 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
602 "request failed: URI too long");
603 ap_send_error_response(r, 0);
604 ap_run_log_transaction(r);
610 apr_setsocketopt(r->connection->client_socket, APR_SO_TIMEOUT,
611 (int)(r->server->timeout * APR_USEC_PER_SEC));
613 if (!r->assbackwards) {
615 if (r->status != HTTP_REQUEST_TIME_OUT) {
616 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
617 "request failed: error reading the headers");
618 ap_send_error_response(r, 0);
619 ap_run_log_transaction(r);
624 if (r->header_only) {
626 * Client asked for headers only with HTTP/0.9, which doesn't send
627 * headers! Have to dink things just to make sure the error message
630 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
631 "client sent invalid HTTP/0.9 request: HEAD %s",
634 r->status = HTTP_BAD_REQUEST;
635 ap_send_error_response(r, 0);
636 ap_run_log_transaction(r);
641 r->status = HTTP_OK; /* Until further notice. */
643 /* update what we think the virtual host is based on the headers we've
644 * now read. may update status.
646 ap_update_vhost_from_headers(r);
648 /* we may have switched to another server */
649 r->per_dir_config = r->server->lookup_defaults;
651 if ((!r->hostname && (r->proto_num >= HTTP_VERSION(1,1))) ||
652 ((r->proto_num == HTTP_VERSION(1,1)) &&
653 !apr_table_get(r->headers_in, "Host"))) {
655 * Client sent us an HTTP/1.1 or later request without telling us the
656 * hostname, either with a full URL or a Host: header. We therefore
657 * need to (as per the 1.1 spec) send an error. As a special case,
658 * HTTP/1.1 mentions twice (S9, S14.23) that a request MUST contain
659 * a Host: header, and the server MUST respond with 400 if it doesn't.
661 r->status = HTTP_BAD_REQUEST;
662 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
663 "client sent HTTP/1.1 request without hostname "
664 "(see RFC2616 section 14.23): %s", r->uri);
666 if (r->status != HTTP_OK) {
667 ap_send_error_response(r, 0);
668 ap_run_log_transaction(r);
671 if (((expect = apr_table_get(r->headers_in, "Expect")) != NULL) &&
672 (expect[0] != '\0')) {
674 * The Expect header field was added to HTTP/1.1 after RFC 2068
675 * as a means to signal when a 100 response is desired and,
676 * unfortunately, to signal a poor man's mandatory extension that
677 * the server must understand or return 417 Expectation Failed.
679 if (strcasecmp(expect, "100-continue") == 0) {
680 r->expecting_100 = 1;
683 r->status = HTTP_EXPECTATION_FAILED;
684 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r,
685 "client sent an unrecognized expectation value of "
686 "Expect: %s", expect);
687 ap_send_error_response(r, 0);
688 (void) ap_discard_request_body(r);
689 ap_run_log_transaction(r);
694 if ((access_status = ap_run_post_read_request(r))) {
695 ap_die(access_status, r);
696 ap_run_log_transaction(r);
704 * A couple of other functions which initialize some of the fields of
705 * a request structure, as appropriate for adjuncts of one kind or another
706 * to a request in progress. Best here, rather than elsewhere, since
707 * *someone* has to set the protocol-specific fields...
710 void ap_set_sub_req_protocol(request_rec *rnew, const request_rec *r)
712 rnew->the_request = r->the_request; /* Keep original request-line */
714 rnew->assbackwards = 1; /* Don't send headers from this. */
715 rnew->no_local_copy = 1; /* Don't try to send HTTP_NOT_MODIFIED for a
717 rnew->method = "GET";
718 rnew->method_number = M_GET;
719 rnew->protocol = "INCLUDED";
721 rnew->status = HTTP_OK;
723 rnew->headers_in = r->headers_in;
724 rnew->subprocess_env = apr_table_copy(rnew->pool, r->subprocess_env);
725 rnew->headers_out = apr_table_make(rnew->pool, 5);
726 rnew->err_headers_out = apr_table_make(rnew->pool, 5);
727 rnew->notes = apr_table_make(rnew->pool, 5);
729 rnew->expecting_100 = r->expecting_100;
730 rnew->read_length = r->read_length;
731 rnew->read_body = REQUEST_NO_BODY;
733 rnew->main = (request_rec *) r;
736 static void end_output_stream(request_rec *r)
738 apr_bucket_brigade *bb;
741 bb = apr_brigade_create(r->pool);
742 b = apr_bucket_eos_create();
743 APR_BRIGADE_INSERT_TAIL(bb, b);
744 ap_pass_brigade(r->output_filters, bb);
747 void ap_finalize_sub_req_protocol(request_rec *sub)
749 end_output_stream(sub);
752 /* finalize_request_protocol is called at completion of sending the
753 * response. Its sole purpose is to send the terminating protocol
754 * information for any wrappers around the response message body
755 * (i.e., transfer encodings). It should have been named finalize_response.
757 AP_DECLARE(void) ap_finalize_request_protocol(request_rec *r)
762 /* tell the filter chain there is no more content coming */
764 end_output_stream(r);
769 * Support for the Basic authentication protocol, and a bit for Digest.
772 AP_DECLARE(void) ap_note_auth_failure(request_rec *r)
774 if (!strcasecmp(ap_auth_type(r), "Basic"))
775 ap_note_basic_auth_failure(r);
776 else if (!strcasecmp(ap_auth_type(r), "Digest"))
777 ap_note_digest_auth_failure(r);
780 AP_DECLARE(void) ap_note_basic_auth_failure(request_rec *r)
782 if (strcasecmp(ap_auth_type(r), "Basic"))
783 ap_note_auth_failure(r);
785 apr_table_setn(r->err_headers_out,
786 (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authenticate" : "WWW-Authenticate",
787 apr_pstrcat(r->pool, "Basic realm=\"", ap_auth_name(r), "\"",
791 AP_DECLARE(void) ap_note_digest_auth_failure(request_rec *r)
793 apr_table_setn(r->err_headers_out,
794 (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authenticate" : "WWW-Authenticate",
795 apr_psprintf(r->pool, "Digest realm=\"%s\", nonce=\"%llx\"",
796 ap_auth_name(r), r->request_time));
799 AP_DECLARE(int) ap_get_basic_auth_pw(request_rec *r, const char **pw)
801 const char *auth_line = apr_table_get(r->headers_in,
802 (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authorization"
806 if (!(t = ap_auth_type(r)) || strcasecmp(t, "Basic"))
809 if (!ap_auth_name(r)) {
810 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR,
811 0, r, "need AuthName: %s", r->uri);
812 return HTTP_INTERNAL_SERVER_ERROR;
816 ap_note_basic_auth_failure(r);
817 return HTTP_UNAUTHORIZED;
820 if (strcasecmp(ap_getword(r->pool, &auth_line, ' '), "Basic")) {
821 /* Client tried to authenticate using wrong auth scheme */
822 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
823 "client used wrong authentication scheme: %s", r->uri);
824 ap_note_basic_auth_failure(r);
825 return HTTP_UNAUTHORIZED;
828 while (*auth_line== ' ' || *auth_line== '\t') {
832 t = ap_pbase64decode(r->pool, auth_line);
833 /* Note that this allocation has to be made from r->connection->pool
834 * because it has the lifetime of the connection. The other allocations
835 * are temporary and can be tossed away any time.
837 r->user = ap_getword_nulls (r->pool, &t, ':');
838 r->ap_auth_type = "Basic";
845 struct content_length_ctx {
846 apr_bucket_brigade *saved;
851 /* This filter computes the content length, but it also computes the number
852 * of bytes sent to the client. This means that this filter will always run
853 * through all of the buckets in all brigades
855 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_content_length_filter(ap_filter_t *f,
856 apr_bucket_brigade *b)
858 request_rec *r = f->r;
859 struct content_length_ctx *ctx;
865 if (!ctx) { /* first time through */
866 f->ctx = ctx = apr_pcalloc(r->pool, sizeof(struct content_length_ctx));
869 APR_BRIGADE_FOREACH(e, b) {
873 if (APR_BUCKET_IS_EOS(e) || APR_BUCKET_IS_FLUSH(e)) {
876 if (e->length == -1) { /* if length unknown */
877 rv = apr_bucket_read(e, &ignored, &length, APR_BLOCK_READ);
878 if (rv != APR_SUCCESS) {
885 ctx->curr_len += length;
886 r->bytes_sent += length;
889 if ((ctx->curr_len < AP_MIN_BYTES_TO_WRITE) && !send_it) {
890 return ap_save_brigade(f, &ctx->saved, &b);
893 /* We will compute a content length if:
894 * The protocol is < 1.1
895 * and We can not chunk
896 * and this is a keepalive request.
897 * or We already have all the data
898 * This is a bit confusing, because we will always buffer up
899 * to AP_MIN_BYTES_TO_WRITE, so if we get all the data while
900 * we are buffering that much data, we set the c-l.
902 if ((r->proto_num < HTTP_VERSION(1,1)
903 && (!ap_find_last_token(f->r->pool,
904 apr_table_get(r->headers_out,
905 "Transfer-Encoding"),
907 && (f->r->connection->keepalive)))
908 || (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(b)))) {
909 ctx->compute_len = 1;
912 ctx->compute_len = 0;
915 if (ctx->compute_len) {
916 /* save the brigade; we can't pass any data to the next
917 * filter until we have the entire content length
920 ap_save_brigade(f, &ctx->saved, &b);
923 ap_set_content_length(r, r->bytes_sent);
926 APR_BRIGADE_CONCAT(ctx->saved, b);
927 apr_brigade_destroy(b);
933 return ap_pass_brigade(f->next, b);
937 * Send the body of a response to the client.
939 AP_DECLARE(apr_status_t) ap_send_fd(apr_file_t *fd, request_rec *r, apr_off_t offset,
940 apr_size_t len, apr_size_t *nbytes)
942 apr_bucket_brigade *bb = NULL;
946 bb = apr_brigade_create(r->pool);
947 b = apr_bucket_file_create(fd, offset, len);
948 APR_BRIGADE_INSERT_TAIL(bb, b);
950 rv = ap_pass_brigade(r->output_filters, bb);
951 if (rv != APR_SUCCESS) {
952 *nbytes = 0; /* no way to tell how many were actually sent */
962 /* send data from an in-memory buffer */
963 AP_DECLARE(size_t) ap_send_mmap(apr_mmap_t *mm, request_rec *r, size_t offset,
966 apr_bucket_brigade *bb = NULL;
969 bb = apr_brigade_create(r->pool);
970 b = apr_bucket_mmap_create(mm, offset, length);
971 APR_BRIGADE_INSERT_TAIL(bb, b);
972 ap_pass_brigade(r->output_filters, bb);
974 return mm->size; /* XXX - change API to report apr_status_t? */
976 #endif /* APR_HAS_MMAP */
979 apr_bucket_brigade *bb;
980 } old_write_filter_ctx;
982 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_old_write_filter(
983 ap_filter_t *f, apr_bucket_brigade *bb)
985 old_write_filter_ctx *ctx = f->ctx;
987 AP_DEBUG_ASSERT(ctx);
990 /* whatever is coming down the pipe (we don't care), we
991 * can simply insert our buffered data at the front and
992 * pass the whole bundle down the chain.
994 APR_BRIGADE_CONCAT(ctx->bb, bb);
997 return ap_pass_brigade(f->next, ctx->bb);
1000 static apr_status_t buffer_output(request_rec *r,
1001 const char *str, apr_size_t len)
1004 old_write_filter_ctx *ctx;
1009 /* future optimization: record some flags in the request_rec to
1010 * say whether we've added our filter, and whether it is first.
1013 /* this will typically exit on the first test */
1014 for (f = r->output_filters; f != NULL; f = f->next)
1015 if (strcmp("OLD_WRITE", f->frec->name) == 0)
1018 /* our filter hasn't been added yet */
1019 ctx = apr_pcalloc(r->pool, sizeof(*ctx));
1020 ap_add_output_filter("OLD_WRITE", ctx, r, r->connection);
1021 f = r->output_filters;
1024 /* if the first filter is not our buffering filter, then we have to
1025 * deliver the content through the normal filter chain */
1026 if (f != r->output_filters) {
1027 apr_bucket_brigade *bb = apr_brigade_create(r->pool);
1028 apr_bucket *b = apr_bucket_transient_create(str, len);
1029 APR_BRIGADE_INSERT_TAIL(bb, b);
1031 return ap_pass_brigade(r->output_filters, bb);
1034 /* grab the context from our filter */
1035 ctx = r->output_filters->ctx;
1037 if (ctx->bb == NULL) {
1038 ctx->bb = apr_brigade_create(r->pool);
1041 ap_fwrite(f->next, ctx->bb, str, len);
1046 AP_DECLARE(int) ap_rputc(int c, request_rec *r)
1050 if (r->connection->aborted) {
1054 if (buffer_output(r, &c2, 1) != APR_SUCCESS)
1060 AP_DECLARE(int) ap_rputs(const char *str, request_rec *r)
1064 if (r->connection->aborted)
1067 if (buffer_output(r, str, len = strlen(str)) != APR_SUCCESS)
1073 AP_DECLARE(int) ap_rwrite(const void *buf, int nbyte, request_rec *r)
1075 if (r->connection->aborted)
1078 if (buffer_output(r, buf, nbyte) != APR_SUCCESS)
1084 AP_DECLARE(int) ap_vrprintf(request_rec *r, const char *fmt, va_list va)
1089 if (r->connection->aborted)
1092 /* ### fix this mechanism to allow more than 4K of output */
1093 written = apr_vsnprintf(buf, sizeof(buf), fmt, va);
1094 if (buffer_output(r, buf, written) != APR_SUCCESS)
1100 AP_DECLARE_NONSTD(int) ap_rprintf(request_rec *r, const char *fmt, ...)
1105 if (r->connection->aborted)
1109 n = ap_vrprintf(r, fmt, va);
1115 AP_DECLARE_NONSTD(int) ap_rvputs(request_rec *r, ...)
1120 apr_size_t written = 0;
1122 if (r->connection->aborted)
1125 /* ### TODO: if the total output is large, put all the strings
1126 ### into a single brigade, rather than flushing each time we
1127 ### fill the buffer */
1130 s = va_arg(va, const char *);
1135 if (buffer_output(r, s, len) != APR_SUCCESS) {
1146 AP_DECLARE(int) ap_rflush(request_rec *r)
1148 apr_bucket_brigade *bb;
1151 bb = apr_brigade_create(r->pool);
1152 b = apr_bucket_flush_create();
1153 APR_BRIGADE_INSERT_TAIL(bb, b);
1154 if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS)
1160 * This function sets the Last-Modified output header field to the value
1161 * of the mtime field in the request structure - rationalized to keep it from
1162 * being in the future.
1164 AP_DECLARE(void) ap_set_last_modified(request_rec *r)
1166 apr_time_t mod_time = ap_rationalize_mtime(r, r->mtime);
1167 char *datestr = apr_palloc(r->pool, APR_RFC822_DATE_LEN);
1168 apr_rfc822_date(datestr, mod_time);
1169 apr_table_setn(r->headers_out, "Last-Modified", datestr);
1172 AP_IMPLEMENT_HOOK_RUN_ALL(int,post_read_request,
1173 (request_rec *r),(r),OK,DECLINED)
1174 AP_IMPLEMENT_HOOK_RUN_ALL(int,log_transaction,
1175 (request_rec *r),(r),OK,DECLINED)
1176 AP_IMPLEMENT_HOOK_RUN_FIRST(const char *,http_method,
1177 (const request_rec *r),(r),NULL)
1178 AP_IMPLEMENT_HOOK_RUN_FIRST(unsigned short,default_port,
1179 (const request_rec *r),(r),0)