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