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