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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include "apr_strings.h"
20 #include "apr_fnmatch.h"
22 #include "apr_thread_proc.h" /* for RLIMIT stuff */
23 #include "apr_random.h"
25 #define APR_WANT_IOVEC
26 #define APR_WANT_STRFUNC
27 #define APR_WANT_MEMFUNC
30 #include "ap_config.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... */
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"
49 #include "mod_proxy.h"
50 #include "ap_listen.h"
52 #include "mod_so.h" /* for ap_find_loaded_module_symbol */
54 #if defined(RLIMIT_CPU) || defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS) || defined (RLIMIT_NPROC)
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)
65 /* LimitXMLRequestBody handling */
66 #define AP_LIMIT_UNSET ((long) -1)
67 #define AP_DEFAULT_LIMIT_XML_BODY ((apr_size_t)1000000)
69 #define AP_MIN_SENDFILE_BYTES (256)
71 /* maximum include nesting level */
72 #ifndef AP_MAX_INCLUDE_DEPTH
73 #define AP_MAX_INCLUDE_DEPTH (128)
76 /* valid in core-conf, but not in runtime r->used_path_info */
77 #define AP_ACCEPT_PATHINFO_UNSET 3
79 #define AP_CONTENT_MD5_OFF 0
80 #define AP_CONTENT_MD5_ON 1
81 #define AP_CONTENT_MD5_UNSET 2
84 APR_HOOK_LINK(get_mgmt_items)
85 APR_HOOK_LINK(insert_network_bucket)
88 AP_IMPLEMENT_HOOK_RUN_ALL(int, get_mgmt_items,
89 (apr_pool_t *p, const char *val, apr_hash_t *ht),
90 (p, val, ht), OK, DECLINED)
92 AP_IMPLEMENT_HOOK_RUN_FIRST(apr_status_t, insert_network_bucket,
93 (conn_rec *c, apr_bucket_brigade *bb,
94 apr_socket_t *socket),
95 (c, bb, socket), AP_DECLINED)
97 /* Server core module... This module provides support for really basic
98 * server operations, including options and commands which control the
99 * operation of other modules. Consider this the bureaucracy module.
101 * The core module also defines handlers, etc., to handle just enough
102 * to allow a server with the core module ONLY to actually serve documents.
104 * This file could almost be mod_core.c, except for the stuff which affects
105 * the http_conf_globals.
108 /* we know core's module_index is 0 */
109 #undef APLOG_MODULE_INDEX
110 #define APLOG_MODULE_INDEX AP_CORE_MODULE_INDEX
112 /* Handles for core filters */
113 AP_DECLARE_DATA ap_filter_rec_t *ap_subreq_core_filter_handle;
114 AP_DECLARE_DATA ap_filter_rec_t *ap_core_output_filter_handle;
115 AP_DECLARE_DATA ap_filter_rec_t *ap_content_length_filter_handle;
116 AP_DECLARE_DATA ap_filter_rec_t *ap_core_input_filter_handle;
118 /* Provide ap_document_root_check storage and default value = true */
119 AP_DECLARE_DATA int ap_document_root_check = 1;
121 /* magic pointer for ErrorDocument xxx "default" */
122 static char errordocument_default;
124 static apr_array_header_t *saved_server_config_defines = NULL;
125 static apr_table_t *server_config_defined_vars = NULL;
127 AP_DECLARE_DATA int ap_main_state = AP_SQ_MS_INITIAL_STARTUP;
128 AP_DECLARE_DATA int ap_run_mode = AP_SQ_RM_UNKNOWN;
129 AP_DECLARE_DATA int ap_config_generation = 0;
131 static void *create_core_dir_config(apr_pool_t *a, char *dir)
133 core_dir_config *conf;
135 conf = (core_dir_config *)apr_pcalloc(a, sizeof(core_dir_config));
137 /* conf->r and conf->d[_*] are initialized by dirsection() or left NULL */
139 conf->opts = dir ? OPT_UNSET : OPT_UNSET|OPT_SYM_LINKS;
140 conf->opts_add = conf->opts_remove = OPT_NONE;
141 conf->override = OR_UNSET|OR_NONE;
142 conf->override_opts = OPT_UNSET | OPT_ALL | OPT_SYM_OWNER | OPT_MULTI;
144 conf->content_md5 = AP_CONTENT_MD5_UNSET;
145 conf->accept_path_info = AP_ACCEPT_PATHINFO_UNSET;
147 conf->use_canonical_name = USE_CANONICAL_NAME_UNSET;
148 conf->use_canonical_phys_port = USE_CANONICAL_PHYS_PORT_UNSET;
150 conf->hostname_lookups = HOSTNAME_LOOKUP_UNSET;
153 * left as NULL (we use apr_pcalloc):
154 * conf->limit_cpu = NULL;
155 * conf->limit_mem = NULL;
156 * conf->limit_nproc = NULL;
157 * conf->sec_file = NULL;
158 * conf->sec_if = NULL;
161 conf->limit_req_body = AP_LIMIT_REQ_BODY_UNSET;
162 conf->limit_xml_body = AP_LIMIT_UNSET;
164 conf->server_signature = srv_sig_unset;
166 conf->add_default_charset = ADD_DEFAULT_CHARSET_UNSET;
167 conf->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
169 /* Overriding all negotiation
170 * Set NULL by apr_pcalloc:
171 * conf->mime_type = NULL;
172 * conf->handler = NULL;
173 * conf->output_filters = NULL;
174 * conf->input_filters = NULL;
178 * Flag for use of inodes in ETags.
180 conf->etag_bits = ETAG_UNSET;
181 conf->etag_add = ETAG_UNSET;
182 conf->etag_remove = ETAG_UNSET;
184 conf->enable_mmap = ENABLE_MMAP_UNSET;
185 conf->enable_sendfile = ENABLE_SENDFILE_UNSET;
186 conf->allow_encoded_slashes = 0;
187 conf->decode_encoded_slashes = 0;
189 conf->max_ranges = AP_MAXRANGES_UNSET;
190 conf->max_overlaps = AP_MAXRANGES_UNSET;
191 conf->max_reversals = AP_MAXRANGES_UNSET;
193 conf->cgi_pass_auth = AP_CGI_PASS_AUTH_UNSET;
194 conf->qualify_redirect_url = AP_CORE_CONFIG_UNSET;
199 static void *merge_core_dir_configs(apr_pool_t *a, void *basev, void *newv)
201 core_dir_config *base = (core_dir_config *)basev;
202 core_dir_config *new = (core_dir_config *)newv;
203 core_dir_config *conf;
205 /* Create this conf by duplicating the base, replacing elements
206 * (or creating copies for merging) where new-> values exist.
208 conf = (core_dir_config *)apr_pmemdup(a, base, sizeof(core_dir_config));
211 conf->d_is_fnmatch = new->d_is_fnmatch;
212 conf->d_components = new->d_components;
214 conf->refs = new->refs;
215 conf->condition = new->condition;
217 if (new->opts & OPT_UNSET) {
218 /* there was no explicit setting of new->opts, so we merge
219 * preserve the invariant (opts_add & opts_remove) == 0
221 conf->opts_add = (conf->opts_add & ~new->opts_remove) | new->opts_add;
222 conf->opts_remove = (conf->opts_remove & ~new->opts_add)
224 conf->opts = (conf->opts & ~conf->opts_remove) | conf->opts_add;
226 /* If Includes was enabled with exec in the base config, but
227 * was enabled without exec in the new config, then disable
228 * exec in the merged set. */
229 if (((base->opts & (OPT_INCLUDES|OPT_INC_WITH_EXEC))
230 == (OPT_INCLUDES|OPT_INC_WITH_EXEC))
231 && ((new->opts & (OPT_INCLUDES|OPT_INC_WITH_EXEC))
233 conf->opts &= ~OPT_INC_WITH_EXEC;
237 /* otherwise we just copy, because an explicit opts setting
238 * overrides all earlier +/- modifiers
240 conf->opts = new->opts;
241 conf->opts_add = new->opts_add;
242 conf->opts_remove = new->opts_remove;
245 if (!(new->override & OR_UNSET)) {
246 conf->override = new->override;
249 if (!(new->override_opts & OPT_UNSET)) {
250 conf->override_opts = new->override_opts;
253 if (new->override_list != NULL) {
254 conf->override_list = new->override_list;
257 if (conf->response_code_exprs == NULL) {
258 conf->response_code_exprs = new->response_code_exprs;
260 else if (new->response_code_exprs != NULL) {
261 conf->response_code_exprs = apr_hash_overlay(a,
262 new->response_code_exprs, conf->response_code_exprs);
264 /* Otherwise we simply use the base->response_code_exprs array
267 if (new->hostname_lookups != HOSTNAME_LOOKUP_UNSET) {
268 conf->hostname_lookups = new->hostname_lookups;
271 if (new->content_md5 != AP_CONTENT_MD5_UNSET) {
272 conf->content_md5 = new->content_md5;
275 if (new->accept_path_info != AP_ACCEPT_PATHINFO_UNSET) {
276 conf->accept_path_info = new->accept_path_info;
279 if (new->use_canonical_name != USE_CANONICAL_NAME_UNSET) {
280 conf->use_canonical_name = new->use_canonical_name;
283 if (new->use_canonical_phys_port != USE_CANONICAL_PHYS_PORT_UNSET) {
284 conf->use_canonical_phys_port = new->use_canonical_phys_port;
288 if (new->limit_cpu) {
289 conf->limit_cpu = new->limit_cpu;
293 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
294 if (new->limit_mem) {
295 conf->limit_mem = new->limit_mem;
300 if (new->limit_nproc) {
301 conf->limit_nproc = new->limit_nproc;
305 if (new->limit_req_body != AP_LIMIT_REQ_BODY_UNSET) {
306 conf->limit_req_body = new->limit_req_body;
309 if (new->limit_xml_body != AP_LIMIT_UNSET)
310 conf->limit_xml_body = new->limit_xml_body;
312 if (!conf->sec_file) {
313 conf->sec_file = new->sec_file;
315 else if (new->sec_file) {
316 /* If we merge, the merge-result must have its own array
318 conf->sec_file = apr_array_append(a, base->sec_file, new->sec_file);
320 /* Otherwise we simply use the base->sec_file array
324 conf->sec_if = new->sec_if;
326 else if (new->sec_if) {
327 /* If we merge, the merge-result must have its own array
329 conf->sec_if = apr_array_append(a, base->sec_if, new->sec_if);
331 /* Otherwise we simply use the base->sec_if array
334 if (new->server_signature != srv_sig_unset) {
335 conf->server_signature = new->server_signature;
338 if (new->add_default_charset != ADD_DEFAULT_CHARSET_UNSET) {
339 conf->add_default_charset = new->add_default_charset;
340 conf->add_default_charset_name = new->add_default_charset_name;
343 /* Overriding all negotiation
345 if (new->mime_type) {
346 conf->mime_type = new->mime_type;
350 conf->handler = new->handler;
352 if (new->expr_handler) {
353 conf->expr_handler = new->expr_handler;
356 if (new->output_filters) {
357 conf->output_filters = new->output_filters;
360 if (new->input_filters) {
361 conf->input_filters = new->input_filters;
365 * Now merge the setting of the FileETag directive.
367 if (new->etag_bits == ETAG_UNSET) {
369 (conf->etag_add & (~ new->etag_remove)) | new->etag_add;
371 (conf->etag_remove & (~ new->etag_add)) | new->etag_remove;
373 (conf->etag_bits & (~ conf->etag_remove)) | conf->etag_add;
376 conf->etag_bits = new->etag_bits;
377 conf->etag_add = new->etag_add;
378 conf->etag_remove = new->etag_remove;
381 if (conf->etag_bits != ETAG_NONE) {
382 conf->etag_bits &= (~ ETAG_NONE);
385 if (new->enable_mmap != ENABLE_MMAP_UNSET) {
386 conf->enable_mmap = new->enable_mmap;
389 if (new->enable_sendfile != ENABLE_SENDFILE_UNSET) {
390 conf->enable_sendfile = new->enable_sendfile;
393 conf->allow_encoded_slashes = new->allow_encoded_slashes;
394 conf->decode_encoded_slashes = new->decode_encoded_slashes;
398 conf->log = new->log;
401 conf->log = ap_new_log_config(a, new->log);
402 ap_merge_log_config(base->log, conf->log);
406 conf->max_ranges = new->max_ranges != AP_MAXRANGES_UNSET ? new->max_ranges : base->max_ranges;
407 conf->max_overlaps = new->max_overlaps != AP_MAXRANGES_UNSET ? new->max_overlaps : base->max_overlaps;
408 conf->max_reversals = new->max_reversals != AP_MAXRANGES_UNSET ? new->max_reversals : base->max_reversals;
410 conf->cgi_pass_auth = new->cgi_pass_auth != AP_CGI_PASS_AUTH_UNSET ? new->cgi_pass_auth : base->cgi_pass_auth;
412 AP_CORE_MERGE_FLAG(qualify_redirect_url, conf, base, new);
417 #if APR_HAS_SO_ACCEPTFILTER
418 #ifndef ACCEPT_FILTER_NAME
419 #define ACCEPT_FILTER_NAME "httpready"
420 #ifdef __FreeBSD_version
421 #if __FreeBSD_version < 411000 /* httpready broken before 4.1.1 */
422 #undef ACCEPT_FILTER_NAME
423 #define ACCEPT_FILTER_NAME "dataready"
429 static void *create_core_server_config(apr_pool_t *a, server_rec *s)
431 core_server_config *conf;
432 int is_virtual = s->is_virtual;
434 conf = (core_server_config *)apr_pcalloc(a, sizeof(core_server_config));
436 /* global-default / global-only settings */
439 conf->ap_document_root = DOCUMENT_LOCATION;
440 conf->access_name = DEFAULT_ACCESS_FNAME;
442 /* A mapping only makes sense in the global context */
443 conf->accf_map = apr_table_make(a, 5);
444 #if APR_HAS_SO_ACCEPTFILTER
445 apr_table_setn(conf->accf_map, "http", ACCEPT_FILTER_NAME);
446 apr_table_setn(conf->accf_map, "https", "dataready");
448 apr_table_setn(conf->accf_map, "http", "data");
449 apr_table_setn(conf->accf_map, "https", "data");
452 /* pcalloc'ed - we have NULL's/0's
453 else ** is_virtual ** {
454 conf->ap_document_root = NULL;
455 conf->access_name = NULL;
456 conf->accf_map = NULL;
460 /* initialization, no special case for global context */
462 conf->sec_dir = apr_array_make(a, 40, sizeof(ap_conf_vector_t *));
463 conf->sec_url = apr_array_make(a, 40, sizeof(ap_conf_vector_t *));
465 /* pcalloc'ed - we have NULL's/0's
466 conf->gprof_dir = NULL;
468 ** recursion stopper; 0 == unset
469 conf->redirect_limit = 0;
470 conf->subreq_limit = 0;
472 conf->protocol = NULL;
475 conf->trace_enable = AP_TRACE_UNSET;
477 conf->protocols = apr_array_make(a, 5, sizeof(const char *));
478 conf->protocols_honor_order = -1;
483 static void *merge_core_server_configs(apr_pool_t *p, void *basev, void *virtv)
485 core_server_config *base = (core_server_config *)basev;
486 core_server_config *virt = (core_server_config *)virtv;
487 core_server_config *conf = (core_server_config *)
488 apr_pmemdup(p, base, sizeof(core_server_config));
490 if (virt->ap_document_root)
491 conf->ap_document_root = virt->ap_document_root;
493 if (virt->access_name)
494 conf->access_name = virt->access_name;
496 /* XXX optimize to keep base->sec_ pointers if virt->sec_ array is empty */
497 conf->sec_dir = apr_array_append(p, base->sec_dir, virt->sec_dir);
498 conf->sec_url = apr_array_append(p, base->sec_url, virt->sec_url);
500 if (virt->redirect_limit)
501 conf->redirect_limit = virt->redirect_limit;
503 if (virt->subreq_limit)
504 conf->subreq_limit = virt->subreq_limit;
506 if (virt->trace_enable != AP_TRACE_UNSET)
507 conf->trace_enable = virt->trace_enable;
509 /* no action for virt->accf_map, not allowed per-vhost */
512 conf->protocol = virt->protocol;
515 conf->gprof_dir = virt->gprof_dir;
517 if (virt->error_log_format)
518 conf->error_log_format = virt->error_log_format;
520 if (virt->error_log_conn)
521 conf->error_log_conn = virt->error_log_conn;
523 if (virt->error_log_req)
524 conf->error_log_req = virt->error_log_req;
526 conf->merge_trailers = (virt->merge_trailers != AP_MERGE_TRAILERS_UNSET)
527 ? virt->merge_trailers
528 : base->merge_trailers;
530 conf->protocols = ((virt->protocols->nelts > 0)?
531 virt->protocols : base->protocols);
532 conf->protocols_honor_order = ((virt->protocols_honor_order < 0)?
533 base->protocols_honor_order :
534 virt->protocols_honor_order);
539 /* Add per-directory configuration entry (for <directory> section);
540 * these are part of the core server config.
543 AP_CORE_DECLARE(void) ap_add_per_dir_conf(server_rec *s, void *dir_config)
545 core_server_config *sconf = ap_get_core_module_config(s->module_config);
546 void **new_space = (void **)apr_array_push(sconf->sec_dir);
548 *new_space = dir_config;
551 AP_CORE_DECLARE(void) ap_add_per_url_conf(server_rec *s, void *url_config)
553 core_server_config *sconf = ap_get_core_module_config(s->module_config);
554 void **new_space = (void **)apr_array_push(sconf->sec_url);
556 *new_space = url_config;
559 AP_CORE_DECLARE(void) ap_add_file_conf(apr_pool_t *p, core_dir_config *conf,
565 conf->sec_file = apr_array_make(p, 2, sizeof(ap_conf_vector_t *));
567 new_space = (void **)apr_array_push(conf->sec_file);
568 *new_space = url_config;
571 AP_CORE_DECLARE(const char *) ap_add_if_conf(apr_pool_t *p,
572 core_dir_config *conf,
576 core_dir_config *new = ap_get_module_config(if_config, &core_module);
579 conf->sec_if = apr_array_make(p, 2, sizeof(ap_conf_vector_t *));
581 if (new->condition_ifelse & AP_CONDITION_ELSE) {
583 if (conf->sec_if->nelts > 0) {
584 core_dir_config *last;
585 ap_conf_vector_t *lastelt = APR_ARRAY_IDX(conf->sec_if,
586 conf->sec_if->nelts - 1,
588 last = ap_get_module_config(lastelt, &core_module);
589 if (last->condition_ifelse & AP_CONDITION_IF)
593 return "<Else> or <ElseIf> section without previous <If> or "
594 "<ElseIf> section in same scope";
597 new_space = (void **)apr_array_push(conf->sec_if);
598 *new_space = if_config;
603 /* We need to do a stable sort, qsort isn't stable. So to make it stable
604 * we'll be maintaining the original index into the list, and using it
605 * as the minor key during sorting. The major key is the number of
606 * components (where the root component is zero).
608 struct reorder_sort_rec {
609 ap_conf_vector_t *elt;
613 static int reorder_sorter(const void *va, const void *vb)
615 const struct reorder_sort_rec *a = va;
616 const struct reorder_sort_rec *b = vb;
617 core_dir_config *core_a;
618 core_dir_config *core_b;
620 core_a = ap_get_core_module_config(a->elt);
621 core_b = ap_get_core_module_config(b->elt);
623 /* a regex always sorts after a non-regex
625 if (!core_a->r && core_b->r) {
628 else if (core_a->r && !core_b->r) {
632 /* we always sort next by the number of components
634 if (core_a->d_components < core_b->d_components) {
637 else if (core_a->d_components > core_b->d_components) {
641 /* They have the same number of components, we now have to compare
642 * the minor key to maintain the original order (from the config.)
644 return a->orig_index - b->orig_index;
647 void ap_core_reorder_directories(apr_pool_t *p, server_rec *s)
649 core_server_config *sconf;
650 apr_array_header_t *sec_dir;
651 struct reorder_sort_rec *sortbin;
653 ap_conf_vector_t **elts;
657 sconf = ap_get_core_module_config(s->module_config);
658 sec_dir = sconf->sec_dir;
659 nelts = sec_dir->nelts;
660 elts = (ap_conf_vector_t **)sec_dir->elts;
663 /* simple case of already being sorted... */
664 /* We're not checking this condition to be fast... we're checking
665 * it to avoid trying to palloc zero bytes, which can trigger some
666 * memory debuggers to barf
671 /* we have to allocate tmp space to do a stable sort */
672 apr_pool_create(&tmp, p);
673 sortbin = apr_palloc(tmp, sec_dir->nelts * sizeof(*sortbin));
674 for (i = 0; i < nelts; ++i) {
675 sortbin[i].orig_index = i;
676 sortbin[i].elt = elts[i];
679 qsort(sortbin, nelts, sizeof(*sortbin), reorder_sorter);
681 /* and now copy back to the original array */
682 for (i = 0; i < nelts; ++i) {
683 elts[i] = sortbin[i].elt;
686 apr_pool_destroy(tmp);
689 /*****************************************************************
691 * There are some elements of the core config structures in which
692 * other modules have a legitimate interest (this is ugly, but necessary
693 * to preserve NCSA back-compatibility). So, we have a bunch of accessors
697 AP_DECLARE(int) ap_allow_options(request_rec *r)
699 core_dir_config *conf =
700 (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
705 AP_DECLARE(int) ap_allow_overrides(request_rec *r)
707 core_dir_config *conf;
708 conf = (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
710 return conf->override;
714 * Optional function coming from mod_authn_core, used for
715 * retrieving the type of autorization
717 static APR_OPTIONAL_FN_TYPE(authn_ap_auth_type) *authn_ap_auth_type;
719 AP_DECLARE(const char *) ap_auth_type(request_rec *r)
721 if (authn_ap_auth_type) {
722 return authn_ap_auth_type(r);
728 * Optional function coming from mod_authn_core, used for
729 * retrieving the authorization realm
731 static APR_OPTIONAL_FN_TYPE(authn_ap_auth_name) *authn_ap_auth_name;
733 AP_DECLARE(const char *) ap_auth_name(request_rec *r)
735 if (authn_ap_auth_name) {
736 return authn_ap_auth_name(r);
742 * Optional function coming from mod_access_compat, used to determine how
743 access control interacts with authentication/authorization
745 static APR_OPTIONAL_FN_TYPE(access_compat_ap_satisfies) *access_compat_ap_satisfies;
747 AP_DECLARE(int) ap_satisfies(request_rec *r)
749 if (access_compat_ap_satisfies) {
750 return access_compat_ap_satisfies(r);
752 return SATISFY_NOSPEC;
755 AP_DECLARE(const char *) ap_document_root(request_rec *r) /* Don't use this! */
757 core_server_config *sconf;
758 core_request_config *rconf = ap_get_core_module_config(r->request_config);
759 if (rconf->document_root)
760 return rconf->document_root;
761 sconf = ap_get_core_module_config(r->server->module_config);
762 return sconf->ap_document_root;
765 AP_DECLARE(const char *) ap_context_prefix(request_rec *r)
767 core_request_config *conf = ap_get_core_module_config(r->request_config);
768 if (conf->context_prefix)
769 return conf->context_prefix;
774 AP_DECLARE(const char *) ap_context_document_root(request_rec *r)
776 core_request_config *conf = ap_get_core_module_config(r->request_config);
777 if (conf->context_document_root)
778 return conf->context_document_root;
780 return ap_document_root(r);
783 AP_DECLARE(void) ap_set_document_root(request_rec *r, const char *document_root)
785 core_request_config *conf = ap_get_core_module_config(r->request_config);
786 conf->document_root = document_root;
789 AP_DECLARE(void) ap_set_context_info(request_rec *r, const char *context_prefix,
790 const char *context_document_root)
792 core_request_config *conf = ap_get_core_module_config(r->request_config);
794 conf->context_prefix = context_prefix;
795 if (context_document_root)
796 conf->context_document_root = context_document_root;
799 /* Should probably just get rid of this... the only code that cares is
800 * part of the core anyway (and in fact, it isn't publicised to other
804 char *ap_response_code_string(request_rec *r, int error_index)
806 core_dir_config *dirconf;
807 core_request_config *reqconf = ap_get_core_module_config(r->request_config);
809 const char *response;
810 ap_expr_info_t *expr;
812 /* check for string registered via ap_custom_response() first */
813 if (reqconf->response_code_strings != NULL
814 && reqconf->response_code_strings[error_index] != NULL) {
815 return reqconf->response_code_strings[error_index];
818 /* check for string specified via ErrorDocument */
819 dirconf = ap_get_core_module_config(r->per_dir_config);
821 if (!dirconf->response_code_exprs) {
825 expr = apr_hash_get(dirconf->response_code_exprs, &error_index,
826 sizeof(error_index));
831 /* special token to indicate revert back to default */
832 if ((char *) expr == &errordocument_default) {
837 response = ap_expr_str_exec(r, expr, &err);
840 APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02841) "core: ErrorDocument: can't "
841 "evaluate require expression: %s", err);
845 /* alas, duplication required as we return not-const */
846 return apr_pstrdup(r->pool, response);
850 /* Code from Harald Hanche-Olsen <hanche@imf.unit.no> */
851 static APR_INLINE int do_double_reverse (int double_reverse,
852 const char *remote_host,
853 apr_sockaddr_t *client_addr,
859 if (double_reverse) {
861 return double_reverse;
864 if (remote_host == NULL || remote_host[0] == '\0') {
865 /* single reverse failed, so don't bother */
869 rv = apr_sockaddr_info_get(&sa, remote_host, APR_UNSPEC, 0, 0, pool);
870 if (rv == APR_SUCCESS) {
872 if (apr_sockaddr_equal(sa, client_addr)) {
883 AP_DECLARE(const char *) ap_get_remote_host(conn_rec *conn, void *dir_config,
884 int type, int *str_is_ip)
886 int hostname_lookups;
887 int ignored_str_is_ip;
889 if (!str_is_ip) { /* caller doesn't want to know */
890 str_is_ip = &ignored_str_is_ip;
894 /* If we haven't checked the host name, and we want to */
896 hostname_lookups = ((core_dir_config *)ap_get_core_module_config(dir_config))
899 if (hostname_lookups == HOSTNAME_LOOKUP_UNSET) {
900 hostname_lookups = HOSTNAME_LOOKUP_OFF;
905 hostname_lookups = HOSTNAME_LOOKUP_OFF;
908 if (type != REMOTE_NOLOOKUP
909 && conn->remote_host == NULL
910 && (type == REMOTE_DOUBLE_REV
911 || hostname_lookups != HOSTNAME_LOOKUP_OFF)) {
913 if (apr_getnameinfo(&conn->remote_host, conn->client_addr, 0)
915 ap_str_tolower(conn->remote_host);
917 if (hostname_lookups == HOSTNAME_LOOKUP_DOUBLE) {
918 conn->double_reverse = do_double_reverse(conn->double_reverse,
922 if (conn->double_reverse != 1) {
923 conn->remote_host = NULL;
928 /* if failed, set it to the NULL string to indicate error */
929 if (conn->remote_host == NULL) {
930 conn->remote_host = "";
934 if (type == REMOTE_DOUBLE_REV) {
935 conn->double_reverse = do_double_reverse(conn->double_reverse,
937 conn->client_addr, conn->pool);
938 if (conn->double_reverse == -1) {
944 * Return the desired information; either the remote DNS name, if found,
945 * or either NULL (if the hostname was requested) or the IP address
946 * (if any identifier was requested).
948 if (conn->remote_host != NULL && conn->remote_host[0] != '\0') {
949 return conn->remote_host;
952 if (type == REMOTE_HOST || type == REMOTE_DOUBLE_REV) {
957 return conn->client_ip;
962 AP_DECLARE(const char *) ap_get_useragent_host(request_rec *r,
963 int type, int *str_is_ip)
965 conn_rec *conn = r->connection;
966 int hostname_lookups;
967 int ignored_str_is_ip;
969 if (r->useragent_addr == conn->client_addr) {
970 return ap_get_remote_host(conn, r->per_dir_config, type, str_is_ip);
973 if (!str_is_ip) { /* caller doesn't want to know */
974 str_is_ip = &ignored_str_is_ip;
978 hostname_lookups = ((core_dir_config *)
979 ap_get_core_module_config(r->per_dir_config))
981 if (hostname_lookups == HOSTNAME_LOOKUP_UNSET) {
982 hostname_lookups = HOSTNAME_LOOKUP_OFF;
985 if (type != REMOTE_NOLOOKUP
986 && r->useragent_host == NULL
987 && (type == REMOTE_DOUBLE_REV
988 || hostname_lookups != HOSTNAME_LOOKUP_OFF)) {
990 if (apr_getnameinfo(&r->useragent_host, r->useragent_addr, 0)
992 ap_str_tolower(r->useragent_host);
994 if (hostname_lookups == HOSTNAME_LOOKUP_DOUBLE) {
995 r->double_reverse = do_double_reverse(r->double_reverse,
999 if (r->double_reverse != 1) {
1000 r->useragent_host = NULL;
1005 /* if failed, set it to the NULL string to indicate error */
1006 if (r->useragent_host == NULL) {
1007 r->useragent_host = "";
1011 if (type == REMOTE_DOUBLE_REV) {
1012 r->double_reverse = do_double_reverse(r->double_reverse,
1014 r->useragent_addr, r->pool);
1015 if (r->double_reverse == -1) {
1021 * Return the desired information; either the remote DNS name, if found,
1022 * or either NULL (if the hostname was requested) or the IP address
1023 * (if any identifier was requested).
1025 if (r->useragent_host != NULL && r->useragent_host[0] != '\0') {
1026 return r->useragent_host;
1029 if (type == REMOTE_HOST || type == REMOTE_DOUBLE_REV) {
1034 return r->useragent_ip;
1040 * Optional function coming from mod_ident, used for looking up ident user
1042 static APR_OPTIONAL_FN_TYPE(ap_ident_lookup) *ident_lookup;
1044 AP_DECLARE(const char *) ap_get_remote_logname(request_rec *r)
1046 if (r->connection->remote_logname != NULL) {
1047 return r->connection->remote_logname;
1051 return ident_lookup(r);
1057 /* There are two options regarding what the "name" of a server is. The
1058 * "canonical" name as defined by ServerName and Port, or the "client's
1059 * name" as supplied by a possible Host: header or full URI.
1061 * The DNS option to UseCanonicalName causes this routine to do a
1062 * reverse lookup on the local IP address of the connection and use
1063 * that for the ServerName. This makes its value more reliable while
1064 * at the same time allowing Demon's magic virtual hosting to work.
1065 * The assumption is that DNS lookups are sufficiently quick...
1066 * -- fanf 1998-10-03
1068 AP_DECLARE(const char *) ap_get_server_name(request_rec *r)
1070 conn_rec *conn = r->connection;
1074 d = (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
1076 switch (d->use_canonical_name) {
1077 case USE_CANONICAL_NAME_ON:
1078 retval = r->server->server_hostname;
1080 case USE_CANONICAL_NAME_DNS:
1081 if (conn->local_host == NULL) {
1082 if (apr_getnameinfo(&conn->local_host,
1083 conn->local_addr, 0) != APR_SUCCESS)
1084 conn->local_host = apr_pstrdup(conn->pool,
1085 r->server->server_hostname);
1087 ap_str_tolower(conn->local_host);
1090 retval = conn->local_host;
1092 case USE_CANONICAL_NAME_OFF:
1093 case USE_CANONICAL_NAME_UNSET:
1094 retval = r->hostname ? r->hostname : r->server->server_hostname;
1097 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00109)
1098 "ap_get_server_name: Invalid UCN Option somehow");
1099 retval = "localhost";
1106 * Get the current server name from the request for the purposes
1107 * of using in a URL. If the server name is an IPv6 literal
1108 * address, it will be returned in URL format (e.g., "[fe80::1]").
1110 AP_DECLARE(const char *) ap_get_server_name_for_url(request_rec *r)
1112 const char *plain_server_name = ap_get_server_name(r);
1115 if (ap_strchr_c(plain_server_name, ':')) { /* IPv6 literal? */
1116 return apr_pstrcat(r->pool, "[", plain_server_name, "]", NULL);
1119 return plain_server_name;
1122 AP_DECLARE(apr_port_t) ap_get_server_port(const request_rec *r)
1125 core_dir_config *d =
1126 (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
1128 switch (d->use_canonical_name) {
1129 case USE_CANONICAL_NAME_OFF:
1130 case USE_CANONICAL_NAME_DNS:
1131 case USE_CANONICAL_NAME_UNSET:
1132 if (d->use_canonical_phys_port == USE_CANONICAL_PHYS_PORT_ON)
1133 port = r->parsed_uri.port_str ? r->parsed_uri.port :
1134 r->connection->local_addr->port ? r->connection->local_addr->port :
1135 r->server->port ? r->server->port :
1137 else /* USE_CANONICAL_PHYS_PORT_OFF or USE_CANONICAL_PHYS_PORT_UNSET */
1138 port = r->parsed_uri.port_str ? r->parsed_uri.port :
1139 r->server->port ? r->server->port :
1142 case USE_CANONICAL_NAME_ON:
1143 /* With UseCanonicalName on (and in all versions prior to 1.3)
1144 * Apache will use the hostname and port specified in the
1145 * ServerName directive to construct a canonical name for the
1146 * server. (If no port was specified in the ServerName
1147 * directive, Apache uses the port supplied by the client if
1148 * any is supplied, and finally the default port for the protocol
1151 if (d->use_canonical_phys_port == USE_CANONICAL_PHYS_PORT_ON)
1152 port = r->server->port ? r->server->port :
1153 r->connection->local_addr->port ? r->connection->local_addr->port :
1155 else /* USE_CANONICAL_PHYS_PORT_OFF or USE_CANONICAL_PHYS_PORT_UNSET */
1156 port = r->server->port ? r->server->port :
1160 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00110)
1161 "ap_get_server_port: Invalid UCN Option somehow");
1162 port = ap_default_port(r);
1169 AP_DECLARE(char *) ap_construct_url(apr_pool_t *p, const char *uri,
1172 unsigned port = ap_get_server_port(r);
1173 const char *host = ap_get_server_name_for_url(r);
1175 if (ap_is_default_port(port, r)) {
1176 return apr_pstrcat(p, ap_http_scheme(r), "://", host, uri, NULL);
1179 return apr_psprintf(p, "%s://%s:%u%s", ap_http_scheme(r), host, port, uri);
1182 AP_DECLARE(apr_off_t) ap_get_limit_req_body(const request_rec *r)
1184 core_dir_config *d =
1185 (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
1187 if (d->limit_req_body == AP_LIMIT_REQ_BODY_UNSET) {
1188 return AP_DEFAULT_LIMIT_REQ_BODY;
1191 return d->limit_req_body;
1195 /*****************************************************************
1197 * Commands... this module handles almost all of the NCSA httpd.conf
1198 * commands, but most of the old srm.conf is in the modules.
1202 /* returns a parent if it matches the given directive */
1203 static const ap_directive_t * find_parent(const ap_directive_t *dirp,
1206 while (dirp->parent != NULL) {
1207 dirp = dirp->parent;
1209 /* ### it would be nice to have atom-ized directives */
1210 if (strcasecmp(dirp->directive, what) == 0)
1217 AP_DECLARE(const char *) ap_check_cmd_context(cmd_parms *cmd,
1220 const char *gt = (cmd->cmd->name[0] == '<'
1221 && cmd->cmd->name[strlen(cmd->cmd->name)-1] != '>')
1223 const ap_directive_t *found;
1225 if ((forbidden & NOT_IN_VIRTUALHOST) && cmd->server->is_virtual) {
1226 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1227 " cannot occur within <VirtualHost> section", NULL);
1230 if ((forbidden & (NOT_IN_LIMIT | NOT_IN_DIR_LOC_FILE))
1231 && cmd->limited != -1) {
1232 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1233 " cannot occur within <Limit> or <LimitExcept> "
1237 if ((forbidden & NOT_IN_HTACCESS) && (cmd->pool == cmd->temp_pool)) {
1238 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1239 " cannot occur within htaccess files", NULL);
1242 if ((forbidden & NOT_IN_DIR_LOC_FILE) == NOT_IN_DIR_LOC_FILE) {
1243 if (cmd->path != NULL) {
1244 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1245 " cannot occur within <Directory/Location/Files> "
1248 if (cmd->cmd->req_override & EXEC_ON_READ) {
1249 /* EXEC_ON_READ must be NOT_IN_DIR_LOC_FILE, if not, it will
1250 * (deliberately) segfault below in the individual tests...
1256 if (((forbidden & NOT_IN_DIRECTORY)
1257 && ((found = find_parent(cmd->directive, "<Directory"))
1258 || (found = find_parent(cmd->directive, "<DirectoryMatch"))))
1259 || ((forbidden & NOT_IN_LOCATION)
1260 && ((found = find_parent(cmd->directive, "<Location"))
1261 || (found = find_parent(cmd->directive, "<LocationMatch"))))
1262 || ((forbidden & NOT_IN_FILES)
1263 && ((found = find_parent(cmd->directive, "<Files"))
1264 || (found = find_parent(cmd->directive, "<FilesMatch"))
1265 || (found = find_parent(cmd->directive, "<If"))
1266 || (found = find_parent(cmd->directive, "<ElseIf"))
1267 || (found = find_parent(cmd->directive, "<Else"))))) {
1268 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1269 " cannot occur within ", found->directive,
1276 static const char *set_access_name(cmd_parms *cmd, void *dummy,
1279 void *sconf = cmd->server->module_config;
1280 core_server_config *conf = ap_get_core_module_config(sconf);
1282 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
1287 conf->access_name = apr_pstrdup(cmd->pool, arg);
1291 AP_DECLARE(const char *) ap_resolve_env(apr_pool_t *p, const char * word)
1293 # define SMALL_EXPANSION 5
1298 } *result, *current, sresult[SMALL_EXPANSION];
1300 const char *s, *e, *ep;
1304 s = ap_strchr_c(word, '$');
1309 /* well, actually something to do */
1310 ep = word + strlen(word);
1312 result = current = &(sresult[spc++]);
1313 current->next = NULL;
1314 current->string = word;
1315 current->len = s - word;
1316 outlen = current->len;
1319 /* prepare next entry */
1321 current->next = (spc < SMALL_EXPANSION)
1323 : (struct sll *)apr_palloc(p,
1324 sizeof(*current->next));
1325 current = current->next;
1326 current->next = NULL;
1331 if (s[1] == '{' && (e = ap_strchr_c(s+2, '}'))) {
1332 char *name = apr_pstrmemdup(p, s+2, e-s-2);
1334 if (server_config_defined_vars)
1335 word = apr_table_get(server_config_defined_vars, name);
1337 word = getenv(name);
1339 current->string = word;
1340 current->len = strlen(word);
1341 outlen += current->len;
1344 if (ap_strchr(name, ':') == 0)
1345 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, NULL, APLOGNO(00111)
1346 "Config variable ${%s} is not defined",
1348 current->string = s;
1349 current->len = e - s + 1;
1350 outlen += current->len;
1355 current->string = s++;
1362 s = ap_strchr_c(s, '$');
1363 current->string = word;
1364 current->len = s ? s - word : ep - word;
1365 outlen += current->len;
1369 /* assemble result */
1370 res_buf = cp = apr_palloc(p, outlen + 1);
1373 memcpy(cp, result->string, result->len);
1376 result = result->next;
1378 res_buf[outlen] = '\0';
1383 static int reset_config_defines(void *dummy)
1385 ap_server_config_defines = saved_server_config_defines;
1386 saved_server_config_defines = NULL;
1387 server_config_defined_vars = NULL;
1392 * Make sure we can revert the effects of Define/UnDefine when restarting.
1393 * This function must be called once per loading of the config, before
1394 * ap_server_config_defines is changed. This may be during reading of the
1395 * config, which is even before the pre_config hook is run (due to
1396 * EXEC_ON_READ for Define/UnDefine).
1398 static void init_config_defines(apr_pool_t *pconf)
1400 saved_server_config_defines = ap_server_config_defines;
1401 /* Use apr_array_copy instead of apr_array_copy_hdr because it does not
1402 * protect from the way unset_define removes entries.
1404 ap_server_config_defines = apr_array_copy(pconf, ap_server_config_defines);
1407 static const char *set_define(cmd_parms *cmd, void *dummy,
1408 const char *name, const char *value)
1410 const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS);
1413 if (ap_strchr_c(name, ':') != NULL)
1414 return "Variable name must not contain ':'";
1416 if (!saved_server_config_defines)
1417 init_config_defines(cmd->pool);
1418 if (!ap_exists_config_define(name)) {
1419 char **newv = (char **)apr_array_push(ap_server_config_defines);
1420 *newv = apr_pstrdup(cmd->pool, name);
1423 if (!server_config_defined_vars)
1424 server_config_defined_vars = apr_table_make(cmd->pool, 5);
1425 apr_table_setn(server_config_defined_vars, name, value);
1431 static const char *unset_define(cmd_parms *cmd, void *dummy,
1436 const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS);
1439 if (ap_strchr_c(name, ':') != NULL)
1440 return "Variable name must not contain ':'";
1442 if (!saved_server_config_defines)
1443 init_config_defines(cmd->pool);
1445 defines = (char **)ap_server_config_defines->elts;
1446 for (i = 0; i < ap_server_config_defines->nelts; i++) {
1447 if (strcmp(defines[i], name) == 0) {
1448 defines[i] = *(char **)apr_array_pop(ap_server_config_defines);
1453 if (server_config_defined_vars) {
1454 apr_table_unset(server_config_defined_vars, name);
1460 static const char *generate_error(cmd_parms *cmd, void *dummy,
1463 if (!arg || !*arg) {
1464 return "The Error directive was used with no message.";
1467 if (*arg == '"' || *arg == '\'') { /* strip off quotes */
1468 apr_size_t len = strlen(arg);
1469 char last = *(arg + len - 1);
1472 return apr_pstrndup(cmd->pool, arg + 1, len - 2);
1480 static const char *set_gprof_dir(cmd_parms *cmd, void *dummy, const char *arg)
1482 void *sconf = cmd->server->module_config;
1483 core_server_config *conf = ap_get_core_module_config(sconf);
1485 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
1490 conf->gprof_dir = arg;
1495 static const char *set_add_default_charset(cmd_parms *cmd,
1496 void *d_, const char *arg)
1498 core_dir_config *d = d_;
1500 if (!strcasecmp(arg, "Off")) {
1501 d->add_default_charset = ADD_DEFAULT_CHARSET_OFF;
1503 else if (!strcasecmp(arg, "On")) {
1504 d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1505 d->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
1508 d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1509 d->add_default_charset_name = arg;
1515 static const char *set_document_root(cmd_parms *cmd, void *dummy,
1518 void *sconf = cmd->server->module_config;
1519 core_server_config *conf = ap_get_core_module_config(sconf);
1521 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
1526 /* When ap_document_root_check is false; skip all the stuff below */
1527 if (!ap_document_root_check) {
1528 conf->ap_document_root = arg;
1532 /* Make it absolute, relative to ServerRoot */
1533 arg = ap_server_root_relative(cmd->pool, arg);
1535 return "DocumentRoot must be a directory";
1538 /* TODO: ap_configtestonly */
1539 if (apr_filepath_merge((char**)&conf->ap_document_root, NULL, arg,
1540 APR_FILEPATH_TRUENAME, cmd->pool) != APR_SUCCESS
1541 || !ap_is_directory(cmd->temp_pool, arg)) {
1542 if (cmd->server->is_virtual) {
1543 ap_log_perror(APLOG_MARK, APLOG_STARTUP, 0,
1544 cmd->pool, APLOGNO(00112)
1545 "Warning: DocumentRoot [%s] does not exist",
1547 conf->ap_document_root = arg;
1550 return "DocumentRoot must be a directory";
1556 AP_DECLARE(void) ap_custom_response(request_rec *r, int status,
1559 core_request_config *conf = ap_get_core_module_config(r->request_config);
1562 if (conf->response_code_strings == NULL) {
1563 conf->response_code_strings =
1564 apr_pcalloc(r->pool,
1565 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
1568 idx = ap_index_of_response(status);
1570 conf->response_code_strings[idx] =
1571 ((ap_is_url(string) || (*string == '/')) && (*string != '"')) ?
1572 apr_pstrdup(r->pool, string) : apr_pstrcat(r->pool, "\"", string, NULL);
1575 static const char *set_error_document(cmd_parms *cmd, void *conf_,
1576 const char *errno_str, const char *msg)
1578 core_dir_config *conf = conf_;
1579 int error_number, index_number, idx500;
1580 enum { MSG, LOCAL_PATH, REMOTE_PATH } what = MSG;
1582 /* 1st parameter should be a 3 digit number, which we recognize;
1583 * convert it into an array index
1585 error_number = atoi(errno_str);
1586 idx500 = ap_index_of_response(HTTP_INTERNAL_SERVER_ERROR);
1588 if (error_number == HTTP_INTERNAL_SERVER_ERROR) {
1589 index_number = idx500;
1591 else if ((index_number = ap_index_of_response(error_number)) == idx500) {
1592 return apr_pstrcat(cmd->pool, "Unsupported HTTP response code ",
1596 /* Heuristic to determine second argument. */
1597 if (ap_strchr_c(msg,' '))
1599 else if (msg[0] == '/')
1601 else if (ap_is_url(msg))
1606 /* The entry should be ignored if it is a full URL for a 401 error */
1608 if (error_number == 401 && what == REMOTE_PATH) {
1609 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, cmd->server, APLOGNO(00113)
1610 "%s:%d cannot use a full URL in a 401 ErrorDocument "
1611 "directive --- ignoring!", cmd->directive->filename, cmd->directive->line_num);
1613 else { /* Store it... */
1614 if (conf->response_code_exprs == NULL) {
1615 conf->response_code_exprs = apr_hash_make(cmd->pool);
1618 if (strcasecmp(msg, "default") == 0) {
1619 /* special case: ErrorDocument 404 default restores the
1620 * canned server error response
1622 apr_hash_set(conf->response_code_exprs,
1623 apr_pmemdup(cmd->pool, &index_number, sizeof(index_number)),
1624 sizeof(index_number), &errordocument_default);
1627 ap_expr_info_t *expr;
1628 const char *expr_err = NULL;
1630 /* hack. Prefix a " if it is a msg; as that is what
1631 * http_protocol.c relies on to distinguish between
1632 * a msg and a (local) path.
1634 const char *response =
1635 (what == MSG) ? apr_pstrcat(cmd->pool, "\"", msg, NULL) :
1636 apr_pstrdup(cmd->pool, msg);
1638 expr = ap_expr_parse_cmd(cmd, response, AP_EXPR_FLAG_STRING_RESULT,
1642 return apr_pstrcat(cmd->temp_pool,
1643 "Cannot parse expression in ErrorDocument: ",
1647 apr_hash_set(conf->response_code_exprs,
1648 apr_pmemdup(cmd->pool, &index_number, sizeof(index_number)),
1649 sizeof(index_number), expr);
1657 static const char *set_allow_opts(cmd_parms *cmd, allow_options_t *opts,
1660 allow_options_t opt;
1663 char *w, *p = (char *) l;
1666 while ((w = apr_strtok(p, ",", &tok_state)) != NULL) {
1674 if (!strcasecmp(w, "Indexes")) {
1677 else if (!strcasecmp(w, "Includes")) {
1678 /* If Includes is permitted, both Includes and
1679 * IncludesNOEXEC may be changed. */
1680 opt = (OPT_INCLUDES | OPT_INC_WITH_EXEC);
1682 else if (!strcasecmp(w, "IncludesNOEXEC")) {
1685 else if (!strcasecmp(w, "FollowSymLinks")) {
1686 opt = OPT_SYM_LINKS;
1688 else if (!strcasecmp(w, "SymLinksIfOwnerMatch")) {
1689 opt = OPT_SYM_OWNER;
1691 else if (!strcasecmp(w, "ExecCGI")) {
1694 else if (!strcasecmp(w, "MultiViews")) {
1697 else if (!strcasecmp(w, "RunScripts")) { /* AI backcompat. Yuck */
1698 opt = OPT_MULTI|OPT_EXECCGI;
1700 else if (!strcasecmp(w, "None")) {
1703 else if (!strcasecmp(w, "All")) {
1707 return apr_pstrcat(cmd->pool, "Illegal option ", w, NULL);
1713 (*opts) &= (~OPT_UNSET);
1718 static const char *set_override(cmd_parms *cmd, void *d_, const char *l)
1720 core_dir_config *d = d_;
1725 /* Throw a warning if we're in <Location> or <Files> */
1726 if (ap_check_cmd_context(cmd, NOT_IN_LOCATION | NOT_IN_FILES)) {
1727 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server, APLOGNO(00114)
1728 "Useless use of AllowOverride in line %d of %s.",
1729 cmd->directive->line_num, cmd->directive->filename);
1731 if ((err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS)) != NULL)
1734 d->override = OR_NONE;
1736 w = ap_getword_conf(cmd->temp_pool, &l);
1744 if (!strcasecmp(w, "Limit")) {
1745 d->override |= OR_LIMIT;
1747 else if (!strcasecmp(k, "Options")) {
1748 d->override |= OR_OPTIONS;
1750 set_allow_opts(cmd, &(d->override_opts), v);
1752 d->override_opts = OPT_ALL;
1754 else if (!strcasecmp(w, "FileInfo")) {
1755 d->override |= OR_FILEINFO;
1757 else if (!strcasecmp(w, "AuthConfig")) {
1758 d->override |= OR_AUTHCFG;
1760 else if (!strcasecmp(w, "Indexes")) {
1761 d->override |= OR_INDEXES;
1763 else if (!strcasecmp(w, "Nonfatal")) {
1764 if (!strcasecmp(v, "Override")) {
1765 d->override |= NONFATAL_OVERRIDE;
1767 else if (!strcasecmp(v, "Unknown")) {
1768 d->override |= NONFATAL_UNKNOWN;
1770 else if (!strcasecmp(v, "All")) {
1771 d->override |= NONFATAL_ALL;
1774 else if (!strcasecmp(w, "None")) {
1775 d->override = OR_NONE;
1777 else if (!strcasecmp(w, "All")) {
1778 d->override = OR_ALL;
1781 return apr_pstrcat(cmd->pool, "Illegal override option ", w, NULL);
1784 d->override &= ~OR_UNSET;
1790 static const char *set_cgi_pass_auth(cmd_parms *cmd, void *d_, int flag)
1792 core_dir_config *d = d_;
1794 d->cgi_pass_auth = flag ? AP_CGI_PASS_AUTH_ON : AP_CGI_PASS_AUTH_OFF;
1799 static const char *set_qualify_redirect_url(cmd_parms *cmd, void *d_, int flag)
1801 core_dir_config *d = d_;
1803 d->qualify_redirect_url = flag ? AP_CORE_CONFIG_ON : AP_CORE_CONFIG_OFF;
1808 static const char *set_override_list(cmd_parms *cmd, void *d_, int argc, char *const argv[])
1810 core_dir_config *d = d_;
1814 /* Throw a warning if we're in <Location> or <Files> */
1815 if (ap_check_cmd_context(cmd, NOT_IN_LOCATION | NOT_IN_FILES)) {
1816 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server, APLOGNO(00115)
1817 "Useless use of AllowOverrideList at %s:%d",
1818 cmd->directive->filename, cmd->directive->line_num);
1820 if ((err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS)) != NULL)
1823 d->override_list = apr_table_make(cmd->pool, argc);
1825 for (i = 0; i < argc; i++) {
1826 if (!strcasecmp(argv[i], "None")) {
1828 return "'None' not allowed with other directives in "
1829 "AllowOverrideList";
1834 const command_rec *result = NULL;
1835 module *mod = ap_top_module;
1837 result = ap_find_command_in_modules(argv[i], &mod);
1838 if (result == NULL) {
1839 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
1840 APLOGNO(00116) "Discarding unrecognized "
1841 "directive `%s' in AllowOverrideList at %s:%d",
1842 argv[i], cmd->directive->filename,
1843 cmd->directive->line_num);
1846 else if ((result->req_override & (OR_ALL|ACCESS_CONF)) == 0) {
1847 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
1848 APLOGNO(02304) "Discarding directive `%s' not "
1849 "allowed in AllowOverrideList at %s:%d",
1850 argv[i], cmd->directive->filename,
1851 cmd->directive->line_num);
1855 apr_table_setn(d->override_list, argv[i], "1");
1863 static const char *set_options(cmd_parms *cmd, void *d_, const char *l)
1865 core_dir_config *d = d_;
1866 allow_options_t opt;
1873 char *w = ap_getword_conf(cmd->temp_pool, &l);
1876 if (*w == '+' || *w == '-') {
1878 if (!merge && !first && !all_none) {
1879 return "Either all Options must start with + or -, or no Option may.";
1887 return "Either all Options must start with + or -, or no Option may.";
1890 if (!strcasecmp(w, "Indexes")) {
1893 else if (!strcasecmp(w, "Includes")) {
1894 opt = (OPT_INCLUDES | OPT_INC_WITH_EXEC);
1896 else if (!strcasecmp(w, "IncludesNOEXEC")) {
1899 else if (!strcasecmp(w, "FollowSymLinks")) {
1900 opt = OPT_SYM_LINKS;
1902 else if (!strcasecmp(w, "SymLinksIfOwnerMatch")) {
1903 opt = OPT_SYM_OWNER;
1905 else if (!strcasecmp(w, "ExecCGI")) {
1908 else if (!strcasecmp(w, "MultiViews")) {
1911 else if (!strcasecmp(w, "RunScripts")) { /* AI backcompat. Yuck */
1912 opt = OPT_MULTI|OPT_EXECCGI;
1914 else if (!strcasecmp(w, "None")) {
1916 return "'Options None' must be the first Option given.";
1918 else if (merge) { /* Only works since None may not follow any other option. */
1919 return "You may not use 'Options +None' or 'Options -None'.";
1924 else if (!strcasecmp(w, "All")) {
1926 return "'Options All' must be the first option given.";
1928 else if (merge) { /* Only works since All may not follow any other option. */
1929 return "You may not use 'Options +All' or 'Options -All'.";
1935 return apr_pstrcat(cmd->pool, "Illegal option ", w, NULL);
1938 if ( (cmd->override_opts & opt) != opt ) {
1939 return apr_pstrcat(cmd->pool, "Option ", w, " not allowed here", NULL);
1941 else if (action == '-') {
1942 /* we ensure the invariant (d->opts_add & d->opts_remove) == 0 */
1943 d->opts_remove |= opt;
1944 d->opts_add &= ~opt;
1947 else if (action == '+') {
1949 d->opts_remove &= ~opt;
1962 static const char *set_default_type(cmd_parms *cmd, void *d_,
1965 if ((strcasecmp(arg, "off") != 0) && (strcasecmp(arg, "none") != 0)) {
1966 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server, APLOGNO(00117)
1967 "Ignoring deprecated use of DefaultType in line %d of %s.",
1968 cmd->directive->line_num, cmd->directive->filename);
1974 static const char *set_sethandler(cmd_parms *cmd,
1978 core_dir_config *dirconf = d_;
1980 dirconf->expr_handler = ap_expr_parse_cmd(cmd, arg_,
1981 AP_EXPR_FLAG_STRING_RESULT,
1984 return apr_pstrcat(cmd->pool,
1985 "Can't parse expression : ", err, NULL);
1991 * Note what data should be used when forming file ETag values.
1992 * It would be nicer to do this as an ITERATE, but then we couldn't
1993 * remember the +/- state properly.
1995 static const char *set_etag_bits(cmd_parms *cmd, void *mconfig,
1998 core_dir_config *cfg;
1999 etag_components_t bit;
2007 cfg = (core_dir_config *)mconfig;
2012 while (args[0] != '\0') {
2016 token = ap_getword_conf(cmd->temp_pool, &args);
2017 if ((*token == '+') || (*token == '-')) {
2023 * The occurrence of an absolute setting wipes
2024 * out any previous relative ones. The first such
2025 * occurrence forgets any inherited ones, too.
2028 cfg->etag_bits = ETAG_UNSET;
2029 cfg->etag_add = ETAG_UNSET;
2030 cfg->etag_remove = ETAG_UNSET;
2035 if (strcasecmp(token, "None") == 0) {
2036 if (action != '*') {
2040 cfg->etag_bits = bit = ETAG_NONE;
2044 else if (strcasecmp(token, "All") == 0) {
2045 if (action != '*') {
2050 cfg->etag_bits = bit = ETAG_ALL;
2053 else if (strcasecmp(token, "Size") == 0) {
2056 else if ((strcasecmp(token, "LMTime") == 0)
2057 || (strcasecmp(token, "MTime") == 0)
2058 || (strcasecmp(token, "LastModified") == 0)) {
2061 else if (strcasecmp(token, "INode") == 0) {
2065 return apr_pstrcat(cmd->pool, "Unknown keyword '",
2066 token, "' for ", cmd->cmd->name,
2067 " directive", NULL);
2071 return apr_pstrcat(cmd->pool, cmd->cmd->name, " keyword '",
2072 token, "' cannot be used with '+' or '-'",
2076 if (action == '+') {
2078 * Make sure it's in the 'add' list and absent from the
2081 cfg->etag_add |= bit;
2082 cfg->etag_remove &= (~ bit);
2084 else if (action == '-') {
2085 cfg->etag_remove |= bit;
2086 cfg->etag_add &= (~ bit);
2090 * Non-relative values wipe out any + or - values
2091 * accumulated so far.
2093 cfg->etag_bits |= bit;
2094 cfg->etag_add = ETAG_UNSET;
2095 cfg->etag_remove = ETAG_UNSET;
2101 * Any setting at all will clear the 'None' and 'Unset' bits.
2104 if (cfg->etag_add != ETAG_UNSET) {
2105 cfg->etag_add &= (~ ETAG_UNSET);
2108 if (cfg->etag_remove != ETAG_UNSET) {
2109 cfg->etag_remove &= (~ ETAG_UNSET);
2113 cfg->etag_bits &= (~ ETAG_UNSET);
2115 if ((cfg->etag_bits & ETAG_NONE) != ETAG_NONE) {
2116 cfg->etag_bits &= (~ ETAG_NONE);
2123 static const char *set_enable_mmap(cmd_parms *cmd, void *d_,
2126 core_dir_config *d = d_;
2128 if (strcasecmp(arg, "on") == 0) {
2129 d->enable_mmap = ENABLE_MMAP_ON;
2131 else if (strcasecmp(arg, "off") == 0) {
2132 d->enable_mmap = ENABLE_MMAP_OFF;
2135 return "parameter must be 'on' or 'off'";
2141 static const char *set_enable_sendfile(cmd_parms *cmd, void *d_,
2144 core_dir_config *d = d_;
2146 if (strcasecmp(arg, "on") == 0) {
2147 d->enable_sendfile = ENABLE_SENDFILE_ON;
2149 else if (strcasecmp(arg, "off") == 0) {
2150 d->enable_sendfile = ENABLE_SENDFILE_OFF;
2153 return "parameter must be 'on' or 'off'";
2161 * Report a missing-'>' syntax error.
2163 static char *unclosed_directive(cmd_parms *cmd)
2165 return apr_pstrcat(cmd->pool, cmd->cmd->name,
2166 "> directive missing closing '>'", NULL);
2170 * Report a missing args in '<Foo >' syntax error.
2172 static char *missing_container_arg(cmd_parms *cmd)
2174 return apr_pstrcat(cmd->pool, cmd->cmd->name,
2175 "> directive requires additional arguments", NULL);
2178 AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd,
2182 const char *endp = ap_strrchr_c(arg, '>');
2183 const char *limited_methods;
2184 void *tog = cmd->cmd->cmd_data;
2185 apr_int64_t limited = 0;
2186 apr_int64_t old_limited = cmd->limited;
2190 return unclosed_directive(cmd);
2193 limited_methods = apr_pstrmemdup(cmd->temp_pool, arg, endp - arg);
2195 if (!limited_methods[0]) {
2196 return missing_container_arg(cmd);
2199 while (limited_methods[0]) {
2200 char *method = ap_getword_conf(cmd->temp_pool, &limited_methods);
2203 /* check for builtin or module registered method number */
2204 methnum = ap_method_number_of(method);
2206 if (methnum == M_TRACE && !tog) {
2207 return "TRACE cannot be controlled by <Limit>, see TraceEnable";
2209 else if (methnum == M_INVALID) {
2210 /* method has not been registered yet, but resource restriction
2211 * is always checked before method handling, so register it.
2213 methnum = ap_method_register(cmd->pool,
2214 apr_pstrdup(cmd->pool, method));
2217 limited |= (AP_METHOD_BIT << methnum);
2220 /* Killing two features with one function,
2221 * if (tog == NULL) <Limit>, else <LimitExcept>
2223 limited = tog ? ~limited : limited;
2225 if (!(old_limited & limited)) {
2226 return apr_pstrcat(cmd->pool, cmd->cmd->name,
2227 "> directive excludes all methods", NULL);
2229 else if ((old_limited & limited) == old_limited) {
2230 return apr_pstrcat(cmd->pool, cmd->cmd->name,
2231 "> directive specifies methods already excluded",
2235 cmd->limited &= limited;
2237 errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context);
2239 cmd->limited = old_limited;
2244 /* XXX: Bogus - need to do this differently (at least OS2/Netware suffer
2245 * the same problem!!!
2246 * We use this in <DirectoryMatch> and <FilesMatch>, to ensure that
2247 * people don't get bitten by wrong-cased regex matches
2251 #define USE_ICASE AP_REG_ICASE
2256 static const char *dirsection(cmd_parms *cmd, void *mconfig, const char *arg)
2259 const char *endp = ap_strrchr_c(arg, '>');
2260 int old_overrides = cmd->override;
2261 char *old_path = cmd->path;
2262 core_dir_config *conf;
2263 ap_conf_vector_t *new_dir_conf = ap_create_per_dir_config(cmd->pool);
2264 ap_regex_t *r = NULL;
2265 const command_rec *thiscmd = cmd->cmd;
2267 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
2273 return unclosed_directive(cmd);
2276 arg = apr_pstrndup(cmd->temp_pool, arg, endp - arg);
2279 return missing_container_arg(cmd);
2282 cmd->path = ap_getword_conf(cmd->pool, &arg);
2283 cmd->override = OR_ALL|ACCESS_CONF;
2285 if (!strcmp(cmd->path, "~")) {
2286 cmd->path = ap_getword_conf(cmd->pool, &arg);
2288 return "<Directory ~ > block must specify a path";
2289 r = ap_pregcomp(cmd->pool, cmd->path, AP_REG_EXTENDED|USE_ICASE);
2291 return "Regex could not be compiled";
2294 else if (thiscmd->cmd_data) { /* <DirectoryMatch> */
2295 r = ap_pregcomp(cmd->pool, cmd->path, AP_REG_EXTENDED|USE_ICASE);
2297 return "Regex could not be compiled";
2300 else if (!strcmp(cmd->path, "/") == 0)
2305 * Ensure that the pathname is canonical, and append the trailing /
2307 apr_status_t rv = apr_filepath_merge(&newpath, NULL, cmd->path,
2308 APR_FILEPATH_TRUENAME, cmd->pool);
2309 if (rv != APR_SUCCESS && rv != APR_EPATHWILD) {
2310 return apr_pstrcat(cmd->pool, "<Directory \"", cmd->path,
2311 "\"> path is invalid.", NULL);
2314 cmd->path = newpath;
2315 if (cmd->path[strlen(cmd->path) - 1] != '/')
2316 cmd->path = apr_pstrcat(cmd->pool, cmd->path, "/", NULL);
2319 /* initialize our config and fetch it */
2320 conf = ap_set_config_vectors(cmd->server, new_dir_conf, cmd->path,
2321 &core_module, cmd->pool);
2323 errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_dir_conf);
2328 conf->d = cmd->path;
2329 conf->d_is_fnmatch = (apr_fnmatch_test(conf->d) != 0);
2332 conf->refs = apr_array_make(cmd->pool, 8, sizeof(char *));
2333 ap_regname(r, conf->refs, AP_REG_MATCH, 1);
2336 /* Make this explicit - the "/" root has 0 elements, that is, we
2337 * will always merge it, and it will always sort and merge first.
2338 * All others are sorted and tested by the number of slashes.
2340 if (strcmp(conf->d, "/") == 0)
2341 conf->d_components = 0;
2343 conf->d_components = ap_count_dirs(conf->d);
2345 ap_add_per_dir_conf(cmd->server, new_dir_conf);
2348 return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
2349 "> arguments not (yet) supported.", NULL);
2352 cmd->path = old_path;
2353 cmd->override = old_overrides;
2358 static const char *urlsection(cmd_parms *cmd, void *mconfig, const char *arg)
2361 const char *endp = ap_strrchr_c(arg, '>');
2362 int old_overrides = cmd->override;
2363 char *old_path = cmd->path;
2364 core_dir_config *conf;
2365 ap_regex_t *r = NULL;
2366 const command_rec *thiscmd = cmd->cmd;
2367 ap_conf_vector_t *new_url_conf = ap_create_per_dir_config(cmd->pool);
2368 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
2374 return unclosed_directive(cmd);
2377 arg = apr_pstrndup(cmd->temp_pool, arg, endp - arg);
2380 return missing_container_arg(cmd);
2383 cmd->path = ap_getword_conf(cmd->pool, &arg);
2384 cmd->override = OR_ALL|ACCESS_CONF;
2386 if (thiscmd->cmd_data) { /* <LocationMatch> */
2387 r = ap_pregcomp(cmd->pool, cmd->path, AP_REG_EXTENDED);
2389 return "Regex could not be compiled";
2392 else if (!strcmp(cmd->path, "~")) {
2393 cmd->path = ap_getword_conf(cmd->pool, &arg);
2394 r = ap_pregcomp(cmd->pool, cmd->path, AP_REG_EXTENDED);
2396 return "Regex could not be compiled";
2400 /* initialize our config and fetch it */
2401 conf = ap_set_config_vectors(cmd->server, new_url_conf, cmd->path,
2402 &core_module, cmd->pool);
2404 errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_url_conf);
2408 conf->d = apr_pstrdup(cmd->pool, cmd->path); /* No mangling, please */
2409 conf->d_is_fnmatch = apr_fnmatch_test(conf->d) != 0;
2413 conf->refs = apr_array_make(cmd->pool, 8, sizeof(char *));
2414 ap_regname(r, conf->refs, AP_REG_MATCH, 1);
2417 ap_add_per_url_conf(cmd->server, new_url_conf);
2420 return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
2421 "> arguments not (yet) supported.", NULL);
2424 cmd->path = old_path;
2425 cmd->override = old_overrides;
2430 static const char *filesection(cmd_parms *cmd, void *mconfig, const char *arg)
2433 const char *endp = ap_strrchr_c(arg, '>');
2434 int old_overrides = cmd->override;
2435 char *old_path = cmd->path;
2436 core_dir_config *conf;
2437 ap_regex_t *r = NULL;
2438 const command_rec *thiscmd = cmd->cmd;
2439 ap_conf_vector_t *new_file_conf = ap_create_per_dir_config(cmd->pool);
2440 const char *err = ap_check_cmd_context(cmd,
2441 NOT_IN_LOCATION | NOT_IN_LIMIT);
2448 return unclosed_directive(cmd);
2451 arg = apr_pstrndup(cmd->temp_pool, arg, endp - arg);
2454 return missing_container_arg(cmd);
2457 cmd->path = ap_getword_conf(cmd->pool, &arg);
2458 /* Only if not an .htaccess file */
2460 cmd->override = OR_ALL|ACCESS_CONF;
2463 if (thiscmd->cmd_data) { /* <FilesMatch> */
2464 r = ap_pregcomp(cmd->pool, cmd->path, AP_REG_EXTENDED|USE_ICASE);
2466 return "Regex could not be compiled";
2469 else if (!strcmp(cmd->path, "~")) {
2470 cmd->path = ap_getword_conf(cmd->pool, &arg);
2471 r = ap_pregcomp(cmd->pool, cmd->path, AP_REG_EXTENDED|USE_ICASE);
2473 return "Regex could not be compiled";
2478 /* Ensure that the pathname is canonical, but we
2479 * can't test the case/aliases without a fixed path */
2480 if (apr_filepath_merge(&newpath, "", cmd->path,
2481 0, cmd->pool) != APR_SUCCESS)
2482 return apr_pstrcat(cmd->pool, "<Files \"", cmd->path,
2483 "\"> is invalid.", NULL);
2484 cmd->path = newpath;
2487 /* initialize our config and fetch it */
2488 conf = ap_set_config_vectors(cmd->server, new_file_conf, cmd->path,
2489 &core_module, cmd->pool);
2491 errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_file_conf);
2495 conf->d = cmd->path;
2496 conf->d_is_fnmatch = apr_fnmatch_test(conf->d) != 0;
2500 conf->refs = apr_array_make(cmd->pool, 8, sizeof(char *));
2501 ap_regname(r, conf->refs, AP_REG_MATCH, 1);
2504 ap_add_file_conf(cmd->pool, (core_dir_config *)mconfig, new_file_conf);
2507 return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
2508 "> arguments not (yet) supported.", NULL);
2511 cmd->path = old_path;
2512 cmd->override = old_overrides;
2517 #define COND_IF ((void *)1)
2518 #define COND_ELSE ((void *)2)
2519 #define COND_ELSEIF ((void *)3)
2521 static const char *ifsection(cmd_parms *cmd, void *mconfig, const char *arg)
2524 const char *endp = ap_strrchr_c(arg, '>');
2525 int old_overrides = cmd->override;
2526 char *old_path = cmd->path;
2527 core_dir_config *conf;
2528 const command_rec *thiscmd = cmd->cmd;
2529 ap_conf_vector_t *new_if_conf = ap_create_per_dir_config(cmd->pool);
2530 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2531 const char *condition;
2532 const char *expr_err;
2539 return unclosed_directive(cmd);
2542 arg = apr_pstrndup(cmd->temp_pool, arg, endp - arg);
2545 * Set a dummy value so that other directives notice that they are inside
2549 /* Only if not an .htaccess file */
2551 cmd->override = OR_ALL|ACCESS_CONF;
2554 /* initialize our config and fetch it */
2555 conf = ap_set_config_vectors(cmd->server, new_if_conf, cmd->path,
2556 &core_module, cmd->pool);
2558 if (cmd->cmd->cmd_data == COND_IF)
2559 conf->condition_ifelse = AP_CONDITION_IF;
2560 else if (cmd->cmd->cmd_data == COND_ELSEIF)
2561 conf->condition_ifelse = AP_CONDITION_ELSEIF;
2562 else if (cmd->cmd->cmd_data == COND_ELSE)
2563 conf->condition_ifelse = AP_CONDITION_ELSE;
2567 if (conf->condition_ifelse == AP_CONDITION_ELSE) {
2569 return "<Else> does not take an argument";
2573 return missing_container_arg(cmd);
2574 condition = ap_getword_conf(cmd->pool, &arg);
2575 conf->condition = ap_expr_parse_cmd(cmd, condition, 0, &expr_err, NULL);
2577 return apr_psprintf(cmd->pool, "Cannot parse condition clause: %s",
2581 errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_if_conf);
2585 conf->d = cmd->path;
2586 conf->d_is_fnmatch = 0;
2589 errmsg = ap_add_if_conf(cmd->pool, (core_dir_config *)mconfig, new_if_conf);
2594 return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
2595 "> arguments not supported.", NULL);
2598 cmd->path = old_path;
2599 cmd->override = old_overrides;
2604 static module *find_module(server_rec *s, const char *name)
2606 module *found = ap_find_linked_module(name);
2608 /* search prelinked stuff */
2610 ap_module_symbol_t *current = ap_prelinked_module_symbols;
2612 for (; current->name; ++current) {
2613 if (!strcmp(current->name, name)) {
2614 found = current->modp;
2620 /* search dynamic stuff */
2622 APR_OPTIONAL_FN_TYPE(ap_find_loaded_module_symbol) *check_symbol =
2623 APR_RETRIEVE_OPTIONAL_FN(ap_find_loaded_module_symbol);
2627 * There are two phases where calling ap_find_loaded_module_symbol
2630 * During reading of the config, ap_server_conf is invalid but s
2631 * points to the main server config, if passed from cmd->server
2632 * of an EXEC_ON_READ directive.
2634 * During config parsing, s may be a virtual host that would cause
2635 * a segfault in mod_so if passed to ap_find_loaded_module_symbol,
2636 * because mod_so's server config for vhosts is initialized later.
2637 * But ap_server_conf is already set at this time.
2639 * Therefore we use s if it is not virtual and ap_server_conf if
2642 found = check_symbol(s->is_virtual ? ap_server_conf : s, name);
2650 static const char *start_ifmod(cmd_parms *cmd, void *mconfig, const char *arg)
2652 const char *endp = ap_strrchr_c(arg, '>');
2653 int not = (arg[0] == '!');
2657 return unclosed_directive(cmd);
2660 arg = apr_pstrndup(cmd->temp_pool, arg, endp - arg);
2667 return missing_container_arg(cmd);
2670 found = find_module(cmd->server, arg);
2672 if ((!not && found) || (not && !found)) {
2673 ap_directive_t *parent = NULL;
2674 ap_directive_t *current = NULL;
2677 retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd,
2678 ¤t, &parent, "<IfModule");
2679 *(ap_directive_t **)mconfig = current;
2683 *(ap_directive_t **)mconfig = NULL;
2684 return ap_soak_end_container(cmd, "<IfModule");
2688 AP_DECLARE(int) ap_exists_config_define(const char *name)
2690 return ap_array_str_contains(ap_server_config_defines, name);
2693 static const char *start_ifdefine(cmd_parms *cmd, void *dummy, const char *arg)
2699 endp = ap_strrchr_c(arg, '>');
2701 return unclosed_directive(cmd);
2704 arg = apr_pstrndup(cmd->temp_pool, arg, endp - arg);
2706 if (arg[0] == '!') {
2712 return missing_container_arg(cmd);
2715 defined = ap_exists_config_define(arg);
2716 if ((!not && defined) || (not && !defined)) {
2717 ap_directive_t *parent = NULL;
2718 ap_directive_t *current = NULL;
2721 retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd,
2722 ¤t, &parent, "<IfDefine");
2723 *(ap_directive_t **)dummy = current;
2727 *(ap_directive_t **)dummy = NULL;
2728 return ap_soak_end_container(cmd, "<IfDefine");
2732 /* httpd.conf commands... beginning with the <VirtualHost> business */
2734 static const char *virtualhost_section(cmd_parms *cmd, void *dummy,
2737 server_rec *main_server = cmd->server, *s;
2739 const char *endp = ap_strrchr_c(arg, '>');
2740 apr_pool_t *p = cmd->pool;
2742 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2748 return unclosed_directive(cmd);
2751 arg = apr_pstrndup(cmd->temp_pool, arg, endp - arg);
2754 return missing_container_arg(cmd);
2757 /* FIXME: There's another feature waiting to happen here -- since you
2758 can now put multiple addresses/names on a single <VirtualHost>
2759 you might want to use it to group common definitions and then
2760 define other "subhosts" with their individual differences. But
2761 personally I'd rather just do it with a macro preprocessor. -djg */
2762 if (main_server->is_virtual) {
2763 return "<VirtualHost> doesn't nest!";
2766 errmsg = ap_init_virtual_host(p, arg, main_server, &s);
2771 s->next = main_server->next;
2772 main_server->next = s;
2774 s->defn_name = cmd->directive->filename;
2775 s->defn_line_number = cmd->directive->line_num;
2779 errmsg = ap_walk_config(cmd->directive->first_child, cmd,
2780 s->lookup_defaults);
2782 cmd->server = main_server;
2787 static const char *set_server_alias(cmd_parms *cmd, void *dummy,
2790 if (!cmd->server->names) {
2791 return "ServerAlias only used in <VirtualHost>";
2795 char **item, *name = ap_getword_conf(cmd->pool, &arg);
2797 if (ap_is_matchexp(name)) {
2798 item = (char **)apr_array_push(cmd->server->wild_names);
2801 item = (char **)apr_array_push(cmd->server->names);
2810 static const char *set_accf_map(cmd_parms *cmd, void *dummy,
2811 const char *iproto, const char* iaccf)
2813 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2814 core_server_config *conf =
2815 ap_get_core_module_config(cmd->server->module_config);
2822 proto = apr_pstrdup(cmd->pool, iproto);
2823 ap_str_tolower(proto);
2824 accf = apr_pstrdup(cmd->pool, iaccf);
2825 ap_str_tolower(accf);
2826 apr_table_setn(conf->accf_map, proto, accf);
2831 AP_DECLARE(const char*) ap_get_server_protocol(server_rec* s)
2833 core_server_config *conf = ap_get_core_module_config(s->module_config);
2834 return conf->protocol;
2837 AP_DECLARE(void) ap_set_server_protocol(server_rec* s, const char* proto)
2839 core_server_config *conf = ap_get_core_module_config(s->module_config);
2840 conf->protocol = proto;
2843 static const char *set_protocol(cmd_parms *cmd, void *dummy,
2846 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
2847 core_server_config *conf =
2848 ap_get_core_module_config(cmd->server->module_config);
2855 proto = apr_pstrdup(cmd->pool, arg);
2856 ap_str_tolower(proto);
2857 conf->protocol = proto;
2862 static const char *set_server_string_slot(cmd_parms *cmd, void *dummy,
2865 /* This one's pretty generic... */
2867 int offset = (int)(long)cmd->info;
2868 char *struct_ptr = (char *)cmd->server;
2870 const char *err = ap_check_cmd_context(cmd,
2871 NOT_IN_DIR_LOC_FILE);
2876 *(const char **)(struct_ptr + offset) = arg;
2881 * The ServerName directive takes one argument with format
2882 * [scheme://]fully-qualified-domain-name[:port], for instance
2883 * ServerName www.example.com
2884 * ServerName www.example.com:80
2885 * ServerName https://www.example.com:443
2888 static const char *server_hostname_port(cmd_parms *cmd, void *dummy, const char *arg)
2890 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
2891 const char *portstr, *part;
2899 if (apr_fnmatch_test(arg))
2900 return apr_pstrcat(cmd->temp_pool, "Invalid ServerName \"", arg,
2901 "\" use ServerAlias to set multiple server names.", NULL);
2903 part = ap_strstr_c(arg, "://");
2906 scheme = apr_pstrndup(cmd->pool, arg, part - arg);
2907 ap_str_tolower(scheme);
2908 cmd->server->server_scheme = (const char *)scheme;
2914 portstr = ap_strchr_c(part, ':');
2916 cmd->server->server_hostname = apr_pstrndup(cmd->pool, part,
2919 port = atoi(portstr);
2920 if (port <= 0 || port >= 65536) { /* 65536 == 1<<16 */
2921 return apr_pstrcat(cmd->temp_pool, "The port number \"", arg,
2922 "\" is outside the appropriate range "
2923 "(i.e., 1..65535).", NULL);
2927 cmd->server->server_hostname = apr_pstrdup(cmd->pool, part);
2931 cmd->server->port = port;
2935 static const char *set_signature_flag(cmd_parms *cmd, void *d_,
2938 core_dir_config *d = d_;
2940 if (strcasecmp(arg, "On") == 0) {
2941 d->server_signature = srv_sig_on;
2943 else if (strcasecmp(arg, "Off") == 0) {
2944 d->server_signature = srv_sig_off;
2946 else if (strcasecmp(arg, "EMail") == 0) {
2947 d->server_signature = srv_sig_withmail;
2950 return "ServerSignature: use one of: off | on | email";
2956 static const char *set_server_root(cmd_parms *cmd, void *dummy,
2959 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2965 if ((apr_filepath_merge((char**)&ap_server_root, NULL, arg,
2966 APR_FILEPATH_TRUENAME, cmd->pool) != APR_SUCCESS)
2967 || !ap_is_directory(cmd->temp_pool, ap_server_root)) {
2968 return "ServerRoot must be a valid directory";
2974 static const char *set_runtime_dir(cmd_parms *cmd, void *dummy, const char *arg)
2976 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2982 if ((apr_filepath_merge((char**)&ap_runtime_dir, NULL,
2983 ap_server_root_relative(cmd->temp_pool, arg),
2984 APR_FILEPATH_TRUENAME, cmd->pool) != APR_SUCCESS)
2985 || !ap_is_directory(cmd->temp_pool, ap_runtime_dir)) {
2986 return "DefaultRuntimeDir must be a valid directory, absolute or relative to ServerRoot";
2992 static const char *set_timeout(cmd_parms *cmd, void *dummy, const char *arg)
2994 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
3000 cmd->server->timeout = apr_time_from_sec(atoi(arg));
3004 static const char *set_allow2f(cmd_parms *cmd, void *d_, const char *arg)
3006 core_dir_config *d = d_;
3008 if (0 == strcasecmp(arg, "on")) {
3009 d->allow_encoded_slashes = 1;
3010 d->decode_encoded_slashes = 1; /* for compatibility with 2.0 & 2.2 */
3011 } else if (0 == strcasecmp(arg, "off")) {
3012 d->allow_encoded_slashes = 0;
3013 d->decode_encoded_slashes = 0;
3014 } else if (0 == strcasecmp(arg, "nodecode")) {
3015 d->allow_encoded_slashes = 1;
3016 d->decode_encoded_slashes = 0;
3018 return apr_pstrcat(cmd->pool,
3019 cmd->cmd->name, " must be On, Off, or NoDecode",
3025 static const char *set_hostname_lookups(cmd_parms *cmd, void *d_,
3028 core_dir_config *d = d_;
3030 if (!strcasecmp(arg, "on")) {
3031 d->hostname_lookups = HOSTNAME_LOOKUP_ON;
3033 else if (!strcasecmp(arg, "off")) {
3034 d->hostname_lookups = HOSTNAME_LOOKUP_OFF;
3036 else if (!strcasecmp(arg, "double")) {
3037 d->hostname_lookups = HOSTNAME_LOOKUP_DOUBLE;
3040 return "parameter must be 'on', 'off', or 'double'";
3046 static const char *set_serverpath(cmd_parms *cmd, void *dummy,
3049 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
3055 cmd->server->path = arg;
3056 cmd->server->pathlen = (int)strlen(arg);
3060 static const char *set_content_md5(cmd_parms *cmd, void *d_, int arg)
3062 core_dir_config *d = d_;
3064 d->content_md5 = arg ? AP_CONTENT_MD5_ON : AP_CONTENT_MD5_OFF;
3068 static const char *set_accept_path_info(cmd_parms *cmd, void *d_, const char *arg)
3070 core_dir_config *d = d_;
3072 if (strcasecmp(arg, "on") == 0) {
3073 d->accept_path_info = AP_REQ_ACCEPT_PATH_INFO;
3075 else if (strcasecmp(arg, "off") == 0) {
3076 d->accept_path_info = AP_REQ_REJECT_PATH_INFO;
3078 else if (strcasecmp(arg, "default") == 0) {
3079 d->accept_path_info = AP_REQ_DEFAULT_PATH_INFO;
3082 return "AcceptPathInfo must be set to on, off or default";
3088 static const char *set_use_canonical_name(cmd_parms *cmd, void *d_,
3091 core_dir_config *d = d_;
3093 if (strcasecmp(arg, "on") == 0) {
3094 d->use_canonical_name = USE_CANONICAL_NAME_ON;
3096 else if (strcasecmp(arg, "off") == 0) {
3097 d->use_canonical_name = USE_CANONICAL_NAME_OFF;
3099 else if (strcasecmp(arg, "dns") == 0) {
3100 d->use_canonical_name = USE_CANONICAL_NAME_DNS;
3103 return "parameter must be 'on', 'off', or 'dns'";
3109 static const char *set_use_canonical_phys_port(cmd_parms *cmd, void *d_,
3112 core_dir_config *d = d_;
3114 if (strcasecmp(arg, "on") == 0) {
3115 d->use_canonical_phys_port = USE_CANONICAL_PHYS_PORT_ON;
3117 else if (strcasecmp(arg, "off") == 0) {
3118 d->use_canonical_phys_port = USE_CANONICAL_PHYS_PORT_OFF;
3121 return "parameter must be 'on' or 'off'";
3127 static const char *include_config (cmd_parms *cmd, void *dummy,
3130 ap_directive_t *conftree = NULL;
3131 const char *conffile, *error;
3132 unsigned *recursion;
3133 int optional = cmd->cmd->cmd_data ? 1 : 0;
3136 apr_pool_userdata_get(&data, "ap_include_sentinel", cmd->pool);
3141 data = recursion = apr_palloc(cmd->pool, sizeof(*recursion));
3143 apr_pool_userdata_setn(data, "ap_include_sentinel", NULL, cmd->pool);
3146 if (++*recursion > AP_MAX_INCLUDE_DEPTH) {
3148 return apr_psprintf(cmd->pool, "Exceeded maximum include depth of %u, "
3149 "There appears to be a recursion.",
3150 AP_MAX_INCLUDE_DEPTH);
3153 conffile = ap_server_root_relative(cmd->pool, name);
3156 return apr_pstrcat(cmd->pool, "Invalid Include path ",
3160 error = ap_process_fnmatch_configs(cmd->server, conffile, &conftree,
3161 cmd->pool, cmd->temp_pool,
3168 *(ap_directive_t **)dummy = conftree;
3170 /* recursion level done */
3178 static const char *set_loglevel(cmd_parms *cmd, void *config_, const char *arg_)
3183 char *arg = apr_pstrdup(cmd->temp_pool, arg_);
3184 struct ap_logconf *log;
3188 core_dir_config *dconf = config_;
3190 dconf->log = ap_new_log_config(cmd->pool, NULL);
3195 log = &cmd->server->log;
3199 return "LogLevel requires level keyword or module loglevel specifier";
3201 level_str = ap_strrchr(arg, ':');
3203 if (level_str == NULL) {
3204 err = ap_parse_log_level(arg, &log->level);
3207 ap_reset_module_loglevels(log, APLOG_NO_MODULE);
3208 ap_log_error(APLOG_MARK, APLOG_TRACE3, 0, cmd->server,
3209 "Setting LogLevel for all modules to %s", arg);
3213 *level_str++ = '\0';
3215 return apr_psprintf(cmd->temp_pool, "Module specifier '%s' must be "
3216 "followed by a log level keyword", arg);
3219 err = ap_parse_log_level(level_str, &level);
3221 return apr_psprintf(cmd->temp_pool, "%s:%s: %s", arg, level_str, err);
3223 if ((module = find_module(cmd->server, arg)) == NULL) {
3224 char *name = apr_psprintf(cmd->temp_pool, "%s_module", arg);
3225 ap_log_error(APLOG_MARK, APLOG_TRACE6, 0, cmd->server,
3226 "Cannot find module '%s', trying '%s'", arg, name);
3227 module = find_module(cmd->server, name);
3230 if (module == NULL) {
3231 return apr_psprintf(cmd->temp_pool, "Cannot find module %s", arg);
3234 ap_set_module_loglevel(cmd->pool, log, module->module_index, level);
3235 ap_log_error(APLOG_MARK, APLOG_TRACE3, 0, cmd->server,
3236 "Setting LogLevel for module %s to %s", module->name,
3242 AP_DECLARE(const char *) ap_psignature(const char *prefix, request_rec *r)
3245 core_dir_config *conf;
3247 conf = (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
3248 if ((conf->server_signature == srv_sig_off)
3249 || (conf->server_signature == srv_sig_unset)) {
3253 apr_snprintf(sport, sizeof sport, "%u", (unsigned) ap_get_server_port(r));
3255 if (conf->server_signature == srv_sig_withmail) {
3256 return apr_pstrcat(r->pool, prefix, "<address>",
3257 ap_get_server_banner(),
3258 " Server at <a href=\"",
3259 ap_is_url(r->server->server_admin) ? "" : "mailto:",
3260 ap_escape_html(r->pool, r->server->server_admin),
3262 ap_escape_html(r->pool, ap_get_server_name(r)),
3263 "</a> Port ", sport,
3264 "</address>\n", NULL);
3267 return apr_pstrcat(r->pool, prefix, "<address>", ap_get_server_banner(),
3269 ap_escape_html(r->pool, ap_get_server_name(r)),
3271 "</address>\n", NULL);
3275 * Handle a request to include the server's OS platform in the Server
3276 * response header field (the ServerTokens directive). Unfortunately
3277 * this requires a new global in order to communicate the setting back to
3278 * http_main so it can insert the information in the right place in the
3282 static char *server_banner = NULL;
3283 static int banner_locked = 0;
3284 static const char *server_description = NULL;
3286 enum server_token_type {
3287 SrvTk_MAJOR, /* eg: Apache/2 */
3288 SrvTk_MINOR, /* eg. Apache/2.0 */
3289 SrvTk_MINIMAL, /* eg: Apache/2.0.41 */
3290 SrvTk_OS, /* eg: Apache/2.0.41 (UNIX) */
3291 SrvTk_FULL, /* eg: Apache/2.0.41 (UNIX) PHP/4.2.2 FooBar/1.2b */
3292 SrvTk_PRODUCT_ONLY /* eg: Apache */
3294 static enum server_token_type ap_server_tokens = SrvTk_FULL;
3296 static apr_status_t reset_banner(void *dummy)
3299 ap_server_tokens = SrvTk_FULL;
3300 server_banner = NULL;
3301 server_description = NULL;
3305 AP_DECLARE(void) ap_get_server_revision(ap_version_t *version)
3307 version->major = AP_SERVER_MAJORVERSION_NUMBER;
3308 version->minor = AP_SERVER_MINORVERSION_NUMBER;
3309 version->patch = AP_SERVER_PATCHLEVEL_NUMBER;
3310 version->add_string = AP_SERVER_ADD_STRING;
3313 AP_DECLARE(const char *) ap_get_server_description(void)
3315 return server_description ? server_description :
3316 AP_SERVER_BASEVERSION " (" PLATFORM ")";
3319 AP_DECLARE(const char *) ap_get_server_banner(void)
3321 return server_banner ? server_banner : AP_SERVER_BASEVERSION;
3324 AP_DECLARE(void) ap_add_version_component(apr_pool_t *pconf, const char *component)
3326 if (! banner_locked) {
3328 * If the version string is null, register our cleanup to reset the
3329 * pointer on pool destruction. We also know that, if NULL,
3330 * we are adding the original SERVER_BASEVERSION string.
3332 if (server_banner == NULL) {
3333 apr_pool_cleanup_register(pconf, NULL, reset_banner,
3334 apr_pool_cleanup_null);
3335 server_banner = apr_pstrdup(pconf, component);
3339 * Tack the given component identifier to the end of
3340 * the existing string.
3342 server_banner = apr_pstrcat(pconf, server_banner, " ",
3346 server_description = apr_pstrcat(pconf, server_description, " ",
3351 * This routine adds the real server base identity to the banner string,
3352 * and then locks out changes until the next reconfig.
3354 static void set_banner(apr_pool_t *pconf)
3356 if (ap_server_tokens == SrvTk_PRODUCT_ONLY) {
3357 ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT);
3359 else if (ap_server_tokens == SrvTk_MINIMAL) {
3360 ap_add_version_component(pconf, AP_SERVER_BASEVERSION);
3362 else if (ap_server_tokens == SrvTk_MINOR) {
3363 ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT "/" AP_SERVER_MINORREVISION);
3365 else if (ap_server_tokens == SrvTk_MAJOR) {
3366 ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT "/" AP_SERVER_MAJORVERSION);
3369 ap_add_version_component(pconf, AP_SERVER_BASEVERSION " (" PLATFORM ")");
3373 * Lock the server_banner string if we're not displaying
3374 * the full set of tokens
3376 if (ap_server_tokens != SrvTk_FULL) {
3379 server_description = AP_SERVER_BASEVERSION " (" PLATFORM ")";
3382 static const char *set_serv_tokens(cmd_parms *cmd, void *dummy,
3385 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
3391 if (!strcasecmp(arg, "OS")) {
3392 ap_server_tokens = SrvTk_OS;
3394 else if (!strcasecmp(arg, "Min") || !strcasecmp(arg, "Minimal")) {
3395 ap_server_tokens = SrvTk_MINIMAL;
3397 else if (!strcasecmp(arg, "Major")) {
3398 ap_server_tokens = SrvTk_MAJOR;
3400 else if (!strcasecmp(arg, "Minor") ) {
3401 ap_server_tokens = SrvTk_MINOR;
3403 else if (!strcasecmp(arg, "Prod") || !strcasecmp(arg, "ProductOnly")) {
3404 ap_server_tokens = SrvTk_PRODUCT_ONLY;
3406 else if (!strcasecmp(arg, "Full")) {
3407 ap_server_tokens = SrvTk_FULL;
3410 return "ServerTokens takes 1 argument: 'Prod(uctOnly)', 'Major', 'Minor', 'Min(imal)', 'OS', or 'Full'";
3416 static const char *set_limit_req_line(cmd_parms *cmd, void *dummy,
3419 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
3428 return apr_pstrcat(cmd->temp_pool, "LimitRequestLine \"", arg,
3429 "\" must be a non-negative integer", NULL);
3432 cmd->server->limit_req_line = lim;
3436 static const char *set_limit_req_fieldsize(cmd_parms *cmd, void *dummy,
3439 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
3448 return apr_pstrcat(cmd->temp_pool, "LimitRequestFieldsize \"", arg,
3449 "\" must be a non-negative integer",
3453 cmd->server->limit_req_fieldsize = lim;
3457 static const char *set_limit_req_fields(cmd_parms *cmd, void *dummy,
3460 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
3469 return apr_pstrcat(cmd->temp_pool, "LimitRequestFields \"", arg,
3470 "\" must be a non-negative integer (0 = no limit)",
3474 cmd->server->limit_req_fields = lim;
3478 static const char *set_limit_req_body(cmd_parms *cmd, void *conf_,
3481 core_dir_config *conf = conf_;
3484 if (APR_SUCCESS != apr_strtoff(&conf->limit_req_body, arg, &errp, 10)) {
3485 return "LimitRequestBody argument is not parsable.";
3487 if (*errp || conf->limit_req_body < 0) {
3488 return "LimitRequestBody requires a non-negative integer.";
3494 static const char *set_limit_xml_req_body(cmd_parms *cmd, void *conf_,
3497 core_dir_config *conf = conf_;
3499 conf->limit_xml_body = atol(arg);
3500 if (conf->limit_xml_body < 0)
3501 return "LimitXMLRequestBody requires a non-negative integer.";
3506 static const char *set_max_ranges(cmd_parms *cmd, void *conf_, const char *arg)
3508 core_dir_config *conf = conf_;
3511 if (!strcasecmp(arg, "none")) {
3512 val = AP_MAXRANGES_NORANGES;
3514 else if (!strcasecmp(arg, "default")) {
3515 val = AP_MAXRANGES_DEFAULT;
3517 else if (!strcasecmp(arg, "unlimited")) {
3518 val = AP_MAXRANGES_UNLIMITED;
3523 return "MaxRanges requires 'none', 'default', 'unlimited' or "
3524 "a positive integer";
3527 conf->max_ranges = val;
3532 static const char *set_max_overlaps(cmd_parms *cmd, void *conf_, const char *arg)
3534 core_dir_config *conf = conf_;
3537 if (!strcasecmp(arg, "none")) {
3538 val = AP_MAXRANGES_NORANGES;
3540 else if (!strcasecmp(arg, "default")) {
3541 val = AP_MAXRANGES_DEFAULT;
3543 else if (!strcasecmp(arg, "unlimited")) {
3544 val = AP_MAXRANGES_UNLIMITED;
3549 return "MaxRangeOverlaps requires 'none', 'default', 'unlimited' or "
3550 "a positive integer";
3553 conf->max_overlaps = val;
3558 static const char *set_max_reversals(cmd_parms *cmd, void *conf_, const char *arg)
3560 core_dir_config *conf = conf_;
3563 if (!strcasecmp(arg, "none")) {
3564 val = AP_MAXRANGES_NORANGES;
3566 else if (!strcasecmp(arg, "default")) {
3567 val = AP_MAXRANGES_DEFAULT;
3569 else if (!strcasecmp(arg, "unlimited")) {
3570 val = AP_MAXRANGES_UNLIMITED;
3575 return "MaxRangeReversals requires 'none', 'default', 'unlimited' or "
3576 "a positive integer";
3579 conf->max_reversals = val;
3584 AP_DECLARE(apr_size_t) ap_get_limit_xml_body(const request_rec *r)
3586 core_dir_config *conf;
3588 conf = ap_get_core_module_config(r->per_dir_config);
3589 if (conf->limit_xml_body == AP_LIMIT_UNSET)
3590 return AP_DEFAULT_LIMIT_XML_BODY;
3592 return (apr_size_t)conf->limit_xml_body;
3595 #if !defined (RLIMIT_CPU) || !(defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)) || !defined (RLIMIT_NPROC)
3596 static const char *no_set_limit(cmd_parms *cmd, void *conf_,
3597 const char *arg, const char *arg2)
3599 ap_log_error(APLOG_MARK, APLOG_ERR, 0, cmd->server, APLOGNO(00118)
3600 "%s not supported on this platform", cmd->cmd->name);
3607 static const char *set_limit_cpu(cmd_parms *cmd, void *conf_,
3608 const char *arg, const char *arg2)
3610 core_dir_config *conf = conf_;
3612 ap_unixd_set_rlimit(cmd, &conf->limit_cpu, arg, arg2, RLIMIT_CPU);
3617 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)
3618 static const char *set_limit_mem(cmd_parms *cmd, void *conf_,
3619 const char *arg, const char * arg2)
3621 core_dir_config *conf = conf_;
3623 #if defined(RLIMIT_AS)
3624 ap_unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2 ,RLIMIT_AS);
3625 #elif defined(RLIMIT_DATA)
3626 ap_unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_DATA);
3627 #elif defined(RLIMIT_VMEM)
3628 ap_unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_VMEM);
3636 static const char *set_limit_nproc(cmd_parms *cmd, void *conf_,
3637 const char *arg, const char * arg2)
3639 core_dir_config *conf = conf_;
3641 ap_unixd_set_rlimit(cmd, &conf->limit_nproc, arg, arg2, RLIMIT_NPROC);
3646 static const char *set_recursion_limit(cmd_parms *cmd, void *dummy,
3647 const char *arg1, const char *arg2)
3649 core_server_config *conf =
3650 ap_get_core_module_config(cmd->server->module_config);
3651 int limit = atoi(arg1);
3654 return "The recursion limit must be greater than zero.";
3657 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server, APLOGNO(00119)
3658 "Limiting internal redirects to very low numbers may "
3659 "cause normal requests to fail.");
3662 conf->redirect_limit = limit;
3668 return "The recursion limit must be greater than zero.";
3671 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server, APLOGNO(00120)
3672 "Limiting the subrequest depth to a very low level may"
3673 " cause normal requests to fail.");
3677 conf->subreq_limit = limit;
3682 static void log_backtrace(const request_rec *r)
3684 const request_rec *top = r;
3686 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00121)
3687 "r->uri = %s", r->uri ? r->uri : "(unexpectedly NULL)");
3689 while (top && (top->prev || top->main)) {
3692 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00122)
3693 "redirected from r->uri = %s",
3694 top->uri ? top->uri : "(unexpectedly NULL)");
3697 if (!top->prev && top->main) {
3699 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(00123)
3700 "subrequested from r->uri = %s",
3701 top->uri ? top->uri : "(unexpectedly NULL)");
3707 * check whether redirect limit is reached
3709 AP_DECLARE(int) ap_is_recursion_limit_exceeded(const request_rec *r)
3711 core_server_config *conf =
3712 ap_get_core_module_config(r->server->module_config);
3713 const request_rec *top = r;
3714 int redirects = 0, subreqs = 0;
3715 int rlimit = conf->redirect_limit
3716 ? conf->redirect_limit
3717 : AP_DEFAULT_MAX_INTERNAL_REDIRECTS;
3718 int slimit = conf->subreq_limit
3719 ? conf->subreq_limit
3720 : AP_DEFAULT_MAX_SUBREQ_DEPTH;
3723 while (top->prev || top->main) {
3725 if (++redirects >= rlimit) {
3726 /* uuh, too much. */
3727 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00124)
3728 "Request exceeded the limit of %d internal "
3729 "redirects due to probable configuration error. "
3730 "Use 'LimitInternalRecursion' to increase the "
3731 "limit if necessary. Use 'LogLevel debug' to get "
3732 "a backtrace.", rlimit);
3734 /* post backtrace */
3737 /* return failure */
3744 if (!top->prev && top->main) {
3745 if (++subreqs >= slimit) {
3746 /* uuh, too much. */
3747 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00125)
3748 "Request exceeded the limit of %d subrequest "
3749 "nesting levels due to probable configuration "
3750 "error. Use 'LimitInternalRecursion' to increase "
3751 "the limit if necessary. Use 'LogLevel debug' to "
3752 "get a backtrace.", slimit);
3754 /* post backtrace */
3757 /* return failure */
3765 /* recursion state: ok */
3769 static const char *set_trace_enable(cmd_parms *cmd, void *dummy,
3772 core_server_config *conf =
3773 ap_get_core_module_config(cmd->server->module_config);
3775 if (strcasecmp(arg1, "on") == 0) {
3776 conf->trace_enable = AP_TRACE_ENABLE;
3778 else if (strcasecmp(arg1, "off") == 0) {
3779 conf->trace_enable = AP_TRACE_DISABLE;
3781 else if (strcasecmp(arg1, "extended") == 0) {
3782 conf->trace_enable = AP_TRACE_EXTENDED;
3785 return "TraceEnable must be one of 'on', 'off', or 'extended'";
3791 static const char *set_protocols(cmd_parms *cmd, void *dummy,
3794 core_server_config *conf =
3795 ap_get_core_module_config(cmd->server->module_config);
3797 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
3803 np = (const char **)apr_array_push(conf->protocols);
3809 static const char *set_protocols_honor_order(cmd_parms *cmd, void *dummy,
3812 core_server_config *conf =
3813 ap_get_core_module_config(cmd->server->module_config);
3814 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE);
3820 if (strcasecmp(arg, "on") == 0) {
3821 conf->protocols_honor_order = 1;
3823 else if (strcasecmp(arg, "off") == 0) {
3824 conf->protocols_honor_order = 0;
3827 return "ProtocolsHonorOrder must be 'on' or 'off'";
3833 static apr_hash_t *errorlog_hash;
3835 static int log_constant_item(const ap_errorlog_info *info, const char *arg,
3836 char *buf, int buflen)
3838 char *end = apr_cpystrn(buf, arg, buflen);
3842 static char *parse_errorlog_misc_string(apr_pool_t *p,
3843 ap_errorlog_format_item *it,
3847 char scratch[MAX_STRING_LEN];
3850 * non-leading white space terminates this string to allow the next field
3851 * separator to be inserted
3855 it->func = log_constant_item;
3858 while (*s && *s != '%' && (*s != ' ' || at_start) && d < scratch + MAX_STRING_LEN) {
3881 /* handle end of string */
3885 /* copy next char verbatim */
3892 it->arg = apr_pstrdup(p, scratch);
3898 static char *parse_errorlog_item(apr_pool_t *p, ap_errorlog_format_item *it,
3901 const char *s = *sa;
3902 ap_errorlog_handler *handler;
3907 it->flags |= AP_ERRORLOG_FLAG_FIELD_SEP;
3909 return parse_errorlog_misc_string(p, it, sa);
3915 /* percent-space (% ) is a field separator */
3916 it->flags |= AP_ERRORLOG_FLAG_FIELD_SEP;
3919 return parse_errorlog_item(p, it, sa);
3921 else if (*s == '%') {
3923 it->func = log_constant_item;
3932 it->arg = ap_getword(p, &s, '}');
3936 it->flags |= AP_ERRORLOG_FLAG_REQUIRED;
3940 it->flags |= AP_ERRORLOG_FLAG_NULL_AS_HYPHEN;
3953 while (apr_isdigit(*++s))
3954 i = i * 10 + (*s) - '0';
3955 it->min_loglevel = i;
3959 it->flags |= AP_ERRORLOG_FLAG_MESSAGE;
3963 handler = (ap_errorlog_handler *)apr_hash_get(errorlog_hash, s, 1);
3969 return apr_pstrcat(p, "Unrecognized error log format directive %",
3972 it->func = handler->func;
3978 return "Ran off end of error log format parsing args to some directive";
3981 static apr_array_header_t *parse_errorlog_string(apr_pool_t *p,
3986 apr_array_header_t *a = apr_array_make(p, 30,
3987 sizeof(ap_errorlog_format_item));
3989 int seen_msg_fmt = 0;
3992 ap_errorlog_format_item *item =
3993 (ap_errorlog_format_item *)apr_array_push(a);
3994 memset(item, 0, sizeof(*item));
3995 res = parse_errorlog_item(p, item, &s);
4000 if (item->flags & AP_ERRORLOG_FLAG_MESSAGE) {
4002 *err = "%M cannot be used in once-per-request or "
4003 "once-per-connection formats";
4008 if (is_main_fmt && item->flags & AP_ERRORLOG_FLAG_REQUIRED) {
4009 *err = "The '+' flag cannot be used in the main error log format";
4012 if (!is_main_fmt && item->min_loglevel) {
4013 *err = "The loglevel cannot be used as a condition in "
4014 "once-per-request or once-per-connection formats";
4017 if (item->min_loglevel > APLOG_TRACE8) {
4018 *err = "The specified loglevel modifier is out of range";
4023 if (is_main_fmt && !seen_msg_fmt) {
4024 *err = "main ErrorLogFormat must contain message format string '%M'";
4031 static const char *set_errorlog_format(cmd_parms *cmd, void *dummy,
4032 const char *arg1, const char *arg2)
4034 const char *err_string = NULL;
4035 core_server_config *conf =
4036 ap_get_core_module_config(cmd->server->module_config);
4039 conf->error_log_format = parse_errorlog_string(cmd->pool, arg1,
4042 else if (!strcasecmp(arg1, "connection")) {
4043 if (!conf->error_log_conn) {
4044 conf->error_log_conn = apr_array_make(cmd->pool, 5,
4045 sizeof(apr_array_header_t *));
4049 apr_array_header_t **e;
4050 e = (apr_array_header_t **) apr_array_push(conf->error_log_conn);
4051 *e = parse_errorlog_string(cmd->pool, arg2, &err_string, 0);
4054 else if (!strcasecmp(arg1, "request")) {
4055 if (!conf->error_log_req) {
4056 conf->error_log_req = apr_array_make(cmd->pool, 5,
4057 sizeof(apr_array_header_t *));
4061 apr_array_header_t **e;
4062 e = (apr_array_header_t **) apr_array_push(conf->error_log_req);
4063 *e = parse_errorlog_string(cmd->pool, arg2, &err_string, 0);
4067 err_string = "ErrorLogFormat type must be one of request, connection";
4073 AP_DECLARE(void) ap_register_errorlog_handler(apr_pool_t *p, char *tag,
4074 ap_errorlog_handler_fn_t *handler,
4077 ap_errorlog_handler *log_struct = apr_palloc(p, sizeof(*log_struct));
4078 log_struct->func = handler;
4079 log_struct->flags = flags;
4081 apr_hash_set(errorlog_hash, tag, 1, (const void *)log_struct);
4085 static const char *set_merge_trailers(cmd_parms *cmd, void *dummy, int arg)
4087 core_server_config *conf = ap_get_module_config(cmd->server->module_config,
4089 conf->merge_trailers = (arg ? AP_MERGE_TRAILERS_ENABLE :
4090 AP_MERGE_TRAILERS_DISABLE);
4095 /* Note --- ErrorDocument will now work from .htaccess files.
4096 * The AllowOverride of Fileinfo allows webmasters to turn it off
4099 static const command_rec core_cmds[] = {
4101 /* Old access config file commands */
4103 AP_INIT_RAW_ARGS("<Directory", dirsection, NULL, RSRC_CONF,
4104 "Container for directives affecting resources located in the specified "
4106 AP_INIT_RAW_ARGS("<Location", urlsection, NULL, RSRC_CONF,
4107 "Container for directives affecting resources accessed through the "
4108 "specified URL paths"),
4109 AP_INIT_RAW_ARGS("<VirtualHost", virtualhost_section, NULL, RSRC_CONF,
4110 "Container to map directives to a particular virtual host, takes one or "
4111 "more host addresses"),
4112 AP_INIT_RAW_ARGS("<Files", filesection, NULL, OR_ALL,
4113 "Container for directives affecting files matching specified patterns"),
4114 AP_INIT_RAW_ARGS("<Limit", ap_limit_section, NULL, OR_LIMIT | OR_AUTHCFG,
4115 "Container for authentication directives when accessed using specified HTTP "
4117 AP_INIT_RAW_ARGS("<LimitExcept", ap_limit_section, (void*)1,
4118 OR_LIMIT | OR_AUTHCFG,
4119 "Container for authentication directives to be applied when any HTTP "
4120 "method other than those specified is used to access the resource"),
4121 AP_INIT_TAKE1("<IfModule", start_ifmod, NULL, EXEC_ON_READ | OR_ALL,
4122 "Container for directives based on existence of specified modules"),
4123 AP_INIT_TAKE1("<IfDefine", start_ifdefine, NULL, EXEC_ON_READ | OR_ALL,
4124 "Container for directives based on existence of command line defines"),
4125 AP_INIT_RAW_ARGS("<DirectoryMatch", dirsection, (void*)1, RSRC_CONF,
4126 "Container for directives affecting resources located in the "
4127 "specified directories"),
4128 AP_INIT_RAW_ARGS("<LocationMatch", urlsection, (void*)1, RSRC_CONF,
4129 "Container for directives affecting resources accessed through the "
4130 "specified URL paths"),
4131 AP_INIT_RAW_ARGS("<FilesMatch", filesection, (void*)1, OR_ALL,
4132 "Container for directives affecting files matching specified patterns"),
4134 AP_INIT_TAKE1("GprofDir", set_gprof_dir, NULL, RSRC_CONF,
4135 "Directory to plop gmon.out files"),
4137 AP_INIT_TAKE1("AddDefaultCharset", set_add_default_charset, NULL, OR_FILEINFO,
4138 "The name of the default charset to add to any Content-Type without one or 'Off' to disable"),
4139 AP_INIT_TAKE1("AcceptPathInfo", set_accept_path_info, NULL, OR_FILEINFO,
4140 "Set to on or off for PATH_INFO to be accepted by handlers, or default for the per-handler preference"),
4141 AP_INIT_TAKE12("Define", set_define, NULL, EXEC_ON_READ|ACCESS_CONF|RSRC_CONF,
4142 "Define a variable, optionally to a value. Same as passing -D to the command line."),
4143 AP_INIT_TAKE1("UnDefine", unset_define, NULL, EXEC_ON_READ|ACCESS_CONF|RSRC_CONF,
4144 "Undefine the existence of a variable. Undo a Define."),
4145 AP_INIT_RAW_ARGS("Error", generate_error, NULL, OR_ALL,
4146 "Generate error message from within configuration"),
4147 AP_INIT_RAW_ARGS("<If", ifsection, COND_IF, OR_ALL,
4148 "Container for directives to be conditionally applied"),
4149 AP_INIT_RAW_ARGS("<ElseIf", ifsection, COND_ELSEIF, OR_ALL,
4150 "Container for directives to be conditionally applied"),
4151 AP_INIT_RAW_ARGS("<Else", ifsection, COND_ELSE, OR_ALL,
4152 "Container for directives to be conditionally applied"),
4154 /* Old resource config file commands */
4156 AP_INIT_RAW_ARGS("AccessFileName", set_access_name, NULL, RSRC_CONF,
4157 "Name(s) of per-directory config files (default: .htaccess)"),
4158 AP_INIT_TAKE1("DocumentRoot", set_document_root, NULL, RSRC_CONF,
4159 "Root directory of the document tree"),
4160 AP_INIT_TAKE2("ErrorDocument", set_error_document, NULL, OR_FILEINFO,
4161 "Change responses for HTTP errors"),
4162 AP_INIT_RAW_ARGS("AllowOverride", set_override, NULL, ACCESS_CONF,
4163 "Controls what groups of directives can be configured by per-directory "
4165 AP_INIT_TAKE_ARGV("AllowOverrideList", set_override_list, NULL, ACCESS_CONF,
4166 "Controls what individual directives can be configured by per-directory "
4168 AP_INIT_RAW_ARGS("Options", set_options, NULL, OR_OPTIONS,
4169 "Set a number of attributes for a given directory"),
4170 AP_INIT_TAKE1("DefaultType", set_default_type, NULL, OR_FILEINFO,
4171 "the default media type for otherwise untyped files (DEPRECATED)"),
4172 AP_INIT_RAW_ARGS("FileETag", set_etag_bits, NULL, OR_FILEINFO,
4173 "Specify components used to construct a file's ETag"),
4174 AP_INIT_TAKE1("EnableMMAP", set_enable_mmap, NULL, OR_FILEINFO,
4175 "Controls whether memory-mapping may be used to read files"),
4176 AP_INIT_TAKE1("EnableSendfile", set_enable_sendfile, NULL, OR_FILEINFO,
4177 "Controls whether sendfile may be used to transmit files"),
4179 /* Old server config file commands */
4181 AP_INIT_TAKE1("Protocol", set_protocol, NULL, RSRC_CONF,
4182 "Set the Protocol for httpd to use."),
4183 AP_INIT_TAKE2("AcceptFilter", set_accf_map, NULL, RSRC_CONF,
4184 "Set the Accept Filter to use for a protocol"),
4185 AP_INIT_TAKE1("Port", ap_set_deprecated, NULL, RSRC_CONF,
4186 "Port was replaced with Listen in Apache 2.0"),
4187 AP_INIT_TAKE1("HostnameLookups", set_hostname_lookups, NULL,
4188 ACCESS_CONF|RSRC_CONF,
4189 "\"on\" to enable, \"off\" to disable reverse DNS lookups, or \"double\" to "
4190 "enable double-reverse DNS lookups"),
4191 AP_INIT_TAKE1("ServerAdmin", set_server_string_slot,
4192 (void *)APR_OFFSETOF(server_rec, server_admin), RSRC_CONF,
4193 "The email address of the server administrator"),
4194 AP_INIT_TAKE1("ServerName", server_hostname_port, NULL, RSRC_CONF,
4195 "The hostname and port of the server"),
4196 AP_INIT_TAKE1("ServerSignature", set_signature_flag, NULL, OR_ALL,
4197 "En-/disable server signature (on|off|email)"),
4198 AP_INIT_TAKE1("ServerRoot", set_server_root, NULL, RSRC_CONF | EXEC_ON_READ,
4199 "Common directory of server-related files (logs, confs, etc.)"),
4200 AP_INIT_TAKE1("DefaultRuntimeDir", set_runtime_dir, NULL, RSRC_CONF | EXEC_ON_READ,
4201 "Common directory for run-time files (shared memory, locks, etc.)"),
4202 AP_INIT_TAKE1("ErrorLog", set_server_string_slot,
4203 (void *)APR_OFFSETOF(server_rec, error_fname), RSRC_CONF,
4204 "The filename of the error log"),
4205 AP_INIT_TAKE12("ErrorLogFormat", set_errorlog_format, NULL, RSRC_CONF,
4206 "Format string for the ErrorLog"),
4207 AP_INIT_RAW_ARGS("ServerAlias", set_server_alias, NULL, RSRC_CONF,
4208 "A name or names alternately used to access the server"),
4209 AP_INIT_TAKE1("ServerPath", set_serverpath, NULL, RSRC_CONF,
4210 "The pathname the server can be reached at"),
4211 AP_INIT_TAKE1("Timeout", set_timeout, NULL, RSRC_CONF,
4212 "Timeout duration (sec)"),
4213 AP_INIT_FLAG("ContentDigest", set_content_md5, NULL, OR_OPTIONS,
4214 "whether or not to send a Content-MD5 header with each request"),
4215 AP_INIT_TAKE1("UseCanonicalName", set_use_canonical_name, NULL,
4216 RSRC_CONF|ACCESS_CONF,
4217 "How to work out the ServerName : Port when constructing URLs"),
4218 AP_INIT_TAKE1("UseCanonicalPhysicalPort", set_use_canonical_phys_port, NULL,
4219 RSRC_CONF|ACCESS_CONF,
4220 "Whether to use the physical Port when constructing URLs"),
4221 /* TODO: RlimitFoo should all be part of mod_cgi, not in the core */
4222 /* TODO: ListenBacklog in MPM */
4223 AP_INIT_TAKE1("Include", include_config, NULL,
4224 (RSRC_CONF | ACCESS_CONF | EXEC_ON_READ),
4225 "Name(s) of the config file(s) to be included; fails if the wildcard does "
4226 "not match at least one file"),
4227 AP_INIT_TAKE1("IncludeOptional", include_config, (void*)1,
4228 (RSRC_CONF | ACCESS_CONF | EXEC_ON_READ),
4229 "Name or pattern of the config file(s) to be included; ignored if the file "
4230 "does not exist or the pattern does not match any files"),
4231 AP_INIT_ITERATE("LogLevel", set_loglevel, NULL, RSRC_CONF|ACCESS_CONF,
4232 "Level of verbosity in error logging"),
4233 AP_INIT_TAKE1("NameVirtualHost", ap_set_name_virtual_host, NULL, RSRC_CONF,
4234 "A numeric IP address:port, or the name of a host"),
4235 AP_INIT_TAKE1("ServerTokens", set_serv_tokens, NULL, RSRC_CONF,
4236 "Determine tokens displayed in the Server: header - Min(imal), "
4237 "Major, Minor, Prod(uctOnly), OS, or Full"),
4238 AP_INIT_TAKE1("LimitRequestLine", set_limit_req_line, NULL, RSRC_CONF,
4239 "Limit on maximum size of an HTTP request line"),
4240 AP_INIT_TAKE1("LimitRequestFieldsize", set_limit_req_fieldsize, NULL,
4242 "Limit on maximum size of an HTTP request header field"),
4243 AP_INIT_TAKE1("LimitRequestFields", set_limit_req_fields, NULL, RSRC_CONF,
4244 "Limit (0 = unlimited) on max number of header fields in a request message"),
4245 AP_INIT_TAKE1("LimitRequestBody", set_limit_req_body,
4246 (void*)APR_OFFSETOF(core_dir_config, limit_req_body), OR_ALL,
4247 "Limit (in bytes) on maximum size of request message body"),
4248 AP_INIT_TAKE1("LimitXMLRequestBody", set_limit_xml_req_body, NULL, OR_ALL,
4249 "Limit (in bytes) on maximum size of an XML-based request "
4251 AP_INIT_RAW_ARGS("Mutex", ap_set_mutex, NULL, RSRC_CONF,
4252 "mutex (or \"default\") and mechanism"),
4254 AP_INIT_TAKE1("MaxRanges", set_max_ranges, NULL, RSRC_CONF|ACCESS_CONF,
4255 "Maximum number of Ranges in a request before returning the entire "
4256 "resource, or 0 for unlimited"),
4257 AP_INIT_TAKE1("MaxRangeOverlaps", set_max_overlaps, NULL, RSRC_CONF|ACCESS_CONF,
4258 "Maximum number of overlaps in Ranges in a request before returning the entire "
4259 "resource, or 0 for unlimited"),
4260 AP_INIT_TAKE1("MaxRangeReversals", set_max_reversals, NULL, RSRC_CONF|ACCESS_CONF,
4261 "Maximum number of reversals in Ranges in a request before returning the entire "
4262 "resource, or 0 for unlimited"),
4263 /* System Resource Controls */
4265 AP_INIT_TAKE12("RLimitCPU", set_limit_cpu,
4266 (void*)APR_OFFSETOF(core_dir_config, limit_cpu),
4267 OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
4269 AP_INIT_TAKE12("RLimitCPU", no_set_limit, NULL,
4270 OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
4272 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined (RLIMIT_AS)
4273 AP_INIT_TAKE12("RLimitMEM", set_limit_mem,
4274 (void*)APR_OFFSETOF(core_dir_config, limit_mem),
4275 OR_ALL, "Soft/hard limits for max memory usage per process"),
4277 AP_INIT_TAKE12("RLimitMEM", no_set_limit, NULL,
4278 OR_ALL, "Soft/hard limits for max memory usage per process"),
4281 AP_INIT_TAKE12("RLimitNPROC", set_limit_nproc,
4282 (void*)APR_OFFSETOF(core_dir_config, limit_nproc),
4283 OR_ALL, "soft/hard limits for max number of processes per uid"),
4285 AP_INIT_TAKE12("RLimitNPROC", no_set_limit, NULL,
4286 OR_ALL, "soft/hard limits for max number of processes per uid"),
4289 /* internal recursion stopper */
4290 AP_INIT_TAKE12("LimitInternalRecursion", set_recursion_limit, NULL, RSRC_CONF,
4291 "maximum recursion depth of internal redirects and subrequests"),
4293 AP_INIT_FLAG("CGIPassAuth", set_cgi_pass_auth, NULL, OR_AUTHCFG,
4294 "Controls whether HTTP authorization headers, normally hidden, will "
4295 "be passed to scripts"),
4296 AP_INIT_FLAG("QualifyRedirectURL", set_qualify_redirect_url, NULL, OR_FILEINFO,
4297 "Controls whether HTTP authorization headers, normally hidden, will "
4298 "be passed to scripts"),
4300 AP_INIT_TAKE1("ForceType", ap_set_string_slot_lower,
4301 (void *)APR_OFFSETOF(core_dir_config, mime_type), OR_FILEINFO,
4302 "a mime type that overrides other configured type"),
4303 AP_INIT_TAKE1("SetHandler", set_sethandler, NULL, OR_FILEINFO,
4304 "a handler name that overrides any other configured handler"),
4305 AP_INIT_TAKE1("SetOutputFilter", ap_set_string_slot,
4306 (void *)APR_OFFSETOF(core_dir_config, output_filters), OR_FILEINFO,
4307 "filter (or ; delimited list of filters) to be run on the request content"),
4308 AP_INIT_TAKE1("SetInputFilter", ap_set_string_slot,
4309 (void *)APR_OFFSETOF(core_dir_config, input_filters), OR_FILEINFO,
4310 "filter (or ; delimited list of filters) to be run on the request body"),
4311 AP_INIT_TAKE1("AllowEncodedSlashes", set_allow2f, NULL, RSRC_CONF,
4312 "Allow URLs containing '/' encoded as '%2F'"),
4314 /* scoreboard.c directives */
4315 AP_INIT_TAKE1("ScoreBoardFile", ap_set_scoreboard, NULL, RSRC_CONF,
4316 "A file for Apache to maintain runtime process management information"),
4317 AP_INIT_FLAG("ExtendedStatus", ap_set_extended_status, NULL, RSRC_CONF,
4318 "\"On\" to track extended status information, \"Off\" to disable"),
4319 AP_INIT_FLAG("SeeRequestTail", ap_set_reqtail, NULL, RSRC_CONF,
4320 "For extended status, \"On\" to see the last 63 chars of "
4321 "the request line, \"Off\" (default) to see the first 63"),
4324 * These are default configuration directives that mpms can/should
4326 * XXX These are not for all platforms, and even some Unix MPMs might not want
4329 AP_INIT_TAKE1("PidFile", ap_mpm_set_pidfile, NULL, RSRC_CONF,
4330 "A file for logging the server process ID"),
4331 AP_INIT_TAKE1("MaxRequestsPerChild", ap_mpm_set_max_requests, NULL, RSRC_CONF,
4332 "Maximum number of connections a particular child serves before "
4333 "dying. (DEPRECATED, use MaxConnectionsPerChild)"),
4334 AP_INIT_TAKE1("MaxConnectionsPerChild", ap_mpm_set_max_requests, NULL, RSRC_CONF,
4335 "Maximum number of connections a particular child serves before dying."),
4336 AP_INIT_TAKE1("CoreDumpDirectory", ap_mpm_set_coredumpdir, NULL, RSRC_CONF,
4337 "The location of the directory Apache changes to before dumping core"),
4338 AP_INIT_TAKE1("MaxMemFree", ap_mpm_set_max_mem_free, NULL, RSRC_CONF,
4339 "Maximum number of 1k blocks a particular child's allocator may hold."),
4340 AP_INIT_TAKE1("ThreadStackSize", ap_mpm_set_thread_stacksize, NULL, RSRC_CONF,
4341 "Size in bytes of stack used by threads handling client connections"),
4342 #if AP_ENABLE_EXCEPTION_HOOK
4343 AP_INIT_TAKE1("EnableExceptionHook", ap_mpm_set_exception_hook, NULL, RSRC_CONF,
4344 "Controls whether exception hook may be called after a crash"),
4346 AP_INIT_TAKE1("TraceEnable", set_trace_enable, NULL, RSRC_CONF,
4347 "'on' (default), 'off' or 'extended' to trace request body content"),
4348 AP_INIT_FLAG("MergeTrailers", set_merge_trailers, NULL, RSRC_CONF,
4349 "merge request trailers into request headers or not"),
4350 AP_INIT_ITERATE("Protocols", set_protocols, NULL, RSRC_CONF,
4351 "Controls which protocols are allowed"),
4352 AP_INIT_TAKE1("ProtocolsHonorOrder", set_protocols_honor_order, NULL, RSRC_CONF,
4353 "'off' (default) or 'on' to respect given order of protocols, "
4354 "by default the client specified order determines selection"),
4358 /*****************************************************************
4360 * Core handlers for various phases of server operation...
4363 AP_DECLARE_NONSTD(int) ap_core_translate(request_rec *r)
4368 /* XXX this seems too specific, this should probably become
4369 * some general-case test
4372 return HTTP_FORBIDDEN;
4374 if (!r->uri || ((r->uri[0] != '/') && strcmp(r->uri, "*"))) {
4375 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00126)
4376 "Invalid URI in request %s", r->the_request);
4377 return HTTP_BAD_REQUEST;
4381 && !strncmp(r->uri, r->server->path, r->server->pathlen)
4382 && (r->server->path[r->server->pathlen - 1] == '/'
4383 || r->uri[r->server->pathlen] == '/'
4384 || r->uri[r->server->pathlen] == '\0'))
4386 path = r->uri + r->server->pathlen;
4392 * Make sure that we do not mess up the translation by adding two
4393 * /'s in a row. This happens under windows when the document
4394 * root ends with a /
4396 /* skip all leading /'s (e.g. http://localhost///foo)
4397 * so we are looking at only the relative path.
4399 while (*path == '/') {
4402 if ((rv = apr_filepath_merge(&r->filename, ap_document_root(r), path,
4403 APR_FILEPATH_TRUENAME
4404 | APR_FILEPATH_SECUREROOT, r->pool))
4406 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(00127)
4407 "Cannot map %s to file", r->the_request);
4408 return HTTP_FORBIDDEN;
4410 r->canonical_filename = r->filename;
4415 /*****************************************************************
4417 * Test the filesystem name through directory_walk and file_walk
4419 static int core_map_to_storage(request_rec *r)
4423 if ((access_status = ap_directory_walk(r))) {
4424 return access_status;
4427 if ((access_status = ap_file_walk(r))) {
4428 return access_status;
4435 static int do_nothing(request_rec *r) { return OK; }
4437 static int core_override_type(request_rec *r)
4439 core_dir_config *conf =
4440 (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
4442 /* Check for overrides with ForceType / SetHandler
4444 if (conf->mime_type && strcmp(conf->mime_type, "none"))
4445 ap_set_content_type(r, (char*) conf->mime_type);
4447 if (conf->expr_handler) {
4450 val = ap_expr_str_exec(r, conf->expr_handler, &err);
4452 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(03154)
4453 "Can't evaluate handler expression: %s", err);
4454 return HTTP_INTERNAL_SERVER_ERROR;
4456 if (strcmp(val, "none")) {
4457 if (val != ap_strstr_c(val, "proxy:unix")) {
4458 /* Retained for compatibility -- but not for UDS */
4459 char *tmp = apr_pstrdup(r->pool, val);
4460 ap_str_tolower(tmp);
4468 else if (conf->handler && strcmp(conf->handler, "none")) {
4469 r->handler = conf->handler;
4472 /* Deal with the poor soul who is trying to force path_info to be
4473 * accepted within the core_handler, where they will let the subreq
4474 * address its contents. This is toggled by the user in the very
4475 * beginning of the fixup phase (here!), so modules should override the user's
4476 * discretion in their own module fixup phase. It is tristate, if
4477 * the user doesn't specify, the result is AP_REQ_DEFAULT_PATH_INFO.
4478 * (which the module may interpret to its own customary behavior.)
4479 * It won't be touched if the value is no longer AP_ACCEPT_PATHINFO_UNSET,
4480 * so any module changing the value prior to the fixup phase
4481 * OVERRIDES the user's choice.
4483 if ((r->used_path_info == AP_REQ_DEFAULT_PATH_INFO)
4484 && (conf->accept_path_info != AP_ACCEPT_PATHINFO_UNSET)) {
4485 /* No module knew better, and the user coded AcceptPathInfo */
4486 r->used_path_info = conf->accept_path_info;
4492 static int default_handler(request_rec *r)
4494 conn_rec *c = r->connection;
4495 apr_bucket_brigade *bb;
4499 apr_file_t *fd = NULL;
4500 apr_status_t status;
4501 /* XXX if/when somebody writes a content-md5 filter we either need to
4502 * remove this support or coordinate when to use the filter vs.
4503 * when to use this code
4504 * The current choice of when to compute the md5 here matches the 1.3
4505 * support fairly closely (unlike 1.3, we don't handle computing md5
4506 * when the charset is translated).
4508 int bld_content_md5;
4510 d = (core_dir_config *)ap_get_core_module_config(r->per_dir_config);
4511 bld_content_md5 = (d->content_md5 == AP_CONTENT_MD5_ON)
4512 && r->output_filters->frec->ftype != AP_FTYPE_RESOURCE;
4514 ap_allow_standard_methods(r, MERGE_ALLOW, M_GET, M_OPTIONS, M_POST, -1);
4516 /* If filters intend to consume the request body, they must
4517 * register an InputFilter to slurp the contents of the POST
4518 * data from the POST input stream. It no longer exists when
4519 * the output filters are invoked by the default handler.
4521 if ((errstatus = ap_discard_request_body(r)) != OK) {
4525 if (r->method_number == M_GET || r->method_number == M_POST) {
4526 if (r->finfo.filetype == APR_NOFILE) {
4527 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00128)
4528 "File does not exist: %s",
4529 apr_pstrcat(r->pool, r->filename, r->path_info, NULL));
4530 return HTTP_NOT_FOUND;
4533 /* Don't try to serve a dir. Some OSs do weird things with
4536 if (r->finfo.filetype == APR_DIR) {
4537 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00129)
4538 "Attempt to serve directory: %s", r->filename);
4539 return HTTP_NOT_FOUND;
4542 if ((r->used_path_info != AP_REQ_ACCEPT_PATH_INFO) &&
4543 r->path_info && *r->path_info)
4545 /* default to reject */
4546 ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(00130)
4547 "File does not exist: %s",
4548 apr_pstrcat(r->pool, r->filename, r->path_info, NULL));
4549 return HTTP_NOT_FOUND;
4552 /* We understood the (non-GET) method, but it might not be legal for
4553 this particular resource. Check to see if the 'deliver_script'
4554 flag is set. If so, then we go ahead and deliver the file since
4555 it isn't really content (only GET normally returns content).
4557 Note: based on logic further above, the only possible non-GET
4558 method at this point is POST. In the future, we should enable
4559 script delivery for all methods. */
4560 if (r->method_number != M_GET) {
4561 core_request_config *req_cfg;
4563 req_cfg = ap_get_core_module_config(r->request_config);
4564 if (!req_cfg->deliver_script) {
4565 /* The flag hasn't been set for this request. Punt. */
4566 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00131)
4567 "This resource does not accept the %s method.",
4569 return HTTP_METHOD_NOT_ALLOWED;
4574 if ((status = apr_file_open(&fd, r->filename, APR_READ | APR_BINARY
4575 #if APR_HAS_SENDFILE
4576 | AP_SENDFILE_ENABLED(d->enable_sendfile)
4578 , 0, r->pool)) != APR_SUCCESS) {
4579 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r, APLOGNO(00132)
4580 "file permissions deny server access: %s", r->filename);
4581 return HTTP_FORBIDDEN;
4584 ap_update_mtime(r, r->finfo.mtime);
4585 ap_set_last_modified(r);
4587 ap_set_accept_ranges(r);
4588 ap_set_content_length(r, r->finfo.size);
4589 if (bld_content_md5) {
4590 apr_table_setn(r->headers_out, "Content-MD5",
4591 ap_md5digest(r->pool, fd));
4594 bb = apr_brigade_create(r->pool, c->bucket_alloc);
4596 if ((errstatus = ap_meets_conditions(r)) != OK) {
4598 r->status = errstatus;
4601 e = apr_brigade_insert_file(bb, fd, 0, r->finfo.size, r->pool);
4604 if (d->enable_mmap == ENABLE_MMAP_OFF) {
4605 (void)apr_bucket_file_enable_mmap(e, 0);
4610 e = apr_bucket_eos_create(c->bucket_alloc);
4611 APR_BRIGADE_INSERT_TAIL(bb, e);
4613 status = ap_pass_brigade(r->output_filters, bb);
4614 if (status == APR_SUCCESS
4615 || r->status != HTTP_OK
4620 /* no way to know what type of error occurred */
4621 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, status, r, APLOGNO(00133)
4622 "default_handler: ap_pass_brigade returned %i",
4624 return AP_FILTER_ERROR;
4627 else { /* unusual method (not GET or POST) */
4628 if (r->method_number == M_INVALID) {
4629 /* See if this looks like an undecrypted SSL handshake attempt.
4630 * It's safe to look a couple bytes into the_request if it exists, as it's
4631 * always allocated at least MIN_LINE_ALLOC (80) bytes.
4634 && r->the_request[0] == 0x16
4635 && (r->the_request[1] == 0x2 || r->the_request[1] == 0x3)) {
4636 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00134)
4637 "Invalid method in request %s - possible attempt to establish SSL connection on non-SSL port", r->the_request);
4639 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00135)
4640 "Invalid method in request %s", r->the_request);
4642 return HTTP_NOT_IMPLEMENTED;
4645 if (r->method_number == M_OPTIONS) {
4646 return ap_send_http_options(r);
4648 return HTTP_METHOD_NOT_ALLOWED;
4652 /* Optional function coming from mod_logio, used for logging of output
4655 APR_OPTIONAL_FN_TYPE(ap_logio_add_bytes_out) *ap__logio_add_bytes_out;
4656 APR_OPTIONAL_FN_TYPE(authz_some_auth_required) *ap__authz_ap_some_auth_required;
4658 /* Insist that at least one module will undertake to provide system
4659 * security by dropping startup privileges.
4661 static int sys_privileges = 0;
4662 AP_DECLARE(int) ap_sys_privileges_handlers(int inc)
4664 sys_privileges += inc;
4665 return sys_privileges;
4668 static int check_errorlog_dir(apr_pool_t *p, server_rec *s)
4670 if (!s->error_fname || s->error_fname[0] == '|'
4671 || strcmp(s->error_fname, "syslog") == 0) {
4675 char *abs = ap_server_root_relative(p, s->error_fname);
4676 char *dir = ap_make_dirstr_parent(p, abs);
4678 apr_status_t rv = apr_stat(&finfo, dir, APR_FINFO_TYPE, p);
4679 if (rv == APR_SUCCESS && finfo.filetype != APR_DIR)
4681 if (rv != APR_SUCCESS) {
4682 const char *desc = "main error log";
4684 desc = apr_psprintf(p, "error log of vhost defined at %s:%d",
4685 s->defn_name, s->defn_line_number);
4686 ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_EMERG, rv,
4687 ap_server_conf, APLOGNO(02291)
4688 "Cannot access directory '%s' for %s", dir, desc);
4695 static int core_check_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
4699 if (check_errorlog_dir(ptemp, s) != OK)
4707 static int core_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
4709 ap_mutex_init(pconf);
4711 if (!saved_server_config_defines)
4712 init_config_defines(pconf);
4713 apr_pool_cleanup_register(pconf, NULL, reset_config_defines,
4714 apr_pool_cleanup_null);
4716 mpm_common_pre_config(pconf);
4721 static int core_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
4723 ap__logio_add_bytes_out = APR_RETRIEVE_OPTIONAL_FN(ap_logio_add_bytes_out);
4724 ident_lookup = APR_RETRIEVE_OPTIONAL_FN(ap_ident_lookup);
4725 ap__authz_ap_some_auth_required = APR_RETRIEVE_OPTIONAL_FN(authz_some_auth_required);
4726 authn_ap_auth_type = APR_RETRIEVE_OPTIONAL_FN(authn_ap_auth_type);
4727 authn_ap_auth_name = APR_RETRIEVE_OPTIONAL_FN(authn_ap_auth_name);
4728 access_compat_ap_satisfies = APR_RETRIEVE_OPTIONAL_FN(access_compat_ap_satisfies);
4731 ap_setup_make_content_type(pconf);
4732 ap_setup_auth_internal(ptemp);
4733 if (!sys_privileges) {
4734 ap_log_error(APLOG_MARK, APLOG_CRIT, 0, NULL, APLOGNO(00136)
4735 "Server MUST relinquish startup privileges before "
4736 "accepting connections. Please ensure mod_unixd "
4737 "or other system security module is loaded.");
4740 apr_pool_cleanup_register(pconf, NULL, ap_mpm_end_gen_helper,
4741 apr_pool_cleanup_null);
4745 static void core_insert_filter(request_rec *r)
4747 core_dir_config *conf = (core_dir_config *)
4748 ap_get_core_module_config(r->per_dir_config);
4749 const char *filter, *filters = conf->output_filters;
4752 while (*filters && (filter = ap_getword(r->pool, &filters, ';'))) {
4753 ap_add_output_filter(filter, NULL, r, r->connection);
4757 filters = conf->input_filters;
4759 while (*filters && (filter = ap_getword(r->pool, &filters, ';'))) {
4760 ap_add_input_filter(filter, NULL, r, r->connection);
4765 static apr_size_t num_request_notes = AP_NUM_STD_NOTES;
4767 static apr_status_t reset_request_notes(void *dummy)
4769 num_request_notes = AP_NUM_STD_NOTES;
4773 AP_DECLARE(apr_size_t) ap_register_request_note(void)
4775 apr_pool_cleanup_register(apr_hook_global_pool, NULL, reset_request_notes,
4776 apr_pool_cleanup_null);
4777 return num_request_notes++;
4780 AP_DECLARE(void **) ap_get_request_note(request_rec *r, apr_size_t note_num)
4782 core_request_config *req_cfg;
4784 if (note_num >= num_request_notes) {
4788 req_cfg = (core_request_config *)
4789 ap_get_core_module_config(r->request_config);
4795 return &(req_cfg->notes[note_num]);
4798 AP_DECLARE(apr_socket_t *) ap_get_conn_socket(conn_rec *c)
4800 return ap_get_core_module_config(c->conn_config);
4803 static int core_create_req(request_rec *r)
4805 /* Alloc the config struct and the array of request notes in
4806 * a single block for efficiency
4808 core_request_config *req_cfg;
4810 req_cfg = apr_pcalloc(r->pool, sizeof(core_request_config) +
4811 sizeof(void *) * num_request_notes);
4812 req_cfg->notes = (void **)((char *)req_cfg + sizeof(core_request_config));
4814 /* ### temporarily enable script delivery as the default */
4815 req_cfg->deliver_script = 1;
4818 core_request_config *main_req_cfg = (core_request_config *)
4819 ap_get_core_module_config(r->main->request_config);
4820 req_cfg->bb = main_req_cfg->bb;
4823 req_cfg->bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
4826 ap_set_core_module_config(r->request_config, req_cfg);
4831 static int core_create_proxy_req(request_rec *r, request_rec *pr)
4833 return core_create_req(pr);
4836 static conn_rec *core_create_conn(apr_pool_t *ptrans, server_rec *server,
4837 apr_socket_t *csd, long id, void *sbh,
4838 apr_bucket_alloc_t *alloc)
4841 conn_rec *c = (conn_rec *) apr_pcalloc(ptrans, sizeof(conn_rec));
4844 (void)ap_update_child_status(c->sbh, SERVER_BUSY_READ, (request_rec *)NULL);
4846 /* Got a connection structure, so initialize what fields we can
4847 * (the rest are zeroed out by pcalloc).
4849 c->conn_config = ap_create_conn_config(ptrans);
4850 c->notes = apr_table_make(ptrans, 5);
4853 if ((rv = apr_socket_addr_get(&c->local_addr, APR_LOCAL, csd))
4855 ap_log_error(APLOG_MARK, APLOG_INFO, rv, server, APLOGNO(00137)
4856 "apr_socket_addr_get(APR_LOCAL)");
4857 apr_socket_close(csd);
4861 apr_sockaddr_ip_get(&c->local_ip, c->local_addr);
4862 if ((rv = apr_socket_addr_get(&c->client_addr, APR_REMOTE, csd))
4864 ap_log_error(APLOG_MARK, APLOG_INFO, rv, server, APLOGNO(00138)
4865 "apr_socket_addr_get(APR_REMOTE)");
4866 apr_socket_close(csd);
4870 apr_sockaddr_ip_get(&c->client_ip, c->client_addr);
4871 c->base_server = server;
4874 c->bucket_alloc = alloc;
4876 c->clogging_input_filters = 0;
4881 static int core_pre_connection(conn_rec *c, void *csd)
4883 core_net_rec *net = apr_palloc(c->pool, sizeof(*net));
4886 /* The Nagle algorithm says that we should delay sending partial
4887 * packets in hopes of getting more data. We don't want to do
4888 * this; we are not telnet. There are bad interactions between
4889 * persistent connections and Nagle's algorithm that have very severe
4890 * performance penalties. (Failing to disable Nagle is not much of a
4891 * problem with simple HTTP.)
4893 rv = apr_socket_opt_set(csd, APR_TCP_NODELAY, 1);
4894 if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
4895 /* expected cause is that the client disconnected already,
4896 * hence the debug level
4898 ap_log_cerror(APLOG_MARK, APLOG_DEBUG, rv, c, APLOGNO(00139)
4899 "apr_socket_opt_set(APR_TCP_NODELAY)");
4902 /* The core filter requires the timeout mode to be set, which
4903 * incidentally sets the socket to be nonblocking. If this
4904 * is not initialized correctly, Linux - for example - will
4905 * be initially blocking, while Solaris will be non blocking
4906 * and any initial read will fail.
4908 rv = apr_socket_timeout_set(csd, c->base_server->timeout);
4909 if (rv != APR_SUCCESS) {
4910 /* expected cause is that the client disconnected already */
4911 ap_log_cerror(APLOG_MARK, APLOG_DEBUG, rv, c, APLOGNO(00140)
4912 "apr_socket_timeout_set");
4917 net->out_ctx = NULL;
4918 net->client_socket = csd;
4920 ap_set_core_module_config(net->c->conn_config, csd);
4921 ap_add_input_filter_handle(ap_core_input_filter_handle, net, NULL, net->c);
4922 ap_add_output_filter_handle(ap_core_output_filter_handle, net, NULL, net->c);
4926 AP_DECLARE(int) ap_state_query(int query)
4929 case AP_SQ_MAIN_STATE:
4930 return ap_main_state;
4931 case AP_SQ_RUN_MODE:
4933 case AP_SQ_CONFIG_GEN:
4934 return ap_config_generation;
4936 return AP_SQ_NOT_SUPPORTED;
4940 static apr_random_t *rng = NULL;
4942 static apr_thread_mutex_t *rng_mutex = NULL;
4945 static void core_child_init(apr_pool_t *pchild, server_rec *s)
4950 if (ap_mpm_query(AP_MPMQ_IS_THREADED, &threaded_mpm) == APR_SUCCESS
4953 apr_thread_mutex_create(&rng_mutex, APR_THREAD_MUTEX_DEFAULT, pchild);
4956 /* The MPMs use plain fork() and not apr_proc_fork(), so we have to call
4957 * apr_random_after_fork() manually in the child
4959 proc.pid = getpid();
4960 apr_random_after_fork(&proc);
4963 static void core_optional_fn_retrieve(void)
4965 ap_init_scoreboard(NULL);
4968 AP_CORE_DECLARE(void) ap_random_parent_after_fork(void)
4971 * To ensure that the RNG state in the parent changes after the fork, we
4972 * pull some data from the RNG and discard it. This ensures that the RNG
4973 * states in the children are different even after the pid wraps around.
4974 * As we only use apr_random for insecure random bytes, pulling 2 bytes
4976 * XXX: APR should probably have some dedicated API to do this, but it
4977 * XXX: currently doesn't.
4980 apr_random_insecure_bytes(rng, &data, sizeof(data));
4983 AP_CORE_DECLARE(void) ap_init_rng(apr_pool_t *p)
4985 unsigned char seed[8];
4987 rng = apr_random_standard_new(p);
4989 rv = apr_generate_random_bytes(seed, sizeof(seed));
4990 if (rv != APR_SUCCESS)
4992 apr_random_add_entropy(rng, seed, sizeof(seed));
4993 rv = apr_random_insecure_ready(rng);
4994 } while (rv == APR_ENOTENOUGHENTROPY);
4995 if (rv == APR_SUCCESS)
4998 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, APLOGNO(00141)
4999 "Could not initialize random number generator");
5003 AP_DECLARE(void) ap_random_insecure_bytes(void *buf, apr_size_t size)
5007 apr_thread_mutex_lock(rng_mutex);
5009 /* apr_random_insecure_bytes can only fail with APR_ENOTENOUGHENTROPY,
5010 * and we have ruled that out during initialization. Therefore we don't
5011 * need to check the return code.
5013 apr_random_insecure_bytes(rng, buf, size);
5016 apr_thread_mutex_unlock(rng_mutex);
5021 * Finding a random number in a range.
5022 * n' = a + n(b-a+1)/(M+1)
5024 * n' = random number in range
5025 * a = low end of range
5026 * b = high end of range
5027 * n = random number of 0..M
5029 * Algorithm 'borrowed' from PHP's rand() function.
5031 #define RAND_RANGE(__n, __min, __max, __tmax) \
5032 (__n) = (__min) + (long) ((double) ((__max) - (__min) + 1.0) * ((__n) / ((__tmax) + 1.0)))
5033 AP_DECLARE(apr_uint32_t) ap_random_pick(apr_uint32_t min, apr_uint32_t max)
5035 apr_uint32_t number;
5036 #if (!__GNUC__ || __GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) || \
5037 !__sparc__ || APR_SIZEOF_VOIDP != 8)
5038 /* This triggers a gcc bug on sparc/64bit with gcc < 4.8, PR 52900 */
5041 ap_random_insecure_bytes(&num16, sizeof(num16));
5042 RAND_RANGE(num16, min, max, APR_UINT16_MAX);
5048 ap_random_insecure_bytes(&number, sizeof(number));
5049 RAND_RANGE(number, min, max, APR_UINT32_MAX);
5054 static apr_status_t core_insert_network_bucket(conn_rec *c,
5055 apr_bucket_brigade *bb,
5056 apr_socket_t *socket)
5058 apr_bucket *e = apr_bucket_socket_create(socket, c->bucket_alloc);
5059 APR_BRIGADE_INSERT_TAIL(bb, e);
5063 static apr_status_t core_dirwalk_stat(apr_finfo_t *finfo, request_rec *r,
5066 return apr_stat(finfo, r->filename, wanted, r->pool);
5069 static void core_dump_config(apr_pool_t *p, server_rec *s)
5071 core_server_config *sconf = ap_get_core_module_config(s->module_config);
5072 apr_file_t *out = NULL;
5074 const char **defines;
5076 if (!ap_exists_config_define("DUMP_RUN_CFG"))
5079 apr_file_open_stdout(&out, p);
5080 apr_file_printf(out, "ServerRoot: \"%s\"\n", ap_server_root);
5081 tmp = ap_server_root_relative(p, sconf->ap_document_root);
5082 apr_file_printf(out, "Main DocumentRoot: \"%s\"\n", tmp);
5083 if (s->error_fname[0] != '|' && strcmp(s->error_fname, "syslog") != 0)
5084 tmp = ap_server_root_relative(p, s->error_fname);
5086 tmp = s->error_fname;
5087 apr_file_printf(out, "Main ErrorLog: \"%s\"\n", tmp);
5088 if (ap_scoreboard_fname) {
5089 tmp = ap_server_root_relative(p, ap_scoreboard_fname);
5090 apr_file_printf(out, "ScoreBoardFile: \"%s\"\n", tmp);
5092 ap_dump_mutexes(p, s, out);
5093 ap_mpm_dump_pidfile(p, out);
5095 defines = (const char **)ap_server_config_defines->elts;
5096 for (i = 0; i < ap_server_config_defines->nelts; i++) {
5097 const char *name = defines[i];
5098 const char *val = NULL;
5099 if (server_config_defined_vars)
5100 val = apr_table_get(server_config_defined_vars, name);
5102 apr_file_printf(out, "Define: %s=%s\n", name, val);
5104 apr_file_printf(out, "Define: %s\n", name);
5108 static int core_upgrade_handler(request_rec *r)
5110 conn_rec *c = r->connection;
5111 const char *upgrade;
5114 /* Not possible to perform an HTTP/1.1 upgrade from a slave
5119 upgrade = apr_table_get(r->headers_in, "Upgrade");
5120 if (upgrade && *upgrade) {
5121 const char *conn = apr_table_get(r->headers_in, "Connection");
5122 if (ap_find_token(r->pool, conn, "upgrade")) {
5123 apr_array_header_t *offers = NULL;
5126 err = ap_parse_token_list_strict(r->pool, upgrade, &offers, 0);
5128 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02910)
5129 "parsing Upgrade header: %s", err);
5133 if (offers && offers->nelts > 0) {
5134 const char *protocol = ap_select_protocol(c, r, NULL, offers);
5135 if (protocol && strcmp(protocol, ap_get_protocol(c))) {
5136 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(02909)
5137 "Upgrade selects '%s'", protocol);
5138 /* Let the client know what we are upgrading to. */
5139 apr_table_clear(r->headers_out);
5140 apr_table_setn(r->headers_out, "Upgrade", protocol);
5141 apr_table_setn(r->headers_out, "Connection", "Upgrade");
5143 r->status = HTTP_SWITCHING_PROTOCOLS;
5144 r->status_line = ap_get_status_line(r->status);
5145 ap_send_interim_response(r, 1);
5147 ap_switch_protocol(c, r, r->server, protocol);
5149 /* make sure httpd closes the connection after this */
5150 c->keepalive = AP_CONN_CLOSE;
5156 else if (!c->keepalives) {
5157 /* first request on a master connection, if we have protocols other
5158 * than the current one enabled here, announce them to the
5159 * client. If the client is already talking a protocol with requests
5160 * on slave connections, leave it be. */
5161 const apr_array_header_t *upgrades;
5162 ap_get_protocol_upgrades(c, r, NULL, 0, &upgrades);
5163 if (upgrades && upgrades->nelts > 0) {
5164 char *protocols = apr_array_pstrcat(r->pool, upgrades, ',');
5165 apr_table_setn(r->headers_out, "Upgrade", protocols);
5166 apr_table_setn(r->headers_out, "Connection", "Upgrade");
5173 static int core_upgrade_storage(request_rec *r)
5175 if ((r->method_number == M_OPTIONS) && r->uri && (r->uri[0] == '*') &&
5176 (r->uri[1] == '\0')) {
5177 return core_upgrade_handler(r);
5182 static void register_hooks(apr_pool_t *p)
5184 errorlog_hash = apr_hash_make(p);
5185 ap_register_log_hooks(p);
5186 ap_register_config_hooks(p);
5189 /* create_connection and pre_connection should always be hooked
5190 * APR_HOOK_REALLY_LAST by core to give other modules the opportunity
5191 * to install alternate network transports and stop other functions
5194 ap_hook_create_connection(core_create_conn, NULL, NULL,
5195 APR_HOOK_REALLY_LAST);
5196 ap_hook_pre_connection(core_pre_connection, NULL, NULL,
5197 APR_HOOK_REALLY_LAST);
5199 ap_hook_pre_config(core_pre_config, NULL, NULL, APR_HOOK_REALLY_FIRST);
5200 ap_hook_post_config(core_post_config,NULL,NULL,APR_HOOK_REALLY_FIRST);
5201 ap_hook_check_config(core_check_config,NULL,NULL,APR_HOOK_FIRST);
5202 ap_hook_test_config(core_dump_config,NULL,NULL,APR_HOOK_FIRST);
5203 ap_hook_translate_name(ap_core_translate,NULL,NULL,APR_HOOK_REALLY_LAST);
5204 ap_hook_map_to_storage(core_upgrade_storage,NULL,NULL,APR_HOOK_REALLY_FIRST);
5205 ap_hook_map_to_storage(core_map_to_storage,NULL,NULL,APR_HOOK_REALLY_LAST);
5206 ap_hook_open_logs(ap_open_logs,NULL,NULL,APR_HOOK_REALLY_FIRST);
5207 ap_hook_child_init(core_child_init,NULL,NULL,APR_HOOK_REALLY_FIRST);
5208 ap_hook_child_init(ap_logs_child_init,NULL,NULL,APR_HOOK_MIDDLE);
5209 ap_hook_handler(core_upgrade_handler,NULL,NULL,APR_HOOK_REALLY_FIRST);
5210 ap_hook_handler(default_handler,NULL,NULL,APR_HOOK_REALLY_LAST);
5211 /* FIXME: I suspect we can eliminate the need for these do_nothings - Ben */
5212 ap_hook_type_checker(do_nothing,NULL,NULL,APR_HOOK_REALLY_LAST);
5213 ap_hook_fixups(core_override_type,NULL,NULL,APR_HOOK_REALLY_FIRST);
5214 ap_hook_create_request(core_create_req, NULL, NULL, APR_HOOK_MIDDLE);
5215 APR_OPTIONAL_HOOK(proxy, create_req, core_create_proxy_req, NULL, NULL,
5217 ap_hook_pre_mpm(ap_create_scoreboard, NULL, NULL, APR_HOOK_MIDDLE);
5218 ap_hook_child_status(ap_core_child_status, NULL, NULL, APR_HOOK_MIDDLE);
5219 ap_hook_insert_network_bucket(core_insert_network_bucket, NULL, NULL,
5220 APR_HOOK_REALLY_LAST);
5221 ap_hook_dirwalk_stat(core_dirwalk_stat, NULL, NULL, APR_HOOK_REALLY_LAST);
5222 ap_hook_open_htaccess(ap_open_htaccess, NULL, NULL, APR_HOOK_REALLY_LAST);
5223 ap_hook_optional_fn_retrieve(core_optional_fn_retrieve, NULL, NULL,
5226 /* register the core's insert_filter hook and register core-provided
5229 ap_hook_insert_filter(core_insert_filter, NULL, NULL, APR_HOOK_MIDDLE);
5231 ap_core_input_filter_handle =
5232 ap_register_input_filter("CORE_IN", ap_core_input_filter,
5233 NULL, AP_FTYPE_NETWORK);
5234 ap_content_length_filter_handle =
5235 ap_register_output_filter("CONTENT_LENGTH", ap_content_length_filter,
5236 NULL, AP_FTYPE_PROTOCOL);
5237 ap_core_output_filter_handle =
5238 ap_register_output_filter("CORE", ap_core_output_filter,
5239 NULL, AP_FTYPE_NETWORK);
5240 ap_subreq_core_filter_handle =
5241 ap_register_output_filter("SUBREQ_CORE", ap_sub_req_output_filter,
5242 NULL, AP_FTYPE_CONTENT_SET);
5244 ap_register_output_filter("OLD_WRITE", ap_old_write_filter,
5245 NULL, AP_FTYPE_RESOURCE - 10);
5248 AP_DECLARE_MODULE(core) = {
5250 AP_PLATFORM_REWRITE_ARGS_HOOK, /* hook to run before apache parses args */
5251 create_core_dir_config, /* create per-directory config structure */
5252 merge_core_dir_configs, /* merge per-directory config structures */
5253 create_core_server_config, /* create per-server config structure */
5254 merge_core_server_configs, /* merge per-server config structures */
5255 core_cmds, /* command apr_table_t */
5256 register_hooks /* register hooks */