]> granicus.if.org Git - apache/blob - server/core.c
eventMPM:
[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_random.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 "util_time.h"
46 #include "mpm_common.h"
47 #include "scoreboard.h"
48 #include "mod_core.h"
49 #include "mod_proxy.h"
50 #include "ap_listen.h"
51 #include "ap_provider.h"
52
53 #include "mod_so.h" /* for ap_find_loaded_module_symbol */
54
55 #if defined(RLIMIT_CPU) || defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS) || defined (RLIMIT_NPROC)
56 #include "unixd.h"
57 #endif
58 #if APR_HAVE_UNISTD_H
59 #include <unistd.h>
60 #endif
61
62 /* LimitRequestBody handling */
63 #define AP_LIMIT_REQ_BODY_UNSET         ((apr_off_t) -1)
64 #define AP_DEFAULT_LIMIT_REQ_BODY       ((apr_off_t) 0)
65
66 /* LimitXMLRequestBody handling */
67 #define AP_LIMIT_UNSET                  ((long) -1)
68 #define AP_DEFAULT_LIMIT_XML_BODY       ((apr_size_t)1000000)
69
70 #define AP_MIN_SENDFILE_BYTES           (256)
71
72 /* maximum include nesting level */
73 #ifndef AP_MAX_INCLUDE_DEPTH
74 #define AP_MAX_INCLUDE_DEPTH            (128)
75 #endif
76
77 /* valid in core-conf, but not in runtime r->used_path_info */
78 #define AP_ACCEPT_PATHINFO_UNSET 3
79
80 #define AP_CONTENT_MD5_OFF   0
81 #define AP_CONTENT_MD5_ON    1
82 #define AP_CONTENT_MD5_UNSET 2
83
84 APR_HOOK_STRUCT(
85     APR_HOOK_LINK(get_mgmt_items)
86     APR_HOOK_LINK(insert_network_bucket)
87 )
88
89 AP_IMPLEMENT_HOOK_RUN_ALL(int, get_mgmt_items,
90                           (apr_pool_t *p, const char *val, apr_hash_t *ht),
91                           (p, val, ht), OK, DECLINED)
92
93 AP_IMPLEMENT_HOOK_RUN_FIRST(apr_status_t, insert_network_bucket,
94                             (conn_rec *c, apr_bucket_brigade *bb,
95                              apr_socket_t *socket),
96                             (c, bb, socket), AP_DECLINED)
97
98 /* Server core module... This module provides support for really basic
99  * server operations, including options and commands which control the
100  * operation of other modules.  Consider this the bureaucracy module.
101  *
102  * The core module also defines handlers, etc., to handle just enough
103  * to allow a server with the core module ONLY to actually serve documents.
104  *
105  * This file could almost be mod_core.c, except for the stuff which affects
106  * the http_conf_globals.
107  */
108
109 /* we know core's module_index is 0 */
110 #undef APLOG_MODULE_INDEX
111 #define APLOG_MODULE_INDEX AP_CORE_MODULE_INDEX
112
113 /* Handles for core filters */
114 AP_DECLARE_DATA ap_filter_rec_t *ap_subreq_core_filter_handle;
115 AP_DECLARE_DATA ap_filter_rec_t *ap_core_output_filter_handle;
116 AP_DECLARE_DATA ap_filter_rec_t *ap_content_length_filter_handle;
117 AP_DECLARE_DATA ap_filter_rec_t *ap_core_input_filter_handle;
118
119 /* Provide ap_document_root_check storage and default value = true */
120 AP_DECLARE_DATA int ap_document_root_check = 1;
121
122 /* magic pointer for ErrorDocument xxx "default" */
123 static char errordocument_default;
124
125 static apr_array_header_t *saved_server_config_defines = NULL;
126 static apr_table_t *server_config_defined_vars = NULL;
127
128 AP_DECLARE_DATA int ap_main_state = AP_SQ_MS_INITIAL_STARTUP;
129 AP_DECLARE_DATA int ap_run_mode = AP_SQ_RM_UNKNOWN;
130 AP_DECLARE_DATA int ap_config_generation = 0;
131
132 typedef struct {
133     apr_ipsubnet_t *subnet;
134     struct ap_logconf log;
135 } conn_log_config;
136
137 static void *create_core_dir_config(apr_pool_t *a, char *dir)
138 {
139     core_dir_config *conf;
140
141     conf = (core_dir_config *)apr_pcalloc(a, sizeof(core_dir_config));
142
143     /* conf->r and conf->d[_*] are initialized by dirsection() or left NULL */
144
145     conf->opts = dir ? OPT_UNSET : OPT_UNSET|OPT_SYM_LINKS;
146     conf->opts_add = conf->opts_remove = OPT_NONE;
147     conf->override = OR_UNSET|OR_NONE;
148     conf->override_opts = OPT_UNSET | OPT_ALL | OPT_SYM_OWNER | OPT_MULTI;
149
150     conf->content_md5 = AP_CONTENT_MD5_UNSET;
151     conf->accept_path_info = AP_ACCEPT_PATHINFO_UNSET;
152
153     conf->use_canonical_name = USE_CANONICAL_NAME_UNSET;
154     conf->use_canonical_phys_port = USE_CANONICAL_PHYS_PORT_UNSET;
155
156     conf->hostname_lookups = HOSTNAME_LOOKUP_UNSET;
157
158     /*
159      * left as NULL (we use apr_pcalloc):
160      * conf->limit_cpu = NULL;
161      * conf->limit_mem = NULL;
162      * conf->limit_nproc = NULL;
163      * conf->sec_file = NULL;
164      * conf->sec_if   = NULL;
165      */
166
167     conf->limit_req_body = AP_LIMIT_REQ_BODY_UNSET;
168     conf->limit_xml_body = AP_LIMIT_UNSET;
169
170     conf->server_signature = srv_sig_unset;
171
172     conf->add_default_charset = ADD_DEFAULT_CHARSET_UNSET;
173     conf->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
174
175     /* Overriding all negotiation
176      * Set NULL by apr_pcalloc:
177      * conf->mime_type = NULL;
178      * conf->handler = NULL;
179      * conf->output_filters = NULL;
180      * conf->input_filters = NULL;
181      */
182
183     /*
184      * Flag for use of inodes in ETags.
185      */
186     conf->etag_bits = ETAG_UNSET;
187     conf->etag_add = ETAG_UNSET;
188     conf->etag_remove = ETAG_UNSET;
189
190     conf->enable_mmap = ENABLE_MMAP_UNSET;
191     conf->enable_sendfile = ENABLE_SENDFILE_UNSET;
192     conf->allow_encoded_slashes = 0;
193     conf->decode_encoded_slashes = 0;
194
195     conf->max_ranges = AP_MAXRANGES_UNSET;
196     conf->max_overlaps = AP_MAXRANGES_UNSET;
197     conf->max_reversals = AP_MAXRANGES_UNSET;
198
199     return (void *)conf;
200 }
201
202 static void *merge_core_dir_configs(apr_pool_t *a, void *basev, void *newv)
203 {
204     core_dir_config *base = (core_dir_config *)basev;
205     core_dir_config *new = (core_dir_config *)newv;
206     core_dir_config *conf;
207     int i;
208
209     /* Create this conf by duplicating the base, replacing elements
210      * (or creating copies for merging) where new-> values exist.
211      */
212     conf = (core_dir_config *)apr_pmemdup(a, base, sizeof(core_dir_config));
213
214     conf->d = new->d;
215     conf->d_is_fnmatch = new->d_is_fnmatch;
216     conf->d_components = new->d_components;
217     conf->r = new->r;
218     conf->refs = new->refs;
219     conf->condition = new->condition;
220
221     if (new->opts & OPT_UNSET) {
222         /* there was no explicit setting of new->opts, so we merge
223          * preserve the invariant (opts_add & opts_remove) == 0
224          */
225         conf->opts_add = (conf->opts_add & ~new->opts_remove) | new->opts_add;
226         conf->opts_remove = (conf->opts_remove & ~new->opts_add)
227                             | new->opts_remove;
228         conf->opts = (conf->opts & ~conf->opts_remove) | conf->opts_add;
229
230         /* If Includes was enabled with exec in the base config, but
231          * was enabled without exec in the new config, then disable
232          * exec in the merged set. */
233         if (((base->opts & (OPT_INCLUDES|OPT_INC_WITH_EXEC))
234              == (OPT_INCLUDES|OPT_INC_WITH_EXEC))
235             && ((new->opts & (OPT_INCLUDES|OPT_INC_WITH_EXEC))
236                 == OPT_INCLUDES)) {
237             conf->opts &= ~OPT_INC_WITH_EXEC;
238         }
239     }
240     else {
241         /* otherwise we just copy, because an explicit opts setting
242          * overrides all earlier +/- modifiers
243          */
244         conf->opts = new->opts;
245         conf->opts_add = new->opts_add;
246         conf->opts_remove = new->opts_remove;
247     }
248
249     if (!(new->override & OR_UNSET)) {
250         conf->override = new->override;
251     }
252
253     if (!(new->override_opts & OPT_UNSET)) {
254         conf->override_opts = new->override_opts;
255     }
256
257     if (new->override_list != NULL) {
258         conf->override_list = new->override_list;
259     }
260
261     if (conf->response_code_strings == NULL) {
262         conf->response_code_strings = new->response_code_strings;
263     }
264     else if (new->response_code_strings != NULL) {
265         /* If we merge, the merge-result must have its own array
266          */
267         conf->response_code_strings = apr_pmemdup(a,
268             base->response_code_strings,
269             sizeof(*conf->response_code_strings) * RESPONSE_CODES);
270
271         for (i = 0; i < RESPONSE_CODES; ++i) {
272             if (new->response_code_strings[i] != NULL) {
273                 conf->response_code_strings[i] = new->response_code_strings[i];
274             }
275         }
276     }
277     /* Otherwise we simply use the base->response_code_strings array
278      */
279
280     if (new->hostname_lookups != HOSTNAME_LOOKUP_UNSET) {
281         conf->hostname_lookups = new->hostname_lookups;
282     }
283
284     if (new->content_md5 != AP_CONTENT_MD5_UNSET) {
285         conf->content_md5 = new->content_md5;
286     }
287
288     if (new->accept_path_info != AP_ACCEPT_PATHINFO_UNSET) {
289         conf->accept_path_info = new->accept_path_info;
290     }
291
292     if (new->use_canonical_name != USE_CANONICAL_NAME_UNSET) {
293         conf->use_canonical_name = new->use_canonical_name;
294     }
295
296     if (new->use_canonical_phys_port != USE_CANONICAL_PHYS_PORT_UNSET) {
297         conf->use_canonical_phys_port = new->use_canonical_phys_port;
298     }
299
300 #ifdef RLIMIT_CPU
301     if (new->limit_cpu) {
302         conf->limit_cpu = new->limit_cpu;
303     }
304 #endif
305
306 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
307     if (new->limit_mem) {
308         conf->limit_mem = new->limit_mem;
309     }
310 #endif
311
312 #ifdef RLIMIT_NPROC
313     if (new->limit_nproc) {
314         conf->limit_nproc = new->limit_nproc;
315     }
316 #endif
317
318     if (new->limit_req_body != AP_LIMIT_REQ_BODY_UNSET) {
319         conf->limit_req_body = new->limit_req_body;
320     }
321
322     if (new->limit_xml_body != AP_LIMIT_UNSET)
323         conf->limit_xml_body = new->limit_xml_body;
324
325     if (!conf->sec_file) {
326         conf->sec_file = new->sec_file;
327     }
328     else if (new->sec_file) {
329         /* If we merge, the merge-result must have its own array
330          */
331         conf->sec_file = apr_array_append(a, base->sec_file, new->sec_file);
332     }
333     /* Otherwise we simply use the base->sec_file array
334      */
335
336     if (!conf->sec_if) {
337         conf->sec_if = new->sec_if;
338     }
339     else if (new->sec_if) {
340         /* If we merge, the merge-result must have its own array
341          */
342         conf->sec_if = apr_array_append(a, base->sec_if, new->sec_if);
343     }
344     /* Otherwise we simply use the base->sec_if array
345      */
346
347     if (new->server_signature != srv_sig_unset) {
348         conf->server_signature = new->server_signature;
349     }
350
351     if (new->add_default_charset != ADD_DEFAULT_CHARSET_UNSET) {
352         conf->add_default_charset = new->add_default_charset;
353         conf->add_default_charset_name = new->add_default_charset_name;
354     }
355
356     /* Overriding all negotiation
357      */
358     if (new->mime_type) {
359         conf->mime_type = new->mime_type;
360     }
361
362     if (new->handler) {
363         conf->handler = new->handler;
364     }
365
366     if (new->output_filters) {
367         conf->output_filters = new->output_filters;
368     }
369
370     if (new->input_filters) {
371         conf->input_filters = new->input_filters;
372     }
373
374     /*
375      * Now merge the setting of the FileETag directive.
376      */
377     if (new->etag_bits == ETAG_UNSET) {
378         conf->etag_add =
379             (conf->etag_add & (~ new->etag_remove)) | new->etag_add;
380         conf->etag_remove =
381             (conf->etag_remove & (~ new->etag_add)) | new->etag_remove;
382         conf->etag_bits =
383             (conf->etag_bits & (~ conf->etag_remove)) | conf->etag_add;
384     }
385     else {
386         conf->etag_bits = new->etag_bits;
387         conf->etag_add = new->etag_add;
388         conf->etag_remove = new->etag_remove;
389     }
390
391     if (conf->etag_bits != ETAG_NONE) {
392         conf->etag_bits &= (~ ETAG_NONE);
393     }
394
395     if (new->enable_mmap != ENABLE_MMAP_UNSET) {
396         conf->enable_mmap = new->enable_mmap;
397     }
398
399     if (new->enable_sendfile != ENABLE_SENDFILE_UNSET) {
400         conf->enable_sendfile = new->enable_sendfile;
401     }
402
403     if (new->allow_encoded_slashes_set) {
404         conf->allow_encoded_slashes = new->allow_encoded_slashes;
405     }
406     if (new->decode_encoded_slashes_set) {
407         conf->decode_encoded_slashes = new->decode_encoded_slashes;
408     }
409
410     if (new->log) {
411         if (!conf->log) {
412             conf->log = new->log;
413         }
414         else {
415             conf->log = ap_new_log_config(a, new->log);
416             ap_merge_log_config(base->log, conf->log);
417         }
418     }
419
420     conf->max_ranges = new->max_ranges != AP_MAXRANGES_UNSET ? new->max_ranges : base->max_ranges;
421     conf->max_overlaps = new->max_overlaps != AP_MAXRANGES_UNSET ? new->max_overlaps : base->max_overlaps;
422     conf->max_reversals = new->max_reversals != AP_MAXRANGES_UNSET ? new->max_reversals : base->max_reversals;
423
424     return (void*)conf;
425 }
426
427 #if APR_HAS_SO_ACCEPTFILTER
428 #ifndef ACCEPT_FILTER_NAME
429 #define ACCEPT_FILTER_NAME "httpready"
430 #ifdef __FreeBSD_version
431 #if __FreeBSD_version < 411000 /* httpready broken before 4.1.1 */
432 #undef ACCEPT_FILTER_NAME
433 #define ACCEPT_FILTER_NAME "dataready"
434 #endif
435 #endif
436 #endif
437 #endif
438
439 static void *create_core_server_config(apr_pool_t *a, server_rec *s)
440 {
441     core_server_config *conf;
442     int is_virtual = s->is_virtual;
443
444     conf = (core_server_config *)apr_pcalloc(a, sizeof(core_server_config));
445
446     /* global-default / global-only settings */
447
448     if (!is_virtual) {
449         conf->ap_document_root = DOCUMENT_LOCATION;
450         conf->access_name = DEFAULT_ACCESS_FNAME;
451
452         /* A mapping only makes sense in the global context */
453         conf->accf_map = apr_table_make(a, 5);
454 #if APR_HAS_SO_ACCEPTFILTER
455         apr_table_setn(conf->accf_map, "http", ACCEPT_FILTER_NAME);
456         apr_table_setn(conf->accf_map, "https", "dataready");
457 #else
458         apr_table_setn(conf->accf_map, "http", "data");
459         apr_table_setn(conf->accf_map, "https", "data");
460 #endif
461     }
462     /* pcalloc'ed - we have NULL's/0's
463     else ** is_virtual ** {
464         conf->ap_document_root = NULL;
465         conf->access_name = NULL;
466         conf->accf_map = NULL;
467     }
468      */
469
470     /* initialization, no special case for global context */
471
472     conf->sec_dir = apr_array_make(a, 40, sizeof(ap_conf_vector_t *));
473     conf->sec_url = apr_array_make(a, 40, sizeof(ap_conf_vector_t *));
474
475     /* pcalloc'ed - we have NULL's/0's
476     conf->gprof_dir = NULL;
477
478     ** recursion stopper; 0 == unset
479     conf->redirect_limit = 0;
480     conf->subreq_limit = 0;
481
482     conf->protocol = NULL;
483      */
484
485     conf->trace_enable = AP_TRACE_UNSET;
486
487     return (void *)conf;
488 }
489
490 static void *merge_core_server_configs(apr_pool_t *p, void *basev, void *virtv)
491 {
492     core_server_config *base = (core_server_config *)basev;
493     core_server_config *virt = (core_server_config *)virtv;
494     core_server_config *conf = (core_server_config *)
495                                apr_pmemdup(p, base, sizeof(core_server_config));
496
497     if (virt->ap_document_root)
498         conf->ap_document_root = virt->ap_document_root;
499
500     if (virt->access_name)
501         conf->access_name = virt->access_name;
502
503     /* XXX optimize to keep base->sec_ pointers if virt->sec_ array is empty */
504     conf->sec_dir = apr_array_append(p, base->sec_dir, virt->sec_dir);
505     conf->sec_url = apr_array_append(p, base->sec_url, virt->sec_url);
506
507     if (virt->redirect_limit)
508         conf->redirect_limit = virt->redirect_limit;
509
510     if (virt->subreq_limit)
511         conf->subreq_limit = virt->subreq_limit;
512
513     if (virt->trace_enable != AP_TRACE_UNSET)
514         conf->trace_enable = virt->trace_enable;
515
516     if (virt->http09_enable != AP_HTTP09_UNSET)
517         conf->http09_enable = virt->http09_enable;
518
519     if (virt->http_conformance != AP_HTTP_CONFORMANCE_UNSET)
520         conf->http_conformance = virt->http_conformance;
521
522     if (virt->http_cl_head_zero != AP_HTTP_CL_HEAD_ZERO_UNSET)
523         conf->http_cl_head_zero = virt->http_cl_head_zero;
524
525     if (virt->http_expect_strict != AP_HTTP_EXPECT_STRICT_UNSET)
526         conf->http_expect_strict = virt->http_expect_strict;
527
528     /* no action for virt->accf_map, not allowed per-vhost */
529
530     if (virt->protocol)
531         conf->protocol = virt->protocol;
532
533     if (virt->gprof_dir)
534         conf->gprof_dir = virt->gprof_dir;
535
536     if (virt->error_log_format)
537         conf->error_log_format = virt->error_log_format;
538
539     if (virt->error_log_conn)
540         conf->error_log_conn = virt->error_log_conn;
541
542     if (virt->error_log_req)
543         conf->error_log_req = virt->error_log_req;
544
545     if (virt->conn_log_level) {
546         if (!conf->conn_log_level) {
547             conf->conn_log_level = virt->conn_log_level;
548         }
549         else {
550             /* apr_array_append actually creates a new array */
551             conf->conn_log_level = apr_array_append(p, conf->conn_log_level,
552                                                     virt->conn_log_level);
553         }
554     }
555
556     return conf;
557 }
558
559 /* Add per-directory configuration entry (for <directory> section);
560  * these are part of the core server config.
561  */
562
563 AP_CORE_DECLARE(void) ap_add_per_dir_conf(server_rec *s, void *dir_config)
564 {
565     core_server_config *sconf = ap_get_core_module_config(s->module_config);
566     void **new_space = (void **)apr_array_push(sconf->sec_dir);
567
568     *new_space = dir_config;
569 }
570
571 AP_CORE_DECLARE(void) ap_add_per_url_conf(server_rec *s, void *url_config)
572 {
573     core_server_config *sconf = ap_get_core_module_config(s->module_config);
574     void **new_space = (void **)apr_array_push(sconf->sec_url);
575
576     *new_space = url_config;
577 }
578
579 AP_CORE_DECLARE(void) ap_add_file_conf(apr_pool_t *p, core_dir_config *conf,
580                                        void *url_config)
581 {
582     void **new_space;
583
584     if (!conf->sec_file)
585         conf->sec_file = apr_array_make(p, 2, sizeof(ap_conf_vector_t *));
586
587     new_space = (void **)apr_array_push(conf->sec_file);
588     *new_space = url_config;
589 }
590
591 AP_CORE_DECLARE(const char *) ap_add_if_conf(apr_pool_t *p,
592                                              core_dir_config *conf,
593                                              void *if_config)
594 {
595     void **new_space;
596     core_dir_config *new = ap_get_module_config(if_config, &core_module);
597
598     if (!conf->sec_if) {
599         conf->sec_if = apr_array_make(p, 2, sizeof(ap_conf_vector_t *));
600     }
601     if (new->condition_ifelse & AP_CONDITION_ELSE) {
602         int have_if = 0;
603         if (conf->sec_if->nelts > 0) {
604             core_dir_config *last;
605             ap_conf_vector_t *lastelt = APR_ARRAY_IDX(conf->sec_if,
606                                                       conf->sec_if->nelts - 1,
607                                                       ap_conf_vector_t *);
608             last = ap_get_module_config(lastelt, &core_module);
609             if (last->condition_ifelse & AP_CONDITION_IF)
610                 have_if = 1;
611         }
612         if (!have_if)
613             return "<Else> or <ElseIf> section without previous <If> or "
614                    "<ElseIf> section in same scope";
615     }
616
617     new_space = (void **)apr_array_push(conf->sec_if);
618     *new_space = if_config;
619     return NULL;
620 }
621
622
623 /* We need to do a stable sort, qsort isn't stable.  So to make it stable
624  * we'll be maintaining the original index into the list, and using it
625  * as the minor key during sorting.  The major key is the number of
626  * components (where the root component is zero).
627  */
628 struct reorder_sort_rec {
629     ap_conf_vector_t *elt;
630     int orig_index;
631 };
632
633 static int reorder_sorter(const void *va, const void *vb)
634 {
635     const struct reorder_sort_rec *a = va;
636     const struct reorder_sort_rec *b = vb;
637     core_dir_config *core_a;
638     core_dir_config *core_b;
639
640     core_a = ap_get_core_module_config(a->elt);
641     core_b = ap_get_core_module_config(b->elt);
642
643     /* a regex always sorts after a non-regex
644      */
645     if (!core_a->r && core_b->r) {
646         return -1;
647     }
648     else if (core_a->r && !core_b->r) {
649         return 1;
650     }
651
652     /* we always sort next by the number of components
653      */
654     if (core_a->d_components < core_b->d_components) {
655         return -1;
656     }
657     else if (core_a->d_components > core_b->d_components) {
658         return 1;
659     }
660
661     /* They have the same number of components, we now have to compare
662      * the minor key to maintain the original order (from the config.)
663      */
664     return a->orig_index - b->orig_index;
665 }
666
667 void ap_core_reorder_directories(apr_pool_t *p, server_rec *s)
668 {
669     core_server_config *sconf;
670     apr_array_header_t *sec_dir;
671     struct reorder_sort_rec *sortbin;
672     int nelts;
673     ap_conf_vector_t **elts;
674     int i;
675     apr_pool_t *tmp;
676
677     sconf = ap_get_core_module_config(s->module_config);
678     sec_dir = sconf->sec_dir;
679     nelts = sec_dir->nelts;
680     elts = (ap_conf_vector_t **)sec_dir->elts;
681
682     if (!nelts) {
683         /* simple case of already being sorted... */
684         /* We're not checking this condition to be fast... we're checking
685          * it to avoid trying to palloc zero bytes, which can trigger some
686          * memory debuggers to barf
687          */
688         return;
689     }
690
691     /* we have to allocate tmp space to do a stable sort */
692     apr_pool_create(&tmp, p);
693     sortbin = apr_palloc(tmp, sec_dir->nelts * sizeof(*sortbin));
694     for (i = 0; i < nelts; ++i) {
695         sortbin[i].orig_index = i;
696         sortbin[i].elt = elts[i];
697     }
698
699     qsort(sortbin, nelts, sizeof(*sortbin), reorder_sorter);
700
701     /* and now copy back to the original array */
702     for (i = 0; i < nelts; ++i) {
703         elts[i] = sortbin[i].elt;
704     }
705
706     apr_pool_destroy(tmp);
707 }
708
709 /*****************************************************************
710  *
711  * There are some elements of the core config structures in which
712  * other modules have a legitimate interest (this is ugly, but necessary
713  * to preserve NCSA back-compatibility).  So, we have a bunch of accessors
714  * here...
715  */
716
717 AP_DECLARE(int) ap_allow_options(request_rec *r)
718 {
719     core_dir_config *conf =
720       (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
721
722     return conf->opts;
723 }
724
725 AP_DECLARE(int) ap_allow_overrides(request_rec *r)
726 {
727     core_dir_config *conf;
728     conf = (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
729
730     return conf->override;
731 }
732
733 /*
734  * Optional function coming from mod_authn_core, used for
735  * retrieving the type of autorization
736  */
737 static APR_OPTIONAL_FN_TYPE(authn_ap_auth_type) *authn_ap_auth_type;
738
739 AP_DECLARE(const char *) ap_auth_type(request_rec *r)
740 {
741     if (authn_ap_auth_type) {
742         return authn_ap_auth_type(r);
743     }
744     return NULL;
745 }
746
747 /*
748  * Optional function coming from mod_authn_core, used for
749  * retrieving the authorization realm
750  */
751 static APR_OPTIONAL_FN_TYPE(authn_ap_auth_name) *authn_ap_auth_name;
752
753 AP_DECLARE(const char *) ap_auth_name(request_rec *r)
754 {
755     if (authn_ap_auth_name) {
756         return authn_ap_auth_name(r);
757     }
758     return NULL;
759 }
760
761 /*
762  * Optional function coming from mod_access_compat, used to determine how
763    access control interacts with authentication/authorization
764  */
765 static APR_OPTIONAL_FN_TYPE(access_compat_ap_satisfies) *access_compat_ap_satisfies;
766
767 AP_DECLARE(int) ap_satisfies(request_rec *r)
768 {
769     if (access_compat_ap_satisfies) {
770         return access_compat_ap_satisfies(r);
771     }
772     return SATISFY_NOSPEC;
773 }
774
775 AP_DECLARE(const char *) ap_document_root(request_rec *r) /* Don't use this! */
776 {
777     core_server_config *sconf;
778     core_request_config *rconf = ap_get_core_module_config(r->request_config);
779     if (rconf->document_root)
780         return rconf->document_root;
781     sconf = ap_get_core_module_config(r->server->module_config);
782     return sconf->ap_document_root;
783 }
784
785 AP_DECLARE(const char *) ap_context_prefix(request_rec *r)
786 {
787     core_request_config *conf = ap_get_core_module_config(r->request_config);
788     if (conf->context_prefix)
789         return conf->context_prefix;
790     else
791         return "";
792 }
793
794 AP_DECLARE(const char *) ap_context_document_root(request_rec *r)
795 {
796     core_request_config *conf = ap_get_core_module_config(r->request_config);
797     if (conf->context_document_root)
798         return conf->context_document_root;
799     else
800         return ap_document_root(r);
801 }
802
803 AP_DECLARE(void) ap_set_document_root(request_rec *r, const char *document_root)
804 {
805     core_request_config *conf = ap_get_core_module_config(r->request_config);
806     conf->document_root = document_root;
807 }
808
809 AP_DECLARE(void) ap_set_context_info(request_rec *r, const char *context_prefix,
810                                      const char *context_document_root)
811 {
812     core_request_config *conf = ap_get_core_module_config(r->request_config);
813     if (context_prefix)
814         conf->context_prefix = context_prefix;
815     if (context_document_root)
816         conf->context_document_root = context_document_root;
817 }
818
819 /* Should probably just get rid of this... the only code that cares is
820  * part of the core anyway (and in fact, it isn't publicised to other
821  * modules).
822  */
823
824 char *ap_response_code_string(request_rec *r, int error_index)
825 {
826     core_dir_config *dirconf;
827     core_request_config *reqconf = ap_get_core_module_config(r->request_config);
828
829     /* check for string registered via ap_custom_response() first */
830     if (reqconf->response_code_strings != NULL &&
831         reqconf->response_code_strings[error_index] != NULL) {
832         return reqconf->response_code_strings[error_index];
833     }
834
835     /* check for string specified via ErrorDocument */
836     dirconf = ap_get_core_module_config(r->per_dir_config);
837
838     if (dirconf->response_code_strings == NULL) {
839         return NULL;
840     }
841
842     if (dirconf->response_code_strings[error_index] == &errordocument_default) {
843         return NULL;
844     }
845
846     return dirconf->response_code_strings[error_index];
847 }
848
849
850 /* Code from Harald Hanche-Olsen <hanche@imf.unit.no> */
851 static APR_INLINE void do_double_reverse (conn_rec *conn)
852 {
853     apr_sockaddr_t *sa;
854     apr_status_t rv;
855
856     if (conn->double_reverse) {
857         /* already done */
858         return;
859     }
860
861     if (conn->remote_host == NULL || conn->remote_host[0] == '\0') {
862         /* single reverse failed, so don't bother */
863         conn->double_reverse = -1;
864         return;
865     }
866
867     rv = apr_sockaddr_info_get(&sa, conn->remote_host, APR_UNSPEC, 0, 0, conn->pool);
868     if (rv == APR_SUCCESS) {
869         while (sa) {
870             if (apr_sockaddr_equal(sa, conn->client_addr)) {
871                 conn->double_reverse = 1;
872                 return;
873             }
874
875             sa = sa->next;
876         }
877     }
878
879     conn->double_reverse = -1;
880 }
881
882 AP_DECLARE(const char *) ap_get_remote_host(conn_rec *conn, void *dir_config,
883                                             int type, int *str_is_ip)
884 {
885     int hostname_lookups;
886     int ignored_str_is_ip;
887
888     if (!str_is_ip) { /* caller doesn't want to know */
889         str_is_ip = &ignored_str_is_ip;
890     }
891     *str_is_ip = 0;
892
893     /* If we haven't checked the host name, and we want to */
894     if (dir_config) {
895         hostname_lookups = ((core_dir_config *)ap_get_core_module_config(dir_config))
896                            ->hostname_lookups;
897
898         if (hostname_lookups == HOSTNAME_LOOKUP_UNSET) {
899             hostname_lookups = HOSTNAME_LOOKUP_OFF;
900         }
901     }
902     else {
903         /* the default */
904         hostname_lookups = HOSTNAME_LOOKUP_OFF;
905     }
906
907     if (type != REMOTE_NOLOOKUP
908         && conn->remote_host == NULL
909         && (type == REMOTE_DOUBLE_REV
910         || hostname_lookups != HOSTNAME_LOOKUP_OFF)) {
911
912         if (apr_getnameinfo(&conn->remote_host, conn->client_addr, 0)
913             == APR_SUCCESS) {
914             ap_str_tolower(conn->remote_host);
915
916             if (hostname_lookups == HOSTNAME_LOOKUP_DOUBLE) {
917                 do_double_reverse(conn);
918                 if (conn->double_reverse != 1) {
919                     conn->remote_host = NULL;
920                 }
921             }
922         }
923
924         /* if failed, set it to the NULL string to indicate error */
925         if (conn->remote_host == NULL) {
926             conn->remote_host = "";
927         }
928     }
929
930     if (type == REMOTE_DOUBLE_REV) {
931         do_double_reverse(conn);
932         if (conn->double_reverse == -1) {
933             return NULL;
934         }
935     }
936
937     /*
938      * Return the desired information; either the remote DNS name, if found,
939      * or either NULL (if the hostname was requested) or the IP address
940      * (if any identifier was requested).
941      */
942     if (conn->remote_host != NULL && conn->remote_host[0] != '\0') {
943         return conn->remote_host;
944     }
945     else {
946         if (type == REMOTE_HOST || type == REMOTE_DOUBLE_REV) {
947             return NULL;
948         }
949         else {
950             *str_is_ip = 1;
951             return conn->client_ip;
952         }
953     }
954 }
955
956 /*
957  * Optional function coming from mod_ident, used for looking up ident user
958  */
959 static APR_OPTIONAL_FN_TYPE(ap_ident_lookup) *ident_lookup;
960
961 AP_DECLARE(const char *) ap_get_remote_logname(request_rec *r)
962 {
963     if (r->connection->remote_logname != NULL) {
964         return r->connection->remote_logname;
965     }
966
967     if (ident_lookup) {
968         return ident_lookup(r);
969     }
970
971     return NULL;
972 }
973
974 /* There are two options regarding what the "name" of a server is.  The
975  * "canonical" name as defined by ServerName and Port, or the "client's
976  * name" as supplied by a possible Host: header or full URI.
977  *
978  * The DNS option to UseCanonicalName causes this routine to do a
979  * reverse lookup on the local IP address of the connection and use
980  * that for the ServerName. This makes its value more reliable while
981  * at the same time allowing Demon's magic virtual hosting to work.
982  * The assumption is that DNS lookups are sufficiently quick...
983  * -- fanf 1998-10-03
984  */
985 AP_DECLARE(const char *) ap_get_server_name(request_rec *r)
986 {
987     conn_rec *conn = r->connection;
988     core_dir_config *d;
989     const char *retval;
990
991     d = (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
992
993     switch (d->use_canonical_name) {
994         case USE_CANONICAL_NAME_ON:
995             retval = r->server->server_hostname;
996             break;
997         case USE_CANONICAL_NAME_DNS:
998             if (conn->local_host == NULL) {
999                 if (apr_getnameinfo(&conn->local_host,
1000                                 conn->local_addr, 0) != APR_SUCCESS)
1001                     conn->local_host = apr_pstrdup(conn->pool,
1002                                                r->server->server_hostname);
1003                 else {
1004                     ap_str_tolower(conn->local_host);
1005                 }
1006             }
1007             retval = conn->local_host;
1008             break;
1009         case USE_CANONICAL_NAME_OFF:
1010         case USE_CANONICAL_NAME_UNSET:
1011             retval = r->hostname ? r->hostname : r->server->server_hostname;
1012             break;
1013         default:
1014             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00109)
1015                          "ap_get_server_name: Invalid UCN Option somehow");
1016             retval = "localhost";
1017             break;
1018     }
1019     return retval;
1020 }
1021
1022 /*
1023  * Get the current server name from the request for the purposes
1024  * of using in a URL.  If the server name is an IPv6 literal
1025  * address, it will be returned in URL format (e.g., "[fe80::1]").
1026  */
1027 AP_DECLARE(const char *) ap_get_server_name_for_url(request_rec *r)
1028 {
1029     const char *plain_server_name = ap_get_server_name(r);
1030
1031 #if APR_HAVE_IPV6
1032     if (ap_strchr_c(plain_server_name, ':')) { /* IPv6 literal? */
1033         return apr_pstrcat(r->pool, "[", plain_server_name, "]", NULL);
1034     }
1035 #endif
1036     return plain_server_name;
1037 }
1038
1039 AP_DECLARE(apr_port_t) ap_get_server_port(const request_rec *r)
1040 {
1041     apr_port_t port;
1042     core_dir_config *d =
1043       (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
1044
1045     switch (d->use_canonical_name) {
1046         case USE_CANONICAL_NAME_OFF:
1047         case USE_CANONICAL_NAME_DNS:
1048         case USE_CANONICAL_NAME_UNSET:
1049             if (d->use_canonical_phys_port == USE_CANONICAL_PHYS_PORT_ON)
1050                 port = r->parsed_uri.port_str ? r->parsed_uri.port :
1051                        r->connection->local_addr->port ? r->connection->local_addr->port :
1052                        r->server->port ? r->server->port :
1053                        ap_default_port(r);
1054             else /* USE_CANONICAL_PHYS_PORT_OFF or USE_CANONICAL_PHYS_PORT_UNSET */
1055                 port = r->parsed_uri.port_str ? r->parsed_uri.port :
1056                        r->server->port ? r->server->port :
1057                        ap_default_port(r);
1058             break;
1059         case USE_CANONICAL_NAME_ON:
1060             /* With UseCanonicalName on (and in all versions prior to 1.3)
1061              * Apache will use the hostname and port specified in the
1062              * ServerName directive to construct a canonical name for the
1063              * server. (If no port was specified in the ServerName
1064              * directive, Apache uses the port supplied by the client if
1065              * any is supplied, and finally the default port for the protocol
1066              * used.
1067              */
1068             if (d->use_canonical_phys_port == USE_CANONICAL_PHYS_PORT_ON)
1069                 port = r->server->port ? r->server->port :
1070                        r->connection->local_addr->port ? r->connection->local_addr->port :
1071                        ap_default_port(r);
1072             else /* USE_CANONICAL_PHYS_PORT_OFF or USE_CANONICAL_PHYS_PORT_UNSET */
1073                 port = r->server->port ? r->server->port :
1074                        ap_default_port(r);
1075             break;
1076         default:
1077             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00110)
1078                          "ap_get_server_port: Invalid UCN Option somehow");
1079             port = ap_default_port(r);
1080             break;
1081     }
1082
1083     return port;
1084 }
1085
1086 AP_DECLARE(char *) ap_construct_url(apr_pool_t *p, const char *uri,
1087                                     request_rec *r)
1088 {
1089     unsigned port = ap_get_server_port(r);
1090     const char *host = ap_get_server_name_for_url(r);
1091
1092     if (ap_is_default_port(port, r)) {
1093         return apr_pstrcat(p, ap_http_scheme(r), "://", host, uri, NULL);
1094     }
1095
1096     return apr_psprintf(p, "%s://%s:%u%s", ap_http_scheme(r), host, port, uri);
1097 }
1098
1099 AP_DECLARE(apr_off_t) ap_get_limit_req_body(const request_rec *r)
1100 {
1101     core_dir_config *d =
1102       (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
1103
1104     if (d->limit_req_body == AP_LIMIT_REQ_BODY_UNSET) {
1105         return AP_DEFAULT_LIMIT_REQ_BODY;
1106     }
1107
1108     return d->limit_req_body;
1109 }
1110
1111
1112 /*****************************************************************
1113  *
1114  * Commands... this module handles almost all of the NCSA httpd.conf
1115  * commands, but most of the old srm.conf is in the the modules.
1116  */
1117
1118
1119 /* returns a parent if it matches the given directive */
1120 static const ap_directive_t * find_parent(const ap_directive_t *dirp,
1121                                           const char *what)
1122 {
1123     while (dirp->parent != NULL) {
1124         dirp = dirp->parent;
1125
1126         /* ### it would be nice to have atom-ized directives */
1127         if (strcasecmp(dirp->directive, what) == 0)
1128             return dirp;
1129     }
1130
1131     return NULL;
1132 }
1133
1134 AP_DECLARE(const char *) ap_check_cmd_context(cmd_parms *cmd,
1135                                               unsigned forbidden)
1136 {
1137     const char *gt = (cmd->cmd->name[0] == '<'
1138                       && cmd->cmd->name[strlen(cmd->cmd->name)-1] != '>')
1139                          ? ">" : "";
1140     const ap_directive_t *found;
1141
1142     if ((forbidden & NOT_IN_VIRTUALHOST) && cmd->server->is_virtual) {
1143         return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1144                            " cannot occur within <VirtualHost> section", NULL);
1145     }
1146
1147     if ((forbidden & (NOT_IN_LIMIT | NOT_IN_DIR_LOC_FILE))
1148         && cmd->limited != -1) {
1149         return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1150                            " cannot occur within <Limit> or <LimitExcept> "
1151                            "section", NULL);
1152     }
1153
1154     if ((forbidden & NOT_IN_HTACCESS) && (cmd->pool == cmd->temp_pool)) {
1155          return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1156                             " cannot occur within htaccess files", NULL);
1157     }
1158
1159     if ((forbidden & NOT_IN_DIR_LOC_FILE) == NOT_IN_DIR_LOC_FILE) {
1160         if (cmd->path != NULL) {
1161             return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1162                             " cannot occur within <Directory/Location/Files> "
1163                             "section", NULL);
1164         }
1165         if (cmd->cmd->req_override & EXEC_ON_READ) {
1166             /* EXEC_ON_READ must be NOT_IN_DIR_LOC_FILE, if not, it will
1167              * (deliberately) segfault below in the individual tests...
1168              */
1169             return NULL;
1170         }
1171     }
1172
1173     if (((forbidden & NOT_IN_DIRECTORY)
1174          && ((found = find_parent(cmd->directive, "<Directory"))
1175              || (found = find_parent(cmd->directive, "<DirectoryMatch"))))
1176         || ((forbidden & NOT_IN_LOCATION)
1177             && ((found = find_parent(cmd->directive, "<Location"))
1178                 || (found = find_parent(cmd->directive, "<LocationMatch"))))
1179         || ((forbidden & NOT_IN_FILES)
1180             && ((found = find_parent(cmd->directive, "<Files"))
1181                 || (found = find_parent(cmd->directive, "<FilesMatch"))
1182                 || (found = find_parent(cmd->directive, "<If"))
1183                 || (found = find_parent(cmd->directive, "<ElseIf"))
1184                 || (found = find_parent(cmd->directive, "<Else"))))) {
1185         return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1186                            " cannot occur within ", found->directive,
1187                            "> section", NULL);
1188     }
1189
1190     return NULL;
1191 }
1192
1193 static const char *set_access_name(cmd_parms *cmd, void *dummy,
1194                                    const char *arg)
1195 {
1196     void *sconf = cmd->server->module_config;
1197     core_server_config *conf = ap_get_core_module_config(sconf);
1198
1199     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
1200     if (err != NULL) {
1201         return err;
1202     }
1203
1204     conf->access_name = apr_pstrdup(cmd->pool, arg);
1205     return NULL;
1206 }
1207
1208 AP_DECLARE(const char *) ap_resolve_env(apr_pool_t *p, const char * word)
1209 {
1210 # define SMALL_EXPANSION 5
1211     struct sll {
1212         struct sll *next;
1213         const char *string;
1214         apr_size_t len;
1215     } *result, *current, sresult[SMALL_EXPANSION];
1216     char *res_buf, *cp;
1217     const char *s, *e, *ep;
1218     unsigned spc;
1219     apr_size_t outlen;
1220
1221     s = ap_strchr_c(word, '$');
1222     if (!s) {
1223         return word;
1224     }
1225
1226     /* well, actually something to do */
1227     ep = word + strlen(word);
1228     spc = 0;
1229     result = current = &(sresult[spc++]);
1230     current->next = NULL;
1231     current->string = word;
1232     current->len = s - word;
1233     outlen = current->len;
1234
1235     do {
1236         /* prepare next entry */
1237         if (current->len) {
1238             current->next = (spc < SMALL_EXPANSION)
1239                             ? &(sresult[spc++])
1240                             : (struct sll *)apr_palloc(p,
1241                                                        sizeof(*current->next));
1242             current = current->next;
1243             current->next = NULL;
1244             current->len = 0;
1245         }
1246
1247         if (*s == '$') {
1248             if (s[1] == '{' && (e = ap_strchr_c(s, '}'))) {
1249                 char *name = apr_pstrndup(p, s+2, e-s-2);
1250                 word = NULL;
1251                 if (server_config_defined_vars)
1252                     word = apr_table_get(server_config_defined_vars, name);
1253                 if (!word)
1254                     word = getenv(name);
1255                 if (word) {
1256                     current->string = word;
1257                     current->len = strlen(word);
1258                     outlen += current->len;
1259                 }
1260                 else {
1261                     if (ap_strchr(name, ':') == 0)
1262                         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, NULL, APLOGNO(00111)
1263                                      "Config variable ${%s} is not defined",
1264                                      name);
1265                     current->string = s;
1266                     current->len = e - s + 1;
1267                     outlen += current->len;
1268                 }
1269                 s = e + 1;
1270             }
1271             else {
1272                 current->string = s++;
1273                 current->len = 1;
1274                 ++outlen;
1275             }
1276         }
1277         else {
1278             word = s;
1279             s = ap_strchr_c(s, '$');
1280             current->string = word;
1281             current->len = s ? s - word : ep - word;
1282             outlen += current->len;
1283         }
1284     } while (s && *s);
1285
1286     /* assemble result */
1287     res_buf = cp = apr_palloc(p, outlen + 1);
1288     do {
1289         if (result->len) {
1290             memcpy(cp, result->string, result->len);
1291             cp += result->len;
1292         }
1293         result = result->next;
1294     } while (result);
1295     res_buf[outlen] = '\0';
1296
1297     return res_buf;
1298 }
1299
1300 static int reset_config_defines(void *dummy)
1301 {
1302     ap_server_config_defines = saved_server_config_defines;
1303     server_config_defined_vars = NULL;
1304     return OK;
1305 }
1306
1307 /*
1308  * Make sure we can revert the effects of Define/UnDefine when restarting.
1309  * This function must be called once per loading of the config, before
1310  * ap_server_config_defines is changed. This may be during reading of the
1311  * config, which is even before the pre_config hook is run (due to
1312  * EXEC_ON_READ for Define/UnDefine).
1313  */
1314 static void init_config_defines(apr_pool_t *pconf)
1315 {
1316     saved_server_config_defines = ap_server_config_defines;
1317     /* Use apr_array_copy instead of apr_array_copy_hdr because it does not
1318      * protect from the way unset_define removes entries.
1319      */
1320     ap_server_config_defines = apr_array_copy(pconf, ap_server_config_defines);
1321 }
1322
1323 static const char *set_define(cmd_parms *cmd, void *dummy,
1324                               const char *name, const char *value)
1325 {
1326     const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS);
1327     if (err)
1328         return err;
1329     if (ap_strchr_c(name, ':') != NULL)
1330         return "Variable name must not contain ':'";
1331
1332     if (!saved_server_config_defines)
1333         init_config_defines(cmd->pool);
1334     if (!ap_exists_config_define(name)) {
1335         char **newv = (char **)apr_array_push(ap_server_config_defines);
1336         *newv = apr_pstrdup(cmd->pool, name);
1337     }
1338     if (value) {
1339         if (!server_config_defined_vars)
1340             server_config_defined_vars = apr_table_make(cmd->pool, 5);
1341         apr_table_setn(server_config_defined_vars, name, value);
1342     }
1343
1344     return NULL;
1345 }
1346
1347 static const char *unset_define(cmd_parms *cmd, void *dummy,
1348                                 const char *name)
1349 {
1350     int i;
1351     char **defines;
1352     const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS);
1353     if (err)
1354         return err;
1355     if (ap_strchr_c(name, ':') != NULL)
1356         return "Variable name must not contain ':'";
1357
1358     if (!saved_server_config_defines)
1359         init_config_defines(cmd->pool);
1360
1361     defines = (char **)ap_server_config_defines->elts;
1362     for (i = 0; i < ap_server_config_defines->nelts; i++) {
1363         if (strcmp(defines[i], name) == 0) {
1364             defines[i] = apr_array_pop(ap_server_config_defines);
1365             break;
1366         }
1367     }
1368
1369     if (server_config_defined_vars) {
1370         apr_table_unset(server_config_defined_vars, name);
1371     }
1372
1373     return NULL;
1374 }
1375
1376 static const char *generate_message(cmd_parms *cmd, void *dummy,
1377                                     const char *arg)
1378 {
1379     /* cast with 64-bit warning avoidance */
1380     int level = (cmd->info==(void*)APLOG_ERR)? APLOG_ERR: APLOG_WARNING;
1381     char * msg;
1382
1383     /* get position information from wherever we can? */
1384     ap_configfile_t * cf = cmd->config_file;
1385     ap_directive_t const * ed1 = cmd->directive;
1386     ap_directive_t const * ed2 = cmd->err_directive;
1387
1388     /* expect an argument */
1389     if (!arg || !*arg) {
1390         return "The Error or Warning directive was used with no message.";
1391     }
1392
1393     /* set message, strip off quotes if necessary */
1394     msg = (char *)arg;
1395     if (*arg == '"' || *arg == '\'') {
1396         apr_size_t len = strlen(arg);
1397         char last = *(arg + len - 1);
1398
1399         if (*arg == last) {
1400             msg = apr_pstrndup(cmd->pool, arg + 1, len - 2);
1401         }
1402     }
1403
1404     /* generate error or warning with a configuration file position.
1405      * the log is displayed on the terminal as no log file is opened yet.
1406      */
1407     ap_log_error(APLOG_MARK, APLOG_NOERRNO|level, 0, NULL,
1408                  "%s on line %d of %s", msg,
1409                  cf? cf->line_number:
1410                    ed1? ed1->line_num:
1411                      ed2? ed2->line_num: -1,
1412                  cf? cf->name:
1413                    ed1? ed1->filename:
1414                      ed2? ed2->filename: "<UNKNOWN>");
1415
1416     /* message displayed above, return will stop configuration processing */
1417     return level==APLOG_ERR?
1418         "Configuration processing stopped by Error directive": NULL;
1419 }
1420
1421 #ifdef GPROF
1422 static const char *set_gprof_dir(cmd_parms *cmd, void *dummy, const char *arg)
1423 {
1424     void *sconf = cmd->server->module_config;
1425     core_server_config *conf = ap_get_core_module_config(sconf);
1426
1427     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
1428     if (err != NULL) {
1429         return err;
1430     }
1431
1432     conf->gprof_dir = arg;
1433     return NULL;
1434 }
1435 #endif /*GPROF*/
1436
1437 static const char *set_add_default_charset(cmd_parms *cmd,
1438                                            void *d_, const char *arg)
1439 {
1440     core_dir_config *d = d_;
1441
1442     if (!strcasecmp(arg, "Off")) {
1443        d->add_default_charset = ADD_DEFAULT_CHARSET_OFF;
1444     }
1445     else if (!strcasecmp(arg, "On")) {
1446        d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1447        d->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
1448     }
1449     else {
1450        d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1451        d->add_default_charset_name = arg;
1452     }
1453
1454     return NULL;
1455 }
1456
1457 static const char *set_document_root(cmd_parms *cmd, void *dummy,
1458                                      const char *arg)
1459 {
1460     void *sconf = cmd->server->module_config;
1461     core_server_config *conf = ap_get_core_module_config(sconf);
1462
1463     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
1464     if (err != NULL) {
1465         return err;
1466     }
1467
1468     /* When ap_document_root_check is false; skip all the stuff below */
1469     if (!ap_document_root_check) {
1470        conf->ap_document_root = arg;
1471        return NULL;
1472     }
1473
1474     /* Make it absolute, relative to ServerRoot */
1475     arg = ap_server_root_relative(cmd->pool, arg);
1476     if (arg == NULL) {
1477         return "DocumentRoot must be a directory";
1478     }
1479
1480     /* TODO: ap_configtestonly */
1481     if (apr_filepath_merge((char**)&conf->ap_document_root, NULL, arg,
1482                            APR_FILEPATH_TRUENAME, cmd->pool) != APR_SUCCESS
1483         || !ap_is_directory(cmd->pool, arg)) {
1484         if (cmd->server->is_virtual) {
1485             ap_log_perror(APLOG_MARK, APLOG_STARTUP, 0,
1486                           cmd->pool, APLOGNO(00112)
1487                           "Warning: DocumentRoot [%s] does not exist",
1488                           arg);
1489             conf->ap_document_root = arg;
1490         }
1491         else {
1492             return apr_psprintf(cmd->pool, 
1493                                 "DocumentRoot '%s' is not a directory, or is not readable",
1494                                 arg);
1495         }
1496     }
1497     return NULL;
1498 }
1499
1500 AP_DECLARE(void) ap_custom_response(request_rec *r, int status,
1501                                     const char *string)
1502 {
1503     core_request_config *conf = ap_get_core_module_config(r->request_config);
1504     int idx;
1505
1506     if (conf->response_code_strings == NULL) {
1507         conf->response_code_strings =
1508             apr_pcalloc(r->pool,
1509                         sizeof(*conf->response_code_strings) * RESPONSE_CODES);
1510     }
1511
1512     idx = ap_index_of_response(status);
1513
1514     conf->response_code_strings[idx] =
1515        ((ap_is_url(string) || (*string == '/')) && (*string != '"')) ?
1516        apr_pstrdup(r->pool, string) : apr_pstrcat(r->pool, "\"", string, NULL);
1517 }
1518
1519 static const char *set_error_document(cmd_parms *cmd, void *conf_,
1520                                       const char *errno_str, const char *msg)
1521 {
1522     core_dir_config *conf = conf_;
1523     int error_number, index_number, idx500;
1524     enum { MSG, LOCAL_PATH, REMOTE_PATH } what = MSG;
1525
1526     /* 1st parameter should be a 3 digit number, which we recognize;
1527      * convert it into an array index
1528      */
1529     error_number = atoi(errno_str);
1530     idx500 = ap_index_of_response(HTTP_INTERNAL_SERVER_ERROR);
1531
1532     if (error_number == HTTP_INTERNAL_SERVER_ERROR) {
1533         index_number = idx500;
1534     }
1535     else if ((index_number = ap_index_of_response(error_number)) == idx500) {
1536         return apr_pstrcat(cmd->pool, "Unsupported HTTP response code ",
1537                            errno_str, NULL);
1538     }
1539
1540     /* Heuristic to determine second argument. */
1541     if (ap_strchr_c(msg,' '))
1542         what = MSG;
1543     else if (msg[0] == '/')
1544         what = LOCAL_PATH;
1545     else if (ap_is_url(msg))
1546         what = REMOTE_PATH;
1547     else
1548         what = MSG;
1549
1550     /* The entry should be ignored if it is a full URL for a 401 error */
1551
1552     if (error_number == 401 && what == REMOTE_PATH) {
1553         ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, cmd->server, APLOGNO(00113)
1554                      "%s:%d cannot use a full URL in a 401 ErrorDocument "
1555                      "directive --- ignoring!", cmd->directive->filename, cmd->directive->line_num);
1556     }
1557     else { /* Store it... */
1558         if (conf->response_code_strings == NULL) {
1559             conf->response_code_strings =
1560                 apr_pcalloc(cmd->pool,
1561                             sizeof(*conf->response_code_strings) *
1562                             RESPONSE_CODES);
1563         }
1564
1565         if (strcasecmp(msg, "default") == 0) {
1566             /* special case: ErrorDocument 404 default restores the
1567              * canned server error response
1568              */
1569             conf->response_code_strings[index_number] = &errordocument_default;
1570         }
1571         else {
1572             /* hack. Prefix a " if it is a msg; as that is what
1573              * http_protocol.c relies on to distinguish between
1574              * a msg and a (local) path.
1575              */
1576             conf->response_code_strings[index_number] = (what == MSG) ?
1577                     apr_pstrcat(cmd->pool, "\"", msg, NULL) :
1578                     apr_pstrdup(cmd->pool, msg);
1579         }
1580     }
1581
1582     return NULL;
1583 }
1584
1585 static const char *set_allow_opts(cmd_parms *cmd, allow_options_t *opts,
1586                                   const char *l)
1587 {
1588     allow_options_t opt;
1589     int first = 1;
1590
1591     char *w, *p = (char *) l;
1592     char *tok_state;
1593
1594     while ((w = apr_strtok(p, ",", &tok_state)) != NULL) {
1595
1596         if (first) {
1597             p = NULL;
1598             *opts = OPT_NONE;
1599             first = 0;
1600         }
1601
1602         if (!strcasecmp(w, "Indexes")) {
1603             opt = OPT_INDEXES;
1604         }
1605         else if (!strcasecmp(w, "Includes")) {
1606             /* If Includes is permitted, both Includes and
1607              * IncludesNOEXEC may be changed. */
1608             opt = (OPT_INCLUDES | OPT_INC_WITH_EXEC);
1609         }
1610         else if (!strcasecmp(w, "IncludesNOEXEC")) {
1611             opt = OPT_INCLUDES;
1612         }
1613         else if (!strcasecmp(w, "FollowSymLinks")) {
1614             opt = OPT_SYM_LINKS;
1615         }
1616         else if (!strcasecmp(w, "SymLinksIfOwnerMatch")) {
1617             opt = OPT_SYM_OWNER;
1618         }
1619         else if (!strcasecmp(w, "ExecCGI")) {
1620             opt = OPT_EXECCGI;
1621         }
1622         else if (!strcasecmp(w, "MultiViews")) {
1623             opt = OPT_MULTI;
1624         }
1625         else if (!strcasecmp(w, "RunScripts")) { /* AI backcompat. Yuck */
1626             opt = OPT_MULTI|OPT_EXECCGI;
1627         }
1628         else if (!strcasecmp(w, "None")) {
1629             opt = OPT_NONE;
1630         }
1631         else if (!strcasecmp(w, "All")) {
1632             opt = OPT_ALL;
1633         }
1634         else {
1635             return apr_pstrcat(cmd->pool, "Illegal option ", w, NULL);
1636         }
1637
1638         *opts |= opt;
1639     }
1640
1641     (*opts) &= (~OPT_UNSET);
1642
1643     return NULL;
1644 }
1645
1646 static const char *set_override(cmd_parms *cmd, void *d_, const char *l)
1647 {
1648     core_dir_config *d = d_;
1649     char *w;
1650     char *k, *v;
1651     const char *err;
1652
1653     /* Throw a warning if we're in <Location> or <Files> */
1654     if (ap_check_cmd_context(cmd, NOT_IN_LOCATION | NOT_IN_FILES)) {
1655         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server, APLOGNO(00114)
1656                      "Useless use of AllowOverride in line %d of %s.",
1657                      cmd->directive->line_num, cmd->directive->filename);
1658     }
1659     if ((err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS)) != NULL)
1660         return err;
1661
1662     d->override = OR_NONE;
1663     while (l[0]) {
1664         w = ap_getword_conf(cmd->temp_pool, &l);
1665
1666         k = w;
1667         v = strchr(k, '=');
1668         if (v) {
1669                 *v++ = '\0';
1670         }
1671
1672         if (!strcasecmp(w, "Limit")) {
1673             d->override |= OR_LIMIT;
1674         }
1675         else if (!strcasecmp(k, "Options")) {
1676             d->override |= OR_OPTIONS;
1677             if (v)
1678                 set_allow_opts(cmd, &(d->override_opts), v);
1679             else
1680                 d->override_opts = OPT_ALL;
1681         }
1682         else if (!strcasecmp(w, "FileInfo")) {
1683             d->override |= OR_FILEINFO;
1684         }
1685         else if (!strcasecmp(w, "AuthConfig")) {
1686             d->override |= OR_AUTHCFG;
1687         }
1688         else if (!strcasecmp(w, "Indexes")) {
1689             d->override |= OR_INDEXES;
1690         }
1691         else if (!strcasecmp(w, "Nonfatal")) {
1692             if (!strcasecmp(v, "Override")) {
1693                 d->override |= NONFATAL_OVERRIDE;
1694             }
1695             else if (!strcasecmp(v, "Unknown")) {
1696                 d->override |= NONFATAL_UNKNOWN;
1697             }
1698             else if (!strcasecmp(v, "All")) {
1699                 d->override |= NONFATAL_ALL;
1700             }
1701         }
1702         else if (!strcasecmp(w, "None")) {
1703             d->override = OR_NONE;
1704         }
1705         else if (!strcasecmp(w, "All")) {
1706             d->override = OR_ALL;
1707         }
1708         else {
1709             return apr_pstrcat(cmd->pool, "Illegal override option ", w, NULL);
1710         }
1711
1712         d->override &= ~OR_UNSET;
1713     }
1714
1715     return NULL;
1716 }
1717
1718 static const char *set_override_list(cmd_parms *cmd, void *d_, int argc, char *const argv[])
1719 {
1720     core_dir_config *d = d_;
1721     int i;
1722     const char *err;
1723
1724     /* Throw a warning if we're in <Location> or <Files> */
1725     if (ap_check_cmd_context(cmd, NOT_IN_LOCATION | NOT_IN_FILES)) {
1726         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server, APLOGNO(00115)
1727                      "Useless use of AllowOverrideList at %s:%d",
1728                      cmd->directive->filename, cmd->directive->line_num);
1729     }
1730     if ((err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS)) != NULL)
1731         return err;
1732
1733     d->override_list = apr_table_make(cmd->pool, argc);
1734
1735     for (i=0;i<argc;i++){
1736         if (!strcasecmp(argv[i], "None")) {
1737             if (argc != 1) {
1738                 return "'None' not allowed with other directives in "
1739                        "AllowOverrideList";
1740             }
1741             return NULL;
1742         }
1743         else {
1744             const command_rec *result = NULL;
1745             module *mod = ap_top_module;
1746             result = ap_find_command_in_modules(argv[i], &mod);
1747             if (result == NULL) {
1748                 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
1749                              APLOGNO(00116) "Discarding unrecognized "
1750                              "directive `%s' in AllowOverrideList at %s:%d",
1751                              argv[i], cmd->directive->filename,
1752                              cmd->directive->line_num);
1753                 continue;
1754             }
1755             else if ((result->req_override & (OR_ALL|ACCESS_CONF)) == 0) {
1756                 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
1757                              APLOGNO(02304) "Discarding directive `%s' not "
1758                              "allowed in AllowOverrideList at %s:%d",
1759                              argv[i], cmd->directive->filename,
1760                              cmd->directive->line_num);
1761                 continue;
1762             }
1763             else {
1764                 apr_table_set(d->override_list, argv[i], "1");
1765             }
1766         }
1767     }
1768
1769     return NULL;
1770 }
1771
1772 static const char *set_options(cmd_parms *cmd, void *d_, const char *l)
1773 {
1774     core_dir_config *d = d_;
1775     allow_options_t opt;
1776     int first = 1;
1777     int merge = 0;
1778     int all_none = 0;
1779     char action;
1780
1781     while (l[0]) {
1782         char *w = ap_getword_conf(cmd->temp_pool, &l);
1783         action = '\0';
1784
1785         if (*w == '+' || *w == '-') {
1786             action = *(w++);
1787             if (!merge && !first && !all_none) {
1788                 return "Either all Options must start with + or -, or no Option may.";
1789             }
1790             merge = 1;
1791         }
1792         else if (first) {
1793             d->opts = OPT_NONE;
1794         }
1795         else if (merge) {
1796             return "Either all Options must start with + or -, or no Option may.";
1797         }
1798
1799         if (!strcasecmp(w, "Indexes")) {
1800             opt = OPT_INDEXES;
1801         }
1802         else if (!strcasecmp(w, "Includes")) {
1803             opt = (OPT_INCLUDES | OPT_INC_WITH_EXEC);
1804         }
1805         else if (!strcasecmp(w, "IncludesNOEXEC")) {
1806             opt = OPT_INCLUDES;
1807         }
1808         else if (!strcasecmp(w, "FollowSymLinks")) {
1809             opt = OPT_SYM_LINKS;
1810         }
1811         else if (!strcasecmp(w, "SymLinksIfOwnerMatch")) {
1812             opt = OPT_SYM_OWNER;
1813         }
1814         else if (!strcasecmp(w, "ExecCGI")) {
1815             opt = OPT_EXECCGI;
1816         }
1817         else if (!strcasecmp(w, "MultiViews")) {
1818             opt = OPT_MULTI;
1819         }
1820         else if (!strcasecmp(w, "RunScripts")) { /* AI backcompat. Yuck */
1821             opt = OPT_MULTI|OPT_EXECCGI;
1822         }
1823         else if (!strcasecmp(w, "None")) {
1824             if (!first) {
1825                 return "'Options None' must be the first Option given.";
1826             }
1827             else if (merge) { /* Only works since None may not follow any other option. */
1828                 return "You may not use 'Options +None' or 'Options -None'.";
1829             }
1830             opt = OPT_NONE;
1831             all_none = 1;
1832         }
1833         else if (!strcasecmp(w, "All")) {
1834             if (!first) {
1835                 return "'Options All' must be the first option given.";
1836             }
1837             else if (merge) { /* Only works since All may not follow any other option. */
1838                 return "You may not use 'Options +All' or 'Options -All'.";
1839             }
1840             opt = OPT_ALL;
1841             all_none = 1;
1842         }
1843         else {
1844             return apr_pstrcat(cmd->pool, "Illegal option ", w, NULL);
1845         }
1846
1847         if ( (cmd->override_opts & opt) != opt ) {
1848             return apr_pstrcat(cmd->pool, "Option ", w, " not allowed here", NULL);
1849         }
1850         else if (action == '-') {
1851             /* we ensure the invariant (d->opts_add & d->opts_remove) == 0 */
1852             d->opts_remove |= opt;
1853             d->opts_add &= ~opt;
1854             d->opts &= ~opt;
1855         }
1856         else if (action == '+') {
1857             d->opts_add |= opt;
1858             d->opts_remove &= ~opt;
1859             d->opts |= opt;
1860         }
1861         else {
1862             d->opts |= opt;
1863         }
1864
1865         first = 0;
1866     }
1867
1868     return NULL;
1869 }
1870
1871 static const char *set_default_type(cmd_parms *cmd, void *d_,
1872                                    const char *arg)
1873 {
1874     if ((strcasecmp(arg, "off") != 0) && (strcasecmp(arg, "none") != 0)) {
1875         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server, APLOGNO(00117)
1876               "Ignoring deprecated use of DefaultType in line %d of %s.",
1877                      cmd->directive->line_num, cmd->directive->filename);
1878     }
1879
1880     return NULL;
1881 }
1882
1883 /*
1884  * Note what data should be used when forming file ETag values.
1885  * It would be nicer to do this as an ITERATE, but then we couldn't
1886  * remember the +/- state properly.
1887  */
1888 static const char *set_etag_bits(cmd_parms *cmd, void *mconfig,
1889                                  const char *args_p)
1890 {
1891     core_dir_config *cfg;
1892     etag_components_t bit;
1893     char action;
1894     char *token;
1895     const char *args;
1896     int valid;
1897     int first;
1898     int explicit;
1899
1900     cfg = (core_dir_config *)mconfig;
1901
1902     args = args_p;
1903     first = 1;
1904     explicit = 0;
1905     while (args[0] != '\0') {
1906         action = '*';
1907         bit = ETAG_UNSET;
1908         valid = 1;
1909         token = ap_getword_conf(cmd->temp_pool, &args);
1910         if ((*token == '+') || (*token == '-')) {
1911             action = *token;
1912             token++;
1913         }
1914         else {
1915             /*
1916              * The occurrence of an absolute setting wipes
1917              * out any previous relative ones.  The first such
1918              * occurrence forgets any inherited ones, too.
1919              */
1920             if (first) {
1921                 cfg->etag_bits = ETAG_UNSET;
1922                 cfg->etag_add = ETAG_UNSET;
1923                 cfg->etag_remove = ETAG_UNSET;
1924                 first = 0;
1925             }
1926         }
1927
1928         if (strcasecmp(token, "None") == 0) {
1929             if (action != '*') {
1930                 valid = 0;
1931             }
1932             else {
1933                 cfg->etag_bits = bit = ETAG_NONE;
1934                 explicit = 1;
1935             }
1936         }
1937         else if (strcasecmp(token, "All") == 0) {
1938             if (action != '*') {
1939                 valid = 0;
1940             }
1941             else {
1942                 explicit = 1;
1943                 cfg->etag_bits = bit = ETAG_ALL;
1944             }
1945         }
1946         else if (strcasecmp(token, "Size") == 0) {
1947             bit = ETAG_SIZE;
1948         }
1949         else if ((strcasecmp(token, "LMTime") == 0)
1950                  || (strcasecmp(token, "MTime") == 0)
1951                  || (strcasecmp(token, "LastModified") == 0)) {
1952             bit = ETAG_MTIME;
1953         }
1954         else if (strcasecmp(token, "INode") == 0) {
1955             bit = ETAG_INODE;
1956         }
1957         else {
1958             return apr_pstrcat(cmd->pool, "Unknown keyword '",
1959                                token, "' for ", cmd->cmd->name,
1960                                " directive", NULL);
1961         }
1962
1963         if (! valid) {
1964             return apr_pstrcat(cmd->pool, cmd->cmd->name, " keyword '",
1965                                token, "' cannot be used with '+' or '-'",
1966                                NULL);
1967         }
1968
1969         if (action == '+') {
1970             /*
1971              * Make sure it's in the 'add' list and absent from the
1972              * 'subtract' list.
1973              */
1974             cfg->etag_add |= bit;
1975             cfg->etag_remove &= (~ bit);
1976         }
1977         else if (action == '-') {
1978             cfg->etag_remove |= bit;
1979             cfg->etag_add &= (~ bit);
1980         }
1981         else {
1982             /*
1983              * Non-relative values wipe out any + or - values
1984              * accumulated so far.
1985              */
1986             cfg->etag_bits |= bit;
1987             cfg->etag_add = ETAG_UNSET;
1988             cfg->etag_remove = ETAG_UNSET;
1989             explicit = 1;
1990         }
1991     }
1992
1993     /*
1994      * Any setting at all will clear the 'None' and 'Unset' bits.
1995      */
1996
1997     if (cfg->etag_add != ETAG_UNSET) {
1998         cfg->etag_add &= (~ ETAG_UNSET);
1999     }
2000
2001     if (cfg->etag_remove != ETAG_UNSET) {
2002         cfg->etag_remove &= (~ ETAG_UNSET);
2003     }
2004
2005     if (explicit) {
2006         cfg->etag_bits &= (~ ETAG_UNSET);
2007
2008         if ((cfg->etag_bits & ETAG_NONE) != ETAG_NONE) {
2009             cfg->etag_bits &= (~ ETAG_NONE);
2010         }
2011     }
2012
2013     return NULL;
2014 }
2015
2016 static const char *set_enable_mmap(cmd_parms *cmd, void *d_,
2017                                    const char *arg)
2018 {
2019     core_dir_config *d = d_;
2020
2021     if (strcasecmp(arg, "on") == 0) {
2022         d->enable_mmap = ENABLE_MMAP_ON;
2023     }
2024     else if (strcasecmp(arg, "off") == 0) {
2025         d->enable_mmap = ENABLE_MMAP_OFF;
2026     }
2027     else {
2028         return "parameter must be 'on' or 'off'";
2029     }
2030
2031     return NULL;
2032 }
2033
2034 static const char *set_enable_sendfile(cmd_parms *cmd, void *d_,
2035                                    const char *arg)
2036 {
2037     core_dir_config *d = d_;
2038
2039     if (strcasecmp(arg, "on") == 0) {
2040         d->enable_sendfile = ENABLE_SENDFILE_ON;
2041     }
2042     else if (strcasecmp(arg, "off") == 0) {
2043         d->enable_sendfile = ENABLE_SENDFILE_OFF;
2044     }
2045     else {
2046         return "parameter must be 'on' or 'off'";
2047     }
2048
2049     return NULL;
2050 }
2051
2052
2053 /*
2054  * Report a missing-'>' syntax error.
2055  */
2056 static char *unclosed_directive(cmd_parms *cmd)
2057 {
2058     return apr_pstrcat(cmd->pool, cmd->cmd->name,
2059                        "> directive missing closing '>'", NULL);
2060 }
2061
2062 /*
2063  * Report a missing args in '<Foo >' syntax error.
2064  */
2065 static char *missing_container_arg(cmd_parms *cmd)
2066 {
2067     return apr_pstrcat(cmd->pool, cmd->cmd->name,
2068                        "> directive requires additional arguments", NULL);
2069 }
2070
2071 AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd,
2072                                                       void *dummy,
2073                                                       const char *arg)
2074 {
2075     const char *endp = ap_strrchr_c(arg, '>');
2076     const char *limited_methods;
2077     void *tog = cmd->cmd->cmd_data;
2078     apr_int64_t limited = 0;
2079     apr_int64_t old_limited = cmd->limited;
2080     const char *errmsg;
2081
2082     if (endp == NULL) {
2083         return unclosed_directive(cmd);
2084     }
2085
2086     limited_methods = apr_pstrndup(cmd->temp_pool, arg, endp - arg);
2087
2088     if (!limited_methods[0]) {
2089         return missing_container_arg(cmd);
2090     }
2091
2092     while (limited_methods[0]) {
2093         char *method = ap_getword_conf(cmd->temp_pool, &limited_methods);
2094         int methnum;
2095
2096         /* check for builtin or module registered method number */
2097         methnum = ap_method_number_of(method);
2098
2099         if (methnum == M_TRACE && !tog) {
2100             return "TRACE cannot be controlled by <Limit>, see TraceEnable";
2101         }
2102         else if (methnum == M_INVALID) {
2103             /* method has not been registered yet, but resorce restriction
2104              * is always checked before method handling, so register it.
2105              */
2106             methnum = ap_method_register(cmd->pool,
2107                                          apr_pstrdup(cmd->pool, method));
2108         }
2109
2110         limited |= (AP_METHOD_BIT << methnum);
2111     }
2112
2113     /* Killing two features with one function,
2114      * if (tog == NULL) <Limit>, else <LimitExcept>
2115      */
2116     limited = tog ? ~limited : limited;
2117
2118     if (!(old_limited & limited)) {
2119         return apr_pstrcat(cmd->pool, cmd->cmd->name,
2120                            "> directive excludes all methods", NULL);
2121     }
2122     else if ((old_limited & limited) == old_limited) {
2123         return apr_pstrcat(cmd->pool, cmd->cmd->name,
2124                            "> directive specifies methods already excluded",
2125                            NULL);
2126     }
2127
2128     cmd->limited &= limited;
2129
2130     errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context);
2131
2132     cmd->limited = old_limited;
2133
2134     return errmsg;
2135 }
2136
2137 /* XXX: Bogus - need to do this differently (at least OS2/Netware suffer
2138  * the same problem!!!
2139  * We use this in <DirectoryMatch> and <FilesMatch>, to ensure that
2140  * people don't get bitten by wrong-cased regex matches
2141  */
2142
2143 #ifdef WIN32
2144 #define USE_ICASE AP_REG_ICASE
2145 #else
2146 #define USE_ICASE 0
2147 #endif
2148
2149 static const char *dirsection(cmd_parms *cmd, void *mconfig, const char *arg)
2150 {
2151     const char *errmsg;
2152     const char *endp = ap_strrchr_c(arg, '>');
2153     int old_overrides = cmd->override;
2154     char *old_path = cmd->path;
2155     core_dir_config *conf;
2156     ap_conf_vector_t *new_dir_conf = ap_create_per_dir_config(cmd->pool);
2157     ap_regex_t *r = NULL;
2158     const command_rec *thiscmd = cmd->cmd;
2159
2160     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
2161     if (err != NULL) {
2162         return err;
2163     }
2164
2165     if (endp == NULL) {
2166         return unclosed_directive(cmd);
2167     }
2168
2169     arg = apr_pstrndup(cmd->temp_pool, arg, endp - arg);
2170
2171     if (!arg[0]) {
2172         return missing_container_arg(cmd);
2173     }
2174
2175     cmd->path = ap_getword_conf(cmd->pool, &arg);
2176     cmd->override = OR_ALL|ACCESS_CONF;
2177
2178     if (!strcmp(cmd->path, "~")) {
2179         cmd->path = ap_getword_conf(cmd->pool, &arg);
2180         if (!cmd->path)
2181             return "<Directory ~ > block must specify a path";
2182         r = ap_pregcomp(cmd->pool, cmd->path, AP_REG_EXTENDED|USE_ICASE);
2183         if (!r) {
2184             return "Regex could not be compiled";
2185         }
2186     }
2187     else if (thiscmd->cmd_data) { /* <DirectoryMatch> */
2188         r = ap_pregcomp(cmd->pool, cmd->path, AP_REG_EXTENDED|USE_ICASE);
2189         if (!r) {
2190             return "Regex could not be compiled";
2191         }
2192     }
2193     else if (!strcmp(cmd->path, "/") == 0)
2194     {
2195         char *newpath;
2196
2197         /*
2198          * Ensure that the pathname is canonical, and append the trailing /
2199          */
2200         apr_status_t rv = apr_filepath_merge(&newpath, NULL, cmd->path,
2201                                              APR_FILEPATH_TRUENAME, cmd->pool);
2202         if (rv != APR_SUCCESS && rv != APR_EPATHWILD) {
2203             return apr_pstrcat(cmd->pool, "<Directory \"", cmd->path,
2204                                "\"> path is invalid.", NULL);
2205         }
2206
2207         cmd->path = newpath;
2208         if (cmd->path[strlen(cmd->path) - 1] != '/')
2209             cmd->path = apr_pstrcat(cmd->pool, cmd->path, "/", NULL);
2210     }
2211
2212     /* initialize our config and fetch it */
2213     conf = ap_set_config_vectors(cmd->server, new_dir_conf, cmd->path,
2214                                  &core_module, cmd->pool);
2215
2216     errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_dir_conf);
2217     if (errmsg != NULL)
2218         return errmsg;
2219
2220     conf->r = r;
2221     conf->d = cmd->path;
2222     conf->d_is_fnmatch = (apr_fnmatch_test(conf->d) != 0);
2223
2224     if (r) {
2225         conf->refs = apr_array_make(cmd->pool, 8, sizeof(char *));
2226         ap_regname(r, conf->refs, AP_REG_MATCH, 1);
2227     }
2228
2229     /* Make this explicit - the "/" root has 0 elements, that is, we
2230      * will always merge it, and it will always sort and merge first.
2231      * All others are sorted and tested by the number of slashes.
2232      */
2233     if (strcmp(conf->d, "/") == 0)
2234         conf->d_components = 0;
2235     else
2236         conf->d_components = ap_count_dirs(conf->d);
2237
2238     ap_add_per_dir_conf(cmd->server, new_dir_conf);
2239
2240     if (*arg != '\0') {
2241         return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
2242                            "> arguments not (yet) supported.", NULL);
2243     }
2244
2245     cmd->path = old_path;
2246     cmd->override = old_overrides;
2247
2248     return NULL;
2249 }
2250
2251 static const char *urlsection(cmd_parms *cmd, void *mconfig, const char *arg)
2252 {
2253     const char *errmsg;
2254     const char *endp = ap_strrchr_c(arg, '>');
2255     int old_overrides = cmd->override;
2256     char *old_path = cmd->path;
2257     core_dir_config *conf;
2258     ap_regex_t *r = NULL;
2259     const command_rec *thiscmd = cmd->cmd;
2260     ap_conf_vector_t *new_url_conf = ap_create_per_dir_config(cmd->pool);
2261     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
2262     if (err != NULL) {
2263         return err;
2264     }
2265
2266     if (endp == NULL) {
2267         return unclosed_directive(cmd);
2268     }
2269
2270     arg = apr_pstrndup(cmd->temp_pool, arg, endp - arg);
2271
2272     if (!arg[0]) {
2273         return missing_container_arg(cmd);
2274     }
2275
2276     cmd->path = ap_getword_conf(cmd->pool, &arg);
2277     cmd->override = OR_ALL|ACCESS_CONF;
2278
2279     if (thiscmd->cmd_data) { /* <LocationMatch> */
2280         r = ap_pregcomp(cmd->pool, cmd->path, AP_REG_EXTENDED);
2281         if (!r) {
2282             return "Regex could not be compiled";
2283         }
2284     }
2285     else if (!strcmp(cmd->path, "~")) {
2286         cmd->path = ap_getword_conf(cmd->pool, &arg);
2287         r = ap_pregcomp(cmd->pool, cmd->path, AP_REG_EXTENDED);
2288         if (!r) {
2289             return "Regex could not be compiled";
2290         }
2291     }
2292
2293     /* initialize our config and fetch it */
2294     conf = ap_set_config_vectors(cmd->server, new_url_conf, cmd->path,
2295                                  &core_module, cmd->pool);
2296
2297     errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_url_conf);
2298     if (errmsg != NULL)
2299         return errmsg;
2300
2301     conf->d = apr_pstrdup(cmd->pool, cmd->path);     /* No mangling, please */
2302     conf->d_is_fnmatch = apr_fnmatch_test(conf->d) != 0;
2303     conf->r = r;
2304
2305     if (r) {
2306         conf->refs = apr_array_make(cmd->pool, 8, sizeof(char *));
2307         ap_regname(r, conf->refs, AP_REG_MATCH, 1);
2308     }
2309
2310     ap_add_per_url_conf(cmd->server, new_url_conf);
2311
2312     if (*arg != '\0') {
2313         return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
2314                            "> arguments not (yet) supported.", NULL);
2315     }
2316
2317     cmd->path = old_path;
2318     cmd->override = old_overrides;
2319
2320     return NULL;
2321 }
2322
2323 static const char *filesection(cmd_parms *cmd, void *mconfig, const char *arg)
2324 {
2325     const char *errmsg;
2326     const char *endp = ap_strrchr_c(arg, '>');
2327     int old_overrides = cmd->override;
2328     char *old_path = cmd->path;
2329     core_dir_config *conf;
2330     ap_regex_t *r = NULL;
2331     const command_rec *thiscmd = cmd->cmd;
2332     ap_conf_vector_t *new_file_conf = ap_create_per_dir_config(cmd->pool);
2333     const char *err = ap_check_cmd_context(cmd,
2334                                            NOT_IN_LOCATION | NOT_IN_LIMIT);
2335
2336     if (err != NULL) {
2337         return err;
2338     }
2339
2340     if (endp == NULL) {
2341         return unclosed_directive(cmd);
2342     }
2343
2344     arg = apr_pstrndup(cmd->temp_pool, arg, endp - arg);
2345
2346     if (!arg[0]) {
2347         return missing_container_arg(cmd);
2348     }
2349
2350     cmd->path = ap_getword_conf(cmd->pool, &arg);
2351     /* Only if not an .htaccess file */
2352     if (!old_path) {
2353         cmd->override = OR_ALL|ACCESS_CONF;
2354     }
2355
2356     if (thiscmd->cmd_data) { /* <FilesMatch> */
2357         r = ap_pregcomp(cmd->pool, cmd->path, AP_REG_EXTENDED|USE_ICASE);
2358         if (!r) {
2359             return "Regex could not be compiled";
2360         }
2361     }
2362     else if (!strcmp(cmd->path, "~")) {
2363         cmd->path = ap_getword_conf(cmd->pool, &arg);
2364         r = ap_pregcomp(cmd->pool, cmd->path, AP_REG_EXTENDED|USE_ICASE);
2365         if (!r) {
2366             return "Regex could not be compiled";
2367         }
2368     }
2369     else {
2370         char *newpath;
2371         /* Ensure that the pathname is canonical, but we
2372          * can't test the case/aliases without a fixed path */
2373         if (apr_filepath_merge(&newpath, "", cmd->path,
2374                                0, cmd->pool) != APR_SUCCESS)
2375                 return apr_pstrcat(cmd->pool, "<Files \"", cmd->path,
2376                                "\"> is invalid.", NULL);
2377         cmd->path = newpath;
2378     }
2379
2380     /* initialize our config and fetch it */
2381     conf = ap_set_config_vectors(cmd->server, new_file_conf, cmd->path,
2382                                  &core_module, cmd->pool);
2383
2384     errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_file_conf);
2385     if (errmsg != NULL)
2386         return errmsg;
2387
2388     conf->d = cmd->path;
2389     conf->d_is_fnmatch = apr_fnmatch_test(conf->d) != 0;
2390     conf->r = r;
2391
2392     if (r) {
2393         conf->refs = apr_array_make(cmd->pool, 8, sizeof(char *));
2394         ap_regname(r, conf->refs, AP_REG_MATCH, 1);
2395     }
2396
2397     ap_add_file_conf(cmd->pool, (core_dir_config *)mconfig, new_file_conf);
2398
2399     if (*arg != '\0') {
2400         return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
2401                            "> arguments not (yet) supported.", NULL);
2402     }
2403
2404     cmd->path = old_path;
2405     cmd->override = old_overrides;
2406
2407     return NULL;
2408 }
2409
2410 #define COND_IF      ((void *)1)
2411 #define COND_ELSE    ((void *)2)
2412 #define COND_ELSEIF  ((void *)3)
2413
2414 static const char *ifsection(cmd_parms *cmd, void *mconfig, const char *arg)
2415 {
2416     const char *errmsg;
2417     const char *endp = ap_strrchr_c(arg, '>');
2418     int old_overrides = cmd->override;
2419     char *old_path = cmd->path;
2420     core_dir_config *conf;
2421     const command_rec *thiscmd = cmd->cmd;
2422     ap_conf_vector_t *new_if_conf = ap_create_per_dir_config(cmd->pool);
2423     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2424     const char *condition;
2425     const char *expr_err;
2426
2427     if (err != NULL) {
2428         return err;
2429     }
2430
2431     if (endp == NULL) {
2432         return unclosed_directive(cmd);
2433     }
2434
2435     arg = apr_pstrndup(cmd->temp_pool, arg, endp - arg);
2436
2437     /*
2438      * Set a dummy value so that other directives notice that they are inside
2439      * a config section.
2440      */
2441     cmd->path = "*If";
2442     /* Only if not an .htaccess file */
2443     if (!old_path) {
2444         cmd->override = OR_ALL|ACCESS_CONF;
2445     }
2446
2447     /* initialize our config and fetch it */
2448     conf = ap_set_config_vectors(cmd->server, new_if_conf, cmd->path,
2449                                  &core_module, cmd->pool);
2450
2451     if (cmd->cmd->cmd_data == COND_IF)
2452         conf->condition_ifelse = AP_CONDITION_IF;
2453     else if (cmd->cmd->cmd_data == COND_ELSEIF)
2454         conf->condition_ifelse = AP_CONDITION_ELSEIF;
2455     else if (cmd->cmd->cmd_data == COND_ELSE)
2456         conf->condition_ifelse = AP_CONDITION_ELSE;
2457     else
2458         ap_assert(0);
2459
2460     if (conf->condition_ifelse == AP_CONDITION_ELSE) {
2461         if (arg[0])
2462             return "<Else> does not take an argument";
2463     }
2464     else {
2465         if (!arg[0])
2466             return missing_container_arg(cmd);
2467         condition = ap_getword_conf(cmd->pool, &arg);
2468         conf->condition = ap_expr_parse_cmd(cmd, condition, 0, &expr_err, NULL);
2469         if (expr_err)
2470             return apr_psprintf(cmd->pool, "Cannot parse condition clause: %s",
2471                                 expr_err);
2472     }
2473
2474     errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_if_conf);
2475     if (errmsg != NULL)
2476         return errmsg;
2477
2478     conf->d = cmd->path;
2479     conf->d_is_fnmatch = 0;
2480     conf->r = NULL;
2481
2482     errmsg = ap_add_if_conf(cmd->pool, (core_dir_config *)mconfig, new_if_conf);
2483     if (errmsg != NULL)
2484         return errmsg;
2485
2486     if (*arg != '\0') {
2487         return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
2488                            "> arguments not supported.", NULL);
2489     }
2490
2491     cmd->path = old_path;
2492     cmd->override = old_overrides;
2493
2494     return NULL;
2495 }
2496
2497 static module *find_module(server_rec *s, const char *name)
2498 {
2499     module *found = ap_find_linked_module(name);
2500
2501     /* search prelinked stuff */
2502     if (!found) {
2503         ap_module_symbol_t *current = ap_prelinked_module_symbols;
2504
2505         for (; current->name; ++current) {
2506             if (!strcmp(current->name, name)) {
2507                 found = current->modp;
2508                 break;
2509             }
2510         }
2511     }
2512
2513     /* search dynamic stuff */
2514     if (!found) {
2515         APR_OPTIONAL_FN_TYPE(ap_find_loaded_module_symbol) *check_symbol =
2516             APR_RETRIEVE_OPTIONAL_FN(ap_find_loaded_module_symbol);
2517
2518         if (check_symbol) {
2519             /*
2520              * There are two phases where calling ap_find_loaded_module_symbol
2521              * is problematic:
2522              *
2523              * During reading of the config, ap_server_conf is invalid but s
2524              * points to the main server config, if passed from cmd->server
2525              * of an EXEC_ON_READ directive.
2526              *
2527              * During config parsing, s may be a virtual host that would cause
2528              * a segfault in mod_so if passed to ap_find_loaded_module_symbol,
2529              * because mod_so's server config for vhosts is initialized later.
2530              * But ap_server_conf is already set at this time.
2531              *
2532              * Therefore we use s if it is not virtual and ap_server_conf if
2533              * s is virtual.
2534              */
2535             found = check_symbol(s->is_virtual ? ap_server_conf : s, name);
2536         }
2537     }
2538
2539     return found;
2540 }
2541
2542
2543 static const char *start_ifmod(cmd_parms *cmd, void *mconfig, const char *arg)
2544 {
2545     const char *endp = ap_strrchr_c(arg, '>');
2546     int not = (arg[0] == '!');
2547     module *found;
2548
2549     if (endp == NULL) {
2550         return unclosed_directive(cmd);
2551     }
2552
2553     arg = apr_pstrndup(cmd->temp_pool, arg, endp - arg);
2554
2555     if (not) {
2556         arg++;
2557     }
2558
2559     if (!arg[0]) {
2560         return missing_container_arg(cmd);
2561     }
2562
2563     found = find_module(cmd->server, arg);
2564
2565     if ((!not && found) || (not && !found)) {
2566         ap_directive_t *parent = NULL;
2567         ap_directive_t *current = NULL;
2568         const char *retval;
2569
2570         retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd,
2571                                       &current, &parent, "<IfModule");
2572         *(ap_directive_t **)mconfig = current;
2573         return retval;
2574     }
2575     else {
2576         *(ap_directive_t **)mconfig = NULL;
2577         return ap_soak_end_container(cmd, "<IfModule");
2578     }
2579 }
2580
2581 AP_DECLARE(int) ap_exists_config_define(const char *name)
2582 {
2583     char **defines;
2584     int i;
2585
2586     defines = (char **)ap_server_config_defines->elts;
2587     for (i = 0; i < ap_server_config_defines->nelts; i++) {
2588         if (strcmp(defines[i], name) == 0) {
2589             return 1;
2590         }
2591     }
2592
2593     return 0;
2594 }
2595
2596 static const char *start_ifdefine(cmd_parms *cmd, void *dummy, const char *arg)
2597 {
2598     const char *endp;
2599     int defined;
2600     int not = 0;
2601
2602     endp = ap_strrchr_c(arg, '>');
2603     if (endp == NULL) {
2604         return unclosed_directive(cmd);
2605     }
2606
2607     arg = apr_pstrndup(cmd->temp_pool, arg, endp - arg);
2608
2609     if (arg[0] == '!') {
2610         not = 1;
2611         arg++;
2612     }
2613
2614     if (!arg[0]) {
2615         return missing_container_arg(cmd);
2616     }
2617
2618     defined = ap_exists_config_define(arg);
2619     if ((!not && defined) || (not && !defined)) {
2620         ap_directive_t *parent = NULL;
2621         ap_directive_t *current = NULL;
2622         const char *retval;
2623
2624         retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd,
2625                                       &current, &parent, "<IfDefine");
2626         *(ap_directive_t **)dummy = current;
2627         return retval;
2628     }
2629     else {
2630         *(ap_directive_t **)dummy = NULL;
2631         return ap_soak_end_container(cmd, "<IfDefine");
2632     }
2633 }
2634
2635 /* httpd.conf commands... beginning with the <VirtualHost> business */
2636
2637 static const char *virtualhost_section(cmd_parms *cmd, void *dummy,
2638                                        const char *arg)
2639 {
2640     server_rec *main_server = cmd->server, *s;
2641     const char *errmsg;
2642     const char *endp = ap_strrchr_c(arg, '>');
2643     apr_pool_t *p = cmd->pool;
2644
2645     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2646     if (err != NULL) {
2647         return err;
2648     }
2649
2650     if (endp == NULL) {
2651         return unclosed_directive(cmd);
2652     }
2653
2654     arg = apr_pstrndup(cmd->temp_pool, arg, endp - arg);
2655
2656     if (!arg[0]) {
2657         return missing_container_arg(cmd);
2658     }
2659
2660     /* FIXME: There's another feature waiting to happen here -- since you
2661         can now put multiple addresses/names on a single <VirtualHost>
2662         you might want to use it to group common definitions and then
2663         define other "subhosts" with their individual differences.  But
2664         personally I'd rather just do it with a macro preprocessor. -djg */
2665     if (main_server->is_virtual) {
2666         return "<VirtualHost> doesn't nest!";
2667     }
2668
2669     errmsg = ap_init_virtual_host(p, arg, main_server, &s);
2670     if (errmsg) {
2671         return errmsg;
2672     }
2673
2674     s->next = main_server->next;
2675     main_server->next = s;
2676
2677     s->defn_name = cmd->directive->filename;
2678     s->defn_line_number = cmd->directive->line_num;
2679
2680     cmd->server = s;
2681
2682     errmsg = ap_walk_config(cmd->directive->first_child, cmd,
2683                             s->lookup_defaults);
2684
2685     cmd->server = main_server;
2686
2687     return errmsg;
2688 }
2689
2690 static const char *set_server_alias(cmd_parms *cmd, void *dummy,
2691                                     const char *arg)
2692 {
2693     if (!cmd->server->names) {
2694         return "ServerAlias only used in <VirtualHost>";
2695     }
2696
2697     while (*arg) {
2698         char **item, *name = ap_getword_conf(cmd->pool, &arg);
2699
2700         if (ap_is_matchexp(name)) {
2701             item = (char **)apr_array_push(cmd->server->wild_names);
2702         }
2703         else {
2704             item = (char **)apr_array_push(cmd->server->names);
2705         }
2706
2707         *item = name;
2708     }
2709
2710     return NULL;
2711 }
2712
2713 static const char *set_accf_map(cmd_parms *cmd, void *dummy,
2714                                 const char *iproto, const char* iaccf)
2715 {
2716     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2717     core_server_config *conf =
2718         ap_get_core_module_config(cmd->server->module_config);
2719     char* proto;
2720     char* accf;
2721     if (err != NULL) {
2722         return err;
2723     }
2724
2725     proto = apr_pstrdup(cmd->pool, iproto);
2726     ap_str_tolower(proto);
2727     accf = apr_pstrdup(cmd->pool, iaccf);
2728     ap_str_tolower(accf);
2729     apr_table_setn(conf->accf_map, proto, accf);
2730
2731     return NULL;
2732 }
2733
2734 AP_DECLARE(const char*) ap_get_server_protocol(server_rec* s)
2735 {
2736     core_server_config *conf = ap_get_core_module_config(s->module_config);
2737     return conf->protocol;
2738 }
2739
2740 AP_DECLARE(void) ap_set_server_protocol(server_rec* s, const char* proto)
2741 {
2742     core_server_config *conf = ap_get_core_module_config(s->module_config);
2743     conf->protocol = proto;
2744 }
2745
2746 static const char *set_protocol(cmd_parms *cmd, void *dummy,
2747                                 const char *arg)
2748 {
2749     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
2750     core_server_config *conf =
2751         ap_get_core_module_config(cmd->server->module_config);
2752     char* proto;
2753
2754     if (err != NULL) {
2755         return err;
2756     }
2757
2758     proto = apr_pstrdup(cmd->pool, arg);
2759     ap_str_tolower(proto);
2760     conf->protocol = proto;
2761
2762     return NULL;
2763 }
2764
2765 static const char *set_server_string_slot(cmd_parms *cmd, void *dummy,
2766                                           const char *arg)
2767 {
2768     /* This one's pretty generic... */
2769
2770     int offset = (int)(long)cmd->info;
2771     char *struct_ptr = (char *)cmd->server;
2772
2773     const char *err = ap_check_cmd_context(cmd,
2774                                            NOT_IN_DIR_LOC_FILE);
2775     if (err != NULL) {
2776         return err;
2777     }
2778
2779     *(const char **)(struct_ptr + offset) = arg;
2780     return NULL;
2781 }
2782
2783 /*
2784  * The ServerName directive takes one argument with format
2785  * [scheme://]fully-qualified-domain-name[:port], for instance
2786  * ServerName www.example.com
2787  * ServerName www.example.com:80
2788  * ServerName https://www.example.com:443
2789  */
2790
2791 static const char *server_hostname_port(cmd_parms *cmd, void *dummy, const char *arg)
2792 {
2793     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
2794     const char *portstr, *part;
2795     char *scheme;
2796     int port;
2797
2798     if (err != NULL) {
2799         return err;
2800     }
2801
2802     if (apr_fnmatch_test(arg))
2803         return apr_pstrcat(cmd->temp_pool, "Invalid ServerName \"", arg,
2804                 "\" use ServerAlias to set multiple server names.", NULL);
2805
2806     part = ap_strstr_c(arg, "://");
2807
2808     if (part) {
2809       scheme = apr_pstrndup(cmd->pool, arg, part - arg);
2810       ap_str_tolower(scheme);
2811       cmd->server->server_scheme = (const char *)scheme;
2812       part += 3;
2813     } else {
2814       part = arg;
2815     }
2816
2817     portstr = ap_strchr_c(part, ':');
2818     if (portstr) {
2819         cmd->server->server_hostname = apr_pstrndup(cmd->pool, part,
2820                                                     portstr - part);
2821         portstr++;
2822         port = atoi(portstr);
2823         if (port <= 0 || port >= 65536) { /* 65536 == 1<<16 */
2824             return apr_pstrcat(cmd->temp_pool, "The port number \"", arg,
2825                           "\" is outside the appropriate range "
2826                           "(i.e., 1..65535).", NULL);
2827         }
2828     }
2829     else {
2830         cmd->server->server_hostname = apr_pstrdup(cmd->pool, part);
2831         port = 0;
2832     }
2833
2834     cmd->server->port = port;
2835     return NULL;
2836 }
2837
2838 static const char *set_signature_flag(cmd_parms *cmd, void *d_,
2839                                       const char *arg)
2840 {
2841     core_dir_config *d = d_;
2842
2843     if (strcasecmp(arg, "On") == 0) {
2844         d->server_signature = srv_sig_on;
2845     }
2846     else if (strcasecmp(arg, "Off") == 0) {
2847         d->server_signature = srv_sig_off;
2848     }
2849     else if (strcasecmp(arg, "EMail") == 0) {
2850         d->server_signature = srv_sig_withmail;
2851     }
2852     else {
2853         return "ServerSignature: use one of: off | on | email";
2854     }
2855
2856     return NULL;
2857 }
2858
2859 static const char *set_server_root(cmd_parms *cmd, void *dummy,
2860                                    const char *arg)
2861 {
2862     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2863
2864     if (err != NULL) {
2865         return err;
2866     }
2867
2868     if ((apr_filepath_merge((char**)&ap_server_root, NULL, arg,
2869                             APR_FILEPATH_TRUENAME, cmd->pool) != APR_SUCCESS)
2870         || !ap_is_directory(cmd->temp_pool, ap_server_root)) {
2871         return "ServerRoot must be a valid directory";
2872     }
2873
2874     return NULL;
2875 }
2876
2877 static const char *set_runtime_dir(cmd_parms *cmd, void *dummy, const char *arg)
2878 {
2879     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2880
2881     if (err != NULL) {
2882         return err;
2883     }
2884
2885     if ((apr_filepath_merge((char**)&ap_runtime_dir, NULL,
2886                             ap_server_root_relative(cmd->pool, arg),
2887                             APR_FILEPATH_TRUENAME, cmd->pool) != APR_SUCCESS)
2888         || !ap_is_directory(cmd->temp_pool, ap_runtime_dir)) {
2889         return "DefaultRuntimeDir must be a valid directory, absolute or relative to ServerRoot";
2890     }
2891
2892     return NULL;
2893 }
2894
2895 static const char *set_timeout(cmd_parms *cmd, void *dummy, const char *arg)
2896 {
2897     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
2898
2899     if (err != NULL) {
2900         return err;
2901     }
2902
2903     cmd->server->timeout = apr_time_from_sec(atoi(arg));
2904     return NULL;
2905 }
2906
2907 static const char *set_allow2f(cmd_parms *cmd, void *d_, const char *arg)
2908 {
2909     core_dir_config *d = d_;
2910
2911     if (0 == strcasecmp(arg, "on")) {
2912         d->allow_encoded_slashes = 1;
2913         d->decode_encoded_slashes = 1; /* for compatibility with 2.0 & 2.2 */
2914     } else if (0 == strcasecmp(arg, "off")) {
2915         d->allow_encoded_slashes = 0;
2916         d->decode_encoded_slashes = 0;
2917     } else if (0 == strcasecmp(arg, "nodecode")) {
2918         d->allow_encoded_slashes = 1;
2919         d->decode_encoded_slashes = 0;
2920     } else {
2921         return apr_pstrcat(cmd->pool,
2922                            cmd->cmd->name, " must be On, Off, or NoDecode",
2923                            NULL);
2924     }
2925
2926     d->allow_encoded_slashes_set = 1;
2927     d->decode_encoded_slashes_set = 1;
2928
2929     return NULL;
2930 }
2931
2932 static const char *set_hostname_lookups(cmd_parms *cmd, void *d_,
2933                                         const char *arg)
2934 {
2935     core_dir_config *d = d_;
2936
2937     if (!strcasecmp(arg, "on")) {
2938         d->hostname_lookups = HOSTNAME_LOOKUP_ON;
2939     }
2940     else if (!strcasecmp(arg, "off")) {
2941         d->hostname_lookups = HOSTNAME_LOOKUP_OFF;
2942     }
2943     else if (!strcasecmp(arg, "double")) {
2944         d->hostname_lookups = HOSTNAME_LOOKUP_DOUBLE;
2945     }
2946     else {
2947         return "parameter must be 'on', 'off', or 'double'";
2948     }
2949
2950     return NULL;
2951 }
2952
2953 static const char *set_serverpath(cmd_parms *cmd, void *dummy,
2954                                   const char *arg)
2955 {
2956     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
2957
2958     if (err != NULL) {
2959         return err;
2960     }
2961
2962     cmd->server->path = arg;
2963     cmd->server->pathlen = (int)strlen(arg);
2964     return NULL;
2965 }
2966
2967 static const char *set_content_md5(cmd_parms *cmd, void *d_, int arg)
2968 {
2969     core_dir_config *d = d_;
2970
2971     d->content_md5 = arg ? AP_CONTENT_MD5_ON : AP_CONTENT_MD5_OFF;
2972     return NULL;
2973 }
2974
2975 static const char *set_accept_path_info(cmd_parms *cmd, void *d_, const char *arg)
2976 {
2977     core_dir_config *d = d_;
2978
2979     if (strcasecmp(arg, "on") == 0) {
2980         d->accept_path_info = AP_REQ_ACCEPT_PATH_INFO;
2981     }
2982     else if (strcasecmp(arg, "off") == 0) {
2983         d->accept_path_info = AP_REQ_REJECT_PATH_INFO;
2984     }
2985     else if (strcasecmp(arg, "default") == 0) {
2986         d->accept_path_info = AP_REQ_DEFAULT_PATH_INFO;
2987     }
2988     else {
2989         return "AcceptPathInfo must be set to on, off or default";
2990     }
2991
2992     return NULL;
2993 }
2994
2995 static const char *set_use_canonical_name(cmd_parms *cmd, void *d_,
2996                                           const char *arg)
2997 {
2998     core_dir_config *d = d_;
2999
3000     if (strcasecmp(arg, "on") == 0) {
3001         d->use_canonical_name = USE_CANONICAL_NAME_ON;
3002     }
3003     else if (strcasecmp(arg, "off") == 0) {
3004         d->use_canonical_name = USE_CANONICAL_NAME_OFF;
3005     }
3006     else if (strcasecmp(arg, "dns") == 0) {
3007         d->use_canonical_name = USE_CANONICAL_NAME_DNS;
3008     }
3009     else {
3010         return "parameter must be 'on', 'off', or 'dns'";
3011     }
3012
3013     return NULL;
3014 }
3015
3016 static const char *set_use_canonical_phys_port(cmd_parms *cmd, void *d_,
3017                                           const char *arg)
3018 {
3019     core_dir_config *d = d_;
3020
3021     if (strcasecmp(arg, "on") == 0) {
3022         d->use_canonical_phys_port = USE_CANONICAL_PHYS_PORT_ON;
3023     }
3024     else if (strcasecmp(arg, "off") == 0) {
3025         d->use_canonical_phys_port = USE_CANONICAL_PHYS_PORT_OFF;
3026     }
3027     else {
3028         return "parameter must be 'on' or 'off'";
3029     }
3030
3031     return NULL;
3032 }
3033
3034 static const char *include_config (cmd_parms *cmd, void *dummy,
3035                                    const char *name)
3036 {
3037     ap_directive_t *conftree = NULL;
3038     const char *conffile, *error;
3039     unsigned *recursion;
3040     int optional = cmd->cmd->cmd_data ? 1 : 0;
3041     void *data;
3042
3043     apr_pool_userdata_get(&data, "ap_include_sentinel", cmd->pool);
3044     if (data) {
3045         recursion = data;
3046     }
3047     else {
3048         data = recursion = apr_palloc(cmd->pool, sizeof(*recursion));
3049         *recursion = 0;
3050         apr_pool_userdata_setn(data, "ap_include_sentinel", NULL, cmd->pool);
3051     }
3052
3053     if (++*recursion > AP_MAX_INCLUDE_DEPTH) {
3054         *recursion = 0;
3055         return apr_psprintf(cmd->pool, "Exceeded maximum include depth of %u, "
3056                             "There appears to be a recursion.",
3057                             AP_MAX_INCLUDE_DEPTH);
3058     }
3059
3060     conffile = ap_server_root_relative(cmd->pool, name);
3061     if (!conffile) {
3062         *recursion = 0;
3063         return apr_pstrcat(cmd->pool, "Invalid Include path ",
3064                            name, NULL);
3065     }
3066
3067     error = ap_process_fnmatch_configs(cmd->server, conffile, &conftree,
3068                                        cmd->pool, cmd->temp_pool,
3069                                        optional);
3070     if (error) {
3071         *recursion = 0;
3072         return error;
3073     }
3074
3075     *(ap_directive_t **)dummy = conftree;
3076
3077     /* recursion level done */
3078     if (*recursion) {
3079         --*recursion;
3080     }
3081
3082     return NULL;
3083 }
3084
3085 static const char *update_loglevel(cmd_parms *cmd, struct ap_logconf *log,
3086                                    const char *arg)
3087 {
3088     const char *level_str, *err;
3089     module *module;
3090     int level;
3091
3092     level_str = ap_strrchr_c(arg, ':');
3093
3094     if (level_str == NULL) {
3095         err = ap_parse_log_level(arg, &log->level);
3096         if (err != NULL)
3097             return err;
3098         ap_reset_module_loglevels(log, APLOG_NO_MODULE);
3099         ap_log_error(APLOG_MARK, APLOG_TRACE3, 0, cmd->server,
3100                      "Setting %s for all modules to %s", cmd->cmd->name, arg);
3101         return NULL;
3102     }
3103
3104     arg = apr_pstrmemdup(cmd->temp_pool, arg, level_str - arg);
3105     level_str++;
3106     if (!*level_str) {
3107         return apr_psprintf(cmd->temp_pool, "Module specifier '%s' must be "
3108                             "followed by a log level keyword", arg);
3109     }
3110
3111     err = ap_parse_log_level(level_str, &level);
3112     if (err != NULL)
3113         return apr_psprintf(cmd->temp_pool, "%s:%s: %s", arg, level_str, err);
3114
3115     if ((module = find_module(cmd->server, arg)) == NULL) {
3116         char *name = apr_psprintf(cmd->temp_pool, "%s_module", arg);
3117         ap_log_error(APLOG_MARK, APLOG_TRACE6, 0, cmd->server,
3118                      "Cannot find module '%s', trying '%s'", arg, name);
3119         module = find_module(cmd->server, name);
3120     }
3121
3122     if (module == NULL) {
3123         return apr_psprintf(cmd->temp_pool, "Cannot find module %s", arg);
3124     }
3125
3126     ap_set_module_loglevel(cmd->pool, log, module->module_index, level);
3127     ap_log_error(APLOG_MARK, APLOG_TRACE3, 0, cmd->server,
3128                  "Setting %s for module %s to %s", cmd->cmd->name,
3129                  module->name, level_str);
3130
3131     return NULL;
3132 }
3133
3134 static const char *set_loglevel(cmd_parms *cmd, void *config_, const char *arg)
3135 {
3136     struct ap_logconf *log;
3137
3138     if (cmd->path) {
3139         core_dir_config *dconf = config_;
3140         if (!dconf->log) {
3141             dconf->log = ap_new_log_config(cmd->pool, NULL);
3142         }
3143         log = dconf->log;
3144     }
3145     else {
3146         log = &cmd->server->log;
3147     }
3148
3149     if (arg == NULL)
3150         return "LogLevel requires level keyword or module loglevel specifier";
3151
3152     return update_loglevel(cmd, log, arg);
3153 }
3154
3155 static const char *set_loglevel_override(cmd_parms *cmd, void *d_, int argc,
3156                                          char *const argv[])
3157 {
3158     core_server_config *sconf;
3159     conn_log_config *entry;
3160     int ret, i;
3161     const char *addr, *mask, *err;
3162
3163     if (argc < 2)
3164         return "LogLevelOverride requires at least two arguments";
3165
3166     entry = apr_pcalloc(cmd->pool, sizeof(conn_log_config));
3167     sconf = ap_get_core_module_config(cmd->server->module_config);
3168     if (!sconf->conn_log_level)
3169         sconf->conn_log_level = apr_array_make(cmd->pool, 4, sizeof(entry));
3170     APR_ARRAY_PUSH(sconf->conn_log_level, conn_log_config *) = entry;
3171
3172     addr = argv[0];
3173     mask = ap_strchr_c(addr, '/');
3174     if (mask) {
3175         addr = apr_pstrmemdup(cmd->temp_pool, addr, mask - addr);
3176         mask++;
3177     }
3178     ret = apr_ipsubnet_create(&entry->subnet, addr, mask, cmd->pool);
3179     if (ret != APR_SUCCESS)
3180         return "parsing of subnet/netmask failed";
3181
3182     for (i = 1; i < argc; i++) {
3183         if ((err = update_loglevel(cmd, &entry->log, argv[i])) != NULL)
3184             return err;
3185     }
3186     return NULL;
3187 }
3188
3189 AP_DECLARE(const char *) ap_psignature(const char *prefix, request_rec *r)
3190 {
3191     char sport[20];
3192     core_dir_config *conf;
3193
3194     conf = (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
3195     if ((conf->server_signature == srv_sig_off)
3196             || (conf->server_signature == srv_sig_unset)) {
3197         return "";
3198     }
3199
3200     apr_snprintf(sport, sizeof sport, "%u", (unsigned) ap_get_server_port(r));
3201
3202     if (conf->server_signature == srv_sig_withmail) {
3203         return apr_pstrcat(r->pool, prefix, "<address>",
3204                            ap_get_server_banner(),
3205                            " Server at <a href=\"",
3206                            ap_is_url(r->server->server_admin) ? "" : "mailto:",
3207                            ap_escape_html(r->pool, r->server->server_admin),
3208                            "\">",
3209                            ap_escape_html(r->pool, ap_get_server_name(r)),
3210                            "</a> Port ", sport,
3211                            "</address>\n", NULL);
3212     }
3213
3214     return apr_pstrcat(r->pool, prefix, "<address>", ap_get_server_banner(),
3215                        " Server at ",
3216                        ap_escape_html(r->pool, ap_get_server_name(r)),
3217                        " Port ", sport,
3218                        "</address>\n", NULL);
3219 }
3220
3221 /*
3222  * Handle a request to include the server's OS platform in the Server
3223  * response header field (the ServerTokens directive).  Unfortunately
3224  * this requires a new global in order to communicate the setting back to
3225  * http_main so it can insert the information in the right place in the
3226  * string.
3227  */
3228
3229 static char *server_banner = NULL;
3230 static int banner_locked = 0;
3231 static const char *server_description = NULL;
3232
3233 enum server_token_type {
3234     SrvTk_MAJOR,         /* eg: Apache/2 */
3235     SrvTk_MINOR,         /* eg. Apache/2.0 */
3236     SrvTk_MINIMAL,       /* eg: Apache/2.0.41 */
3237     SrvTk_OS,            /* eg: Apache/2.0.41 (UNIX) */
3238     SrvTk_FULL,          /* eg: Apache/2.0.41 (UNIX) PHP/4.2.2 FooBar/1.2b */
3239     SrvTk_PRODUCT_ONLY   /* eg: Apache */
3240 };
3241 static enum server_token_type ap_server_tokens = SrvTk_FULL;
3242
3243 static apr_status_t reset_banner(void *dummy)
3244 {
3245     banner_locked = 0;
3246     ap_server_tokens = SrvTk_FULL;
3247     server_banner = NULL;
3248     server_description = NULL;
3249     return APR_SUCCESS;
3250 }
3251
3252 AP_DECLARE(void) ap_get_server_revision(ap_version_t *version)
3253 {
3254     version->major = AP_SERVER_MAJORVERSION_NUMBER;
3255     version->minor = AP_SERVER_MINORVERSION_NUMBER;
3256     version->patch = AP_SERVER_PATCHLEVEL_NUMBER;
3257     version->add_string = AP_SERVER_ADD_STRING;
3258 }
3259
3260 AP_DECLARE(const char *) ap_get_server_description(void)
3261 {
3262     return server_description ? server_description :
3263         AP_SERVER_BASEVERSION " (" PLATFORM ")";
3264 }
3265
3266 AP_DECLARE(const char *) ap_get_server_banner(void)
3267 {
3268     return server_banner ? server_banner : AP_SERVER_BASEVERSION;
3269 }
3270
3271 AP_DECLARE(void) ap_add_version_component(apr_pool_t *pconf, const char *component)
3272 {
3273     if (! banner_locked) {
3274         /*
3275          * If the version string is null, register our cleanup to reset the
3276          * pointer on pool destruction. We also know that, if NULL,
3277          * we are adding the original SERVER_BASEVERSION string.
3278          */
3279         if (server_banner == NULL) {
3280             apr_pool_cleanup_register(pconf, NULL, reset_banner,
3281                                       apr_pool_cleanup_null);
3282             server_banner = apr_pstrdup(pconf, component);
3283         }
3284         else {
3285             /*
3286              * Tack the given component identifier to the end of
3287              * the existing string.
3288              */
3289             server_banner = apr_pstrcat(pconf, server_banner, " ",
3290                                         component, NULL);
3291         }
3292     }
3293     server_description = apr_pstrcat(pconf, server_description, " ",
3294                                      component, NULL);
3295 }
3296
3297 /*
3298  * This routine adds the real server base identity to the banner string,
3299  * and then locks out changes until the next reconfig.
3300  */
3301 static void set_banner(apr_pool_t *pconf)
3302 {
3303     if (ap_server_tokens == SrvTk_PRODUCT_ONLY) {
3304         ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT);
3305     }
3306     else if (ap_server_tokens == SrvTk_MINIMAL) {
3307         ap_add_version_component(pconf, AP_SERVER_BASEVERSION);
3308     }
3309     else if (ap_server_tokens == SrvTk_MINOR) {
3310         ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT "/" AP_SERVER_MINORREVISION);
3311     }
3312     else if (ap_server_tokens == SrvTk_MAJOR) {
3313         ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT "/" AP_SERVER_MAJORVERSION);
3314     }
3315     else {
3316         ap_add_version_component(pconf, AP_SERVER_BASEVERSION " (" PLATFORM ")");
3317     }
3318
3319     /*
3320      * Lock the server_banner string if we're not displaying
3321      * the full set of tokens
3322      */
3323     if (ap_server_tokens != SrvTk_FULL) {
3324         banner_locked++;
3325     }
3326     server_description = AP_SERVER_BASEVERSION " (" PLATFORM ")";
3327 }
3328
3329 static const char *set_serv_tokens(cmd_parms *cmd, void *dummy,
3330                                    const char *arg)
3331 {
3332     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
3333
3334     if (err != NULL) {
3335         return err;
3336     }
3337
3338     if (!strcasecmp(arg, "OS")) {
3339         ap_server_tokens = SrvTk_OS;
3340     }
3341     else if (!strcasecmp(arg, "Min") || !strcasecmp(arg, "Minimal")) {
3342         ap_server_tokens = SrvTk_MINIMAL;
3343     }
3344     else if (!strcasecmp(arg, "Major")) {
3345         ap_server_tokens = SrvTk_MAJOR;
3346     }
3347     else if (!strcasecmp(arg, "Minor") ) {
3348         ap_server_tokens = SrvTk_MINOR;
3349     }
3350     else if (!strcasecmp(arg, "Prod") || !strcasecmp(arg, "ProductOnly")) {
3351         ap_server_tokens = SrvTk_PRODUCT_ONLY;
3352     }
3353     else if (!strcasecmp(arg, "Full")) {
3354         ap_server_tokens = SrvTk_FULL;
3355     }
3356     else {
3357         return "ServerTokens takes 1 argument: 'Prod(uctOnly)', 'Major', 'Minor', 'Min(imal)', 'OS', or 'Full'";
3358     }
3359
3360     return NULL;
3361 }
3362
3363 static const char *set_limit_req_line(cmd_parms *cmd, void *dummy,
3364                                       const char *arg)
3365 {
3366     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
3367     int lim;
3368
3369     if (err != NULL) {
3370         return err;
3371     }
3372
3373     lim = atoi(arg);
3374     if (lim < 0) {
3375         return apr_pstrcat(cmd->temp_pool, "LimitRequestLine \"", arg,
3376                            "\" must be a non-negative integer", NULL);
3377     }
3378
3379     cmd->server->limit_req_line = lim;
3380     return NULL;
3381 }
3382
3383 static const char *set_limit_req_fieldsize(cmd_parms *cmd, void *dummy,
3384                                            const char *arg)
3385 {
3386     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
3387     int lim;
3388
3389     if (err != NULL) {
3390         return err;
3391     }
3392
3393     lim = atoi(arg);
3394     if (lim < 0) {
3395         return apr_pstrcat(cmd->temp_pool, "LimitRequestFieldsize \"", arg,
3396                           "\" must be a non-negative integer",
3397                           NULL);
3398     }
3399
3400     cmd->server->limit_req_fieldsize = lim;
3401     return NULL;
3402 }
3403
3404 static const char *set_limit_req_fields(cmd_parms *cmd, void *dummy,
3405                                         const char *arg)
3406 {
3407     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
3408     int lim;
3409
3410     if (err != NULL) {
3411         return err;
3412     }
3413
3414     lim = atoi(arg);
3415     if (lim < 0) {
3416         return apr_pstrcat(cmd->temp_pool, "LimitRequestFields \"", arg,
3417                            "\" must be a non-negative integer (0 = no limit)",
3418                            NULL);
3419     }
3420
3421     cmd->server->limit_req_fields = lim;
3422     return NULL;
3423 }
3424
3425 static const char *set_limit_req_body(cmd_parms *cmd, void *conf_,
3426                                       const char *arg)
3427 {
3428     core_dir_config *conf = conf_;
3429     char *errp;
3430
3431     if (APR_SUCCESS != apr_strtoff(&conf->limit_req_body, arg, &errp, 10)) {
3432         return "LimitRequestBody argument is not parsable.";
3433     }
3434     if (*errp || conf->limit_req_body < 0) {
3435         return "LimitRequestBody requires a non-negative integer.";
3436     }
3437
3438     return NULL;
3439 }
3440
3441 static const char *set_limit_xml_req_body(cmd_parms *cmd, void *conf_,
3442                                           const char *arg)
3443 {
3444     core_dir_config *conf = conf_;
3445
3446     conf->limit_xml_body = atol(arg);
3447     if (conf->limit_xml_body < 0)
3448         return "LimitXMLRequestBody requires a non-negative integer.";
3449
3450     return NULL;
3451 }
3452
3453 static const char *set_max_ranges(cmd_parms *cmd, void *conf_, const char *arg)
3454 {
3455     core_dir_config *conf = conf_;
3456     int val = 0;
3457
3458     if (!strcasecmp(arg, "none")) {
3459         val = AP_MAXRANGES_NORANGES;
3460     }
3461     else if (!strcasecmp(arg, "default")) {
3462         val = AP_MAXRANGES_DEFAULT;
3463     }
3464     else if (!strcasecmp(arg, "unlimited")) {
3465         val = AP_MAXRANGES_UNLIMITED;
3466     }
3467     else {
3468         val = atoi(arg);
3469         if (val <= 0)
3470             return "MaxRanges requires 'none', 'default', 'unlimited' or "
3471                    "a positive integer";
3472     }
3473
3474     conf->max_ranges = val;
3475
3476     return NULL;
3477 }
3478
3479 static const char *set_max_overlaps(cmd_parms *cmd, void *conf_, const char *arg)
3480 {
3481     core_dir_config *conf = conf_;
3482     int val = 0;
3483
3484     if (!strcasecmp(arg, "none")) {
3485         val = AP_MAXRANGES_NORANGES;
3486     }
3487     else if (!strcasecmp(arg, "default")) {
3488         val = AP_MAXRANGES_DEFAULT;
3489     }
3490     else if (!strcasecmp(arg, "unlimited")) {
3491         val = AP_MAXRANGES_UNLIMITED;
3492     }
3493     else {
3494         val = atoi(arg);
3495         if (val <= 0)
3496             return "MaxRangeOverlaps requires 'none', 'default', 'unlimited' or "
3497             "a positive integer";
3498     }
3499
3500     conf->max_overlaps = val;
3501
3502     return NULL;
3503 }
3504
3505 static const char *set_max_reversals(cmd_parms *cmd, void *conf_, const char *arg)
3506 {
3507     core_dir_config *conf = conf_;
3508     int val = 0;
3509
3510     if (!strcasecmp(arg, "none")) {
3511         val = AP_MAXRANGES_NORANGES;
3512     }
3513     else if (!strcasecmp(arg, "default")) {
3514         val = AP_MAXRANGES_DEFAULT;
3515     }
3516     else if (!strcasecmp(arg, "unlimited")) {
3517         val = AP_MAXRANGES_UNLIMITED;
3518     }
3519     else {
3520         val = atoi(arg);
3521         if (val <= 0)
3522             return "MaxRangeReversals requires 'none', 'default', 'unlimited' or "
3523             "a positive integer";
3524     }
3525
3526     conf->max_reversals = val;
3527
3528     return NULL;
3529 }
3530
3531 AP_DECLARE(apr_size_t) ap_get_limit_xml_body(const request_rec *r)
3532 {
3533     core_dir_config *conf;
3534
3535     conf = ap_get_core_module_config(r->per_dir_config);
3536     if (conf->limit_xml_body == AP_LIMIT_UNSET)
3537         return AP_DEFAULT_LIMIT_XML_BODY;
3538
3539     return (apr_size_t)conf->limit_xml_body;
3540 }
3541
3542 #if !defined (RLIMIT_CPU) || !(defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)) || !defined (RLIMIT_NPROC)
3543 static const char *no_set_limit(cmd_parms *cmd, void *conf_,
3544                                 const char *arg, const char *arg2)
3545 {
3546     ap_log_error(APLOG_MARK, APLOG_ERR, 0, cmd->server, APLOGNO(00118)
3547                 "%s not supported on this platform", cmd->cmd->name);
3548
3549     return NULL;
3550 }
3551 #endif
3552
3553 #ifdef RLIMIT_CPU
3554 static const char *set_limit_cpu(cmd_parms *cmd, void *conf_,
3555                                  const char *arg, const char *arg2)
3556 {
3557     core_dir_config *conf = conf_;
3558
3559     ap_unixd_set_rlimit(cmd, &conf->limit_cpu, arg, arg2, RLIMIT_CPU);
3560     return NULL;
3561 }
3562 #endif
3563
3564 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)
3565 static const char *set_limit_mem(cmd_parms *cmd, void *conf_,
3566                                  const char *arg, const char * arg2)
3567 {
3568     core_dir_config *conf = conf_;
3569
3570 #if defined(RLIMIT_AS)
3571     ap_unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2 ,RLIMIT_AS);
3572 #elif defined(RLIMIT_DATA)
3573     ap_unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_DATA);
3574 #elif defined(RLIMIT_VMEM)
3575     ap_unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_VMEM);
3576 #endif
3577
3578     return NULL;
3579 }
3580 #endif
3581
3582 #ifdef RLIMIT_NPROC
3583 static const char *set_limit_nproc(cmd_parms *cmd, void *conf_,
3584                                    const char *arg, const char * arg2)
3585 {
3586     core_dir_config *conf = conf_;
3587
3588     ap_unixd_set_rlimit(cmd, &conf->limit_nproc, arg, arg2, RLIMIT_NPROC);
3589     return NULL;
3590 }
3591 #endif
3592
3593 static const char *set_recursion_limit(cmd_parms *cmd, void *dummy,
3594                                        const char *arg1, const char *arg2)
3595 {
3596     core_server_config *conf =
3597         ap_get_core_module_config(cmd->server->module_config);
3598     int limit = atoi(arg1);
3599
3600     if (limit <= 0) {
3601         return "The recursion limit must be greater than zero.";
3602     }
3603     if (limit < 4) {
3604         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server, APLOGNO(00119)
3605                      "Limiting internal redirects to very low numbers may "
3606                      "cause normal requests to fail.");
3607     }
3608
3609     conf->redirect_limit = limit;
3610
3611     if (arg2) {
3612         limit = atoi(arg2);
3613
3614         if (limit <= 0) {
3615             return "The recursion limit must be greater than zero.";
3616         }
3617         if (limit < 4) {
3618             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server, APLOGNO(00120)
3619                          "Limiting the subrequest depth to a very low level may"
3620                          " cause normal requests to fail.");
3621         }
3622     }
3623
3624     conf->subreq_limit = limit;
3625
3626     return NULL;
3627 }
3628
3629 static void log_backtrace(const request_rec *r)
3630 {
3631     const request_rec *top = r;
3632
3633     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00121)
3634                   "r->uri = %s", r->uri ? r->uri : "(unexpectedly NULL)");
3635
3636     while (top && (top->prev || top->main)) {
3637         if (top->prev) {
3638             top = top->prev;
3639             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00122)
3640                           "redirected from r->uri = %s",
3641                           top->uri ? top->uri : "(unexpectedly NULL)");
3642         }
3643
3644         if (!top->prev && top->main) {
3645             top = top->main;
3646             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00123)
3647                           "subrequested from r->uri = %s",
3648                           top->uri ? top->uri : "(unexpectedly NULL)");
3649         }
3650     }
3651 }
3652
3653 /*
3654  * check whether redirect limit is reached
3655  */
3656 AP_DECLARE(int) ap_is_recursion_limit_exceeded(const request_rec *r)
3657 {
3658     core_server_config *conf =
3659         ap_get_core_module_config(r->server->module_config);
3660     const request_rec *top = r;
3661     int redirects = 0, subreqs = 0;
3662     int rlimit = conf->redirect_limit
3663                  ? conf->redirect_limit
3664                  : AP_DEFAULT_MAX_INTERNAL_REDIRECTS;
3665     int slimit = conf->subreq_limit
3666                  ? conf->subreq_limit
3667                  : AP_DEFAULT_MAX_SUBREQ_DEPTH;
3668
3669
3670     while (top->prev || top->main) {
3671         if (top->prev) {
3672             if (++redirects >= rlimit) {
3673                 /* uuh, too much. */
3674                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00124)
3675                               "Request exceeded the limit of %d internal "
3676                               "redirects due to probable configuration error. "
3677                               "Use 'LimitInternalRecursion' to increase the "
3678                               "limit if necessary. Use 'LogLevel debug' to get "
3679                               "a backtrace.", rlimit);
3680
3681                 /* post backtrace */
3682                 log_backtrace(r);
3683
3684                 /* return failure */
3685                 return 1;
3686             }
3687
3688             top = top->prev;
3689         }
3690
3691         if (!top->prev && top->main) {
3692             if (++subreqs >= slimit) {
3693                 /* uuh, too much. */
3694                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00125)
3695                               "Request exceeded the limit of %d subrequest "
3696                               "nesting levels due to probable configuration "
3697                               "error. Use 'LimitInternalRecursion' to increase "
3698                               "the limit if necessary. Use 'LogLevel debug' to "
3699                               "get a backtrace.", slimit);
3700
3701                 /* post backtrace */
3702                 log_backtrace(r);
3703
3704                 /* return failure */
3705                 return 1;
3706             }
3707
3708             top = top->main;
3709         }
3710     }
3711
3712     /* recursion state: ok */
3713     return 0;
3714 }
3715
3716 static const char *set_trace_enable(cmd_parms *cmd, void *dummy,
3717                                     const char *arg1)
3718 {
3719     core_server_config *conf =
3720         ap_get_core_module_config(cmd->server->module_config);
3721
3722     if (strcasecmp(arg1, "on") == 0) {
3723         conf->trace_enable = AP_TRACE_ENABLE;
3724     }
3725     else if (strcasecmp(arg1, "off") == 0) {
3726         conf->trace_enable = AP_TRACE_DISABLE;
3727     }
3728     else if (strcasecmp(arg1, "extended") == 0) {
3729         conf->trace_enable = AP_TRACE_EXTENDED;
3730     }
3731     else {
3732         return "TraceEnable must be one of 'on', 'off', or 'extended'";
3733     }
3734
3735     return NULL;
3736 }
3737
3738 static const char *set_http_protocol(cmd_parms *cmd, void *dummy,
3739                                      const char *arg)
3740 {
3741     core_server_config *conf =
3742         ap_get_core_module_config(cmd->server->module_config);
3743
3744     if (strncmp(arg, "min=", 4) == 0) {
3745         arg += 4;
3746         if (strcmp(arg, "0.9") == 0)
3747             conf->http09_enable = AP_HTTP09_ENABLE;
3748         else if (strcmp(arg, "1.0") == 0)
3749             conf->http09_enable = AP_HTTP09_DISABLE;
3750         else
3751             return "HttpProtocol 'min' must be one of '0.9' and '1.0'";
3752         return NULL;
3753     }
3754
3755     if (strcmp(arg, "strict") == 0)
3756         conf->http_conformance = AP_HTTP_CONFORMANCE_STRICT;
3757     else if (strcmp(arg, "strict,log-only") == 0)
3758         conf->http_conformance = AP_HTTP_CONFORMANCE_STRICT|
3759                                  AP_HTTP_CONFORMANCE_LOGONLY;
3760     else if (strcmp(arg, "liberal") == 0)
3761         conf->http_conformance = AP_HTTP_CONFORMANCE_LIBERAL;
3762     else
3763         return "HttpProtocol accepts 'min=0.9', 'min=1.0', 'liberal', "
3764                "'strict', 'strict,log-only'";
3765
3766     if ((conf->http_conformance & AP_HTTP_CONFORMANCE_STRICT) &&
3767         (conf->http_conformance & AP_HTTP_CONFORMANCE_LIBERAL)) {
3768         return "HttpProtocol 'strict' and 'liberal' are mutually exclusive";
3769     }
3770
3771     return NULL;
3772 }
3773
3774 static const char *set_http_method(cmd_parms *cmd, void *conf, const char *arg)
3775 {
3776     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
3777     if (err != NULL)
3778         return err;
3779     ap_method_register(cmd->pool, arg);
3780     return NULL;
3781 }
3782
3783 static const char *set_cl_head_zero(cmd_parms *cmd, void *dummy, int arg)
3784 {
3785     core_server_config *conf =
3786         ap_get_core_module_config(cmd->server->module_config);
3787
3788     if (arg) {
3789         conf->http_cl_head_zero = AP_HTTP_CL_HEAD_ZERO_ENABLE;
3790     } else {
3791         conf->http_cl_head_zero = AP_HTTP_CL_HEAD_ZERO_DISABLE;
3792     }
3793     return NULL;
3794 }
3795
3796 static const char *set_expect_strict(cmd_parms *cmd, void *dummy, int arg)
3797 {
3798     core_server_config *conf =
3799         ap_get_core_module_config(cmd->server->module_config);
3800
3801     if (arg) {
3802         conf->http_expect_strict = AP_HTTP_EXPECT_STRICT_ENABLE;
3803     } else {
3804         conf->http_expect_strict = AP_HTTP_EXPECT_STRICT_DISABLE;
3805     }
3806     return NULL;
3807 }
3808
3809 static apr_hash_t *errorlog_hash;
3810
3811 static int log_constant_item(const ap_errorlog_info *info, const char *arg,
3812                              char *buf, int buflen)
3813 {
3814     char *end = apr_cpystrn(buf, arg, buflen);
3815     return end - buf;
3816 }
3817
3818 static char *parse_errorlog_misc_string(apr_pool_t *p,
3819                                         ap_errorlog_format_item *it,
3820                                         const char **sa)
3821 {
3822     const char *s;
3823     char scratch[MAX_STRING_LEN];
3824     char *d = scratch;
3825     /*
3826      * non-leading white space terminates this string to allow the next field
3827      * separator to be inserted
3828      */
3829     int at_start = 1;
3830
3831     it->func = log_constant_item;
3832     s = *sa;
3833
3834     while (*s && *s != '%' && (*s != ' ' || at_start) && d < scratch + MAX_STRING_LEN) {
3835         if (*s != '\\') {
3836             if (*s != ' ') {
3837                 at_start = 0;
3838             }
3839             *d++ = *s++;
3840         }
3841         else {
3842             s++;
3843             switch (*s) {
3844             case 'r':
3845                 *d++ = '\r';
3846                 s++;
3847                 break;
3848             case 'n':
3849                 *d++ = '\n';
3850                 s++;
3851                 break;
3852             case 't':
3853                 *d++ = '\t';
3854                 s++;
3855                 break;
3856             case '\0':
3857                 /* handle end of string */
3858                 *d++ = '\\';
3859                 break;
3860             default:
3861                 /* copy next char verbatim */
3862                 *d++ = *s++;
3863                 break;
3864             }
3865         }
3866     }
3867     *d = '\0';
3868     it->arg = apr_pstrdup(p, scratch);
3869
3870     *sa = s;
3871     return NULL;
3872 }
3873
3874 static char *parse_errorlog_item(apr_pool_t *p, ap_errorlog_format_item *it,
3875                                  const char **sa)
3876 {
3877     const char *s = *sa;
3878     ap_errorlog_handler *handler;
3879     int i;
3880
3881     if (*s != '%') {
3882         if (*s == ' ') {
3883             it->flags |= AP_ERRORLOG_FLAG_FIELD_SEP;
3884         }
3885         return parse_errorlog_misc_string(p, it, sa);
3886     }
3887
3888     ++s;
3889
3890     if (*s == ' ') {
3891         /* percent-space (% ) is a field separator */
3892         it->flags |= AP_ERRORLOG_FLAG_FIELD_SEP;
3893         *sa = ++s;
3894         /* recurse */
3895         return parse_errorlog_item(p, it, sa);
3896     }
3897     else if (*s == '%') {
3898         it->arg = "%";
3899         it->func = log_constant_item;
3900         *sa = ++s;
3901         return NULL;
3902     }
3903
3904     while (*s) {
3905         switch (*s) {
3906         case '{':
3907             ++s;
3908             it->arg = ap_getword(p, &s, '}');
3909             break;
3910         case '+':
3911             ++s;
3912             it->flags |= AP_ERRORLOG_FLAG_REQUIRED;
3913             break;
3914         case '-':
3915             ++s;
3916             it->flags |= AP_ERRORLOG_FLAG_NULL_AS_HYPHEN;
3917             break;
3918         case '0':
3919         case '1':
3920         case '2':
3921         case '3':
3922         case '4':
3923         case '5':
3924         case '6':
3925         case '7':
3926         case '8':
3927         case '9':
3928             i = *s - '0';
3929             while (apr_isdigit(*++s))
3930                 i = i * 10 + (*s) - '0';
3931             it->min_loglevel = i;
3932             break;
3933         case 'M':
3934             it->func = NULL;
3935             it->flags |= AP_ERRORLOG_FLAG_MESSAGE;
3936             *sa = ++s;
3937             return NULL;
3938         default:
3939             handler = (ap_errorlog_handler *)apr_hash_get(errorlog_hash, s, 1);
3940             if (!handler) {
3941                 char dummy[2];
3942
3943                 dummy[0] = *s;
3944                 dummy[1] = '\0';
3945                 return apr_pstrcat(p, "Unrecognized error log format directive %",
3946                                dummy, NULL);
3947             }
3948             it->func = handler->func;
3949             *sa = ++s;
3950             return NULL;
3951         }
3952     }
3953
3954     return "Ran off end of error log format parsing args to some directive";
3955 }
3956
3957 static apr_array_header_t *parse_errorlog_string(apr_pool_t *p,
3958                                                  const char *s,
3959                                                  const char **err,
3960                                                  int is_main_fmt)
3961 {
3962     apr_array_header_t *a = apr_array_make(p, 30,
3963                                            sizeof(ap_errorlog_format_item));
3964     char *res;
3965     int seen_msg_fmt = 0;
3966
3967     while (s && *s) {
3968         ap_errorlog_format_item *item =
3969             (ap_errorlog_format_item *)apr_array_push(a);
3970         memset(item, 0, sizeof(*item));
3971         res = parse_errorlog_item(p, item, &s);
3972         if (res) {
3973             *err = res;
3974             return NULL;
3975         }
3976         if (item->flags & AP_ERRORLOG_FLAG_MESSAGE) {
3977             if (!is_main_fmt) {
3978                 *err = "%M cannot be used in once-per-request or "
3979                        "once-per-connection formats";
3980                 return NULL;
3981             }
3982             seen_msg_fmt = 1;
3983         }
3984         if (is_main_fmt && item->flags & AP_ERRORLOG_FLAG_REQUIRED) {
3985             *err = "The '+' flag cannot be used in the main error log format";
3986             return NULL;
3987         }
3988         if (!is_main_fmt && item->min_loglevel) {
3989             *err = "The loglevel cannot be used as a condition in "
3990                    "once-per-request or once-per-connection formats";
3991             return NULL;
3992         }
3993         if (item->min_loglevel > APLOG_TRACE8) {
3994             *err = "The specified loglevel modifier is out of range";
3995             return NULL;
3996         }
3997     }
3998
3999     if (is_main_fmt && !seen_msg_fmt) {
4000         *err = "main ErrorLogFormat must contain message format string '%M'";
4001         return NULL;
4002     }
4003
4004     return a;
4005 }
4006
4007 static const char *set_errorlog(cmd_parms *cmd, void *dummy, const char *arg1,
4008                                 const char *arg2)
4009 {
4010     ap_errorlog_provider *provider;
4011     const char *err;
4012     cmd->server->errorlog_provider = NULL;
4013
4014     if (!arg2) {
4015         /* Stay backward compatible and check for "syslog" */
4016         if (strncmp("syslog", arg1, 6) == 0) {
4017             arg2 = arg1 + 7; /* skip the ':' if any */
4018             arg1 = "syslog";
4019         }
4020         else {
4021             /* Admin can define only "ErrorLog provider" and we should 
4022              * still handle that using the defined provider, but with empty
4023              * error_fname. */
4024             provider = ap_lookup_provider(AP_ERRORLOG_PROVIDER_GROUP, arg1,
4025                                           AP_ERRORLOG_PROVIDER_VERSION);
4026             if (provider) {
4027                 arg2 = "";
4028             }
4029             else {
4030                 return set_server_string_slot(cmd, dummy, arg1);
4031             }
4032         }
4033     }
4034
4035     if (strcmp("file", arg1) == 0) {
4036         return set_server_string_slot(cmd, dummy, arg2);
4037     }
4038
4039     provider = ap_lookup_provider(AP_ERRORLOG_PROVIDER_GROUP, arg1,
4040                                     AP_ERRORLOG_PROVIDER_VERSION);
4041     if (!provider) {
4042         return apr_psprintf(cmd->pool,
4043                             "Unknown ErrorLog provider: %s",
4044                             arg1);
4045     }
4046
4047     err = provider->parse_errorlog_arg(cmd, arg2);
4048     if (err) {
4049         return err;
4050     }
4051
4052     cmd->server->errorlog_provider = provider;
4053     return set_server_string_slot(cmd, dummy, arg2);
4054 }
4055
4056 static const char *set_errorlog_format(cmd_parms *cmd, void *dummy,
4057                                        const char *arg1, const char *arg2)
4058 {
4059     const char *err_string = NULL;
4060     core_server_config *conf =
4061         ap_get_core_module_config(cmd->server->module_config);
4062
4063     if (!arg2) {
4064         conf->error_log_format = parse_errorlog_string(cmd->pool, arg1,
4065                                                        &err_string, 1);
4066     }
4067     else if (!strcasecmp(arg1, "connection")) {
4068         if (!conf->error_log_conn) {
4069             conf->error_log_conn = apr_array_make(cmd->pool, 5,
4070                                                   sizeof(apr_array_header_t *));
4071         }
4072
4073         if (*arg2) {
4074             apr_array_header_t **e;
4075             e = (apr_array_header_t **) apr_array_push(conf->error_log_conn);
4076             *e = parse_errorlog_string(cmd->pool, arg2, &err_string, 0);
4077         }
4078     }
4079     else if (!strcasecmp(arg1, "request")) {
4080         if (!conf->error_log_req) {
4081             conf->error_log_req = apr_array_make(cmd->pool, 5,
4082                                                  sizeof(apr_array_header_t *));
4083         }
4084
4085         if (*arg2) {
4086             apr_array_header_t **e;
4087             e = (apr_array_header_t **) apr_array_push(conf->error_log_req);
4088             *e = parse_errorlog_string(cmd->pool, arg2, &err_string, 0);
4089         }
4090     }
4091     else {
4092         err_string = "ErrorLogFormat type must be one of request, connection";
4093     }
4094
4095     return err_string;
4096 }
4097
4098 AP_DECLARE(void) ap_register_errorlog_handler(apr_pool_t *p, char *tag,
4099                                               ap_errorlog_handler_fn_t *handler,
4100                                               int flags)
4101 {
4102     ap_errorlog_handler *log_struct = apr_palloc(p, sizeof(*log_struct));
4103     log_struct->func = handler;
4104     log_struct->flags = flags;
4105
4106     apr_hash_set(errorlog_hash, tag, 1, (const void *)log_struct);
4107 }
4108
4109
4110 /* Note --- ErrorDocument will now work from .htaccess files.
4111  * The AllowOverride of Fileinfo allows webmasters to turn it off
4112  */
4113
4114 static const command_rec core_cmds[] = {
4115
4116 /* Old access config file commands */
4117
4118 AP_INIT_RAW_ARGS("<Directory", dirsection, NULL, RSRC_CONF,
4119   "Container for directives affecting resources located in the specified "
4120   "directories"),
4121 AP_INIT_RAW_ARGS("<Location", urlsection, NULL, RSRC_CONF,
4122   "Container for directives affecting resources accessed through the "
4123   "specified URL paths"),
4124 AP_INIT_RAW_ARGS("<VirtualHost", virtualhost_section, NULL, RSRC_CONF,
4125   "Container to map directives to a particular virtual host, takes one or "
4126   "more host addresses"),
4127 AP_INIT_RAW_ARGS("<Files", filesection, NULL, OR_ALL,
4128   "Container for directives affecting files matching specified patterns"),
4129 AP_INIT_RAW_ARGS("<Limit", ap_limit_section, NULL, OR_LIMIT | OR_AUTHCFG,
4130   "Container for authentication directives when accessed using specified HTTP "
4131   "methods"),
4132 AP_INIT_RAW_ARGS("<LimitExcept", ap_limit_section, (void*)1,
4133                  OR_LIMIT | OR_AUTHCFG,
4134   "Container for authentication directives to be applied when any HTTP "
4135   "method other than those specified is used to access the resource"),
4136 AP_INIT_TAKE1("<IfModule", start_ifmod, NULL, EXEC_ON_READ | OR_ALL,
4137   "Container for directives based on existence of specified modules"),
4138 AP_INIT_TAKE1("<IfDefine", start_ifdefine, NULL, EXEC_ON_READ | OR_ALL,
4139   "Container for directives based on existence of command line defines"),
4140 AP_INIT_RAW_ARGS("<DirectoryMatch", dirsection, (void*)1, RSRC_CONF,
4141   "Container for directives affecting resources located in the "
4142   "specified directories"),
4143 AP_INIT_RAW_ARGS("<LocationMatch", urlsection, (void*)1, RSRC_CONF,
4144   "Container for directives affecting resources accessed through the "
4145   "specified URL paths"),
4146 AP_INIT_RAW_ARGS("<FilesMatch", filesection, (void*)1, OR_ALL,
4147   "Container for directives affecting files matching specified patterns"),
4148 #ifdef GPROF
4149 AP_INIT_TAKE1("GprofDir", set_gprof_dir, NULL, RSRC_CONF,
4150   "Directory to plop gmon.out files"),
4151 #endif
4152 AP_INIT_TAKE1("AddDefaultCharset", set_add_default_charset, NULL, OR_FILEINFO,
4153   "The name of the default charset to add to any Content-Type without one or 'Off' to disable"),
4154 AP_INIT_TAKE1("AcceptPathInfo", set_accept_path_info, NULL, OR_FILEINFO,
4155   "Set to on or off for PATH_INFO to be accepted by handlers, or default for the per-handler preference"),
4156 AP_INIT_TAKE12("Define", set_define, NULL, EXEC_ON_READ|ACCESS_CONF|RSRC_CONF,
4157               "Define a variable, optionally to a value.  Same as passing -D to the command line."),
4158 AP_INIT_TAKE1("UnDefine", unset_define, NULL, EXEC_ON_READ|ACCESS_CONF|RSRC_CONF,
4159               "Undefine the existence of a variable. Undo a Define."),
4160 AP_INIT_RAW_ARGS("Error", generate_message, (void*) APLOG_ERR, OR_ALL,
4161                  "Generate error message from within configuration."),
4162 AP_INIT_RAW_ARGS("Warning", generate_message, (void*) APLOG_WARNING, OR_ALL,
4163                  "Generate warning message from within configuration."),
4164 AP_INIT_RAW_ARGS("<If", ifsection, COND_IF, OR_ALL,
4165   "Container for directives to be conditionally applied"),
4166 AP_INIT_RAW_ARGS("<ElseIf", ifsection, COND_ELSEIF, OR_ALL,
4167   "Container for directives to be conditionally applied"),
4168 AP_INIT_RAW_ARGS("<Else", ifsection, COND_ELSE, OR_ALL,
4169   "Container for directives to be conditionally applied"),
4170
4171 /* Old resource config file commands */
4172
4173 AP_INIT_RAW_ARGS("AccessFileName", set_access_name, NULL, RSRC_CONF,
4174   "Name(s) of per-directory config files (default: .htaccess)"),
4175 AP_INIT_TAKE1("DocumentRoot", set_document_root, NULL, RSRC_CONF,
4176   "Root directory of the document tree"),
4177 AP_INIT_TAKE2("ErrorDocument", set_error_document, NULL, OR_FILEINFO,
4178   "Change responses for HTTP errors"),
4179 AP_INIT_RAW_ARGS("AllowOverride", set_override, NULL, ACCESS_CONF,
4180   "Controls what groups of directives can be configured by per-directory "
4181   "config files"),
4182 AP_INIT_TAKE_ARGV("AllowOverrideList", set_override_list, NULL, ACCESS_CONF,
4183   "Controls what individual directives can be configured by per-directory "
4184   "config files"),
4185 AP_INIT_RAW_ARGS("Options", set_options, NULL, OR_OPTIONS,
4186   "Set a number of attributes for a given directory"),
4187 AP_INIT_TAKE1("DefaultType", set_default_type, NULL, OR_FILEINFO,
4188   "the default media type for otherwise untyped files (DEPRECATED)"),
4189 AP_INIT_RAW_ARGS("FileETag", set_etag_bits, NULL, OR_FILEINFO,
4190   "Specify components used to construct a file's ETag"),
4191 AP_INIT_TAKE1("EnableMMAP", set_enable_mmap, NULL, OR_FILEINFO,
4192   "Controls whether memory-mapping may be used to read files"),
4193 AP_INIT_TAKE1("EnableSendfile", set_enable_sendfile, NULL, OR_FILEINFO,
4194   "Controls whether sendfile may be used to transmit files"),
4195
4196 /* Old server config file commands */
4197
4198 AP_INIT_TAKE1("Protocol", set_protocol, NULL, RSRC_CONF,
4199   "Set the Protocol for httpd to use."),
4200 AP_INIT_TAKE2("AcceptFilter", set_accf_map, NULL, RSRC_CONF,
4201   "Set the Accept Filter to use for a protocol"),
4202 AP_INIT_TAKE1("Port", ap_set_deprecated, NULL, RSRC_CONF,
4203   "Port was replaced with Listen in Apache 2.0"),
4204 AP_INIT_TAKE1("HostnameLookups", set_hostname_lookups, NULL,
4205   ACCESS_CONF|RSRC_CONF,
4206   "\"on\" to enable, \"off\" to disable reverse DNS lookups, or \"double\" to "
4207   "enable double-reverse DNS lookups"),
4208 AP_INIT_TAKE1("ServerAdmin", set_server_string_slot,
4209   (void *)APR_OFFSETOF(server_rec, server_admin), RSRC_CONF,
4210   "The email address of the server administrator"),
4211 AP_INIT_TAKE1("ServerName", server_hostname_port, NULL, RSRC_CONF,
4212   "The hostname and port of the server"),
4213 AP_INIT_TAKE1("ServerSignature", set_signature_flag, NULL, OR_ALL,
4214   "En-/disable server signature (on|off|email)"),
4215 AP_INIT_TAKE1("ServerRoot", set_server_root, NULL, RSRC_CONF | EXEC_ON_READ,
4216   "Common directory of server-related files (logs, confs, etc.)"),
4217 AP_INIT_TAKE1("DefaultRuntimeDir", set_runtime_dir, NULL, RSRC_CONF | EXEC_ON_READ,
4218   "Common directory for run-time files (shared memory, locks, etc.)"),
4219 AP_INIT_TAKE12("ErrorLog", set_errorlog,
4220   (void *)APR_OFFSETOF(server_rec, error_fname), RSRC_CONF,
4221   "The filename of the error log"),
4222 AP_INIT_TAKE12("ErrorLogFormat", set_errorlog_format, NULL, RSRC_CONF,
4223   "Format string for the ErrorLog"),
4224 AP_INIT_RAW_ARGS("ServerAlias", set_server_alias, NULL, RSRC_CONF,
4225   "A name or names alternately used to access the server"),
4226 AP_INIT_TAKE1("ServerPath", set_serverpath, NULL, RSRC_CONF,
4227   "The pathname the server can be reached at"),
4228 AP_INIT_TAKE1("Timeout", set_timeout, NULL, RSRC_CONF,
4229   "Timeout duration (sec)"),
4230 AP_INIT_FLAG("ContentDigest", set_content_md5, NULL, OR_OPTIONS,
4231   "whether or not to send a Content-MD5 header with each request"),
4232 AP_INIT_TAKE1("UseCanonicalName", set_use_canonical_name, NULL,
4233   RSRC_CONF|ACCESS_CONF,
4234   "How to work out the ServerName : Port when constructing URLs"),
4235 AP_INIT_TAKE1("UseCanonicalPhysicalPort", set_use_canonical_phys_port, NULL,
4236   RSRC_CONF|ACCESS_CONF,
4237   "Whether to use the physical Port when constructing URLs"),
4238 /* TODO: RlimitFoo should all be part of mod_cgi, not in the core */
4239 /* TODO: ListenBacklog in MPM */
4240 AP_INIT_TAKE1("Include", include_config, NULL,
4241   (RSRC_CONF | ACCESS_CONF | EXEC_ON_READ),
4242   "Name(s) of the config file(s) to be included; fails if the wildcard does "
4243   "not match at least one file"),
4244 AP_INIT_TAKE1("IncludeOptional", include_config, (void*)1,
4245   (RSRC_CONF | ACCESS_CONF | EXEC_ON_READ),
4246   "Name or pattern of the config file(s) to be included; ignored if the file "
4247   "does not exist or the pattern does not match any files"),
4248 AP_INIT_ITERATE("LogLevel", set_loglevel, NULL, RSRC_CONF|ACCESS_CONF,
4249   "Level of verbosity in error logging"),
4250 AP_INIT_TAKE_ARGV("LogLevelOverride", set_loglevel_override, NULL, RSRC_CONF,
4251   "Override LogLevel for clients with certain IPs"),
4252 AP_INIT_TAKE1("NameVirtualHost", ap_set_name_virtual_host, NULL, RSRC_CONF,
4253   "A numeric IP address:port, or the name of a host"),
4254 AP_INIT_TAKE1("ServerTokens", set_serv_tokens, NULL, RSRC_CONF,
4255   "Determine tokens displayed in the Server: header - Min(imal), "
4256   "Major, Minor, Prod(uctOnly), OS, or Full"),
4257 AP_INIT_TAKE1("LimitRequestLine", set_limit_req_line, NULL, RSRC_CONF,
4258   "Limit on maximum size of an HTTP request line"),
4259 AP_INIT_TAKE1("LimitRequestFieldsize", set_limit_req_fieldsize, NULL,
4260   RSRC_CONF,
4261   "Limit on maximum size of an HTTP request header field"),
4262 AP_INIT_TAKE1("LimitRequestFields", set_limit_req_fields, NULL, RSRC_CONF,
4263   "Limit (0 = unlimited) on max number of header fields in a request message"),
4264 AP_INIT_TAKE1("LimitRequestBody", set_limit_req_body,
4265   (void*)APR_OFFSETOF(core_dir_config, limit_req_body), OR_ALL,
4266   "Limit (in bytes) on maximum size of request message body"),
4267 AP_INIT_TAKE1("LimitXMLRequestBody", set_limit_xml_req_body, NULL, OR_ALL,
4268               "Limit (in bytes) on maximum size of an XML-based request "
4269               "body"),
4270 AP_INIT_RAW_ARGS("Mutex", ap_set_mutex, NULL, RSRC_CONF,
4271                  "mutex (or \"default\") and mechanism"),
4272
4273 AP_INIT_TAKE1("MaxRanges", set_max_ranges, NULL, RSRC_CONF|ACCESS_CONF,
4274               "Maximum number of Ranges in a request before returning the entire "
4275               "resource, or 0 for unlimited"),
4276 AP_INIT_TAKE1("MaxRangeOverlaps", set_max_overlaps, NULL, RSRC_CONF|ACCESS_CONF,
4277               "Maximum number of overlaps in Ranges in a request before returning the entire "
4278               "resource, or 0 for unlimited"),
4279 AP_INIT_TAKE1("MaxRangeReversals", set_max_reversals, NULL, RSRC_CONF|ACCESS_CONF,
4280               "Maximum number of reversals in Ranges in a request before returning the entire "
4281               "resource, or 0 for unlimited"),
4282 /* System Resource Controls */
4283 #ifdef RLIMIT_CPU
4284 AP_INIT_TAKE12("RLimitCPU", set_limit_cpu,
4285   (void*)APR_OFFSETOF(core_dir_config, limit_cpu),
4286   OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
4287 #else
4288 AP_INIT_TAKE12("RLimitCPU", no_set_limit, NULL,
4289   OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
4290 #endif
4291 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined (RLIMIT_AS)
4292 AP_INIT_TAKE12("RLimitMEM", set_limit_mem,
4293   (void*)APR_OFFSETOF(core_dir_config, limit_mem),
4294   OR_ALL, "Soft/hard limits for max memory usage per process"),
4295 #else
4296 AP_INIT_TAKE12("RLimitMEM", no_set_limit, NULL,
4297   OR_ALL, "Soft/hard limits for max memory usage per process"),
4298 #endif
4299 #ifdef RLIMIT_NPROC
4300 AP_INIT_TAKE12("RLimitNPROC", set_limit_nproc,
4301   (void*)APR_OFFSETOF(core_dir_config, limit_nproc),
4302   OR_ALL, "soft/hard limits for max number of processes per uid"),
4303 #else
4304 AP_INIT_TAKE12("RLimitNPROC", no_set_limit, NULL,
4305    OR_ALL, "soft/hard limits for max number of processes per uid"),
4306 #endif
4307
4308 /* internal recursion stopper */
4309 AP_INIT_TAKE12("LimitInternalRecursion", set_recursion_limit, NULL, RSRC_CONF,
4310               "maximum recursion depth of internal redirects and subrequests"),
4311
4312 AP_INIT_TAKE1("ForceType", ap_set_string_slot_lower,
4313        (void *)APR_OFFSETOF(core_dir_config, mime_type), OR_FILEINFO,
4314      "a mime type that overrides other configured type"),
4315 AP_INIT_TAKE1("SetHandler", ap_set_string_slot_lower,
4316        (void *)APR_OFFSETOF(core_dir_config, handler), OR_FILEINFO,
4317    "a handler name that overrides any other configured handler"),
4318 AP_INIT_TAKE1("SetOutputFilter", ap_set_string_slot,
4319        (void *)APR_OFFSETOF(core_dir_config, output_filters), OR_FILEINFO,
4320    "filter (or ; delimited list of filters) to be run on the request content"),
4321 AP_INIT_TAKE1("SetInputFilter", ap_set_string_slot,
4322        (void *)APR_OFFSETOF(core_dir_config, input_filters), OR_FILEINFO,
4323    "filter (or ; delimited list of filters) to be run on the request body"),
4324 AP_INIT_TAKE1("AllowEncodedSlashes", set_allow2f, NULL, RSRC_CONF,
4325              "Allow URLs containing '/' encoded as '%2F'"),
4326
4327 /* scoreboard.c directives */
4328 AP_INIT_TAKE1("ScoreBoardFile", ap_set_scoreboard, NULL, RSRC_CONF,
4329               "A file for Apache to maintain runtime process management information"),
4330 AP_INIT_FLAG("ExtendedStatus", ap_set_extended_status, NULL, RSRC_CONF,
4331              "\"On\" to track extended status information, \"Off\" to disable"),
4332 AP_INIT_FLAG("SeeRequestTail", ap_set_reqtail, NULL, RSRC_CONF,
4333              "For extended status, \"On\" to see the last 63 chars of "
4334              "the request line, \"Off\" (default) to see the first 63"),
4335
4336 /*
4337  * These are default configuration directives that mpms can/should
4338  * pay attention to.
4339  * XXX These are not for all platforms, and even some Unix MPMs might not want
4340  * some directives.
4341  */
4342 AP_INIT_TAKE1("PidFile",  ap_mpm_set_pidfile, NULL, RSRC_CONF,
4343               "A file for logging the server process ID"),
4344 AP_INIT_TAKE1("MaxRequestsPerChild", ap_mpm_set_max_requests, NULL, RSRC_CONF,
4345               "Maximum number of connections a particular child serves before "
4346               "dying. (DEPRECATED, use MaxConnectionsPerChild)"),
4347 AP_INIT_TAKE1("MaxConnectionsPerChild", ap_mpm_set_max_requests, NULL, RSRC_CONF,
4348               "Maximum number of connections a particular child serves before dying."),
4349 AP_INIT_TAKE1("CoreDumpDirectory", ap_mpm_set_coredumpdir, NULL, RSRC_CONF,
4350               "The location of the directory Apache changes to before dumping core"),
4351 AP_INIT_TAKE1("MaxMemFree", ap_mpm_set_max_mem_free, NULL, RSRC_CONF,
4352               "Maximum number of 1k blocks a particular child's allocator may hold."),
4353 AP_INIT_TAKE1("ThreadStackSize", ap_mpm_set_thread_stacksize, NULL, RSRC_CONF,
4354               "Size in bytes of stack used by threads handling client connections"),
4355 #if AP_ENABLE_EXCEPTION_HOOK
4356 AP_INIT_TAKE1("EnableExceptionHook", ap_mpm_set_exception_hook, NULL, RSRC_CONF,
4357               "Controls whether exception hook may be called after a crash"),
4358 #endif
4359 AP_INIT_TAKE1("TraceEnable", set_trace_enable, NULL, RSRC_CONF,
4360               "'on' (default), 'off' or 'extended' to trace request body content"),
4361 AP_INIT_ITERATE("HttpProtocol", set_http_protocol, NULL, RSRC_CONF,
4362               "'min=0.9' (default) or 'min=1.0' to allow/deny HTTP/0.9; "
4363               "'liberal', 'strict', 'strict,log-only'"),
4364 AP_INIT_ITERATE("RegisterHttpMethod", set_http_method, NULL, RSRC_CONF,
4365                 "Registers non-standard HTTP methods"),
4366 AP_INIT_FLAG("HttpContentLengthHeadZero", set_cl_head_zero, NULL, OR_OPTIONS,
4367   "whether to permit Content-Length of 0 responses to HEAD requests"),
4368 AP_INIT_FLAG("HttpExpectStrict", set_expect_strict, NULL, OR_OPTIONS,
4369   "whether to return a 417 if a client doesn't send 100-Continue"),
4370 { NULL }
4371 };
4372
4373 /*****************************************************************
4374  *
4375  * Core handlers for various phases of server operation...
4376  */
4377
4378 AP_DECLARE_NONSTD(int) ap_core_translate(request_rec *r)
4379 {
4380     apr_status_t rv;
4381     char *path;
4382
4383     /* XXX this seems too specific, this should probably become
4384      * some general-case test
4385      */
4386     if (r->proxyreq) {
4387         return HTTP_FORBIDDEN;
4388     }
4389     if (!r->uri || ((r->uri[0] != '/') && strcmp(r->uri, "*"))) {
4390         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00126)
4391                      "Invalid URI in request %s", r->the_request);
4392         return HTTP_BAD_REQUEST;
4393     }
4394
4395     if (r->server->path
4396         && !strncmp(r->uri, r->server->path, r->server->pathlen)
4397         && (r->server->path[r->server->pathlen - 1] == '/'
4398             || r->uri[r->server->pathlen] == '/'
4399             || r->uri[r->server->pathlen] == '\0'))
4400     {
4401         path = r->uri + r->server->pathlen;
4402     }
4403     else {
4404         path = r->uri;
4405     }
4406     /*
4407      * Make sure that we do not mess up the translation by adding two
4408      * /'s in a row.  This happens under windows when the document
4409      * root ends with a /
4410      */
4411     /* skip all leading /'s (e.g. http://localhost///foo)
4412      * so we are looking at only the relative path.
4413      */
4414     while (*path == '/') {
4415         ++path;
4416     }
4417     if ((rv = apr_filepath_merge(&r->filename, ap_document_root(r), path,
4418                                  APR_FILEPATH_TRUENAME
4419                                | APR_FILEPATH_SECUREROOT, r->pool))
4420                 != APR_SUCCESS) {
4421         ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(00127)
4422                      "Cannot map %s to file", r->the_request);
4423         return HTTP_FORBIDDEN;
4424     }
4425     r->canonical_filename = r->filename;
4426
4427     return OK;
4428 }
4429
4430 /*****************************************************************
4431  *
4432  * Test the filesystem name through directory_walk and file_walk
4433  */
4434 static int core_map_to_storage(request_rec *r)
4435 {
4436     int access_status;
4437
4438     if ((access_status = ap_directory_walk(r))) {
4439         return access_status;
4440     }
4441
4442     if ((access_status = ap_file_walk(r))) {
4443         return access_status;
4444     }
4445
4446     return OK;
4447 }
4448
4449
4450 static int do_nothing(request_rec *r) { return OK; }
4451
4452
4453 static int core_override_type(request_rec *r)
4454 {
4455     core_dir_config *conf =
4456         (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
4457
4458     /* Check for overrides with ForceType / SetHandler
4459      */
4460     if (conf->mime_type && strcmp(conf->mime_type, "none"))
4461         ap_set_content_type(r, (char*) conf->mime_type);
4462
4463     if (conf->handler && strcmp(conf->handler, "none"))
4464         r->handler = conf->handler;
4465
4466     /* Deal with the poor soul who is trying to force path_info to be
4467      * accepted within the core_handler, where they will let the subreq
4468      * address its contents.  This is toggled by the user in the very
4469      * beginning of the fixup phase (here!), so modules should override the user's
4470      * discretion in their own module fixup phase.  It is tristate, if
4471      * the user doesn't specify, the result is AP_REQ_DEFAULT_PATH_INFO.
4472      * (which the module may interpret to its own customary behavior.)
4473      * It won't be touched if the value is no longer AP_ACCEPT_PATHINFO_UNSET,
4474      * so any module changing the value prior to the fixup phase
4475      * OVERRIDES the user's choice.
4476      */
4477     if ((r->used_path_info == AP_REQ_DEFAULT_PATH_INFO)
4478         && (conf->accept_path_info != AP_ACCEPT_PATHINFO_UNSET)) {
4479         /* No module knew better, and the user coded AcceptPathInfo */
4480         r->used_path_info = conf->accept_path_info;
4481     }
4482
4483     return OK;
4484 }
4485
4486 static int default_handler(request_rec *r)
4487 {
4488     conn_rec *c = r->connection;
4489     apr_bucket_brigade *bb;
4490     apr_bucket *e;
4491     core_dir_config *d;
4492     int errstatus;
4493     apr_file_t *fd = NULL;
4494     apr_status_t status;
4495     /* XXX if/when somebody writes a content-md5 filter we either need to
4496      *     remove this support or coordinate when to use the filter vs.
4497      *     when to use this code
4498      *     The current choice of when to compute the md5 here matches the 1.3
4499      *     support fairly closely (unlike 1.3, we don't handle computing md5
4500      *     when the charset is translated).
4501      */
4502     int bld_content_md5;
4503
4504     d = (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
4505     bld_content_md5 = (d->content_md5 == AP_CONTENT_MD5_ON)
4506                       && r->output_filters->frec->ftype != AP_FTYPE_RESOURCE;
4507
4508     ap_allow_standard_methods(r, MERGE_ALLOW, M_GET, M_OPTIONS, M_POST, -1);
4509
4510     /* If filters intend to consume the request body, they must
4511      * register an InputFilter to slurp the contents of the POST
4512      * data from the POST input stream.  It no longer exists when
4513      * the output filters are invoked by the default handler.
4514      */
4515     if ((errstatus = ap_discard_request_body(r)) != OK) {
4516         return errstatus;
4517     }
4518
4519     if (r->method_number == M_GET || r->method_number == M_POST) {
4520         if (r->finfo.filetype == APR_NOFILE) {
4521             ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00128)
4522                           "File does not exist: %s",
4523                           apr_pstrcat(r->pool, r->filename, r->path_info, NULL));
4524             return HTTP_NOT_FOUND;
4525         }
4526
4527         /* Don't try to serve a dir.  Some OSs do weird things with
4528          * raw I/O on a dir.
4529          */
4530         if (r->finfo.filetype == APR_DIR) {
4531             ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00129)
4532                           "Attempt to serve directory: %s", r->filename);
4533             return HTTP_NOT_FOUND;
4534         }
4535
4536         if ((r->used_path_info != AP_REQ_ACCEPT_PATH_INFO) &&
4537             r->path_info && *r->path_info)
4538         {
4539             /* default to reject */
4540             ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00130)
4541                           "File does not exist: %s",
4542                           apr_pstrcat(r->pool, r->filename, r->path_info, NULL));
4543             return HTTP_NOT_FOUND;
4544         }
4545
4546         /* We understood the (non-GET) method, but it might not be legal for
4547            this particular resource. Check to see if the 'deliver_script'
4548            flag is set. If so, then we go ahead and deliver the file since
4549            it isn't really content (only GET normally returns content).
4550
4551            Note: based on logic further above, the only possible non-GET
4552            method at this point is POST. In the future, we should enable
4553            script delivery for all methods.  */
4554         if (r->method_number != M_GET) {
4555             core_request_config *req_cfg;
4556
4557             req_cfg = ap_get_core_module_config(r->request_config);
4558             if (!req_cfg->deliver_script) {
4559                 /* The flag hasn't been set for this request. Punt. */
4560                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00131)
4561                               "This resource does not accept the %s method.",
4562                               r->method);
4563                 return HTTP_METHOD_NOT_ALLOWED;
4564             }
4565         }
4566
4567
4568         if ((status = apr_file_open(&fd, r->filename, APR_READ | APR_BINARY
4569 #if APR_HAS_SENDFILE
4570                             | AP_SENDFILE_ENABLED(d->enable_sendfile)
4571 #endif
4572                                     , 0, r->pool)) != APR_SUCCESS) {
4573             ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(00132)
4574                           "file permissions deny server access: %s", r->filename);
4575             return HTTP_FORBIDDEN;
4576         }
4577
4578         ap_update_mtime(r, r->finfo.mtime);
4579         ap_set_last_modified(r);
4580         ap_set_etag(r);
4581         ap_set_accept_ranges(r);
4582         ap_set_content_length(r, r->finfo.size);
4583         if (bld_content_md5) {
4584             apr_table_setn(r->headers_out, "Content-MD5",
4585                            ap_md5digest(r->pool, fd));
4586         }
4587
4588         bb = apr_brigade_create(r->pool, c->bucket_alloc);
4589
4590         if ((errstatus = ap_meets_conditions(r)) != OK) {
4591             apr_file_close(fd);
4592             r->status = errstatus;
4593         }
4594         else {
4595             e = apr_brigade_insert_file(bb, fd, 0, r->finfo.size, r->pool);
4596
4597 #if APR_HAS_MMAP
4598             if (d->enable_mmap == ENABLE_MMAP_OFF) {
4599                 (void)apr_bucket_file_enable_mmap(e, 0);
4600             }
4601 #endif
4602         }
4603
4604         e = apr_bucket_eos_create(c->bucket_alloc);
4605         APR_BRIGADE_INSERT_TAIL(bb, e);
4606
4607         status = ap_pass_brigade(r->output_filters, bb);
4608         if (status == APR_SUCCESS
4609             || r->status != HTTP_OK
4610             || c->aborted) {
4611             return OK;
4612         }
4613         else {
4614             /* no way to know what type of error occurred */
4615             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, status, r, APLOGNO(00133)
4616                           "default_handler: ap_pass_brigade returned %i",
4617                           status);
4618             return HTTP_INTERNAL_SERVER_ERROR;
4619         }
4620     }
4621     else {              /* unusual method (not GET or POST) */
4622         if (r->method_number == M_INVALID) {
4623             /* See if this looks like an undecrypted SSL handshake attempt.
4624              * It's safe to look a couple bytes into the_request if it exists, as it's
4625              * always allocated at least MIN_LINE_ALLOC (80) bytes.
4626              */
4627             if (r->the_request
4628                 && r->the_request[0] == 0x16
4629                 && (r->the_request[1] == 0x2 || r->the_request[1] == 0x3)) {
4630                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00134)
4631                               "Invalid method in request %s - possible attempt to establish SSL connection on non-SSL port", r->the_request);
4632             } else {
4633                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00135)
4634                               "Invalid method in request %s", r->the_request);
4635             }
4636             return HTTP_NOT_IMPLEMENTED;
4637         }
4638
4639         if (r->method_number == M_OPTIONS) {
4640             return ap_send_http_options(r);
4641         }
4642         return HTTP_METHOD_NOT_ALLOWED;
4643     }
4644 }
4645
4646 /* Optional function coming from mod_logio, used for logging of output
4647  * traffic
4648  */
4649 APR_OPTIONAL_FN_TYPE(ap_logio_add_bytes_out) *ap__logio_add_bytes_out;
4650 APR_OPTIONAL_FN_TYPE(authz_some_auth_required) *ap__authz_ap_some_auth_required;
4651
4652 /* Insist that at least one module will undertake to provide system
4653  * security by dropping startup privileges.
4654  */
4655 static int sys_privileges = 0;
4656 AP_DECLARE(int) ap_sys_privileges_handlers(int inc)
4657 {
4658     sys_privileges += inc;
4659     return sys_privileges;
4660 }
4661
4662 static int check_errorlog_dir(apr_pool_t *p, server_rec *s)
4663 {
4664     if (!s->error_fname || s->error_fname[0] == '|'
4665         || s->errorlog_provider != NULL) {
4666         return APR_SUCCESS;
4667     }
4668     else {
4669         char *abs = ap_server_root_relative(p, s->error_fname);
4670         char *dir = ap_make_dirstr_parent(p, abs);
4671         apr_finfo_t finfo;
4672         apr_status_t rv = apr_stat(&finfo, dir, APR_FINFO_TYPE, p);
4673         if (rv == APR_SUCCESS && finfo.filetype != APR_DIR)
4674             rv = APR_ENOTDIR;
4675         if (rv != APR_SUCCESS) {
4676             const char *desc = "main error log";
4677             if (s->defn_name)
4678                 desc = apr_psprintf(p, "error log of vhost defined at %s:%d",
4679                                     s->defn_name, s->defn_line_number);
4680             ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_EMERG, rv,
4681                           ap_server_conf, APLOGNO(02291)
4682                          "Cannot access directory '%s' for %s", dir, desc);
4683             return !OK;
4684         }
4685     }
4686     return OK;
4687 }
4688
4689 static int core_check_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
4690 {
4691     int rv = OK;
4692     while (s) {
4693         if (check_errorlog_dir(ptemp, s) != OK)
4694             rv = !OK;
4695         s = s->next;
4696     }
4697     return rv;
4698 }
4699
4700
4701 static int core_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
4702 {
4703     ap_mutex_init(pconf);
4704
4705     if (!saved_server_config_defines)
4706         init_config_defines(pconf);
4707     apr_pool_cleanup_register(pconf, NULL, reset_config_defines,
4708                               apr_pool_cleanup_null);
4709
4710     mpm_common_pre_config(pconf);
4711
4712     return OK;
4713 }
4714
4715 static int core_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
4716 {
4717     ap__logio_add_bytes_out = APR_RETRIEVE_OPTIONAL_FN(ap_logio_add_bytes_out);
4718     ident_lookup = APR_RETRIEVE_OPTIONAL_FN(ap_ident_lookup);
4719     ap__authz_ap_some_auth_required = APR_RETRIEVE_OPTIONAL_FN(authz_some_auth_required);
4720     authn_ap_auth_type = APR_RETRIEVE_OPTIONAL_FN(authn_ap_auth_type);
4721     authn_ap_auth_name = APR_RETRIEVE_OPTIONAL_FN(authn_ap_auth_name);
4722     access_compat_ap_satisfies = APR_RETRIEVE_OPTIONAL_FN(access_compat_ap_satisfies);
4723
4724     set_banner(pconf);
4725     ap_setup_make_content_type(pconf);
4726     ap_setup_auth_internal(ptemp);
4727     if (!sys_privileges) {
4728         ap_log_error(APLOG_MARK, APLOG_CRIT, 0, NULL, APLOGNO(00136)
4729                      "Server MUST relinquish startup privileges before "
4730                      "accepting connections.  Please ensure mod_unixd "
4731                      "or other system security module is loaded.");
4732         return !OK;
4733     }
4734     apr_pool_cleanup_register(pconf, NULL, ap_mpm_end_gen_helper,
4735                               apr_pool_cleanup_null);
4736     return OK;
4737 }
4738
4739 static void core_insert_filter(request_rec *r)
4740 {
4741     core_dir_config *conf = (core_dir_config *)
4742                             ap_get_core_module_config(r->per_dir_config);
4743     const char *filter, *filters = conf->output_filters;
4744
4745     if (filters) {
4746         while (*filters && (filter = ap_getword(r->pool, &filters, ';'))) {
4747             ap_add_output_filter(filter, NULL, r, r->connection);
4748         }
4749     }
4750
4751     filters = conf->input_filters;
4752     if (filters) {
4753         while (*filters && (filter = ap_getword(r->pool, &filters, ';'))) {
4754             ap_add_input_filter(filter, NULL, r, r->connection);
4755         }
4756     }
4757 }
4758
4759 static apr_size_t num_request_notes = AP_NUM_STD_NOTES;
4760
4761 static apr_status_t reset_request_notes(void *dummy)
4762 {
4763     num_request_notes = AP_NUM_STD_NOTES;
4764     return APR_SUCCESS;
4765 }
4766
4767 AP_DECLARE(apr_size_t) ap_register_request_note(void)
4768 {
4769     apr_pool_cleanup_register(apr_hook_global_pool, NULL, reset_request_notes,
4770                               apr_pool_cleanup_null);
4771     return num_request_notes++;
4772 }
4773
4774 AP_DECLARE(void **) ap_get_request_note(request_rec *r, apr_size_t note_num)
4775 {
4776     core_request_config *req_cfg;
4777
4778     if (note_num >= num_request_notes) {
4779         return NULL;
4780     }
4781
4782     req_cfg = (core_request_config *)
4783         ap_get_core_module_config(r->request_config);
4784
4785     if (!req_cfg) {
4786         return NULL;
4787     }
4788
4789     return &(req_cfg->notes[note_num]);
4790 }
4791
4792 AP_DECLARE(apr_socket_t *) ap_get_conn_socket(conn_rec *c)
4793 {
4794     return ap_get_core_module_config(c->conn_config);
4795 }
4796
4797 static int core_create_req(request_rec *r)
4798 {
4799     /* Alloc the config struct and the array of request notes in
4800      * a single block for efficiency
4801      */
4802     core_request_config *req_cfg;
4803
4804     req_cfg = apr_pcalloc(r->pool, sizeof(core_request_config) +
4805                           sizeof(void *) * num_request_notes);
4806     req_cfg->notes = (void **)((char *)req_cfg + sizeof(core_request_config));
4807
4808     /* ### temporarily enable script delivery as the default */
4809     req_cfg->deliver_script = 1;
4810
4811     if (r->main) {
4812         core_request_config *main_req_cfg = (core_request_config *)
4813             ap_get_core_module_config(r->main->request_config);
4814         req_cfg->bb = main_req_cfg->bb;
4815     }
4816     else {
4817         req_cfg->bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
4818     }
4819
4820     ap_set_core_module_config(r->request_config, req_cfg);
4821
4822     return OK;
4823 }
4824
4825 static int core_create_proxy_req(request_rec *r, request_rec *pr)
4826 {
4827     return core_create_req(pr);
4828 }
4829
4830 static conn_rec *core_create_conn(apr_pool_t *ptrans, server_rec *s,
4831                                   apr_socket_t *csd, long id, void *sbh,
4832                                   apr_bucket_alloc_t *alloc)
4833 {
4834     apr_status_t rv;
4835     apr_pool_t *pool;
4836     conn_rec *c = (conn_rec *) apr_pcalloc(ptrans, sizeof(conn_rec));
4837     core_server_config *sconf = ap_get_core_module_config(s->module_config);
4838
4839     c->sbh = sbh;
4840     (void)ap_update_child_status(c->sbh, SERVER_BUSY_READ, (request_rec *)NULL);
4841
4842     /* Got a connection structure, so initialize what fields we can
4843      * (the rest are zeroed out by pcalloc).
4844      */
4845     apr_pool_create(&pool, ptrans);
4846     apr_pool_tag(pool, "master_conn");
4847     c->pool = pool;
4848
4849     c->conn_config = ap_create_conn_config(c->pool);
4850     c->notes = apr_table_make(c->pool, 5);
4851     c->slaves = apr_array_make(c->pool, 20, sizeof(conn_slave_rec *));
4852
4853
4854     if ((rv = apr_socket_addr_get(&c->local_addr, APR_LOCAL, csd))
4855         != APR_SUCCESS) {
4856         ap_log_error(APLOG_MARK, APLOG_INFO, rv, s, APLOGNO(00137)
4857                      "apr_socket_addr_get(APR_LOCAL)");
4858         apr_socket_close(csd);
4859         return NULL;
4860     }
4861
4862     apr_sockaddr_ip_get(&c->local_ip, c->local_addr);
4863     if ((rv = apr_socket_addr_get(&c->client_addr, APR_REMOTE, csd))
4864         != APR_SUCCESS) {
4865         ap_log_error(APLOG_MARK, APLOG_INFO, rv, s, APLOGNO(00138)
4866                      "apr_socket_addr_get(APR_REMOTE)");
4867         apr_socket_close(csd);
4868         return NULL;
4869     }
4870
4871     apr_sockaddr_ip_get(&c->client_ip, c->client_addr);
4872     c->base_server = s;
4873
4874     c->id = id;
4875     c->bucket_alloc = alloc;
4876
4877     c->clogging_input_filters = 0;
4878
4879     if (sconf->conn_log_level) {
4880         int i;
4881         conn_log_config *conf;
4882         const struct ap_logconf *log = NULL;
4883         struct ap_logconf *merged;
4884
4885         for (i = 0; i < sconf->conn_log_level->nelts; i++) {
4886             conf = APR_ARRAY_IDX(sconf->conn_log_level, i, conn_log_config *);
4887             if (apr_ipsubnet_test(conf->subnet, c->client_addr))
4888                 log = &conf->log;
4889         }
4890         if (log) {
4891             merged = ap_new_log_config(c->pool, log);
4892             ap_merge_log_config(&s->log, merged);
4893             c->log = merged;
4894         }
4895     }
4896
4897     return c;
4898 }
4899
4900 static int core_pre_connection(conn_rec *c, void *csd)
4901 {
4902     core_net_rec *net = apr_palloc(c->pool, sizeof(*net));
4903     apr_status_t rv;
4904
4905     /* The Nagle algorithm says that we should delay sending partial
4906      * packets in hopes of getting more data.  We don't want to do
4907      * this; we are not telnet.  There are bad interactions between
4908      * persistent connections and Nagle's algorithm that have very severe
4909      * performance penalties.  (Failing to disable Nagle is not much of a
4910      * problem with simple HTTP.)
4911      */
4912     rv = apr_socket_opt_set(csd, APR_TCP_NODELAY, 1);
4913     if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
4914         /* expected cause is that the client disconnected already,
4915          * hence the debug level
4916          */
4917         ap_log_cerror(APLOG_MARK, APLOG_DEBUG, rv, c, APLOGNO(00139)
4918                       "apr_socket_opt_set(APR_TCP_NODELAY)");
4919     }
4920
4921     /* The core filter requires the timeout mode to be set, which
4922      * incidentally sets the socket to be nonblocking.  If this
4923      * is not initialized correctly, Linux - for example - will
4924      * be initially blocking, while Solaris will be non blocking
4925      * and any initial read will fail.
4926      */
4927     rv = apr_socket_timeout_set(csd, c->base_server->timeout);
4928     if (rv != APR_SUCCESS) {
4929         /* expected cause is that the client disconnected already */
4930         ap_log_cerror(APLOG_MARK, APLOG_DEBUG, rv, c, APLOGNO(00140)
4931                       "apr_socket_timeout_set");
4932     }
4933
4934     net->c = c;
4935     net->in_ctx = NULL;
4936     net->out_ctx = NULL;
4937     net->client_socket = csd;
4938
4939     ap_set_core_module_config(net->c->conn_config, csd);
4940     /* only the master connection talks to the network */
4941     if (c->master == NULL) {
4942         ap_add_input_filter_handle(ap_core_input_filter_handle, net, NULL,
4943                                    net->c);
4944         ap_add_output_filter_handle(ap_core_output_filter_handle, net, NULL,
4945                                     net->c);
4946     }
4947     return DONE;
4948 }
4949
4950 AP_CORE_DECLARE(conn_rec *) ap_create_slave_connection(conn_rec *c)
4951 {
4952     apr_pool_t *pool;
4953     conn_slave_rec *new;
4954     conn_rec *sc = (conn_rec *) apr_palloc(c->pool, sizeof(conn_rec));
4955
4956     apr_pool_create(&pool, c->pool);
4957     apr_pool_tag(pool, "slave_conn");
4958     memcpy(sc, c, sizeof(conn_rec));
4959     sc->slaves = NULL;
4960     sc->master = c;
4961     sc->input_filters = NULL;
4962     sc->output_filters = NULL;
4963     sc->pool = pool;
4964     new = apr_array_push(c->slaves);
4965     new->c = sc;
4966     return sc;
4967 }
4968
4969 AP_DECLARE(int) ap_state_query(int query)
4970 {
4971     switch (query) {
4972     case AP_SQ_MAIN_STATE:
4973         return ap_main_state;
4974     case AP_SQ_RUN_MODE:
4975         return ap_run_mode;
4976     case AP_SQ_CONFIG_GEN:
4977         return ap_config_generation;
4978     default:
4979         return AP_SQ_NOT_SUPPORTED;
4980     }
4981 }
4982
4983 static apr_random_t *rng = NULL;
4984 #if APR_HAS_THREADS
4985 static apr_thread_mutex_t *rng_mutex = NULL;
4986 #endif
4987
4988 static void core_child_init(apr_pool_t *pchild, server_rec *s)
4989 {
4990     apr_proc_t proc;
4991 #if APR_HAS_THREADS
4992     int threaded_mpm;
4993     if (ap_mpm_query(AP_MPMQ_IS_THREADED, &threaded_mpm) == APR_SUCCESS
4994         && threaded_mpm)
4995     {
4996         apr_thread_mutex_create(&rng_mutex, APR_THREAD_MUTEX_DEFAULT, pchild);
4997     }
4998 #endif
4999     /* The MPMs use plain fork() and not apr_proc_fork(), so we have to call
5000      * apr_random_after_fork() manually in the child
5001      */
5002     proc.pid = getpid();
5003     apr_random_after_fork(&proc);
5004 }
5005
5006 AP_CORE_DECLARE(void) ap_random_parent_after_fork(void)
5007 {
5008     /*
5009      * To ensure that the RNG state in the parent changes after the fork, we
5010      * pull some data from the RNG and discard it. This ensures that the RNG
5011      * states in the children are different even after the pid wraps around.
5012      * As we only use apr_random for insecure random bytes, pulling 2 bytes
5013      * should be enough.
5014      * XXX: APR should probably have some dedicated API to do this, but it
5015      * XXX: currently doesn't.
5016      */
5017     apr_uint16_t data;
5018     apr_random_insecure_bytes(rng, &data, sizeof(data));
5019 }
5020
5021 AP_CORE_DECLARE(void) ap_init_rng(apr_pool_t *p)
5022 {
5023     unsigned char seed[8];
5024     apr_status_t rv;
5025     rng = apr_random_standard_new(p);
5026     do {
5027         rv = apr_generate_random_bytes(seed, sizeof(seed));
5028         if (rv != APR_SUCCESS)
5029             goto error;
5030         apr_random_add_entropy(rng, seed, sizeof(seed));
5031         rv = apr_random_insecure_ready(rng);
5032     } while (rv == APR_ENOTENOUGHENTROPY);
5033     if (rv == APR_SUCCESS)
5034         return;
5035 error:
5036     ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, APLOGNO(00141)
5037                  "Could not initialize random number generator");
5038     exit(1);
5039 }
5040
5041 AP_DECLARE(void) ap_random_insecure_bytes(void *buf, apr_size_t size)
5042 {
5043 #if APR_HAS_THREADS
5044     if (rng_mutex)
5045         apr_thread_mutex_lock(rng_mutex);
5046 #endif
5047     /* apr_random_insecure_bytes can only fail with APR_ENOTENOUGHENTROPY,
5048      * and we have ruled that out during initialization. Therefore we don't
5049      * need to check the return code.
5050      */
5051     apr_random_insecure_bytes(rng, buf, size);
5052 #if APR_HAS_THREADS
5053     if (rng_mutex)
5054         apr_thread_mutex_unlock(rng_mutex);
5055 #endif
5056 }
5057
5058 /*
5059  * Finding a random number in a range.
5060  *      n' = a + n(b-a+1)/(M+1)
5061  * where:
5062  *      n' = random number in range
5063  *      a  = low end of range
5064  *      b  = high end of range
5065  *      n  = random number of 0..M
5066  *      M  = maxint
5067  * Algorithm 'borrowed' from PHP's rand() function.
5068  */
5069 #define RAND_RANGE(__n, __min, __max, __tmax) \
5070 (__n) = (__min) + (long) ((double) ((__max) - (__min) + 1.0) * ((__n) / ((__tmax) + 1.0)))
5071 AP_DECLARE(apr_uint32_t) ap_random_pick(apr_uint32_t min, apr_uint32_t max)
5072 {
5073     apr_uint32_t number;
5074 #if (!__GNUC__ || __GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) || \
5075      !__sparc__ || APR_SIZEOF_VOIDP != 8)
5076     /* This triggers a gcc bug on sparc/64bit with gcc < 4.8, PR 52900 */
5077     if (max < 16384) {
5078         apr_uint16_t num16;
5079         ap_random_insecure_bytes(&num16, sizeof(num16));
5080         RAND_RANGE(num16, min, max, APR_UINT16_MAX);
5081         number = num16;
5082     }
5083     else
5084 #endif
5085     {
5086         ap_random_insecure_bytes(&number, sizeof(number));
5087         RAND_RANGE(number, min, max, APR_UINT32_MAX);
5088     }
5089     return number;
5090 }
5091
5092 static apr_status_t core_insert_network_bucket(conn_rec *c,
5093                                                apr_bucket_brigade *bb,
5094                                                apr_socket_t *socket)
5095 {
5096     apr_bucket *e = apr_bucket_socket_create(socket, c->bucket_alloc);
5097     APR_BRIGADE_INSERT_TAIL(bb, e);
5098     return APR_SUCCESS;
5099 }
5100
5101 static apr_status_t core_dirwalk_stat(apr_finfo_t *finfo, request_rec *r,
5102                                       apr_int32_t wanted) 
5103 {
5104     return apr_stat(finfo, r->filename, wanted, r->pool);
5105 }
5106
5107 static void core_dump_config(apr_pool_t *p, server_rec *s)
5108 {
5109     core_server_config *sconf = ap_get_core_module_config(s->module_config);
5110     apr_file_t *out = NULL;
5111     const char *tmp;
5112     const char **defines;
5113     int i;
5114     if (!ap_exists_config_define("DUMP_RUN_CFG"))
5115         return;
5116
5117     apr_file_open_stdout(&out, p);
5118     apr_file_printf(out, "ServerRoot: \"%s\"\n", ap_server_root);
5119     tmp = ap_server_root_relative(p, sconf->ap_document_root);
5120     apr_file_printf(out, "Main DocumentRoot: \"%s\"\n", tmp);
5121     if (s->error_fname[0] != '|' && s->errorlog_provider == NULL)
5122         tmp = ap_server_root_relative(p, s->error_fname);
5123     else
5124         tmp = s->error_fname;
5125     apr_file_printf(out, "Main ErrorLog: \"%s\"\n", tmp);
5126     if (ap_scoreboard_fname) {
5127         tmp = ap_runtime_dir_relative(p, ap_scoreboard_fname);
5128         apr_file_printf(out, "ScoreBoardFile: \"%s\"\n", tmp);
5129     }
5130     ap_dump_mutexes(p, s, out);
5131     ap_mpm_dump_pidfile(p, out);
5132
5133     defines = (const char **)ap_server_config_defines->elts;
5134     for (i = 0; i < ap_server_config_defines->nelts; i++) {
5135         const char *name = defines[i];
5136         const char *val = NULL;
5137         if (server_config_defined_vars)
5138            val = apr_table_get(server_config_defined_vars, name);
5139         if (val)
5140             apr_file_printf(out, "Define: %s=%s\n", name, val);
5141         else
5142             apr_file_printf(out, "Define: %s\n", name);
5143     }
5144 }
5145
5146 static void register_hooks(apr_pool_t *p)
5147 {
5148     errorlog_hash = apr_hash_make(p);
5149     ap_register_log_hooks(p);
5150     ap_register_config_hooks(p);
5151     ap_expr_init(p);
5152
5153     /* create_connection and pre_connection should always be hooked
5154      * APR_HOOK_REALLY_LAST by core to give other modules the opportunity
5155      * to install alternate network transports and stop other functions
5156      * from being run.
5157      */
5158     ap_hook_create_connection(core_create_conn, NULL, NULL,
5159                               APR_HOOK_REALLY_LAST);
5160     ap_hook_pre_connection(core_pre_connection, NULL, NULL,
5161                            APR_HOOK_REALLY_LAST);
5162
5163     ap_hook_pre_config(core_pre_config, NULL, NULL, APR_HOOK_REALLY_FIRST);
5164     ap_hook_post_config(core_post_config,NULL,NULL,APR_HOOK_REALLY_FIRST);
5165     ap_hook_check_config(core_check_config,NULL,NULL,APR_HOOK_FIRST);
5166     ap_hook_test_config(core_dump_config,NULL,NULL,APR_HOOK_FIRST);
5167     ap_hook_translate_name(ap_core_translate,NULL,NULL,APR_HOOK_REALLY_LAST);
5168     ap_hook_map_to_storage(core_map_to_storage,NULL,NULL,APR_HOOK_REALLY_LAST);
5169     ap_hook_open_logs(ap_open_logs,NULL,NULL,APR_HOOK_REALLY_FIRST);
5170     ap_hook_child_init(core_child_init,NULL,NULL,APR_HOOK_REALLY_FIRST);
5171     ap_hook_child_init(ap_logs_child_init,NULL,NULL,APR_HOOK_MIDDLE);
5172     ap_hook_handler(default_handler,NULL,NULL,APR_HOOK_REALLY_LAST);
5173     /* FIXME: I suspect we can eliminate the need for these do_nothings - Ben */
5174     ap_hook_type_checker(do_nothing,NULL,NULL,APR_HOOK_REALLY_LAST);
5175     ap_hook_fixups(core_override_type,NULL,NULL,APR_HOOK_REALLY_FIRST);
5176     ap_hook_create_request(core_create_req, NULL, NULL, APR_HOOK_MIDDLE);
5177     APR_OPTIONAL_HOOK(proxy, create_req, core_create_proxy_req, NULL, NULL,
5178                       APR_HOOK_MIDDLE);
5179     ap_hook_pre_mpm(ap_create_scoreboard, NULL, NULL, APR_HOOK_MIDDLE);
5180     ap_hook_child_status(ap_core_child_status, NULL, NULL, APR_HOOK_MIDDLE);
5181     ap_hook_insert_network_bucket(core_insert_network_bucket, NULL, NULL,
5182                                   APR_HOOK_REALLY_LAST);
5183     ap_hook_dirwalk_stat(core_dirwalk_stat, NULL, NULL, APR_HOOK_REALLY_LAST);
5184     ap_hook_open_htaccess(ap_open_htaccess, NULL, NULL, APR_HOOK_REALLY_LAST);
5185     
5186     /* register the core's insert_filter hook and register core-provided
5187      * filters
5188      */
5189     ap_hook_insert_filter(core_insert_filter, NULL, NULL, APR_HOOK_MIDDLE);
5190
5191     ap_core_input_filter_handle =
5192         ap_register_input_filter("CORE_IN", ap_core_input_filter,
5193                                  NULL, AP_FTYPE_NETWORK);
5194     ap_content_length_filter_handle =
5195         ap_register_output_filter("CONTENT_LENGTH", ap_content_length_filter,
5196                                   NULL, AP_FTYPE_PROTOCOL);
5197     ap_core_output_filter_handle =
5198         ap_register_output_filter("CORE", ap_core_output_filter,
5199                                   NULL, AP_FTYPE_NETWORK);
5200     ap_subreq_core_filter_handle =
5201         ap_register_output_filter("SUBREQ_CORE", ap_sub_req_output_filter,
5202                                   NULL, AP_FTYPE_CONTENT_SET);
5203     ap_old_write_func =
5204         ap_register_output_filter("OLD_WRITE", ap_old_write_filter,
5205                                   NULL, AP_FTYPE_RESOURCE - 10);
5206 }
5207
5208 AP_DECLARE_MODULE(core) = {
5209     MPM20_MODULE_STUFF,
5210     AP_PLATFORM_REWRITE_ARGS_HOOK, /* hook to run before apache parses args */
5211     create_core_dir_config,       /* create per-directory config structure */
5212     merge_core_dir_configs,       /* merge per-directory config structures */
5213     create_core_server_config,    /* create per-server config structure */
5214     merge_core_server_configs,    /* merge per-server config structures */
5215     core_cmds,                    /* command apr_table_t */
5216     register_hooks                /* register hooks */
5217 };
5218