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