]> granicus.if.org Git - apache/blob - server/protocol.c
Merge r1741310, r1741461 from trunk:
[apache] / server / protocol.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * protocol.c --- routines which directly communicate with the client.
19  *
20  * Code originally by Rob McCool; much redone by Robert S. Thau
21  * and the Apache Software Foundation.
22  */
23
24 #include "apr.h"
25 #include "apr_strings.h"
26 #include "apr_buckets.h"
27 #include "apr_lib.h"
28 #include "apr_signal.h"
29 #include "apr_strmatch.h"
30
31 #define APR_WANT_STDIO          /* for sscanf */
32 #define APR_WANT_STRFUNC
33 #define APR_WANT_MEMFUNC
34 #include "apr_want.h"
35
36 #include "util_filter.h"
37 #include "ap_config.h"
38 #include "httpd.h"
39 #include "http_config.h"
40 #include "http_core.h"
41 #include "http_protocol.h"
42 #include "http_main.h"
43 #include "http_request.h"
44 #include "http_vhost.h"
45 #include "http_log.h"           /* For errors detected in basic auth common
46                                  * support code... */
47 #include "mod_core.h"
48 #include "util_charset.h"
49 #include "util_ebcdic.h"
50 #include "scoreboard.h"
51
52 #if APR_HAVE_STDARG_H
53 #include <stdarg.h>
54 #endif
55 #if APR_HAVE_UNISTD_H
56 #include <unistd.h>
57 #endif
58
59 /* we know core's module_index is 0 */
60 #undef APLOG_MODULE_INDEX
61 #define APLOG_MODULE_INDEX AP_CORE_MODULE_INDEX
62
63 APR_HOOK_STRUCT(
64     APR_HOOK_LINK(pre_read_request)
65     APR_HOOK_LINK(post_read_request)
66     APR_HOOK_LINK(log_transaction)
67     APR_HOOK_LINK(http_scheme)
68     APR_HOOK_LINK(default_port)
69     APR_HOOK_LINK(note_auth_failure)
70     APR_HOOK_LINK(protocol_propose)
71     APR_HOOK_LINK(protocol_switch)
72     APR_HOOK_LINK(protocol_get)
73 )
74
75 AP_DECLARE_DATA ap_filter_rec_t *ap_old_write_func = NULL;
76
77
78 /* Patterns to match in ap_make_content_type() */
79 static const char *needcset[] = {
80     "text/plain",
81     "text/html",
82     NULL
83 };
84 static const apr_strmatch_pattern **needcset_patterns;
85 static const apr_strmatch_pattern *charset_pattern;
86
87 AP_DECLARE(void) ap_setup_make_content_type(apr_pool_t *pool)
88 {
89     int i;
90     for (i = 0; needcset[i]; i++) {
91         continue;
92     }
93     needcset_patterns = (const apr_strmatch_pattern **)
94         apr_palloc(pool, (i + 1) * sizeof(apr_strmatch_pattern *));
95     for (i = 0; needcset[i]; i++) {
96         needcset_patterns[i] = apr_strmatch_precompile(pool, needcset[i], 0);
97     }
98     needcset_patterns[i] = NULL;
99     charset_pattern = apr_strmatch_precompile(pool, "charset=", 0);
100 }
101
102 /*
103  * Builds the content-type that should be sent to the client from the
104  * content-type specified.  The following rules are followed:
105  *    - if type is NULL or "", return NULL (do not set content-type).
106  *    - if charset adding is disabled, stop processing and return type.
107  *    - then, if there are no parameters on type, add the default charset
108  *    - return type
109  */
110 AP_DECLARE(const char *)ap_make_content_type(request_rec *r, const char *type)
111 {
112     const apr_strmatch_pattern **pcset;
113     core_dir_config *conf =
114         (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
115     core_request_config *request_conf;
116     apr_size_t type_len;
117
118     if (!type || *type == '\0') {
119         return NULL;
120     }
121
122     if (conf->add_default_charset != ADD_DEFAULT_CHARSET_ON) {
123         return type;
124     }
125
126     request_conf = ap_get_core_module_config(r->request_config);
127     if (request_conf->suppress_charset) {
128         return type;
129     }
130
131     type_len = strlen(type);
132
133     if (apr_strmatch(charset_pattern, type, type_len) != NULL) {
134         /* already has parameter, do nothing */
135         /* XXX we don't check the validity */
136         ;
137     }
138     else {
139         /* see if it makes sense to add the charset. At present,
140          * we only add it if the Content-type is one of needcset[]
141          */
142         for (pcset = needcset_patterns; *pcset ; pcset++) {
143             if (apr_strmatch(*pcset, type, type_len) != NULL) {
144                 struct iovec concat[3];
145                 concat[0].iov_base = (void *)type;
146                 concat[0].iov_len = type_len;
147                 concat[1].iov_base = (void *)"; charset=";
148                 concat[1].iov_len = sizeof("; charset=") - 1;
149                 concat[2].iov_base = (void *)(conf->add_default_charset_name);
150                 concat[2].iov_len = strlen(conf->add_default_charset_name);
151                 type = apr_pstrcatv(r->pool, concat, 3, NULL);
152                 break;
153             }
154         }
155     }
156
157     return type;
158 }
159
160 AP_DECLARE(void) ap_set_content_length(request_rec *r, apr_off_t clength)
161 {
162     r->clength = clength;
163     apr_table_setn(r->headers_out, "Content-Length",
164                    apr_off_t_toa(r->pool, clength));
165 }
166
167 /*
168  * Return the latest rational time from a request/mtime (modification time)
169  * pair.  We return the mtime unless it's in the future, in which case we
170  * return the current time.  We use the request time as a reference in order
171  * to limit the number of calls to time().  We don't check for futurosity
172  * unless the mtime is at least as new as the reference.
173  */
174 AP_DECLARE(apr_time_t) ap_rationalize_mtime(request_rec *r, apr_time_t mtime)
175 {
176     apr_time_t now;
177
178     /* For all static responses, it's almost certain that the file was
179      * last modified before the beginning of the request.  So there's
180      * no reason to call time(NULL) again.  But if the response has been
181      * created on demand, then it might be newer than the time the request
182      * started.  In this event we really have to call time(NULL) again
183      * so that we can give the clients the most accurate Last-Modified.  If we
184      * were given a time in the future, we return the current time - the
185      * Last-Modified can't be in the future.
186      */
187     now = (mtime < r->request_time) ? r->request_time : apr_time_now();
188     return (mtime > now) ? now : mtime;
189 }
190
191 /* Get a line of protocol input, including any continuation lines
192  * caused by MIME folding (or broken clients) if fold != 0, and place it
193  * in the buffer s, of size n bytes, without the ending newline.
194  *
195  * If s is NULL, ap_rgetline_core will allocate necessary memory from r->pool.
196  *
197  * Returns APR_SUCCESS if there are no problems and sets *read to be
198  * the full length of s.
199  *
200  * APR_ENOSPC is returned if there is not enough buffer space.
201  * Other errors may be returned on other errors.
202  *
203  * The LF is *not* returned in the buffer.  Therefore, a *read of 0
204  * indicates that an empty line was read.
205  *
206  * Notes: Because the buffer uses 1 char for NUL, the most we can return is
207  *        (n - 1) actual characters.
208  *
209  *        If no LF is detected on the last line due to a dropped connection
210  *        or a full buffer, that's considered an error.
211  */
212 AP_DECLARE(apr_status_t) ap_rgetline_core(char **s, apr_size_t n,
213                                           apr_size_t *read, request_rec *r,
214                                           int fold, apr_bucket_brigade *bb)
215 {
216     apr_status_t rv;
217     apr_bucket *e;
218     apr_size_t bytes_handled = 0, current_alloc = 0;
219     char *pos, *last_char = *s;
220     int do_alloc = (*s == NULL), saw_eos = 0;
221
222     /*
223      * Initialize last_char as otherwise a random value will be compared
224      * against APR_ASCII_LF at the end of the loop if bb only contains
225      * zero-length buckets.
226      */
227     if (last_char)
228         *last_char = '\0';
229
230     for (;;) {
231         apr_brigade_cleanup(bb);
232         rv = ap_get_brigade(r->input_filters, bb, AP_MODE_GETLINE,
233                             APR_BLOCK_READ, 0);
234         if (rv != APR_SUCCESS) {
235             return rv;
236         }
237
238         /* Something horribly wrong happened.  Someone didn't block! */
239         if (APR_BRIGADE_EMPTY(bb)) {
240             return APR_EGENERAL;
241         }
242
243         for (e = APR_BRIGADE_FIRST(bb);
244              e != APR_BRIGADE_SENTINEL(bb);
245              e = APR_BUCKET_NEXT(e))
246         {
247             const char *str;
248             apr_size_t len;
249
250             /* If we see an EOS, don't bother doing anything more. */
251             if (APR_BUCKET_IS_EOS(e)) {
252                 saw_eos = 1;
253                 break;
254             }
255
256             rv = apr_bucket_read(e, &str, &len, APR_BLOCK_READ);
257             if (rv != APR_SUCCESS) {
258                 return rv;
259             }
260
261             if (len == 0) {
262                 /* no use attempting a zero-byte alloc (hurts when
263                  * using --with-efence --enable-pool-debug) or
264                  * doing any of the other logic either
265                  */
266                 continue;
267             }
268
269             /* Would this overrun our buffer?  If so, we'll die. */
270             if (n < bytes_handled + len) {
271                 *read = bytes_handled;
272                 if (*s) {
273                     /* ensure this string is NUL terminated */
274                     if (bytes_handled > 0) {
275                         (*s)[bytes_handled-1] = '\0';
276                     }
277                     else {
278                         (*s)[0] = '\0';
279                     }
280                 }
281                 return APR_ENOSPC;
282             }
283
284             /* Do we have to handle the allocation ourselves? */
285             if (do_alloc) {
286                 /* We'll assume the common case where one bucket is enough. */
287                 if (!*s) {
288                     current_alloc = len;
289                     *s = apr_palloc(r->pool, current_alloc);
290                 }
291                 else if (bytes_handled + len > current_alloc) {
292                     /* Increase the buffer size */
293                     apr_size_t new_size = current_alloc * 2;
294                     char *new_buffer;
295
296                     if (bytes_handled + len > new_size) {
297                         new_size = (bytes_handled + len) * 2;
298                     }
299
300                     new_buffer = apr_palloc(r->pool, new_size);
301
302                     /* Copy what we already had. */
303                     memcpy(new_buffer, *s, bytes_handled);
304                     current_alloc = new_size;
305                     *s = new_buffer;
306                 }
307             }
308
309             /* Just copy the rest of the data to the end of the old buffer. */
310             pos = *s + bytes_handled;
311             memcpy(pos, str, len);
312             last_char = pos + len - 1;
313
314             /* We've now processed that new data - update accordingly. */
315             bytes_handled += len;
316         }
317
318         /* If we got a full line of input, stop reading */
319         if (last_char && (*last_char == APR_ASCII_LF)) {
320             break;
321         }
322     }
323
324     /* Now NUL-terminate the string at the end of the line;
325      * if the last-but-one character is a CR, terminate there */
326     if (last_char > *s && last_char[-1] == APR_ASCII_CR) {
327         last_char--;
328     }
329     *last_char = '\0';
330     bytes_handled = last_char - *s;
331
332     /* If we're folding, we have more work to do.
333      *
334      * Note that if an EOS was seen, we know we can't have another line.
335      */
336     if (fold && bytes_handled && !saw_eos) {
337         for (;;) {
338             const char *str;
339             apr_size_t len;
340             char c;
341
342             /* Clear the temp brigade for this filter read. */
343             apr_brigade_cleanup(bb);
344
345             /* We only care about the first byte. */
346             rv = ap_get_brigade(r->input_filters, bb, AP_MODE_SPECULATIVE,
347                                 APR_BLOCK_READ, 1);
348             if (rv != APR_SUCCESS) {
349                 return rv;
350             }
351
352             if (APR_BRIGADE_EMPTY(bb)) {
353                 break;
354             }
355
356             e = APR_BRIGADE_FIRST(bb);
357
358             /* If we see an EOS, don't bother doing anything more. */
359             if (APR_BUCKET_IS_EOS(e)) {
360                 break;
361             }
362
363             rv = apr_bucket_read(e, &str, &len, APR_BLOCK_READ);
364             if (rv != APR_SUCCESS) {
365                 apr_brigade_cleanup(bb);
366                 return rv;
367             }
368
369             /* Found one, so call ourselves again to get the next line.
370              *
371              * FIXME: If the folding line is completely blank, should we
372              * stop folding?  Does that require also looking at the next
373              * char?
374              */
375             /* When we call destroy, the buckets are deleted, so save that
376              * one character we need.  This simplifies our execution paths
377              * at the cost of one character read.
378              */
379             c = *str;
380             if (c == APR_ASCII_BLANK || c == APR_ASCII_TAB) {
381                 /* Do we have enough space? We may be full now. */
382                 if (bytes_handled >= n) {
383                     *read = n;
384                     /* ensure this string is terminated */
385                     (*s)[n-1] = '\0';
386                     return APR_ENOSPC;
387                 }
388                 else {
389                     apr_size_t next_size, next_len;
390                     char *tmp;
391
392                     /* If we're doing the allocations for them, we have to
393                      * give ourselves a NULL and copy it on return.
394                      */
395                     if (do_alloc) {
396                         tmp = NULL;
397                     } else {
398                         /* We're null terminated. */
399                         tmp = last_char;
400                     }
401
402                     next_size = n - bytes_handled;
403
404                     rv = ap_rgetline_core(&tmp, next_size,
405                                           &next_len, r, 0, bb);
406                     if (rv != APR_SUCCESS) {
407                         return rv;
408                     }
409
410                     if (do_alloc && next_len > 0) {
411                         char *new_buffer;
412                         apr_size_t new_size = bytes_handled + next_len + 1;
413
414                         /* we need to alloc an extra byte for a null */
415                         new_buffer = apr_palloc(r->pool, new_size);
416
417                         /* Copy what we already had. */
418                         memcpy(new_buffer, *s, bytes_handled);
419
420                         /* copy the new line, including the trailing null */
421                         memcpy(new_buffer + bytes_handled, tmp, next_len + 1);
422                         *s = new_buffer;
423                     }
424
425                     last_char += next_len;
426                     bytes_handled += next_len;
427                 }
428             }
429             else { /* next character is not tab or space */
430                 break;
431             }
432         }
433     }
434     *read = bytes_handled;
435
436     /* PR#43039: We shouldn't accept NULL bytes within the line */
437     if (strlen(*s) < bytes_handled) {
438         return APR_EINVAL;
439     }
440
441     return APR_SUCCESS;
442 }
443
444 #if APR_CHARSET_EBCDIC
445 AP_DECLARE(apr_status_t) ap_rgetline(char **s, apr_size_t n,
446                                      apr_size_t *read, request_rec *r,
447                                      int fold, apr_bucket_brigade *bb)
448 {
449     /* on ASCII boxes, ap_rgetline is a macro which simply invokes
450      * ap_rgetline_core with the same parms
451      *
452      * on EBCDIC boxes, each complete http protocol input line needs to be
453      * translated into the code page used by the compiler.  Since
454      * ap_rgetline_core uses recursion, we do the translation in a wrapper
455      * function to ensure that each input character gets translated only once.
456      */
457     apr_status_t rv;
458
459     rv = ap_rgetline_core(s, n, read, r, fold, bb);
460     if (rv == APR_SUCCESS) {
461         ap_xlate_proto_from_ascii(*s, *read);
462     }
463     return rv;
464 }
465 #endif
466
467 AP_DECLARE(int) ap_getline(char *s, int n, request_rec *r, int fold)
468 {
469     char *tmp_s = s;
470     apr_status_t rv;
471     apr_size_t len;
472     apr_bucket_brigade *tmp_bb;
473
474     tmp_bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
475     rv = ap_rgetline(&tmp_s, n, &len, r, fold, tmp_bb);
476     apr_brigade_destroy(tmp_bb);
477
478     /* Map the out-of-space condition to the old API. */
479     if (rv == APR_ENOSPC) {
480         return n;
481     }
482
483     /* Anything else is just bad. */
484     if (rv != APR_SUCCESS) {
485         return -1;
486     }
487
488     return (int)len;
489 }
490
491 /* parse_uri: break apart the uri
492  * Side Effects:
493  * - sets r->args to rest after '?' (or NULL if no '?')
494  * - sets r->uri to request uri (without r->args part)
495  * - sets r->hostname (if not set already) from request (scheme://host:port)
496  */
497 AP_CORE_DECLARE(void) ap_parse_uri(request_rec *r, const char *uri)
498 {
499     int status = HTTP_OK;
500
501     r->unparsed_uri = apr_pstrdup(r->pool, uri);
502
503     /* http://issues.apache.org/bugzilla/show_bug.cgi?id=31875
504      * http://issues.apache.org/bugzilla/show_bug.cgi?id=28450
505      *
506      * This is not in fact a URI, it's a path.  That matters in the
507      * case of a leading double-slash.  We need to resolve the issue
508      * by normalising that out before treating it as a URI.
509      */
510     while ((uri[0] == '/') && (uri[1] == '/')) {
511         ++uri ;
512     }
513     if (r->method_number == M_CONNECT) {
514         status = apr_uri_parse_hostinfo(r->pool, uri, &r->parsed_uri);
515     }
516     else {
517         status = apr_uri_parse(r->pool, uri, &r->parsed_uri);
518     }
519
520     if (status == APR_SUCCESS) {
521         /* if it has a scheme we may need to do absoluteURI vhost stuff */
522         if (r->parsed_uri.scheme
523             && !strcasecmp(r->parsed_uri.scheme, ap_http_scheme(r))) {
524             r->hostname = r->parsed_uri.hostname;
525         }
526         else if (r->method_number == M_CONNECT) {
527             r->hostname = r->parsed_uri.hostname;
528         }
529
530         r->args = r->parsed_uri.query;
531         r->uri = r->parsed_uri.path ? r->parsed_uri.path
532                  : apr_pstrdup(r->pool, "/");
533
534 #if defined(OS2) || defined(WIN32)
535         /* Handle path translations for OS/2 and plug security hole.
536          * This will prevent "http://www.wherever.com/..\..\/" from
537          * returning a directory for the root drive.
538          */
539         {
540             char *x;
541
542             for (x = r->uri; (x = strchr(x, '\\')) != NULL; )
543                 *x = '/';
544         }
545 #endif /* OS2 || WIN32 */
546     }
547     else {
548         r->args = NULL;
549         r->hostname = NULL;
550         r->status = HTTP_BAD_REQUEST;             /* set error status */
551         r->uri = apr_pstrdup(r->pool, uri);
552     }
553 }
554
555 static int read_request_line(request_rec *r, apr_bucket_brigade *bb)
556 {
557     const char *ll;
558     const char *uri;
559     const char *pro;
560
561     unsigned int major = 1, minor = 0;   /* Assume HTTP/1.0 if non-"HTTP" protocol */
562     char http[5];
563     apr_size_t len;
564     int num_blank_lines = DEFAULT_LIMIT_BLANK_LINES;
565
566     /* Read past empty lines until we get a real request line,
567      * a read error, the connection closes (EOF), or we timeout.
568      *
569      * We skip empty lines because browsers have to tack a CRLF on to the end
570      * of POSTs to support old CERN webservers.  But note that we may not
571      * have flushed any previous response completely to the client yet.
572      * We delay the flush as long as possible so that we can improve
573      * performance for clients that are pipelining requests.  If a request
574      * is pipelined then we won't block during the (implicit) read() below.
575      * If the requests aren't pipelined, then the client is still waiting
576      * for the final buffer flush from us, and we will block in the implicit
577      * read().  B_SAFEREAD ensures that the BUFF layer flushes if it will
578      * have to block during a read.
579      */
580
581     do {
582         apr_status_t rv;
583
584         /* ensure ap_rgetline allocates memory each time thru the loop
585          * if there are empty lines
586          */
587         r->the_request = NULL;
588         rv = ap_rgetline(&(r->the_request), (apr_size_t)(r->server->limit_req_line + 2),
589                          &len, r, 0, bb);
590
591         if (rv != APR_SUCCESS) {
592             r->request_time = apr_time_now();
593
594             /* ap_rgetline returns APR_ENOSPC if it fills up the
595              * buffer before finding the end-of-line.  This is only going to
596              * happen if it exceeds the configured limit for a request-line.
597              */
598             if (APR_STATUS_IS_ENOSPC(rv)) {
599                 r->status    = HTTP_REQUEST_URI_TOO_LARGE;
600             }
601             else if (APR_STATUS_IS_TIMEUP(rv)) {
602                 r->status = HTTP_REQUEST_TIME_OUT;
603             }
604             else if (APR_STATUS_IS_EINVAL(rv)) {
605                 r->status = HTTP_BAD_REQUEST;
606             }
607             r->proto_num = HTTP_VERSION(1,0);
608             r->protocol  = apr_pstrdup(r->pool, "HTTP/1.0");
609             return 0;
610         }
611     } while ((len <= 0) && (--num_blank_lines >= 0));
612
613     if (APLOGrtrace5(r)) {
614         ap_log_rerror(APLOG_MARK, APLOG_TRACE5, 0, r,
615                       "Request received from client: %s",
616                       ap_escape_logitem(r->pool, r->the_request));
617     }
618
619     r->request_time = apr_time_now();
620     ll = r->the_request;
621     r->method = ap_getword_white(r->pool, &ll);
622
623     uri = ap_getword_white(r->pool, &ll);
624
625     if (!*r->method || !*uri) {
626         r->status    = HTTP_BAD_REQUEST;
627         r->proto_num = HTTP_VERSION(1,0);
628         r->protocol  = apr_pstrdup(r->pool, "HTTP/1.0");
629         return 0;
630     }
631
632     /* Provide quick information about the request method as soon as known */
633
634     r->method_number = ap_method_number_of(r->method);
635     if (r->method_number == M_GET && r->method[0] == 'H') {
636         r->header_only = 1;
637     }
638
639     ap_parse_uri(r, uri);
640     if (r->status != HTTP_OK) {
641         r->proto_num = HTTP_VERSION(1,0);
642         r->protocol  = apr_pstrdup(r->pool, "HTTP/1.0");
643         return 0;
644     }
645
646     if (ll[0]) {
647         r->assbackwards = 0;
648         pro = ll;
649         len = strlen(ll);
650     } else {
651         r->assbackwards = 1;
652         pro = "HTTP/0.9";
653         len = 8;
654     }
655     r->protocol = apr_pstrmemdup(r->pool, pro, len);
656
657     /* Avoid sscanf in the common case */
658     if (len == 8
659         && pro[0] == 'H' && pro[1] == 'T' && pro[2] == 'T' && pro[3] == 'P'
660         && pro[4] == '/' && apr_isdigit(pro[5]) && pro[6] == '.'
661         && apr_isdigit(pro[7])) {
662         r->proto_num = HTTP_VERSION(pro[5] - '0', pro[7] - '0');
663     }
664     else if (3 == sscanf(r->protocol, "%4s/%u.%u", http, &major, &minor)
665              && (strcasecmp("http", http) == 0)
666              && (minor < HTTP_VERSION(1, 0)) ) /* don't allow HTTP/0.1000 */
667         r->proto_num = HTTP_VERSION(major, minor);
668     else
669         r->proto_num = HTTP_VERSION(1, 0);
670
671     return 1;
672 }
673
674 static int table_do_fn_check_lengths(void *r_, const char *key,
675                                      const char *value)
676 {
677     request_rec *r = r_;
678     if (value == NULL || r->server->limit_req_fieldsize >= strlen(value) )
679         return 1;
680
681     r->status = HTTP_BAD_REQUEST;
682     apr_table_setn(r->notes, "error-notes",
683                    apr_pstrcat(r->pool, "Size of a request header field "
684                                "after merging exceeds server limit.<br />"
685                                "\n<pre>\n",
686                                ap_escape_html(r->pool, key),
687                                "</pre>\n", NULL));
688     ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00560) "Request header "
689                   "exceeds LimitRequestFieldSize after merging: %s", key);
690     return 0;
691 }
692
693 /* get the length of the field name for logging, but no more than 80 bytes */
694 #define LOG_NAME_MAX_LEN 80
695 static int field_name_len(const char *field)
696 {
697     const char *end = ap_strchr_c(field, ':');
698     if (end == NULL || end - field > LOG_NAME_MAX_LEN)
699         return LOG_NAME_MAX_LEN;
700     return end - field;
701 }
702
703 AP_DECLARE(void) ap_get_mime_headers_core(request_rec *r, apr_bucket_brigade *bb)
704 {
705     char *last_field = NULL;
706     apr_size_t last_len = 0;
707     apr_size_t alloc_len = 0;
708     char *field;
709     char *value;
710     apr_size_t len;
711     int fields_read = 0;
712     char *tmp_field;
713
714     /*
715      * Read header lines until we get the empty separator line, a read error,
716      * the connection closes (EOF), reach the server limit, or we timeout.
717      */
718     while(1) {
719         apr_status_t rv;
720         int folded = 0;
721
722         field = NULL;
723         rv = ap_rgetline(&field, r->server->limit_req_fieldsize + 2,
724                          &len, r, 0, bb);
725
726         if (rv != APR_SUCCESS) {
727             if (APR_STATUS_IS_TIMEUP(rv)) {
728                 r->status = HTTP_REQUEST_TIME_OUT;
729             }
730             else {
731                 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r, 
732                               "Failed to read request header line %s", field);
733                 r->status = HTTP_BAD_REQUEST;
734             }
735
736             /* ap_rgetline returns APR_ENOSPC if it fills up the buffer before
737              * finding the end-of-line.  This is only going to happen if it
738              * exceeds the configured limit for a field size.
739              */
740             if (rv == APR_ENOSPC) {
741                 const char *field_escaped;
742                 if (field && len) {
743                     /* ensure ap_escape_html will terminate correctly */
744                     field[len - 1] = '\0';
745                     field_escaped = ap_escape_html(r->pool, field);
746                 }
747                 else {
748                     field_escaped = field = "";
749                 }
750
751                 apr_table_setn(r->notes, "error-notes",
752                                apr_psprintf(r->pool,
753                                            "Size of a request header field "
754                                            "exceeds server limit.<br />\n"
755                                            "<pre>\n%.*s\n</pre>\n", 
756                                            field_name_len(field_escaped),
757                                            field_escaped));
758                 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00561)
759                               "Request header exceeds LimitRequestFieldSize%s"
760                               "%.*s",
761                               *field ? ": " : "",
762                               field_name_len(field), field);
763             }
764             return;
765         }
766
767         if (last_field != NULL) {
768             if ((len > 0) && ((*field == '\t') || *field == ' ')) {
769                 /* This line is a continuation of the preceding line(s),
770                  * so append it to the line that we've set aside.
771                  * Note: this uses a power-of-two allocator to avoid
772                  * doing O(n) allocs and using O(n^2) space for
773                  * continuations that span many many lines.
774                  */
775                 apr_size_t fold_len = last_len + len + 1; /* trailing null */
776
777                 if (fold_len >= (apr_size_t)(r->server->limit_req_fieldsize)) {
778                     const char *field_escaped;
779
780                     r->status = HTTP_BAD_REQUEST;
781                     /* report what we have accumulated so far before the
782                      * overflow (last_field) as the field with the problem
783                      */
784                     field_escaped = ap_escape_html(r->pool, last_field);
785                     apr_table_setn(r->notes, "error-notes",
786                                    apr_psprintf(r->pool,
787                                                "Size of a request header field "
788                                                "after folding "
789                                                "exceeds server limit.<br />\n"
790                                                "<pre>\n%.*s\n</pre>\n", 
791                                                field_name_len(field_escaped), 
792                                                field_escaped));
793                     ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00562)
794                                   "Request header exceeds LimitRequestFieldSize "
795                                   "after folding: %.*s",
796                                   field_name_len(last_field), last_field);
797                     return;
798                 }
799
800                 if (fold_len > alloc_len) {
801                     char *fold_buf;
802                     alloc_len += alloc_len;
803                     if (fold_len > alloc_len) {
804                         alloc_len = fold_len;
805                     }
806                     fold_buf = (char *)apr_palloc(r->pool, alloc_len);
807                     memcpy(fold_buf, last_field, last_len);
808                     last_field = fold_buf;
809                 }
810                 memcpy(last_field + last_len, field, len +1); /* +1 for nul */
811                 last_len += len;
812                 folded = 1;
813             }
814             else /* not a continuation line */ {
815
816                 if (r->server->limit_req_fields
817                     && (++fields_read > r->server->limit_req_fields)) {
818                     r->status = HTTP_BAD_REQUEST;
819                     apr_table_setn(r->notes, "error-notes",
820                                    "The number of request header fields "
821                                    "exceeds this server's limit.");
822                     ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00563)
823                                   "Number of request headers exceeds "
824                                   "LimitRequestFields");
825                     return;
826                 }
827
828                 if (!(value = strchr(last_field, ':'))) { /* Find ':' or    */
829                     r->status = HTTP_BAD_REQUEST;      /* abort bad request */
830                     apr_table_setn(r->notes, "error-notes",
831                                    apr_psprintf(r->pool,
832                                                "Request header field is "
833                                                "missing ':' separator.<br />\n"
834                                                "<pre>\n%.*s</pre>\n", 
835                                                (int)LOG_NAME_MAX_LEN,
836                                                ap_escape_html(r->pool,
837                                                               last_field)));
838                     ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00564)
839                                   "Request header field is missing ':' "
840                                   "separator: %.*s", (int)LOG_NAME_MAX_LEN,
841                                   last_field);
842                     return;
843                 }
844
845                 tmp_field = value - 1; /* last character of field-name */
846
847                 *value++ = '\0'; /* NUL-terminate at colon */
848
849                 while (*value == ' ' || *value == '\t') {
850                     ++value;            /* Skip to start of value   */
851                 }
852
853                 /* Strip LWS after field-name: */
854                 while (tmp_field > last_field
855                        && (*tmp_field == ' ' || *tmp_field == '\t')) {
856                     *tmp_field-- = '\0';
857                 }
858
859                 /* Strip LWS after field-value: */
860                 tmp_field = last_field + last_len - 1;
861                 while (tmp_field > value
862                        && (*tmp_field == ' ' || *tmp_field == '\t')) {
863                     *tmp_field-- = '\0';
864                 }
865
866                 apr_table_addn(r->headers_in, last_field, value);
867
868                 /* reset the alloc_len so that we'll allocate a new
869                  * buffer if we have to do any more folding: we can't
870                  * use the previous buffer because its contents are
871                  * now part of r->headers_in
872                  */
873                 alloc_len = 0;
874
875             } /* end if current line is not a continuation starting with tab */
876         }
877
878         /* Found a blank line, stop. */
879         if (len == 0) {
880             break;
881         }
882
883         /* Keep track of this line so that we can parse it on
884          * the next loop iteration.  (In the folded case, last_field
885          * has been updated already.)
886          */
887         if (!folded) {
888             last_field = field;
889             last_len = len;
890         }
891     }
892
893     /* Combine multiple message-header fields with the same
894      * field-name, following RFC 2616, 4.2.
895      */
896     apr_table_compress(r->headers_in, APR_OVERLAP_TABLES_MERGE);
897
898     /* enforce LimitRequestFieldSize for merged headers */
899     apr_table_do(table_do_fn_check_lengths, r, r->headers_in, NULL);
900 }
901
902 AP_DECLARE(void) ap_get_mime_headers(request_rec *r)
903 {
904     apr_bucket_brigade *tmp_bb;
905     tmp_bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
906     ap_get_mime_headers_core(r, tmp_bb);
907     apr_brigade_destroy(tmp_bb);
908 }
909
910 request_rec *ap_read_request(conn_rec *conn)
911 {
912     request_rec *r;
913     apr_pool_t *p;
914     const char *expect;
915     int access_status = HTTP_OK;
916     apr_bucket_brigade *tmp_bb;
917     apr_socket_t *csd;
918     apr_interval_time_t cur_timeout;
919
920
921     apr_pool_create(&p, conn->pool);
922     apr_pool_tag(p, "request");
923     r = apr_pcalloc(p, sizeof(request_rec));
924     AP_READ_REQUEST_ENTRY((intptr_t)r, (uintptr_t)conn);
925     r->pool            = p;
926     r->connection      = conn;
927     r->server          = conn->base_server;
928
929     r->user            = NULL;
930     r->ap_auth_type    = NULL;
931
932     r->allowed_methods = ap_make_method_list(p, 2);
933
934     r->headers_in      = apr_table_make(r->pool, 25);
935     r->trailers_in     = apr_table_make(r->pool, 5);
936     r->subprocess_env  = apr_table_make(r->pool, 25);
937     r->headers_out     = apr_table_make(r->pool, 12);
938     r->err_headers_out = apr_table_make(r->pool, 5);
939     r->trailers_out    = apr_table_make(r->pool, 5);
940     r->notes           = apr_table_make(r->pool, 5);
941
942     r->request_config  = ap_create_request_config(r->pool);
943     /* Must be set before we run create request hook */
944
945     r->proto_output_filters = conn->output_filters;
946     r->output_filters  = r->proto_output_filters;
947     r->proto_input_filters = conn->input_filters;
948     r->input_filters   = r->proto_input_filters;
949     ap_run_create_request(r);
950     r->per_dir_config  = r->server->lookup_defaults;
951
952     r->sent_bodyct     = 0;                      /* bytect isn't for body */
953
954     r->read_length     = 0;
955     r->read_body       = REQUEST_NO_BODY;
956
957     r->status          = HTTP_OK;  /* Until further notice */
958     r->the_request     = NULL;
959
960     /* Begin by presuming any module can make its own path_info assumptions,
961      * until some module interjects and changes the value.
962      */
963     r->used_path_info = AP_REQ_DEFAULT_PATH_INFO;
964
965     r->useragent_addr = conn->client_addr;
966     r->useragent_ip = conn->client_ip;
967
968     tmp_bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
969
970     ap_run_pre_read_request(r, conn);
971
972     /* Get the request... */
973     if (!read_request_line(r, tmp_bb)) {
974         if (r->status == HTTP_REQUEST_URI_TOO_LARGE
975             || r->status == HTTP_BAD_REQUEST) {
976             if (r->status == HTTP_REQUEST_URI_TOO_LARGE) {
977                 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00565)
978                               "request failed: client's request-line exceeds LimitRequestLine (longer than %d)",
979                               r->server->limit_req_line);
980             }
981             else if (r->method == NULL) {
982                 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00566)
983                               "request failed: invalid characters in URI");
984             }
985             access_status = r->status;
986             r->status = HTTP_OK;
987             ap_die(access_status, r);
988             ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
989             ap_run_log_transaction(r);
990             r = NULL;
991             apr_brigade_destroy(tmp_bb);
992             goto traceout;
993         }
994         else if (r->status == HTTP_REQUEST_TIME_OUT) {
995             ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
996             if (!r->connection->keepalives) {
997                 ap_run_log_transaction(r);
998             }
999             apr_brigade_destroy(tmp_bb);
1000             goto traceout;
1001         }
1002
1003         apr_brigade_destroy(tmp_bb);
1004         r = NULL;
1005         goto traceout;
1006     }
1007
1008     /* We may have been in keep_alive_timeout mode, so toggle back
1009      * to the normal timeout mode as we fetch the header lines,
1010      * as necessary.
1011      */
1012     csd = ap_get_conn_socket(conn);
1013     apr_socket_timeout_get(csd, &cur_timeout);
1014     if (cur_timeout != conn->base_server->timeout) {
1015         apr_socket_timeout_set(csd, conn->base_server->timeout);
1016         cur_timeout = conn->base_server->timeout;
1017     }
1018
1019     if (!r->assbackwards) {
1020         const char *tenc;
1021
1022         ap_get_mime_headers_core(r, tmp_bb);
1023         if (r->status != HTTP_OK) {
1024             ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00567)
1025                           "request failed: error reading the headers");
1026             ap_send_error_response(r, 0);
1027             ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
1028             ap_run_log_transaction(r);
1029             apr_brigade_destroy(tmp_bb);
1030             goto traceout;
1031         }
1032
1033         tenc = apr_table_get(r->headers_in, "Transfer-Encoding");
1034         if (tenc) {
1035             /* http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-23
1036              * Section 3.3.3.3: "If a Transfer-Encoding header field is
1037              * present in a request and the chunked transfer coding is not
1038              * the final encoding ...; the server MUST respond with the 400
1039              * (Bad Request) status code and then close the connection".
1040              */
1041             if (!(strcasecmp(tenc, "chunked") == 0 /* fast path */
1042                     || ap_find_last_token(r->pool, tenc, "chunked"))) {
1043                 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(02539)
1044                               "client sent unknown Transfer-Encoding "
1045                               "(%s): %s", tenc, r->uri);
1046                 r->status = HTTP_BAD_REQUEST;
1047                 conn->keepalive = AP_CONN_CLOSE;
1048                 ap_send_error_response(r, 0);
1049                 ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
1050                 ap_run_log_transaction(r);
1051                 apr_brigade_destroy(tmp_bb);
1052                 goto traceout;
1053             }
1054
1055             /* http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-23
1056              * Section 3.3.3.3: "If a message is received with both a
1057              * Transfer-Encoding and a Content-Length header field, the
1058              * Transfer-Encoding overrides the Content-Length. ... A sender
1059              * MUST remove the received Content-Length field".
1060              */
1061             apr_table_unset(r->headers_in, "Content-Length");
1062         }
1063     }
1064     else {
1065         if (r->header_only) {
1066             /*
1067              * Client asked for headers only with HTTP/0.9, which doesn't send
1068              * headers! Have to dink things just to make sure the error message
1069              * comes through...
1070              */
1071             ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00568)
1072                           "client sent invalid HTTP/0.9 request: HEAD %s",
1073                           r->uri);
1074             r->header_only = 0;
1075             r->status = HTTP_BAD_REQUEST;
1076             ap_send_error_response(r, 0);
1077             ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
1078             ap_run_log_transaction(r);
1079             apr_brigade_destroy(tmp_bb);
1080             goto traceout;
1081         }
1082     }
1083
1084     apr_brigade_destroy(tmp_bb);
1085
1086     /* update what we think the virtual host is based on the headers we've
1087      * now read. may update status.
1088      */
1089     ap_update_vhost_from_headers(r);
1090
1091     /* Toggle to the Host:-based vhost's timeout mode to fetch the
1092      * request body and send the response body, if needed.
1093      */
1094     if (cur_timeout != r->server->timeout) {
1095         apr_socket_timeout_set(csd, r->server->timeout);
1096         cur_timeout = r->server->timeout;
1097     }
1098
1099     /* we may have switched to another server */
1100     r->per_dir_config = r->server->lookup_defaults;
1101
1102     if ((!r->hostname && (r->proto_num >= HTTP_VERSION(1, 1)))
1103         || ((r->proto_num == HTTP_VERSION(1, 1))
1104             && !apr_table_get(r->headers_in, "Host"))) {
1105         /*
1106          * Client sent us an HTTP/1.1 or later request without telling us the
1107          * hostname, either with a full URL or a Host: header. We therefore
1108          * need to (as per the 1.1 spec) send an error.  As a special case,
1109          * HTTP/1.1 mentions twice (S9, S14.23) that a request MUST contain
1110          * a Host: header, and the server MUST respond with 400 if it doesn't.
1111          */
1112         access_status = HTTP_BAD_REQUEST;
1113         ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00569)
1114                       "client sent HTTP/1.1 request without hostname "
1115                       "(see RFC2616 section 14.23): %s", r->uri);
1116     }
1117
1118     /*
1119      * Add the HTTP_IN filter here to ensure that ap_discard_request_body
1120      * called by ap_die and by ap_send_error_response works correctly on
1121      * status codes that do not cause the connection to be dropped and
1122      * in situations where the connection should be kept alive.
1123      */
1124
1125     ap_add_input_filter_handle(ap_http_input_filter_handle,
1126                                NULL, r, r->connection);
1127
1128     if (access_status != HTTP_OK
1129         || (access_status = ap_run_post_read_request(r))) {
1130         ap_die(access_status, r);
1131         ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
1132         ap_run_log_transaction(r);
1133         r = NULL;
1134         goto traceout;
1135     }
1136
1137     if (((expect = apr_table_get(r->headers_in, "Expect")) != NULL)
1138         && (expect[0] != '\0')) {
1139         /*
1140          * The Expect header field was added to HTTP/1.1 after RFC 2068
1141          * as a means to signal when a 100 response is desired and,
1142          * unfortunately, to signal a poor man's mandatory extension that
1143          * the server must understand or return 417 Expectation Failed.
1144          */
1145         if (strcasecmp(expect, "100-continue") == 0) {
1146             r->expecting_100 = 1;
1147         }
1148         else {
1149             r->status = HTTP_EXPECTATION_FAILED;
1150             ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00570)
1151                           "client sent an unrecognized expectation value of "
1152                           "Expect: %s", expect);
1153             ap_send_error_response(r, 0);
1154             ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
1155             ap_run_log_transaction(r);
1156             goto traceout;
1157         }
1158     }
1159
1160     AP_READ_REQUEST_SUCCESS((uintptr_t)r, (char *)r->method, (char *)r->uri, (char *)r->server->defn_name, r->status);
1161     return r;
1162     traceout:
1163     AP_READ_REQUEST_FAILURE((uintptr_t)r);
1164     return r;
1165 }
1166
1167 /* if a request with a body creates a subrequest, remove original request's
1168  * input headers which pertain to the body which has already been read.
1169  * out-of-line helper function for ap_set_sub_req_protocol.
1170  */
1171
1172 static void strip_headers_request_body(request_rec *rnew)
1173 {
1174     apr_table_unset(rnew->headers_in, "Content-Encoding");
1175     apr_table_unset(rnew->headers_in, "Content-Language");
1176     apr_table_unset(rnew->headers_in, "Content-Length");
1177     apr_table_unset(rnew->headers_in, "Content-Location");
1178     apr_table_unset(rnew->headers_in, "Content-MD5");
1179     apr_table_unset(rnew->headers_in, "Content-Range");
1180     apr_table_unset(rnew->headers_in, "Content-Type");
1181     apr_table_unset(rnew->headers_in, "Expires");
1182     apr_table_unset(rnew->headers_in, "Last-Modified");
1183     apr_table_unset(rnew->headers_in, "Transfer-Encoding");
1184 }
1185
1186 /*
1187  * A couple of other functions which initialize some of the fields of
1188  * a request structure, as appropriate for adjuncts of one kind or another
1189  * to a request in progress.  Best here, rather than elsewhere, since
1190  * *someone* has to set the protocol-specific fields...
1191  */
1192
1193 AP_DECLARE(void) ap_set_sub_req_protocol(request_rec *rnew,
1194                                          const request_rec *r)
1195 {
1196     rnew->the_request     = r->the_request;  /* Keep original request-line */
1197
1198     rnew->assbackwards    = 1;   /* Don't send headers from this. */
1199     rnew->no_local_copy   = 1;   /* Don't try to send HTTP_NOT_MODIFIED for a
1200                                   * fragment. */
1201     rnew->method          = "GET";
1202     rnew->method_number   = M_GET;
1203     rnew->protocol        = "INCLUDED";
1204
1205     rnew->status          = HTTP_OK;
1206
1207     rnew->headers_in      = apr_table_copy(rnew->pool, r->headers_in);
1208     rnew->trailers_in     = apr_table_copy(rnew->pool, r->trailers_in);
1209
1210     /* did the original request have a body?  (e.g. POST w/SSI tags)
1211      * if so, make sure the subrequest doesn't inherit body headers
1212      */
1213     if (!r->kept_body && (apr_table_get(r->headers_in, "Content-Length")
1214         || apr_table_get(r->headers_in, "Transfer-Encoding"))) {
1215         strip_headers_request_body(rnew);
1216     }
1217     rnew->subprocess_env  = apr_table_copy(rnew->pool, r->subprocess_env);
1218     rnew->headers_out     = apr_table_make(rnew->pool, 5);
1219     rnew->err_headers_out = apr_table_make(rnew->pool, 5);
1220     rnew->trailers_out    = apr_table_make(rnew->pool, 5);
1221     rnew->notes           = apr_table_make(rnew->pool, 5);
1222
1223     rnew->expecting_100   = r->expecting_100;
1224     rnew->read_length     = r->read_length;
1225     rnew->read_body       = REQUEST_NO_BODY;
1226
1227     rnew->main = (request_rec *) r;
1228 }
1229
1230 static void end_output_stream(request_rec *r)
1231 {
1232     conn_rec *c = r->connection;
1233     apr_bucket_brigade *bb;
1234     apr_bucket *b;
1235
1236     bb = apr_brigade_create(r->pool, c->bucket_alloc);
1237     b = apr_bucket_eos_create(c->bucket_alloc);
1238     APR_BRIGADE_INSERT_TAIL(bb, b);
1239     ap_pass_brigade(r->output_filters, bb);
1240 }
1241
1242 AP_DECLARE(void) ap_finalize_sub_req_protocol(request_rec *sub)
1243 {
1244     /* tell the filter chain there is no more content coming */
1245     if (!sub->eos_sent) {
1246         end_output_stream(sub);
1247     }
1248 }
1249
1250 /* finalize_request_protocol is called at completion of sending the
1251  * response.  Its sole purpose is to send the terminating protocol
1252  * information for any wrappers around the response message body
1253  * (i.e., transfer encodings).  It should have been named finalize_response.
1254  */
1255 AP_DECLARE(void) ap_finalize_request_protocol(request_rec *r)
1256 {
1257     (void) ap_discard_request_body(r);
1258
1259     /* tell the filter chain there is no more content coming */
1260     if (!r->eos_sent) {
1261         end_output_stream(r);
1262     }
1263 }
1264
1265 /*
1266  * Support for the Basic authentication protocol, and a bit for Digest.
1267  */
1268 AP_DECLARE(void) ap_note_auth_failure(request_rec *r)
1269 {
1270     const char *type = ap_auth_type(r);
1271     if (type) {
1272         ap_run_note_auth_failure(r, type);
1273     }
1274     else {
1275         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00571)
1276                       "need AuthType to note auth failure: %s", r->uri);
1277     }
1278 }
1279
1280 AP_DECLARE(void) ap_note_basic_auth_failure(request_rec *r)
1281 {
1282     ap_note_auth_failure(r);
1283 }
1284
1285 AP_DECLARE(void) ap_note_digest_auth_failure(request_rec *r)
1286 {
1287     ap_note_auth_failure(r);
1288 }
1289
1290 AP_DECLARE(int) ap_get_basic_auth_pw(request_rec *r, const char **pw)
1291 {
1292     const char *auth_line = apr_table_get(r->headers_in,
1293                                           (PROXYREQ_PROXY == r->proxyreq)
1294                                               ? "Proxy-Authorization"
1295                                               : "Authorization");
1296     const char *t;
1297
1298     if (!(t = ap_auth_type(r)) || strcasecmp(t, "Basic"))
1299         return DECLINED;
1300
1301     if (!ap_auth_name(r)) {
1302         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00572) 
1303                       "need AuthName: %s", r->uri);
1304         return HTTP_INTERNAL_SERVER_ERROR;
1305     }
1306
1307     if (!auth_line) {
1308         ap_note_auth_failure(r);
1309         return HTTP_UNAUTHORIZED;
1310     }
1311
1312     if (strcasecmp(ap_getword(r->pool, &auth_line, ' '), "Basic")) {
1313         /* Client tried to authenticate using wrong auth scheme */
1314         ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00573)
1315                       "client used wrong authentication scheme: %s", r->uri);
1316         ap_note_auth_failure(r);
1317         return HTTP_UNAUTHORIZED;
1318     }
1319
1320     while (*auth_line == ' ' || *auth_line == '\t') {
1321         auth_line++;
1322     }
1323
1324     t = ap_pbase64decode(r->pool, auth_line);
1325     r->user = ap_getword_nulls (r->pool, &t, ':');
1326     r->ap_auth_type = "Basic";
1327
1328     *pw = t;
1329
1330     return OK;
1331 }
1332
1333 struct content_length_ctx {
1334     int data_sent;  /* true if the C-L filter has already sent at
1335                      * least one bucket on to the next output filter
1336                      * for this request
1337                      */
1338     apr_bucket_brigade *tmpbb;
1339 };
1340
1341 /* This filter computes the content length, but it also computes the number
1342  * of bytes sent to the client.  This means that this filter will always run
1343  * through all of the buckets in all brigades
1344  */
1345 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_content_length_filter(
1346     ap_filter_t *f,
1347     apr_bucket_brigade *b)
1348 {
1349     request_rec *r = f->r;
1350     struct content_length_ctx *ctx;
1351     apr_bucket *e;
1352     int eos = 0;
1353     apr_read_type_e eblock = APR_NONBLOCK_READ;
1354
1355     ctx = f->ctx;
1356     if (!ctx) {
1357         f->ctx = ctx = apr_palloc(r->pool, sizeof(*ctx));
1358         ctx->data_sent = 0;
1359         ctx->tmpbb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1360     }
1361
1362     /* Loop through this set of buckets to compute their length
1363      */
1364     e = APR_BRIGADE_FIRST(b);
1365     while (e != APR_BRIGADE_SENTINEL(b)) {
1366         if (APR_BUCKET_IS_EOS(e)) {
1367             eos = 1;
1368             break;
1369         }
1370         if (e->length == (apr_size_t)-1) {
1371             apr_size_t len;
1372             const char *ignored;
1373             apr_status_t rv;
1374
1375             /* This is probably a pipe bucket.  Send everything
1376              * prior to this, and then read the data for this bucket.
1377              */
1378             rv = apr_bucket_read(e, &ignored, &len, eblock);
1379             if (rv == APR_SUCCESS) {
1380                 /* Attempt a nonblocking read next time through */
1381                 eblock = APR_NONBLOCK_READ;
1382                 r->bytes_sent += len;
1383             }
1384             else if (APR_STATUS_IS_EAGAIN(rv)) {
1385                 /* Output everything prior to this bucket, and then
1386                  * do a blocking read on the next batch.
1387                  */
1388                 if (e != APR_BRIGADE_FIRST(b)) {
1389                     apr_bucket *flush;
1390                     apr_brigade_split_ex(b, e, ctx->tmpbb);
1391                     flush = apr_bucket_flush_create(r->connection->bucket_alloc);
1392
1393                     APR_BRIGADE_INSERT_TAIL(b, flush);
1394                     rv = ap_pass_brigade(f->next, b);
1395                     if (rv != APR_SUCCESS || f->c->aborted) {
1396                         return rv;
1397                     }
1398                     apr_brigade_cleanup(b);
1399                     APR_BRIGADE_CONCAT(b, ctx->tmpbb);
1400                     e = APR_BRIGADE_FIRST(b);
1401
1402                     ctx->data_sent = 1;
1403                 }
1404                 eblock = APR_BLOCK_READ;
1405                 continue;
1406             }
1407             else {
1408                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(00574)
1409                               "ap_content_length_filter: "
1410                               "apr_bucket_read() failed");
1411                 return rv;
1412             }
1413         }
1414         else {
1415             r->bytes_sent += e->length;
1416         }
1417         e = APR_BUCKET_NEXT(e);
1418     }
1419
1420     /* If we've now seen the entire response and it's otherwise
1421      * okay to set the C-L in the response header, then do so now.
1422      *
1423      * We can only set a C-L in the response header if we haven't already
1424      * sent any buckets on to the next output filter for this request.
1425      */
1426     if (ctx->data_sent == 0 && eos &&
1427         /* don't whack the C-L if it has already been set for a HEAD
1428          * by something like proxy.  the brigade only has an EOS bucket
1429          * in this case, making r->bytes_sent zero.
1430          *
1431          * if r->bytes_sent > 0 we have a (temporary) body whose length may
1432          * have been changed by a filter.  the C-L header might not have been
1433          * updated so we do it here.  long term it would be cleaner to have
1434          * such filters update or remove the C-L header, and just use it
1435          * if present.
1436          */
1437         !(r->header_only && r->bytes_sent == 0 &&
1438             apr_table_get(r->headers_out, "Content-Length"))) {
1439         ap_set_content_length(r, r->bytes_sent);
1440     }
1441
1442     ctx->data_sent = 1;
1443     return ap_pass_brigade(f->next, b);
1444 }
1445
1446 /*
1447  * Send the body of a response to the client.
1448  */
1449 AP_DECLARE(apr_status_t) ap_send_fd(apr_file_t *fd, request_rec *r,
1450                                     apr_off_t offset, apr_size_t len,
1451                                     apr_size_t *nbytes)
1452 {
1453     conn_rec *c = r->connection;
1454     apr_bucket_brigade *bb = NULL;
1455     apr_status_t rv;
1456
1457     bb = apr_brigade_create(r->pool, c->bucket_alloc);
1458
1459     apr_brigade_insert_file(bb, fd, offset, len, r->pool);
1460
1461     rv = ap_pass_brigade(r->output_filters, bb);
1462     if (rv != APR_SUCCESS) {
1463         *nbytes = 0; /* no way to tell how many were actually sent */
1464     }
1465     else {
1466         *nbytes = len;
1467     }
1468
1469     return rv;
1470 }
1471
1472 #if APR_HAS_MMAP
1473 /* send data from an in-memory buffer */
1474 AP_DECLARE(apr_size_t) ap_send_mmap(apr_mmap_t *mm,
1475                                     request_rec *r,
1476                                     apr_size_t offset,
1477                                     apr_size_t length)
1478 {
1479     conn_rec *c = r->connection;
1480     apr_bucket_brigade *bb = NULL;
1481     apr_bucket *b;
1482
1483     bb = apr_brigade_create(r->pool, c->bucket_alloc);
1484     b = apr_bucket_mmap_create(mm, offset, length, c->bucket_alloc);
1485     APR_BRIGADE_INSERT_TAIL(bb, b);
1486     ap_pass_brigade(r->output_filters, bb);
1487
1488     return mm->size; /* XXX - change API to report apr_status_t? */
1489 }
1490 #endif /* APR_HAS_MMAP */
1491
1492 typedef struct {
1493     apr_bucket_brigade *bb;
1494     apr_bucket_brigade *tmpbb;
1495 } old_write_filter_ctx;
1496
1497 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_old_write_filter(
1498     ap_filter_t *f, apr_bucket_brigade *bb)
1499 {
1500     old_write_filter_ctx *ctx = f->ctx;
1501
1502     AP_DEBUG_ASSERT(ctx);
1503
1504     if (ctx->bb != NULL) {
1505         /* whatever is coming down the pipe (we don't care), we
1506          * can simply insert our buffered data at the front and
1507          * pass the whole bundle down the chain.
1508          */
1509         APR_BRIGADE_PREPEND(bb, ctx->bb);
1510     }
1511
1512     return ap_pass_brigade(f->next, bb);
1513 }
1514
1515 static ap_filter_t *insert_old_write_filter(request_rec *r)
1516 {
1517     ap_filter_t *f;
1518     old_write_filter_ctx *ctx;
1519
1520     /* future optimization: record some flags in the request_rec to
1521      * say whether we've added our filter, and whether it is first.
1522      */
1523
1524     /* this will typically exit on the first test */
1525     for (f = r->output_filters; f != NULL; f = f->next) {
1526         if (ap_old_write_func == f->frec)
1527             break;
1528     }
1529
1530     if (f == NULL) {
1531         /* our filter hasn't been added yet */
1532         ctx = apr_pcalloc(r->pool, sizeof(*ctx));
1533         ctx->tmpbb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1534
1535         ap_add_output_filter("OLD_WRITE", ctx, r, r->connection);
1536         f = r->output_filters;
1537     }
1538
1539     return f;
1540 }
1541
1542 static apr_status_t buffer_output(request_rec *r,
1543                                   const char *str, apr_size_t len)
1544 {
1545     conn_rec *c = r->connection;
1546     ap_filter_t *f;
1547     old_write_filter_ctx *ctx;
1548
1549     if (len == 0)
1550         return APR_SUCCESS;
1551
1552     f = insert_old_write_filter(r);
1553     ctx = f->ctx;
1554
1555     /* if the first filter is not our buffering filter, then we have to
1556      * deliver the content through the normal filter chain
1557      */
1558     if (f != r->output_filters) {
1559         apr_status_t rv;
1560         apr_bucket *b = apr_bucket_transient_create(str, len, c->bucket_alloc);
1561         APR_BRIGADE_INSERT_TAIL(ctx->tmpbb, b);
1562
1563         rv = ap_pass_brigade(r->output_filters, ctx->tmpbb);
1564         apr_brigade_cleanup(ctx->tmpbb);
1565         return rv;
1566     }
1567
1568     if (ctx->bb == NULL) {
1569         ctx->bb = apr_brigade_create(r->pool, c->bucket_alloc);
1570     }
1571
1572     return ap_fwrite(f->next, ctx->bb, str, len);
1573 }
1574
1575 AP_DECLARE(int) ap_rputc(int c, request_rec *r)
1576 {
1577     char c2 = (char)c;
1578
1579     if (r->connection->aborted) {
1580         return -1;
1581     }
1582
1583     if (buffer_output(r, &c2, 1) != APR_SUCCESS)
1584         return -1;
1585
1586     return c;
1587 }
1588
1589 AP_DECLARE(int) ap_rwrite(const void *buf, int nbyte, request_rec *r)
1590 {
1591     if (r->connection->aborted)
1592         return -1;
1593
1594     if (buffer_output(r, buf, nbyte) != APR_SUCCESS)
1595         return -1;
1596
1597     return nbyte;
1598 }
1599
1600 struct ap_vrprintf_data {
1601     apr_vformatter_buff_t vbuff;
1602     request_rec *r;
1603     char *buff;
1604 };
1605
1606 /* Flush callback for apr_vformatter; returns -1 on error. */
1607 static int r_flush(apr_vformatter_buff_t *buff)
1608 {
1609     /* callback function passed to ap_vformatter to be called when
1610      * vformatter needs to write into buff and buff.curpos > buff.endpos */
1611
1612     /* ap_vrprintf_data passed as a apr_vformatter_buff_t, which is then
1613      * "downcast" to an ap_vrprintf_data */
1614     struct ap_vrprintf_data *vd = (struct ap_vrprintf_data*)buff;
1615
1616     if (vd->r->connection->aborted)
1617         return -1;
1618
1619     /* r_flush is called when vbuff is completely full */
1620     if (buffer_output(vd->r, vd->buff, AP_IOBUFSIZE)) {
1621         return -1;
1622     }
1623
1624     /* reset the buffer position */
1625     vd->vbuff.curpos = vd->buff;
1626     vd->vbuff.endpos = vd->buff + AP_IOBUFSIZE;
1627
1628     return 0;
1629 }
1630
1631 AP_DECLARE(int) ap_vrprintf(request_rec *r, const char *fmt, va_list va)
1632 {
1633     apr_size_t written;
1634     struct ap_vrprintf_data vd;
1635     char vrprintf_buf[AP_IOBUFSIZE];
1636
1637     vd.vbuff.curpos = vrprintf_buf;
1638     vd.vbuff.endpos = vrprintf_buf + AP_IOBUFSIZE;
1639     vd.r = r;
1640     vd.buff = vrprintf_buf;
1641
1642     if (r->connection->aborted)
1643         return -1;
1644
1645     written = apr_vformatter(r_flush, &vd.vbuff, fmt, va);
1646
1647     if (written != -1) {
1648         int n = vd.vbuff.curpos - vrprintf_buf;
1649
1650         /* last call to buffer_output, to finish clearing the buffer */
1651         if (buffer_output(r, vrprintf_buf,n) != APR_SUCCESS)
1652             return -1;
1653
1654         written += n;
1655     }
1656
1657     return written;
1658 }
1659
1660 AP_DECLARE_NONSTD(int) ap_rprintf(request_rec *r, const char *fmt, ...)
1661 {
1662     va_list va;
1663     int n;
1664
1665     if (r->connection->aborted)
1666         return -1;
1667
1668     va_start(va, fmt);
1669     n = ap_vrprintf(r, fmt, va);
1670     va_end(va);
1671
1672     return n;
1673 }
1674
1675 AP_DECLARE_NONSTD(int) ap_rvputs(request_rec *r, ...)
1676 {
1677     va_list va;
1678     const char *s;
1679     apr_size_t len;
1680     apr_size_t written = 0;
1681
1682     if (r->connection->aborted)
1683         return -1;
1684
1685     /* ### TODO: if the total output is large, put all the strings
1686      * ### into a single brigade, rather than flushing each time we
1687      * ### fill the buffer
1688      */
1689     va_start(va, r);
1690     while (1) {
1691         s = va_arg(va, const char *);
1692         if (s == NULL)
1693             break;
1694
1695         len = strlen(s);
1696         if (buffer_output(r, s, len) != APR_SUCCESS) {
1697             return -1;
1698         }
1699
1700         written += len;
1701     }
1702     va_end(va);
1703
1704     return written;
1705 }
1706
1707 AP_DECLARE(int) ap_rflush(request_rec *r)
1708 {
1709     conn_rec *c = r->connection;
1710     apr_bucket *b;
1711     ap_filter_t *f;
1712     old_write_filter_ctx *ctx;
1713     apr_status_t rv;
1714
1715     f = insert_old_write_filter(r);
1716     ctx = f->ctx;
1717
1718     b = apr_bucket_flush_create(c->bucket_alloc);
1719     APR_BRIGADE_INSERT_TAIL(ctx->tmpbb, b);
1720
1721     rv = ap_pass_brigade(r->output_filters, ctx->tmpbb);
1722     apr_brigade_cleanup(ctx->tmpbb);
1723     if (rv != APR_SUCCESS)
1724         return -1;
1725
1726     return 0;
1727 }
1728
1729 /*
1730  * This function sets the Last-Modified output header field to the value
1731  * of the mtime field in the request structure - rationalized to keep it from
1732  * being in the future.
1733  */
1734 AP_DECLARE(void) ap_set_last_modified(request_rec *r)
1735 {
1736     if (!r->assbackwards) {
1737         apr_time_t mod_time = ap_rationalize_mtime(r, r->mtime);
1738         char *datestr = apr_palloc(r->pool, APR_RFC822_DATE_LEN);
1739
1740         apr_rfc822_date(datestr, mod_time);
1741         apr_table_setn(r->headers_out, "Last-Modified", datestr);
1742     }
1743 }
1744
1745 typedef struct hdr_ptr {
1746     ap_filter_t *f;
1747     apr_bucket_brigade *bb;
1748 } hdr_ptr;
1749 static int send_header(void *data, const char *key, const char *val)
1750 {
1751     ap_fputstrs(((hdr_ptr*)data)->f, ((hdr_ptr*)data)->bb,
1752                 key, ": ", val, CRLF, NULL);
1753     return 1;
1754 }
1755 AP_DECLARE(void) ap_send_interim_response(request_rec *r, int send_headers)
1756 {
1757     hdr_ptr x;
1758     char *status_line = NULL;
1759     request_rec *rr;
1760
1761     if (r->proto_num < HTTP_VERSION(1,1)) {
1762         /* don't send interim response to HTTP/1.0 Client */
1763         return;
1764     }
1765     if (!ap_is_HTTP_INFO(r->status)) {
1766         ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00575)
1767                       "Status is %d - not sending interim response", r->status);
1768         return;
1769     }
1770     if ((r->status == HTTP_CONTINUE) && !r->expecting_100) {
1771         /*
1772          * Don't send 100-Continue when there was no Expect: 100-continue
1773          * in the request headers. For origin servers this is a SHOULD NOT
1774          * for proxies it is a MUST NOT according to RFC 2616 8.2.3
1775          */
1776         return;
1777     }
1778
1779     /* if we send an interim response, we're no longer in a state of
1780      * expecting one.  Also, this could feasibly be in a subrequest,
1781      * so we need to propagate the fact that we responded.
1782      */
1783     for (rr = r; rr != NULL; rr = rr->main) {
1784         rr->expecting_100 = 0;
1785     }
1786
1787     status_line = apr_pstrcat(r->pool, AP_SERVER_PROTOCOL, " ", r->status_line, CRLF, NULL);
1788     ap_xlate_proto_to_ascii(status_line, strlen(status_line));
1789
1790     x.f = r->connection->output_filters;
1791     x.bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
1792
1793     ap_fputs(x.f, x.bb, status_line);
1794     if (send_headers) {
1795         apr_table_do(send_header, &x, r->headers_out, NULL);
1796         apr_table_clear(r->headers_out);
1797     }
1798     ap_fputs(x.f, x.bb, CRLF_ASCII);
1799     ap_fflush(x.f, x.bb);
1800     apr_brigade_destroy(x.bb);
1801 }
1802
1803 /*
1804  * Compare two protocol identifier. Result is similar to strcmp():
1805  * 0 gives same precedence, >0 means proto1 is preferred.
1806  */
1807 static int protocol_cmp(const apr_array_header_t *preferences,
1808                         const char *proto1,
1809                         const char *proto2)
1810 {
1811     if (preferences && preferences->nelts > 0) {
1812         int index1 = ap_array_str_index(preferences, proto1, 0);
1813         int index2 = ap_array_str_index(preferences, proto2, 0);
1814         if (index2 > index1) {
1815             return (index1 >= 0) ? 1 : -1;
1816         }
1817         else if (index1 > index2) {
1818             return (index2 >= 0) ? -1 : 1;
1819         }
1820     }
1821     /* both have the same index (mabye -1 or no pref configured) and we compare
1822      * the names so that spdy3 gets precedence over spdy2. That makes
1823      * the outcome at least deterministic. */
1824     return strcmp(proto1, proto2);
1825 }
1826
1827 AP_DECLARE(const char *) ap_get_protocol(conn_rec *c)
1828 {
1829     const char *protocol = ap_run_protocol_get(c);
1830     return protocol? protocol : AP_PROTOCOL_HTTP1;
1831 }
1832
1833 AP_DECLARE(apr_status_t) ap_get_protocol_upgrades(conn_rec *c, request_rec *r, 
1834                                                   server_rec *s, int report_all, 
1835                                                   const apr_array_header_t **pupgrades)
1836 {
1837     apr_pool_t *pool = r? r->pool : c->pool;
1838     core_server_config *conf;
1839     const char *existing;
1840     apr_array_header_t *upgrades = NULL;
1841
1842     if (!s) {
1843         s = (r? r->server : c->base_server);
1844     }
1845     conf = ap_get_core_module_config(s->module_config);
1846     
1847     if (conf->protocols->nelts > 0) {
1848         existing = ap_get_protocol(c);
1849         if (conf->protocols->nelts > 1 
1850             || !ap_array_str_contains(conf->protocols, existing)) {
1851             int i;
1852             
1853             /* possibly more than one choice or one, but not the
1854              * existing. (TODO: maybe 426 and Upgrade then?) */
1855             upgrades = apr_array_make(pool, conf->protocols->nelts + 1, 
1856                                       sizeof(char *));
1857             for (i = 0; i < conf->protocols->nelts; i++) {
1858                 const char *p = APR_ARRAY_IDX(conf->protocols, i, char *);
1859                 if (strcmp(existing, p)) {
1860                     /* not the one we have and possible, add in this order */
1861                     APR_ARRAY_PUSH(upgrades, const char*) = p;
1862                 }
1863                 else if (!report_all) {
1864                     break;
1865                 }
1866             }
1867         }
1868     }
1869     
1870     *pupgrades = upgrades;
1871     return APR_SUCCESS;
1872 }
1873
1874 AP_DECLARE(const char *) ap_select_protocol(conn_rec *c, request_rec *r, 
1875                                             server_rec *s,
1876                                             const apr_array_header_t *choices)
1877 {
1878     apr_pool_t *pool = r? r->pool : c->pool;
1879     core_server_config *conf;
1880     const char *protocol = NULL, *existing;
1881     apr_array_header_t *proposals;
1882
1883     if (!s) {
1884         s = (r? r->server : c->base_server);
1885     }
1886     conf = ap_get_core_module_config(s->module_config);
1887     
1888     if (APLOGcdebug(c)) {
1889         const char *p = apr_array_pstrcat(pool, conf->protocols, ',');
1890         ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c, APLOGNO(03155) 
1891                       "select protocol from %s, choices=%s for server %s", 
1892                       p, apr_array_pstrcat(pool, choices, ','),
1893                       s->server_hostname);
1894     }
1895
1896     if (conf->protocols->nelts <= 0) {
1897         /* nothing configured, by default, we only allow http/1.1 here.
1898          * For now...
1899          */
1900         if (ap_array_str_contains(choices, AP_PROTOCOL_HTTP1)) {
1901             return AP_PROTOCOL_HTTP1;
1902         }
1903         else {
1904             return NULL;
1905         }
1906     }
1907
1908     proposals = apr_array_make(pool, choices->nelts + 1, sizeof(char *));
1909     ap_run_protocol_propose(c, r, s, choices, proposals);
1910
1911     /* If the existing protocol has not been proposed, but is a choice,
1912      * add it to the proposals implicitly.
1913      */
1914     existing = ap_get_protocol(c);
1915     if (!ap_array_str_contains(proposals, existing)
1916         && ap_array_str_contains(choices, existing)) {
1917         APR_ARRAY_PUSH(proposals, const char*) = existing;
1918     }
1919
1920     if (proposals->nelts > 0) {
1921         int i;
1922         const apr_array_header_t *prefs = NULL;
1923
1924         /* Default for protocols_honor_order is 'on' or != 0 */
1925         if (conf->protocols_honor_order == 0 && choices->nelts > 0) {
1926             prefs = choices;
1927         }
1928         else {
1929             prefs = conf->protocols;
1930         }
1931
1932         /* Select the most preferred protocol */
1933         if (APLOGcdebug(c)) {
1934             ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c, APLOGNO(03156) 
1935                           "select protocol, proposals=%s preferences=%s configured=%s", 
1936                           apr_array_pstrcat(pool, proposals, ','),
1937                           apr_array_pstrcat(pool, prefs, ','),
1938                           apr_array_pstrcat(pool, conf->protocols, ','));
1939         }
1940         for (i = 0; i < proposals->nelts; ++i) {
1941             const char *p = APR_ARRAY_IDX(proposals, i, const char *);
1942             if (!ap_array_str_contains(conf->protocols, p)) {
1943                 /* not a configured protocol here */
1944                 continue;
1945             }
1946             else if (!protocol 
1947                      || (protocol_cmp(prefs, protocol, p) < 0)) {
1948                 /* none selected yet or this one has preference */
1949                 protocol = p;
1950             }
1951         }
1952     }
1953     if (APLOGcdebug(c)) {
1954         ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, c, APLOGNO(03157)
1955                       "selected protocol=%s", 
1956                       protocol? protocol : "(none)");
1957     }
1958
1959     return protocol;
1960 }
1961
1962 AP_DECLARE(apr_status_t) ap_switch_protocol(conn_rec *c, request_rec *r, 
1963                                             server_rec *s,
1964                                             const char *protocol)
1965 {
1966     const char *current = ap_get_protocol(c);
1967     int rc;
1968     
1969     if (!strcmp(current, protocol)) {
1970         ap_log_cerror(APLOG_MARK, APLOG_WARNING, 0, c, APLOGNO(02906)
1971                       "already at it, protocol_switch to %s", 
1972                       protocol);
1973         return APR_SUCCESS;
1974     }
1975     
1976     rc = ap_run_protocol_switch(c, r, s, protocol);
1977     switch (rc) {
1978         case DECLINED:
1979             ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, c, APLOGNO(02907)
1980                           "no implementation for protocol_switch to %s", 
1981                           protocol);
1982             return APR_ENOTIMPL;
1983         case OK:
1984         case DONE:
1985             return APR_SUCCESS;
1986         default:
1987             ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, c, APLOGNO(02905)
1988                           "unexpected return code %d from protocol_switch to %s"
1989                           , rc, protocol);
1990             return APR_EOF;
1991     }    
1992 }
1993
1994 AP_DECLARE(int) ap_is_allowed_protocol(conn_rec *c, request_rec *r,
1995                                        server_rec *s, const char *protocol)
1996 {
1997     core_server_config *conf;
1998
1999     if (!s) {
2000         s = (r? r->server : c->base_server);
2001     }
2002     conf = ap_get_core_module_config(s->module_config);
2003     
2004     if (conf->protocols->nelts > 0) {
2005         return ap_array_str_contains(conf->protocols, protocol);
2006     }
2007     return !strcmp(AP_PROTOCOL_HTTP1, protocol);
2008 }
2009
2010
2011 AP_IMPLEMENT_HOOK_VOID(pre_read_request,
2012                        (request_rec *r, conn_rec *c),
2013                        (r, c))
2014 AP_IMPLEMENT_HOOK_RUN_ALL(int,post_read_request,
2015                           (request_rec *r), (r), OK, DECLINED)
2016 AP_IMPLEMENT_HOOK_RUN_ALL(int,log_transaction,
2017                           (request_rec *r), (r), OK, DECLINED)
2018 AP_IMPLEMENT_HOOK_RUN_FIRST(const char *,http_scheme,
2019                             (const request_rec *r), (r), NULL)
2020 AP_IMPLEMENT_HOOK_RUN_FIRST(unsigned short,default_port,
2021                             (const request_rec *r), (r), 0)
2022 AP_IMPLEMENT_HOOK_RUN_FIRST(int, note_auth_failure,
2023                             (request_rec *r, const char *auth_type),
2024                             (r, auth_type), DECLINED)
2025 AP_IMPLEMENT_HOOK_RUN_ALL(int,protocol_propose,
2026                           (conn_rec *c, request_rec *r, server_rec *s,
2027                            const apr_array_header_t *offers,
2028                            apr_array_header_t *proposals), 
2029                           (c, r, s, offers, proposals), OK, DECLINED)
2030 AP_IMPLEMENT_HOOK_RUN_FIRST(int,protocol_switch,
2031                             (conn_rec *c, request_rec *r, server_rec *s,
2032                              const char *protocol), 
2033                             (c, r, s, protocol), DECLINED)
2034 AP_IMPLEMENT_HOOK_RUN_FIRST(const char *,protocol_get,
2035                             (const conn_rec *c), (c), NULL)