]> granicus.if.org Git - apache/blob - server/core.c
First order simplification; Add IncludeOptional for introducing
[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 static const char *include_config (cmd_parms *cmd, void *dummy,
2570                                    const char *name)
2571 {
2572     ap_directive_t *conftree = NULL;
2573     const char *conffile, *error;
2574     unsigned *recursion;
2575     int optional = (int)cmd->cmd->cmd_data;
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                             "There appears to be a recursion.",
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_fnmatch_configs(cmd->server, conffile, &conftree, 
2603                                        cmd->pool, cmd->temp_pool, 
2604                                        optional);
2605     if (error) {
2606         *recursion = 0;
2607         return error;
2608     }
2609
2610     *(ap_directive_t **)dummy = conftree;
2611
2612     /* recursion level done */
2613     if (*recursion) {
2614         --*recursion;
2615     }
2616
2617     return NULL;
2618 }
2619
2620 static const char *set_loglevel(cmd_parms *cmd, void *dummy, const char *arg)
2621 {
2622     char *str;
2623
2624     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
2625     if (err != NULL) {
2626         return err;
2627     }
2628
2629     if ((str = ap_getword_conf(cmd->pool, &arg))) {
2630         err = ap_parse_log_level(str, &cmd->server->loglevel);
2631         if (err != NULL)
2632             return apr_psprintf(cmd->pool, "LogLevel: %s", err);
2633     }
2634     else {
2635         return "LogLevel requires level keyword";
2636     }
2637
2638     return NULL;
2639 }
2640
2641 AP_DECLARE(const char *) ap_psignature(const char *prefix, request_rec *r)
2642 {
2643     char sport[20];
2644     core_dir_config *conf;
2645
2646     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
2647                                                    &core_module);
2648     if ((conf->server_signature == srv_sig_off)
2649             || (conf->server_signature == srv_sig_unset)) {
2650         return "";
2651     }
2652
2653     apr_snprintf(sport, sizeof sport, "%u", (unsigned) ap_get_server_port(r));
2654
2655     if (conf->server_signature == srv_sig_withmail) {
2656         return apr_pstrcat(r->pool, prefix, "<address>",
2657                            ap_get_server_banner(),
2658                            " Server at <a href=\"",
2659                            ap_is_url(r->server->server_admin) ? "" : "mailto:",
2660                            ap_escape_html(r->pool, r->server->server_admin),
2661                            "\">",
2662                            ap_escape_html(r->pool, ap_get_server_name(r)),
2663                            "</a> Port ", sport,
2664                            "</address>\n", NULL);
2665     }
2666
2667     return apr_pstrcat(r->pool, prefix, "<address>", ap_get_server_banner(),
2668                        " Server at ",
2669                        ap_escape_html(r->pool, ap_get_server_name(r)),
2670                        " Port ", sport,
2671                        "</address>\n", NULL);
2672 }
2673
2674 /*
2675  * Handle a request to include the server's OS platform in the Server
2676  * response header field (the ServerTokens directive).  Unfortunately
2677  * this requires a new global in order to communicate the setting back to
2678  * http_main so it can insert the information in the right place in the
2679  * string.
2680  */
2681
2682 static char *server_banner = NULL;
2683 static int banner_locked = 0;
2684 static const char *server_description = NULL;
2685
2686 enum server_token_type {
2687     SrvTk_MAJOR,         /* eg: Apache/2 */
2688     SrvTk_MINOR,         /* eg. Apache/2.0 */
2689     SrvTk_MINIMAL,       /* eg: Apache/2.0.41 */
2690     SrvTk_OS,            /* eg: Apache/2.0.41 (UNIX) */
2691     SrvTk_FULL,          /* eg: Apache/2.0.41 (UNIX) PHP/4.2.2 FooBar/1.2b */
2692     SrvTk_PRODUCT_ONLY  /* eg: Apache */
2693 };
2694 static enum server_token_type ap_server_tokens = SrvTk_FULL;
2695
2696 static apr_status_t reset_banner(void *dummy)
2697 {
2698     banner_locked = 0;
2699     ap_server_tokens = SrvTk_FULL;
2700     server_banner = NULL;
2701     server_description = NULL;
2702     return APR_SUCCESS;
2703 }
2704
2705 AP_DECLARE(void) ap_get_server_revision(ap_version_t *version)
2706 {
2707     version->major = AP_SERVER_MAJORVERSION_NUMBER;
2708     version->minor = AP_SERVER_MINORVERSION_NUMBER;
2709     version->patch = AP_SERVER_PATCHLEVEL_NUMBER;
2710     version->add_string = AP_SERVER_ADD_STRING;
2711 }
2712
2713 AP_DECLARE(const char *) ap_get_server_description(void)
2714 {
2715     return server_description ? server_description :
2716         AP_SERVER_BASEVERSION " (" PLATFORM ")";
2717 }
2718
2719 AP_DECLARE(const char *) ap_get_server_banner(void)
2720 {
2721     return server_banner ? server_banner : AP_SERVER_BASEVERSION;
2722 }
2723
2724 AP_DECLARE(void) ap_add_version_component(apr_pool_t *pconf, const char *component)
2725 {
2726     if (! banner_locked) {
2727         /*
2728          * If the version string is null, register our cleanup to reset the
2729          * pointer on pool destruction. We also know that, if NULL,
2730          * we are adding the original SERVER_BASEVERSION string.
2731          */
2732         if (server_banner == NULL) {
2733             apr_pool_cleanup_register(pconf, NULL, reset_banner,
2734                                       apr_pool_cleanup_null);
2735             server_banner = apr_pstrdup(pconf, component);
2736         }
2737         else {
2738             /*
2739              * Tack the given component identifier to the end of
2740              * the existing string.
2741              */
2742             server_banner = apr_pstrcat(pconf, server_banner, " ",
2743                                         component, NULL);
2744         }
2745     }
2746     server_description = apr_pstrcat(pconf, server_description, " ",
2747                                      component, NULL);
2748 }
2749
2750 /*
2751  * This routine adds the real server base identity to the banner string,
2752  * and then locks out changes until the next reconfig.
2753  */
2754 static void set_banner(apr_pool_t *pconf)
2755 {
2756     if (ap_server_tokens == SrvTk_PRODUCT_ONLY) {
2757         ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT);
2758     }
2759     else if (ap_server_tokens == SrvTk_MINIMAL) {
2760         ap_add_version_component(pconf, AP_SERVER_BASEVERSION);
2761     }
2762     else if (ap_server_tokens == SrvTk_MINOR) {
2763         ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT "/" AP_SERVER_MINORREVISION);
2764     }
2765     else if (ap_server_tokens == SrvTk_MAJOR) {
2766         ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT "/" AP_SERVER_MAJORVERSION);
2767     }
2768     else {
2769         ap_add_version_component(pconf, AP_SERVER_BASEVERSION " (" PLATFORM ")");
2770     }
2771
2772     /*
2773      * Lock the server_banner string if we're not displaying
2774      * the full set of tokens
2775      */
2776     if (ap_server_tokens != SrvTk_FULL) {
2777         banner_locked++;
2778     }
2779     server_description = AP_SERVER_BASEVERSION " (" PLATFORM ")";
2780 }
2781
2782 static const char *set_serv_tokens(cmd_parms *cmd, void *dummy,
2783                                    const char *arg1, const char *arg2)
2784 {
2785     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2786
2787     if (err != NULL) {
2788         return err;
2789     }
2790
2791     if (!strcasecmp(arg1, "OS")) {
2792         ap_server_tokens = SrvTk_OS;
2793     }
2794     else if (!strcasecmp(arg1, "Min") || !strcasecmp(arg1, "Minimal")) {
2795         ap_server_tokens = SrvTk_MINIMAL;
2796     }
2797     else if (!strcasecmp(arg1, "Major")) {
2798         ap_server_tokens = SrvTk_MAJOR;
2799     }
2800     else if (!strcasecmp(arg1, "Minor") ) {
2801         ap_server_tokens = SrvTk_MINOR;
2802     }
2803     else if (!strcasecmp(arg1, "Prod") || !strcasecmp(arg1, "ProductOnly")) {
2804         ap_server_tokens = SrvTk_PRODUCT_ONLY;
2805     }
2806     else {
2807         ap_server_tokens = SrvTk_FULL;
2808     }
2809
2810     return NULL;
2811 }
2812
2813 static const char *set_limit_req_line(cmd_parms *cmd, void *dummy,
2814                                       const char *arg)
2815 {
2816     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
2817     int lim;
2818
2819     if (err != NULL) {
2820         return err;
2821     }
2822
2823     lim = atoi(arg);
2824     if (lim < 0) {
2825         return apr_pstrcat(cmd->temp_pool, "LimitRequestLine \"", arg,
2826                            "\" must be a non-negative integer", NULL);
2827     }
2828
2829     cmd->server->limit_req_line = lim;
2830     return NULL;
2831 }
2832
2833 static const char *set_limit_req_fieldsize(cmd_parms *cmd, void *dummy,
2834                                            const char *arg)
2835 {
2836     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
2837     int lim;
2838
2839     if (err != NULL) {
2840         return err;
2841     }
2842
2843     lim = atoi(arg);
2844     if (lim < 0) {
2845         return apr_pstrcat(cmd->temp_pool, "LimitRequestFieldsize \"", arg,
2846                           "\" must be a non-negative integer",
2847                           NULL);
2848     }
2849
2850     cmd->server->limit_req_fieldsize = lim;
2851     return NULL;
2852 }
2853
2854 static const char *set_limit_req_fields(cmd_parms *cmd, void *dummy,
2855                                         const char *arg)
2856 {
2857     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
2858     int lim;
2859
2860     if (err != NULL) {
2861         return err;
2862     }
2863
2864     lim = atoi(arg);
2865     if (lim < 0) {
2866         return apr_pstrcat(cmd->temp_pool, "LimitRequestFields \"", arg,
2867                            "\" must be a non-negative integer (0 = no limit)",
2868                            NULL);
2869     }
2870
2871     cmd->server->limit_req_fields = lim;
2872     return NULL;
2873 }
2874
2875 static const char *set_limit_req_body(cmd_parms *cmd, void *conf_,
2876                                       const char *arg)
2877 {
2878     core_dir_config *conf = conf_;
2879     char *errp;
2880
2881     if (APR_SUCCESS != apr_strtoff(&conf->limit_req_body, arg, &errp, 10)) {
2882         return "LimitRequestBody argument is not parsable.";
2883     }
2884     if (*errp || conf->limit_req_body < 0) {
2885         return "LimitRequestBody requires a non-negative integer.";
2886     }
2887
2888     return NULL;
2889 }
2890
2891 static const char *set_limit_xml_req_body(cmd_parms *cmd, void *conf_,
2892                                           const char *arg)
2893 {
2894     core_dir_config *conf = conf_;
2895
2896     conf->limit_xml_body = atol(arg);
2897     if (conf->limit_xml_body < 0)
2898         return "LimitXMLRequestBody requires a non-negative integer.";
2899
2900     return NULL;
2901 }
2902
2903 AP_DECLARE(size_t) ap_get_limit_xml_body(const request_rec *r)
2904 {
2905     core_dir_config *conf;
2906
2907     conf = ap_get_module_config(r->per_dir_config, &core_module);
2908     if (conf->limit_xml_body == AP_LIMIT_UNSET)
2909         return AP_DEFAULT_LIMIT_XML_BODY;
2910
2911     return (size_t)conf->limit_xml_body;
2912 }
2913
2914 #if !defined (RLIMIT_CPU) || !(defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)) || !defined (RLIMIT_NPROC)
2915 static const char *no_set_limit(cmd_parms *cmd, void *conf_,
2916                                 const char *arg, const char *arg2)
2917 {
2918     ap_log_error(APLOG_MARK, APLOG_ERR, 0, cmd->server,
2919                 "%s not supported on this platform", cmd->cmd->name);
2920
2921     return NULL;
2922 }
2923 #endif
2924
2925 #ifdef RLIMIT_CPU
2926 static const char *set_limit_cpu(cmd_parms *cmd, void *conf_,
2927                                  const char *arg, const char *arg2)
2928 {
2929     core_dir_config *conf = conf_;
2930
2931     ap_unixd_set_rlimit(cmd, &conf->limit_cpu, arg, arg2, RLIMIT_CPU);
2932     return NULL;
2933 }
2934 #endif
2935
2936 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)
2937 static const char *set_limit_mem(cmd_parms *cmd, void *conf_,
2938                                  const char *arg, const char * arg2)
2939 {
2940     core_dir_config *conf = conf_;
2941
2942 #if defined(RLIMIT_AS)
2943     ap_unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2 ,RLIMIT_AS);
2944 #elif defined(RLIMIT_DATA)
2945     ap_unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_DATA);
2946 #elif defined(RLIMIT_VMEM)
2947     ap_unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_VMEM);
2948 #endif
2949
2950     return NULL;
2951 }
2952 #endif
2953
2954 #ifdef RLIMIT_NPROC
2955 static const char *set_limit_nproc(cmd_parms *cmd, void *conf_,
2956                                    const char *arg, const char * arg2)
2957 {
2958     core_dir_config *conf = conf_;
2959
2960     ap_unixd_set_rlimit(cmd, &conf->limit_nproc, arg, arg2, RLIMIT_NPROC);
2961     return NULL;
2962 }
2963 #endif
2964
2965 static const char *set_recursion_limit(cmd_parms *cmd, void *dummy,
2966                                        const char *arg1, const char *arg2)
2967 {
2968     core_server_config *conf = ap_get_module_config(cmd->server->module_config,
2969                                                     &core_module);
2970     int limit = atoi(arg1);
2971
2972     if (limit <= 0) {
2973         return "The recursion limit must be greater than zero.";
2974     }
2975     if (limit < 4) {
2976         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
2977                      "Limiting internal redirects to very low numbers may "
2978                      "cause normal requests to fail.");
2979     }
2980
2981     conf->redirect_limit = limit;
2982
2983     if (arg2) {
2984         limit = atoi(arg2);
2985
2986         if (limit <= 0) {
2987             return "The recursion limit must be greater than zero.";
2988         }
2989         if (limit < 4) {
2990             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
2991                          "Limiting the subrequest depth to a very low level may"
2992                          " cause normal requests to fail.");
2993         }
2994     }
2995
2996     conf->subreq_limit = limit;
2997
2998     return NULL;
2999 }
3000
3001 static void log_backtrace(const request_rec *r)
3002 {
3003     const request_rec *top = r;
3004
3005     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
3006                   "r->uri = %s", r->uri ? r->uri : "(unexpectedly NULL)");
3007
3008     while (top && (top->prev || top->main)) {
3009         if (top->prev) {
3010             top = top->prev;
3011             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
3012                           "redirected from r->uri = %s",
3013                           top->uri ? top->uri : "(unexpectedly NULL)");
3014         }
3015
3016         if (!top->prev && top->main) {
3017             top = top->main;
3018             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
3019                           "subrequested from r->uri = %s",
3020                           top->uri ? top->uri : "(unexpectedly NULL)");
3021         }
3022     }
3023 }
3024
3025 /*
3026  * check whether redirect limit is reached
3027  */
3028 AP_DECLARE(int) ap_is_recursion_limit_exceeded(const request_rec *r)
3029 {
3030     core_server_config *conf = ap_get_module_config(r->server->module_config,
3031                                                     &core_module);
3032     const request_rec *top = r;
3033     int redirects = 0, subreqs = 0;
3034     int rlimit = conf->redirect_limit
3035                  ? conf->redirect_limit
3036                  : AP_DEFAULT_MAX_INTERNAL_REDIRECTS;
3037     int slimit = conf->subreq_limit
3038                  ? conf->subreq_limit
3039                  : AP_DEFAULT_MAX_SUBREQ_DEPTH;
3040
3041
3042     while (top->prev || top->main) {
3043         if (top->prev) {
3044             if (++redirects >= rlimit) {
3045                 /* uuh, too much. */
3046                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3047                               "Request exceeded the limit of %d internal "
3048                               "redirects due to probable configuration error. "
3049                               "Use 'LimitInternalRecursion' to increase the "
3050                               "limit if necessary. Use 'LogLevel debug' to get "
3051                               "a backtrace.", rlimit);
3052
3053                 /* post backtrace */
3054                 log_backtrace(r);
3055
3056                 /* return failure */
3057                 return 1;
3058             }
3059
3060             top = top->prev;
3061         }
3062
3063         if (!top->prev && top->main) {
3064             if (++subreqs >= slimit) {
3065                 /* uuh, too much. */
3066                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3067                               "Request exceeded the limit of %d subrequest "
3068                               "nesting levels due to probable configuration "
3069                               "error. Use 'LimitInternalRecursion' to increase "
3070                               "the limit if necessary. Use 'LogLevel debug' to "
3071                               "get a backtrace.", slimit);
3072
3073                 /* post backtrace */
3074                 log_backtrace(r);
3075
3076                 /* return failure */
3077                 return 1;
3078             }
3079
3080             top = top->main;
3081         }
3082     }
3083
3084     /* recursion state: ok */
3085     return 0;
3086 }
3087
3088 static const char *add_ct_output_filters(cmd_parms *cmd, void *conf_,
3089                                          const char *arg, const char *arg2)
3090 {
3091     core_dir_config *conf = conf_;
3092     ap_filter_rec_t *old, *new = NULL;
3093     const char *filter_name;
3094
3095     if (!conf->ct_output_filters) {
3096         conf->ct_output_filters = apr_hash_make(cmd->pool);
3097         old = NULL;
3098     }
3099     else {
3100         old = (ap_filter_rec_t*) apr_hash_get(conf->ct_output_filters, arg2,
3101                                               APR_HASH_KEY_STRING);
3102         /* find last entry */
3103         if (old) {
3104             while (old->next) {
3105                 old = old->next;
3106             }
3107         }
3108     }
3109
3110     while (*arg &&
3111            (filter_name = ap_getword(cmd->pool, &arg, ';')) &&
3112            strcmp(filter_name, "")) {
3113         new = apr_pcalloc(cmd->pool, sizeof(ap_filter_rec_t));
3114         new->name = filter_name;
3115
3116         /* We found something, so let's append it.  */
3117         if (old) {
3118             old->next = new;
3119         }
3120         else {
3121             apr_hash_set(conf->ct_output_filters, arg2,
3122                          APR_HASH_KEY_STRING, new);
3123         }
3124         old = new;
3125     }
3126
3127     if (!new) {
3128         return "invalid filter name";
3129     }
3130
3131     return NULL;
3132 }
3133 /*
3134  * Insert filters requested by the AddOutputFilterByType
3135  * configuration directive. We cannot add filters based
3136  * on content-type until after the handler has started
3137  * to run. Only then do we reliably know the content-type.
3138  */
3139 void ap_add_output_filters_by_type(request_rec *r)
3140 {
3141     core_dir_config *conf;
3142     const char *ctype;
3143
3144     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
3145                                                    &core_module);
3146
3147     /* We can't do anything with no content-type or if we don't have a
3148      * filter configured.
3149      */
3150     if (!r->content_type || !conf->ct_output_filters) {
3151         return;
3152     }
3153
3154     /* remove c-t decoration */
3155     ctype = ap_field_noparam(r->pool, r->content_type);
3156     if (ctype) {
3157         ap_filter_rec_t *ct_filter;
3158         ct_filter = apr_hash_get(conf->ct_output_filters, ctype,
3159                                  APR_HASH_KEY_STRING);
3160         while (ct_filter) {
3161             ap_add_output_filter(ct_filter->name, NULL, r, r->connection);
3162             ct_filter = ct_filter->next;
3163         }
3164     }
3165
3166     return;
3167 }
3168
3169 static const char *set_trace_enable(cmd_parms *cmd, void *dummy,
3170                                     const char *arg1)
3171 {
3172     core_server_config *conf = ap_get_module_config(cmd->server->module_config,
3173                                                     &core_module);
3174
3175     if (strcasecmp(arg1, "on") == 0) {
3176         conf->trace_enable = AP_TRACE_ENABLE;
3177     }
3178     else if (strcasecmp(arg1, "off") == 0) {
3179         conf->trace_enable = AP_TRACE_DISABLE;
3180     }
3181     else if (strcasecmp(arg1, "extended") == 0) {
3182         conf->trace_enable = AP_TRACE_EXTENDED;
3183     }
3184     else {
3185         return "TraceEnable must be one of 'on', 'off', or 'extended'";
3186     }
3187
3188     return NULL;
3189 }
3190
3191 /* Note --- ErrorDocument will now work from .htaccess files.
3192  * The AllowOverride of Fileinfo allows webmasters to turn it off
3193  */
3194
3195 static const command_rec core_cmds[] = {
3196
3197 /* Old access config file commands */
3198
3199 AP_INIT_RAW_ARGS("<Directory", dirsection, NULL, RSRC_CONF,
3200   "Container for directives affecting resources located in the specified "
3201   "directories"),
3202 AP_INIT_RAW_ARGS("<Location", urlsection, NULL, RSRC_CONF,
3203   "Container for directives affecting resources accessed through the "
3204   "specified URL paths"),
3205 AP_INIT_RAW_ARGS("<VirtualHost", virtualhost_section, NULL, RSRC_CONF,
3206   "Container to map directives to a particular virtual host, takes one or "
3207   "more host addresses"),
3208 AP_INIT_RAW_ARGS("<Files", filesection, NULL, OR_ALL,
3209   "Container for directives affecting files matching specified patterns"),
3210 AP_INIT_RAW_ARGS("<Limit", ap_limit_section, NULL, OR_LIMIT | OR_AUTHCFG,
3211   "Container for authentication directives when accessed using specified HTTP "
3212   "methods"),
3213 AP_INIT_RAW_ARGS("<LimitExcept", ap_limit_section, (void*)1,
3214                  OR_LIMIT | OR_AUTHCFG,
3215   "Container for authentication directives to be applied when any HTTP "
3216   "method other than those specified is used to access the resource"),
3217 AP_INIT_TAKE1("<IfModule", start_ifmod, NULL, EXEC_ON_READ | OR_ALL,
3218   "Container for directives based on existance of specified modules"),
3219 AP_INIT_TAKE1("<IfDefine", start_ifdefine, NULL, EXEC_ON_READ | OR_ALL,
3220   "Container for directives based on existance of command line defines"),
3221 AP_INIT_RAW_ARGS("<DirectoryMatch", dirsection, (void*)1, RSRC_CONF,
3222   "Container for directives affecting resources located in the "
3223   "specified directories"),
3224 AP_INIT_RAW_ARGS("<LocationMatch", urlsection, (void*)1, RSRC_CONF,
3225   "Container for directives affecting resources accessed through the "
3226   "specified URL paths"),
3227 AP_INIT_RAW_ARGS("<FilesMatch", filesection, (void*)1, OR_ALL,
3228   "Container for directives affecting files matching specified patterns"),
3229 #ifdef GPROF
3230 AP_INIT_TAKE1("GprofDir", set_gprof_dir, NULL, RSRC_CONF,
3231   "Directory to plop gmon.out files"),
3232 #endif
3233 AP_INIT_TAKE1("AddDefaultCharset", set_add_default_charset, NULL, OR_FILEINFO,
3234   "The name of the default charset to add to any Content-Type without one or 'Off' to disable"),
3235 AP_INIT_TAKE1("AcceptPathInfo", set_accept_path_info, NULL, OR_FILEINFO,
3236   "Set to on or off for PATH_INFO to be accepted by handlers, or default for the per-handler preference"),
3237 AP_INIT_TAKE1("Define", set_define, NULL, RSRC_CONF,
3238               "Define the existance of a variable.  Same as passing -D to the command line."),
3239 AP_INIT_TAKE1("UnDefine", unset_define, NULL, RSRC_CONF,
3240               "Undefine the existance of a variable. Undo a Define."),
3241 AP_INIT_RAW_ARGS("<If", ifsection, NULL, OR_ALL,
3242   "Container for directives to be conditionally applied"),
3243
3244 /* Old resource config file commands */
3245
3246 AP_INIT_RAW_ARGS("AccessFileName", set_access_name, NULL, RSRC_CONF,
3247   "Name(s) of per-directory config files (default: .htaccess)"),
3248 AP_INIT_TAKE1("DocumentRoot", set_document_root, NULL, RSRC_CONF,
3249   "Root directory of the document tree"),
3250 AP_INIT_TAKE2("ErrorDocument", set_error_document, NULL, OR_FILEINFO,
3251   "Change responses for HTTP errors"),
3252 AP_INIT_RAW_ARGS("AllowOverride", set_override, NULL, ACCESS_CONF,
3253   "Controls what groups of directives can be configured by per-directory "
3254   "config files"),
3255 AP_INIT_RAW_ARGS("Options", set_options, NULL, OR_OPTIONS,
3256   "Set a number of attributes for a given directory"),
3257 AP_INIT_TAKE1("DefaultType", set_default_type, NULL, OR_FILEINFO,
3258   "the default media type for otherwise untyped files (DEPRECATED)"),
3259 AP_INIT_RAW_ARGS("FileETag", set_etag_bits, NULL, OR_FILEINFO,
3260   "Specify components used to construct a file's ETag"),
3261 AP_INIT_TAKE1("EnableMMAP", set_enable_mmap, NULL, OR_FILEINFO,
3262   "Controls whether memory-mapping may be used to read files"),
3263 AP_INIT_TAKE1("EnableSendfile", set_enable_sendfile, NULL, OR_FILEINFO,
3264   "Controls whether sendfile may be used to transmit files"),
3265
3266 /* Old server config file commands */
3267
3268 AP_INIT_TAKE1("Protocol", set_protocol, NULL, RSRC_CONF,
3269   "Set the Protocol for httpd to use."),
3270 AP_INIT_TAKE2("AcceptFilter", set_accf_map, NULL, RSRC_CONF,
3271   "Set the Accept Filter to use for a protocol"),
3272 AP_INIT_TAKE1("Port", ap_set_deprecated, NULL, RSRC_CONF,
3273   "Port was replaced with Listen in Apache 2.0"),
3274 AP_INIT_TAKE1("HostnameLookups", set_hostname_lookups, NULL,
3275   ACCESS_CONF|RSRC_CONF,
3276   "\"on\" to enable, \"off\" to disable reverse DNS lookups, or \"double\" to "
3277   "enable double-reverse DNS lookups"),
3278 AP_INIT_TAKE1("ServerAdmin", set_server_string_slot,
3279   (void *)APR_OFFSETOF(server_rec, server_admin), RSRC_CONF,
3280   "The email address of the server administrator"),
3281 AP_INIT_TAKE1("ServerName", server_hostname_port, NULL, RSRC_CONF,
3282   "The hostname and port of the server"),
3283 AP_INIT_TAKE1("ServerSignature", set_signature_flag, NULL, OR_ALL,
3284   "En-/disable server signature (on|off|email)"),
3285 AP_INIT_TAKE1("ServerRoot", set_server_root, NULL, RSRC_CONF | EXEC_ON_READ,
3286   "Common directory of server-related files (logs, confs, etc.)"),
3287 AP_INIT_TAKE1("ErrorLog", set_server_string_slot,
3288   (void *)APR_OFFSETOF(server_rec, error_fname), RSRC_CONF,
3289   "The filename of the error log"),
3290 AP_INIT_RAW_ARGS("ServerAlias", set_server_alias, NULL, RSRC_CONF,
3291   "A name or names alternately used to access the server"),
3292 AP_INIT_TAKE1("ServerPath", set_serverpath, NULL, RSRC_CONF,
3293   "The pathname the server can be reached at"),
3294 AP_INIT_TAKE1("Timeout", set_timeout, NULL, RSRC_CONF,
3295   "Timeout duration (sec)"),
3296 AP_INIT_FLAG("ContentDigest", set_content_md5, NULL, OR_OPTIONS,
3297   "whether or not to send a Content-MD5 header with each request"),
3298 AP_INIT_TAKE1("UseCanonicalName", set_use_canonical_name, NULL,
3299   RSRC_CONF|ACCESS_CONF,
3300   "How to work out the ServerName : Port when constructing URLs"),
3301 AP_INIT_TAKE1("UseCanonicalPhysicalPort", set_use_canonical_phys_port, NULL,
3302   RSRC_CONF|ACCESS_CONF,
3303   "Whether to use the physical Port when constructing URLs"),
3304 /* TODO: RlimitFoo should all be part of mod_cgi, not in the core */
3305 /* TODO: ListenBacklog in MPM */
3306 AP_INIT_TAKE1("Include", include_config, NULL,
3307   (RSRC_CONF | ACCESS_CONF | EXEC_ON_READ),
3308   "Name(s) of the config file(s) to be included; fails if the wildcard does "
3309   "not match at least one file"),
3310 AP_INIT_TAKE1("IncludeOptional", include_config, (void*)1,
3311   (RSRC_CONF | ACCESS_CONF | EXEC_ON_READ),
3312   "Name or pattern of the config file(s) to be included; ignored if the file "
3313   "does not exist or the pattern does not match any files"),
3314 AP_INIT_TAKE1("LogLevel", set_loglevel, NULL, RSRC_CONF,
3315   "Level of verbosity in error logging"),
3316 AP_INIT_TAKE1("NameVirtualHost", ap_set_name_virtual_host, NULL, RSRC_CONF,
3317   "A numeric IP address:port, or the name of a host"),
3318 AP_INIT_TAKE12("ServerTokens", set_serv_tokens, NULL, RSRC_CONF,
3319   "Determine tokens displayed in the Server: header - Min(imal), "
3320   "Major, Minor, Prod, OS or Full"),
3321 AP_INIT_TAKE1("LimitRequestLine", set_limit_req_line, NULL, RSRC_CONF,
3322   "Limit on maximum size of an HTTP request line"),
3323 AP_INIT_TAKE1("LimitRequestFieldsize", set_limit_req_fieldsize, NULL,
3324   RSRC_CONF,
3325   "Limit on maximum size of an HTTP request header field"),
3326 AP_INIT_TAKE1("LimitRequestFields", set_limit_req_fields, NULL, RSRC_CONF,
3327   "Limit (0 = unlimited) on max number of header fields in a request message"),
3328 AP_INIT_TAKE1("LimitRequestBody", set_limit_req_body,
3329   (void*)APR_OFFSETOF(core_dir_config, limit_req_body), OR_ALL,
3330   "Limit (in bytes) on maximum size of request message body"),
3331 AP_INIT_TAKE1("LimitXMLRequestBody", set_limit_xml_req_body, NULL, OR_ALL,
3332               "Limit (in bytes) on maximum size of an XML-based request "
3333               "body"),
3334 AP_INIT_RAW_ARGS("Mutex", ap_set_mutex, NULL, RSRC_CONF,
3335                  "mutex (or \"default\") and mechanism"),
3336
3337 /* System Resource Controls */
3338 #ifdef RLIMIT_CPU
3339 AP_INIT_TAKE12("RLimitCPU", set_limit_cpu,
3340   (void*)APR_OFFSETOF(core_dir_config, limit_cpu),
3341   OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
3342 #else
3343 AP_INIT_TAKE12("RLimitCPU", no_set_limit, NULL,
3344   OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
3345 #endif
3346 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined (RLIMIT_AS)
3347 AP_INIT_TAKE12("RLimitMEM", set_limit_mem,
3348   (void*)APR_OFFSETOF(core_dir_config, limit_mem),
3349   OR_ALL, "Soft/hard limits for max memory usage per process"),
3350 #else
3351 AP_INIT_TAKE12("RLimitMEM", no_set_limit, NULL,
3352   OR_ALL, "Soft/hard limits for max memory usage per process"),
3353 #endif
3354 #ifdef RLIMIT_NPROC
3355 AP_INIT_TAKE12("RLimitNPROC", set_limit_nproc,
3356   (void*)APR_OFFSETOF(core_dir_config, limit_nproc),
3357   OR_ALL, "soft/hard limits for max number of processes per uid"),
3358 #else
3359 AP_INIT_TAKE12("RLimitNPROC", no_set_limit, NULL,
3360    OR_ALL, "soft/hard limits for max number of processes per uid"),
3361 #endif
3362
3363 /* internal recursion stopper */
3364 AP_INIT_TAKE12("LimitInternalRecursion", set_recursion_limit, NULL, RSRC_CONF,
3365               "maximum recursion depth of internal redirects and subrequests"),
3366
3367 AP_INIT_TAKE1("ForceType", ap_set_string_slot_lower,
3368        (void *)APR_OFFSETOF(core_dir_config, mime_type), OR_FILEINFO,
3369      "a mime type that overrides other configured type"),
3370 AP_INIT_TAKE1("SetHandler", ap_set_string_slot_lower,
3371        (void *)APR_OFFSETOF(core_dir_config, handler), OR_FILEINFO,
3372    "a handler name that overrides any other configured handler"),
3373 AP_INIT_TAKE1("SetOutputFilter", ap_set_string_slot,
3374        (void *)APR_OFFSETOF(core_dir_config, output_filters), OR_FILEINFO,
3375    "filter (or ; delimited list of filters) to be run on the request content"),
3376 AP_INIT_TAKE1("SetInputFilter", ap_set_string_slot,
3377        (void *)APR_OFFSETOF(core_dir_config, input_filters), OR_FILEINFO,
3378    "filter (or ; delimited list of filters) to be run on the request body"),
3379 AP_INIT_ITERATE2("AddOutputFilterByType", add_ct_output_filters,
3380        (void *)APR_OFFSETOF(core_dir_config, ct_output_filters), OR_FILEINFO,
3381      "output filter name followed by one or more content-types"),
3382 AP_INIT_FLAG("AllowEncodedSlashes", set_allow2f, NULL, RSRC_CONF,
3383              "Allow URLs containing '/' encoded as '%2F'"),
3384
3385 /* scoreboard.c directives */
3386 AP_INIT_TAKE1("ScoreboardFile", ap_set_scoreboard, NULL, RSRC_CONF,
3387               "A file for Apache to maintain runtime process management information"),
3388 AP_INIT_FLAG("ExtendedStatus", ap_set_extended_status, NULL, RSRC_CONF,
3389              "\"On\" to track extended status information, \"Off\" to disable"),
3390 AP_INIT_FLAG("SeeRequestTail", ap_set_reqtail, NULL, RSRC_CONF,
3391              "For extended status, \"On\" to see the last 63 chars of "
3392              "the request line, \"Off\" (default) to see the first 63"),
3393
3394 /*
3395  * These are default configuration directives that mpms can/should
3396  * pay attention to.
3397  * XXX These are not for all platforms, and even some Unix MPMs might not want
3398  * some directives.
3399  */
3400 AP_INIT_TAKE1("PidFile",  ap_mpm_set_pidfile, NULL, RSRC_CONF,
3401               "A file for logging the server process ID"),
3402 AP_INIT_TAKE1("MaxRequestsPerChild", ap_mpm_set_max_requests, NULL, RSRC_CONF,
3403               "Maximum number of requests a particular child serves before dying."),
3404 AP_INIT_TAKE1("CoreDumpDirectory", ap_mpm_set_coredumpdir, NULL, RSRC_CONF,
3405               "The location of the directory Apache changes to before dumping core"),
3406 AP_INIT_TAKE1("MaxMemFree", ap_mpm_set_max_mem_free, NULL, RSRC_CONF,
3407               "Maximum number of 1k blocks a particular childs allocator may hold."),
3408 AP_INIT_TAKE1("ThreadStackSize", ap_mpm_set_thread_stacksize, NULL, RSRC_CONF,
3409               "Size in bytes of stack used by threads handling client connections"),
3410 #if AP_ENABLE_EXCEPTION_HOOK
3411 AP_INIT_TAKE1("EnableExceptionHook", ap_mpm_set_exception_hook, NULL, RSRC_CONF,
3412               "Controls whether exception hook may be called after a crash"),
3413 #endif
3414 AP_INIT_TAKE1("TraceEnable", set_trace_enable, NULL, RSRC_CONF,
3415               "'on' (default), 'off' or 'extended' to trace request body content"),
3416 { NULL }
3417 };
3418
3419 /*****************************************************************
3420  *
3421  * Core handlers for various phases of server operation...
3422  */
3423
3424 AP_DECLARE_NONSTD(int) ap_core_translate(request_rec *r)
3425 {
3426     void *sconf = r->server->module_config;
3427     core_server_config *conf = ap_get_module_config(sconf, &core_module);
3428     apr_status_t rv;
3429
3430     /* XXX this seems too specific, this should probably become
3431      * some general-case test
3432      */
3433     if (r->proxyreq) {
3434         return HTTP_FORBIDDEN;
3435     }
3436     if (!r->uri || ((r->uri[0] != '/') && strcmp(r->uri, "*"))) {
3437         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3438                      "Invalid URI in request %s", r->the_request);
3439         return HTTP_BAD_REQUEST;
3440     }
3441
3442     if (r->server->path
3443         && !strncmp(r->uri, r->server->path, r->server->pathlen)
3444         && (r->server->path[r->server->pathlen - 1] == '/'
3445             || r->uri[r->server->pathlen] == '/'
3446             || r->uri[r->server->pathlen] == '\0'))
3447     {
3448         /* skip all leading /'s (e.g. http://localhost///foo)
3449          * so we are looking at only the relative path.
3450          */
3451         char *path = r->uri + r->server->pathlen;
3452         while (*path == '/') {
3453             ++path;
3454         }
3455         if ((rv = apr_filepath_merge(&r->filename, conf->ap_document_root, path,
3456                                      APR_FILEPATH_TRUENAME
3457                                    | APR_FILEPATH_SECUREROOT, r->pool))
3458                     != APR_SUCCESS) {
3459             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
3460                          "Cannot map %s to file", r->the_request);
3461             return HTTP_FORBIDDEN;
3462         }
3463         r->canonical_filename = r->filename;
3464     }
3465     else {
3466         /*
3467          * Make sure that we do not mess up the translation by adding two
3468          * /'s in a row.  This happens under windows when the document
3469          * root ends with a /
3470          */
3471         /* skip all leading /'s (e.g. http://localhost///foo)
3472          * so we are looking at only the relative path.
3473          */
3474         char *path = r->uri;
3475         while (*path == '/') {
3476             ++path;
3477         }
3478         if ((rv = apr_filepath_merge(&r->filename, conf->ap_document_root, path,
3479                                      APR_FILEPATH_TRUENAME
3480                                    | APR_FILEPATH_SECUREROOT, r->pool))
3481                     != APR_SUCCESS) {
3482             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
3483                          "Cannot map %s to file", r->the_request);
3484             return HTTP_FORBIDDEN;
3485         }
3486         r->canonical_filename = r->filename;
3487     }
3488
3489     return OK;
3490 }
3491
3492 /*****************************************************************
3493  *
3494  * Test the filesystem name through directory_walk and file_walk
3495  */
3496 static int core_map_to_storage(request_rec *r)
3497 {
3498     int access_status;
3499
3500     if ((access_status = ap_directory_walk(r))) {
3501         return access_status;
3502     }
3503
3504     if ((access_status = ap_file_walk(r))) {
3505         return access_status;
3506     }
3507
3508     return OK;
3509 }
3510
3511
3512 static int do_nothing(request_rec *r) { return OK; }
3513
3514
3515 static int core_override_type(request_rec *r)
3516 {
3517     core_dir_config *conf =
3518         (core_dir_config *)ap_get_module_config(r->per_dir_config,
3519                                                 &core_module);
3520
3521     /* Check for overrides with ForceType / SetHandler
3522      */
3523     if (conf->mime_type && strcmp(conf->mime_type, "none"))
3524         ap_set_content_type(r, (char*) conf->mime_type);
3525
3526     if (conf->handler && strcmp(conf->handler, "none"))
3527         r->handler = conf->handler;
3528
3529     /* Deal with the poor soul who is trying to force path_info to be
3530      * accepted within the core_handler, where they will let the subreq
3531      * address its contents.  This is toggled by the user in the very
3532      * beginning of the fixup phase, so modules should override the user's
3533      * discretion in their own module fixup phase.  It is tristate, if
3534      * the user doesn't specify, the result is 2 (which the module may
3535      * interpret to its own customary behavior.)  It won't be touched
3536      * if the value is no longer undefined (2), so any module changing
3537      * the value prior to the fixup phase OVERRIDES the user's choice.
3538      */
3539     if ((r->used_path_info == AP_REQ_DEFAULT_PATH_INFO)
3540         && (conf->accept_path_info != 3)) {
3541         r->used_path_info = conf->accept_path_info;
3542     }
3543
3544     return OK;
3545 }
3546
3547 static int default_handler(request_rec *r)
3548 {
3549     conn_rec *c = r->connection;
3550     apr_bucket_brigade *bb;
3551     apr_bucket *e;
3552     core_dir_config *d;
3553     int errstatus;
3554     apr_file_t *fd = NULL;
3555     apr_status_t status;
3556     /* XXX if/when somebody writes a content-md5 filter we either need to
3557      *     remove this support or coordinate when to use the filter vs.
3558      *     when to use this code
3559      *     The current choice of when to compute the md5 here matches the 1.3
3560      *     support fairly closely (unlike 1.3, we don't handle computing md5
3561      *     when the charset is translated).
3562      */
3563     int bld_content_md5;
3564
3565     d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
3566                                                 &core_module);
3567     bld_content_md5 = (d->content_md5 & 1)
3568                       && r->output_filters->frec->ftype != AP_FTYPE_RESOURCE;
3569
3570     ap_allow_standard_methods(r, MERGE_ALLOW, M_GET, M_OPTIONS, M_POST, -1);
3571
3572     /* If filters intend to consume the request body, they must
3573      * register an InputFilter to slurp the contents of the POST
3574      * data from the POST input stream.  It no longer exists when
3575      * the output filters are invoked by the default handler.
3576      */
3577     if ((errstatus = ap_discard_request_body(r)) != OK) {
3578         return errstatus;
3579     }
3580
3581     if (r->method_number == M_GET || r->method_number == M_POST) {
3582         if (r->finfo.filetype == 0) {
3583             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3584                           "File does not exist: %s", r->filename);
3585             return HTTP_NOT_FOUND;
3586         }
3587
3588         /* Don't try to serve a dir.  Some OSs do weird things with
3589          * raw I/O on a dir.
3590          */
3591         if (r->finfo.filetype == APR_DIR) {
3592             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3593                           "Attempt to serve directory: %s", r->filename);
3594             return HTTP_NOT_FOUND;
3595         }
3596
3597         if ((r->used_path_info != AP_REQ_ACCEPT_PATH_INFO) &&
3598             r->path_info && *r->path_info)
3599         {
3600             /* default to reject */
3601             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3602                           "File does not exist: %s",
3603                           apr_pstrcat(r->pool, r->filename, r->path_info, NULL));
3604             return HTTP_NOT_FOUND;
3605         }
3606
3607         /* We understood the (non-GET) method, but it might not be legal for
3608            this particular resource. Check to see if the 'deliver_script'
3609            flag is set. If so, then we go ahead and deliver the file since
3610            it isn't really content (only GET normally returns content).
3611
3612            Note: based on logic further above, the only possible non-GET
3613            method at this point is POST. In the future, we should enable
3614            script delivery for all methods.  */
3615         if (r->method_number != M_GET) {
3616             core_request_config *req_cfg;
3617
3618             req_cfg = ap_get_module_config(r->request_config, &core_module);
3619             if (!req_cfg->deliver_script) {
3620                 /* The flag hasn't been set for this request. Punt. */
3621                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3622                               "This resource does not accept the %s method.",
3623                               r->method);
3624                 return HTTP_METHOD_NOT_ALLOWED;
3625             }
3626         }
3627
3628
3629         if ((status = apr_file_open(&fd, r->filename, APR_READ | APR_BINARY
3630 #if APR_HAS_SENDFILE
3631                             | ((d->enable_sendfile == ENABLE_SENDFILE_OFF)
3632                                                 ? 0 : APR_SENDFILE_ENABLED)
3633 #endif
3634                                     , 0, r->pool)) != APR_SUCCESS) {
3635             ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r,
3636                           "file permissions deny server access: %s", r->filename);
3637             return HTTP_FORBIDDEN;
3638         }
3639
3640         ap_update_mtime(r, r->finfo.mtime);
3641         ap_set_last_modified(r);
3642         ap_set_etag(r);
3643         apr_table_setn(r->headers_out, "Accept-Ranges", "bytes");
3644         ap_set_content_length(r, r->finfo.size);
3645         if (bld_content_md5) {
3646             apr_table_setn(r->headers_out, "Content-MD5",
3647                            ap_md5digest(r->pool, fd));
3648         }
3649
3650         bb = apr_brigade_create(r->pool, c->bucket_alloc);
3651
3652         if ((errstatus = ap_meets_conditions(r)) != OK) {
3653             apr_file_close(fd);
3654             r->status = errstatus;
3655         }
3656         else {
3657             e = apr_brigade_insert_file(bb, fd, 0, r->finfo.size, r->pool);
3658
3659 #if APR_HAS_MMAP
3660             if (d->enable_mmap == ENABLE_MMAP_OFF) {
3661                 (void)apr_bucket_file_enable_mmap(e, 0);
3662             }
3663 #endif
3664         }
3665
3666         e = apr_bucket_eos_create(c->bucket_alloc);
3667         APR_BRIGADE_INSERT_TAIL(bb, e);
3668
3669         status = ap_pass_brigade(r->output_filters, bb);
3670         if (status == APR_SUCCESS
3671             || r->status != HTTP_OK
3672             || c->aborted) {
3673             return OK;
3674         }
3675         else {
3676             /* no way to know what type of error occurred */
3677             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, status, r,
3678                           "default_handler: ap_pass_brigade returned %i",
3679                           status);
3680             return HTTP_INTERNAL_SERVER_ERROR;
3681         }
3682     }
3683     else {              /* unusual method (not GET or POST) */
3684         if (r->method_number == M_INVALID) {
3685             /* See if this looks like an undecrypted SSL handshake attempt.
3686              * It's safe to look a couple bytes into the_request if it exists, as it's
3687              * always allocated at least MIN_LINE_ALLOC (80) bytes.
3688              */
3689             if (r->the_request
3690                 && r->the_request[0] == 0x16                                
3691                 && (r->the_request[1] == 0x2 || r->the_request[1] == 0x3)) {
3692                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3693                               "Invalid method in request %s - possible attempt to establish SSL connection on non-SSL port", r->the_request);
3694             } else {
3695                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3696                               "Invalid method in request %s", r->the_request);
3697             }
3698             return HTTP_NOT_IMPLEMENTED;
3699         }
3700
3701         if (r->method_number == M_OPTIONS) {
3702             return ap_send_http_options(r);
3703         }
3704         return HTTP_METHOD_NOT_ALLOWED;
3705     }
3706 }
3707
3708 /* Optional function coming from mod_logio, used for logging of output
3709  * traffic
3710  */
3711 APR_OPTIONAL_FN_TYPE(ap_logio_add_bytes_out) *ap__logio_add_bytes_out;
3712 APR_OPTIONAL_FN_TYPE(authz_some_auth_required) *ap__authz_ap_some_auth_required;
3713
3714 /* Insist that at least one module will undertake to provide system
3715  * security by dropping startup privileges.
3716  */
3717 static int sys_privileges = 0;
3718 AP_DECLARE(int) ap_sys_privileges_handlers(int inc)
3719 {
3720     sys_privileges += inc;
3721     return sys_privileges;
3722 }
3723
3724 static int core_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
3725 {
3726     ap_mutex_init(pconf);
3727     return APR_SUCCESS;
3728 }
3729
3730 static int core_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
3731 {
3732     ap__logio_add_bytes_out = APR_RETRIEVE_OPTIONAL_FN(ap_logio_add_bytes_out);
3733     ident_lookup = APR_RETRIEVE_OPTIONAL_FN(ap_ident_lookup);
3734     ap__authz_ap_some_auth_required = APR_RETRIEVE_OPTIONAL_FN(authz_some_auth_required);
3735     authn_ap_auth_type = APR_RETRIEVE_OPTIONAL_FN(authn_ap_auth_type);
3736     authn_ap_auth_name = APR_RETRIEVE_OPTIONAL_FN(authn_ap_auth_name);
3737     access_compat_ap_satisfies = APR_RETRIEVE_OPTIONAL_FN(access_compat_ap_satisfies);
3738
3739     set_banner(pconf);
3740     ap_setup_make_content_type(pconf);
3741     ap_setup_auth_internal(ptemp);
3742     if (!sys_privileges) {
3743         ap_log_error(APLOG_MARK, APLOG_CRIT, 0, NULL,
3744                      "Server MUST relinquish startup privileges before "
3745                      "accepting connections.  Please ensure mod_unixd "
3746                      "or other system security module is loaded.");
3747         return !OK;
3748     }
3749     return OK;
3750 }
3751
3752 static void core_insert_filter(request_rec *r)
3753 {
3754     core_dir_config *conf = (core_dir_config *)
3755                             ap_get_module_config(r->per_dir_config,
3756                                                  &core_module);
3757     const char *filter, *filters = conf->output_filters;
3758
3759     if (filters) {
3760         while (*filters && (filter = ap_getword(r->pool, &filters, ';'))) {
3761             ap_add_output_filter(filter, NULL, r, r->connection);
3762         }
3763     }
3764
3765     filters = conf->input_filters;
3766     if (filters) {
3767         while (*filters && (filter = ap_getword(r->pool, &filters, ';'))) {
3768             ap_add_input_filter(filter, NULL, r, r->connection);
3769         }
3770     }
3771 }
3772
3773 static apr_size_t num_request_notes = AP_NUM_STD_NOTES;
3774
3775 static apr_status_t reset_request_notes(void *dummy)
3776 {
3777     num_request_notes = AP_NUM_STD_NOTES;
3778     return APR_SUCCESS;
3779 }
3780
3781 AP_DECLARE(apr_size_t) ap_register_request_note(void)
3782 {
3783     apr_pool_cleanup_register(apr_hook_global_pool, NULL, reset_request_notes,
3784                               apr_pool_cleanup_null);
3785     return num_request_notes++;
3786 }
3787
3788 AP_DECLARE(void **) ap_get_request_note(request_rec *r, apr_size_t note_num)
3789 {
3790     core_request_config *req_cfg;
3791
3792     if (note_num >= num_request_notes) {
3793         return NULL;
3794     }
3795
3796     req_cfg = (core_request_config *)
3797         ap_get_module_config(r->request_config, &core_module);
3798
3799     if (!req_cfg) {
3800         return NULL;
3801     }
3802
3803     return &(req_cfg->notes[note_num]);
3804 }
3805
3806 static int core_create_req(request_rec *r)
3807 {
3808     /* Alloc the config struct and the array of request notes in
3809      * a single block for efficiency
3810      */
3811     core_request_config *req_cfg;
3812
3813     req_cfg = apr_pcalloc(r->pool, sizeof(core_request_config) +
3814                           sizeof(void *) * num_request_notes);
3815     req_cfg->notes = (void **)((char *)req_cfg + sizeof(core_request_config));
3816
3817     /* ### temporarily enable script delivery as the default */
3818     req_cfg->deliver_script = 1;
3819
3820     if (r->main) {
3821         core_request_config *main_req_cfg = (core_request_config *)
3822             ap_get_module_config(r->main->request_config, &core_module);
3823         req_cfg->bb = main_req_cfg->bb;
3824     }
3825     else {
3826         req_cfg->bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
3827     }
3828
3829     ap_set_module_config(r->request_config, &core_module, req_cfg);
3830
3831     return OK;
3832 }
3833
3834 static int core_create_proxy_req(request_rec *r, request_rec *pr)
3835 {
3836     return core_create_req(pr);
3837 }
3838
3839 static conn_rec *core_create_conn(apr_pool_t *ptrans, server_rec *server,
3840                                   apr_socket_t *csd, long id, void *sbh,
3841                                   apr_bucket_alloc_t *alloc)
3842 {
3843     apr_status_t rv;
3844     conn_rec *c = (conn_rec *) apr_pcalloc(ptrans, sizeof(conn_rec));
3845
3846     c->sbh = sbh;
3847     (void)ap_update_child_status(c->sbh, SERVER_BUSY_READ, (request_rec *)NULL);
3848
3849     /* Got a connection structure, so initialize what fields we can
3850      * (the rest are zeroed out by pcalloc).
3851      */
3852     c->conn_config = ap_create_conn_config(ptrans);
3853     c->notes = apr_table_make(ptrans, 5);
3854
3855     c->pool = ptrans;
3856     if ((rv = apr_socket_addr_get(&c->local_addr, APR_LOCAL, csd))
3857         != APR_SUCCESS) {
3858         ap_log_error(APLOG_MARK, APLOG_INFO, rv, server,
3859                      "apr_socket_addr_get(APR_LOCAL)");
3860         apr_socket_close(csd);
3861         return NULL;
3862     }
3863
3864     apr_sockaddr_ip_get(&c->local_ip, c->local_addr);
3865     if ((rv = apr_socket_addr_get(&c->remote_addr, APR_REMOTE, csd))
3866         != APR_SUCCESS) {
3867         ap_log_error(APLOG_MARK, APLOG_INFO, rv, server,
3868                      "apr_socket_addr_get(APR_REMOTE)");
3869         apr_socket_close(csd);
3870         return NULL;
3871     }
3872
3873     apr_sockaddr_ip_get(&c->remote_ip, c->remote_addr);
3874     c->base_server = server;
3875
3876     c->id = id;
3877     c->bucket_alloc = alloc;
3878
3879     c->cs = (conn_state_t *)apr_pcalloc(ptrans, sizeof(conn_state_t));
3880     APR_RING_INIT(&(c->cs->timeout_list), conn_state_t, timeout_list);
3881     c->cs->expiration_time = 0;
3882     c->cs->state = CONN_STATE_CHECK_REQUEST_LINE_READABLE;
3883     c->cs->c = c;
3884     c->cs->p = ptrans;
3885     c->cs->bucket_alloc = alloc;
3886     c->clogging_input_filters = 0;
3887
3888     return c;
3889 }
3890
3891 static int core_pre_connection(conn_rec *c, void *csd)
3892 {
3893     core_net_rec *net = apr_palloc(c->pool, sizeof(*net));
3894     apr_status_t rv;
3895
3896     /* The Nagle algorithm says that we should delay sending partial
3897      * packets in hopes of getting more data.  We don't want to do
3898      * this; we are not telnet.  There are bad interactions between
3899      * persistent connections and Nagle's algorithm that have very severe
3900      * performance penalties.  (Failing to disable Nagle is not much of a
3901      * problem with simple HTTP.)
3902      */
3903     rv = apr_socket_opt_set(csd, APR_TCP_NODELAY, 1);
3904     if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
3905         /* expected cause is that the client disconnected already,
3906          * hence the debug level
3907          */
3908         ap_log_cerror(APLOG_MARK, APLOG_DEBUG, rv, c,
3909                       "apr_socket_opt_set(APR_TCP_NODELAY)");
3910     }
3911
3912     /* The core filter requires the timeout mode to be set, which
3913      * incidentally sets the socket to be nonblocking.  If this
3914      * is not initialized correctly, Linux - for example - will
3915      * be initially blocking, while Solaris will be non blocking
3916      * and any initial read will fail.
3917      */
3918     rv = apr_socket_timeout_set(csd, c->base_server->timeout);
3919     if (rv != APR_SUCCESS) {
3920         /* expected cause is that the client disconnected already */
3921         ap_log_cerror(APLOG_MARK, APLOG_DEBUG, rv, c,
3922                       "apr_socket_timeout_set");
3923     }
3924
3925     net->c = c;
3926     net->in_ctx = NULL;
3927     net->out_ctx = NULL;
3928     net->client_socket = csd;
3929
3930     ap_set_module_config(net->c->conn_config, &core_module, csd);
3931     ap_add_input_filter_handle(ap_core_input_filter_handle, net, NULL, net->c);
3932     ap_add_output_filter_handle(ap_core_output_filter_handle, net, NULL, net->c);
3933     return DONE;
3934 }
3935
3936 static void register_hooks(apr_pool_t *p)
3937 {
3938     /* create_connection and pre_connection should always be hooked
3939      * APR_HOOK_REALLY_LAST by core to give other modules the opportunity
3940      * to install alternate network transports and stop other functions 
3941      * from being run.
3942      */
3943     ap_hook_create_connection(core_create_conn, NULL, NULL,
3944                               APR_HOOK_REALLY_LAST);
3945     ap_hook_pre_connection(core_pre_connection, NULL, NULL,
3946                            APR_HOOK_REALLY_LAST);
3947
3948     ap_hook_pre_config(core_pre_config, NULL, NULL, APR_HOOK_REALLY_FIRST);
3949     ap_hook_post_config(core_post_config,NULL,NULL,APR_HOOK_REALLY_FIRST);
3950     ap_hook_translate_name(ap_core_translate,NULL,NULL,APR_HOOK_REALLY_LAST);
3951     ap_hook_map_to_storage(core_map_to_storage,NULL,NULL,APR_HOOK_REALLY_LAST);
3952     ap_hook_open_logs(ap_open_logs,NULL,NULL,APR_HOOK_REALLY_FIRST);
3953     ap_hook_child_init(ap_logs_child_init,NULL,NULL,APR_HOOK_MIDDLE);
3954     ap_hook_handler(default_handler,NULL,NULL,APR_HOOK_REALLY_LAST);
3955     /* FIXME: I suspect we can eliminate the need for these do_nothings - Ben */
3956     ap_hook_type_checker(do_nothing,NULL,NULL,APR_HOOK_REALLY_LAST);
3957     ap_hook_fixups(core_override_type,NULL,NULL,APR_HOOK_REALLY_FIRST);
3958     ap_hook_create_request(core_create_req, NULL, NULL, APR_HOOK_MIDDLE);
3959     APR_OPTIONAL_HOOK(proxy, create_req, core_create_proxy_req, NULL, NULL,
3960                       APR_HOOK_MIDDLE);
3961     ap_hook_pre_mpm(ap_create_scoreboard, NULL, NULL, APR_HOOK_MIDDLE);
3962
3963     /* register the core's insert_filter hook and register core-provided
3964      * filters
3965      */
3966     ap_hook_insert_filter(core_insert_filter, NULL, NULL, APR_HOOK_MIDDLE);
3967
3968     ap_core_input_filter_handle =
3969         ap_register_input_filter("CORE_IN", ap_core_input_filter,
3970                                  NULL, AP_FTYPE_NETWORK);
3971     ap_content_length_filter_handle =
3972         ap_register_output_filter("CONTENT_LENGTH", ap_content_length_filter,
3973                                   NULL, AP_FTYPE_PROTOCOL);
3974     ap_core_output_filter_handle =
3975         ap_register_output_filter("CORE", ap_core_output_filter,
3976                                   NULL, AP_FTYPE_NETWORK);
3977     ap_subreq_core_filter_handle =
3978         ap_register_output_filter("SUBREQ_CORE", ap_sub_req_output_filter,
3979                                   NULL, AP_FTYPE_CONTENT_SET);
3980     ap_old_write_func =
3981         ap_register_output_filter("OLD_WRITE", ap_old_write_filter,
3982                                   NULL, AP_FTYPE_RESOURCE - 10);
3983 }
3984
3985 AP_DECLARE_DATA module core_module = {
3986     MPM20_MODULE_STUFF,
3987     AP_PLATFORM_REWRITE_ARGS_HOOK, /* hook to run before apache parses args */
3988     create_core_dir_config,       /* create per-directory config structure */
3989     merge_core_dir_configs,       /* merge per-directory config structures */
3990     create_core_server_config,    /* create per-server config structure */
3991     merge_core_server_configs,    /* merge per-server config structures */
3992     core_cmds,                    /* command apr_table_t */
3993     register_hooks                /* register hooks */
3994 };
3995