]> granicus.if.org Git - apache/blob - server/protocol.c
Optimization: changed some apr_pstrndup calls to apr_pstrmemdup
[apache] / server / protocol.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2001 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
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
17  *    distribution.
18  *
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.
25  *
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.
30  *
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.
34  *
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
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
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/>.
53  *
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.
57  */
58
59 /*
60  * http_protocol.c --- routines which directly communicate with the client.
61  *
62  * Code originally by Rob McCool; much redone by Robert S. Thau
63  * and the Apache Software Foundation.
64  */
65
66 #include "apr.h"
67 #include "apr_strings.h"
68 #include "apr_buckets.h"
69 #include "apr_lib.h"
70 #include "apr_signal.h"
71
72 #define APR_WANT_STDIO          /* for sscanf */
73 #define APR_WANT_STRFUNC
74 #define APR_WANT_MEMFUNC
75 #include "apr_want.h"
76
77 #define CORE_PRIVATE
78 #include "util_filter.h"
79 #include "ap_config.h"
80 #include "httpd.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
88                                  * support code... */
89 #include "util_charset.h"
90 #include "util_ebcdic.h"
91
92 #if APR_HAVE_STDARG_H
93 #include <stdarg.h>
94 #endif
95 #if APR_HAVE_UNISTD_H
96 #include <unistd.h>
97 #endif
98
99
100 APR_HOOK_STRUCT(
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)
105 )
106
107 AP_DECLARE_DATA ap_filter_rec_t *ap_old_write_func;
108
109 /*
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
115  *    - return type
116  */
117 AP_DECLARE(const char *)ap_make_content_type(request_rec *r, const char *type)
118 {
119     static const char *needcset[] = {
120         "text/plain",
121         "text/html",
122         NULL };
123     const char **pcset;
124     core_dir_config *conf =
125         (core_dir_config *)ap_get_module_config(r->per_dir_config,
126                                                 &core_module);
127
128     if (!type) {
129         type = ap_default_type(r);
130     }
131     if (conf->add_default_charset != ADD_DEFAULT_CHARSET_ON) {
132         return type;
133     }
134
135     if (ap_strcasestr(type, "charset=") != NULL) {
136         /* already has parameter, do nothing */
137         /* XXX we don't check the validity */
138         ;
139     }
140     else {
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[]
143          */
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);
148                 break;
149             }
150         }
151     }
152     return type;
153 }
154
155 AP_DECLARE(void) ap_set_content_length(request_rec *r, apr_off_t clength)
156 {
157     r->clength = clength;
158     apr_table_setn(r->headers_out, "Content-Length",
159                    apr_off_t_toa(r->pool, clength));
160 }
161
162 /*
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.
168  */
169 AP_DECLARE(apr_time_t) ap_rationalize_mtime(request_rec *r, apr_time_t mtime)
170 {
171     apr_time_t now;
172
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.
181      */
182     now = (mtime < r->request_time) ? r->request_time : apr_time_now();
183     return (mtime > now) ? now : mtime;
184 }
185
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.
189  *
190  * Returns: 
191  *     the length of s (normal case),
192  *     n               (buffer full),
193  *    -1               (other errors)
194  *
195  * Notes: Because the buffer uses 1 char for NUL, the most we can return is 
196  *        (n - 1) actual characters.  
197  *
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.
200  */
201 AP_DECLARE(int) ap_getline(char *s, int n, request_rec *r, int fold)
202 {
203     char *pos = s;
204     char *last_char;
205     char *beyond_buff = s + n;
206     const char *temp;
207     int retval;
208     int total = 0;
209     int looking_ahead = 0;
210     apr_size_t length;
211     core_request_config *req_cfg;
212     apr_bucket_brigade *b;
213     apr_bucket *e;
214
215     req_cfg = (core_request_config *)
216                 ap_get_module_config(r->request_config, &core_module);
217     b = req_cfg->bb;
218     /* make sure it's empty unless we're folding */ 
219     AP_DEBUG_ASSERT(fold || APR_BRIGADE_EMPTY(b));
220
221     while (1) {
222         if (APR_BRIGADE_EMPTY(b)) {
223             apr_off_t zero = 0;
224             if ((retval = ap_get_brigade(r->input_filters, b,
225                                          AP_MODE_BLOCKING,
226                                          &zero /* readline */)) != APR_SUCCESS ||
227                 APR_BRIGADE_EMPTY(b)) {
228                 apr_brigade_destroy(b);
229                 return -1;
230             }
231         }
232         e = APR_BRIGADE_FIRST(b); 
233         if (APR_BUCKET_IS_EOS(e)) {
234             apr_brigade_destroy(b);
235             return -1;
236         }
237         if (e->length == 0) {
238             apr_bucket_delete(e);
239             continue;
240         }
241         retval = apr_bucket_read(e, &temp, &length, APR_BLOCK_READ);
242         if (retval != APR_SUCCESS) {
243             apr_brigade_destroy(b);
244             ap_log_rerror(APLOG_MARK, APLOG_ERR, retval, r, "apr_bucket_read() failed");
245             if (total) {
246                 break; /* report previously-read data to caller, do ap_xlate_proto_to_ascii() */
247             }
248             else {
249                 return -1;
250             }
251         }
252
253         if ((looking_ahead) && (*temp != APR_ASCII_BLANK) && (*temp != APR_ASCII_TAB)) { 
254             /* can't fold because next line isn't indented, 
255              * so return what we have.  lookahead brigade is 
256              * stashed on req_cfg->bb
257              */
258             AP_DEBUG_ASSERT(!APR_BRIGADE_EMPTY(req_cfg->bb));
259             break;
260         }
261         last_char = pos + length - 1;
262         if (last_char < beyond_buff) {
263             memcpy(pos, temp, length);
264             apr_bucket_delete(e);
265         }
266         else {
267             /* input line was larger than the caller's buffer */
268             apr_brigade_destroy(b); 
269
270             /* don't need to worry about req_cfg->bb being bogus.
271              * the request is about to die, and ErrorDocument
272              * redirects get a new req_cfg->bb
273              */
274
275             return n;
276         }
277         
278         pos = last_char;        /* Point at the last character           */
279
280         if (*pos == APR_ASCII_LF) { /* Did we get a full line of input?      */
281                 
282             if (pos > s && *(pos - 1) == APR_ASCII_CR) {
283                 --pos;          /* zap optional CR before LF             */
284             }
285                 
286             /*
287              * Trim any extra trailing spaces or tabs except for the first
288              * space or tab at the beginning of a blank string.  This makes
289              * it much easier to check field values for exact matches, and
290              * saves memory as well.  Terminate string at end of line.
291              */
292             while (pos > (s + 1) && 
293                    (*(pos - 1) == APR_ASCII_BLANK || *(pos - 1) == APR_ASCII_TAB)) {
294                 --pos;          /* trim extra trailing spaces or tabs    */
295             }
296             *pos = '\0';        /* zap end of string                     */
297             total = pos - s;    /* update total string length            */
298
299             /* look ahead another line if line folding is desired 
300              * and this line isn't empty
301              */
302             if (fold && total) {
303                 looking_ahead = 1;
304             }
305             else {
306                 AP_DEBUG_ASSERT(APR_BRIGADE_EMPTY(req_cfg->bb));
307                 break;
308             }
309         }
310         else {
311             /* no LF yet...character mode client (telnet)...keep going
312              * bump past last character read,   
313              * and set total in case we bail before finding a LF   
314              */
315             total = ++pos - s;    
316             looking_ahead = 0;  /* only appropriate right after LF       */ 
317         }
318     }
319     ap_xlate_proto_from_ascii(s, total);
320     return total;
321 }
322
323 /* parse_uri: break apart the uri
324  * Side Effects:
325  * - sets r->args to rest after '?' (or NULL if no '?')
326  * - sets r->uri to request uri (without r->args part)
327  * - sets r->hostname (if not set already) from request (scheme://host:port)
328  */
329 AP_CORE_DECLARE(void) ap_parse_uri(request_rec *r, const char *uri)
330 {
331     int status = HTTP_OK;
332
333     r->unparsed_uri = apr_pstrdup(r->pool, uri);
334
335     if (r->method_number == M_CONNECT) {
336         status = apr_uri_parse_hostinfo(r->pool, uri, &r->parsed_uri);
337     }
338     else {
339         /* Simple syntax Errors in URLs are trapped by parse_uri_components(). */
340         status = apr_uri_parse(r->pool, uri, &r->parsed_uri);
341     }
342
343     if (status == APR_SUCCESS) {
344         /* if it has a scheme we may need to do absoluteURI vhost stuff */
345         if (r->parsed_uri.scheme
346             && !strcasecmp(r->parsed_uri.scheme, ap_http_method(r))) {
347             r->hostname = r->parsed_uri.hostname;
348         }
349         else if (r->method_number == M_CONNECT) {
350             r->hostname = r->parsed_uri.hostname;
351         }
352         r->args = r->parsed_uri.query;
353         r->uri = r->parsed_uri.path ? r->parsed_uri.path
354                                     : apr_pstrdup(r->pool, "/");
355 #if defined(OS2) || defined(WIN32)
356         /* Handle path translations for OS/2 and plug security hole.
357          * This will prevent "http://www.wherever.com/..\..\/" from
358          * returning a directory for the root drive.
359          */
360         {
361             char *x;
362
363             for (x = r->uri; (x = strchr(x, '\\')) != NULL; )
364                 *x = '/';
365         }
366 #endif  /* OS2 || WIN32 */
367     }
368     else {
369         r->args = NULL;
370         r->hostname = NULL;
371         r->status = HTTP_BAD_REQUEST;             /* set error status */
372         r->uri = apr_pstrdup(r->pool, uri);
373     }
374 }
375
376 static int read_request_line(request_rec *r)
377 {
378     char l[DEFAULT_LIMIT_REQUEST_LINE + 2]; /* getline's two extra for \n\0 */
379     const char *ll = l;
380     const char *uri;
381     const char *pro;
382
383 #if 0
384     conn_rec *conn = r->connection;
385 #endif
386     int major = 1, minor = 0;   /* Assume HTTP/1.0 if non-"HTTP" protocol */
387     int len;
388
389     /* Read past empty lines until we get a real request line,
390      * a read error, the connection closes (EOF), or we timeout.
391      *
392      * We skip empty lines because browsers have to tack a CRLF on to the end
393      * of POSTs to support old CERN webservers.  But note that we may not
394      * have flushed any previous response completely to the client yet.
395      * We delay the flush as long as possible so that we can improve
396      * performance for clients that are pipelining requests.  If a request
397      * is pipelined then we won't block during the (implicit) read() below.
398      * If the requests aren't pipelined, then the client is still waiting
399      * for the final buffer flush from us, and we will block in the implicit
400      * read().  B_SAFEREAD ensures that the BUFF layer flushes if it will
401      * have to block during a read.
402      */
403
404     while ((len = ap_getline(l, sizeof(l), r, 0)) <= 0) {
405         if (len < 0) {             /* includes EOF */
406             /* this is a hack to make sure that request time is set,
407              * it's not perfect, but it's better than nothing 
408              */
409             r->request_time = apr_time_now();
410             return 0;
411         }
412     }
413     /* we've probably got something to do, ignore graceful restart requests */
414
415     r->request_time = apr_time_now();
416     r->the_request = apr_pstrdup(r->pool, l);
417     r->method = ap_getword_white(r->pool, &ll);
418
419 #if 0
420 /* XXX If we want to keep track of the Method, the protocol module should do
421  * it.  That support isn't in the scoreboard yet.  Hopefully next week 
422  * sometime.   rbb */
423     ap_update_connection_status(AP_CHILD_THREAD_FROM_ID(conn->id), "Method", r->method); 
424 #endif
425     uri = ap_getword_white(r->pool, &ll);
426
427     /* Provide quick information about the request method as soon as known */
428
429     r->method_number = ap_method_number_of(r->method);
430     if (r->method_number == M_GET && r->method[0] == 'H') {
431         r->header_only = 1;
432     }
433
434     ap_parse_uri(r, uri);
435
436     /* ap_getline returns (size of max buffer - 1) if it fills up the
437      * buffer before finding the end-of-line.  This is only going to
438      * happen if it exceeds the configured limit for a request-line.
439      */
440     if (len > r->server->limit_req_line) {
441         r->status    = HTTP_REQUEST_URI_TOO_LARGE;
442         r->proto_num = HTTP_VERSION(1,0);
443         r->protocol  = apr_pstrdup(r->pool, "HTTP/1.0");
444         return 0;
445     }
446
447     if (ll[0]) {
448         r->assbackwards = 0;
449         pro = ll;
450         len = strlen(ll);
451     } else {
452         r->assbackwards = 1;
453         pro = "HTTP/0.9";
454         len = 8;
455     }
456     r->protocol = apr_pstrmemdup(r->pool, pro, len);
457
458     /* XXX ap_update_connection_status(conn->id, "Protocol", r->protocol); */
459
460     /* Avoid sscanf in the common case */
461     if (len == 8 &&
462         pro[0] == 'H' && pro[1] == 'T' && pro[2] == 'T' && pro[3] == 'P' &&
463         pro[4] == '/' && apr_isdigit(pro[5]) && pro[6] == '.' &&
464         apr_isdigit(pro[7])) {
465         r->proto_num = HTTP_VERSION(pro[5] - '0', pro[7] - '0');
466     } else if (2 == sscanf(r->protocol, "HTTP/%u.%u", &major, &minor)
467                && minor < HTTP_VERSION(1,0))    /* don't allow HTTP/0.1000 */
468         r->proto_num = HTTP_VERSION(major, minor);
469     else
470         r->proto_num = HTTP_VERSION(1,0);
471
472     return 1;
473 }
474
475 static void get_mime_headers(request_rec *r)
476 {
477     char field[DEFAULT_LIMIT_REQUEST_FIELDSIZE + 2]; /* getline's two extra */
478     char *value;
479     char *copy;
480     int len;
481     int fields_read = 0;
482     apr_table_t *tmp_headers;
483
484     /* We'll use apr_table_overlap later to merge these into r->headers_in. */
485     tmp_headers = apr_table_make(r->pool, 50);
486
487     /*
488      * Read header lines until we get the empty separator line, a read error,
489      * the connection closes (EOF), reach the server limit, or we timeout.
490      */
491     while ((len = ap_getline(field, sizeof(field), r, 1)) > 0) {
492
493         if (r->server->limit_req_fields &&
494             (++fields_read > r->server->limit_req_fields)) {
495             r->status = HTTP_BAD_REQUEST;
496             apr_table_setn(r->notes, "error-notes",
497                            "The number of request header fields exceeds "
498                            "this server's limit.");
499             return;
500         }
501         /* ap_getline returns (size of max buffer - 1) if it fills up the
502          * buffer before finding the end-of-line.  This is only going to
503          * happen if it exceeds the configured limit for a field size.
504          */
505         if (len > r->server->limit_req_fieldsize) {
506             r->status = HTTP_BAD_REQUEST;
507             apr_table_setn(r->notes, "error-notes",
508                            apr_pstrcat(r->pool,
509                                        "Size of a request header field "
510                                        "exceeds server limit.<br />\n"
511                                        "<pre>\n",
512                                        ap_escape_html(r->pool, field),
513                                        "</pre>\n", NULL));
514             return;
515         }
516         copy = apr_palloc(r->pool, len + 1);
517         memcpy(copy, field, len + 1);
518
519         if (!(value = strchr(copy, ':'))) {     /* Find the colon separator */
520             r->status = HTTP_BAD_REQUEST;       /* or abort the bad request */
521             apr_table_setn(r->notes, "error-notes",
522                            apr_pstrcat(r->pool,
523                                        "Request header field is missing "
524                                        "colon separator.<br />\n"
525                                        "<pre>\n",
526                                        ap_escape_html(r->pool, copy),
527                                        "</pre>\n", NULL));
528             return;
529         }
530
531         *value = '\0';
532         ++value;
533         while (*value == ' ' || *value == '\t') {
534             ++value;            /* Skip to start of value   */
535         }
536
537         apr_table_addn(tmp_headers, copy, value);
538     }
539
540     apr_table_overlap(r->headers_in, tmp_headers, APR_OVERLAP_TABLES_MERGE);
541 }
542
543 request_rec *ap_read_request(conn_rec *conn)
544 {
545     request_rec *r;
546     apr_pool_t *p;
547     const char *expect;
548     int access_status;
549
550     apr_pool_create(&p, conn->pool);
551     r = apr_pcalloc(p, sizeof(request_rec));
552     r->pool            = p;
553     r->connection      = conn;
554     r->server          = conn->base_server;
555
556     r->user            = NULL;
557     r->ap_auth_type    = NULL;
558
559     r->allowed_methods = ap_make_method_list(p, 2);
560
561     r->headers_in      = apr_table_make(r->pool, 50);
562     r->subprocess_env  = apr_table_make(r->pool, 50);
563     r->headers_out     = apr_table_make(r->pool, 12);
564     r->err_headers_out = apr_table_make(r->pool, 5);
565     r->notes           = apr_table_make(r->pool, 5);
566
567     r->request_config  = ap_create_request_config(r->pool);
568     /* Must be set before we run create request hook */
569     r->output_filters  = conn->output_filters;
570     r->input_filters   = conn->input_filters;
571     ap_run_create_request(r);
572     r->per_dir_config  = r->server->lookup_defaults;
573
574     r->sent_bodyct     = 0;                      /* bytect isn't for body */
575
576     r->read_length     = 0;
577     r->read_body       = REQUEST_NO_BODY;
578
579     r->status          = HTTP_REQUEST_TIME_OUT;  /* Until we get a request */
580     r->the_request     = NULL;
581
582     /* Get the request... */
583     if (!read_request_line(r)) {
584         if (r->status == HTTP_REQUEST_URI_TOO_LARGE) {
585             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
586                           "request failed: URI too long");
587             ap_send_error_response(r, 0);
588             ap_run_log_transaction(r);
589             return r;
590         }
591         return NULL;
592     }
593
594     if (!r->assbackwards) {
595         get_mime_headers(r);
596         if (r->status != HTTP_REQUEST_TIME_OUT) {
597             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
598                           "request failed: error reading the headers");
599             ap_send_error_response(r, 0);
600             ap_run_log_transaction(r);
601             return r;
602         }
603     }
604     else {
605         if (r->header_only) {
606             /*
607              * Client asked for headers only with HTTP/0.9, which doesn't send
608              * headers! Have to dink things just to make sure the error message
609              * comes through...
610              */
611             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
612                           "client sent invalid HTTP/0.9 request: HEAD %s",
613                           r->uri);
614             r->header_only = 0;
615             r->status = HTTP_BAD_REQUEST;
616             ap_send_error_response(r, 0);
617             ap_run_log_transaction(r);
618             return r;
619         }
620     }
621
622     r->status = HTTP_OK;                         /* Until further notice. */
623
624     /* update what we think the virtual host is based on the headers we've
625      * now read. may update status.
626      */
627     ap_update_vhost_from_headers(r);
628
629     /* we may have switched to another server */
630     r->per_dir_config = r->server->lookup_defaults;
631
632     if ((!r->hostname && (r->proto_num >= HTTP_VERSION(1,1))) ||
633         ((r->proto_num == HTTP_VERSION(1,1)) &&
634          !apr_table_get(r->headers_in, "Host"))) {
635         /*
636          * Client sent us an HTTP/1.1 or later request without telling us the
637          * hostname, either with a full URL or a Host: header. We therefore
638          * need to (as per the 1.1 spec) send an error.  As a special case,
639          * HTTP/1.1 mentions twice (S9, S14.23) that a request MUST contain
640          * a Host: header, and the server MUST respond with 400 if it doesn't.
641          */
642         r->status = HTTP_BAD_REQUEST;
643         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
644                       "client sent HTTP/1.1 request without hostname "
645                       "(see RFC2616 section 14.23): %s", r->uri);
646     }
647     if (r->status != HTTP_OK) {
648         ap_send_error_response(r, 0);
649         ap_run_log_transaction(r);
650         return r;
651     }
652     if (((expect = apr_table_get(r->headers_in, "Expect")) != NULL) &&
653         (expect[0] != '\0')) {
654         /*
655          * The Expect header field was added to HTTP/1.1 after RFC 2068
656          * as a means to signal when a 100 response is desired and,
657          * unfortunately, to signal a poor man's mandatory extension that
658          * the server must understand or return 417 Expectation Failed.
659          */
660         if (strcasecmp(expect, "100-continue") == 0) {
661             r->expecting_100 = 1;
662         }
663         else {
664             r->status = HTTP_EXPECTATION_FAILED;
665             ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r,
666                           "client sent an unrecognized expectation value of "
667                           "Expect: %s", expect);
668             ap_send_error_response(r, 0);
669             (void) ap_discard_request_body(r);
670             ap_run_log_transaction(r);
671             return r;
672         }
673     }
674
675     ap_add_input_filter("HTTP_IN", NULL, r, r->connection);
676
677     if ((access_status = ap_run_post_read_request(r))) {
678         ap_die(access_status, r);
679         ap_run_log_transaction(r);
680         return NULL;
681     }
682
683     return r;
684 }
685
686 /*
687  * A couple of other functions which initialize some of the fields of
688  * a request structure, as appropriate for adjuncts of one kind or another
689  * to a request in progress.  Best here, rather than elsewhere, since
690  * *someone* has to set the protocol-specific fields...
691  */
692
693 void ap_set_sub_req_protocol(request_rec *rnew, const request_rec *r)
694 {
695     rnew->the_request     = r->the_request;  /* Keep original request-line */
696
697     rnew->assbackwards    = 1;   /* Don't send headers from this. */
698     rnew->no_local_copy   = 1;   /* Don't try to send HTTP_NOT_MODIFIED for a
699                                   * fragment. */
700     rnew->method          = "GET";
701     rnew->method_number   = M_GET;
702     rnew->protocol        = "INCLUDED";
703
704     rnew->status          = HTTP_OK;
705
706     rnew->headers_in      = r->headers_in;
707     rnew->subprocess_env  = apr_table_copy(rnew->pool, r->subprocess_env);
708     rnew->headers_out     = apr_table_make(rnew->pool, 5);
709     rnew->err_headers_out = apr_table_make(rnew->pool, 5);
710     rnew->notes           = apr_table_make(rnew->pool, 5);
711
712     rnew->expecting_100   = r->expecting_100;
713     rnew->read_length     = r->read_length;
714     rnew->read_body       = REQUEST_NO_BODY;
715
716     rnew->main = (request_rec *) r;
717 }
718
719 static void end_output_stream(request_rec *r)
720 {
721     apr_bucket_brigade *bb;
722     apr_bucket *b;
723
724     bb = apr_brigade_create(r->pool);
725     b = apr_bucket_eos_create();
726     APR_BRIGADE_INSERT_TAIL(bb, b);
727     ap_pass_brigade(r->output_filters, bb);
728 }
729
730 void ap_finalize_sub_req_protocol(request_rec *sub)
731 {
732     end_output_stream(sub); 
733 }
734
735 /* finalize_request_protocol is called at completion of sending the
736  * response.  Its sole purpose is to send the terminating protocol
737  * information for any wrappers around the response message body
738  * (i.e., transfer encodings).  It should have been named finalize_response.
739  */
740 AP_DECLARE(void) ap_finalize_request_protocol(request_rec *r)
741 {
742     while (r->next) {
743         r = r->next;
744     }
745     /* tell the filter chain there is no more content coming */
746     if (!r->eos_sent) {
747         end_output_stream(r);
748     }
749
750
751 /*
752  * Support for the Basic authentication protocol, and a bit for Digest.
753  */
754
755 AP_DECLARE(void) ap_note_auth_failure(request_rec *r)
756 {
757     const char *type = ap_auth_type(r);
758     if (type) {
759         if (!strcasecmp(type, "Basic"))
760             ap_note_basic_auth_failure(r);
761         else if (!strcasecmp(type, "Digest"))
762             ap_note_digest_auth_failure(r);
763     }
764     else {
765         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR,
766                       0, r, "need AuthType to note auth failure: %s", r->uri);
767     }
768 }
769
770 AP_DECLARE(void) ap_note_basic_auth_failure(request_rec *r)
771 {
772     const char *type = ap_auth_type(r);
773     /* if there is no AuthType configure or it is something other than
774      * Basic, let ap_note_auth_failure() deal with it
775      */
776     if (!type || strcasecmp(type, "Basic"))
777         ap_note_auth_failure(r);
778     else
779         apr_table_setn(r->err_headers_out,
780                   (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authenticate" : "WWW-Authenticate",
781                   apr_pstrcat(r->pool, "Basic realm=\"", ap_auth_name(r), "\"",
782                           NULL));
783 }
784
785 AP_DECLARE(void) ap_note_digest_auth_failure(request_rec *r)
786 {
787     apr_table_setn(r->err_headers_out,
788             (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authenticate" : "WWW-Authenticate",
789             apr_psprintf(r->pool, "Digest realm=\"%s\", nonce=\"%llx\"",
790                 ap_auth_name(r), r->request_time));
791 }
792
793 AP_DECLARE(int) ap_get_basic_auth_pw(request_rec *r, const char **pw)
794 {
795     const char *auth_line = apr_table_get(r->headers_in,
796                                       (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authorization"
797                                                   : "Authorization");
798     const char *t;
799
800     if (!(t = ap_auth_type(r)) || strcasecmp(t, "Basic"))
801         return DECLINED;
802
803     if (!ap_auth_name(r)) {
804         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR,
805                       0, r, "need AuthName: %s", r->uri);
806         return HTTP_INTERNAL_SERVER_ERROR;
807     }
808
809     if (!auth_line) {
810         ap_note_basic_auth_failure(r);
811         return HTTP_UNAUTHORIZED;
812     }
813
814     if (strcasecmp(ap_getword(r->pool, &auth_line, ' '), "Basic")) {
815         /* Client tried to authenticate using wrong auth scheme */
816         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
817                       "client used wrong authentication scheme: %s", r->uri);
818         ap_note_basic_auth_failure(r);
819         return HTTP_UNAUTHORIZED;
820     }
821
822     while (*auth_line== ' ' || *auth_line== '\t') {
823         auth_line++;
824     }
825
826     t = ap_pbase64decode(r->pool, auth_line);
827     /* Note that this allocation has to be made from r->connection->pool
828      * because it has the lifetime of the connection.  The other allocations
829      * are temporary and can be tossed away any time.
830      */
831     r->user = ap_getword_nulls (r->pool, &t, ':');
832     r->ap_auth_type = "Basic";
833
834     *pw = t;
835
836     return OK;
837 }
838
839 struct content_length_ctx {
840     apr_bucket_brigade *saved;
841     int compute_len;
842     apr_size_t curr_len;
843 };
844
845 /* This filter computes the content length, but it also computes the number
846  * of bytes sent to the client.  This means that this filter will always run
847  * through all of the buckets in all brigades 
848  */
849 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_content_length_filter(ap_filter_t *f,
850                                                               apr_bucket_brigade *b)
851 {
852     request_rec *r = f->r;
853     struct content_length_ctx *ctx;
854     apr_status_t rv;
855     apr_bucket *e;
856     int eos = 0, flush = 0, partial_send_okay = 0;
857     apr_bucket_brigade *more, *split;
858     apr_read_type_e eblock = APR_NONBLOCK_READ;
859
860     ctx = f->ctx;
861     if (!ctx) { /* first time through */
862         f->ctx = ctx = apr_pcalloc(r->pool, sizeof(struct content_length_ctx));
863         ctx->compute_len = 1;   /* Assume we will compute the length */
864     }
865
866     /* Humm, is this check the best it can be? 
867      * - protocol >= HTTP/1.1 implies support for chunking 
868      * - non-keepalive implies the end of byte stream will be signaled
869      *    by a connection close
870      * In both cases, we can send bytes to the client w/o needing to
871      * compute content-length. 
872      * Todo: 
873      * We should be able to force connection close from this filter
874      * when we see we are buffering too much. 
875      */
876     if ((r->proto_num >= HTTP_VERSION(1,1)) ||
877         (!f->r->connection->keepalive)) {
878         partial_send_okay = 1;
879     }
880
881     more = b;
882     while (more) {
883         b = more;
884         more = NULL;
885         split = NULL;
886         flush = 0;
887
888         APR_BRIGADE_FOREACH(e, b) {
889             const char *ignored;
890             apr_size_t len;
891             len = 0;
892             if (APR_BUCKET_IS_EOS(e)) {
893                 eos = 1;
894             }
895             else if (APR_BUCKET_IS_FLUSH(e)) {
896                 if (partial_send_okay) {
897                     split = b;
898                     more = apr_brigade_split(b, APR_BUCKET_NEXT(e));
899                     break;
900                 }
901             }
902             else if ((ctx->curr_len > 4*AP_MIN_BYTES_TO_WRITE)) {
903                 /* If we've accumulated more than 4xAP_MIN_BYTES_TO_WRITE and 
904                  * the client supports chunked encoding, send what we have 
905                  * and come back for more.
906                  */
907                 if (partial_send_okay) {
908                     split = b;
909                     more = apr_brigade_split(b, e);
910                     break;
911                 }
912             }
913             if (e->length == -1) { /* if length unknown */
914                 rv = apr_bucket_read(e, &ignored, &len, eblock);
915                 if (rv == APR_SUCCESS) {
916                     /* Attempt a nonblocking read next time through */
917                     eblock = APR_NONBLOCK_READ;
918                 }
919                 else if (APR_STATUS_IS_EAGAIN(rv)) {
920                     /* Make the next read blocking.  If the client supports chunked
921                      * encoding, flush the filter stack to the network.
922                      */
923                     eblock = APR_BLOCK_READ;
924                     if (partial_send_okay) {
925                         split = b;
926                         more = apr_brigade_split(b, e);
927                         flush = 1;
928                         break;
929                     }
930                 }
931                 else if (rv != APR_EOF) {
932                     ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, 
933                         "ap_content_length_filter: apr_bucket_read() failed");
934                     return rv;
935                 }
936             }
937             else {
938                 len = e->length;
939             }
940             ctx->curr_len += len;
941             r->bytes_sent += len;
942         }
943
944         if (split) {
945             ctx->compute_len = 0;  /* Ooops, can't compute the length now */
946             ctx->curr_len = 0;
947             if (ctx->saved) {
948                 APR_BRIGADE_CONCAT(ctx->saved, split);
949                 apr_brigade_destroy(split);
950                 split = ctx->saved;
951                 ctx->saved = NULL;
952             }
953             if (flush) {
954                 rv = ap_fflush(f->next, split);
955             }
956             else {
957                 rv = ap_pass_brigade(f->next, split);
958             }
959             if (rv != APR_SUCCESS)
960                 return rv;
961         }
962     }
963
964     if ((ctx->curr_len < AP_MIN_BYTES_TO_WRITE) && !eos) {
965         return ap_save_brigade(f, &ctx->saved, &b, (r->main) ? r->main->pool : r->pool);
966     }
967
968     if (ctx->compute_len) {
969         /* save the brigade; we can't pass any data to the next
970          * filter until we have the entire content length
971          */
972         if (!eos) {
973             return ap_save_brigade(f, &ctx->saved, &b, r->pool);
974         }
975         ap_set_content_length(r, r->bytes_sent);
976     }
977     if (ctx->saved) {
978         APR_BRIGADE_CONCAT(ctx->saved, b);
979         apr_brigade_destroy(b);
980         b = ctx->saved;
981         ctx->saved = NULL;
982     }
983
984     ctx->curr_len = 0;
985     return ap_pass_brigade(f->next, b);
986 }
987
988 /*
989  * Send the body of a response to the client.
990  */
991 AP_DECLARE(apr_status_t) ap_send_fd(apr_file_t *fd, request_rec *r, apr_off_t offset, 
992                                     apr_size_t len, apr_size_t *nbytes) 
993 {
994     apr_bucket_brigade *bb = NULL;
995     apr_bucket *b;
996     apr_status_t rv;
997
998     bb = apr_brigade_create(r->pool);
999     b = apr_bucket_file_create(fd, offset, len, r->pool);
1000     APR_BRIGADE_INSERT_TAIL(bb, b);
1001
1002     rv = ap_pass_brigade(r->output_filters, bb);
1003     if (rv != APR_SUCCESS) {
1004         *nbytes = 0; /* no way to tell how many were actually sent */
1005     }
1006     else {
1007         *nbytes = len;
1008     }
1009
1010     return rv;
1011 }
1012
1013 #if APR_HAS_MMAP
1014 /* send data from an in-memory buffer */
1015 AP_DECLARE(size_t) ap_send_mmap(apr_mmap_t *mm, request_rec *r, size_t offset,
1016                              size_t length)
1017 {
1018     apr_bucket_brigade *bb = NULL;
1019     apr_bucket *b;
1020
1021     bb = apr_brigade_create(r->pool);
1022     b = apr_bucket_mmap_create(mm, offset, length);
1023     APR_BRIGADE_INSERT_TAIL(bb, b);
1024     ap_pass_brigade(r->output_filters, bb);
1025
1026     return mm->size; /* XXX - change API to report apr_status_t? */
1027 }
1028 #endif /* APR_HAS_MMAP */
1029
1030 typedef struct {
1031     apr_bucket_brigade *bb;
1032 } old_write_filter_ctx;
1033
1034 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_old_write_filter(
1035     ap_filter_t *f, apr_bucket_brigade *bb)
1036 {
1037     old_write_filter_ctx *ctx = f->ctx;
1038
1039     AP_DEBUG_ASSERT(ctx);
1040
1041     if (ctx->bb != 0) {
1042         /* whatever is coming down the pipe (we don't care), we
1043          * can simply insert our buffered data at the front and
1044          * pass the whole bundle down the chain. 
1045          */
1046         APR_BRIGADE_CONCAT(ctx->bb, bb);
1047     }
1048
1049     return ap_pass_brigade(f->next, ctx->bb);
1050 }
1051
1052 static apr_status_t buffer_output(request_rec *r,
1053                                   const char *str, apr_size_t len)
1054 {
1055     ap_filter_t *f;
1056     old_write_filter_ctx *ctx;
1057
1058     if (len == 0)
1059         return APR_SUCCESS;
1060
1061     /* future optimization: record some flags in the request_rec to
1062      * say whether we've added our filter, and whether it is first.
1063      */
1064
1065     /* this will typically exit on the first test */
1066     for (f = r->output_filters; f != NULL; f = f->next)
1067         if (ap_old_write_func == f->frec)
1068             break;
1069     if (f == NULL) {
1070         /* our filter hasn't been added yet */
1071         ctx = apr_pcalloc(r->pool, sizeof(*ctx));
1072         ap_add_output_filter("OLD_WRITE", ctx, r, r->connection);
1073         f = r->output_filters;
1074     }
1075
1076     /* if the first filter is not our buffering filter, then we have to
1077      * deliver the content through the normal filter chain */
1078     if (f != r->output_filters) {
1079         apr_bucket_brigade *bb = apr_brigade_create(r->pool);
1080         apr_bucket *b = apr_bucket_transient_create(str, len);
1081         APR_BRIGADE_INSERT_TAIL(bb, b);
1082
1083         return ap_pass_brigade(r->output_filters, bb);
1084     }
1085
1086     /* grab the context from our filter */
1087     ctx = r->output_filters->ctx;
1088
1089     if (ctx->bb == NULL) {
1090         ctx->bb = apr_brigade_create(r->pool);
1091     }
1092
1093     return ap_fwrite(f->next, ctx->bb, str, len);
1094 }
1095
1096 AP_DECLARE(int) ap_rputc(int c, request_rec *r)
1097 {
1098     char c2 = (char)c;
1099
1100     if (r->connection->aborted) {
1101         return -1;
1102     }
1103
1104     if (buffer_output(r, &c2, 1) != APR_SUCCESS)
1105         return -1;
1106
1107     return c;
1108 }
1109
1110 AP_DECLARE(int) ap_rputs(const char *str, request_rec *r)
1111 {
1112     apr_size_t len;
1113
1114     if (r->connection->aborted)
1115         return -1;
1116
1117     if (buffer_output(r, str, len = strlen(str)) != APR_SUCCESS)
1118         return -1;
1119
1120     return len;
1121 }
1122
1123 AP_DECLARE(int) ap_rwrite(const void *buf, int nbyte, request_rec *r)
1124 {
1125     if (r->connection->aborted)
1126         return -1;
1127
1128     if (buffer_output(r, buf, nbyte) != APR_SUCCESS)
1129         return -1;
1130
1131     return nbyte;
1132 }
1133
1134 struct ap_vrprintf_data {
1135     apr_vformatter_buff_t vbuff;
1136     request_rec *r;
1137     char *buff;
1138 };
1139
1140 static apr_status_t r_flush(apr_vformatter_buff_t *buff)
1141 {
1142     /* callback function passed to ap_vformatter to be called when
1143      * vformatter needs to write into buff and buff.curpos > buff.endpos */
1144
1145     /* ap_vrprintf_data passed as a apr_vformatter_buff_t, which is then
1146      * "downcast" to an ap_vrprintf_data */
1147     struct ap_vrprintf_data *vd = (struct ap_vrprintf_data*)buff;
1148
1149     if (vd->r->connection->aborted)
1150         return -1;
1151
1152     /* r_flush is called when vbuff is completely full */
1153     if (buffer_output(vd->r, vd->buff, AP_IOBUFSIZE)) {
1154         return -1;
1155     }
1156
1157     /* reset the buffer position */
1158     vd->vbuff.curpos = vd->buff;
1159     vd->vbuff.endpos = vd->buff + AP_IOBUFSIZE;
1160
1161     return APR_SUCCESS;
1162 }
1163
1164 AP_DECLARE(int) ap_vrprintf(request_rec *r, const char *fmt, va_list va)
1165 {
1166     apr_size_t written;
1167     struct ap_vrprintf_data vd;
1168     char vrprintf_buf[AP_IOBUFSIZE];
1169
1170     vd.vbuff.curpos = vrprintf_buf;
1171     vd.vbuff.endpos = vrprintf_buf + AP_IOBUFSIZE;
1172     vd.r = r;
1173     vd.buff = vrprintf_buf;
1174
1175     if (r->connection->aborted)
1176         return -1;
1177
1178     written = apr_vformatter(r_flush, &vd.vbuff, fmt, va);
1179     /* tack on null terminator on remaining string */
1180     *(vd.vbuff.curpos) = '\0';
1181
1182     if (written != -1) {
1183         int n = vd.vbuff.curpos - vrprintf_buf;
1184
1185         /* last call to buffer_output, to finish clearing the buffer */
1186         if (buffer_output(r, vrprintf_buf,n) != APR_SUCCESS)
1187             return -1;
1188
1189         written += n;
1190     }
1191
1192     return written;
1193 }
1194
1195 AP_DECLARE_NONSTD(int) ap_rprintf(request_rec *r, const char *fmt, ...)
1196 {
1197     va_list va;
1198     int n;
1199
1200     if (r->connection->aborted)
1201         return -1;
1202
1203     va_start(va, fmt);
1204     n = ap_vrprintf(r, fmt, va);
1205     va_end(va);
1206
1207     return n;
1208 }
1209
1210 AP_DECLARE_NONSTD(int) ap_rvputs(request_rec *r, ...)
1211 {
1212     va_list va;
1213     const char *s;
1214     apr_size_t len;
1215     apr_size_t written = 0;
1216
1217     if (r->connection->aborted)
1218         return -1;
1219
1220     /* ### TODO: if the total output is large, put all the strings
1221        ### into a single brigade, rather than flushing each time we
1222        ### fill the buffer */
1223     va_start(va, r);
1224     while (1) {
1225         s = va_arg(va, const char *);
1226         if (s == NULL)
1227             break;
1228
1229         len = strlen(s);
1230         if (buffer_output(r, s, len) != APR_SUCCESS) {
1231             return -1;
1232         }
1233
1234         written += len;
1235     }
1236     va_end(va);
1237
1238     return written;
1239 }
1240
1241 AP_DECLARE(int) ap_rflush(request_rec *r)
1242 {
1243     apr_bucket_brigade *bb;
1244     apr_bucket *b;
1245
1246     bb = apr_brigade_create(r->pool);
1247     b = apr_bucket_flush_create();
1248     APR_BRIGADE_INSERT_TAIL(bb, b);
1249     if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS)
1250         return -1;
1251     return 0;
1252 }
1253
1254 /*
1255  * This function sets the Last-Modified output header field to the value
1256  * of the mtime field in the request structure - rationalized to keep it from
1257  * being in the future.
1258  */
1259 AP_DECLARE(void) ap_set_last_modified(request_rec *r)
1260 {
1261     apr_time_t mod_time = ap_rationalize_mtime(r, r->mtime);
1262     char *datestr = apr_palloc(r->pool, APR_RFC822_DATE_LEN);
1263     apr_rfc822_date(datestr, mod_time);
1264     apr_table_setn(r->headers_out, "Last-Modified", datestr);
1265 }
1266
1267 AP_IMPLEMENT_HOOK_RUN_ALL(int,post_read_request,
1268                           (request_rec *r),(r),OK,DECLINED)
1269 AP_IMPLEMENT_HOOK_RUN_ALL(int,log_transaction,
1270                           (request_rec *r),(r),OK,DECLINED)
1271 AP_IMPLEMENT_HOOK_RUN_FIRST(const char *,http_method,
1272                             (const request_rec *r),(r),NULL)
1273 AP_IMPLEMENT_HOOK_RUN_FIRST(unsigned short,default_port,
1274                             (const request_rec *r),(r),0)