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