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