1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000-2003 The Apache Software Foundation. All rights
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
19 * 3. The end-user documentation included with the redistribution,
20 * if any, must include the following acknowledgment:
21 * "This product includes software developed by the
22 * Apache Software Foundation (http://www.apache.org/)."
23 * Alternately, this acknowledgment may appear in the software itself,
24 * if and wherever such third-party acknowledgments normally appear.
26 * 4. The names "Apache" and "Apache Software Foundation" must
27 * not be used to endorse or promote products derived from this
28 * software without prior written permission. For written
29 * permission, please contact apache@apache.org.
31 * 5. Products derived from this software may not be called "Apache",
32 * nor may "Apache" appear in their name, without prior written
33 * permission of the Apache Software Foundation.
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation. For more
51 * information on the Apache Software Foundation, please see
52 * <http://www.apache.org/>.
54 * Portions of this software are based upon public domain software
55 * originally written at the National Center for Supercomputing Applications,
56 * University of Illinois, Urbana-Champaign.
60 #include "apr_strings.h"
62 #include "apr_fnmatch.h"
64 #include "apr_thread_proc.h" /* for RLIMIT stuff */
65 #include "apr_hooks.h"
67 #define APR_WANT_IOVEC
68 #define APR_WANT_STRFUNC
69 #define APR_WANT_MEMFUNC
73 #include "ap_config.h"
75 #include "http_config.h"
76 #include "http_core.h"
77 #include "http_protocol.h" /* For index_of_response(). Grump. */
78 #include "http_request.h"
79 #include "http_vhost.h"
80 #include "http_main.h" /* For the default_handler below... */
83 #include "http_connection.h"
84 #include "apr_buckets.h"
85 #include "util_filter.h"
86 #include "util_ebcdic.h"
88 #include "mpm_common.h"
89 #include "scoreboard.h"
91 #include "mod_proxy.h"
92 #include "ap_listen.h"
94 /* LimitXMLRequestBody handling */
95 #define AP_LIMIT_UNSET ((long) -1)
96 #define AP_DEFAULT_LIMIT_XML_BODY ((size_t)1000000)
98 #define AP_MIN_SENDFILE_BYTES (256)
101 APR_HOOK_LINK(get_mgmt_items)
104 AP_IMPLEMENT_HOOK_RUN_ALL(int, get_mgmt_items,
105 (apr_pool_t *p, const char *val, apr_hash_t *ht),
106 (p, val, ht), OK, DECLINED)
108 /* Server core module... This module provides support for really basic
109 * server operations, including options and commands which control the
110 * operation of other modules. Consider this the bureaucracy module.
112 * The core module also defines handlers, etc., do handle just enough
113 * to allow a server with the core module ONLY to actually serve documents
114 * (though it slaps DefaultType on all of 'em); this was useful in testing,
115 * but may not be worth preserving.
117 * This file could almost be mod_core.c, except for the stuff which affects
118 * the http_conf_globals.
121 /* Handles for core filters */
122 AP_DECLARE_DATA ap_filter_rec_t *ap_subreq_core_filter_handle;
123 AP_DECLARE_DATA ap_filter_rec_t *ap_core_output_filter_handle;
124 AP_DECLARE_DATA ap_filter_rec_t *ap_content_length_filter_handle;
125 AP_DECLARE_DATA ap_filter_rec_t *ap_net_time_filter_handle;
126 AP_DECLARE_DATA ap_filter_rec_t *ap_core_input_filter_handle;
128 static void *create_core_dir_config(apr_pool_t *a, char *dir)
130 core_dir_config *conf;
132 conf = (core_dir_config *)apr_pcalloc(a, sizeof(core_dir_config));
134 /* conf->r and conf->d[_*] are initialized by dirsection() or left NULL */
136 conf->opts = dir ? OPT_UNSET : OPT_UNSET|OPT_ALL;
137 conf->opts_add = conf->opts_remove = OPT_NONE;
138 conf->override = dir ? OR_UNSET : OR_UNSET|OR_ALL;
140 conf->content_md5 = 2;
141 conf->accept_path_info = 3;
143 conf->use_canonical_name = USE_CANONICAL_NAME_UNSET;
145 conf->hostname_lookups = HOSTNAME_LOOKUP_UNSET;
146 conf->satisfy = SATISFY_NOSPEC;
149 conf->limit_cpu = NULL;
151 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
152 conf->limit_mem = NULL;
155 conf->limit_nproc = NULL;
158 conf->limit_req_body = 0;
159 conf->limit_xml_body = AP_LIMIT_UNSET;
160 conf->sec_file = apr_array_make(a, 2, sizeof(ap_conf_vector_t *));
162 conf->server_signature = srv_sig_unset;
164 conf->add_default_charset = ADD_DEFAULT_CHARSET_UNSET;
165 conf->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
167 /* Overriding all negotiation
169 conf->mime_type = NULL;
170 conf->handler = NULL;
171 conf->output_filters = NULL;
172 conf->input_filters = NULL;
175 * Flag for use of inodes in ETags.
177 conf->etag_bits = ETAG_UNSET;
178 conf->etag_add = ETAG_UNSET;
179 conf->etag_remove = ETAG_UNSET;
181 conf->enable_mmap = ENABLE_MMAP_UNSET;
182 conf->enable_sendfile = ENABLE_SENDFILE_UNSET;
183 conf->allow_encoded_slashes = 0;
189 * Overlay one hash table of ct_output_filters onto another
191 static void *merge_ct_filters(apr_pool_t *p,
194 const void *overlay_val,
195 const void *base_val,
198 ap_filter_rec_t *cur;
199 const ap_filter_rec_t *overlay_info = (const ap_filter_rec_t *)overlay_val;
200 const ap_filter_rec_t *base_info = (const ap_filter_rec_t *)base_val;
204 while (overlay_info) {
205 ap_filter_rec_t *new;
207 new = apr_pcalloc(p, sizeof(ap_filter_rec_t));
208 new->name = apr_pstrdup(p, overlay_info->name);
211 overlay_info = overlay_info->next;
218 /* We can't have dups. */
221 if (!strcasecmp(base_info->name, f->name)) {
230 f = apr_pcalloc(p, sizeof(ap_filter_rec_t));
231 f->name = apr_pstrdup(p, base_info->name);
236 base_info = base_info->next;
242 static void *merge_core_dir_configs(apr_pool_t *a, void *basev, void *newv)
244 core_dir_config *base = (core_dir_config *)basev;
245 core_dir_config *new = (core_dir_config *)newv;
246 core_dir_config *conf;
249 /* Create this conf by duplicating the base, replacing elements
250 * (or creating copies for merging) where new-> values exist.
252 conf = (core_dir_config *)apr_palloc(a, sizeof(core_dir_config));
253 memcpy(conf, base, sizeof(core_dir_config));
256 conf->d_is_fnmatch = new->d_is_fnmatch;
257 conf->d_components = new->d_components;
260 if (new->opts & OPT_UNSET) {
261 /* there was no explicit setting of new->opts, so we merge
262 * preserve the invariant (opts_add & opts_remove) == 0
264 conf->opts_add = (conf->opts_add & ~new->opts_remove) | new->opts_add;
265 conf->opts_remove = (conf->opts_remove & ~new->opts_add)
267 conf->opts = (conf->opts & ~conf->opts_remove) | conf->opts_add;
268 if ((base->opts & OPT_INCNOEXEC) && (new->opts & OPT_INCLUDES)) {
269 conf->opts = (conf->opts & ~OPT_INCNOEXEC) | OPT_INCLUDES;
273 /* otherwise we just copy, because an explicit opts setting
274 * overrides all earlier +/- modifiers
276 conf->opts = new->opts;
277 conf->opts_add = new->opts_add;
278 conf->opts_remove = new->opts_remove;
281 if (!(new->override & OR_UNSET)) {
282 conf->override = new->override;
285 if (new->ap_default_type) {
286 conf->ap_default_type = new->ap_default_type;
289 if (new->ap_auth_type) {
290 conf->ap_auth_type = new->ap_auth_type;
293 if (new->ap_auth_name) {
294 conf->ap_auth_name = new->ap_auth_name;
297 if (new->ap_requires) {
298 conf->ap_requires = new->ap_requires;
301 if (conf->response_code_strings == NULL) {
302 conf->response_code_strings = new->response_code_strings;
304 else if (new->response_code_strings != NULL) {
305 /* If we merge, the merge-result must have it's own array
307 conf->response_code_strings = apr_palloc(a,
308 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
309 memcpy(conf->response_code_strings, base->response_code_strings,
310 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
312 for (i = 0; i < RESPONSE_CODES; ++i) {
313 if (new->response_code_strings[i] != NULL) {
314 conf->response_code_strings[i] = new->response_code_strings[i];
318 /* Otherwise we simply use the base->response_code_strings array
321 if (new->hostname_lookups != HOSTNAME_LOOKUP_UNSET) {
322 conf->hostname_lookups = new->hostname_lookups;
325 if ((new->content_md5 & 2) == 0) {
326 conf->content_md5 = new->content_md5;
329 if (new->accept_path_info != 3) {
330 conf->accept_path_info = new->accept_path_info;
333 if (new->use_canonical_name != USE_CANONICAL_NAME_UNSET) {
334 conf->use_canonical_name = new->use_canonical_name;
338 if (new->limit_cpu) {
339 conf->limit_cpu = new->limit_cpu;
343 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
344 if (new->limit_mem) {
345 conf->limit_mem = new->limit_mem;
350 if (new->limit_nproc) {
351 conf->limit_nproc = new->limit_nproc;
355 if (new->limit_req_body) {
356 conf->limit_req_body = new->limit_req_body;
359 if (new->limit_xml_body != AP_LIMIT_UNSET)
360 conf->limit_xml_body = new->limit_xml_body;
362 conf->limit_xml_body = base->limit_xml_body;
364 if (!conf->sec_file) {
365 conf->sec_file = new->sec_file;
367 else if (new->sec_file) {
368 /* If we merge, the merge-result must have it's own array
370 conf->sec_file = apr_array_append(a, base->sec_file, new->sec_file);
372 /* Otherwise we simply use the base->sec_file array
375 if (new->satisfy != SATISFY_NOSPEC) {
376 conf->satisfy = new->satisfy;
379 if (new->server_signature != srv_sig_unset) {
380 conf->server_signature = new->server_signature;
383 if (new->add_default_charset != ADD_DEFAULT_CHARSET_UNSET) {
384 conf->add_default_charset = new->add_default_charset;
385 conf->add_default_charset_name = new->add_default_charset_name;
388 /* Overriding all negotiation
390 if (new->mime_type) {
391 conf->mime_type = new->mime_type;
395 conf->handler = new->handler;
398 if (new->output_filters) {
399 conf->output_filters = new->output_filters;
402 if (new->input_filters) {
403 conf->input_filters = new->input_filters;
406 if (conf->ct_output_filters && new->ct_output_filters) {
407 conf->ct_output_filters = apr_hash_merge(a,
408 new->ct_output_filters,
409 conf->ct_output_filters,
413 else if (new->ct_output_filters) {
414 conf->ct_output_filters = apr_hash_copy(a, new->ct_output_filters);
416 else if (conf->ct_output_filters) {
417 /* That memcpy above isn't enough. */
418 conf->ct_output_filters = apr_hash_copy(a, base->ct_output_filters);
422 * Now merge the setting of the FileETag directive.
424 if (new->etag_bits == ETAG_UNSET) {
426 (conf->etag_add & (~ new->etag_remove)) | new->etag_add;
428 (conf->opts_remove & (~ new->etag_add)) | new->etag_remove;
430 (conf->etag_bits & (~ conf->etag_remove)) | conf->etag_add;
433 conf->etag_bits = new->etag_bits;
434 conf->etag_add = new->etag_add;
435 conf->etag_remove = new->etag_remove;
438 if (conf->etag_bits != ETAG_NONE) {
439 conf->etag_bits &= (~ ETAG_NONE);
442 if (new->enable_mmap != ENABLE_MMAP_UNSET) {
443 conf->enable_mmap = new->enable_mmap;
446 if (new->enable_sendfile != ENABLE_SENDFILE_UNSET) {
447 conf->enable_sendfile = new->enable_sendfile;
450 conf->allow_encoded_slashes = new->allow_encoded_slashes;
455 static void *create_core_server_config(apr_pool_t *a, server_rec *s)
457 core_server_config *conf;
458 int is_virtual = s->is_virtual;
460 conf = (core_server_config *)apr_pcalloc(a, sizeof(core_server_config));
463 conf->gprof_dir = NULL;
466 conf->access_name = is_virtual ? NULL : DEFAULT_ACCESS_FNAME;
467 conf->ap_document_root = is_virtual ? NULL : DOCUMENT_LOCATION;
468 conf->sec_dir = apr_array_make(a, 40, sizeof(ap_conf_vector_t *));
469 conf->sec_url = apr_array_make(a, 40, sizeof(ap_conf_vector_t *));
471 /* recursion stopper */
472 conf->redirect_limit = 0; /* 0 == unset */
473 conf->subreq_limit = 0;
478 static void *merge_core_server_configs(apr_pool_t *p, void *basev, void *virtv)
480 core_server_config *base = (core_server_config *)basev;
481 core_server_config *virt = (core_server_config *)virtv;
482 core_server_config *conf;
484 conf = (core_server_config *)apr_palloc(p, sizeof(core_server_config));
485 memcpy(conf, virt, sizeof(core_server_config));
487 if (!conf->access_name) {
488 conf->access_name = base->access_name;
491 if (!conf->ap_document_root) {
492 conf->ap_document_root = base->ap_document_root;
495 conf->sec_dir = apr_array_append(p, base->sec_dir, virt->sec_dir);
496 conf->sec_url = apr_array_append(p, base->sec_url, virt->sec_url);
498 conf->redirect_limit = virt->redirect_limit
499 ? virt->redirect_limit
500 : base->redirect_limit;
502 conf->subreq_limit = virt->subreq_limit
504 : base->subreq_limit;
509 /* Add per-directory configuration entry (for <directory> section);
510 * these are part of the core server config.
513 AP_CORE_DECLARE(void) ap_add_per_dir_conf(server_rec *s, void *dir_config)
515 core_server_config *sconf = ap_get_module_config(s->module_config,
517 void **new_space = (void **)apr_array_push(sconf->sec_dir);
519 *new_space = dir_config;
522 AP_CORE_DECLARE(void) ap_add_per_url_conf(server_rec *s, void *url_config)
524 core_server_config *sconf = ap_get_module_config(s->module_config,
526 void **new_space = (void **)apr_array_push(sconf->sec_url);
528 *new_space = url_config;
531 AP_CORE_DECLARE(void) ap_add_file_conf(core_dir_config *conf, void *url_config)
533 void **new_space = (void **)apr_array_push(conf->sec_file);
535 *new_space = url_config;
538 /* We need to do a stable sort, qsort isn't stable. So to make it stable
539 * we'll be maintaining the original index into the list, and using it
540 * as the minor key during sorting. The major key is the number of
541 * components (where the root component is zero).
543 struct reorder_sort_rec {
544 ap_conf_vector_t *elt;
548 static int reorder_sorter(const void *va, const void *vb)
550 const struct reorder_sort_rec *a = va;
551 const struct reorder_sort_rec *b = vb;
552 core_dir_config *core_a;
553 core_dir_config *core_b;
555 core_a = ap_get_module_config(a->elt, &core_module);
556 core_b = ap_get_module_config(b->elt, &core_module);
558 /* a regex always sorts after a non-regex
560 if (!core_a->r && core_b->r) {
563 else if (core_a->r && !core_b->r) {
567 /* we always sort next by the number of components
569 if (core_a->d_components < core_b->d_components) {
572 else if (core_a->d_components > core_b->d_components) {
576 /* They have the same number of components, we now have to compare
577 * the minor key to maintain the original order (from the config.)
579 return a->orig_index - b->orig_index;
582 void ap_core_reorder_directories(apr_pool_t *p, server_rec *s)
584 core_server_config *sconf;
585 apr_array_header_t *sec_dir;
586 struct reorder_sort_rec *sortbin;
588 ap_conf_vector_t **elts;
592 sconf = ap_get_module_config(s->module_config, &core_module);
593 sec_dir = sconf->sec_dir;
594 nelts = sec_dir->nelts;
595 elts = (ap_conf_vector_t **)sec_dir->elts;
598 /* simple case of already being sorted... */
599 /* We're not checking this condition to be fast... we're checking
600 * it to avoid trying to palloc zero bytes, which can trigger some
601 * memory debuggers to barf
606 /* we have to allocate tmp space to do a stable sort */
607 apr_pool_create(&tmp, p);
608 sortbin = apr_palloc(tmp, sec_dir->nelts * sizeof(*sortbin));
609 for (i = 0; i < nelts; ++i) {
610 sortbin[i].orig_index = i;
611 sortbin[i].elt = elts[i];
614 qsort(sortbin, nelts, sizeof(*sortbin), reorder_sorter);
616 /* and now copy back to the original array */
617 for (i = 0; i < nelts; ++i) {
618 elts[i] = sortbin[i].elt;
621 apr_pool_destroy(tmp);
624 /*****************************************************************
626 * There are some elements of the core config structures in which
627 * other modules have a legitimate interest (this is ugly, but necessary
628 * to preserve NCSA back-compatibility). So, we have a bunch of accessors
632 AP_DECLARE(int) ap_allow_options(request_rec *r)
634 core_dir_config *conf =
635 (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
640 AP_DECLARE(int) ap_allow_overrides(request_rec *r)
642 core_dir_config *conf;
643 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
646 return conf->override;
649 AP_DECLARE(const char *) ap_auth_type(request_rec *r)
651 core_dir_config *conf;
653 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
656 return conf->ap_auth_type;
659 AP_DECLARE(const char *) ap_auth_name(request_rec *r)
661 core_dir_config *conf;
663 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
666 return conf->ap_auth_name;
669 AP_DECLARE(const char *) ap_default_type(request_rec *r)
671 core_dir_config *conf;
673 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
676 return conf->ap_default_type
677 ? conf->ap_default_type
678 : DEFAULT_CONTENT_TYPE;
681 AP_DECLARE(const char *) ap_document_root(request_rec *r) /* Don't use this! */
683 core_server_config *conf;
685 conf = (core_server_config *)ap_get_module_config(r->server->module_config,
688 return conf->ap_document_root;
691 AP_DECLARE(const apr_array_header_t *) ap_requires(request_rec *r)
693 core_dir_config *conf;
695 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
698 return conf->ap_requires;
701 AP_DECLARE(int) ap_satisfies(request_rec *r)
703 core_dir_config *conf;
705 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
708 return conf->satisfy;
711 /* Should probably just get rid of this... the only code that cares is
712 * part of the core anyway (and in fact, it isn't publicised to other
716 char *ap_response_code_string(request_rec *r, int error_index)
718 core_dir_config *conf;
720 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
723 if (conf->response_code_strings == NULL) {
727 return conf->response_code_strings[error_index];
731 /* Code from Harald Hanche-Olsen <hanche@imf.unit.no> */
732 static APR_INLINE void do_double_reverse (conn_rec *conn)
737 if (conn->double_reverse) {
742 if (conn->remote_host == NULL || conn->remote_host[0] == '\0') {
743 /* single reverse failed, so don't bother */
744 conn->double_reverse = -1;
748 rv = apr_sockaddr_info_get(&sa, conn->remote_host, APR_UNSPEC, 0, 0, conn->pool);
749 if (rv == APR_SUCCESS) {
751 if (apr_sockaddr_equal(sa, conn->remote_addr)) {
752 conn->double_reverse = 1;
760 conn->double_reverse = -1;
763 AP_DECLARE(const char *) ap_get_remote_host(conn_rec *conn, void *dir_config,
764 int type, int *str_is_ip)
766 int hostname_lookups;
768 if (str_is_ip) { /* if caller wants to know */
772 /* If we haven't checked the host name, and we want to */
775 ((core_dir_config *)ap_get_module_config(dir_config, &core_module))
778 if (hostname_lookups == HOSTNAME_LOOKUP_UNSET) {
779 hostname_lookups = HOSTNAME_LOOKUP_OFF;
784 hostname_lookups = HOSTNAME_LOOKUP_OFF;
787 if (type != REMOTE_NOLOOKUP
788 && conn->remote_host == NULL
789 && (type == REMOTE_DOUBLE_REV
790 || hostname_lookups != HOSTNAME_LOOKUP_OFF)) {
792 if (apr_getnameinfo(&conn->remote_host, conn->remote_addr, 0)
794 ap_str_tolower(conn->remote_host);
796 if (hostname_lookups == HOSTNAME_LOOKUP_DOUBLE) {
797 do_double_reverse(conn);
798 if (conn->double_reverse != 1) {
799 conn->remote_host = NULL;
804 /* if failed, set it to the NULL string to indicate error */
805 if (conn->remote_host == NULL) {
806 conn->remote_host = "";
810 if (type == REMOTE_DOUBLE_REV) {
811 do_double_reverse(conn);
812 if (conn->double_reverse == -1) {
818 * Return the desired information; either the remote DNS name, if found,
819 * or either NULL (if the hostname was requested) or the IP address
820 * (if any identifier was requested).
822 if (conn->remote_host != NULL && conn->remote_host[0] != '\0') {
823 return conn->remote_host;
826 if (type == REMOTE_HOST || type == REMOTE_DOUBLE_REV) {
830 if (str_is_ip) { /* if caller wants to know */
834 return conn->remote_ip;
840 * Optional function coming from mod_ident, used for looking up ident user
842 static APR_OPTIONAL_FN_TYPE(ap_ident_lookup) *ident_lookup;
844 AP_DECLARE(const char *) ap_get_remote_logname(request_rec *r)
846 if (r->connection->remote_logname != NULL) {
847 return r->connection->remote_logname;
851 return ident_lookup(r);
857 /* There are two options regarding what the "name" of a server is. The
858 * "canonical" name as defined by ServerName and Port, or the "client's
859 * name" as supplied by a possible Host: header or full URI. We never
860 * trust the port passed in the client's headers, we always use the
861 * port of the actual socket.
863 * The DNS option to UseCanonicalName causes this routine to do a
864 * reverse lookup on the local IP address of the connection and use
865 * that for the ServerName. This makes its value more reliable while
866 * at the same time allowing Demon's magic virtual hosting to work.
867 * The assumption is that DNS lookups are sufficiently quick...
870 AP_DECLARE(const char *) ap_get_server_name(request_rec *r)
872 conn_rec *conn = r->connection;
875 d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
878 if (d->use_canonical_name == USE_CANONICAL_NAME_OFF) {
879 return r->hostname ? r->hostname : r->server->server_hostname;
882 if (d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
883 if (conn->local_host == NULL) {
884 if (apr_getnameinfo(&conn->local_host,
885 conn->local_addr, 0) != APR_SUCCESS)
886 conn->local_host = apr_pstrdup(conn->pool,
887 r->server->server_hostname);
889 ap_str_tolower(conn->local_host);
893 return conn->local_host;
897 return r->server->server_hostname;
901 * Get the current server name from the request for the purposes
902 * of using in a URL. If the server name is an IPv6 literal
903 * address, it will be returned in URL format (e.g., "[fe80::1]").
905 static const char *get_server_name_for_url(request_rec *r)
907 const char *plain_server_name = ap_get_server_name(r);
910 if (ap_strchr_c(plain_server_name, ':')) { /* IPv6 literal? */
911 return apr_psprintf(r->pool, "[%s]", plain_server_name);
914 return plain_server_name;
917 AP_DECLARE(apr_port_t) ap_get_server_port(const request_rec *r)
921 (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
923 if (d->use_canonical_name == USE_CANONICAL_NAME_OFF
924 || d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
926 /* With UseCanonicalName off Apache will form self-referential
927 * URLs using the hostname and port supplied by the client if
928 * any are supplied (otherwise it will use the canonical name).
930 port = r->parsed_uri.port ? r->parsed_uri.port :
931 r->server->port ? r->server->port :
934 else { /* d->use_canonical_name == USE_CANONICAL_NAME_ON */
936 /* With UseCanonicalName on (and in all versions prior to 1.3)
937 * Apache will use the hostname and port specified in the
938 * ServerName directive to construct a canonical name for the
939 * server. (If no port was specified in the ServerName
940 * directive, Apache uses the port supplied by the client if
941 * any is supplied, and finally the default port for the protocol
944 port = r->server->port ? r->server->port :
945 r->connection->local_addr->port ? r->connection->local_addr->port :
953 AP_DECLARE(char *) ap_construct_url(apr_pool_t *p, const char *uri,
956 unsigned port = ap_get_server_port(r);
957 const char *host = get_server_name_for_url(r);
959 if (ap_is_default_port(port, r)) {
960 return apr_pstrcat(p, ap_http_method(r), "://", host, uri, NULL);
963 return apr_psprintf(p, "%s://%s:%u%s", ap_http_method(r), host, port, uri);
966 AP_DECLARE(apr_off_t) ap_get_limit_req_body(const request_rec *r)
969 (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
971 return d->limit_req_body;
975 /*****************************************************************
977 * Commands... this module handles almost all of the NCSA httpd.conf
978 * commands, but most of the old srm.conf is in the the modules.
982 /* returns a parent if it matches the given directive */
983 static const ap_directive_t * find_parent(const ap_directive_t *dirp,
986 while (dirp->parent != NULL) {
989 /* ### it would be nice to have atom-ized directives */
990 if (strcasecmp(dirp->directive, what) == 0)
997 AP_DECLARE(const char *) ap_check_cmd_context(cmd_parms *cmd,
1000 const char *gt = (cmd->cmd->name[0] == '<'
1001 && cmd->cmd->name[strlen(cmd->cmd->name)-1] != '>')
1003 const ap_directive_t *found;
1005 if ((forbidden & NOT_IN_VIRTUALHOST) && cmd->server->is_virtual) {
1006 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1007 " cannot occur within <VirtualHost> section", NULL);
1010 if ((forbidden & NOT_IN_LIMIT) && cmd->limited != -1) {
1011 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1012 " cannot occur within <Limit> section", NULL);
1015 if ((forbidden & NOT_IN_DIR_LOC_FILE) == NOT_IN_DIR_LOC_FILE) {
1016 if (cmd->path != NULL) {
1017 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1018 " cannot occur within <Directory/Location/Files> "
1021 if (cmd->cmd->req_override & EXEC_ON_READ) {
1022 /* EXEC_ON_READ must be NOT_IN_DIR_LOC_FILE, if not, it will
1023 * (deliberately) segfault below in the individual tests...
1029 if (((forbidden & NOT_IN_DIRECTORY)
1030 && ((found = find_parent(cmd->directive, "<Directory"))
1031 || (found = find_parent(cmd->directive, "<DirectoryMatch"))))
1032 || ((forbidden & NOT_IN_LOCATION)
1033 && ((found = find_parent(cmd->directive, "<Location"))
1034 || (found = find_parent(cmd->directive, "<LocationMatch"))))
1035 || ((forbidden & NOT_IN_FILES)
1036 && ((found = find_parent(cmd->directive, "<Files"))
1037 || (found = find_parent(cmd->directive, "<FilesMatch"))))) {
1038 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1039 " cannot occur within ", found->directive,
1046 static const char *set_access_name(cmd_parms *cmd, void *dummy,
1049 void *sconf = cmd->server->module_config;
1050 core_server_config *conf = ap_get_module_config(sconf, &core_module);
1052 const char *err = ap_check_cmd_context(cmd,
1053 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1058 conf->access_name = apr_pstrdup(cmd->pool, arg);
1063 static const char *set_gprof_dir(cmd_parms *cmd, void *dummy, const char *arg)
1065 void *sconf = cmd->server->module_config;
1066 core_server_config *conf = ap_get_module_config(sconf, &core_module);
1068 const char *err = ap_check_cmd_context(cmd,
1069 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1074 conf->gprof_dir = apr_pstrdup(cmd->pool, arg);
1079 static const char *set_add_default_charset(cmd_parms *cmd,
1080 void *d_, const char *arg)
1082 core_dir_config *d = d_;
1084 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1089 if (!strcasecmp(arg, "Off")) {
1090 d->add_default_charset = ADD_DEFAULT_CHARSET_OFF;
1092 else if (!strcasecmp(arg, "On")) {
1093 d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1094 d->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
1097 d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1098 d->add_default_charset_name = arg;
1104 static const char *set_document_root(cmd_parms *cmd, void *dummy,
1107 void *sconf = cmd->server->module_config;
1108 core_server_config *conf = ap_get_module_config(sconf, &core_module);
1110 const char *err = ap_check_cmd_context(cmd,
1111 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1116 /* Make it absolute, relative to ServerRoot */
1117 arg = ap_server_root_relative(cmd->pool, arg);
1119 /* TODO: ap_configtestonly && ap_docrootcheck && */
1120 if (apr_filepath_merge((char**)&conf->ap_document_root, NULL, arg,
1121 APR_FILEPATH_TRUENAME, cmd->pool) != APR_SUCCESS
1122 || !ap_is_directory(cmd->pool, arg)) {
1123 if (cmd->server->is_virtual) {
1124 ap_log_perror(APLOG_MARK, APLOG_STARTUP, 0,
1126 "Warning: DocumentRoot [%s] does not exist",
1128 conf->ap_document_root = arg;
1131 return "DocumentRoot must be a directory";
1137 AP_DECLARE(void) ap_custom_response(request_rec *r, int status,
1140 core_dir_config *conf =
1141 ap_get_module_config(r->per_dir_config, &core_module);
1144 if(conf->response_code_strings == NULL) {
1145 conf->response_code_strings =
1146 apr_pcalloc(r->pool,
1147 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
1150 idx = ap_index_of_response(status);
1152 conf->response_code_strings[idx] =
1153 ((ap_is_url(string) || (*string == '/')) && (*string != '"')) ?
1154 apr_pstrdup(r->pool, string) : apr_pstrcat(r->pool, "\"", string, NULL);
1157 static const char *set_error_document(cmd_parms *cmd, void *conf_,
1158 const char *errno_str, const char *msg)
1160 core_dir_config *conf = conf_;
1161 int error_number, index_number, idx500;
1162 enum { MSG, LOCAL_PATH, REMOTE_PATH } what = MSG;
1164 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1169 /* 1st parameter should be a 3 digit number, which we recognize;
1170 * convert it into an array index
1172 error_number = atoi(errno_str);
1173 idx500 = ap_index_of_response(HTTP_INTERNAL_SERVER_ERROR);
1175 if (error_number == HTTP_INTERNAL_SERVER_ERROR) {
1176 index_number = idx500;
1178 else if ((index_number = ap_index_of_response(error_number)) == idx500) {
1179 return apr_pstrcat(cmd->pool, "Unsupported HTTP response code ",
1183 /* Heuristic to determine second argument. */
1184 if (ap_strchr_c(msg,' '))
1186 else if (msg[0] == '/')
1188 else if (ap_is_url(msg))
1193 /* The entry should be ignored if it is a full URL for a 401 error */
1195 if (error_number == 401 && what == REMOTE_PATH) {
1196 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, cmd->server,
1197 "cannot use a full URL in a 401 ErrorDocument "
1198 "directive --- ignoring!");
1200 else { /* Store it... */
1201 if (conf->response_code_strings == NULL) {
1202 conf->response_code_strings =
1203 apr_pcalloc(cmd->pool,
1204 sizeof(*conf->response_code_strings) *
1208 /* hack. Prefix a " if it is a msg; as that is what
1209 * http_protocol.c relies on to distinguish between
1210 * a msg and a (local) path.
1212 conf->response_code_strings[index_number] = (what == MSG) ?
1213 apr_pstrcat(cmd->pool, "\"",msg,NULL) :
1214 apr_pstrdup(cmd->pool, msg);
1220 static const char *set_override(cmd_parms *cmd, void *d_, const char *l)
1222 core_dir_config *d = d_;
1225 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1230 /* Throw a warning if we're in <Location> or <Files> */
1231 if (ap_check_cmd_context(cmd, NOT_IN_LOCATION | NOT_IN_FILES)) {
1232 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
1233 "Useless use of AllowOverride in line %d.",
1234 cmd->directive->line_num);
1237 d->override = OR_NONE;
1239 w = ap_getword_conf(cmd->pool, &l);
1240 if (!strcasecmp(w, "Limit")) {
1241 d->override |= OR_LIMIT;
1243 else if (!strcasecmp(w, "Options")) {
1244 d->override |= OR_OPTIONS;
1246 else if (!strcasecmp(w, "FileInfo")) {
1247 d->override |= OR_FILEINFO;
1249 else if (!strcasecmp(w, "AuthConfig")) {
1250 d->override |= OR_AUTHCFG;
1252 else if (!strcasecmp(w, "Indexes")) {
1253 d->override |= OR_INDEXES;
1255 else if (!strcasecmp(w, "None")) {
1256 d->override = OR_NONE;
1258 else if (!strcasecmp(w, "All")) {
1259 d->override = OR_ALL;
1262 return apr_pstrcat(cmd->pool, "Illegal override option ", w, NULL);
1265 d->override &= ~OR_UNSET;
1271 static const char *set_options(cmd_parms *cmd, void *d_, const char *l)
1273 core_dir_config *d = d_;
1274 allow_options_t opt;
1279 char *w = ap_getword_conf(cmd->pool, &l);
1282 if (*w == '+' || *w == '-') {
1290 if (!strcasecmp(w, "Indexes")) {
1293 else if (!strcasecmp(w, "Includes")) {
1296 else if (!strcasecmp(w, "IncludesNOEXEC")) {
1297 opt = (OPT_INCLUDES | OPT_INCNOEXEC);
1299 else if (!strcasecmp(w, "FollowSymLinks")) {
1300 opt = OPT_SYM_LINKS;
1302 else if (!strcasecmp(w, "SymLinksIfOwnerMatch")) {
1303 opt = OPT_SYM_OWNER;
1305 else if (!strcasecmp(w, "execCGI")) {
1308 else if (!strcasecmp(w, "MultiViews")) {
1311 else if (!strcasecmp(w, "RunScripts")) { /* AI backcompat. Yuck */
1312 opt = OPT_MULTI|OPT_EXECCGI;
1314 else if (!strcasecmp(w, "None")) {
1317 else if (!strcasecmp(w, "All")) {
1321 return apr_pstrcat(cmd->pool, "Illegal option ", w, NULL);
1324 /* we ensure the invariant (d->opts_add & d->opts_remove) == 0 */
1325 if (action == '-') {
1326 d->opts_remove |= opt;
1327 d->opts_add &= ~opt;
1330 else if (action == '+') {
1332 d->opts_remove &= ~opt;
1344 * Note what data should be used when forming file ETag values.
1345 * It would be nicer to do this as an ITERATE, but then we couldn't
1346 * remember the +/- state properly.
1348 static const char *set_etag_bits(cmd_parms *cmd, void *mconfig,
1351 core_dir_config *cfg;
1352 etag_components_t bit;
1360 cfg = (core_dir_config *)mconfig;
1365 while (args[0] != '\0') {
1369 token = ap_getword_conf(cmd->pool, &args);
1370 if ((*token == '+') || (*token == '-')) {
1376 * The occurrence of an absolute setting wipes
1377 * out any previous relative ones. The first such
1378 * occurrence forgets any inherited ones, too.
1381 cfg->etag_bits = ETAG_UNSET;
1382 cfg->etag_add = ETAG_UNSET;
1383 cfg->etag_remove = ETAG_UNSET;
1388 if (strcasecmp(token, "None") == 0) {
1389 if (action != '*') {
1393 cfg->etag_bits = bit = ETAG_NONE;
1397 else if (strcasecmp(token, "All") == 0) {
1398 if (action != '*') {
1403 cfg->etag_bits = bit = ETAG_ALL;
1406 else if (strcasecmp(token, "Size") == 0) {
1409 else if ((strcasecmp(token, "LMTime") == 0)
1410 || (strcasecmp(token, "MTime") == 0)
1411 || (strcasecmp(token, "LastModified") == 0)) {
1414 else if (strcasecmp(token, "INode") == 0) {
1418 return apr_pstrcat(cmd->pool, "Unknown keyword '",
1419 token, "' for ", cmd->cmd->name,
1420 " directive", NULL);
1424 return apr_pstrcat(cmd->pool, cmd->cmd->name, " keyword '",
1425 token, "' cannot be used with '+' or '-'",
1429 if (action == '+') {
1431 * Make sure it's in the 'add' list and absent from the
1434 cfg->etag_add |= bit;
1435 cfg->etag_remove &= (~ bit);
1437 else if (action == '-') {
1438 cfg->etag_remove |= bit;
1439 cfg->etag_add &= (~ bit);
1443 * Non-relative values wipe out any + or - values
1444 * accumulated so far.
1446 cfg->etag_bits |= bit;
1447 cfg->etag_add = ETAG_UNSET;
1448 cfg->etag_remove = ETAG_UNSET;
1454 * Any setting at all will clear the 'None' and 'Unset' bits.
1457 if (cfg->etag_add != ETAG_UNSET) {
1458 cfg->etag_add &= (~ ETAG_UNSET);
1461 if (cfg->etag_remove != ETAG_UNSET) {
1462 cfg->etag_remove &= (~ ETAG_UNSET);
1466 cfg->etag_bits &= (~ ETAG_UNSET);
1468 if ((cfg->etag_bits & ETAG_NONE) != ETAG_NONE) {
1469 cfg->etag_bits &= (~ ETAG_NONE);
1476 static const char *set_enable_mmap(cmd_parms *cmd, void *d_,
1479 core_dir_config *d = d_;
1480 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1486 if (strcasecmp(arg, "on") == 0) {
1487 d->enable_mmap = ENABLE_MMAP_ON;
1489 else if (strcasecmp(arg, "off") == 0) {
1490 d->enable_mmap = ENABLE_MMAP_OFF;
1493 return "parameter must be 'on' or 'off'";
1499 static const char *set_enable_sendfile(cmd_parms *cmd, void *d_,
1502 core_dir_config *d = d_;
1503 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1509 if (strcasecmp(arg, "on") == 0) {
1510 d->enable_sendfile = ENABLE_SENDFILE_ON;
1512 else if (strcasecmp(arg, "off") == 0) {
1513 d->enable_sendfile = ENABLE_SENDFILE_OFF;
1516 return "parameter must be 'on' or 'off'";
1522 static const char *satisfy(cmd_parms *cmd, void *c_, const char *arg)
1524 core_dir_config *c = c_;
1526 if (!strcasecmp(arg, "all")) {
1527 c->satisfy = SATISFY_ALL;
1529 else if (!strcasecmp(arg, "any")) {
1530 c->satisfy = SATISFY_ANY;
1533 return "Satisfy either 'any' or 'all'.";
1539 static const char *require(cmd_parms *cmd, void *c_, const char *arg)
1542 core_dir_config *c = c_;
1544 if (!c->ap_requires) {
1545 c->ap_requires = apr_array_make(cmd->pool, 2, sizeof(require_line));
1548 r = (require_line *)apr_array_push(c->ap_requires);
1549 r->requirement = apr_pstrdup(cmd->pool, arg);
1550 r->method_mask = cmd->limited;
1555 AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd,
1559 const char *limited_methods = ap_getword(cmd->pool, &arg, '>');
1560 void *tog = cmd->cmd->cmd_data;
1561 apr_int64_t limited = 0;
1564 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1569 while (limited_methods[0]) {
1570 char *method = ap_getword_conf(cmd->pool, &limited_methods);
1573 /* check for builtin or module registered method number */
1574 methnum = ap_method_number_of(method);
1576 if (methnum == M_TRACE && !tog) {
1577 return "TRACE cannot be controlled by <Limit>";
1579 else if (methnum == M_INVALID) {
1580 /* method has not been registered yet, but resorce restriction
1581 * is always checked before method handling, so register it.
1583 methnum = ap_method_register(cmd->pool, method);
1586 limited |= (AP_METHOD_BIT << methnum);
1589 /* Killing two features with one function,
1590 * if (tog == NULL) <Limit>, else <LimitExcept>
1592 cmd->limited = tog ? ~limited : limited;
1594 errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context);
1601 /* XXX: Bogus - need to do this differently (at least OS2/Netware suffer
1602 * the same problem!!!
1603 * We use this in <DirectoryMatch> and <FilesMatch>, to ensure that
1604 * people don't get bitten by wrong-cased regex matches
1608 #define USE_ICASE REG_ICASE
1614 * Report a missing-'>' syntax error.
1616 static char *unclosed_directive(cmd_parms *cmd)
1618 return apr_pstrcat(cmd->pool, cmd->cmd->name,
1619 "> directive missing closing '>'", NULL);
1622 static const char *dirsection(cmd_parms *cmd, void *mconfig, const char *arg)
1625 const char *endp = ap_strrchr_c(arg, '>');
1626 int old_overrides = cmd->override;
1627 char *old_path = cmd->path;
1628 core_dir_config *conf;
1629 ap_conf_vector_t *new_dir_conf = ap_create_per_dir_config(cmd->pool);
1631 const command_rec *thiscmd = cmd->cmd;
1633 const char *err = ap_check_cmd_context(cmd,
1634 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1640 return unclosed_directive(cmd);
1643 arg = apr_pstrndup(cmd->pool, arg, endp - arg);
1646 if (thiscmd->cmd_data)
1647 return "<DirectoryMatch > block must specify a path";
1649 return "<Directory > block must specify a path";
1652 cmd->path = ap_getword_conf(cmd->pool, &arg);
1653 cmd->override = OR_ALL|ACCESS_CONF;
1655 if (!strcmp(cmd->path, "~")) {
1656 cmd->path = ap_getword_conf(cmd->pool, &arg);
1658 return "<Directory ~ > block must specify a path";
1659 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1661 else if (thiscmd->cmd_data) { /* <DirectoryMatch> */
1662 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1664 else if (!strcmp(cmd->path, "/") == 0)
1669 * Ensure that the pathname is canonical, and append the trailing /
1671 apr_status_t rv = apr_filepath_merge(&newpath, NULL, cmd->path,
1672 APR_FILEPATH_TRUENAME, cmd->pool);
1673 if (rv != APR_SUCCESS && rv != APR_EPATHWILD) {
1674 return apr_pstrcat(cmd->pool, "<Directory \"", cmd->path,
1675 "\"> path is invalid.", NULL);
1678 cmd->path = newpath;
1679 if (cmd->path[strlen(cmd->path) - 1] != '/')
1680 cmd->path = apr_pstrcat(cmd->pool, cmd->path, "/", NULL);
1683 /* initialize our config and fetch it */
1684 conf = ap_set_config_vectors(cmd->server, new_dir_conf, cmd->path,
1685 &core_module, cmd->pool);
1687 errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_dir_conf);
1692 conf->d = cmd->path;
1693 conf->d_is_fnmatch = (apr_fnmatch_test(conf->d) != 0);
1695 /* Make this explicit - the "/" root has 0 elements, that is, we
1696 * will always merge it, and it will always sort and merge first.
1697 * All others are sorted and tested by the number of slashes.
1699 if (strcmp(conf->d, "/") == 0)
1700 conf->d_components = 0;
1702 conf->d_components = ap_count_dirs(conf->d);
1704 ap_add_per_dir_conf(cmd->server, new_dir_conf);
1707 return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1708 "> arguments not (yet) supported.", NULL);
1711 cmd->path = old_path;
1712 cmd->override = old_overrides;
1717 static const char *urlsection(cmd_parms *cmd, void *mconfig, const char *arg)
1720 const char *endp = ap_strrchr_c(arg, '>');
1721 int old_overrides = cmd->override;
1722 char *old_path = cmd->path;
1723 core_dir_config *conf;
1725 const command_rec *thiscmd = cmd->cmd;
1726 ap_conf_vector_t *new_url_conf = ap_create_per_dir_config(cmd->pool);
1727 const char *err = ap_check_cmd_context(cmd,
1728 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1734 return unclosed_directive(cmd);
1737 arg = apr_pstrndup(cmd->pool, arg, endp - arg);
1739 cmd->path = ap_getword_conf(cmd->pool, &arg);
1740 cmd->override = OR_ALL|ACCESS_CONF;
1742 if (thiscmd->cmd_data) { /* <LocationMatch> */
1743 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1745 else if (!strcmp(cmd->path, "~")) {
1746 cmd->path = ap_getword_conf(cmd->pool, &arg);
1747 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1750 /* initialize our config and fetch it */
1751 conf = ap_set_config_vectors(cmd->server, new_url_conf, cmd->path,
1752 &core_module, cmd->pool);
1754 errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_url_conf);
1758 conf->d = apr_pstrdup(cmd->pool, cmd->path); /* No mangling, please */
1759 conf->d_is_fnmatch = apr_fnmatch_test(conf->d) != 0;
1762 ap_add_per_url_conf(cmd->server, new_url_conf);
1765 return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1766 "> arguments not (yet) supported.", NULL);
1769 cmd->path = old_path;
1770 cmd->override = old_overrides;
1775 static const char *filesection(cmd_parms *cmd, void *mconfig, const char *arg)
1778 const char *endp = ap_strrchr_c(arg, '>');
1779 int old_overrides = cmd->override;
1780 char *old_path = cmd->path;
1781 core_dir_config *conf;
1783 const command_rec *thiscmd = cmd->cmd;
1784 core_dir_config *c = mconfig;
1785 ap_conf_vector_t *new_file_conf = ap_create_per_dir_config(cmd->pool);
1786 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT|NOT_IN_LOCATION);
1793 return unclosed_directive(cmd);
1796 arg = apr_pstrndup(cmd->pool, arg, endp - arg);
1798 cmd->path = ap_getword_conf(cmd->pool, &arg);
1799 /* Only if not an .htaccess file */
1801 cmd->override = OR_ALL|ACCESS_CONF;
1804 if (thiscmd->cmd_data) { /* <FilesMatch> */
1805 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1807 else if (!strcmp(cmd->path, "~")) {
1808 cmd->path = ap_getword_conf(cmd->pool, &arg);
1809 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1813 /* Ensure that the pathname is canonical, but we
1814 * can't test the case/aliases without a fixed path */
1815 if (apr_filepath_merge(&newpath, "", cmd->path,
1816 0, cmd->pool) != APR_SUCCESS)
1817 return apr_pstrcat(cmd->pool, "<Files \"", cmd->path,
1818 "\"> is invalid.", NULL);
1819 cmd->path = newpath;
1822 /* initialize our config and fetch it */
1823 conf = ap_set_config_vectors(cmd->server, new_file_conf, cmd->path,
1824 &core_module, cmd->pool);
1826 errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_file_conf);
1830 conf->d = cmd->path;
1831 conf->d_is_fnmatch = apr_fnmatch_test(conf->d) != 0;
1834 ap_add_file_conf(c, new_file_conf);
1837 return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1838 "> arguments not (yet) supported.", NULL);
1841 cmd->path = old_path;
1842 cmd->override = old_overrides;
1847 static const char *start_ifmod(cmd_parms *cmd, void *mconfig, const char *arg)
1849 const char *endp = ap_strrchr_c(arg, '>');
1850 int not = (arg[0] == '!');
1854 return unclosed_directive(cmd);
1857 arg = apr_pstrndup(cmd->pool, arg, endp - arg);
1863 found = ap_find_linked_module(arg);
1865 if ((!not && found) || (not && !found)) {
1866 ap_directive_t *parent = NULL;
1867 ap_directive_t *current = NULL;
1870 retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd,
1871 ¤t, &parent, "<IfModule");
1872 *(ap_directive_t **)mconfig = current;
1876 *(ap_directive_t **)mconfig = NULL;
1877 return ap_soak_end_container(cmd, "<IfModule");
1881 AP_DECLARE(int) ap_exists_config_define(const char *name)
1886 defines = (char **)ap_server_config_defines->elts;
1887 for (i = 0; i < ap_server_config_defines->nelts; i++) {
1888 if (strcmp(defines[i], name) == 0) {
1896 static const char *start_ifdefine(cmd_parms *cmd, void *dummy, const char *arg)
1902 endp = ap_strrchr_c(arg, '>');
1904 return unclosed_directive(cmd);
1907 arg = apr_pstrndup(cmd->pool, arg, endp - arg);
1909 if (arg[0] == '!') {
1914 defined = ap_exists_config_define(arg);
1915 if ((!not && defined) || (not && !defined)) {
1916 ap_directive_t *parent = NULL;
1917 ap_directive_t *current = NULL;
1920 retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd,
1921 ¤t, &parent, "<IfDefine");
1922 *(ap_directive_t **)dummy = current;
1926 *(ap_directive_t **)dummy = NULL;
1927 return ap_soak_end_container(cmd, "<IfDefine");
1931 /* httpd.conf commands... beginning with the <VirtualHost> business */
1933 static const char *virtualhost_section(cmd_parms *cmd, void *dummy,
1936 server_rec *main_server = cmd->server, *s;
1938 const char *endp = ap_strrchr_c(arg, '>');
1939 apr_pool_t *p = cmd->pool;
1941 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1947 return unclosed_directive(cmd);
1950 arg = apr_pstrndup(cmd->pool, arg, endp - arg);
1952 /* FIXME: There's another feature waiting to happen here -- since you
1953 can now put multiple addresses/names on a single <VirtualHost>
1954 you might want to use it to group common definitions and then
1955 define other "subhosts" with their individual differences. But
1956 personally I'd rather just do it with a macro preprocessor. -djg */
1957 if (main_server->is_virtual) {
1958 return "<VirtualHost> doesn't nest!";
1961 errmsg = ap_init_virtual_host(p, arg, main_server, &s);
1966 s->next = main_server->next;
1967 main_server->next = s;
1969 s->defn_name = cmd->directive->filename;
1970 s->defn_line_number = cmd->directive->line_num;
1974 errmsg = ap_walk_config(cmd->directive->first_child, cmd,
1975 s->lookup_defaults);
1977 cmd->server = main_server;
1982 static const char *set_server_alias(cmd_parms *cmd, void *dummy,
1985 if (!cmd->server->names) {
1986 return "ServerAlias only used in <VirtualHost>";
1990 char **item, *name = ap_getword_conf(cmd->pool, &arg);
1992 if (ap_is_matchexp(name)) {
1993 item = (char **)apr_array_push(cmd->server->wild_names);
1996 item = (char **)apr_array_push(cmd->server->names);
2005 static const char *set_server_string_slot(cmd_parms *cmd, void *dummy,
2008 /* This one's pretty generic... */
2010 int offset = (int)(long)cmd->info;
2011 char *struct_ptr = (char *)cmd->server;
2013 const char *err = ap_check_cmd_context(cmd,
2014 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2019 *(const char **)(struct_ptr + offset) = arg;
2023 static const char *server_hostname_port(cmd_parms *cmd, void *dummy, const char *arg)
2025 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2026 const char *portstr;
2033 portstr = ap_strchr_c(arg, ':');
2035 cmd->server->server_hostname = apr_pstrndup(cmd->pool, arg,
2038 port = atoi(portstr);
2039 if (port <= 0 || port >= 65536) { /* 65536 == 1<<16 */
2040 return apr_pstrcat(cmd->temp_pool, "The port number \"", arg,
2041 "\" is outside the appropriate range "
2042 "(i.e., 1..65535).", NULL);
2046 cmd->server->server_hostname = apr_pstrdup(cmd->pool, arg);
2050 cmd->server->port = port;
2054 static const char *set_signature_flag(cmd_parms *cmd, void *d_,
2057 core_dir_config *d = d_;
2058 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2064 if (strcasecmp(arg, "On") == 0) {
2065 d->server_signature = srv_sig_on;
2067 else if (strcasecmp(arg, "Off") == 0) {
2068 d->server_signature = srv_sig_off;
2070 else if (strcasecmp(arg, "EMail") == 0) {
2071 d->server_signature = srv_sig_withmail;
2074 return "ServerSignature: use one of: off | on | email";
2080 static const char *set_server_root(cmd_parms *cmd, void *dummy,
2083 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2089 if ((apr_filepath_merge((char**)&ap_server_root, NULL, arg,
2090 APR_FILEPATH_TRUENAME, cmd->pool) != APR_SUCCESS)
2091 || !ap_is_directory(cmd->pool, ap_server_root)) {
2092 return "ServerRoot must be a valid directory";
2098 static const char *set_timeout(cmd_parms *cmd, void *dummy, const char *arg)
2100 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2106 cmd->server->timeout = apr_time_from_sec(atoi(arg));
2110 static const char *set_allow2f(cmd_parms *cmd, void *d_, int arg)
2112 core_dir_config *d = d_;
2113 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2119 d->allow_encoded_slashes = arg != 0;
2123 static const char *set_hostname_lookups(cmd_parms *cmd, void *d_,
2126 core_dir_config *d = d_;
2127 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2133 if (!strcasecmp(arg, "on")) {
2134 d->hostname_lookups = HOSTNAME_LOOKUP_ON;
2136 else if (!strcasecmp(arg, "off")) {
2137 d->hostname_lookups = HOSTNAME_LOOKUP_OFF;
2139 else if (!strcasecmp(arg, "double")) {
2140 d->hostname_lookups = HOSTNAME_LOOKUP_DOUBLE;
2143 return "parameter must be 'on', 'off', or 'double'";
2149 static const char *set_serverpath(cmd_parms *cmd, void *dummy,
2152 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2158 cmd->server->path = arg;
2159 cmd->server->pathlen = strlen(arg);
2163 static const char *set_content_md5(cmd_parms *cmd, void *d_, int arg)
2165 core_dir_config *d = d_;
2166 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2172 d->content_md5 = arg != 0;
2176 static const char *set_accept_path_info(cmd_parms *cmd, void *d_, const char *arg)
2178 core_dir_config *d = d_;
2180 if (strcasecmp(arg, "on") == 0) {
2181 d->accept_path_info = AP_REQ_ACCEPT_PATH_INFO;
2183 else if (strcasecmp(arg, "off") == 0) {
2184 d->accept_path_info = AP_REQ_REJECT_PATH_INFO;
2186 else if (strcasecmp(arg, "default") == 0) {
2187 d->accept_path_info = AP_REQ_DEFAULT_PATH_INFO;
2190 return "AcceptPathInfo must be set to on, off or default";
2196 static const char *set_use_canonical_name(cmd_parms *cmd, void *d_,
2199 core_dir_config *d = d_;
2200 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2206 if (strcasecmp(arg, "on") == 0) {
2207 d->use_canonical_name = USE_CANONICAL_NAME_ON;
2209 else if (strcasecmp(arg, "off") == 0) {
2210 d->use_canonical_name = USE_CANONICAL_NAME_OFF;
2212 else if (strcasecmp(arg, "dns") == 0) {
2213 d->use_canonical_name = USE_CANONICAL_NAME_DNS;
2216 return "parameter must be 'on', 'off', or 'dns'";
2223 static const char *include_config (cmd_parms *cmd, void *dummy,
2226 ap_directive_t *conftree = NULL;
2227 const char* conffile = ap_server_root_relative(cmd->pool, name);
2230 return apr_pstrcat(cmd->pool, "Invalid Include path ",
2234 ap_process_resource_config(cmd->server, conffile,
2235 &conftree, cmd->pool, cmd->temp_pool);
2236 *(ap_directive_t **)dummy = conftree;
2240 static const char *set_loglevel(cmd_parms *cmd, void *dummy, const char *arg)
2244 const char *err = ap_check_cmd_context(cmd,
2245 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2250 if ((str = ap_getword_conf(cmd->pool, &arg))) {
2251 if (!strcasecmp(str, "emerg")) {
2252 cmd->server->loglevel = APLOG_EMERG;
2254 else if (!strcasecmp(str, "alert")) {
2255 cmd->server->loglevel = APLOG_ALERT;
2257 else if (!strcasecmp(str, "crit")) {
2258 cmd->server->loglevel = APLOG_CRIT;
2260 else if (!strcasecmp(str, "error")) {
2261 cmd->server->loglevel = APLOG_ERR;
2263 else if (!strcasecmp(str, "warn")) {
2264 cmd->server->loglevel = APLOG_WARNING;
2266 else if (!strcasecmp(str, "notice")) {
2267 cmd->server->loglevel = APLOG_NOTICE;
2269 else if (!strcasecmp(str, "info")) {
2270 cmd->server->loglevel = APLOG_INFO;
2272 else if (!strcasecmp(str, "debug")) {
2273 cmd->server->loglevel = APLOG_DEBUG;
2276 return "LogLevel requires level keyword: one of "
2277 "emerg/alert/crit/error/warn/notice/info/debug";
2281 return "LogLevel requires level keyword";
2287 AP_DECLARE(const char *) ap_psignature(const char *prefix, request_rec *r)
2290 core_dir_config *conf;
2292 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
2294 if ((conf->server_signature == srv_sig_off)
2295 || (conf->server_signature == srv_sig_unset)) {
2299 apr_snprintf(sport, sizeof sport, "%u", (unsigned) ap_get_server_port(r));
2301 if (conf->server_signature == srv_sig_withmail) {
2302 return apr_pstrcat(r->pool, prefix, "<address>",
2303 ap_get_server_version(),
2304 " Server at <a href=\"mailto:",
2305 r->server->server_admin, "\">",
2306 ap_escape_html(r->pool, ap_get_server_name(r)),
2307 "</a> Port ", sport,
2308 "</address>\n", NULL);
2311 return apr_pstrcat(r->pool, prefix, "<address>", ap_get_server_version(),
2313 ap_escape_html(r->pool, ap_get_server_name(r)),
2315 "</address>\n", NULL);
2319 * Load an authorisation realm into our location configuration, applying the
2320 * usual rules that apply to realms.
2322 static const char *set_authname(cmd_parms *cmd, void *mconfig,
2325 core_dir_config *aconfig = (core_dir_config *)mconfig;
2327 aconfig->ap_auth_name = ap_escape_quotes(cmd->pool, word1);
2332 * Handle a request to include the server's OS platform in the Server
2333 * response header field (the ServerTokens directive). Unfortunately
2334 * this requires a new global in order to communicate the setting back to
2335 * http_main so it can insert the information in the right place in the
2339 static char *server_version = NULL;
2340 static int version_locked = 0;
2342 enum server_token_type {
2343 SrvTk_MAJOR, /* eg: Apache/2 */
2344 SrvTk_MINOR, /* eg. Apache/2.0 */
2345 SrvTk_MINIMAL, /* eg: Apache/2.0.41 */
2346 SrvTk_OS, /* eg: Apache/2.0.41 (UNIX) */
2347 SrvTk_FULL, /* eg: Apache/2.0.41 (UNIX) PHP/4.2.2 FooBar/1.2b */
2348 SrvTk_PRODUCT_ONLY /* eg: Apache */
2350 static enum server_token_type ap_server_tokens = SrvTk_FULL;
2352 static apr_status_t reset_version(void *dummy)
2355 ap_server_tokens = SrvTk_FULL;
2356 server_version = NULL;
2360 AP_DECLARE(const char *) ap_get_server_version(void)
2362 return (server_version ? server_version : AP_SERVER_BASEVERSION);
2365 AP_DECLARE(void) ap_add_version_component(apr_pool_t *pconf, const char *component)
2367 if (! version_locked) {
2369 * If the version string is null, register our cleanup to reset the
2370 * pointer on pool destruction. We also know that, if NULL,
2371 * we are adding the original SERVER_BASEVERSION string.
2373 if (server_version == NULL) {
2374 apr_pool_cleanup_register(pconf, NULL, reset_version,
2375 apr_pool_cleanup_null);
2376 server_version = apr_pstrdup(pconf, component);
2380 * Tack the given component identifier to the end of
2381 * the existing string.
2383 server_version = apr_pstrcat(pconf, server_version, " ",
2390 * This routine adds the real server base identity to the version string,
2391 * and then locks out changes until the next reconfig.
2393 static void ap_set_version(apr_pool_t *pconf)
2395 if (ap_server_tokens == SrvTk_PRODUCT_ONLY) {
2396 ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT);
2398 else if (ap_server_tokens == SrvTk_MINIMAL) {
2399 ap_add_version_component(pconf, AP_SERVER_BASEVERSION);
2401 else if (ap_server_tokens == SrvTk_MINOR) {
2402 ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT "/" AP_SERVER_MINORREVISION);
2404 else if (ap_server_tokens == SrvTk_MAJOR) {
2405 ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT "/" AP_SERVER_MAJORVERSION);
2408 ap_add_version_component(pconf, AP_SERVER_BASEVERSION " (" PLATFORM ")");
2412 * Lock the server_version string if we're not displaying
2413 * the full set of tokens
2415 if (ap_server_tokens != SrvTk_FULL) {
2420 static const char *set_serv_tokens(cmd_parms *cmd, void *dummy,
2423 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2429 if (!strcasecmp(arg, "OS")) {
2430 ap_server_tokens = SrvTk_OS;
2432 else if (!strcasecmp(arg, "Min") || !strcasecmp(arg, "Minimal")) {
2433 ap_server_tokens = SrvTk_MINIMAL;
2435 else if (!strcasecmp(arg, "Major")) {
2436 ap_server_tokens = SrvTk_MAJOR;
2438 else if (!strcasecmp(arg, "Minor") ) {
2439 ap_server_tokens = SrvTk_MINOR;
2441 else if (!strcasecmp(arg, "Prod") || !strcasecmp(arg, "ProductOnly")) {
2442 ap_server_tokens = SrvTk_PRODUCT_ONLY;
2445 ap_server_tokens = SrvTk_FULL;
2451 static const char *set_limit_req_line(cmd_parms *cmd, void *dummy,
2454 const char *err = ap_check_cmd_context(cmd,
2455 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2464 return apr_pstrcat(cmd->temp_pool, "LimitRequestLine \"", arg,
2465 "\" must be a non-negative integer", NULL);
2468 if (lim > DEFAULT_LIMIT_REQUEST_LINE) {
2469 return apr_psprintf(cmd->temp_pool, "LimitRequestLine \"%s\" "
2470 "must not exceed the precompiled maximum of %d",
2471 arg, DEFAULT_LIMIT_REQUEST_LINE);
2474 cmd->server->limit_req_line = lim;
2478 static const char *set_limit_req_fieldsize(cmd_parms *cmd, void *dummy,
2481 const char *err = ap_check_cmd_context(cmd,
2482 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2491 return apr_pstrcat(cmd->temp_pool, "LimitRequestFieldsize \"", arg,
2492 "\" must be a non-negative integer (0 = no limit)",
2496 if (lim > DEFAULT_LIMIT_REQUEST_FIELDSIZE) {
2497 return apr_psprintf(cmd->temp_pool, "LimitRequestFieldsize \"%s\" "
2498 "must not exceed the precompiled maximum of %d",
2499 arg, DEFAULT_LIMIT_REQUEST_FIELDSIZE);
2502 cmd->server->limit_req_fieldsize = lim;
2506 static const char *set_limit_req_fields(cmd_parms *cmd, void *dummy,
2509 const char *err = ap_check_cmd_context(cmd,
2510 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2519 return apr_pstrcat(cmd->temp_pool, "LimitRequestFields \"", arg,
2520 "\" must be a non-negative integer (0 = no limit)",
2524 cmd->server->limit_req_fields = lim;
2528 static const char *set_limit_req_body(cmd_parms *cmd, void *conf_,
2531 core_dir_config *conf = conf_;
2532 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2539 /* WTF: If strtoul is not portable, then write a replacement.
2540 * Instead we have an idiotic define in httpd.h that prevents
2541 * it from being used even when it is available. Sheesh.
2543 conf->limit_req_body = (apr_off_t)strtol(arg, &errp, 10);
2544 if (*errp != '\0') {
2545 return "LimitRequestBody requires a non-negative integer.";
2551 static const char *set_limit_xml_req_body(cmd_parms *cmd, void *conf_,
2554 core_dir_config *conf = conf_;
2555 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2561 conf->limit_xml_body = atol(arg);
2562 if (conf->limit_xml_body < 0)
2563 return "LimitXMLRequestBody requires a non-negative integer.";
2568 AP_DECLARE(size_t) ap_get_limit_xml_body(const request_rec *r)
2570 core_dir_config *conf;
2572 conf = ap_get_module_config(r->per_dir_config, &core_module);
2573 if (conf->limit_xml_body == AP_LIMIT_UNSET)
2574 return AP_DEFAULT_LIMIT_XML_BODY;
2576 return (size_t)conf->limit_xml_body;
2579 #if !defined (RLIMIT_CPU) || !(defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)) || !defined (RLIMIT_NPROC)
2580 static const char *no_set_limit(cmd_parms *cmd, void *conf_,
2581 const char *arg, const char *arg2)
2583 ap_log_error(APLOG_MARK, APLOG_ERR, 0, cmd->server,
2584 "%s not supported on this platform", cmd->cmd->name);
2591 static const char *set_limit_cpu(cmd_parms *cmd, void *conf_,
2592 const char *arg, const char *arg2)
2594 core_dir_config *conf = conf_;
2596 unixd_set_rlimit(cmd, &conf->limit_cpu, arg, arg2, RLIMIT_CPU);
2601 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)
2602 static const char *set_limit_mem(cmd_parms *cmd, void *conf_,
2603 const char *arg, const char * arg2)
2605 core_dir_config *conf = conf_;
2607 #if defined(RLIMIT_AS)
2608 unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2 ,RLIMIT_AS);
2609 #elif defined(RLIMIT_DATA)
2610 unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_DATA);
2611 #elif defined(RLIMIT_VMEM)
2612 unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_VMEM);
2620 static const char *set_limit_nproc(cmd_parms *cmd, void *conf_,
2621 const char *arg, const char * arg2)
2623 core_dir_config *conf = conf_;
2625 unixd_set_rlimit(cmd, &conf->limit_nproc, arg, arg2, RLIMIT_NPROC);
2630 static const char *set_recursion_limit(cmd_parms *cmd, void *dummy,
2631 const char *arg1, const char *arg2)
2633 core_server_config *conf = ap_get_module_config(cmd->server->module_config,
2635 int limit = atoi(arg1);
2638 return "The recursion limit must be greater than zero.";
2641 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
2642 "Limiting internal redirects to very low numbers may "
2643 "cause normal requests to fail.");
2646 conf->redirect_limit = limit;
2652 return "The recursion limit must be greater than zero.";
2655 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
2656 "Limiting the subrequest depth to a very low level may"
2657 " cause normal requests to fail.");
2661 conf->subreq_limit = limit;
2666 static void log_backtrace(const request_rec *r)
2668 const request_rec *top = r;
2670 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
2671 "r->uri = %s", r->uri ? r->uri : "(unexpectedly NULL)");
2673 while (top && (top->prev || top->main)) {
2676 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
2677 "redirected from r->uri = %s",
2678 top->uri ? top->uri : "(unexpectedly NULL)");
2681 if (!top->prev && top->main) {
2683 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
2684 "subrequested from r->uri = %s",
2685 top->uri ? top->uri : "(unexpectedly NULL)");
2691 * check whether redirect limit is reached
2693 AP_DECLARE(int) ap_is_recursion_limit_exceeded(const request_rec *r)
2695 core_server_config *conf = ap_get_module_config(r->server->module_config,
2697 const request_rec *top = r;
2698 int redirects = 0, subreqs = 0;
2699 int rlimit = conf->redirect_limit
2700 ? conf->redirect_limit
2701 : AP_DEFAULT_MAX_INTERNAL_REDIRECTS;
2702 int slimit = conf->subreq_limit
2703 ? conf->subreq_limit
2704 : AP_DEFAULT_MAX_SUBREQ_DEPTH;
2707 while (top->prev || top->main) {
2709 if (++redirects >= rlimit) {
2710 /* uuh, too much. */
2711 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
2712 "Request exceeded the limit of %d internal "
2713 "redirects due to probable configuration error. "
2714 "Use 'LimitInternalRecursion' to increase the "
2715 "limit if necessary. Use 'LogLevel debug' to get "
2716 "a backtrace.", rlimit);
2718 /* post backtrace */
2721 /* return failure */
2728 if (!top->prev && top->main) {
2729 if (++subreqs >= slimit) {
2730 /* uuh, too much. */
2731 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
2732 "Request exceeded the limit of %d subrequest "
2733 "nesting levels due to probable confguration "
2734 "error. Use 'LimitInternalRecursion' to increase "
2735 "the limit if necessary. Use 'LogLevel debug' to "
2736 "get a backtrace.", slimit);
2738 /* post backtrace */
2741 /* return failure */
2749 /* recursion state: ok */
2753 static const char *add_ct_output_filters(cmd_parms *cmd, void *conf_,
2754 const char *arg, const char *arg2)
2756 core_dir_config *conf = conf_;
2757 ap_filter_rec_t *old, *new = NULL;
2758 const char *filter_name;
2760 if (!conf->ct_output_filters) {
2761 conf->ct_output_filters = apr_hash_make(cmd->pool);
2765 old = (ap_filter_rec_t*) apr_hash_get(conf->ct_output_filters, arg2,
2766 APR_HASH_KEY_STRING);
2767 /* find last entry */
2776 (filter_name = ap_getword(cmd->pool, &arg, ';')) &&
2777 strcmp(filter_name, "")) {
2778 new = apr_pcalloc(cmd->pool, sizeof(ap_filter_rec_t));
2779 new->name = filter_name;
2781 /* We found something, so let's append it. */
2786 apr_hash_set(conf->ct_output_filters, arg2,
2787 APR_HASH_KEY_STRING, new);
2793 return "invalid filter name";
2799 * Insert filters requested by the AddOutputFilterByType
2800 * configuration directive. We cannot add filters based
2801 * on content-type until after the handler has started
2802 * to run. Only then do we reliably know the content-type.
2804 void ap_add_output_filters_by_type(request_rec *r)
2806 core_dir_config *conf;
2809 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
2812 /* We can't do anything with proxy requests, no content-types or if
2813 * we don't have a filter configured.
2815 if (r->proxyreq != PROXYREQ_NONE || !r->content_type ||
2816 !conf->ct_output_filters) {
2820 /* remove c-t decoration */
2821 ctype = ap_field_noparam(r->pool, r->content_type);
2823 ap_filter_rec_t *ct_filter;
2824 ct_filter = apr_hash_get(conf->ct_output_filters, ctype,
2825 APR_HASH_KEY_STRING);
2827 ap_add_output_filter(ct_filter->name, NULL, r, r->connection);
2828 ct_filter = ct_filter->next;
2835 static apr_status_t writev_it_all(apr_socket_t *s,
2836 struct iovec *vec, int nvec,
2837 apr_size_t len, apr_size_t *nbytes)
2839 apr_size_t bytes_written = 0;
2846 /* XXX handle checking for non-blocking socket */
2847 while (bytes_written != len) {
2848 rv = apr_socket_sendv(s, vec + i, nvec - i, &n);
2850 if (rv != APR_SUCCESS)
2855 /* If the write did not complete, adjust the iovecs and issue
2856 * apr_socket_sendv again
2858 if (bytes_written < len) {
2859 /* Skip over the vectors that have already been written */
2860 apr_size_t cnt = vec[i].iov_len;
2861 while (n >= cnt && i + 1 < nvec) {
2863 cnt += vec[i].iov_len;
2867 /* Handle partial write of vec i */
2868 vec[i].iov_base = (char *) vec[i].iov_base +
2869 (vec[i].iov_len - (cnt - n));
2870 vec[i].iov_len = cnt -n;
2874 n = len - bytes_written;
2880 /* sendfile_it_all()
2881 * send the entire file using sendfile()
2882 * handle partial writes
2883 * return only when all bytes have been sent or an error is encountered.
2886 #if APR_HAS_SENDFILE
2887 static apr_status_t sendfile_it_all(core_net_rec *c,
2890 apr_off_t file_offset,
2891 apr_size_t file_bytes_left,
2892 apr_size_t total_bytes_left,
2893 apr_size_t *bytes_sent,
2898 apr_interval_time_t timeout = 0;
2901 AP_DEBUG_ASSERT((apr_socket_timeout_get(c->client_socket, &timeout)
2903 && timeout > 0); /* socket must be in timeout mode */
2905 /* Reset the bytes_sent field */
2909 apr_size_t tmplen = file_bytes_left;
2911 rv = apr_socket_sendfile(c->client_socket, fd, hdtr, &file_offset, &tmplen,
2913 *bytes_sent += tmplen;
2914 total_bytes_left -= tmplen;
2915 if (!total_bytes_left || rv != APR_SUCCESS) {
2916 return rv; /* normal case & error exit */
2919 AP_DEBUG_ASSERT(total_bytes_left > 0 && tmplen > 0);
2921 /* partial write, oooh noooo...
2922 * Skip over any header data which was written
2924 while (tmplen && hdtr->numheaders) {
2925 if (tmplen >= hdtr->headers[0].iov_len) {
2926 tmplen -= hdtr->headers[0].iov_len;
2931 char *iov_base = (char *)hdtr->headers[0].iov_base;
2933 hdtr->headers[0].iov_len -= tmplen;
2935 hdtr->headers[0].iov_base = iov_base;
2940 /* Skip over any file data which was written */
2942 if (tmplen <= file_bytes_left) {
2943 file_offset += tmplen;
2944 file_bytes_left -= tmplen;
2948 tmplen -= file_bytes_left;
2949 file_bytes_left = 0;
2952 /* Skip over any trailer data which was written */
2954 while (tmplen && hdtr->numtrailers) {
2955 if (tmplen >= hdtr->trailers[0].iov_len) {
2956 tmplen -= hdtr->trailers[0].iov_len;
2957 --hdtr->numtrailers;
2961 char *iov_base = (char *)hdtr->trailers[0].iov_base;
2963 hdtr->trailers[0].iov_len -= tmplen;
2965 hdtr->trailers[0].iov_base = iov_base;
2974 * emulate_sendfile()
2975 * Sends the contents of file fd along with header/trailer bytes, if any,
2976 * to the network. emulate_sendfile will return only when all the bytes have been
2977 * sent (i.e., it handles partial writes) or on a network error condition.
2979 static apr_status_t emulate_sendfile(core_net_rec *c, apr_file_t *fd,
2980 apr_hdtr_t *hdtr, apr_off_t offset,
2981 apr_size_t length, apr_size_t *nbytes)
2983 apr_status_t rv = APR_SUCCESS;
2984 apr_int32_t togo; /* Remaining number of bytes in the file to send */
2985 apr_size_t sendlen = 0;
2986 apr_size_t bytes_sent;
2988 apr_off_t o; /* Track the file offset for partial writes */
2994 * writev_it_all handles partial writes.
2995 * XXX: optimization... if headers are less than MIN_WRITE_SIZE, copy
2998 if (hdtr && hdtr->numheaders > 0 ) {
2999 for (i = 0; i < hdtr->numheaders; i++) {
3000 sendlen += hdtr->headers[i].iov_len;
3003 rv = writev_it_all(c->client_socket, hdtr->headers, hdtr->numheaders,
3004 sendlen, &bytes_sent);
3005 if (rv == APR_SUCCESS)
3006 *nbytes += bytes_sent; /* track total bytes sent */
3009 /* Seek the file to 'offset' */
3010 if (offset != 0 && rv == APR_SUCCESS) {
3011 rv = apr_file_seek(fd, APR_SET, &offset);
3014 /* Send the file, making sure to handle partial writes */
3016 while (rv == APR_SUCCESS && togo) {
3017 sendlen = togo > sizeof(buffer) ? sizeof(buffer) : togo;
3019 rv = apr_file_read(fd, buffer, &sendlen);
3020 while (rv == APR_SUCCESS && sendlen) {
3021 bytes_sent = sendlen;
3022 rv = apr_socket_send(c->client_socket, &buffer[o], &bytes_sent);
3023 if (rv == APR_SUCCESS) {
3024 sendlen -= bytes_sent; /* sendlen != bytes_sent ==> partial write */
3025 o += bytes_sent; /* o is where we are in the buffer */
3026 *nbytes += bytes_sent;
3027 togo -= bytes_sent; /* track how much of the file we've sent */
3032 /* Send the trailers
3033 * XXX: optimization... if it will fit, send this on the last send in the
3037 if ( rv == APR_SUCCESS && hdtr && hdtr->numtrailers > 0 ) {
3038 for (i = 0; i < hdtr->numtrailers; i++) {
3039 sendlen += hdtr->trailers[i].iov_len;
3041 rv = writev_it_all(c->client_socket, hdtr->trailers, hdtr->numtrailers,
3042 sendlen, &bytes_sent);
3043 if (rv == APR_SUCCESS)
3044 *nbytes += bytes_sent;
3050 /* Note --- ErrorDocument will now work from .htaccess files.
3051 * The AllowOverride of Fileinfo allows webmasters to turn it off
3054 static const command_rec core_cmds[] = {
3056 /* Old access config file commands */
3058 AP_INIT_RAW_ARGS("<Directory", dirsection, NULL, RSRC_CONF,
3059 "Container for directives affecting resources located in the specified "
3061 AP_INIT_RAW_ARGS("<Location", urlsection, NULL, RSRC_CONF,
3062 "Container for directives affecting resources accessed through the "
3063 "specified URL paths"),
3064 AP_INIT_RAW_ARGS("<VirtualHost", virtualhost_section, NULL, RSRC_CONF,
3065 "Container to map directives to a particular virtual host, takes one or "
3066 "more host addresses"),
3067 AP_INIT_RAW_ARGS("<Files", filesection, NULL, OR_ALL,
3068 "Container for directives affecting files matching specified patterns"),
3069 AP_INIT_RAW_ARGS("<Limit", ap_limit_section, NULL, OR_ALL,
3070 "Container for authentication directives when accessed using specified HTTP "
3072 AP_INIT_RAW_ARGS("<LimitExcept", ap_limit_section, (void*)1, OR_ALL,
3073 "Container for authentication directives to be applied when any HTTP "
3074 "method other than those specified is used to access the resource"),
3075 AP_INIT_TAKE1("<IfModule", start_ifmod, NULL, EXEC_ON_READ | OR_ALL,
3076 "Container for directives based on existance of specified modules"),
3077 AP_INIT_TAKE1("<IfDefine", start_ifdefine, NULL, EXEC_ON_READ | OR_ALL,
3078 "Container for directives based on existance of command line defines"),
3079 AP_INIT_RAW_ARGS("<DirectoryMatch", dirsection, (void*)1, RSRC_CONF,
3080 "Container for directives affecting resources located in the "
3081 "specified directories"),
3082 AP_INIT_RAW_ARGS("<LocationMatch", urlsection, (void*)1, RSRC_CONF,
3083 "Container for directives affecting resources accessed through the "
3084 "specified URL paths"),
3085 AP_INIT_RAW_ARGS("<FilesMatch", filesection, (void*)1, OR_ALL,
3086 "Container for directives affecting files matching specified patterns"),
3087 AP_INIT_TAKE1("AuthType", ap_set_string_slot,
3088 (void*)APR_OFFSETOF(core_dir_config, ap_auth_type), OR_AUTHCFG,
3089 "An HTTP authorization type (e.g., \"Basic\")"),
3090 AP_INIT_TAKE1("AuthName", set_authname, NULL, OR_AUTHCFG,
3091 "The authentication realm (e.g. \"Members Only\")"),
3092 AP_INIT_RAW_ARGS("Require", require, NULL, OR_AUTHCFG,
3093 "Selects which authenticated users or groups may access a protected space"),
3094 AP_INIT_TAKE1("Satisfy", satisfy, NULL, OR_AUTHCFG,
3095 "access policy if both allow and require used ('all' or 'any')"),
3097 AP_INIT_TAKE1("GprofDir", set_gprof_dir, NULL, RSRC_CONF,
3098 "Directory to plop gmon.out files"),
3100 AP_INIT_TAKE1("AddDefaultCharset", set_add_default_charset, NULL, OR_FILEINFO,
3101 "The name of the default charset to add to any Content-Type without one or 'Off' to disable"),
3102 AP_INIT_TAKE1("AcceptPathInfo", set_accept_path_info, NULL, OR_FILEINFO,
3103 "Set to on or off for PATH_INFO to be accepted by handlers, or default for the per-handler preference"),
3105 /* Old resource config file commands */
3107 AP_INIT_RAW_ARGS("AccessFileName", set_access_name, NULL, RSRC_CONF,
3108 "Name(s) of per-directory config files (default: .htaccess)"),
3109 AP_INIT_TAKE1("DocumentRoot", set_document_root, NULL, RSRC_CONF,
3110 "Root directory of the document tree"),
3111 AP_INIT_TAKE2("ErrorDocument", set_error_document, NULL, OR_FILEINFO,
3112 "Change responses for HTTP errors"),
3113 AP_INIT_RAW_ARGS("AllowOverride", set_override, NULL, ACCESS_CONF,
3114 "Controls what groups of directives can be configured by per-directory "
3116 AP_INIT_RAW_ARGS("Options", set_options, NULL, OR_OPTIONS,
3117 "Set a number of attributes for a given directory"),
3118 AP_INIT_TAKE1("DefaultType", ap_set_string_slot,
3119 (void*)APR_OFFSETOF(core_dir_config, ap_default_type),
3120 OR_FILEINFO, "the default MIME type for untypable files"),
3121 AP_INIT_RAW_ARGS("FileETag", set_etag_bits, NULL, OR_FILEINFO,
3122 "Specify components used to construct a file's ETag"),
3123 AP_INIT_TAKE1("EnableMMAP", set_enable_mmap, NULL, OR_FILEINFO,
3124 "Controls whether memory-mapping may be used to read files"),
3125 AP_INIT_TAKE1("EnableSendfile", set_enable_sendfile, NULL, OR_FILEINFO,
3126 "Controls whether sendfile may be used to transmit files"),
3128 /* Old server config file commands */
3130 AP_INIT_TAKE1("Port", ap_set_deprecated, NULL, RSRC_CONF,
3131 "Port was replaced with Listen in Apache 2.0"),
3132 AP_INIT_TAKE1("HostnameLookups", set_hostname_lookups, NULL,
3133 ACCESS_CONF|RSRC_CONF,
3134 "\"on\" to enable, \"off\" to disable reverse DNS lookups, or \"double\" to "
3135 "enable double-reverse DNS lookups"),
3136 AP_INIT_TAKE1("ServerAdmin", set_server_string_slot,
3137 (void *)APR_OFFSETOF(server_rec, server_admin), RSRC_CONF,
3138 "The email address of the server administrator"),
3139 AP_INIT_TAKE1("ServerName", server_hostname_port, NULL, RSRC_CONF,
3140 "The hostname and port of the server"),
3141 AP_INIT_TAKE1("ServerSignature", set_signature_flag, NULL, OR_ALL,
3142 "En-/disable server signature (on|off|email)"),
3143 AP_INIT_TAKE1("ServerRoot", set_server_root, NULL, RSRC_CONF | EXEC_ON_READ,
3144 "Common directory of server-related files (logs, confs, etc.)"),
3145 AP_INIT_TAKE1("ErrorLog", set_server_string_slot,
3146 (void *)APR_OFFSETOF(server_rec, error_fname), RSRC_CONF,
3147 "The filename of the error log"),
3148 AP_INIT_RAW_ARGS("ServerAlias", set_server_alias, NULL, RSRC_CONF,
3149 "A name or names alternately used to access the server"),
3150 AP_INIT_TAKE1("ServerPath", set_serverpath, NULL, RSRC_CONF,
3151 "The pathname the server can be reached at"),
3152 AP_INIT_TAKE1("Timeout", set_timeout, NULL, RSRC_CONF,
3153 "Timeout duration (sec)"),
3154 AP_INIT_FLAG("ContentDigest", set_content_md5, NULL, OR_OPTIONS,
3155 "whether or not to send a Content-MD5 header with each request"),
3156 AP_INIT_TAKE1("UseCanonicalName", set_use_canonical_name, NULL,
3157 RSRC_CONF|ACCESS_CONF,
3158 "How to work out the ServerName : Port when constructing URLs"),
3159 /* TODO: RlimitFoo should all be part of mod_cgi, not in the core */
3160 /* TODO: ListenBacklog in MPM */
3161 AP_INIT_TAKE1("Include", include_config, NULL,
3162 (RSRC_CONF | ACCESS_CONF | EXEC_ON_READ),
3163 "Name of the config file to be included"),
3164 AP_INIT_TAKE1("LogLevel", set_loglevel, NULL, RSRC_CONF,
3165 "Level of verbosity in error logging"),
3166 AP_INIT_TAKE1("NameVirtualHost", ap_set_name_virtual_host, NULL, RSRC_CONF,
3167 "A numeric IP address:port, or the name of a host"),
3168 AP_INIT_TAKE1("ServerTokens", set_serv_tokens, NULL, RSRC_CONF,
3169 "Determine tokens displayed in the Server: header - Min(imal), OS or Full"),
3170 AP_INIT_TAKE1("LimitRequestLine", set_limit_req_line, NULL, RSRC_CONF,
3171 "Limit on maximum size of an HTTP request line"),
3172 AP_INIT_TAKE1("LimitRequestFieldsize", set_limit_req_fieldsize, NULL,
3174 "Limit on maximum size of an HTTP request header field"),
3175 AP_INIT_TAKE1("LimitRequestFields", set_limit_req_fields, NULL, RSRC_CONF,
3176 "Limit (0 = unlimited) on max number of header fields in a request message"),
3177 AP_INIT_TAKE1("LimitRequestBody", set_limit_req_body,
3178 (void*)APR_OFFSETOF(core_dir_config, limit_req_body), OR_ALL,
3179 "Limit (in bytes) on maximum size of request message body"),
3180 AP_INIT_TAKE1("LimitXMLRequestBody", set_limit_xml_req_body, NULL, OR_ALL,
3181 "Limit (in bytes) on maximum size of an XML-based request "
3184 /* System Resource Controls */
3186 AP_INIT_TAKE12("RLimitCPU", set_limit_cpu,
3187 (void*)APR_OFFSETOF(core_dir_config, limit_cpu),
3188 OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
3190 AP_INIT_TAKE12("RLimitCPU", no_set_limit, NULL,
3191 OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
3193 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined (RLIMIT_AS)
3194 AP_INIT_TAKE12("RLimitMEM", set_limit_mem,
3195 (void*)APR_OFFSETOF(core_dir_config, limit_mem),
3196 OR_ALL, "Soft/hard limits for max memory usage per process"),
3198 AP_INIT_TAKE12("RLimitMEM", no_set_limit, NULL,
3199 OR_ALL, "Soft/hard limits for max memory usage per process"),
3202 AP_INIT_TAKE12("RLimitNPROC", set_limit_nproc,
3203 (void*)APR_OFFSETOF(core_dir_config, limit_nproc),
3204 OR_ALL, "soft/hard limits for max number of processes per uid"),
3206 AP_INIT_TAKE12("RLimitNPROC", no_set_limit, NULL,
3207 OR_ALL, "soft/hard limits for max number of processes per uid"),
3210 /* internal recursion stopper */
3211 AP_INIT_TAKE12("LimitInternalRecursion", set_recursion_limit, NULL, RSRC_CONF,
3212 "maximum recursion depth of internal redirects and subrequests"),
3214 AP_INIT_TAKE1("ForceType", ap_set_string_slot_lower,
3215 (void *)APR_OFFSETOF(core_dir_config, mime_type), OR_FILEINFO,
3216 "a mime type that overrides other configured type"),
3217 AP_INIT_TAKE1("SetHandler", ap_set_string_slot_lower,
3218 (void *)APR_OFFSETOF(core_dir_config, handler), OR_FILEINFO,
3219 "a handler name that overrides any other configured handler"),
3220 AP_INIT_TAKE1("SetOutputFilter", ap_set_string_slot,
3221 (void *)APR_OFFSETOF(core_dir_config, output_filters), OR_FILEINFO,
3222 "filter (or ; delimited list of filters) to be run on the request content"),
3223 AP_INIT_TAKE1("SetInputFilter", ap_set_string_slot,
3224 (void *)APR_OFFSETOF(core_dir_config, input_filters), OR_FILEINFO,
3225 "filter (or ; delimited list of filters) to be run on the request body"),
3226 AP_INIT_ITERATE2("AddOutputFilterByType", add_ct_output_filters,
3227 (void *)APR_OFFSETOF(core_dir_config, ct_output_filters), OR_FILEINFO,
3228 "output filter name followed by one or more content-types"),
3229 AP_INIT_FLAG("AllowEncodedSlashes", set_allow2f, NULL, RSRC_CONF,
3230 "Allow URLs containing '/' encoded as '%2F'"),
3233 * These are default configuration directives that mpms can/should
3234 * pay attention to. If an mpm wishes to use these, they should
3235 * #defined them in mpm.h.
3237 #ifdef AP_MPM_WANT_SET_PIDFILE
3238 AP_INIT_TAKE1("PidFile", ap_mpm_set_pidfile, NULL, RSRC_CONF,
3239 "A file for logging the server process ID"),
3241 #ifdef AP_MPM_WANT_SET_SCOREBOARD
3242 AP_INIT_TAKE1("ScoreBoardFile", ap_mpm_set_scoreboard, NULL, RSRC_CONF,
3243 "A file for Apache to maintain runtime process management information"),
3245 #ifdef AP_MPM_WANT_SET_LOCKFILE
3246 AP_INIT_TAKE1("LockFile", ap_mpm_set_lockfile, NULL, RSRC_CONF,
3247 "The lockfile used when Apache needs to lock the accept() call"),
3249 #ifdef AP_MPM_WANT_SET_MAX_REQUESTS
3250 AP_INIT_TAKE1("MaxRequestsPerChild", ap_mpm_set_max_requests, NULL, RSRC_CONF,
3251 "Maximum number of requests a particular child serves before dying."),
3253 #ifdef AP_MPM_WANT_SET_COREDUMPDIR
3254 AP_INIT_TAKE1("CoreDumpDirectory", ap_mpm_set_coredumpdir, NULL, RSRC_CONF,
3255 "The location of the directory Apache changes to before dumping core"),
3257 #ifdef AP_MPM_WANT_SET_ACCEPT_LOCK_MECH
3258 AP_INIT_TAKE1("AcceptMutex", ap_mpm_set_accept_lock_mech, NULL, RSRC_CONF,
3259 ap_valid_accept_mutex_string),
3261 #ifdef AP_MPM_WANT_SET_MAX_MEM_FREE
3262 AP_INIT_TAKE1("MaxMemFree", ap_mpm_set_max_mem_free, NULL, RSRC_CONF,
3263 "Maximum number of 1k blocks a particular childs allocator may hold."),
3268 /*****************************************************************
3270 * Core handlers for various phases of server operation...
3273 AP_DECLARE_NONSTD(int) ap_core_translate(request_rec *r)
3275 void *sconf = r->server->module_config;
3276 core_server_config *conf = ap_get_module_config(sconf, &core_module);
3278 /* XXX this seems too specific, this should probably become
3279 * some general-case test
3282 return HTTP_FORBIDDEN;
3284 if (!r->uri || ((r->uri[0] != '/') && strcmp(r->uri, "*"))) {
3285 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3286 "Invalid URI in request %s", r->the_request);
3287 return HTTP_BAD_REQUEST;
3291 && !strncmp(r->uri, r->server->path, r->server->pathlen)
3292 && (r->server->path[r->server->pathlen - 1] == '/'
3293 || r->uri[r->server->pathlen] == '/'
3294 || r->uri[r->server->pathlen] == '\0'))
3296 /* skip all leading /'s (e.g. http://localhost///foo)
3297 * so we are looking at only the relative path.
3299 char *path = r->uri + r->server->pathlen;
3300 while (*path == '/') {
3303 if (apr_filepath_merge(&r->filename, conf->ap_document_root, path,
3304 APR_FILEPATH_TRUENAME
3305 | APR_FILEPATH_SECUREROOT, r->pool)
3307 return HTTP_FORBIDDEN;
3309 r->canonical_filename = r->filename;
3313 * Make sure that we do not mess up the translation by adding two
3314 * /'s in a row. This happens under windows when the document
3315 * root ends with a /
3317 /* skip all leading /'s (e.g. http://localhost///foo)
3318 * so we are looking at only the relative path.
3320 char *path = r->uri;
3321 while (*path == '/') {
3324 if (apr_filepath_merge(&r->filename, conf->ap_document_root, path,
3325 APR_FILEPATH_TRUENAME
3326 | APR_FILEPATH_SECUREROOT, r->pool)
3328 return HTTP_FORBIDDEN;
3330 r->canonical_filename = r->filename;
3336 /*****************************************************************
3338 * Test the filesystem name through directory_walk and file_walk
3340 static int core_map_to_storage(request_rec *r)
3344 if ((access_status = ap_directory_walk(r))) {
3345 return access_status;
3348 if ((access_status = ap_file_walk(r))) {
3349 return access_status;
3356 static int do_nothing(request_rec *r) { return OK; }
3359 static int core_override_type(request_rec *r)
3361 core_dir_config *conf =
3362 (core_dir_config *)ap_get_module_config(r->per_dir_config,
3365 /* Check for overrides with ForceType / SetHandler
3367 if (conf->mime_type && strcmp(conf->mime_type, "none"))
3368 ap_set_content_type(r, (char*) conf->mime_type);
3370 if (conf->handler && strcmp(conf->handler, "none"))
3371 r->handler = conf->handler;
3373 /* Deal with the poor soul who is trying to force path_info to be
3374 * accepted within the core_handler, where they will let the subreq
3375 * address its contents. This is toggled by the user in the very
3376 * beginning of the fixup phase, so modules should override the user's
3377 * discretion in their own module fixup phase. It is tristate, if
3378 * the user doesn't specify, the result is 2 (which the module may
3379 * interpret to its own customary behavior.) It won't be touched
3380 * if the value is no longer undefined (2), so any module changing
3381 * the value prior to the fixup phase OVERRIDES the user's choice.
3383 if ((r->used_path_info == AP_REQ_DEFAULT_PATH_INFO)
3384 && (conf->accept_path_info != 3)) {
3385 r->used_path_info = conf->accept_path_info;
3393 static int default_handler(request_rec *r)
3395 conn_rec *c = r->connection;
3396 apr_bucket_brigade *bb;
3400 apr_file_t *fd = NULL;
3401 apr_status_t status;
3402 /* XXX if/when somebody writes a content-md5 filter we either need to
3403 * remove this support or coordinate when to use the filter vs.
3404 * when to use this code
3405 * The current choice of when to compute the md5 here matches the 1.3
3406 * support fairly closely (unlike 1.3, we don't handle computing md5
3407 * when the charset is translated).
3409 int bld_content_md5;
3411 d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
3413 bld_content_md5 = (d->content_md5 & 1)
3414 && r->output_filters->frec->ftype != AP_FTYPE_RESOURCE;
3416 ap_allow_standard_methods(r, MERGE_ALLOW, M_GET, M_OPTIONS, M_POST, -1);
3418 /* If filters intend to consume the request body, they must
3419 * register an InputFilter to slurp the contents of the POST
3420 * data from the POST input stream. It no longer exists when
3421 * the output filters are invoked by the default handler.
3423 if ((errstatus = ap_discard_request_body(r)) != OK) {
3427 if (r->method_number == M_GET || r->method_number == M_POST) {
3428 if (r->finfo.filetype == 0) {
3429 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3430 "File does not exist: %s", r->filename);
3431 return HTTP_NOT_FOUND;
3434 /* Don't try to serve a dir. Some OSs do weird things with
3437 if (r->finfo.filetype == APR_DIR) {
3438 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3439 "Attempt to serve directory: %s", r->filename);
3440 return HTTP_NOT_FOUND;
3443 if ((r->used_path_info != AP_REQ_ACCEPT_PATH_INFO) &&
3444 r->path_info && *r->path_info)
3446 /* default to reject */
3447 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3448 "File does not exist: %s",
3449 apr_pstrcat(r->pool, r->filename, r->path_info, NULL));
3450 return HTTP_NOT_FOUND;
3453 /* We understood the (non-GET) method, but it might not be legal for
3454 this particular resource. Check to see if the 'deliver_script'
3455 flag is set. If so, then we go ahead and deliver the file since
3456 it isn't really content (only GET normally returns content).
3458 Note: based on logic further above, the only possible non-GET
3459 method at this point is POST. In the future, we should enable
3460 script delivery for all methods. */
3461 if (r->method_number != M_GET) {
3462 core_request_config *req_cfg;
3464 req_cfg = ap_get_module_config(r->request_config, &core_module);
3465 if (!req_cfg->deliver_script) {
3466 /* The flag hasn't been set for this request. Punt. */
3467 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3468 "This resource does not accept the %s method.",
3470 return HTTP_METHOD_NOT_ALLOWED;
3475 if ((status = apr_file_open(&fd, r->filename, APR_READ | APR_BINARY
3476 #if APR_HAS_SENDFILE
3477 | ((d->enable_sendfile == ENABLE_SENDFILE_OFF)
3478 ? 0 : APR_SENDFILE_ENABLED)
3480 , 0, r->pool)) != APR_SUCCESS) {
3481 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r,
3482 "file permissions deny server access: %s", r->filename);
3483 return HTTP_FORBIDDEN;
3486 ap_update_mtime(r, r->finfo.mtime);
3487 ap_set_last_modified(r);
3489 apr_table_setn(r->headers_out, "Accept-Ranges", "bytes");
3490 ap_set_content_length(r, r->finfo.size);
3491 if ((errstatus = ap_meets_conditions(r)) != OK) {
3496 if (bld_content_md5) {
3497 apr_table_setn(r->headers_out, "Content-MD5",
3498 ap_md5digest(r->pool, fd));
3501 bb = apr_brigade_create(r->pool, c->bucket_alloc);
3502 #if APR_HAS_SENDFILE && APR_HAS_LARGE_FILES
3503 if ((d->enable_sendfile != ENABLE_SENDFILE_OFF) &&
3504 (r->finfo.size > AP_MAX_SENDFILE)) {
3505 /* APR_HAS_LARGE_FILES issue; must split into mutiple buckets,
3506 * no greater than MAX(apr_size_t), and more granular than that
3507 * in case the brigade code/filters attempt to read it directly.
3509 apr_off_t fsize = r->finfo.size;
3510 e = apr_bucket_file_create(fd, 0, AP_MAX_SENDFILE, r->pool,
3512 while (fsize > AP_MAX_SENDFILE) {
3514 apr_bucket_copy(e, &ce);
3515 APR_BRIGADE_INSERT_TAIL(bb, ce);
3516 e->start += AP_MAX_SENDFILE;
3517 fsize -= AP_MAX_SENDFILE;
3519 e->length = (apr_size_t)fsize; /* Resize just the last bucket */
3523 e = apr_bucket_file_create(fd, 0, (apr_size_t)r->finfo.size,
3524 r->pool, c->bucket_alloc);
3527 if (d->enable_mmap == ENABLE_MMAP_OFF) {
3528 (void)apr_bucket_file_enable_mmap(e, 0);
3531 APR_BRIGADE_INSERT_TAIL(bb, e);
3532 e = apr_bucket_eos_create(c->bucket_alloc);
3533 APR_BRIGADE_INSERT_TAIL(bb, e);
3535 return ap_pass_brigade(r->output_filters, bb);
3537 else { /* unusual method (not GET or POST) */
3538 if (r->method_number == M_INVALID) {
3539 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3540 "Invalid method in request %s", r->the_request);
3541 return HTTP_NOT_IMPLEMENTED;
3544 if (r->method_number == M_OPTIONS) {
3545 return ap_send_http_options(r);
3547 return HTTP_METHOD_NOT_ALLOWED;
3551 typedef struct net_time_filter_ctx {
3554 } net_time_filter_ctx_t;
3555 static int net_time_filter(ap_filter_t *f, apr_bucket_brigade *b,
3556 ap_input_mode_t mode, apr_read_type_e block,
3557 apr_off_t readbytes)
3559 net_time_filter_ctx_t *ctx = f->ctx;
3560 int keptalive = f->c->keepalive == AP_CONN_KEEPALIVE;
3563 f->ctx = ctx = apr_palloc(f->r->pool, sizeof(*ctx));
3564 ctx->first_line = 1;
3565 ctx->csd = ap_get_module_config(f->c->conn_config, &core_module);
3568 if (mode != AP_MODE_INIT && mode != AP_MODE_EATCRLF) {
3569 if (ctx->first_line) {
3570 apr_socket_timeout_set(ctx->csd,
3572 ? f->c->base_server->keep_alive_timeout
3573 : f->c->base_server->timeout);
3574 ctx->first_line = 0;
3578 apr_socket_timeout_set(ctx->csd, f->c->base_server->timeout);
3582 return ap_get_brigade(f->next, b, mode, block, readbytes);
3586 * Remove all zero length buckets from the brigade.
3588 #define BRIGADE_NORMALIZE(b) \
3590 apr_bucket *e = APR_BRIGADE_FIRST(b); \
3592 if (e->length == 0 && !APR_BUCKET_IS_METADATA(e)) { \
3594 d = APR_BUCKET_NEXT(e); \
3595 apr_bucket_delete(e); \
3598 e = APR_BUCKET_NEXT(e); \
3599 } while (!APR_BRIGADE_EMPTY(b) && (e != APR_BRIGADE_SENTINEL(b))); \
3602 static int core_input_filter(ap_filter_t *f, apr_bucket_brigade *b,
3603 ap_input_mode_t mode, apr_read_type_e block,
3604 apr_off_t readbytes)
3608 core_net_rec *net = f->ctx;
3609 core_ctx_t *ctx = net->in_ctx;
3613 if (mode == AP_MODE_INIT) {
3615 * this mode is for filters that might need to 'initialize'
3616 * a connection before reading request data from a client.
3617 * NNTP over SSL for example needs to handshake before the
3618 * server sends the welcome message.
3619 * such filters would have changed the mode before this point
3620 * is reached. however, protocol modules such as NNTP should
3621 * not need to know anything about SSL. given the example, if
3622 * SSL is not in the filter chain, AP_MODE_INIT is a noop.
3629 ctx = apr_pcalloc(f->c->pool, sizeof(*ctx));
3630 ctx->b = apr_brigade_create(f->c->pool, f->c->bucket_alloc);
3632 /* seed the brigade with the client socket. */
3633 e = apr_bucket_socket_create(net->client_socket, f->c->bucket_alloc);
3634 APR_BRIGADE_INSERT_TAIL(ctx->b, e);
3637 else if (APR_BRIGADE_EMPTY(ctx->b)) {
3641 /* ### This is bad. */
3642 BRIGADE_NORMALIZE(ctx->b);
3644 /* check for empty brigade again *AFTER* BRIGADE_NORMALIZE()
3645 * If we have lost our socket bucket (see above), we are EOF.
3647 * Ideally, this should be returning SUCCESS with EOS bucket, but
3648 * some higher-up APIs (spec. read_request_line via ap_rgetline)
3649 * want an error code. */
3650 if (APR_BRIGADE_EMPTY(ctx->b)) {
3654 if (mode == AP_MODE_GETLINE) {
3655 /* we are reading a single LF line, e.g. the HTTP headers */
3656 rv = apr_brigade_split_line(b, ctx->b, block, HUGE_STRING_LEN);
3657 /* We should treat EAGAIN here the same as we do for EOF (brigade is
3658 * empty). We do this by returning whatever we have read. This may
3659 * or may not be bogus, but is consistent (for now) with EOF logic.
3661 if (APR_STATUS_IS_EAGAIN(rv)) {
3667 /* ### AP_MODE_PEEK is a horrific name for this mode because we also
3668 * eat any CRLFs that we see. That's not the obvious intention of
3669 * this mode. Determine whether anyone actually uses this or not. */
3670 if (mode == AP_MODE_EATCRLF) {
3674 /* The purpose of this loop is to ignore any CRLF (or LF) at the end
3675 * of a request. Many browsers send extra lines at the end of POST
3676 * requests. We use the PEEK method to determine if there is more
3677 * data on the socket, so that we know if we should delay sending the
3678 * end of one request until we have served the second request in a
3679 * pipelined situation. We don't want to actually delay sending a
3680 * response if the server finds a CRLF (or LF), becuause that doesn't
3681 * mean that there is another request, just a blank line.
3684 if (APR_BRIGADE_EMPTY(ctx->b))
3687 e = APR_BRIGADE_FIRST(ctx->b);
3689 rv = apr_bucket_read(e, &str, &len, APR_NONBLOCK_READ);
3691 if (rv != APR_SUCCESS)
3695 while (c < str + len) {
3696 if (*c == APR_ASCII_LF)
3698 else if (*c == APR_ASCII_CR && *(c + 1) == APR_ASCII_LF)
3704 /* If we reach here, we were a bucket just full of CRLFs, so
3705 * just toss the bucket. */
3706 /* FIXME: Is this the right thing to do in the core? */
3707 apr_bucket_delete(e);
3712 /* If mode is EXHAUSTIVE, we want to just read everything until the end
3713 * of the brigade, which in this case means the end of the socket.
3714 * To do this, we attach the brigade that has currently been setaside to
3715 * the brigade that was passed down, and send that brigade back.
3717 * NOTE: This is VERY dangerous to use, and should only be done with
3718 * extreme caution. However, the Perchild MPM needs this feature
3719 * if it is ever going to work correctly again. With this, the Perchild
3720 * MPM can easily request the socket and all data that has been read,
3721 * which means that it can pass it to the correct child process.
3723 if (mode == AP_MODE_EXHAUSTIVE) {
3726 /* Tack on any buckets that were set aside. */
3727 APR_BRIGADE_CONCAT(b, ctx->b);
3729 /* Since we've just added all potential buckets (which will most
3730 * likely simply be the socket bucket) we know this is the end,
3731 * so tack on an EOS too. */
3732 /* We have read until the brigade was empty, so we know that we
3734 e = apr_bucket_eos_create(f->c->bucket_alloc);
3735 APR_BRIGADE_INSERT_TAIL(b, e);
3739 /* read up to the amount they specified. */
3740 if (mode == AP_MODE_READBYTES || mode == AP_MODE_SPECULATIVE) {
3742 apr_bucket_brigade *newbb;
3744 AP_DEBUG_ASSERT(readbytes > 0);
3746 e = APR_BRIGADE_FIRST(ctx->b);
3747 rv = apr_bucket_read(e, &str, &len, block);
3749 if (APR_STATUS_IS_EAGAIN(rv)) {
3752 else if (rv != APR_SUCCESS) {
3755 else if (block == APR_BLOCK_READ && len == 0) {
3756 /* We wanted to read some bytes in blocking mode. We read
3757 * 0 bytes. Hence, we now assume we are EOS.
3759 * When we are in normal mode, return an EOS bucket to the
3761 * When we are in speculative mode, leave ctx->b empty, so
3762 * that the next call returns an EOS bucket.
3764 apr_bucket_delete(e);
3766 if (mode == AP_MODE_READBYTES) {
3767 e = apr_bucket_eos_create(f->c->bucket_alloc);
3768 APR_BRIGADE_INSERT_TAIL(b, e);
3773 /* We can only return at most what we read. */
3774 if (len < readbytes) {
3778 rv = apr_brigade_partition(ctx->b, readbytes, &e);
3779 if (rv != APR_SUCCESS) {
3783 /* Must do split before CONCAT */
3784 newbb = apr_brigade_split(ctx->b, e);
3786 if (mode == AP_MODE_READBYTES) {
3787 APR_BRIGADE_CONCAT(b, ctx->b);
3789 else if (mode == AP_MODE_SPECULATIVE) {
3790 apr_bucket *copy_bucket;
3791 APR_BRIGADE_FOREACH(e, ctx->b) {
3792 rv = apr_bucket_copy(e, ©_bucket);
3793 if (rv != APR_SUCCESS) {
3796 APR_BRIGADE_INSERT_TAIL(b, copy_bucket);
3800 /* Take what was originally there and place it back on ctx->b */
3801 APR_BRIGADE_CONCAT(ctx->b, newbb);
3806 /* Default filter. This filter should almost always be used. Its only job
3807 * is to send the headers if they haven't already been sent, and then send
3810 #define MAX_IOVEC_TO_WRITE 16
3812 /* Optional function coming from mod_logio, used for logging of output
3815 static APR_OPTIONAL_FN_TYPE(ap_logio_add_bytes_out) *logio_add_bytes_out;
3817 static apr_status_t core_output_filter(ap_filter_t *f, apr_bucket_brigade *b)
3820 apr_bucket_brigade *more;
3822 core_net_rec *net = f->ctx;
3823 core_output_filter_ctx_t *ctx = net->out_ctx;
3824 apr_read_type_e eblock = APR_NONBLOCK_READ;
3825 apr_pool_t *input_pool = b->p;
3828 ctx = apr_pcalloc(c->pool, sizeof(*ctx));
3832 /* If we have a saved brigade, concatenate the new brigade to it */
3834 APR_BRIGADE_CONCAT(ctx->b, b);
3839 /* Perform multiple passes over the brigade, sending batches of output
3840 to the connection. */
3841 while (b && !APR_BRIGADE_EMPTY(b)) {
3842 apr_size_t nbytes = 0;
3843 apr_bucket *last_e = NULL; /* initialized for debugging */
3846 /* one group of iovecs per pass over the brigade */
3847 apr_size_t nvec = 0;
3848 apr_size_t nvec_trailers = 0;
3849 struct iovec vec[MAX_IOVEC_TO_WRITE];
3850 struct iovec vec_trailers[MAX_IOVEC_TO_WRITE];
3852 /* one file per pass over the brigade */
3853 apr_file_t *fd = NULL;
3854 apr_size_t flen = 0;
3855 apr_off_t foffset = 0;
3857 /* keep track of buckets that we've concatenated
3858 * to avoid small writes
3860 apr_bucket *last_merged_bucket = NULL;
3862 /* tail of brigade if we need another pass */
3865 /* Iterate over the brigade: collect iovecs and/or a file */
3866 APR_BRIGADE_FOREACH(e, b) {
3867 /* keep track of the last bucket processed */
3869 if (APR_BUCKET_IS_EOS(e)) {
3872 if (APR_BUCKET_IS_FLUSH(e)) {
3873 if (e != APR_BRIGADE_LAST(b)) {
3874 more = apr_brigade_split(b, APR_BUCKET_NEXT(e));
3879 /* It doesn't make any sense to use sendfile for a file bucket
3880 * that represents 10 bytes.
3882 else if (APR_BUCKET_IS_FILE(e)
3883 && (e->length >= AP_MIN_SENDFILE_BYTES)) {
3884 apr_bucket_file *a = e->data;
3886 /* We can't handle more than one file bucket at a time
3887 * so we split here and send the file we have already
3891 more = apr_brigade_split(b, e);
3903 rv = apr_bucket_read(e, &str, &n, eblock);
3904 if (APR_STATUS_IS_EAGAIN(rv)) {
3905 /* send what we have so far since we shouldn't expect more
3906 * output for a while... next time we read, block
3908 more = apr_brigade_split(b, e);
3909 eblock = APR_BLOCK_READ;
3912 eblock = APR_NONBLOCK_READ;
3915 if (nvec == MAX_IOVEC_TO_WRITE) {
3916 /* woah! too many. buffer them up, for use later. */
3917 apr_bucket *temp, *next;
3918 apr_bucket_brigade *temp_brig;
3920 if (nbytes >= AP_MIN_BYTES_TO_WRITE) {
3921 /* We have enough data in the iovec
3922 * to justify doing a writev
3924 more = apr_brigade_split(b, e);
3928 /* Create a temporary brigade as a means
3929 * of concatenating a bunch of buckets together
3931 if (last_merged_bucket) {
3932 /* If we've concatenated together small
3933 * buckets already in a previous pass,
3934 * the initial buckets in this brigade
3935 * are heap buckets that may have extra
3936 * space left in them (because they
3937 * were created by apr_brigade_write()).
3938 * We can take advantage of this by
3939 * building the new temp brigade out of
3940 * these buckets, so that the content
3941 * in them doesn't have to be copied again.
3943 apr_bucket_brigade *bb;
3944 bb = apr_brigade_split(b,
3945 APR_BUCKET_NEXT(last_merged_bucket));
3950 temp_brig = apr_brigade_create(f->c->pool,
3951 f->c->bucket_alloc);
3954 temp = APR_BRIGADE_FIRST(b);
3957 rv = apr_bucket_read(temp, &str, &n, APR_BLOCK_READ);
3958 apr_brigade_write(temp_brig, NULL, NULL, str, n);
3960 temp = APR_BUCKET_NEXT(temp);
3961 apr_bucket_delete(d);
3966 temp = APR_BRIGADE_FIRST(temp_brig);
3967 APR_BUCKET_REMOVE(temp);
3968 APR_BRIGADE_INSERT_HEAD(b, temp);
3969 apr_bucket_read(temp, &str, &n, APR_BLOCK_READ);
3970 vec[nvec].iov_base = (char*) str;
3971 vec[nvec].iov_len = n;
3974 /* Just in case the temporary brigade has
3975 * multiple buckets, recover the rest of
3976 * them and put them in the brigade that
3979 for (next = APR_BRIGADE_FIRST(temp_brig);
3980 next != APR_BRIGADE_SENTINEL(temp_brig);
3981 next = APR_BRIGADE_FIRST(temp_brig)) {
3982 APR_BUCKET_REMOVE(next);
3983 APR_BUCKET_INSERT_AFTER(temp, next);
3985 apr_bucket_read(next, &str, &n,
3987 vec[nvec].iov_base = (char*) str;
3988 vec[nvec].iov_len = n;
3992 apr_brigade_destroy(temp_brig);
3994 last_merged_bucket = temp;
3999 vec[nvec].iov_base = (char*) str;
4000 vec[nvec].iov_len = n;
4005 /* The bucket is a trailer to a file bucket */
4007 if (nvec_trailers == MAX_IOVEC_TO_WRITE) {
4008 /* woah! too many. stop now. */
4009 more = apr_brigade_split(b, e);
4013 vec_trailers[nvec_trailers].iov_base = (char*) str;
4014 vec_trailers[nvec_trailers].iov_len = n;
4024 /* Completed iterating over the brigade, now determine if we want
4025 * to buffer the brigade or send the brigade out on the network.
4027 * Save if we haven't accumulated enough bytes to send, and:
4029 * 1) we didn't see a file, we don't have more passes over the
4030 * brigade to perform, AND we didn't stop at a FLUSH bucket.
4031 * (IOW, we will save plain old bytes such as HTTP headers)
4033 * 2) we hit the EOS and have a keep-alive connection
4034 * (IOW, this response is a bit more complex, but we save it
4035 * with the hope of concatenating with another response)
4037 if (nbytes + flen < AP_MIN_BYTES_TO_WRITE
4038 && ((!fd && !more && !APR_BUCKET_IS_FLUSH(last_e))
4039 || (APR_BUCKET_IS_EOS(last_e)
4040 && c->keepalive == AP_CONN_KEEPALIVE))) {
4042 /* NEVER save an EOS in here. If we are saving a brigade with
4043 * an EOS bucket, then we are doing keepalive connections, and
4044 * we want to process to second request fully.
4046 if (APR_BUCKET_IS_EOS(last_e)) {
4048 int file_bucket_saved = 0;
4049 apr_bucket_delete(last_e);
4050 for (bucket = APR_BRIGADE_FIRST(b);
4051 bucket != APR_BRIGADE_SENTINEL(b);
4052 bucket = APR_BUCKET_NEXT(bucket)) {
4054 /* Do a read on each bucket to pull in the
4055 * data from pipe and socket buckets, so
4056 * that we don't leave their file descriptors
4057 * open indefinitely. Do the same for file
4058 * buckets, with one exception: allow the
4059 * first file bucket in the brigade to remain
4060 * a file bucket, so that we don't end up
4061 * doing an mmap+memcpy every time a client
4062 * requests a <8KB file over a keepalive
4065 if (APR_BUCKET_IS_FILE(bucket) && !file_bucket_saved) {
4066 file_bucket_saved = 1;
4071 rv = apr_bucket_read(bucket, &buf, &len,
4073 if (rv != APR_SUCCESS) {
4074 ap_log_error(APLOG_MARK, APLOG_ERR, rv,
4075 c->base_server, "core_output_filter:"
4076 " Error reading from bucket.");
4077 return HTTP_INTERNAL_SERVER_ERROR;
4082 if (!ctx->deferred_write_pool) {
4083 apr_pool_create(&ctx->deferred_write_pool, c->pool);
4085 ap_save_brigade(f, &ctx->b, &b, ctx->deferred_write_pool);
4092 apr_size_t bytes_sent;
4094 #if APR_HAS_SENDFILE
4095 apr_int32_t flags = 0;
4098 memset(&hdtr, '\0', sizeof(hdtr));
4100 hdtr.numheaders = nvec;
4104 if (nvec_trailers) {
4105 hdtr.numtrailers = nvec_trailers;
4106 hdtr.trailers = vec_trailers;
4109 #if APR_HAS_SENDFILE
4110 if (apr_file_flags_get(fd) & APR_SENDFILE_ENABLED) {
4112 if (c->keepalive == AP_CONN_CLOSE && APR_BUCKET_IS_EOS(last_e)) {
4113 /* Prepare the socket to be reused */
4114 flags |= APR_SENDFILE_DISCONNECT_SOCKET;
4117 rv = sendfile_it_all(net, /* the network information */
4118 fd, /* the file to send */
4119 &hdtr, /* header and trailer iovecs */
4120 foffset, /* offset in the file to begin
4122 flen, /* length of file */
4123 nbytes + flen, /* total length including
4125 &bytes_sent, /* how many bytes were
4127 flags); /* apr_sendfile flags */
4129 if (logio_add_bytes_out && bytes_sent > 0)
4130 logio_add_bytes_out(c, bytes_sent);
4135 rv = emulate_sendfile(net, fd, &hdtr, foffset, flen,
4138 if (logio_add_bytes_out && bytes_sent > 0)
4139 logio_add_bytes_out(c, bytes_sent);
4145 apr_size_t bytes_sent;
4147 rv = writev_it_all(net->client_socket,
4149 nbytes, &bytes_sent);
4151 if (logio_add_bytes_out && bytes_sent > 0)
4152 logio_add_bytes_out(c, bytes_sent);
4155 apr_brigade_destroy(b);
4157 /* drive cleanups for resources which were set aside
4158 * this may occur before or after termination of the request which
4159 * created the resource
4161 if (ctx->deferred_write_pool) {
4162 if (more && more->p == ctx->deferred_write_pool) {
4163 /* "more" belongs to the deferred_write_pool,
4164 * which is about to be cleared.
4166 if (APR_BRIGADE_EMPTY(more)) {
4170 /* uh oh... change more's lifetime
4171 * to the input brigade's lifetime
4173 apr_bucket_brigade *tmp_more = more;
4175 ap_save_brigade(f, &more, &tmp_more, input_pool);
4178 apr_pool_clear(ctx->deferred_write_pool);
4181 if (rv != APR_SUCCESS) {
4182 ap_log_error(APLOG_MARK, APLOG_INFO, rv, c->base_server,
4183 "core_output_filter: writing data to the network");
4186 apr_brigade_destroy(more);
4188 /* No need to check for SUCCESS, we did that above. */
4189 if (!APR_STATUS_IS_EAGAIN(rv)) {
4193 /* The client has aborted, but the request was successful. We
4194 * will report success, and leave it to the access and error
4195 * logs to note that the connection was aborted.
4202 } /* end while () */
4207 static int core_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
4209 logio_add_bytes_out = APR_RETRIEVE_OPTIONAL_FN(ap_logio_add_bytes_out);
4210 ident_lookup = APR_RETRIEVE_OPTIONAL_FN(ap_ident_lookup);
4212 ap_set_version(pconf);
4213 ap_setup_make_content_type(pconf);
4217 static void core_insert_filter(request_rec *r)
4219 core_dir_config *conf = (core_dir_config *)
4220 ap_get_module_config(r->per_dir_config,
4222 const char *filter, *filters = conf->output_filters;
4225 while (*filters && (filter = ap_getword(r->pool, &filters, ';'))) {
4226 ap_add_output_filter(filter, NULL, r, r->connection);
4230 filters = conf->input_filters;
4232 while (*filters && (filter = ap_getword(r->pool, &filters, ';'))) {
4233 ap_add_input_filter(filter, NULL, r, r->connection);
4238 static apr_size_t num_request_notes = AP_NUM_STD_NOTES;
4240 static apr_status_t reset_request_notes(void *dummy)
4242 num_request_notes = AP_NUM_STD_NOTES;
4246 AP_DECLARE(apr_size_t) ap_register_request_note(void)
4248 apr_pool_cleanup_register(apr_hook_global_pool, NULL, reset_request_notes,
4249 apr_pool_cleanup_null);
4250 return num_request_notes++;
4253 AP_DECLARE(void **) ap_get_request_note(request_rec *r, apr_size_t note_num)
4255 core_request_config *req_cfg;
4257 if (note_num >= num_request_notes) {
4261 req_cfg = (core_request_config *)
4262 ap_get_module_config(r->request_config, &core_module);
4268 return &(req_cfg->notes[note_num]);
4271 static int core_create_req(request_rec *r)
4273 /* Alloc the config struct and the array of request notes in
4274 * a single block for efficiency
4276 core_request_config *req_cfg;
4278 req_cfg = apr_pcalloc(r->pool, sizeof(core_request_config) +
4279 sizeof(void *) * num_request_notes);
4280 req_cfg->notes = (void **)((char *)req_cfg + sizeof(core_request_config));
4282 /* ### temporarily enable script delivery as the default */
4283 req_cfg->deliver_script = 1;
4286 core_request_config *main_req_cfg = (core_request_config *)
4287 ap_get_module_config(r->main->request_config, &core_module);
4288 req_cfg->bb = main_req_cfg->bb;
4291 req_cfg->bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
4293 ap_add_input_filter_handle(ap_net_time_filter_handle,
4294 NULL, r, r->connection);
4298 ap_set_module_config(r->request_config, &core_module, req_cfg);
4300 /* Begin by presuming any module can make its own path_info assumptions,
4301 * until some module interjects and changes the value.
4303 r->used_path_info = AP_REQ_DEFAULT_PATH_INFO;
4308 static int core_create_proxy_req(request_rec *r, request_rec *pr)
4310 return core_create_req(pr);
4313 static conn_rec *core_create_conn(apr_pool_t *ptrans, server_rec *server,
4314 apr_socket_t *csd, long id, void *sbh,
4315 apr_bucket_alloc_t *alloc)
4318 conn_rec *c = (conn_rec *) apr_pcalloc(ptrans, sizeof(conn_rec));
4321 (void)ap_update_child_status(c->sbh, SERVER_BUSY_READ, (request_rec *)NULL);
4323 /* Got a connection structure, so initialize what fields we can
4324 * (the rest are zeroed out by pcalloc).
4326 c->conn_config = ap_create_conn_config(ptrans);
4327 c->notes = apr_table_make(ptrans, 5);
4330 if ((rv = apr_socket_addr_get(&c->local_addr, APR_LOCAL, csd))
4332 ap_log_error(APLOG_MARK, APLOG_INFO, rv, server,
4333 "apr_socket_addr_get(APR_LOCAL)");
4334 apr_socket_close(csd);
4338 apr_sockaddr_ip_get(&c->local_ip, c->local_addr);
4339 if ((rv = apr_socket_addr_get(&c->remote_addr, APR_REMOTE, csd))
4341 ap_log_error(APLOG_MARK, APLOG_INFO, rv, server,
4342 "apr_socket_addr_get(APR_REMOTE)");
4343 apr_socket_close(csd);
4347 apr_sockaddr_ip_get(&c->remote_ip, c->remote_addr);
4348 c->base_server = server;
4351 c->bucket_alloc = alloc;
4356 static int core_pre_connection(conn_rec *c, void *csd)
4358 core_net_rec *net = apr_palloc(c->pool, sizeof(*net));
4360 #ifdef AP_MPM_DISABLE_NAGLE_ACCEPTED_SOCK
4361 /* BillS says perhaps this should be moved to the MPMs. Some OSes
4362 * allow listening socket attributes to be inherited by the
4363 * accept sockets which means this call only needs to be made
4364 * once on the listener
4366 ap_sock_disable_nagle(csd);
4370 net->out_ctx = NULL;
4371 net->client_socket = csd;
4373 ap_set_module_config(net->c->conn_config, &core_module, csd);
4374 ap_add_input_filter_handle(ap_core_input_filter_handle, net, NULL, net->c);
4375 ap_add_output_filter_handle(ap_core_output_filter_handle, net, NULL, net->c);
4379 static void register_hooks(apr_pool_t *p)
4381 /* create_connection and install_transport_filters are
4382 * hooks that should always be APR_HOOK_REALLY_LAST to give other
4383 * modules the opportunity to install alternate network transports
4384 * and stop other functions from being run.
4386 ap_hook_create_connection(core_create_conn, NULL, NULL,
4387 APR_HOOK_REALLY_LAST);
4388 ap_hook_pre_connection(core_pre_connection, NULL, NULL,
4389 APR_HOOK_REALLY_LAST);
4391 ap_hook_post_config(core_post_config,NULL,NULL,APR_HOOK_REALLY_FIRST);
4392 ap_hook_translate_name(ap_core_translate,NULL,NULL,APR_HOOK_REALLY_LAST);
4393 ap_hook_map_to_storage(core_map_to_storage,NULL,NULL,APR_HOOK_REALLY_LAST);
4394 ap_hook_open_logs(ap_open_logs,NULL,NULL,APR_HOOK_REALLY_FIRST);
4395 ap_hook_handler(default_handler,NULL,NULL,APR_HOOK_REALLY_LAST);
4396 /* FIXME: I suspect we can eliminate the need for these do_nothings - Ben */
4397 ap_hook_type_checker(do_nothing,NULL,NULL,APR_HOOK_REALLY_LAST);
4398 ap_hook_fixups(core_override_type,NULL,NULL,APR_HOOK_REALLY_FIRST);
4399 ap_hook_access_checker(do_nothing,NULL,NULL,APR_HOOK_REALLY_LAST);
4400 ap_hook_create_request(core_create_req, NULL, NULL, APR_HOOK_MIDDLE);
4401 APR_OPTIONAL_HOOK(proxy, create_req, core_create_proxy_req, NULL, NULL,
4403 ap_hook_pre_mpm(ap_create_scoreboard, NULL, NULL, APR_HOOK_MIDDLE);
4405 /* register the core's insert_filter hook and register core-provided
4408 ap_hook_insert_filter(core_insert_filter, NULL, NULL, APR_HOOK_MIDDLE);
4410 ap_core_input_filter_handle =
4411 ap_register_input_filter("CORE_IN", core_input_filter,
4412 NULL, AP_FTYPE_NETWORK);
4413 ap_net_time_filter_handle =
4414 ap_register_input_filter("NET_TIME", net_time_filter,
4415 NULL, AP_FTYPE_PROTOCOL);
4416 ap_content_length_filter_handle =
4417 ap_register_output_filter("CONTENT_LENGTH", ap_content_length_filter,
4418 NULL, AP_FTYPE_PROTOCOL);
4419 ap_core_output_filter_handle =
4420 ap_register_output_filter("CORE", core_output_filter,
4421 NULL, AP_FTYPE_NETWORK);
4422 ap_subreq_core_filter_handle =
4423 ap_register_output_filter("SUBREQ_CORE", ap_sub_req_output_filter,
4424 NULL, AP_FTYPE_CONTENT_SET);
4426 ap_register_output_filter("OLD_WRITE", ap_old_write_filter,
4427 NULL, AP_FTYPE_RESOURCE - 10);
4430 AP_DECLARE_DATA module core_module = {
4431 STANDARD20_MODULE_STUFF,
4432 create_core_dir_config, /* create per-directory config structure */
4433 merge_core_dir_configs, /* merge per-directory config structures */
4434 create_core_server_config, /* create per-server config structure */
4435 merge_core_server_configs, /* merge per-server config structures */
4436 core_cmds, /* command apr_table_t */
4437 register_hooks /* register hooks */