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