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