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