]> granicus.if.org Git - apache/blob - server/core.c
0621294e3311d1220a1bc02960c618f38074b48f
[apache] / server / core.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 #include "apr.h"
60 #include "apr_strings.h"
61 #include "apr_lib.h"
62 #include "apr_fnmatch.h"
63 #include "apr_hash.h"
64 #include "apr_thread_proc.h"    /* for RLIMIT stuff */
65 #include "apr_hooks.h"
66
67 #define APR_WANT_IOVEC
68 #define APR_WANT_STRFUNC
69 #define APR_WANT_MEMFUNC
70 #include "apr_want.h"
71
72 #define CORE_PRIVATE
73 #include "ap_config.h"
74 #include "httpd.h"
75 #include "http_config.h"
76 #include "http_core.h"
77 #include "http_protocol.h"      /* For index_of_response().  Grump. */
78 #include "http_request.h"
79 #include "http_vhost.h"
80 #include "http_main.h"          /* For the default_handler below... */
81 #include "http_log.h"
82 #include "rfc1413.h"
83 #include "util_md5.h"
84 #include "http_connection.h"
85 #include "apr_buckets.h"
86 #include "util_filter.h"
87 #include "util_ebcdic.h"
88 #include "mpm.h"
89 #include "mpm_common.h"
90 #include "scoreboard.h"
91 #include "mod_core.h"
92 #include "mod_proxy.h"
93 #include "ap_listen.h"
94
95 /* LimitXMLRequestBody handling */
96 #define AP_LIMIT_UNSET                  ((long) -1)
97 #define AP_DEFAULT_LIMIT_XML_BODY       ((size_t)1000000)
98
99 #define AP_MIN_SENDFILE_BYTES           (256)
100
101 APR_HOOK_STRUCT(
102     APR_HOOK_LINK(get_mgmt_items)
103 )
104
105 AP_IMPLEMENT_HOOK_RUN_ALL(int, get_mgmt_items,
106                           (apr_pool_t *p, const char *val, apr_hash_t *ht),
107                           (p, val, ht), OK, DECLINED)
108
109 /* Server core module... This module provides support for really basic
110  * server operations, including options and commands which control the
111  * operation of other modules.  Consider this the bureaucracy module.
112  *
113  * The core module also defines handlers, etc., do handle just enough
114  * to allow a server with the core module ONLY to actually serve documents
115  * (though it slaps DefaultType on all of 'em); this was useful in testing,
116  * but may not be worth preserving.
117  *
118  * This file could almost be mod_core.c, except for the stuff which affects
119  * the http_conf_globals.
120  */
121
122 /* Handles for core filters */
123 ap_filter_rec_t *ap_subreq_core_filter_handle;
124 ap_filter_rec_t *ap_core_output_filter_handle;
125 ap_filter_rec_t *ap_content_length_filter_handle;
126 ap_filter_rec_t *ap_net_time_filter_handle;
127 ap_filter_rec_t *ap_core_input_filter_handle;
128
129 static void *create_core_dir_config(apr_pool_t *a, char *dir)
130 {
131     core_dir_config *conf;
132
133     conf = (core_dir_config *)apr_pcalloc(a, sizeof(core_dir_config));
134     
135     /* conf->r and conf->d[_*] are initialized by dirsection() or left NULL */
136
137     conf->opts = dir ? OPT_UNSET : OPT_UNSET|OPT_ALL;
138     conf->opts_add = conf->opts_remove = OPT_NONE;
139     conf->override = dir ? OR_UNSET : OR_UNSET|OR_ALL;
140
141     conf->content_md5 = 2;
142     conf->accept_path_info = 3;
143
144     conf->use_canonical_name = USE_CANONICAL_NAME_UNSET;
145
146     conf->hostname_lookups = HOSTNAME_LOOKUP_UNSET;
147     conf->do_rfc1413 = DEFAULT_RFC1413 | 2; /* set bit 1 to indicate default */
148     conf->satisfy = SATISFY_NOSPEC;
149
150 #ifdef RLIMIT_CPU
151     conf->limit_cpu = NULL;
152 #endif
153 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
154     conf->limit_mem = NULL;
155 #endif
156 #ifdef RLIMIT_NPROC
157     conf->limit_nproc = NULL;
158 #endif
159
160     conf->limit_req_body = 0;
161     conf->limit_xml_body = AP_LIMIT_UNSET;
162     conf->sec_file = apr_array_make(a, 2, sizeof(ap_conf_vector_t *));
163
164     conf->server_signature = srv_sig_unset;
165
166     conf->add_default_charset = ADD_DEFAULT_CHARSET_UNSET;
167     conf->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
168
169     /* Overriding all negotiation 
170      */
171     conf->mime_type = NULL;
172     conf->handler = NULL;
173     conf->output_filters = NULL;
174     conf->input_filters = NULL;
175
176     /*
177      * Flag for use of inodes in ETags.
178      */
179     conf->etag_bits = ETAG_UNSET;
180     conf->etag_add = ETAG_UNSET;
181     conf->etag_remove = ETAG_UNSET;
182
183     return (void *)conf;
184 }
185
186 /*
187  * Overlay one hash table of ct_output_filters onto another
188  */
189 static void *merge_ct_filters(apr_pool_t *p,
190                               const void *key,
191                               apr_ssize_t klen,
192                               const void *overlay_val,
193                               const void *base_val,
194                               const void *data)
195 {
196     ap_filter_rec_t *cur;
197     const ap_filter_rec_t *overlay_info = (const ap_filter_rec_t *)overlay_val;
198     const ap_filter_rec_t *base_info = (const ap_filter_rec_t *)base_val;
199
200     cur = NULL;
201     
202     while (overlay_info) {
203         ap_filter_rec_t *new;
204
205         new = apr_pcalloc(p, sizeof(ap_filter_rec_t));
206         new->name = apr_pstrdup(p, overlay_info->name);
207         new->next = cur;
208         cur = new;
209         overlay_info = overlay_info->next;
210     }
211
212     while (base_info) {
213         ap_filter_rec_t *f;
214         int found = 0;
215
216         /* We can't have dups. */
217         f = cur;
218         while (f) {
219             if (!strcasecmp(base_info->name, f->name)) {
220                 found = 1;
221                 break;
222             }
223             f = f->next;
224         }
225         if (!found) {
226             f = apr_pcalloc(p, sizeof(ap_filter_rec_t));
227             f->name = apr_pstrdup(p, base_info->name);
228             f->next = cur;
229             cur = f;
230         }
231         base_info = base_info->next;
232     }
233
234     return cur;
235 }
236
237 static void *merge_core_dir_configs(apr_pool_t *a, void *basev, void *newv)
238 {
239     core_dir_config *base = (core_dir_config *)basev;
240     core_dir_config *new = (core_dir_config *)newv;
241     core_dir_config *conf;
242     int i;
243
244     /* Create this conf by duplicating the base, replacing elements
245      * (or creating copies for merging) where new-> values exist.
246      */
247     conf = (core_dir_config *)apr_palloc(a, sizeof(core_dir_config));
248     memcpy(conf, base, sizeof(core_dir_config));
249
250     conf->d = new->d;
251     conf->d_is_fnmatch = new->d_is_fnmatch;
252     conf->d_components = new->d_components;
253     conf->r = new->r;
254     
255     if (new->opts & OPT_UNSET) {
256         /* there was no explicit setting of new->opts, so we merge
257          * preserve the invariant (opts_add & opts_remove) == 0
258          */
259         conf->opts_add = (conf->opts_add & ~new->opts_remove) | new->opts_add;
260         conf->opts_remove = (conf->opts_remove & ~new->opts_add)
261                             | new->opts_remove;
262         conf->opts = (conf->opts & ~conf->opts_remove) | conf->opts_add;
263         if ((base->opts & OPT_INCNOEXEC) && (new->opts & OPT_INCLUDES)) {
264             conf->opts = (conf->opts & ~OPT_INCNOEXEC) | OPT_INCLUDES;
265         }
266     }
267     else {
268         /* otherwise we just copy, because an explicit opts setting
269          * overrides all earlier +/- modifiers
270          */
271         conf->opts = new->opts;
272         conf->opts_add = new->opts_add;
273         conf->opts_remove = new->opts_remove;
274     }
275
276     if (!(new->override & OR_UNSET)) {
277         conf->override = new->override;
278     }
279     if (new->ap_default_type) {
280         conf->ap_default_type = new->ap_default_type;
281     }
282     
283     if (new->ap_auth_type) {
284         conf->ap_auth_type = new->ap_auth_type;
285     }
286
287     if (new->ap_auth_name) {
288         conf->ap_auth_name = new->ap_auth_name;
289     }
290
291     if (new->ap_requires) {
292         conf->ap_requires = new->ap_requires;
293     }
294
295     if (conf->response_code_strings == NULL) {
296         conf->response_code_strings = new->response_code_strings;
297     }
298     else if (new->response_code_strings != NULL) {
299         /* If we merge, the merge-result must have it's own array 
300          */
301         conf->response_code_strings = apr_palloc(a,
302             sizeof(*conf->response_code_strings) * RESPONSE_CODES);
303         memcpy(conf->response_code_strings, base->response_code_strings,
304                sizeof(*conf->response_code_strings) * RESPONSE_CODES);
305         for (i = 0; i < RESPONSE_CODES; ++i) {
306             if (new->response_code_strings[i] != NULL) {
307                 conf->response_code_strings[i]
308                     = new->response_code_strings[i];
309             }
310         }
311     }
312     /* Otherwise we simply use the base->response_code_strings array
313      */
314
315     if (new->hostname_lookups != HOSTNAME_LOOKUP_UNSET) {
316         conf->hostname_lookups = new->hostname_lookups;
317     }
318     if ((new->do_rfc1413 & 2) == 0) {
319         conf->do_rfc1413 = new->do_rfc1413;
320     }
321     if ((new->content_md5 & 2) == 0) {
322         conf->content_md5 = new->content_md5;
323     }
324     if (new->accept_path_info != 3) {
325         conf->accept_path_info = new->accept_path_info;
326     }
327     if (new->use_canonical_name != USE_CANONICAL_NAME_UNSET) {
328         conf->use_canonical_name = new->use_canonical_name;
329     }
330
331 #ifdef RLIMIT_CPU
332     if (new->limit_cpu) {
333         conf->limit_cpu = new->limit_cpu;
334     }
335 #endif
336 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
337     if (new->limit_mem) {
338         conf->limit_mem = new->limit_mem;
339     }
340 #endif
341 #ifdef RLIMIT_NPROC
342     if (new->limit_nproc) {
343         conf->limit_nproc = new->limit_nproc;
344     }
345 #endif
346
347     if (new->limit_req_body) {
348         conf->limit_req_body = new->limit_req_body;
349     }
350
351     if (new->limit_xml_body != AP_LIMIT_UNSET)
352         conf->limit_xml_body = new->limit_xml_body;
353     else
354         conf->limit_xml_body = base->limit_xml_body;
355
356     if (!conf->sec_file) {
357         conf->sec_file = new->sec_file;
358     }
359     else if (new->sec_file) {
360         /* If we merge, the merge-result must have it's own array 
361          */
362         conf->sec_file = apr_array_append(a, base->sec_file, new->sec_file);
363     }
364     /* Otherwise we simply use the base->sec_file array
365      */
366
367     if (new->satisfy != SATISFY_NOSPEC) {
368         conf->satisfy = new->satisfy;
369     }
370
371     if (new->server_signature != srv_sig_unset) {
372         conf->server_signature = new->server_signature;
373     }
374
375     if (new->add_default_charset != ADD_DEFAULT_CHARSET_UNSET) {
376         conf->add_default_charset = new->add_default_charset;
377         conf->add_default_charset_name = new->add_default_charset_name;
378     }
379
380     /* Overriding all negotiation 
381      */
382     if (new->mime_type) {
383         conf->mime_type = new->mime_type;
384     }
385
386     if (new->handler) {
387         conf->handler = new->handler;
388     }
389
390     if (new->output_filters) {
391         conf->output_filters = new->output_filters;
392     }
393
394     if (new->input_filters) {
395         conf->input_filters = new->input_filters;
396     }
397
398     if (conf->ct_output_filters && new->ct_output_filters) {
399         conf->ct_output_filters = apr_hash_merge(a, 
400                                                  new->ct_output_filters,
401                                                  conf->ct_output_filters,
402                                                  merge_ct_filters,
403                                                  NULL);
404     }
405     else if (new->ct_output_filters) {
406         conf->ct_output_filters = apr_hash_copy(a, new->ct_output_filters);
407     }
408     else if (conf->ct_output_filters) {
409         /* That memcpy above isn't enough. */
410         conf->ct_output_filters = apr_hash_copy(a, base->ct_output_filters);
411     }
412
413     /*
414      * Now merge the setting of the FileETag directive.
415      */
416     if (new->etag_bits == ETAG_UNSET) {
417         conf->etag_add =
418             (conf->etag_add & (~ new->etag_remove)) | new->etag_add;
419         conf->etag_remove =
420             (conf->opts_remove & (~ new->etag_add)) | new->etag_remove;
421         conf->etag_bits =
422             (conf->etag_bits & (~ conf->etag_remove)) | conf->etag_add;
423     }
424     else {
425         conf->etag_bits = new->etag_bits;
426         conf->etag_add = new->etag_add;
427         conf->etag_remove = new->etag_remove;
428     }
429     if (conf->etag_bits != ETAG_NONE) {
430         conf->etag_bits &= (~ ETAG_NONE);
431     }
432
433     return (void*)conf;
434 }
435
436 static void *create_core_server_config(apr_pool_t *a, server_rec *s)
437 {
438     core_server_config *conf;
439     int is_virtual = s->is_virtual;
440   
441     conf = (core_server_config *)apr_pcalloc(a, sizeof(core_server_config));
442 #ifdef GPROF
443     conf->gprof_dir = NULL;
444 #endif
445     conf->access_name = is_virtual ? NULL : DEFAULT_ACCESS_FNAME;
446     conf->ap_document_root = is_virtual ? NULL : DOCUMENT_LOCATION;
447     conf->sec_dir = apr_array_make(a, 40, sizeof(ap_conf_vector_t *));
448     conf->sec_url = apr_array_make(a, 40, sizeof(ap_conf_vector_t *));
449     
450     return (void *)conf;
451 }
452
453 static void *merge_core_server_configs(apr_pool_t *p, void *basev, void *virtv)
454 {
455     core_server_config *base = (core_server_config *)basev;
456     core_server_config *virt = (core_server_config *)virtv;
457     core_server_config *conf;
458
459     conf = (core_server_config *)apr_palloc(p, sizeof(core_server_config));
460     memcpy(conf, virt, sizeof(core_server_config));
461     if (!conf->access_name) {
462         conf->access_name = base->access_name;
463     }
464     if (!conf->ap_document_root) {
465         conf->ap_document_root = base->ap_document_root;
466     }
467     conf->sec_dir = apr_array_append(p, base->sec_dir, virt->sec_dir);
468     conf->sec_url = apr_array_append(p, base->sec_url, virt->sec_url);
469
470     return conf;
471 }
472
473 /* Add per-directory configuration entry (for <directory> section);
474  * these are part of the core server config.
475  */
476
477 AP_CORE_DECLARE(void) ap_add_per_dir_conf(server_rec *s, void *dir_config)
478 {
479     core_server_config *sconf = ap_get_module_config(s->module_config,
480                                                      &core_module);
481     void **new_space = (void **)apr_array_push(sconf->sec_dir);
482     
483     *new_space = dir_config;
484 }
485
486 AP_CORE_DECLARE(void) ap_add_per_url_conf(server_rec *s, void *url_config)
487 {
488     core_server_config *sconf = ap_get_module_config(s->module_config,
489                                                      &core_module);
490     void **new_space = (void **)apr_array_push(sconf->sec_url);
491     
492     *new_space = url_config;
493 }
494
495 AP_CORE_DECLARE(void) ap_add_file_conf(core_dir_config *conf, void *url_config)
496 {
497     void **new_space = (void **)apr_array_push(conf->sec_file);
498     
499     *new_space = url_config;
500 }
501
502 /* We need to do a stable sort, qsort isn't stable.  So to make it stable
503  * we'll be maintaining the original index into the list, and using it
504  * as the minor key during sorting.  The major key is the number of
505  * components (where the root component is zero).
506  */
507 struct reorder_sort_rec {
508     ap_conf_vector_t *elt;
509     int orig_index;
510 };
511
512 static int reorder_sorter(const void *va, const void *vb)
513 {
514     const struct reorder_sort_rec *a = va;
515     const struct reorder_sort_rec *b = vb;
516     core_dir_config *core_a;
517     core_dir_config *core_b;
518
519     core_a = ap_get_module_config(a->elt, &core_module);
520     core_b = ap_get_module_config(b->elt, &core_module);
521
522     /* a regex always sorts after a non-regex
523      */
524     if (!core_a->r && core_b->r) {
525         return -1;
526     }
527     else if (core_a->r && !core_b->r) {
528         return 1;
529     }
530     /* we always sort next by the number of components
531      */
532     if (core_a->d_components < core_b->d_components) {
533         return -1;
534     }
535     else if (core_a->d_components > core_b->d_components) {
536         return 1;
537     }
538     /* They have the same number of components, we now have to compare
539      * the minor key to maintain the original order (from the config.) 
540      */
541     return a->orig_index - b->orig_index;
542 }
543
544 void ap_core_reorder_directories(apr_pool_t *p, server_rec *s)
545 {
546     core_server_config *sconf;
547     apr_array_header_t *sec_dir;
548     struct reorder_sort_rec *sortbin;
549     int nelts;
550     ap_conf_vector_t **elts;
551     int i;
552     apr_pool_t *tmp;
553
554     sconf = ap_get_module_config(s->module_config, &core_module);
555     sec_dir = sconf->sec_dir;
556     nelts = sec_dir->nelts;
557     elts = (ap_conf_vector_t **)sec_dir->elts;
558
559     if (!nelts) {
560         /* simple case of already being sorted... */
561         /* We're not checking this condition to be fast... we're checking
562          * it to avoid trying to palloc zero bytes, which can trigger some
563          * memory debuggers to barf
564          */
565         return;
566     }
567     
568     /* we have to allocate tmp space to do a stable sort */
569     apr_pool_create(&tmp, p);
570     sortbin = apr_palloc(tmp, sec_dir->nelts * sizeof(*sortbin));
571     for (i = 0; i < nelts; ++i) {
572         sortbin[i].orig_index = i;
573         sortbin[i].elt = elts[i];
574     }
575
576     qsort(sortbin, nelts, sizeof(*sortbin), reorder_sorter);
577
578     /* and now copy back to the original array */
579     for (i = 0; i < nelts; ++i) {
580       elts[i] = sortbin[i].elt;
581     }
582
583     apr_pool_destroy(tmp);
584 }
585
586 /*****************************************************************
587  *
588  * There are some elements of the core config structures in which
589  * other modules have a legitimate interest (this is ugly, but necessary
590  * to preserve NCSA back-compatibility).  So, we have a bunch of accessors
591  * here...
592  */
593
594 AP_DECLARE(int) ap_allow_options(request_rec *r)
595 {
596     core_dir_config *conf = 
597       (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module); 
598
599     return conf->opts; 
600
601
602 AP_DECLARE(int) ap_allow_overrides(request_rec *r) 
603
604     core_dir_config *conf;
605     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
606                                                    &core_module); 
607
608     return conf->override; 
609
610
611 AP_DECLARE(const char *) ap_auth_type(request_rec *r)
612 {
613     core_dir_config *conf;
614
615     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
616                                                    &core_module); 
617     return conf->ap_auth_type;
618 }
619
620 AP_DECLARE(const char *) ap_auth_name(request_rec *r)
621 {
622     core_dir_config *conf;
623
624     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
625                                                    &core_module); 
626     return conf->ap_auth_name;
627 }
628
629 AP_DECLARE(const char *) ap_default_type(request_rec *r)
630 {
631     core_dir_config *conf;
632
633     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
634                                                    &core_module); 
635     return conf->ap_default_type 
636                ? conf->ap_default_type 
637                : DEFAULT_CONTENT_TYPE;
638 }
639
640 AP_DECLARE(const char *) ap_document_root(request_rec *r) /* Don't use this! */
641 {
642     core_server_config *conf;
643
644     conf = (core_server_config *)ap_get_module_config(r->server->module_config,
645                                                       &core_module); 
646     return conf->ap_document_root;
647 }
648
649 AP_DECLARE(const apr_array_header_t *) ap_requires(request_rec *r)
650 {
651     core_dir_config *conf;
652
653     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
654                                                    &core_module); 
655     return conf->ap_requires;
656 }
657
658 AP_DECLARE(int) ap_satisfies(request_rec *r)
659 {
660     core_dir_config *conf;
661
662     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
663                                                    &core_module);
664
665     return conf->satisfy;
666 }
667
668 /* Should probably just get rid of this... the only code that cares is
669  * part of the core anyway (and in fact, it isn't publicised to other
670  * modules).
671  */
672
673 char *ap_response_code_string(request_rec *r, int error_index)
674 {
675     core_dir_config *conf;
676
677     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
678                                                    &core_module); 
679
680     if (conf->response_code_strings == NULL) {
681         return NULL;
682     }
683     return conf->response_code_strings[error_index];
684 }
685
686
687 /* Code from Harald Hanche-Olsen <hanche@imf.unit.no> */
688 static APR_INLINE void do_double_reverse (conn_rec *conn)
689 {
690     apr_sockaddr_t *sa;
691     apr_status_t rv;
692
693     if (conn->double_reverse) {
694         /* already done */
695         return;
696     }
697     if (conn->remote_host == NULL || conn->remote_host[0] == '\0') {
698         /* single reverse failed, so don't bother */
699         conn->double_reverse = -1;
700         return;
701     }
702     rv = apr_sockaddr_info_get(&sa, conn->remote_host, APR_UNSPEC, 0, 0, conn->pool);
703     if (rv == APR_SUCCESS) {
704         while (sa) {
705             if (apr_sockaddr_equal(sa, conn->remote_addr)) {
706                 conn->double_reverse = 1;
707                 return;
708             }
709             sa = sa->next;
710         }
711     }
712     conn->double_reverse = -1;
713 }
714
715 AP_DECLARE(const char *) ap_get_remote_host(conn_rec *conn, void *dir_config,
716                                             int type, int *str_is_ip)
717 {
718     int hostname_lookups;
719
720     if (str_is_ip) { /* if caller wants to know */
721         *str_is_ip = 0;
722     }
723
724     /* If we haven't checked the host name, and we want to */
725     if (dir_config) {
726         hostname_lookups =
727             ((core_dir_config *)ap_get_module_config(dir_config, &core_module))
728                 ->hostname_lookups;
729         if (hostname_lookups == HOSTNAME_LOOKUP_UNSET) {
730             hostname_lookups = HOSTNAME_LOOKUP_OFF;
731         }
732     }
733     else {
734         /* the default */
735         hostname_lookups = HOSTNAME_LOOKUP_OFF;
736     }
737
738     if (type != REMOTE_NOLOOKUP
739         && conn->remote_host == NULL
740         && (type == REMOTE_DOUBLE_REV
741             || hostname_lookups != HOSTNAME_LOOKUP_OFF)) {
742
743         if (apr_getnameinfo(&conn->remote_host, conn->remote_addr, 0) == APR_SUCCESS) {
744             ap_str_tolower(conn->remote_host);
745            
746             if (hostname_lookups == HOSTNAME_LOOKUP_DOUBLE) {
747                 do_double_reverse(conn);
748                 if (conn->double_reverse != 1) {
749                     conn->remote_host = NULL;
750                 }
751             }
752         }
753         /* if failed, set it to the NULL string to indicate error */
754         if (conn->remote_host == NULL) {
755             conn->remote_host = "";
756         }
757     }
758     if (type == REMOTE_DOUBLE_REV) {
759         do_double_reverse(conn);
760         if (conn->double_reverse == -1) {
761             return NULL;
762         }
763     }
764
765 /*
766  * Return the desired information; either the remote DNS name, if found,
767  * or either NULL (if the hostname was requested) or the IP address
768  * (if any identifier was requested).
769  */
770     if (conn->remote_host != NULL && conn->remote_host[0] != '\0') {
771         return conn->remote_host;
772     }
773     else {
774         if (type == REMOTE_HOST || type == REMOTE_DOUBLE_REV) {
775             return NULL;
776         }
777         else {
778             if (str_is_ip) { /* if caller wants to know */
779                 *str_is_ip = 1;
780             }
781             return conn->remote_ip;
782         }
783     }
784 }
785
786 AP_DECLARE(const char *) ap_get_remote_logname(request_rec *r)
787 {
788     core_dir_config *dir_conf;
789
790     if (r->connection->remote_logname != NULL) {
791         return r->connection->remote_logname;
792     }
793
794 /* If we haven't checked the identity, and we want to */
795     dir_conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
796                                                        &core_module);
797
798     if (dir_conf->do_rfc1413 & 1) {
799         return ap_rfc1413(r->connection, r->server);
800     }
801     else {
802         return NULL;
803     }
804 }
805
806 /* There are two options regarding what the "name" of a server is.  The
807  * "canonical" name as defined by ServerName and Port, or the "client's
808  * name" as supplied by a possible Host: header or full URI.  We never
809  * trust the port passed in the client's headers, we always use the
810  * port of the actual socket.
811  *
812  * The DNS option to UseCanonicalName causes this routine to do a
813  * reverse lookup on the local IP address of the connection and use
814  * that for the ServerName. This makes its value more reliable while
815  * at the same time allowing Demon's magic virtual hosting to work.
816  * The assumption is that DNS lookups are sufficiently quick...
817  * -- fanf 1998-10-03
818  */
819 AP_DECLARE(const char *) ap_get_server_name(request_rec *r)
820 {
821     conn_rec *conn = r->connection;
822     core_dir_config *d;
823
824     d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
825                                                 &core_module);
826
827     if (d->use_canonical_name == USE_CANONICAL_NAME_OFF) {
828         return r->hostname ? r->hostname : r->server->server_hostname;
829     }
830     if (d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
831         if (conn->local_host == NULL) {
832
833             if (apr_getnameinfo(&conn->local_host, conn->local_addr, 0) != APR_SUCCESS)
834                 conn->local_host = apr_pstrdup(conn->pool, r->server->server_hostname);
835             else {
836                 ap_str_tolower(conn->local_host);
837             }
838         }
839         return conn->local_host;
840     }
841     /* default */
842     return r->server->server_hostname;
843 }
844
845 AP_DECLARE(apr_port_t) ap_get_server_port(const request_rec *r)
846 {
847     apr_port_t port;
848     core_dir_config *d =
849       (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
850     
851     if (d->use_canonical_name == USE_CANONICAL_NAME_OFF
852         || d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
853
854         /* With UseCanonicalName off Apache will form self-referential
855          * URLs using the hostname and port supplied by the client if
856          * any are supplied (otherwise it will use the canonical name).
857          */
858         port = r->parsed_uri.port ? r->parsed_uri.port :
859                r->server->port ? r->server->port :
860                ap_default_port(r);
861     }
862     else { /* d->use_canonical_name == USE_CANONICAL_NAME_ON */
863
864         /* With UseCanonicalName on (and in all versions prior to 1.3)
865          * Apache will use the hostname and port specified in the
866          * ServerName directive to construct a canonical name for the
867          * server. (If no port was specified in the ServerName
868          * directive, Apache uses the port supplied by the client if
869          * any is supplied, and finally the default port for the protocol
870          * used.
871          */
872         port = r->server->port ? r->server->port :
873                r->connection->local_addr->port ? r->connection->local_addr->port :
874                ap_default_port(r);
875     }
876
877     /* default */
878     return port;
879 }
880
881 AP_DECLARE(char *) ap_construct_url(apr_pool_t *p, const char *uri,
882                                     request_rec *r)
883 {
884     unsigned port = ap_get_server_port(r);
885     const char *host = ap_get_server_name(r);
886
887     if (ap_is_default_port(port, r)) {
888         return apr_pstrcat(p, ap_http_method(r), "://", host, uri, NULL);
889     }
890     return apr_psprintf(p, "%s://%s:%u%s", ap_http_method(r), host, port, uri);
891 }
892
893 AP_DECLARE(apr_off_t) ap_get_limit_req_body(const request_rec *r)
894 {
895     core_dir_config *d =
896       (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
897     
898     return d->limit_req_body;
899 }
900
901
902 /*****************************************************************
903  *
904  * Commands... this module handles almost all of the NCSA httpd.conf
905  * commands, but most of the old srm.conf is in the the modules.
906  */
907
908
909 /* returns a parent if it matches the given directive */
910 static const ap_directive_t * find_parent(const ap_directive_t *dirp,
911                                           const char *what)
912 {
913     while (dirp->parent != NULL) {
914         dirp = dirp->parent;
915         /* ### it would be nice to have atom-ized directives */
916         if (strcasecmp(dirp->directive, what) == 0)
917             return dirp;
918     }
919     return NULL;
920 }
921
922 AP_DECLARE(const char *) ap_check_cmd_context(cmd_parms *cmd,
923                                               unsigned forbidden)
924 {
925     const char *gt = (cmd->cmd->name[0] == '<'
926                       && cmd->cmd->name[strlen(cmd->cmd->name)-1] != '>')
927                          ? ">" : "";
928     const ap_directive_t *found;
929
930     if ((forbidden & NOT_IN_VIRTUALHOST) && cmd->server->is_virtual) {
931         return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
932                           " cannot occur within <VirtualHost> section", NULL);
933     }
934
935     if ((forbidden & NOT_IN_LIMIT) && cmd->limited != -1) {
936         return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
937                           " cannot occur within <Limit> section", NULL);
938     }
939
940     if ((forbidden & NOT_IN_DIR_LOC_FILE) == NOT_IN_DIR_LOC_FILE
941         && cmd->path != NULL) {
942         return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
943                           " cannot occur within <Directory/Location/Files> "
944                           "section", NULL);
945     }
946     
947     if (((forbidden & NOT_IN_DIRECTORY)
948          && ((found = find_parent(cmd->directive, "<Directory"))
949              || (found = find_parent(cmd->directive, "<DirectoryMatch"))))
950         || ((forbidden & NOT_IN_LOCATION)
951             && ((found = find_parent(cmd->directive, "<Location"))
952                 || (found = find_parent(cmd->directive, "<LocationMatch"))))
953         || ((forbidden & NOT_IN_FILES)
954             && ((found = find_parent(cmd->directive, "<Files"))
955                 || (found = find_parent(cmd->directive, "<FilesMatch"))))) {
956         return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
957                           " cannot occur within ", found->directive,
958                           "> section", NULL);
959     }
960
961     return NULL;
962 }
963
964 static const char *set_access_name(cmd_parms *cmd, void *dummy,
965                                    const char *arg)
966 {
967     void *sconf = cmd->server->module_config;
968     core_server_config *conf = ap_get_module_config(sconf, &core_module);
969
970     const char *err = ap_check_cmd_context(cmd,
971                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
972     if (err != NULL) {
973         return err;
974     }
975
976     conf->access_name = apr_pstrdup(cmd->pool, arg);
977     return NULL;
978 }
979
980 #ifdef GPROF
981 static const char *set_gprof_dir(cmd_parms *cmd, void *dummy, const char *arg)
982 {
983     void *sconf = cmd->server->module_config;
984     core_server_config *conf = ap_get_module_config(sconf, &core_module);
985
986     const char *err = ap_check_cmd_context(cmd,
987                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
988     if (err != NULL) {
989         return err;
990     }
991
992     conf->gprof_dir = apr_pstrdup(cmd->pool, arg);
993     return NULL;
994 }
995 #endif /*GPROF*/
996
997 static const char *set_add_default_charset(cmd_parms *cmd, 
998                                            void *d_, const char *arg)
999 {
1000     core_dir_config *d=d_;
1001
1002     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1003     if (err != NULL) {
1004         return err;
1005     }
1006     if (!strcasecmp(arg, "Off")) {
1007        d->add_default_charset = ADD_DEFAULT_CHARSET_OFF;
1008     }
1009     else if (!strcasecmp(arg, "On")) {
1010        d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1011        d->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
1012     }
1013     else {
1014        d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1015        d->add_default_charset_name = arg;
1016     }
1017     return NULL;
1018 }
1019
1020 static const char *set_document_root(cmd_parms *cmd, void *dummy,
1021                                      const char *arg)
1022 {
1023     void *sconf = cmd->server->module_config;
1024     core_server_config *conf = ap_get_module_config(sconf, &core_module);
1025   
1026     const char *err = ap_check_cmd_context(cmd,
1027                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1028     if (err != NULL) {
1029         return err;
1030     }
1031
1032     /* TODO: ap_configtestonly && ap_docrootcheck && */
1033     /* XXX Shouldn't this be relative to ServerRoot ??? */
1034     if (apr_filepath_merge((char**)&conf->ap_document_root, NULL, arg,
1035                            APR_FILEPATH_TRUENAME, cmd->pool) != APR_SUCCESS
1036         || !ap_is_directory(cmd->pool, arg)) {
1037         if (cmd->server->is_virtual) {
1038             ap_log_perror(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, cmd->pool,
1039                          "Warning: DocumentRoot [%s] does not exist",
1040                          arg);
1041             conf->ap_document_root = arg;
1042         }
1043         else {
1044             return "DocumentRoot must be a directory";
1045         }
1046     }
1047     return NULL;
1048 }
1049
1050 AP_DECLARE(void) ap_custom_response(request_rec *r, int status, const char *string)
1051 {
1052     core_dir_config *conf = 
1053         ap_get_module_config(r->per_dir_config, &core_module);
1054     int idx;
1055
1056     if(conf->response_code_strings == NULL) {
1057         conf->response_code_strings = 
1058             apr_pcalloc(r->pool,
1059                     sizeof(*conf->response_code_strings) * 
1060                     RESPONSE_CODES);
1061     }
1062
1063     idx = ap_index_of_response(status);
1064
1065     conf->response_code_strings[idx] = 
1066        ((ap_is_url(string) || (*string == '/')) && (*string != '"')) ? 
1067        apr_pstrdup(r->pool, string) : apr_pstrcat(r->pool, "\"", string, NULL);
1068 }
1069
1070 static const char *set_error_document(cmd_parms *cmd, void *conf_,
1071                                       const char *errno_str, const char *msg)
1072 {
1073     core_dir_config *conf=conf_;
1074     int error_number, index_number, idx500;
1075     enum { MSG, LOCAL_PATH, REMOTE_PATH } what = MSG;
1076                 
1077     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1078     if (err != NULL) {
1079         return err;
1080     }
1081
1082     /* 1st parameter should be a 3 digit number, which we recognize;
1083      * convert it into an array index
1084      */
1085     error_number = atoi(errno_str);
1086     idx500 = ap_index_of_response(HTTP_INTERNAL_SERVER_ERROR);
1087
1088     if (error_number == HTTP_INTERNAL_SERVER_ERROR) {
1089         index_number = idx500;
1090     }
1091     else if ((index_number = ap_index_of_response(error_number)) == idx500) {
1092         return apr_pstrcat(cmd->pool, "Unsupported HTTP response code ",
1093                           errno_str, NULL);
1094     }
1095
1096     /* Heuristic to determine second argument. */
1097     if (ap_strchr_c(msg,' ')) 
1098         what = MSG;
1099     else if (msg[0] == '/')
1100         what = LOCAL_PATH;
1101     else if (ap_is_url(msg))
1102         what = REMOTE_PATH;
1103     else
1104         what = MSG;
1105    
1106     /* The entry should be ignored if it is a full URL for a 401 error */
1107
1108     if (error_number == 401 && what == REMOTE_PATH) {
1109         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, cmd->server,
1110                      "cannot use a full URL in a 401 ErrorDocument "
1111                      "directive --- ignoring!");
1112     }
1113     else { /* Store it... */
1114         if (conf->response_code_strings == NULL) {
1115             conf->response_code_strings =
1116                 apr_pcalloc(cmd->pool,
1117                            sizeof(*conf->response_code_strings) * RESPONSE_CODES);
1118         }
1119         /* hack. Prefix a " if it is a msg; as that is what
1120          * http_protocol.c relies on to distinguish between
1121          * a msg and a (local) path.
1122          */
1123         conf->response_code_strings[index_number] = (what == MSG) ?
1124                 apr_pstrcat(cmd->pool, "\"",msg,NULL) :
1125                 apr_pstrdup(cmd->pool, msg);
1126     }   
1127
1128     return NULL;
1129 }
1130
1131 static const char *set_override(cmd_parms *cmd, void *d_, const char *l)
1132 {
1133     core_dir_config *d=d_;
1134     char *w;
1135   
1136     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1137     if (err != NULL) {
1138         return err;
1139     }
1140
1141     d->override = OR_NONE;
1142     while (l[0]) {
1143         w = ap_getword_conf(cmd->pool, &l);
1144         if (!strcasecmp(w, "Limit")) {
1145             d->override |= OR_LIMIT;
1146         }
1147         else if (!strcasecmp(w, "Options")) {
1148             d->override |= OR_OPTIONS;
1149         }
1150         else if (!strcasecmp(w, "FileInfo")) {
1151             d->override |= OR_FILEINFO;
1152         }
1153         else if (!strcasecmp(w, "AuthConfig")) {
1154             d->override |= OR_AUTHCFG;
1155         }
1156         else if (!strcasecmp(w, "Indexes")) {
1157             d->override |= OR_INDEXES;
1158         }
1159         else if (!strcasecmp(w, "None")) {
1160             d->override = OR_NONE;
1161         }
1162         else if (!strcasecmp(w, "All")) {
1163             d->override = OR_ALL;
1164         }
1165         else {
1166             return apr_pstrcat(cmd->pool, "Illegal override option ", w, NULL);
1167         }
1168         d->override &= ~OR_UNSET;
1169     }
1170
1171     return NULL;
1172 }
1173
1174 static const char *set_options(cmd_parms *cmd, void *d_, const char *l)
1175 {
1176     core_dir_config *d=d_;
1177     allow_options_t opt;
1178     int first = 1;
1179     char action;
1180
1181     while (l[0]) {
1182         char *w = ap_getword_conf(cmd->pool, &l);
1183         action = '\0';
1184
1185         if (*w == '+' || *w == '-') {
1186             action = *(w++);
1187         }
1188         else if (first) {
1189             d->opts = OPT_NONE;
1190             first = 0;
1191         }
1192             
1193         if (!strcasecmp(w, "Indexes")) {
1194             opt = OPT_INDEXES;
1195         }
1196         else if (!strcasecmp(w, "Includes")) {
1197             opt = OPT_INCLUDES;
1198         }
1199         else if (!strcasecmp(w, "IncludesNOEXEC")) {
1200             opt = (OPT_INCLUDES | OPT_INCNOEXEC);
1201         }
1202         else if (!strcasecmp(w, "FollowSymLinks")) {
1203             opt = OPT_SYM_LINKS;
1204         }
1205         else if (!strcasecmp(w, "SymLinksIfOwnerMatch")) {
1206             opt = OPT_SYM_OWNER;
1207         }
1208         else if (!strcasecmp(w, "execCGI")) {
1209             opt = OPT_EXECCGI;
1210         }
1211         else if (!strcasecmp(w, "MultiViews")) {
1212             opt = OPT_MULTI;
1213         }
1214         else if (!strcasecmp(w, "RunScripts")) { /* AI backcompat. Yuck */
1215             opt = OPT_MULTI|OPT_EXECCGI;
1216         }
1217         else if (!strcasecmp(w, "None")) {
1218             opt = OPT_NONE;
1219         }
1220         else if (!strcasecmp(w, "All")) {
1221             opt = OPT_ALL;
1222         }
1223         else {
1224             return apr_pstrcat(cmd->pool, "Illegal option ", w, NULL);
1225         }
1226
1227         /* we ensure the invariant (d->opts_add & d->opts_remove) == 0 */
1228         if (action == '-') {
1229             d->opts_remove |= opt;
1230             d->opts_add &= ~opt;
1231             d->opts &= ~opt;
1232         }
1233         else if (action == '+') {
1234             d->opts_add |= opt;
1235             d->opts_remove &= ~opt;
1236             d->opts |= opt;
1237         }
1238         else {
1239             d->opts |= opt;
1240         }
1241     }
1242
1243     return NULL;
1244 }
1245
1246 /*
1247  * Note what data should be used when forming file ETag values.
1248  * It would be nicer to do this as an ITERATE, but then we couldn't
1249  * remember the +/- state properly.
1250  */
1251 static const char *set_etag_bits(cmd_parms *cmd, void *mconfig,
1252                                  const char *args_p)
1253 {
1254     core_dir_config *cfg;
1255     etag_components_t bit;
1256     char action;
1257     char *token;
1258     const char *args;
1259     int valid;
1260     int first;
1261     int explicit;
1262
1263     cfg = (core_dir_config *) mconfig;
1264
1265     args = args_p;
1266     first = 1;
1267     explicit = 0;
1268     while (args[0] != '\0') {
1269         action = '*';
1270         bit = ETAG_UNSET;
1271         valid = 1;
1272         token = ap_getword_conf(cmd->pool, &args);
1273         if ((*token == '+') || (*token == '-')) {
1274             action = *token;
1275             token++;
1276         }
1277         else {
1278             /*
1279              * The occurrence of an absolute setting wipes
1280              * out any previous relative ones.  The first such
1281              * occurrence forgets any inherited ones, too.
1282              */
1283             if (first) {
1284                 cfg->etag_bits = ETAG_UNSET;
1285                 cfg->etag_add = ETAG_UNSET;
1286                 cfg->etag_remove = ETAG_UNSET;
1287                 first = 0;
1288             }
1289         }
1290
1291         if (strcasecmp(token, "None") == 0) {
1292             if (action != '*') {
1293                 valid = 0;
1294             }
1295             else {
1296                 cfg->etag_bits = bit = ETAG_NONE;
1297                 explicit = 1;
1298             }
1299         }
1300         else if (strcasecmp(token, "All") == 0) {
1301             if (action != '*') {
1302                 valid = 0;
1303             }
1304             else {
1305                 explicit = 1;
1306                 cfg->etag_bits = bit = ETAG_ALL;
1307             }
1308         }
1309         else if (strcasecmp(token, "Size") == 0) {
1310             bit = ETAG_SIZE;
1311         }
1312         else if ((strcasecmp(token, "LMTime") == 0)
1313                  || (strcasecmp(token, "MTime") == 0)
1314                  || (strcasecmp(token, "LastModified") == 0)) {
1315             bit = ETAG_MTIME;
1316         }
1317         else if (strcasecmp(token, "INode") == 0) {
1318             bit = ETAG_INODE;
1319         }
1320         else {
1321             return ap_pstrcat(cmd->pool, "Unknown keyword '",
1322                               token, "' for ", cmd->cmd->name,
1323                               " directive", NULL);
1324         }
1325
1326         if (! valid) {
1327             return ap_pstrcat(cmd->pool, cmd->cmd->name, " keyword '",
1328                               token, "' cannot be used with '+' or '-'",
1329                               NULL);
1330         }
1331
1332         if (action == '+') {
1333             /*
1334              * Make sure it's in the 'add' list and absent from the
1335              * 'subtract' list.
1336              */
1337             cfg->etag_add |= bit;
1338             cfg->etag_remove &= (~ bit);
1339         }
1340         else if (action == '-') {
1341             cfg->etag_remove |= bit;
1342             cfg->etag_add &= (~ bit);
1343         }
1344         else {
1345             /*
1346              * Non-relative values wipe out any + or - values
1347              * accumulated so far.
1348              */
1349             cfg->etag_bits |= bit;
1350             cfg->etag_add = ETAG_UNSET;
1351             cfg->etag_remove = ETAG_UNSET;
1352             explicit = 1;
1353         }
1354     }
1355
1356     /*
1357      * Any setting at all will clear the 'None' and 'Unset' bits.
1358      */
1359
1360     if (cfg->etag_add != ETAG_UNSET) {
1361         cfg->etag_add &= (~ ETAG_UNSET);
1362     }
1363     if (cfg->etag_remove != ETAG_UNSET) {
1364         cfg->etag_remove &= (~ ETAG_UNSET);
1365     }
1366     if (explicit) {
1367         cfg->etag_bits &= (~ ETAG_UNSET);
1368         if ((cfg->etag_bits & ETAG_NONE) != ETAG_NONE) {
1369             cfg->etag_bits &= (~ ETAG_NONE);
1370         }
1371     }
1372     return NULL;
1373 }
1374
1375 static const char *satisfy(cmd_parms *cmd, void *c_, const char *arg)
1376 {
1377     core_dir_config *c=c_;
1378
1379     if (!strcasecmp(arg, "all")) {
1380         c->satisfy = SATISFY_ALL;
1381     }
1382     else if (!strcasecmp(arg, "any")) {
1383         c->satisfy = SATISFY_ANY;
1384     }
1385     else {
1386         return "Satisfy either 'any' or 'all'.";
1387     }
1388     return NULL;
1389 }
1390
1391 static const char *require(cmd_parms *cmd, void *c_, const char *arg)
1392 {
1393     require_line *r;
1394     core_dir_config *c=c_;
1395
1396     if (!c->ap_requires) {
1397         c->ap_requires = apr_array_make(cmd->pool, 2, sizeof(require_line));
1398     }
1399     r = (require_line *)apr_array_push(c->ap_requires);
1400     r->requirement = apr_pstrdup(cmd->pool, arg);
1401     r->method_mask = cmd->limited;
1402     return NULL;
1403 }
1404
1405 AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd, void *dummy,
1406                                                   const char *arg) {
1407     const char *limited_methods = ap_getword(cmd->pool, &arg, '>');
1408     void *tog = cmd->cmd->cmd_data;
1409     apr_int64_t limited = 0;
1410     const char *errmsg;
1411   
1412     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1413     if (err != NULL) {
1414         return err;
1415     }
1416
1417     while (limited_methods[0]) {
1418         char *method = ap_getword_conf(cmd->pool, &limited_methods);
1419         int methnum;
1420
1421         /* check for builtin or module registered method number */
1422         methnum = ap_method_number_of(method);
1423
1424         if (methnum == M_TRACE && !tog) {
1425             return "TRACE cannot be controlled by <Limit>";
1426         }
1427         else if (methnum == M_INVALID) {
1428             /* method has not been registered yet, but resorce restriction
1429              * is always checked before method handling, so register it.
1430              */
1431             methnum = ap_method_register(cmd->pool, method);
1432         }
1433         limited |= (AP_METHOD_BIT << methnum);
1434     }
1435
1436     /* Killing two features with one function,
1437      * if (tog == NULL) <Limit>, else <LimitExcept>
1438      */
1439     cmd->limited = tog ? ~limited : limited;
1440
1441     errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context);
1442
1443     cmd->limited = -1;
1444
1445     return errmsg;
1446 }
1447
1448 /* XXX: Bogus - need to do this differently (at least OS2/Netware suffer
1449  * the same problem!!!
1450  * We use this in <DirectoryMatch> and <FilesMatch>, to ensure that 
1451  * people don't get bitten by wrong-cased regex matches
1452  */
1453
1454 #ifdef WIN32
1455 #define USE_ICASE REG_ICASE
1456 #else
1457 #define USE_ICASE 0
1458 #endif
1459
1460 /*
1461  * Report a missing-'>' syntax error.
1462  */
1463 static char *unclosed_directive(cmd_parms *cmd)
1464 {
1465     return apr_pstrcat(cmd->pool, cmd->cmd->name,
1466                       "> directive missing closing '>'", NULL);
1467 }
1468
1469 static const char *dirsection(cmd_parms *cmd, void *mconfig, const char *arg)
1470 {
1471     const char *errmsg;
1472     const char *endp = ap_strrchr_c(arg, '>');
1473     int old_overrides = cmd->override;
1474     char *old_path = cmd->path;
1475     core_dir_config *conf;
1476     ap_conf_vector_t *new_dir_conf = ap_create_per_dir_config(cmd->pool);
1477     regex_t *r = NULL;
1478     const command_rec *thiscmd = cmd->cmd;
1479
1480     const char *err = ap_check_cmd_context(cmd,
1481                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1482     if (err != NULL) {
1483         return err;
1484     }
1485
1486     if (endp == NULL) {
1487         return unclosed_directive(cmd);
1488     }
1489
1490     arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1491
1492     if (!arg) {
1493         if (thiscmd->cmd_data)
1494             return "<DirectoryMatch > block must specify a path";
1495         else
1496             return "<Directory > block must specify a path";
1497     }
1498
1499     cmd->path = ap_getword_conf(cmd->pool, &arg);
1500     cmd->override = OR_ALL|ACCESS_CONF;
1501
1502     if (!strcmp(cmd->path, "~")) {
1503         cmd->path = ap_getword_conf(cmd->pool, &arg);
1504         if (!cmd->path)
1505             return "<Directory ~ > block must specify a path";
1506     }
1507     else if (thiscmd->cmd_data) { /* <DirectoryMatch> */
1508         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1509     }
1510     else if (!strcmp(cmd->path, "/") == 0) 
1511     {
1512         char *newpath;
1513         /*
1514          * Ensure that the pathname is canonical, and append the trailing /
1515          */
1516         if (apr_filepath_merge(&newpath, NULL, cmd->path, 
1517                                APR_FILEPATH_TRUENAME, cmd->pool) != APR_SUCCESS) {
1518             return apr_pstrcat(cmd->pool, "<Directory \"", cmd->path,
1519                                "\"> path is invalid.", NULL);
1520         }
1521         cmd->path = newpath;
1522         if (cmd->path[strlen(cmd->path) - 1] != '/')
1523             cmd->path = apr_pstrcat(cmd->pool, cmd->path, "/", NULL);
1524     }
1525
1526     /* initialize our config and fetch it */
1527     conf = ap_set_config_vectors(cmd->server, new_dir_conf, cmd->path,
1528                                  &core_module, cmd->pool);
1529
1530     errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_dir_conf);
1531     if (errmsg != NULL)
1532         return errmsg;
1533
1534     conf->r = r;
1535     conf->d = cmd->path;
1536     conf->d_is_fnmatch = (apr_is_fnmatch(conf->d) != 0);
1537
1538     /* Make this explicit - the "/" root has 0 elements, that is, we
1539      * will always merge it, and it will always sort and merge first.
1540      * All others are sorted and tested by the number of slashes.
1541      */
1542     if (strcmp(conf->d, "/") == 0)
1543         conf->d_components = 0;
1544     else
1545         conf->d_components = ap_count_dirs(conf->d);
1546
1547     ap_add_per_dir_conf(cmd->server, new_dir_conf);
1548
1549     if (*arg != '\0') {
1550         return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1551                           "> arguments not (yet) supported.", NULL);
1552     }
1553
1554     cmd->path = old_path;
1555     cmd->override = old_overrides;
1556
1557     return NULL;
1558 }
1559
1560 static const char *urlsection(cmd_parms *cmd, void *mconfig, const char *arg)
1561 {
1562     const char *errmsg;
1563     const char *endp = ap_strrchr_c(arg, '>');
1564     int old_overrides = cmd->override;
1565     char *old_path = cmd->path;
1566     core_dir_config *conf;
1567     regex_t *r = NULL;
1568     const command_rec *thiscmd = cmd->cmd;
1569     ap_conf_vector_t *new_url_conf = ap_create_per_dir_config(cmd->pool);
1570     const char *err = ap_check_cmd_context(cmd,
1571                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1572     if (err != NULL) {
1573         return err;
1574     }
1575
1576     if (endp == NULL) {
1577         return unclosed_directive(cmd);
1578     }
1579
1580     arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1581
1582     cmd->path = ap_getword_conf(cmd->pool, &arg);
1583     cmd->override = OR_ALL|ACCESS_CONF;
1584
1585     if (thiscmd->cmd_data) { /* <LocationMatch> */
1586         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1587     }
1588     else if (!strcmp(cmd->path, "~")) {
1589         cmd->path = ap_getword_conf(cmd->pool, &arg);
1590         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1591     }
1592
1593     /* initialize our config and fetch it */
1594     conf = ap_set_config_vectors(cmd->server, new_url_conf, cmd->path,
1595                                  &core_module, cmd->pool);
1596
1597     errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_url_conf);
1598     if (errmsg != NULL)
1599         return errmsg;
1600
1601     conf->d = apr_pstrdup(cmd->pool, cmd->path);     /* No mangling, please */
1602     conf->d_is_fnmatch = apr_is_fnmatch(conf->d) != 0;
1603     conf->r = r;
1604
1605     ap_add_per_url_conf(cmd->server, new_url_conf);
1606     
1607     if (*arg != '\0') {
1608         return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1609                           "> arguments not (yet) supported.", NULL);
1610     }
1611
1612     cmd->path = old_path;
1613     cmd->override = old_overrides;
1614
1615     return NULL;
1616 }
1617
1618 static const char *filesection(cmd_parms *cmd, void *mconfig, const char *arg)
1619 {
1620     const char *errmsg;
1621     const char *endp = ap_strrchr_c(arg, '>');
1622     int old_overrides = cmd->override;
1623     char *old_path = cmd->path;
1624     core_dir_config *conf;
1625     regex_t *r = NULL;
1626     const command_rec *thiscmd = cmd->cmd;
1627     core_dir_config *c=mconfig;
1628     ap_conf_vector_t *new_file_conf = ap_create_per_dir_config(cmd->pool);
1629     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT|NOT_IN_LOCATION);
1630
1631     if (err != NULL) {
1632         return err;
1633     }
1634
1635     if (endp == NULL) {
1636         return unclosed_directive(cmd);
1637     }
1638
1639     arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1640
1641     cmd->path = ap_getword_conf(cmd->pool, &arg);
1642     /* Only if not an .htaccess file */
1643     if (!old_path) {
1644         cmd->override = OR_ALL|ACCESS_CONF;
1645     }
1646
1647     if (thiscmd->cmd_data) { /* <FilesMatch> */
1648         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1649     }
1650     else if (!strcmp(cmd->path, "~")) {
1651         cmd->path = ap_getword_conf(cmd->pool, &arg);
1652         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1653     }
1654     else {
1655         char *newpath;
1656         /* Ensure that the pathname is canonical, but we
1657          * can't test the case/aliases without a fixed path */
1658         if (apr_filepath_merge(&newpath, "", cmd->path, 
1659                                0, cmd->pool) != APR_SUCCESS)
1660             return apr_pstrcat(cmd->pool, "<Files \"", cmd->path,
1661                                "\"> is invalid.", NULL);
1662         cmd->path = newpath;
1663     }
1664
1665     /* initialize our config and fetch it */
1666     conf = ap_set_config_vectors(cmd->server, new_file_conf, cmd->path,
1667                                  &core_module, cmd->pool);
1668
1669     errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_file_conf);
1670     if (errmsg != NULL)
1671         return errmsg;
1672
1673     conf->d = cmd->path;
1674     conf->d_is_fnmatch = apr_is_fnmatch(conf->d) != 0;
1675     conf->r = r;
1676
1677     ap_add_file_conf(c, new_file_conf);
1678
1679     if (*arg != '\0') {
1680         return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1681                           "> arguments not (yet) supported.", NULL);
1682     }
1683
1684     cmd->path = old_path;
1685     cmd->override = old_overrides;
1686
1687     return NULL;
1688 }
1689
1690 static const char *start_ifmod(cmd_parms *cmd, void *mconfig, const char *arg)
1691 {
1692     const char *endp = ap_strrchr_c(arg, '>');
1693     int not = (arg[0] == '!');
1694     module *found;
1695
1696     if (endp == NULL) {
1697         return unclosed_directive(cmd);
1698     }
1699
1700     arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1701
1702     if (not) {
1703         arg++;
1704     }
1705
1706     found = ap_find_linked_module(arg);
1707
1708     if ((!not && found) || (not && !found)) {
1709         ap_directive_t *parent = NULL;
1710         ap_directive_t *current = NULL;
1711         const char *retval;
1712
1713         retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd, 
1714                                       &current, &parent, "<IfModule");
1715         *(ap_directive_t **)mconfig = current;
1716         return retval;
1717     }
1718     else { 
1719         *(ap_directive_t **)mconfig = NULL;
1720         return ap_soak_end_container(cmd, "<IfModule");
1721     }
1722 }
1723
1724 AP_DECLARE(int) ap_exists_config_define(const char *name)
1725 {
1726     char **defines;
1727     int i;
1728
1729     defines = (char **)ap_server_config_defines->elts;
1730     for (i = 0; i < ap_server_config_defines->nelts; i++) {
1731         if (strcmp(defines[i], name) == 0) {
1732             return 1;
1733         }
1734     }
1735     return 0;
1736 }
1737
1738 static const char *start_ifdefine(cmd_parms *cmd, void *dummy, const char *arg)
1739 {
1740     const char *endp;
1741     int defined;
1742     int not = 0;
1743
1744     endp = ap_strrchr_c(arg, '>');
1745     if (endp == NULL) {
1746         return unclosed_directive(cmd);
1747     }
1748
1749     arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1750
1751     if (arg[0] == '!') {
1752         not = 1;
1753         arg++;
1754     }
1755
1756     defined = ap_exists_config_define(arg);
1757     if ((!not && defined) || (not && !defined)) {
1758         ap_directive_t *parent = NULL;
1759         ap_directive_t *current = NULL;
1760         const char *retval;
1761
1762         retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd, 
1763                                       &current, &parent, "<IfDefine");
1764         *(ap_directive_t **)dummy = current;
1765         return retval;
1766     }
1767     else { 
1768         *(ap_directive_t **)dummy = NULL;
1769         return ap_soak_end_container(cmd, "<IfDefine");
1770     }
1771 }
1772
1773 /* httpd.conf commands... beginning with the <VirtualHost> business */
1774
1775 static const char *virtualhost_section(cmd_parms *cmd, void *dummy,
1776                                        const char *arg)
1777 {
1778     server_rec *main_server = cmd->server, *s;
1779     const char *errmsg;
1780     const char *endp = ap_strrchr_c(arg, '>');
1781     apr_pool_t *p = cmd->pool;
1782
1783     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1784     if (err != NULL) {
1785         return err;
1786     }
1787
1788     if (endp == NULL) {
1789         return unclosed_directive(cmd);
1790     }
1791
1792     arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1793     
1794     /* FIXME: There's another feature waiting to happen here -- since you
1795         can now put multiple addresses/names on a single <VirtualHost>
1796         you might want to use it to group common definitions and then
1797         define other "subhosts" with their individual differences.  But
1798         personally I'd rather just do it with a macro preprocessor. -djg */
1799     if (main_server->is_virtual) {
1800         return "<VirtualHost> doesn't nest!";
1801     }
1802     
1803     errmsg = ap_init_virtual_host(p, arg, main_server, &s);
1804     if (errmsg) {
1805         return errmsg;
1806     }
1807
1808     s->next = main_server->next;
1809     main_server->next = s;
1810
1811     s->defn_name = cmd->directive->filename;
1812     s->defn_line_number = cmd->directive->line_num;
1813
1814     cmd->server = s;
1815
1816     errmsg = ap_walk_config(cmd->directive->first_child, cmd,
1817                             s->lookup_defaults);
1818
1819     cmd->server = main_server;
1820
1821     return errmsg;
1822 }
1823
1824 static const char *set_server_alias(cmd_parms *cmd, void *dummy,
1825                                     const char *arg)
1826 {
1827     if (!cmd->server->names) {
1828         return "ServerAlias only used in <VirtualHost>";
1829     }
1830     while (*arg) {
1831         char **item, *name = ap_getword_conf(cmd->pool, &arg);
1832         if (ap_is_matchexp(name)) {
1833             item = (char **)apr_array_push(cmd->server->wild_names);
1834         }
1835         else {
1836             item = (char **)apr_array_push(cmd->server->names);
1837         }
1838         *item = name;
1839     }
1840     return NULL;
1841 }
1842
1843 static const char *set_server_string_slot(cmd_parms *cmd, void *dummy,
1844                                           const char *arg)
1845 {
1846     /* This one's pretty generic... */
1847   
1848     int offset = (int)(long)cmd->info;
1849     char *struct_ptr = (char *)cmd->server;
1850     
1851     const char *err = ap_check_cmd_context(cmd, 
1852                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1853     if (err != NULL) {
1854         return err;
1855     }
1856
1857     *(const char **)(struct_ptr + offset) = arg;
1858     return NULL;
1859 }
1860
1861 static const char *server_hostname_port(cmd_parms *cmd, void *dummy, const char *arg)
1862 {
1863     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1864     const char *portstr;
1865     int port;
1866
1867     if (err != NULL) {
1868         return err;
1869     }
1870     portstr = ap_strchr_c(arg, ':');
1871     if (portstr) {
1872         cmd->server->server_hostname = apr_pstrndup(cmd->pool, arg, 
1873                                                     portstr - arg);
1874         portstr++;
1875         port = atoi(portstr);
1876         if (port <= 0 || port >= 65536) { /* 65536 == 1<<16 */
1877             return apr_pstrcat(cmd->temp_pool, "The port number \"", arg, 
1878                           "\" is outside the appropriate range "
1879                           "(i.e., 1..65535).", NULL);
1880         }
1881     }
1882     else {
1883         cmd->server->server_hostname = apr_pstrdup(cmd->pool, arg);
1884         port = 0;
1885     }
1886     cmd->server->port = port;
1887     return NULL;
1888 }
1889
1890 static const char *set_signature_flag(cmd_parms *cmd, void *d_,
1891                                       const char *arg)
1892 {
1893     core_dir_config *d=d_;
1894
1895     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1896     if (err != NULL) {
1897         return err;
1898     }
1899
1900     if (strcasecmp(arg, "On") == 0) {
1901         d->server_signature = srv_sig_on;
1902     }
1903     else if (strcasecmp(arg, "Off") == 0) {
1904         d->server_signature = srv_sig_off;
1905     }
1906     else if (strcasecmp(arg, "EMail") == 0) {
1907         d->server_signature = srv_sig_withmail;
1908     }
1909     else {
1910         return "ServerSignature: use one of: off | on | email";
1911     }
1912     return NULL;
1913 }
1914
1915 static const char *set_server_root(cmd_parms *cmd, void *dummy,
1916                                    const char *arg) 
1917 {
1918     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1919
1920     if (err != NULL) {
1921         return err;
1922     }
1923
1924     if ((apr_filepath_merge((char**)&ap_server_root, NULL, arg, 
1925                             APR_FILEPATH_TRUENAME, cmd->pool) != APR_SUCCESS)
1926         || !ap_is_directory(cmd->pool, ap_server_root)) {
1927         return "ServerRoot must be a valid directory";
1928     }
1929     return NULL;
1930 }
1931
1932 static const char *set_timeout(cmd_parms *cmd, void *dummy, const char *arg)
1933 {
1934     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1935     if (err != NULL) {
1936         return err;
1937     }
1938
1939     cmd->server->timeout = atoi(arg);
1940     return NULL;
1941 }
1942
1943 static const char *set_idcheck(cmd_parms *cmd, void *d_, int arg) 
1944 {
1945     core_dir_config *d=d_;
1946     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1947     if (err != NULL) {
1948         return err;
1949     }
1950
1951     d->do_rfc1413 = arg != 0;
1952     return NULL;
1953 }
1954
1955 static const char *set_hostname_lookups(cmd_parms *cmd, void *d_,
1956                                         const char *arg)
1957 {
1958     core_dir_config *d=d_;
1959
1960     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1961     if (err != NULL) {
1962         return err;
1963     }
1964
1965     if (!strcasecmp(arg, "on")) {
1966         d->hostname_lookups = HOSTNAME_LOOKUP_ON;
1967     }
1968     else if (!strcasecmp(arg, "off")) {
1969         d->hostname_lookups = HOSTNAME_LOOKUP_OFF;
1970     }
1971     else if (!strcasecmp(arg, "double")) {
1972         d->hostname_lookups = HOSTNAME_LOOKUP_DOUBLE;
1973     }
1974     else {
1975         return "parameter must be 'on', 'off', or 'double'";
1976     }
1977     return NULL;
1978 }
1979
1980 static const char *set_serverpath(cmd_parms *cmd, void *dummy,
1981                                   const char *arg) 
1982 {
1983     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1984     if (err != NULL) {
1985         return err;
1986     }
1987
1988     cmd->server->path = arg;
1989     cmd->server->pathlen = strlen(arg);
1990     return NULL;
1991 }
1992
1993 static const char *set_content_md5(cmd_parms *cmd, void *d_, int arg)
1994 {
1995     core_dir_config *d=d_;
1996     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1997     if (err != NULL) {
1998         return err;
1999     }
2000
2001     d->content_md5 = arg != 0;
2002     return NULL;
2003 }
2004
2005 static const char *set_accept_path_info(cmd_parms *cmd, void *d_, const char *arg)
2006 {
2007     core_dir_config *d=d_;
2008
2009     if (strcasecmp(arg, "on") == 0) {
2010         d->accept_path_info = AP_REQ_ACCEPT_PATH_INFO;
2011     }
2012     else if (strcasecmp(arg, "off") == 0) {
2013         d->accept_path_info = AP_REQ_REJECT_PATH_INFO;
2014     }
2015     else if (strcasecmp(arg, "default") == 0) {
2016         d->accept_path_info = AP_REQ_DEFAULT_PATH_INFO;
2017     }
2018     else {
2019         return "AcceptPathInfo must be set to on, off or default";
2020     }
2021
2022     return NULL;
2023 }
2024
2025 static const char *set_use_canonical_name(cmd_parms *cmd, void *d_,
2026                                           const char *arg)
2027 {
2028     core_dir_config *d=d_;
2029     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2030     if (err != NULL) {
2031         return err;
2032     }
2033
2034     if (strcasecmp(arg, "on") == 0) {
2035         d->use_canonical_name = USE_CANONICAL_NAME_ON;
2036     }
2037     else if (strcasecmp(arg, "off") == 0) {
2038         d->use_canonical_name = USE_CANONICAL_NAME_OFF;
2039     }
2040     else if (strcasecmp(arg, "dns") == 0) {
2041         d->use_canonical_name = USE_CANONICAL_NAME_DNS;
2042     }
2043     else {
2044         return "parameter must be 'on', 'off', or 'dns'";
2045     }
2046     return NULL;
2047 }
2048
2049
2050 static const char *include_config (cmd_parms *cmd, void *dummy,
2051                                    const char *name)
2052 {
2053     ap_directive_t *conftree = NULL;
2054
2055     ap_process_resource_config(cmd->server,
2056                                ap_server_root_relative(cmd->pool, name),
2057                                &conftree, cmd->pool, cmd->temp_pool);
2058     *(ap_directive_t **)dummy = conftree;
2059     return NULL;
2060 }
2061
2062 static const char *set_loglevel(cmd_parms *cmd, void *dummy, const char *arg) 
2063 {
2064     char *str;
2065     
2066     const char *err = ap_check_cmd_context(cmd,
2067                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2068     if (err != NULL) {
2069         return err;
2070     }
2071
2072     if ((str = ap_getword_conf(cmd->pool, &arg))) {
2073         if (!strcasecmp(str, "emerg")) {
2074             cmd->server->loglevel = APLOG_EMERG;
2075         }
2076         else if (!strcasecmp(str, "alert")) {
2077             cmd->server->loglevel = APLOG_ALERT;
2078         }
2079         else if (!strcasecmp(str, "crit")) {
2080             cmd->server->loglevel = APLOG_CRIT;
2081         }
2082         else if (!strcasecmp(str, "error")) {
2083             cmd->server->loglevel = APLOG_ERR;
2084         }
2085         else if (!strcasecmp(str, "warn")) {
2086             cmd->server->loglevel = APLOG_WARNING;
2087         }
2088         else if (!strcasecmp(str, "notice")) {
2089             cmd->server->loglevel = APLOG_NOTICE;
2090         }
2091         else if (!strcasecmp(str, "info")) {
2092             cmd->server->loglevel = APLOG_INFO;
2093         }
2094         else if (!strcasecmp(str, "debug")) {
2095             cmd->server->loglevel = APLOG_DEBUG;
2096         }
2097         else {
2098             return "LogLevel requires level keyword: one of "
2099                    "emerg/alert/crit/error/warn/notice/info/debug";
2100         }
2101     }
2102     else {
2103         return "LogLevel requires level keyword";
2104     }
2105
2106     return NULL;
2107 }
2108
2109 AP_DECLARE(const char *) ap_psignature(const char *prefix, request_rec *r)
2110 {
2111     char sport[20];
2112     core_dir_config *conf;
2113
2114     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
2115                                                    &core_module);
2116     if ((conf->server_signature == srv_sig_off)
2117             || (conf->server_signature == srv_sig_unset)) {
2118         return "";
2119     }
2120
2121     apr_snprintf(sport, sizeof sport, "%u", (unsigned) ap_get_server_port(r));
2122
2123     if (conf->server_signature == srv_sig_withmail) {
2124         return apr_pstrcat(r->pool, prefix, "<address>" AP_SERVER_BASEVERSION
2125                           " Server at <a href=\"mailto:",
2126                           r->server->server_admin, "\">",
2127                           ap_get_server_name(r), "</a> Port ", sport,
2128                           "</address>\n", NULL);
2129     }
2130     return apr_pstrcat(r->pool, prefix, "<address>" AP_SERVER_BASEVERSION
2131                       " Server at ", ap_get_server_name(r), " Port ", sport,
2132                       "</address>\n", NULL);
2133 }
2134
2135 /*
2136  * Load an authorisation realm into our location configuration, applying the
2137  * usual rules that apply to realms.
2138  */
2139 static const char *set_authname(cmd_parms *cmd, void *mconfig,
2140                                 const char *word1)
2141 {
2142     core_dir_config *aconfig = (core_dir_config *)mconfig;
2143
2144     aconfig->ap_auth_name = ap_escape_quotes(cmd->pool, word1);
2145     return NULL;
2146 }
2147
2148 #ifdef _OSD_POSIX /* BS2000 Logon Passwd file */
2149 static const char *set_bs2000_account(cmd_parms *cmd, void *dummy, char *name)
2150 {
2151     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2152     if (err != NULL) {
2153         return err;
2154     }
2155
2156     return os_set_account(cmd->pool, name);
2157 }
2158 #endif /*_OSD_POSIX*/
2159
2160 /*
2161  * Handle a request to include the server's OS platform in the Server
2162  * response header field (the ServerTokens directive).  Unfortunately
2163  * this requires a new global in order to communicate the setting back to
2164  * http_main so it can insert the information in the right place in the
2165  * string.
2166  */
2167
2168 static char *server_version = NULL;
2169 static int version_locked = 0; 
2170
2171 enum server_token_type {
2172     SrvTk_MIN,          /* eg: Apache/1.3.0 */
2173     SrvTk_OS,           /* eg: Apache/1.3.0 (UNIX) */
2174     SrvTk_FULL,         /* eg: Apache/1.3.0 (UNIX) PHP/3.0 FooBar/1.2b */
2175     SrvTk_PRODUCT_ONLY  /* eg: Apache */
2176 };
2177 static enum server_token_type ap_server_tokens = SrvTk_FULL;
2178
2179 static apr_status_t reset_version(void *dummy)
2180 {
2181     version_locked = 0;
2182     ap_server_tokens = SrvTk_FULL;
2183     server_version = NULL;
2184     return APR_SUCCESS;
2185 }
2186
2187 AP_DECLARE(const char *) ap_get_server_version(void)
2188 {
2189     return (server_version ? server_version : AP_SERVER_BASEVERSION);
2190 }
2191
2192 AP_DECLARE(void) ap_add_version_component(apr_pool_t *pconf, const char *component)
2193 {
2194     if (! version_locked) {
2195         /*
2196          * If the version string is null, register our cleanup to reset the
2197          * pointer on pool destruction. We also know that, if NULL,
2198          * we are adding the original SERVER_BASEVERSION string.
2199          */
2200         if (server_version == NULL) {
2201             apr_pool_cleanup_register(pconf, NULL, reset_version,
2202                                 apr_pool_cleanup_null);
2203             server_version = apr_pstrdup(pconf, component);
2204         }
2205         else {
2206             /*
2207              * Tack the given component identifier to the end of
2208              * the existing string.
2209              */
2210             server_version = apr_pstrcat(pconf, server_version, " ",
2211                                         component, NULL);
2212         }
2213     }
2214 }
2215
2216 /*
2217  * This routine adds the real server base identity to the version string,
2218  * and then locks out changes until the next reconfig.
2219  */
2220 static void ap_set_version(apr_pool_t *pconf)
2221 {
2222     if (ap_server_tokens == SrvTk_PRODUCT_ONLY) {
2223         ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT);
2224     }
2225     else if (ap_server_tokens == SrvTk_MIN) {
2226         ap_add_version_component(pconf, AP_SERVER_BASEVERSION);
2227     }
2228     else {
2229         ap_add_version_component(pconf, AP_SERVER_BASEVERSION " (" PLATFORM ")");
2230     }
2231     /*
2232      * Lock the server_version string if we're not displaying
2233      * the full set of tokens
2234      */
2235     if (ap_server_tokens != SrvTk_FULL) {
2236         version_locked++;
2237     }
2238 }
2239
2240 static const char *set_serv_tokens(cmd_parms *cmd, void *dummy,
2241                                    const char *arg)
2242 {
2243     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2244     if (err != NULL) {
2245         return err;
2246     }
2247
2248     if (!strcasecmp(arg, "OS")) {
2249         ap_server_tokens = SrvTk_OS;
2250     }
2251     else if (!strcasecmp(arg, "Min") || !strcasecmp(arg, "Minimal")) {
2252         ap_server_tokens = SrvTk_MIN;
2253     }
2254     else if (!strcasecmp(arg, "Prod") || !strcasecmp(arg, "ProductOnly")) {
2255         ap_server_tokens = SrvTk_PRODUCT_ONLY;
2256     }
2257     else {
2258         ap_server_tokens = SrvTk_FULL;
2259     }
2260     return NULL;
2261 }
2262
2263 static const char *set_limit_req_line(cmd_parms *cmd, void *dummy,
2264                                       const char *arg)
2265 {
2266     const char *err = ap_check_cmd_context(cmd,
2267                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2268     int lim;
2269
2270     if (err != NULL) {
2271         return err;
2272     }
2273     lim = atoi(arg);
2274     if (lim < 0) {
2275         return apr_pstrcat(cmd->temp_pool, "LimitRequestLine \"", arg, 
2276                           "\" must be a non-negative integer", NULL);
2277     }
2278     if (lim > DEFAULT_LIMIT_REQUEST_LINE) {
2279         return apr_psprintf(cmd->temp_pool, "LimitRequestLine \"%s\" "
2280                            "must not exceed the precompiled maximum of %d",
2281                            arg, DEFAULT_LIMIT_REQUEST_LINE);
2282     }
2283     cmd->server->limit_req_line = lim;
2284     return NULL;
2285 }
2286
2287 static const char *set_limit_req_fieldsize(cmd_parms *cmd, void *dummy,
2288                                            const char *arg)
2289 {
2290     const char *err = ap_check_cmd_context(cmd,
2291                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2292     int lim;
2293
2294     if (err != NULL) {
2295         return err;
2296     }
2297     lim = atoi(arg);
2298     if (lim < 0) {
2299         return apr_pstrcat(cmd->temp_pool, "LimitRequestFieldsize \"", arg, 
2300                           "\" must be a non-negative integer (0 = no limit)",
2301                           NULL);
2302     }
2303     if (lim > DEFAULT_LIMIT_REQUEST_FIELDSIZE) {
2304         return apr_psprintf(cmd->temp_pool, "LimitRequestFieldsize \"%s\" "
2305                           "must not exceed the precompiled maximum of %d",
2306                            arg, DEFAULT_LIMIT_REQUEST_FIELDSIZE);
2307     }
2308     cmd->server->limit_req_fieldsize = lim;
2309     return NULL;
2310 }
2311
2312 static const char *set_limit_req_fields(cmd_parms *cmd, void *dummy,
2313                                         const char *arg)
2314 {
2315     const char *err = ap_check_cmd_context(cmd,
2316                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2317     int lim;
2318
2319     if (err != NULL) {
2320         return err;
2321     }
2322     lim = atoi(arg);
2323     if (lim < 0) {
2324         return apr_pstrcat(cmd->temp_pool, "LimitRequestFields \"", arg, 
2325                           "\" must be a non-negative integer (0 = no limit)",
2326                           NULL);
2327     }
2328     cmd->server->limit_req_fields = lim;
2329     return NULL;
2330 }
2331
2332 static const char *set_limit_req_body(cmd_parms *cmd, void *conf_,
2333                                       const char *arg) 
2334 {
2335     core_dir_config *conf=conf_;
2336     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2337     char *errp;
2338     if (err != NULL) {
2339         return err;
2340     }
2341
2342     /* WTF: If strtoul is not portable, then write a replacement.
2343      *      Instead we have an idiotic define in httpd.h that prevents
2344      *      it from being used even when it is available. Sheesh.
2345      */
2346     conf->limit_req_body = (apr_off_t)strtol(arg, &errp, 10);
2347     if (*errp != '\0') {
2348         return "LimitRequestBody requires a non-negative integer.";
2349     }
2350     return NULL;
2351 }
2352
2353 static const char *set_limit_xml_req_body(cmd_parms *cmd, void *conf_,
2354                                           const char *arg) 
2355 {
2356     core_dir_config *conf = conf_;
2357     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2358     if (err != NULL) {
2359         return err;
2360     }
2361
2362     conf->limit_xml_body = atol(arg);
2363     if (conf->limit_xml_body < 0)
2364         return "LimitXMLRequestBody requires a non-negative integer.";
2365
2366     return NULL;
2367 }
2368
2369 AP_DECLARE(size_t) ap_get_limit_xml_body(const request_rec *r)
2370 {
2371     core_dir_config *conf;
2372
2373     conf = ap_get_module_config(r->per_dir_config, &core_module);
2374     if (conf->limit_xml_body == AP_LIMIT_UNSET)
2375         return AP_DEFAULT_LIMIT_XML_BODY;
2376     return (size_t)conf->limit_xml_body;
2377 }
2378
2379 #if !defined (RLIMIT_CPU) || !(defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)) || !defined (RLIMIT_NPROC)
2380 static const char *no_set_limit(cmd_parms *cmd, void *conf_,
2381                                 const char *arg, const char *arg2)
2382 {
2383     ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, cmd->server,
2384                 "%s not supported on this platform", cmd->cmd->name);
2385     return NULL;
2386 }
2387 #endif
2388
2389 #ifdef RLIMIT_CPU
2390 static const char *set_limit_cpu(cmd_parms *cmd, void *conf_,
2391                                  const char *arg, const char *arg2)
2392 {
2393     core_dir_config *conf=conf_;
2394
2395     unixd_set_rlimit(cmd, &conf->limit_cpu, arg, arg2, RLIMIT_CPU);
2396     return NULL;
2397 }
2398 #endif
2399
2400 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)
2401 static const char *set_limit_mem(cmd_parms *cmd, void *conf_,
2402                                  const char *arg, const char * arg2)
2403 {
2404     core_dir_config *conf=conf_;
2405
2406 #if defined(RLIMIT_AS)
2407     unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2 ,RLIMIT_AS);
2408 #elif defined(RLIMIT_DATA)
2409     unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_DATA);
2410 #elif defined(RLIMIT_VMEM)
2411     unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_VMEM);
2412 #endif
2413     return NULL;
2414 }
2415 #endif
2416
2417 #ifdef RLIMIT_NPROC
2418 static const char *set_limit_nproc(cmd_parms *cmd, void *conf_,
2419                                    const char *arg, const char * arg2)
2420 {
2421     core_dir_config *conf=conf_;
2422
2423     unixd_set_rlimit(cmd, &conf->limit_nproc, arg, arg2, RLIMIT_NPROC);
2424     return NULL;
2425 }
2426 #endif
2427
2428 static const char *add_ct_output_filters(cmd_parms *cmd, void *conf_,
2429                                          const char *arg, const char *arg2)
2430 {
2431     core_dir_config *conf=conf_;
2432     ap_filter_rec_t *old, *new;
2433
2434     if (!conf->ct_output_filters) {
2435         conf->ct_output_filters = apr_hash_make(cmd->pool);
2436         old = NULL;
2437     }
2438     else {
2439         old = (ap_filter_rec_t*) apr_hash_get(conf->ct_output_filters, arg2,
2440                                               APR_HASH_KEY_STRING);
2441     }
2442
2443     new = apr_pcalloc(cmd->pool, sizeof(ap_filter_rec_t));
2444     new->name = apr_pstrdup(cmd->pool, arg);
2445
2446     /* We found something, so let's append it.  */ 
2447     if (old) {
2448         new->next = old;
2449     }
2450
2451     apr_hash_set(conf->ct_output_filters, arg2, APR_HASH_KEY_STRING, new);
2452     
2453     return NULL; 
2454 }
2455
2456 static apr_status_t writev_it_all(apr_socket_t *s,
2457                                   struct iovec *vec, int nvec,
2458                                   apr_size_t len, apr_size_t *nbytes)
2459 {
2460     apr_size_t bytes_written = 0;
2461     apr_status_t rv;
2462     apr_size_t n = len;
2463     int i = 0;
2464
2465     *nbytes = 0;
2466
2467     /* XXX handle checking for non-blocking socket */
2468     while (bytes_written != len) {
2469         rv = apr_sendv(s, vec + i, nvec - i, &n);
2470         bytes_written += n;
2471         if (rv != APR_SUCCESS)
2472             return rv;
2473         *nbytes += n;
2474
2475         /* If the write did not complete, adjust the iovecs and issue
2476          * apr_sendv again
2477          */
2478         if (bytes_written < len) {
2479             /* Skip over the vectors that have already been written */
2480             apr_size_t cnt = vec[i].iov_len;
2481             while (n >= cnt && i + 1 < nvec) {
2482                 i++;
2483                 cnt += vec[i].iov_len;
2484             }
2485             if (n < cnt) {
2486                 /* Handle partial write of vec i */
2487                 vec[i].iov_base = (char *) vec[i].iov_base + 
2488                     (vec[i].iov_len - (cnt - n));
2489                 vec[i].iov_len = cnt -n;
2490             }
2491         }
2492         n = len - bytes_written;
2493     }
2494
2495     return APR_SUCCESS;
2496 }
2497
2498 /* sendfile_it_all()
2499  *  send the entire file using sendfile()
2500  *  handle partial writes
2501  *  return only when all bytes have been sent or an error is encountered.
2502  */
2503
2504 #if APR_HAS_SENDFILE
2505 static apr_status_t sendfile_it_all(core_net_rec *c, 
2506                                     apr_file_t *fd,
2507                                     apr_hdtr_t *hdtr, 
2508                                     apr_off_t   file_offset,
2509                                     apr_size_t  file_bytes_left, 
2510                                     apr_size_t  total_bytes_left,
2511                                     apr_int32_t flags)
2512 {
2513     apr_status_t rv;
2514 #ifdef AP_DEBUG
2515     apr_int32_t timeout = 0;
2516 #endif
2517
2518     AP_DEBUG_ASSERT((apr_getsocketopt(c->client_socket, APR_SO_TIMEOUT, 
2519                        &timeout) == APR_SUCCESS) && 
2520                      timeout > 0);  /* socket must be in timeout mode */ 
2521     do {
2522         apr_size_t tmplen = file_bytes_left;
2523         
2524         rv = apr_sendfile(c->client_socket, fd, hdtr, &file_offset, &tmplen, 
2525                           flags);
2526         total_bytes_left -= tmplen;
2527         if (!total_bytes_left || rv != APR_SUCCESS) {
2528             return rv;        /* normal case & error exit */ 
2529         }
2530
2531         AP_DEBUG_ASSERT(total_bytes_left > 0 && tmplen > 0);
2532         
2533         /* partial write, oooh noooo... 
2534          * Skip over any header data which was written
2535          */
2536         while (tmplen && hdtr->numheaders) {
2537             if (tmplen >= hdtr->headers[0].iov_len) {
2538                 tmplen -= hdtr->headers[0].iov_len;
2539                 --hdtr->numheaders;
2540                 ++hdtr->headers;
2541             }
2542             else {
2543                 char *iov_base = (char *)hdtr->headers[0].iov_base;
2544
2545                 hdtr->headers[0].iov_len -= tmplen;
2546                 iov_base += tmplen;
2547                 hdtr->headers[0].iov_base = iov_base;
2548                 tmplen = 0;
2549             }
2550         }
2551
2552         /* Skip over any file data which was written */
2553
2554         if (tmplen <= file_bytes_left) {
2555             file_offset += tmplen;
2556             file_bytes_left -= tmplen;
2557             continue; 
2558         }
2559         tmplen -= file_bytes_left;
2560         file_bytes_left = 0;
2561         file_offset = 0;
2562         
2563         /* Skip over any trailer data which was written */
2564         
2565         while (tmplen && hdtr->numtrailers) {
2566             if (tmplen >= hdtr->trailers[0].iov_len) {
2567                 tmplen -= hdtr->trailers[0].iov_len;
2568                 --hdtr->numtrailers;
2569                 ++hdtr->trailers;
2570             }
2571             else {
2572                 char *iov_base = (char *)hdtr->trailers[0].iov_base;
2573
2574                 hdtr->trailers[0].iov_len -= tmplen;
2575                 iov_base += tmplen;
2576                 hdtr->trailers[0].iov_base = iov_base;
2577                 tmplen = 0;
2578             }
2579         }
2580     } while (1);
2581 }
2582 #endif
2583         
2584 /*
2585  * emulate_sendfile()
2586  * Sends the contents of file fd along with header/trailer bytes, if any,
2587  * to the network. emulate_sendfile will return only when all the bytes have been
2588  * sent (i.e., it handles partial writes) or on a network error condition.
2589  */
2590 static apr_status_t emulate_sendfile(core_net_rec *c, apr_file_t *fd, 
2591                                      apr_hdtr_t *hdtr, apr_off_t offset, 
2592                                      apr_size_t length, apr_size_t *nbytes) 
2593 {
2594     apr_status_t rv = APR_SUCCESS;
2595     apr_int32_t togo;        /* Remaining number of bytes in the file to send */
2596     apr_size_t sendlen = 0;
2597     apr_size_t bytes_sent;
2598     apr_int32_t i;
2599     apr_off_t o;             /* Track the file offset for partial writes */
2600     char buffer[8192];
2601
2602     *nbytes = 0;
2603
2604     /* Send the headers 
2605      * writev_it_all handles partial writes.
2606      * XXX: optimization... if headers are less than MIN_WRITE_SIZE, copy 
2607      * them into buffer
2608      */
2609     if ( hdtr && hdtr->numheaders > 0 ) {
2610         for (i = 0; i < hdtr->numheaders; i++) {
2611             sendlen += hdtr->headers[i].iov_len;
2612         }
2613         rv = writev_it_all(c->client_socket, hdtr->headers, hdtr->numheaders,
2614                            sendlen, &bytes_sent);
2615         if (rv == APR_SUCCESS)
2616             *nbytes += bytes_sent;     /* track total bytes sent */
2617     }
2618
2619     /* Seek the file to 'offset' */
2620     if (offset != 0 && rv == APR_SUCCESS) {
2621         rv = apr_file_seek(fd, APR_SET, &offset);
2622     }
2623
2624     /* Send the file, making sure to handle partial writes */
2625     togo = length;
2626     while (rv == APR_SUCCESS && togo) {
2627         sendlen = togo > sizeof(buffer) ? sizeof(buffer) : togo;
2628         o = 0;
2629         rv = apr_file_read(fd, buffer, &sendlen);
2630         while (rv == APR_SUCCESS && sendlen) {
2631             bytes_sent = sendlen;
2632             rv = apr_send(c->client_socket, &buffer[o], &bytes_sent);
2633             if (rv == APR_SUCCESS) {
2634                 sendlen -= bytes_sent; /* sendlen != bytes_sent ==> partial write */
2635                 o += bytes_sent;       /* o is where we are in the buffer */
2636                 *nbytes += bytes_sent;
2637                 togo -= bytes_sent;    /* track how much of the file we've sent */
2638             }
2639         }
2640     }
2641
2642     /* Send the trailers 
2643      * XXX: optimization... if it will fit, send this on the last send in the 
2644      * loop above
2645      */
2646     sendlen = 0;
2647     if ( rv == APR_SUCCESS && hdtr && hdtr->numtrailers > 0 ) {
2648         for (i = 0; i < hdtr->numtrailers; i++) {
2649             sendlen += hdtr->trailers[i].iov_len;
2650         }
2651         rv = writev_it_all(c->client_socket, hdtr->trailers, hdtr->numtrailers,
2652                            sendlen, &bytes_sent);
2653         if (rv == APR_SUCCESS)
2654             *nbytes += bytes_sent;
2655     }
2656
2657     return rv;
2658 }
2659
2660 /* Note --- ErrorDocument will now work from .htaccess files.  
2661  * The AllowOverride of Fileinfo allows webmasters to turn it off
2662  */
2663
2664 static const command_rec core_cmds[] = {
2665
2666 /* Old access config file commands */
2667
2668 AP_INIT_RAW_ARGS("<Directory", dirsection, NULL, RSRC_CONF, 
2669   "Container for directives affecting resources located in the specified "
2670   "directories"),
2671 AP_INIT_RAW_ARGS("<Location", urlsection, NULL, RSRC_CONF,
2672   "Container for directives affecting resources accessed through the "
2673   "specified URL paths"),
2674 AP_INIT_RAW_ARGS("<VirtualHost", virtualhost_section, NULL, RSRC_CONF,
2675   "Container to map directives to a particular virtual host, takes one or "
2676   "more host addresses"),
2677 AP_INIT_RAW_ARGS("<Files", filesection, NULL, OR_ALL,
2678   "Container for directives affecting files matching specified patterns"),
2679 AP_INIT_RAW_ARGS("<Limit", ap_limit_section, NULL, OR_ALL,
2680   "Container for authentication directives when accessed using specified HTTP "
2681   "methods"),
2682 AP_INIT_RAW_ARGS("<LimitExcept", ap_limit_section, (void*)1, OR_ALL,
2683   "Container for authentication directives to be applied when any HTTP "
2684   "method other than those specified is used to access the resource"),
2685 AP_INIT_TAKE1("<IfModule", start_ifmod, NULL, EXEC_ON_READ | OR_ALL,
2686   "Container for directives based on existance of specified modules"),
2687 AP_INIT_TAKE1("<IfDefine", start_ifdefine, NULL, EXEC_ON_READ | OR_ALL,
2688   "Container for directives based on existance of command line defines"),
2689 AP_INIT_RAW_ARGS("<DirectoryMatch", dirsection, (void*)1, RSRC_CONF,
2690   "Container for directives affecting resources located in the "
2691   "specified directories"),
2692 AP_INIT_RAW_ARGS("<LocationMatch", urlsection, (void*)1, RSRC_CONF,
2693   "Container for directives affecting resources accessed through the "
2694   "specified URL paths"),
2695 AP_INIT_RAW_ARGS("<FilesMatch", filesection, (void*)1, OR_ALL,
2696   "Container for directives affecting files matching specified patterns"),
2697 AP_INIT_TAKE1("AuthType", ap_set_string_slot,
2698   (void*)APR_XtOffsetOf(core_dir_config, ap_auth_type), OR_AUTHCFG, 
2699   "An HTTP authorization type (e.g., \"Basic\")"),
2700 AP_INIT_TAKE1("AuthName", set_authname, NULL, OR_AUTHCFG,
2701   "The authentication realm (e.g. \"Members Only\")"),
2702 AP_INIT_RAW_ARGS("Require", require, NULL, OR_AUTHCFG,
2703   "Selects which authenticated users or groups may access a protected space"),
2704 AP_INIT_TAKE1("Satisfy", satisfy, NULL, OR_AUTHCFG,
2705   "access policy if both allow and require used ('all' or 'any')"),
2706 #ifdef GPROF
2707 AP_INIT_TAKE1("GprofDir", set_gprof_dir, NULL, RSRC_CONF,
2708   "Directory to plop gmon.out files"),
2709 #endif
2710 AP_INIT_TAKE1("AddDefaultCharset", set_add_default_charset, NULL, OR_FILEINFO, 
2711   "The name of the default charset to add to any Content-Type without one or 'Off' to disable"),
2712 AP_INIT_TAKE1("AcceptPathInfo", set_accept_path_info, NULL, OR_FILEINFO,
2713   "Set to on or off for PATH_INFO to be accepted by handlers, or default for the per-handler preference"),
2714
2715 /* Old resource config file commands */
2716   
2717 AP_INIT_RAW_ARGS("AccessFileName", set_access_name, NULL, RSRC_CONF,
2718   "Name(s) of per-directory config files (default: .htaccess)"),
2719 AP_INIT_TAKE1("DocumentRoot", set_document_root, NULL, RSRC_CONF,
2720   "Root directory of the document tree"),
2721 AP_INIT_TAKE2("ErrorDocument", set_error_document, NULL, OR_FILEINFO,
2722   "Change responses for HTTP errors"),
2723 AP_INIT_RAW_ARGS("AllowOverride", set_override, NULL, ACCESS_CONF,
2724   "Controls what groups of directives can be configured by per-directory "
2725   "config files"),
2726 AP_INIT_RAW_ARGS("Options", set_options, NULL, OR_OPTIONS,
2727   "Set a number of attributes for a given directory"),
2728 AP_INIT_TAKE1("DefaultType", ap_set_string_slot,
2729   (void*)APR_XtOffsetOf (core_dir_config, ap_default_type),
2730   OR_FILEINFO, "the default MIME type for untypable files"),
2731 AP_INIT_RAW_ARGS("FileETag", set_etag_bits, NULL, OR_FILEINFO,
2732   "Specify components used to construct a file's ETag"),
2733
2734 /* Old server config file commands */
2735
2736 AP_INIT_TAKE1("Port", ap_set_deprecated, NULL, RSRC_CONF, 
2737   "Port was replaced with Listen in Apache 2.0"),
2738 AP_INIT_TAKE1("HostnameLookups", set_hostname_lookups, NULL,
2739   ACCESS_CONF|RSRC_CONF,
2740   "\"on\" to enable, \"off\" to disable reverse DNS lookups, or \"double\" to "
2741   "enable double-reverse DNS lookups"),
2742 AP_INIT_TAKE1("ServerAdmin", set_server_string_slot,
2743   (void *)APR_XtOffsetOf (server_rec, server_admin), RSRC_CONF,
2744   "The email address of the server administrator"),
2745 AP_INIT_TAKE1("ServerName", server_hostname_port, NULL, RSRC_CONF,
2746   "The hostname and port of the server"),
2747 AP_INIT_TAKE1("ServerSignature", set_signature_flag, NULL, OR_ALL,
2748   "En-/disable server signature (on|off|email)"),
2749 AP_INIT_TAKE1("ServerRoot", set_server_root, NULL, RSRC_CONF,
2750   "Common directory of server-related files (logs, confs, etc.)"),
2751 AP_INIT_TAKE1("ErrorLog", set_server_string_slot,
2752   (void *)APR_XtOffsetOf (server_rec, error_fname), RSRC_CONF,
2753   "The filename of the error log"),
2754 AP_INIT_RAW_ARGS("ServerAlias", set_server_alias, NULL, RSRC_CONF,
2755   "A name or names alternately used to access the server"),
2756 AP_INIT_TAKE1("ServerPath", set_serverpath, NULL, RSRC_CONF,
2757   "The pathname the server can be reached at"),
2758 AP_INIT_TAKE1("Timeout", set_timeout, NULL, RSRC_CONF,
2759   "Timeout duration (sec)"),
2760 AP_INIT_FLAG("IdentityCheck", set_idcheck, NULL, RSRC_CONF|ACCESS_CONF,
2761   "Enable identd (RFC 1413) user lookups - SLOW"),
2762 AP_INIT_FLAG("ContentDigest", set_content_md5, NULL, OR_OPTIONS,
2763   "whether or not to send a Content-MD5 header with each request"),
2764 AP_INIT_TAKE1("UseCanonicalName", set_use_canonical_name, NULL,
2765   RSRC_CONF|ACCESS_CONF,
2766   "How to work out the ServerName : Port when constructing URLs"),
2767 /* TODO: RlimitFoo should all be part of mod_cgi, not in the core */
2768 /* TODO: ListenBacklog in MPM */
2769 AP_INIT_TAKE1("Include", include_config, NULL,
2770   (RSRC_CONF | ACCESS_CONF | EXEC_ON_READ),
2771   "Name of the config file to be included"),
2772 AP_INIT_TAKE1("LogLevel", set_loglevel, NULL, RSRC_CONF,
2773   "Level of verbosity in error logging"),
2774 AP_INIT_TAKE1("NameVirtualHost", ap_set_name_virtual_host, NULL, RSRC_CONF,
2775   "A numeric IP address:port, or the name of a host"),
2776 #ifdef _OSD_POSIX
2777 AP_INIT_TAKE1("BS2000Account", set_bs2000_account, NULL, RSRC_CONF,
2778   "Name of server User's bs2000 logon account name"),
2779 #endif
2780 AP_INIT_TAKE1("ServerTokens", set_serv_tokens, NULL, RSRC_CONF,
2781   "Determine tokens displayed in the Server: header - Min(imal), OS or Full"),
2782 AP_INIT_TAKE1("LimitRequestLine", set_limit_req_line, NULL, RSRC_CONF,
2783   "Limit on maximum size of an HTTP request line"),
2784 AP_INIT_TAKE1("LimitRequestFieldsize", set_limit_req_fieldsize, NULL,
2785   RSRC_CONF,
2786   "Limit on maximum size of an HTTP request header field"),
2787 AP_INIT_TAKE1("LimitRequestFields", set_limit_req_fields, NULL, RSRC_CONF,
2788   "Limit (0 = unlimited) on max number of header fields in a request message"),
2789 AP_INIT_TAKE1("LimitRequestBody", set_limit_req_body,
2790   (void*)APR_XtOffsetOf(core_dir_config, limit_req_body), OR_ALL,
2791   "Limit (in bytes) on maximum size of request message body"),
2792 AP_INIT_TAKE1("LimitXMLRequestBody", set_limit_xml_req_body, NULL, OR_ALL,
2793               "Limit (in bytes) on maximum size of an XML-based request "
2794               "body"),
2795
2796 /* System Resource Controls */
2797 #ifdef RLIMIT_CPU
2798 AP_INIT_TAKE12("RLimitCPU", set_limit_cpu,
2799   (void*)APR_XtOffsetOf(core_dir_config, limit_cpu),
2800   OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
2801 #else
2802 AP_INIT_TAKE12("RLimitCPU", no_set_limit, NULL,
2803   OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
2804 #endif
2805 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined (RLIMIT_AS)
2806 AP_INIT_TAKE12("RLimitMEM", set_limit_mem,
2807   (void*)APR_XtOffsetOf(core_dir_config, limit_mem),
2808   OR_ALL, "Soft/hard limits for max memory usage per process"),
2809 #else
2810 AP_INIT_TAKE12("RLimitMEM", no_set_limit, NULL,
2811   OR_ALL, "Soft/hard limits for max memory usage per process"),
2812 #endif
2813 #ifdef RLIMIT_NPROC
2814 AP_INIT_TAKE12("RLimitNPROC", set_limit_nproc,
2815   (void*)APR_XtOffsetOf(core_dir_config, limit_nproc),
2816   OR_ALL, "soft/hard limits for max number of processes per uid"),
2817 #else
2818 AP_INIT_TAKE12("RLimitNPROC", no_set_limit, NULL,
2819    OR_ALL, "soft/hard limits for max number of processes per uid"),
2820 #endif
2821
2822 AP_INIT_TAKE1("ForceType", ap_set_string_slot_lower, 
2823        (void *)APR_XtOffsetOf(core_dir_config, mime_type), OR_FILEINFO,
2824      "a mime type that overrides other configured type"),
2825 AP_INIT_TAKE1("SetHandler", ap_set_string_slot_lower, 
2826        (void *)APR_XtOffsetOf(core_dir_config, handler), OR_FILEINFO,
2827    "a handler name that overrides any other configured handler"),
2828 AP_INIT_TAKE1("SetOutputFilter", ap_set_string_slot, 
2829        (void *)APR_XtOffsetOf(core_dir_config, output_filters), OR_FILEINFO,
2830    "filter (or ; delimited list of filters) to be run on the request content"),
2831 AP_INIT_TAKE1("SetInputFilter", ap_set_string_slot, 
2832        (void *)APR_XtOffsetOf(core_dir_config, input_filters), OR_FILEINFO,
2833    "filter (or ; delimited list of filters) to be run on the request body"),
2834 AP_INIT_ITERATE2("AddOutputFilterByType", add_ct_output_filters,
2835        (void *)APR_XtOffsetOf(core_dir_config, ct_output_filters), OR_FILEINFO,
2836      "output filter name followed by one or more content-types"),
2837
2838 /*
2839  * These are default configuration directives that mpms can/should
2840  * pay attention to. If an mpm wishes to use these, they should
2841  * #defined them in mpm.h.
2842  */
2843 #ifdef AP_MPM_WANT_SET_PIDFILE
2844 AP_INIT_TAKE1("PidFile",  ap_mpm_set_pidfile, NULL, RSRC_CONF, \
2845               "A file for logging the server process ID"),
2846 #endif
2847 #ifdef AP_MPM_WANT_SET_SCOREBOARD
2848 AP_INIT_TAKE1("ScoreBoardFile", ap_mpm_set_scoreboard, NULL, RSRC_CONF, \
2849               "A file for Apache to maintain runtime process management information"),
2850 #endif
2851 #ifdef AP_MPM_WANT_SET_LOCKFILE
2852 AP_INIT_TAKE1("LockFile",  ap_mpm_set_lockfile, NULL, RSRC_CONF, \
2853               "The lockfile used when Apache needs to lock the accept() call"),
2854 #endif
2855 #ifdef AP_MPM_WANT_SET_MAX_REQUESTS
2856 AP_INIT_TAKE1("MaxRequestsPerChild", ap_mpm_set_max_requests, NULL, RSRC_CONF,\
2857               "Maximum number of requests a particular child serves before dying."),
2858 #endif
2859 #ifdef AP_MPM_WANT_SET_COREDUMPDIR
2860 AP_INIT_TAKE1("CoreDumpDirectory", ap_mpm_set_coredumpdir, NULL, RSRC_CONF, \
2861               "The location of the directory Apache changes to before dumping core"),
2862 #endif
2863 #ifdef AP_MPM_WANT_SET_ACCEPT_LOCK_MECH
2864 AP_INIT_TAKE1("AcceptMutex", ap_mpm_set_accept_lock_mech, NULL, RSRC_CONF, \
2865               "The system mutex implementation to use for the accept mutex"),
2866 #endif
2867 { NULL }
2868 };
2869
2870 /*****************************************************************
2871  *
2872  * Core handlers for various phases of server operation...
2873  */
2874
2875 AP_DECLARE_NONSTD(int) ap_core_translate(request_rec *r)
2876 {
2877     void *sconf = r->server->module_config;
2878     core_server_config *conf = ap_get_module_config(sconf, &core_module);
2879   
2880     /* XXX this seems too specific, this should probably become
2881      * some general-case test 
2882      */
2883     if (r->proxyreq) {
2884         return HTTP_FORBIDDEN;
2885     }
2886     if (!r->uri || ((r->uri[0] != '/') && strcmp(r->uri, "*"))) {
2887         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2888                      "Invalid URI in request %s", r->the_request);
2889         return HTTP_BAD_REQUEST;
2890     }
2891     
2892     if (r->server->path 
2893         && !strncmp(r->uri, r->server->path, r->server->pathlen)
2894         && (r->server->path[r->server->pathlen - 1] == '/'
2895             || r->uri[r->server->pathlen] == '/'
2896             || r->uri[r->server->pathlen] == '\0')) {
2897         if (apr_filepath_merge(&r->filename, conf->ap_document_root,
2898                                r->uri + r->server->pathlen, 
2899                                APR_FILEPATH_TRUENAME 
2900                              | APR_FILEPATH_SECUREROOT, r->pool)
2901                     != APR_SUCCESS) {
2902             return HTTP_FORBIDDEN;
2903         }
2904         r->canonical_filename = r->filename;
2905     }
2906     else {
2907         /*
2908          * Make sure that we do not mess up the translation by adding two
2909          * /'s in a row.  This happens under windows when the document
2910          * root ends with a /
2911          */
2912         if (apr_filepath_merge(&r->filename, conf->ap_document_root,
2913                                r->uri + ((*(r->uri) == '/') ? 1 : 0),
2914                                APR_FILEPATH_TRUENAME
2915                              | APR_FILEPATH_SECUREROOT, r->pool)
2916                     != APR_SUCCESS) {
2917             return HTTP_FORBIDDEN;
2918         }
2919         r->canonical_filename = r->filename;
2920     }
2921
2922     return OK;
2923 }
2924
2925 /*****************************************************************
2926  *
2927  * Test the filesystem name through directory_walk and file_walk
2928  */
2929 static int core_map_to_storage(request_rec *r)
2930 {
2931     int access_status;
2932
2933     if ((access_status = ap_directory_walk(r))) {
2934         return access_status;
2935     }
2936
2937     if ((access_status = ap_file_walk(r))) {
2938         return access_status;
2939     }
2940
2941     return OK;
2942 }
2943
2944
2945 static int do_nothing(request_rec *r) { return OK; }
2946
2947
2948 static int core_override_type(request_rec *r)
2949 {
2950     core_dir_config *conf = 
2951         (core_dir_config *)ap_get_module_config(r->per_dir_config,
2952                                                 &core_module);
2953
2954     /* Check for overrides with ForceType / SetHandler
2955      */
2956     if (conf->mime_type && strcmp(conf->mime_type, "none"))
2957         r->content_type = conf->mime_type;
2958
2959     if (conf->handler && strcmp(conf->handler, "none"))
2960         r->handler = conf->handler;
2961
2962     /* Deal with the poor soul who is trying to force path_info to be
2963      * accepted within the core_handler, where they will let the subreq
2964      * address it's contents.  This is toggled by the user in the very
2965      * beginning of the fixup phase, so modules should override the user's 
2966      * discresion in their own module fixup phase.  It is tristate, if
2967      * the user doesn't specify, the result is 2 (which the module may
2968      * interpret to it's own customary behavior.)  It won't be tounched
2969      * if the value is no longer undefined (2), so any module changing
2970      * the value prior to the fixup phase OVERRIDES the user's choice.
2971      */
2972     if ((r->used_path_info == AP_REQ_DEFAULT_PATH_INFO)
2973             && (conf->accept_path_info != 3)) {
2974         r->used_path_info = conf->accept_path_info;
2975     }
2976     return OK;
2977 }
2978
2979 static int core_filters_type(request_rec *r)
2980 {
2981     core_dir_config *conf;
2982     const char *ctype, *ctypes;
2983
2984     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
2985                                                    &core_module);
2986
2987     /* We can't do anything with proxy requests, no content-types or if
2988      * we don't have a filter configured. */ 
2989     if (r->proxyreq != PROXYREQ_NONE || !r->content_type || 
2990         !conf->ct_output_filters) {
2991         return OK;
2992     }
2993
2994     ctypes = r->content_type;
2995   
2996     /* We must be able to handle decorated content-types.  */
2997     while (*ctypes && (ctype = ap_getword(r->pool, &ctypes, ';'))) {
2998         ap_filter_rec_t *ct_filter;
2999         ct_filter = apr_hash_get(conf->ct_output_filters, ctype,
3000                                  APR_HASH_KEY_STRING);
3001         while (ct_filter) {
3002             ap_add_output_filter(ct_filter->name, NULL, r, r->connection);
3003             ct_filter = ct_filter->next;
3004         }
3005     }
3006
3007     return OK;
3008 }
3009
3010 static int default_handler(request_rec *r)
3011 {
3012     apr_bucket_brigade *bb;
3013     apr_bucket *e;
3014     core_dir_config *d;
3015     int errstatus;
3016     apr_file_t *fd = NULL;
3017     apr_status_t status;
3018     /* XXX if/when somebody writes a content-md5 filter we either need to
3019      *     remove this support or coordinate when to use the filter vs.
3020      *     when to use this code
3021      *     The current choice of when to compute the md5 here matches the 1.3
3022      *     support fairly closely (unlike 1.3, we don't handle computing md5
3023      *     when the charset is translated).
3024      */
3025     int bld_content_md5;
3026
3027     /*
3028      * The old way of doing handlers meant that this handler would
3029      * match literally anything - this way will require handler to
3030      * have a / in the middle, which probably captures the original
3031      * intent, but may cause problems at first - Ben 7th Jan 01
3032      * Don't try to serve a dir.  Some OSs do weird things with
3033      * raw I/O on a dir.
3034      */
3035     if ((strcmp(r->handler, "default-handler")
3036          && !ap_strchr_c(r->handler, '/'))
3037         || r->finfo.filetype == APR_DIR)
3038         return DECLINED;
3039
3040     d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
3041                                                 &core_module);
3042     bld_content_md5 = (d->content_md5 & 1)
3043       && r->output_filters->frec->ftype != AP_FTYPE_CONTENT;
3044
3045     ap_allow_standard_methods(r, MERGE_ALLOW, M_GET, M_OPTIONS, M_POST, -1);
3046
3047     /* If filters intend to consume the request body, they must
3048      * register an InputFilter to slurp the contents of the POST
3049      * data from the POST input stream.  It no longer exists when
3050      * the output filters are invoked by the default handler.
3051      */
3052     if ((errstatus = ap_discard_request_body(r)) != OK) {
3053         return errstatus;
3054     }
3055     if (r->method_number == M_INVALID) {
3056         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
3057                     "Invalid method in request %s", r->the_request);
3058         return HTTP_NOT_IMPLEMENTED;
3059     }
3060     if (r->method_number == M_OPTIONS) {
3061         return ap_send_http_options(r);
3062     }
3063     if (r->method_number != M_GET && r->method_number != M_POST) {
3064         return HTTP_METHOD_NOT_ALLOWED;
3065     }
3066     if (r->finfo.filetype == 0) {
3067         ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r,
3068                       "File does not exist: %s", r->filename);
3069         return HTTP_NOT_FOUND;
3070     }
3071     if (!(r->used_path_info & 1) && r->path_info && *r->path_info) {
3072         ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r,
3073                       "File does not exist: %s",
3074                       apr_pstrcat(r->pool, r->filename, r->path_info, NULL));
3075         return HTTP_NOT_FOUND;
3076     }
3077     if ((status = apr_file_open(&fd, r->filename, APR_READ | APR_BINARY, 0, r->pool)) != APR_SUCCESS) {
3078         ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r,
3079                      "file permissions deny server access: %s", r->filename);
3080         return HTTP_FORBIDDEN;
3081     }
3082     ap_update_mtime(r, r->finfo.mtime);
3083     ap_set_last_modified(r);
3084     ap_set_etag(r);
3085     apr_table_setn(r->headers_out, "Accept-Ranges", "bytes");
3086     ap_set_content_length(r, r->finfo.size); 
3087     if ((errstatus = ap_meets_conditions(r)) != OK) {
3088         apr_file_close(fd);
3089         return errstatus;
3090     }
3091
3092     if (bld_content_md5) {
3093         apr_table_setn(r->headers_out, "Content-MD5",
3094                        ap_md5digest(r->pool, fd));
3095     }
3096
3097     bb = apr_brigade_create(r->pool);
3098 #if APR_HAS_LARGE_FILES
3099     if (r->finfo.size > AP_MAX_SENDFILE) {
3100         /* APR_HAS_LARGE_FILES issue; must split into mutiple buckets, 
3101          * no greater than MAX(apr_size_t), and more granular than that
3102          * in case the brigade code/filters attempt to read it directly.
3103          */
3104         apr_off_t fsize = r->finfo.size;
3105         e = apr_bucket_file_create(fd, 0, AP_MAX_SENDFILE, r->pool);
3106         while (fsize > AP_MAX_SENDFILE) {
3107             apr_bucket *ce;
3108             apr_bucket_copy(e, &ce);
3109             APR_BRIGADE_INSERT_TAIL(bb, ce);
3110             e->start += AP_MAX_SENDFILE;
3111             fsize -= AP_MAX_SENDFILE;
3112         }
3113         e->length = (apr_size_t)fsize; /* Resize just the last bucket */
3114     }
3115     else
3116 #endif
3117         e = apr_bucket_file_create(fd, 0, (apr_size_t)r->finfo.size, r->pool);
3118
3119     APR_BRIGADE_INSERT_TAIL(bb, e);
3120     e = apr_bucket_eos_create();
3121     APR_BRIGADE_INSERT_TAIL(bb, e);
3122
3123     return ap_pass_brigade(r->output_filters, bb);
3124 }
3125
3126 static int net_time_filter(ap_filter_t *f, apr_bucket_brigade *b, 
3127                            ap_input_mode_t mode, apr_read_type_e block,
3128                            apr_off_t readbytes)
3129 {
3130     int keptalive = f->c->keepalive == 1;
3131     apr_socket_t *csd = ap_get_module_config(f->c->conn_config, &core_module);
3132     int *first_line = f->ctx;
3133
3134     if (!f->ctx) {
3135         f->ctx = first_line = apr_palloc(f->r->pool, sizeof(*first_line));
3136         *first_line = 1;
3137     }
3138
3139     if (mode != AP_MODE_INIT && mode != AP_MODE_EATCRLF) {
3140         if (*first_line) {
3141             apr_setsocketopt(csd, APR_SO_TIMEOUT,
3142                              (int)(keptalive
3143                       ? f->c->base_server->keep_alive_timeout * APR_USEC_PER_SEC
3144                       : f->c->base_server->timeout * APR_USEC_PER_SEC));
3145             *first_line = 0;
3146         }
3147         else {
3148             if (keptalive) {
3149                 apr_setsocketopt(csd, APR_SO_TIMEOUT,
3150                          (int)(f->c->base_server->timeout * APR_USEC_PER_SEC));
3151             }
3152         }
3153     }
3154     return ap_get_brigade(f->next, b, mode, block, readbytes);
3155 }
3156
3157 /**
3158  * Remove all zero length buckets from the brigade.
3159  */
3160 #define BRIGADE_NORMALIZE(b)       \
3161 do { \
3162     apr_bucket *e = APR_BRIGADE_FIRST(b); \
3163     do {  \
3164         if (e->length == 0) { \
3165             apr_bucket *d; \
3166             d = APR_BUCKET_NEXT(e); \
3167             apr_bucket_delete(e); \
3168             e = d; \
3169         } \
3170         e = APR_BUCKET_NEXT(e); \
3171     } while (!APR_BRIGADE_EMPTY(b) && (e != APR_BRIGADE_SENTINEL(b))); \
3172 } while (0)
3173
3174 static int core_input_filter(ap_filter_t *f, apr_bucket_brigade *b, 
3175                              ap_input_mode_t mode, apr_read_type_e block,
3176                              apr_off_t readbytes)
3177 {
3178     apr_bucket *e;
3179     apr_status_t rv;
3180     core_net_rec *net = f->ctx;
3181     core_ctx_t *ctx = net->in_ctx;
3182     const char *str;
3183     apr_size_t len;
3184
3185     if (mode == AP_MODE_INIT) {
3186         /*
3187          * this mode is for filters that might need to 'initialize'
3188          * a connection before reading request data from a client.
3189          * NNTP over SSL for example needs to handshake before the 
3190          * server sends the welcome message.
3191          * such filters would have changed the mode before this point
3192          * is reached.  however, protocol modules such as NNTP should
3193          * not need to know anything about SSL.  given the example, if
3194          * SSL is not in the filter chain, AP_MODE_INIT is a noop.
3195          */
3196         return APR_SUCCESS;
3197     }
3198
3199     if (!ctx)
3200     {
3201         ctx = apr_pcalloc(f->c->pool, sizeof(*ctx));
3202         ctx->b = apr_brigade_create(f->c->pool);
3203
3204         /* seed the brigade with the client socket. */
3205         e = apr_bucket_socket_create(net->client_socket);
3206         APR_BRIGADE_INSERT_TAIL(ctx->b, e);
3207         net->in_ctx = ctx;
3208     }
3209     else if (APR_BRIGADE_EMPTY(ctx->b)) {
3210         return APR_EOF;
3211     }
3212     
3213     /* ### This is bad. */
3214     BRIGADE_NORMALIZE(ctx->b);
3215
3216     /* check for empty brigade again *AFTER* BRIGADE_NORMALIZE()
3217      * If we have lost our socket bucket (see above), we are EOF.
3218      *
3219      * Ideally, this should be returning SUCCESS with EOS bucket, but
3220      * some higher-up APIs (spec. read_request_line via ap_rgetline)
3221      * want an error code. */
3222     if (APR_BRIGADE_EMPTY(ctx->b)) {
3223         return APR_EOF;
3224     }
3225     
3226     /* ### AP_MODE_PEEK is a horrific name for this mode because we also
3227      * eat any CRLFs that we see.  That's not the obvious intention of
3228      * this mode.  Determine whether anyone actually uses this or not. */
3229     if (mode == AP_MODE_EATCRLF) {
3230         apr_bucket *e;
3231         const char *c;
3232
3233         /* The purpose of this loop is to ignore any CRLF (or LF) at the end
3234          * of a request.  Many browsers send extra lines at the end of POST
3235          * requests.  We use the PEEK method to determine if there is more
3236          * data on the socket, so that we know if we should delay sending the
3237          * end of one request until we have served the second request in a
3238          * pipelined situation.  We don't want to actually delay sending a
3239          * response if the server finds a CRLF (or LF), becuause that doesn't
3240          * mean that there is another request, just a blank line.
3241          */
3242         while (1) {
3243
3244             if (APR_BRIGADE_EMPTY(ctx->b))
3245                 return APR_EOF;
3246
3247             e = APR_BRIGADE_FIRST(ctx->b);
3248
3249             rv = apr_bucket_read(e, &str, &len, APR_NONBLOCK_READ);
3250
3251             if (rv != APR_SUCCESS)
3252                 return rv;
3253
3254             c = str;
3255             while (c < str + len) {
3256                 if (*c == APR_ASCII_LF)
3257                     c++;
3258                 else if (*c == APR_ASCII_CR && *(c + 1) == APR_ASCII_LF)
3259                     c += 2;
3260                 else 
3261                     return APR_SUCCESS;
3262             }
3263             /* If we reach here, we were a bucket just full of CRLFs, so
3264              * just toss the bucket. */
3265             /* FIXME: Is this the right thing to do in the core? */
3266             apr_bucket_delete(e);
3267         }
3268     }
3269
3270     /* If mode is EXHAUSTIVE, we want to just read everything until the end
3271      * of the brigade, which in this case means the end of the socket.
3272      * To do this, we attach the brigade that has currently been setaside to
3273      * the brigade that was passed down, and send that brigade back.
3274      * 
3275      * NOTE:  This is VERY dangerous to use, and should only be done with
3276      * extreme caution.  However, the Perchild MPM needs this feature
3277      * if it is ever going to work correctly again.  With this, the Perchild
3278      * MPM can easily request the socket and all data that has been read,
3279      * which means that it can pass it to the correct child process.
3280      */
3281     if (mode == AP_MODE_EXHAUSTIVE) {
3282         apr_bucket *e;
3283         apr_off_t total;
3284
3285         /* Force a recompute of the length and force a read-all */
3286         apr_brigade_length(ctx->b, 1, &total);
3287         APR_BRIGADE_CONCAT(b, ctx->b);
3288         /* We have read until the brigade was empty, so we know that we 
3289          * must be EOS. */
3290         e = apr_bucket_eos_create();
3291         APR_BRIGADE_INSERT_TAIL(b, e);
3292         return APR_SUCCESS;
3293     }
3294     /* read up to the amount they specified. */
3295     if (mode == AP_MODE_READBYTES || mode == AP_MODE_SPECULATIVE) {
3296         apr_off_t total;
3297         apr_bucket *e;
3298         apr_bucket_brigade *newbb;
3299
3300         AP_DEBUG_ASSERT(readbytes > 0);
3301         
3302         e = APR_BRIGADE_FIRST(ctx->b);
3303         rv = apr_bucket_read(e, &str, &len, block);
3304
3305         if (APR_STATUS_IS_EAGAIN(rv)) {
3306             return APR_SUCCESS;
3307         }
3308         else if (rv != APR_SUCCESS) {
3309             return rv;
3310         } else if (block == APR_BLOCK_READ && len == 0) {
3311             /* We wanted to read some bytes in blocking mode.  We read
3312              * 0 bytes.  Hence, we now assume we are EOS.
3313              *
3314              * When we are in normal mode, return an EOS bucket to the
3315              * caller.
3316              * When we are in speculative mode, leave ctx->b empty, so
3317              * that the next call returns an EOS bucket.
3318              */
3319             apr_bucket_delete(e);
3320
3321             if (mode == AP_MODE_READBYTES) {
3322                 e = apr_bucket_eos_create();
3323                 APR_BRIGADE_INSERT_TAIL(b, e);
3324             }
3325             return APR_SUCCESS;
3326         }
3327
3328         /* We can only return at most what we read. */
3329         if (len < readbytes) {
3330             readbytes = len;
3331         }
3332
3333         apr_brigade_partition(ctx->b, readbytes, &e);
3334
3335         /* Must do split before CONCAT */
3336         newbb = apr_brigade_split(ctx->b, e);
3337
3338         if (mode == AP_MODE_READBYTES) {
3339             APR_BRIGADE_CONCAT(b, ctx->b);
3340         }
3341         else if (mode == AP_MODE_SPECULATIVE) {
3342             apr_bucket *copy_bucket;
3343             APR_BRIGADE_FOREACH(e, ctx->b) {
3344                 rv = apr_bucket_copy(e, &copy_bucket);
3345                 if (rv != APR_SUCCESS) {
3346                     return rv;
3347                 }
3348                 APR_BRIGADE_INSERT_TAIL(b, copy_bucket);
3349             }
3350         }
3351
3352         /* Take what was originally there and place it back on ctx->b */
3353         APR_BRIGADE_CONCAT(ctx->b, newbb);
3354
3355         apr_brigade_length(b, 1, &total);
3356
3357         return APR_SUCCESS;
3358     }
3359
3360     /* we are reading a single LF line, e.g. the HTTP headers */
3361     rv = apr_brigade_split_line(b, ctx->b, block, HUGE_STRING_LEN);
3362     /* We should treat EAGAIN here the same as we do for EOF (brigade is
3363      * empty).  We do this by returning whatever we have read.  This may 
3364      * or may not be bogus, but is consistent (for now) with EOF logic.
3365      */
3366     if (APR_STATUS_IS_EAGAIN(rv)) {
3367         rv = APR_SUCCESS;
3368     }
3369
3370     return rv;
3371 }
3372
3373 /* Default filter.  This filter should almost always be used.  Its only job
3374  * is to send the headers if they haven't already been sent, and then send
3375  * the actual data.
3376  */
3377 #define MAX_IOVEC_TO_WRITE 16
3378
3379 static apr_status_t core_output_filter(ap_filter_t *f, apr_bucket_brigade *b)
3380 {
3381     apr_status_t rv;
3382     conn_rec *c = f->c;
3383     core_net_rec *net = f->ctx;
3384     core_output_filter_ctx_t *ctx = net->out_ctx;
3385
3386     if (ctx == NULL) {
3387         ctx = apr_pcalloc(c->pool, sizeof(*ctx));
3388         net->out_ctx = ctx;
3389     }
3390
3391     /* If we have a saved brigade, concatenate the new brigade to it */
3392     if (ctx->b) {
3393         APR_BRIGADE_CONCAT(ctx->b, b);
3394         b = ctx->b;
3395         ctx->b = NULL;
3396     }
3397
3398     /* Perform multiple passes over the brigade, sending batches of output
3399        to the connection. */
3400     while (b) {
3401         apr_size_t nbytes = 0;
3402         apr_bucket *last_e = NULL; /* initialized for debugging */
3403         apr_bucket *e;
3404
3405         /* tail of brigade if we need another pass */
3406         apr_bucket_brigade *more = NULL;
3407
3408         /* one group of iovecs per pass over the brigade */
3409         apr_size_t nvec = 0;
3410         apr_size_t nvec_trailers = 0;
3411         struct iovec vec[MAX_IOVEC_TO_WRITE];
3412         struct iovec vec_trailers[MAX_IOVEC_TO_WRITE];
3413
3414         /* one file per pass over the brigade */
3415         apr_file_t *fd = NULL;
3416         apr_size_t flen = 0;
3417         apr_off_t foffset = 0;
3418
3419         /* keep track of buckets that we've concatenated
3420          * to avoid small writes
3421          */
3422         apr_bucket *last_merged_bucket = NULL;
3423
3424         /* Iterate over the brigade: collect iovecs and/or a file */
3425         APR_BRIGADE_FOREACH(e, b) {
3426             /* keep track of the last bucket processed */
3427             last_e = e;
3428             if (APR_BUCKET_IS_EOS(e) || APR_BUCKET_IS_FLUSH(e)) {
3429                 break;
3430             }
3431             /* It doesn't make any sense to use sendfile for a file bucket
3432              * that represents 10 bytes.
3433              */
3434             else if (APR_BUCKET_IS_FILE(e)
3435                      && (e->length >= AP_MIN_SENDFILE_BYTES)) {
3436                 apr_bucket_file *a = e->data;
3437     
3438                 /* We can't handle more than one file bucket at a time
3439                  * so we split here and send the file we have already
3440                  * found.
3441                  */
3442                 if (fd) {
3443                     more = apr_brigade_split(b, e);
3444                     break;
3445                 }
3446     
3447                 fd = a->fd;
3448                 flen = e->length;
3449                 foffset = e->start;
3450             }
3451             else {
3452                 const char *str;
3453                 apr_size_t n;
3454
3455                 rv = apr_bucket_read(e, &str, &n, APR_BLOCK_READ);
3456                 if (n) {
3457                     if (!fd) {
3458                         if (nvec == MAX_IOVEC_TO_WRITE) {
3459                             /* woah! too many. buffer them up, for use later. */
3460                             apr_bucket *temp, *next;
3461                             apr_bucket_brigade *temp_brig;
3462
3463                             if (nbytes >= AP_MIN_BYTES_TO_WRITE) {
3464                                 /* We have enough data in the iovec
3465                                  * to justify doing a writev
3466                                  */
3467                                 more = apr_brigade_split(b, e);
3468                                 break;
3469                             }
3470
3471                             /* Create a temporary brigade as a means
3472                              * of concatenating a bunch of buckets together
3473                              */
3474                             if (last_merged_bucket) {
3475                                 /* If we've concatenated together small
3476                                  * buckets already in a previous pass,
3477                                  * the initial buckets in this brigade
3478                                  * are heap buckets that may have extra
3479                                  * space left in them (because they
3480                                  * were created by apr_brigade_write()).
3481                                  * We can take advantage of this by
3482                                  * building the new temp brigade out of
3483                                  * these buckets, so that the content
3484                                  * in them doesn't have to be copied again.
3485                                  */
3486                                 apr_bucket_brigade *bb;
3487                                 bb = apr_brigade_split(b,
3488                                          APR_BUCKET_NEXT(last_merged_bucket));
3489                                 temp_brig = b;
3490                                 b = bb;
3491                             }
3492                             else {
3493                                 temp_brig = apr_brigade_create(f->c->pool);
3494                             }
3495                             temp = APR_BRIGADE_FIRST(b);
3496                             while (temp != e) {
3497                                 apr_bucket *d;
3498                                 rv = apr_bucket_read(temp, &str, &n, APR_BLOCK_READ);
3499                                 apr_brigade_write(temp_brig, NULL, NULL, str, n);
3500                                 d = temp;
3501                                 temp = APR_BUCKET_NEXT(temp);
3502                                 apr_bucket_delete(d);
3503                             }
3504                             nvec = 0;
3505                             nbytes = 0;
3506                             temp = APR_BRIGADE_FIRST(temp_brig);
3507                             APR_BUCKET_REMOVE(temp);
3508                             APR_BRIGADE_INSERT_HEAD(b, temp);
3509                             apr_bucket_read(temp, &str, &n, APR_BLOCK_READ);
3510                             vec[nvec].iov_base = (char*) str;
3511                             vec[nvec].iov_len = n;
3512                             nvec++;
3513
3514                             /* Just in case the temporary brigade has
3515                              * multiple buckets, recover the rest of
3516                              * them and put them in the brigade that
3517                              * we're sending.
3518                              */
3519                             for (next = APR_BRIGADE_FIRST(temp_brig);
3520                                  next != APR_BRIGADE_SENTINEL(temp_brig);
3521                                  next = APR_BRIGADE_FIRST(temp_brig)) {
3522                                 APR_BUCKET_REMOVE(next);
3523                                 APR_BUCKET_INSERT_AFTER(temp, next);
3524                                 temp = next;
3525                                 apr_bucket_read(next, &str, &n,
3526                                                 APR_BLOCK_READ);
3527                                 vec[nvec].iov_base = (char*) str;
3528                                 vec[nvec].iov_len = n;
3529                                 nvec++;
3530                             }
3531                             apr_brigade_destroy(temp_brig);
3532
3533                             last_merged_bucket = temp;
3534                             e = temp;
3535                             last_e = e;
3536                         }
3537                         else {
3538                             vec[nvec].iov_base = (char*) str;
3539                             vec[nvec].iov_len = n;
3540                             nvec++;
3541                         }
3542                     }
3543                     else {
3544                         /* The bucket is a trailer to a file bucket */
3545
3546                         if (nvec_trailers == MAX_IOVEC_TO_WRITE) {
3547                             /* woah! too many. stop now. */
3548                             more = apr_brigade_split(b, e);
3549                             break;
3550                         }
3551                         vec_trailers[nvec_trailers].iov_base = (char*) str;
3552                         vec_trailers[nvec_trailers].iov_len = n;
3553                         nvec_trailers++;
3554                     }
3555                     nbytes += n;
3556                 }
3557             }
3558         }
3559
3560     
3561         /* Completed iterating over the brigades, now determine if we want 
3562          * to buffer the brigade or send the brigade out on the network.
3563          *
3564          * Save if:
3565          *
3566          *   1) we didn't see a file, we don't have more passes over the
3567          *      brigade to perform, we haven't accumulated enough bytes to
3568          *      send, AND we didn't stop at a FLUSH bucket.
3569          *      (IOW, we will save away plain old bytes)
3570          * or
3571          *   2) we hit the EOS and have a keep-alive connection
3572          *      (IOW, this response is a bit more complex, but we save it
3573          *       with the hope of concatenating with another response)
3574          */
3575         if ((!fd && !more && 
3576             (nbytes + flen < AP_MIN_BYTES_TO_WRITE) && !APR_BUCKET_IS_FLUSH(last_e))
3577             || (nbytes + flen < AP_MIN_BYTES_TO_WRITE && APR_BUCKET_IS_EOS(last_e) && c->keepalive)) {
3578
3579             /* NEVER save an EOS in here.  If we are saving a brigade with 
3580              * an EOS bucket, then we are doing keepalive connections, and 
3581              * we want to process to second request fully.
3582              */
3583             if (APR_BUCKET_IS_EOS(last_e)) {
3584                 apr_bucket *bucket = NULL;
3585                 /* If we are in here, then this request is a keepalive.  We
3586                  * need to be certain that any data in a bucket is valid
3587                  * after the request_pool is cleared.
3588                  */ 
3589                 if (ctx->b == NULL) {
3590                     ctx->b = apr_brigade_create(net->c->pool);
3591                 }
3592
3593                 APR_BRIGADE_FOREACH(bucket, b) {
3594                     const char *str;
3595                     apr_size_t n;
3596
3597                     rv = apr_bucket_read(bucket, &str, &n, APR_BLOCK_READ);
3598
3599                     /* This apr_brigade_write does not use a flush function
3600                        because we assume that we will not write enough data
3601                        into it to cause a flush. However, if we *do* write
3602                        "too much", then we could end up with transient
3603                        buckets which would suck. This works for now, but is
3604                        a bit shaky if changes are made to some of the
3605                        buffering sizes. Let's do an assert to prevent
3606                        potential future problems... */
3607                     AP_DEBUG_ASSERT(AP_MIN_BYTES_TO_WRITE <=
3608                                     APR_BUCKET_BUFF_SIZE);
3609                     if (rv != APR_SUCCESS) {
3610                         ap_log_error(APLOG_MARK, APLOG_ERR, rv, c->base_server,
3611                                      "core_output_filter: Error reading from bucket.");
3612                         return rv;
3613                     }
3614                     apr_brigade_write(ctx->b, NULL, NULL, str, n);
3615                 }
3616                 apr_brigade_destroy(b);
3617             }
3618             else {
3619                 ap_save_brigade(f, &ctx->b, &b, c->pool);
3620             }
3621             return APR_SUCCESS;
3622         }
3623
3624         if (fd) {
3625             apr_hdtr_t hdtr;
3626 #if APR_HAS_SENDFILE
3627             apr_int32_t flags = 0;
3628 #endif
3629     
3630             memset(&hdtr, '\0', sizeof(hdtr));
3631             if (nvec) {
3632                 hdtr.numheaders = nvec;
3633                 hdtr.headers = vec;
3634             }
3635             if (nvec_trailers) {
3636                 hdtr.numtrailers = nvec_trailers;
3637                 hdtr.trailers = vec_trailers;
3638             }
3639 #if APR_HAS_SENDFILE
3640             if (!c->keepalive && APR_BUCKET_IS_EOS(last_e)) {
3641                 /* Prepare the socket to be reused */
3642                 flags |= APR_SENDFILE_DISCONNECT_SOCKET;
3643             }
3644             rv = sendfile_it_all(net,      /* the network information   */
3645                                  fd,       /* the file to send          */
3646                                  &hdtr,    /* header and trailer iovecs */
3647                                  foffset,  /* offset in the file to begin
3648                                               sending from              */
3649                                  flen,     /* length of file            */
3650                                  nbytes + flen, /* total length including
3651                                                    headers                */
3652                                  flags);   /* apr_sendfile flags        */
3653     
3654             /* If apr_sendfile() returns APR_ENOTIMPL, call emulate_sendfile().
3655              * emulate_sendfile() is useful to enable the same Apache binary 
3656              * distribution to support Windows NT/2000 (supports TransmitFile) 
3657              * and Win95/98 (do not support TransmitFile)
3658              */
3659             if (rv == APR_ENOTIMPL)
3660 #endif
3661             {
3662                 apr_size_t unused_bytes_sent;
3663                 rv = emulate_sendfile(net, fd, &hdtr, foffset, flen, 
3664                                       &unused_bytes_sent);
3665             }
3666             fd = NULL;
3667         }
3668         else {
3669             apr_size_t unused_bytes_sent;
3670
3671             rv = writev_it_all(net->client_socket, 
3672                                vec, nvec, 
3673                                nbytes, &unused_bytes_sent);
3674         }
3675
3676         apr_brigade_destroy(b);
3677         if (rv != APR_SUCCESS) {
3678             ap_log_error(APLOG_MARK, APLOG_INFO, rv, c->base_server,
3679                "core_output_filter: writing data to the network");
3680             if (more)
3681                 apr_brigade_destroy(more);
3682             if (APR_STATUS_IS_ECONNABORTED(rv) ||
3683                 APR_STATUS_IS_ECONNRESET(rv) ||
3684                 APR_STATUS_IS_EPIPE(rv)) {
3685                 c->aborted = 1;
3686             }
3687             return rv;
3688         }
3689     
3690         b = more;
3691         more = NULL;
3692     }  /* end while () */
3693
3694     return APR_SUCCESS;
3695 }
3696
3697 static int core_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
3698 {
3699     ap_set_version(pconf);
3700     return OK;
3701 }
3702
3703 static int core_open_logs(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
3704 {
3705     ap_open_logs(s, plog);
3706     return OK;  
3707 }
3708
3709 static void core_insert_filter(request_rec *r)
3710 {
3711     core_dir_config *conf = (core_dir_config *)
3712                             ap_get_module_config(r->per_dir_config,
3713                                                    &core_module); 
3714     const char *filter, *filters = conf->output_filters;
3715
3716     if (filters) {
3717         while (*filters && (filter = ap_getword(r->pool, &filters, ';'))) {
3718             ap_add_output_filter(filter, NULL, r, r->connection);
3719         }
3720     }
3721
3722     filters = conf->input_filters;
3723     if (filters) {
3724         while (*filters && (filter = ap_getword(r->pool, &filters, ';'))) {
3725             ap_add_input_filter(filter, NULL, r, r->connection);
3726         }
3727     }
3728 }
3729
3730 static apr_size_t num_request_notes = AP_NUM_STD_NOTES;
3731
3732 static apr_status_t reset_request_notes(void *dummy)
3733 {
3734     num_request_notes = AP_NUM_STD_NOTES;
3735     return APR_SUCCESS;
3736 }
3737
3738 AP_DECLARE(apr_size_t) ap_register_request_note(void)
3739 {
3740     apr_pool_cleanup_register(apr_global_hook_pool, NULL, reset_request_notes,
3741                               apr_pool_cleanup_null);
3742     return num_request_notes++;
3743 }
3744
3745 AP_DECLARE(void **) ap_get_request_note(request_rec *r, apr_size_t note_num)
3746 {
3747     core_request_config *req_cfg;
3748     if (note_num >= num_request_notes) {
3749         return NULL;
3750     }
3751     req_cfg = (core_request_config *)
3752         ap_get_module_config(r->request_config, &core_module);
3753     if (!req_cfg) {
3754         return NULL;
3755     }
3756     return &(req_cfg->notes[note_num]);
3757 }
3758
3759 static int core_create_req(request_rec *r)
3760 {
3761     /* Alloc the config struct and the array of request notes in
3762      * a single block for efficiency
3763      */
3764     core_request_config *req_cfg;
3765     req_cfg = apr_pcalloc(r->pool, sizeof(core_request_config) +
3766                           sizeof(void *) * num_request_notes);
3767     req_cfg->notes = (void **)((char *)req_cfg + sizeof(core_request_config));
3768     if (r->main) {
3769         core_request_config *main_req_cfg = (core_request_config *)
3770             ap_get_module_config(r->main->request_config, &core_module);
3771         req_cfg->bb = main_req_cfg->bb;
3772     }
3773     else {
3774         req_cfg->bb = apr_brigade_create(r->pool);
3775     }
3776     ap_set_module_config(r->request_config, &core_module, req_cfg);
3777
3778     ap_add_input_filter_handle(ap_net_time_filter_handle,
3779                                NULL, r, r->connection);
3780     
3781     /* Begin by presuming any module can make it's own path_info assumptions,
3782      * until some module interjects and changes the value.
3783      */
3784     r->used_path_info = 2;
3785     return OK;
3786 }
3787
3788 static int core_create_proxy_req(request_rec *r, request_rec *pr)
3789 {
3790     return core_create_req(pr);
3791 }
3792 static conn_rec *core_create_conn(apr_pool_t *ptrans, server_rec *server,
3793                                   apr_socket_t *csd, long id, void *sbh)
3794 {
3795     apr_status_t rv;
3796     conn_rec *c = (conn_rec *) apr_pcalloc(ptrans, sizeof(conn_rec));
3797
3798     c->sbh = sbh; 
3799     (void) ap_update_child_status(c->sbh, SERVER_BUSY_READ, (request_rec *) NULL);
3800
3801     /* Got a connection structure, so initialize what fields we can
3802      * (the rest are zeroed out by pcalloc).
3803      */
3804     c->conn_config=ap_create_conn_config(ptrans);
3805     c->notes = apr_table_make(ptrans, 5);
3806  
3807     c->pool = ptrans;
3808     if ((rv = apr_socket_addr_get(&c->local_addr, APR_LOCAL, csd))
3809         != APR_SUCCESS) {
3810         ap_log_error(APLOG_MARK, APLOG_INFO, rv, server,
3811                      "apr_socket_addr_get(APR_LOCAL)");
3812         apr_socket_close(csd);
3813         return NULL;
3814     }
3815     apr_sockaddr_ip_get(&c->local_ip, c->local_addr);
3816     if ((rv = apr_socket_addr_get(&c->remote_addr, APR_REMOTE, csd))
3817         != APR_SUCCESS) {
3818         ap_log_error(APLOG_MARK, APLOG_INFO, rv, server,
3819                      "apr_socket_addr_get(APR_REMOTE)");
3820         apr_socket_close(csd);
3821         return NULL;
3822     }
3823     apr_sockaddr_ip_get(&c->remote_ip, c->remote_addr);
3824     c->base_server = server;
3825  
3826     c->id = id;
3827     return c;
3828 }
3829 static int core_pre_connection(conn_rec *c, void *csd)
3830 {
3831     core_net_rec *net = apr_palloc(c->pool, sizeof(*net));
3832
3833 #ifdef AP_MPM_DISABLE_NAGLE_ACCEPTED_SOCK
3834     /* BillS says perhaps this should be moved to the MPMs. Some OSes
3835      * allow listening socket attributes to be inherited by the
3836      * accept sockets which means this call only needs to be made 
3837      * once on the listener
3838      */
3839     ap_sock_disable_nagle(csd);
3840 #endif
3841     net->c = c;
3842     net->in_ctx = NULL;
3843     net->out_ctx = NULL;
3844     net->client_socket = csd;
3845
3846     ap_set_module_config(net->c->conn_config, &core_module, csd);
3847     ap_add_input_filter("CORE_IN", net, NULL, net->c);
3848     ap_add_output_filter("CORE", net, NULL, net->c);
3849     return DONE;
3850 }
3851
3852 static void register_hooks(apr_pool_t *p)
3853 {
3854     /* create_connection and install_transport_filters are
3855      * hooks that should always be APR_HOOK_REALLY_LAST to give other 
3856      * modules the opportunity to install alternate network transports
3857      * and stop other functions from being run.
3858      */
3859     ap_hook_create_connection(core_create_conn, NULL, NULL, APR_HOOK_REALLY_LAST);
3860     ap_hook_pre_connection(core_pre_connection, NULL, 
3861                                       NULL, APR_HOOK_REALLY_LAST);
3862
3863     ap_hook_post_config(core_post_config,NULL,NULL,APR_HOOK_REALLY_FIRST);
3864     ap_hook_translate_name(ap_core_translate,NULL,NULL,APR_HOOK_REALLY_LAST);
3865     ap_hook_map_to_storage(core_map_to_storage,NULL,NULL,APR_HOOK_REALLY_LAST);
3866     ap_hook_open_logs(core_open_logs,NULL,NULL,APR_HOOK_MIDDLE);
3867     ap_hook_handler(default_handler,NULL,NULL,APR_HOOK_REALLY_LAST);
3868     /* FIXME: I suspect we can eliminate the need for these do_nothings - Ben */
3869     ap_hook_type_checker(do_nothing,NULL,NULL,APR_HOOK_REALLY_LAST);
3870     ap_hook_fixups(core_override_type,NULL,NULL,APR_HOOK_REALLY_FIRST);
3871     ap_hook_fixups(core_filters_type,NULL,NULL,APR_HOOK_MIDDLE);
3872     ap_hook_access_checker(do_nothing,NULL,NULL,APR_HOOK_REALLY_LAST);
3873     ap_hook_create_request(core_create_req, NULL, NULL, APR_HOOK_MIDDLE);
3874     APR_OPTIONAL_HOOK(proxy, create_req, core_create_proxy_req, NULL, NULL, 
3875                       APR_HOOK_MIDDLE);
3876     ap_hook_pre_mpm(ap_create_scoreboard, NULL, NULL, APR_HOOK_MIDDLE);
3877
3878     /* register the core's insert_filter hook and register core-provided
3879      * filters
3880      */
3881     ap_hook_insert_filter(core_insert_filter, NULL, NULL, APR_HOOK_MIDDLE);
3882
3883     ap_core_input_filter_handle =
3884         ap_register_input_filter("CORE_IN", core_input_filter,
3885                                  AP_FTYPE_NETWORK);
3886     ap_net_time_filter_handle =
3887         ap_register_input_filter("NET_TIME", net_time_filter,
3888                                  AP_FTYPE_CONTENT);
3889     ap_content_length_filter_handle =
3890         ap_register_output_filter("CONTENT_LENGTH", ap_content_length_filter, 
3891                                   AP_FTYPE_HTTP_HEADER);
3892     ap_core_output_filter_handle =
3893         ap_register_output_filter("CORE", core_output_filter,
3894                                   AP_FTYPE_NETWORK);
3895     ap_subreq_core_filter_handle =
3896         ap_register_output_filter("SUBREQ_CORE", ap_sub_req_output_filter, 
3897                                   AP_FTYPE_HTTP_HEADER);
3898     ap_old_write_func = ap_register_output_filter("OLD_WRITE", 
3899                                    ap_old_write_filter, AP_FTYPE_CONTENT - 10);
3900 }
3901
3902 AP_DECLARE_DATA module core_module = {
3903     STANDARD20_MODULE_STUFF,
3904     create_core_dir_config,     /* create per-directory config structure */
3905     merge_core_dir_configs,     /* merge per-directory config structures */
3906     create_core_server_config,  /* create per-server config structure */
3907     merge_core_server_configs,  /* merge per-server config structures */
3908     core_cmds,                  /* command apr_table_t */
3909     register_hooks              /* register hooks */
3910 };
3911
3912