1 /* Copyright 2001-2004 The Apache Software Foundation
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
17 #include "apr_strings.h"
19 #include "apr_fnmatch.h"
21 #include "apr_thread_proc.h" /* for RLIMIT stuff */
22 #include "apr_hooks.h"
24 #define APR_WANT_IOVEC
25 #define APR_WANT_STRFUNC
26 #define APR_WANT_MEMFUNC
30 #include "ap_config.h"
32 #include "http_config.h"
33 #include "http_core.h"
34 #include "http_protocol.h" /* For index_of_response(). Grump. */
35 #include "http_request.h"
36 #include "http_vhost.h"
37 #include "http_main.h" /* For the default_handler below... */
40 #include "http_connection.h"
41 #include "apr_buckets.h"
42 #include "util_filter.h"
43 #include "util_ebcdic.h"
45 #include "mpm_common.h"
46 #include "scoreboard.h"
48 #include "mod_proxy.h"
49 #include "ap_listen.h"
51 /* LimitXMLRequestBody handling */
52 #define AP_LIMIT_UNSET ((long) -1)
53 #define AP_DEFAULT_LIMIT_XML_BODY ((size_t)1000000)
55 #define AP_MIN_SENDFILE_BYTES (256)
58 APR_HOOK_LINK(get_mgmt_items)
61 AP_IMPLEMENT_HOOK_RUN_ALL(int, get_mgmt_items,
62 (apr_pool_t *p, const char *val, apr_hash_t *ht),
63 (p, val, ht), OK, DECLINED)
65 /* Server core module... This module provides support for really basic
66 * server operations, including options and commands which control the
67 * operation of other modules. Consider this the bureaucracy module.
69 * The core module also defines handlers, etc., do handle just enough
70 * to allow a server with the core module ONLY to actually serve documents
71 * (though it slaps DefaultType on all of 'em); this was useful in testing,
72 * but may not be worth preserving.
74 * This file could almost be mod_core.c, except for the stuff which affects
75 * the http_conf_globals.
78 /* Handles for core filters */
79 AP_DECLARE_DATA ap_filter_rec_t *ap_subreq_core_filter_handle;
80 AP_DECLARE_DATA ap_filter_rec_t *ap_core_output_filter_handle;
81 AP_DECLARE_DATA ap_filter_rec_t *ap_content_length_filter_handle;
82 AP_DECLARE_DATA ap_filter_rec_t *ap_net_time_filter_handle;
83 AP_DECLARE_DATA ap_filter_rec_t *ap_core_input_filter_handle;
85 /* magic pointer for ErrorDocument xxx "default" */
86 static char errordocument_default;
88 static void *create_core_dir_config(apr_pool_t *a, char *dir)
90 core_dir_config *conf;
93 conf = (core_dir_config *)apr_pcalloc(a, sizeof(core_dir_config));
95 /* conf->r and conf->d[_*] are initialized by dirsection() or left NULL */
97 conf->opts = dir ? OPT_UNSET : OPT_UNSET|OPT_ALL;
98 conf->opts_add = conf->opts_remove = OPT_NONE;
99 conf->override = dir ? OR_UNSET : OR_UNSET|OR_ALL;
101 conf->content_md5 = 2;
102 conf->accept_path_info = 3;
104 conf->use_canonical_name = USE_CANONICAL_NAME_UNSET;
106 conf->hostname_lookups = HOSTNAME_LOOKUP_UNSET;
107 conf->satisfy = apr_palloc(a, sizeof(*conf->satisfy) * METHODS);
108 for (i = 0; i < METHODS; ++i) {
109 conf->satisfy[i] = SATISFY_NOSPEC;
113 conf->limit_cpu = NULL;
115 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
116 conf->limit_mem = NULL;
119 conf->limit_nproc = NULL;
122 conf->limit_req_body = 0;
123 conf->limit_xml_body = AP_LIMIT_UNSET;
124 conf->sec_file = apr_array_make(a, 2, sizeof(ap_conf_vector_t *));
126 conf->server_signature = srv_sig_unset;
128 conf->add_default_charset = ADD_DEFAULT_CHARSET_UNSET;
129 conf->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
131 /* Overriding all negotiation
133 conf->mime_type = NULL;
134 conf->handler = NULL;
135 conf->output_filters = NULL;
136 conf->input_filters = NULL;
139 * Flag for use of inodes in ETags.
141 conf->etag_bits = ETAG_UNSET;
142 conf->etag_add = ETAG_UNSET;
143 conf->etag_remove = ETAG_UNSET;
145 conf->enable_mmap = ENABLE_MMAP_UNSET;
146 conf->enable_sendfile = ENABLE_SENDFILE_UNSET;
147 conf->allow_encoded_slashes = 0;
153 * Overlay one hash table of ct_output_filters onto another
155 static void *merge_ct_filters(apr_pool_t *p,
158 const void *overlay_val,
159 const void *base_val,
162 ap_filter_rec_t *cur;
163 const ap_filter_rec_t *overlay_info = (const ap_filter_rec_t *)overlay_val;
164 const ap_filter_rec_t *base_info = (const ap_filter_rec_t *)base_val;
168 while (overlay_info) {
169 ap_filter_rec_t *new;
171 new = apr_pcalloc(p, sizeof(ap_filter_rec_t));
172 new->name = apr_pstrdup(p, overlay_info->name);
175 overlay_info = overlay_info->next;
182 /* We can't have dups. */
185 if (!strcasecmp(base_info->name, f->name)) {
194 f = apr_pcalloc(p, sizeof(ap_filter_rec_t));
195 f->name = apr_pstrdup(p, base_info->name);
200 base_info = base_info->next;
206 static void *merge_core_dir_configs(apr_pool_t *a, void *basev, void *newv)
208 core_dir_config *base = (core_dir_config *)basev;
209 core_dir_config *new = (core_dir_config *)newv;
210 core_dir_config *conf;
213 /* Create this conf by duplicating the base, replacing elements
214 * (or creating copies for merging) where new-> values exist.
216 conf = (core_dir_config *)apr_palloc(a, sizeof(core_dir_config));
217 memcpy(conf, base, sizeof(core_dir_config));
220 conf->d_is_fnmatch = new->d_is_fnmatch;
221 conf->d_components = new->d_components;
224 if (new->opts & OPT_UNSET) {
225 /* there was no explicit setting of new->opts, so we merge
226 * preserve the invariant (opts_add & opts_remove) == 0
228 conf->opts_add = (conf->opts_add & ~new->opts_remove) | new->opts_add;
229 conf->opts_remove = (conf->opts_remove & ~new->opts_add)
231 conf->opts = (conf->opts & ~conf->opts_remove) | conf->opts_add;
232 if ((base->opts & OPT_INCNOEXEC) && (new->opts & OPT_INCLUDES)) {
233 conf->opts = (conf->opts & ~OPT_INCNOEXEC) | OPT_INCLUDES;
237 /* otherwise we just copy, because an explicit opts setting
238 * overrides all earlier +/- modifiers
240 conf->opts = new->opts;
241 conf->opts_add = new->opts_add;
242 conf->opts_remove = new->opts_remove;
245 if (!(new->override & OR_UNSET)) {
246 conf->override = new->override;
249 if (new->ap_default_type) {
250 conf->ap_default_type = new->ap_default_type;
253 if (new->ap_auth_type) {
254 conf->ap_auth_type = new->ap_auth_type;
257 if (new->ap_auth_name) {
258 conf->ap_auth_name = new->ap_auth_name;
261 if (new->ap_requires) {
262 conf->ap_requires = new->ap_requires;
265 if (conf->response_code_strings == NULL) {
266 conf->response_code_strings = new->response_code_strings;
268 else if (new->response_code_strings != NULL) {
269 /* If we merge, the merge-result must have it's own array
271 conf->response_code_strings = apr_palloc(a,
272 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
273 memcpy(conf->response_code_strings, base->response_code_strings,
274 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
276 for (i = 0; i < RESPONSE_CODES; ++i) {
277 if (new->response_code_strings[i] != NULL) {
278 conf->response_code_strings[i] = new->response_code_strings[i];
282 /* Otherwise we simply use the base->response_code_strings array
285 if (new->hostname_lookups != HOSTNAME_LOOKUP_UNSET) {
286 conf->hostname_lookups = new->hostname_lookups;
289 if ((new->content_md5 & 2) == 0) {
290 conf->content_md5 = new->content_md5;
293 if (new->accept_path_info != 3) {
294 conf->accept_path_info = new->accept_path_info;
297 if (new->use_canonical_name != USE_CANONICAL_NAME_UNSET) {
298 conf->use_canonical_name = new->use_canonical_name;
302 if (new->limit_cpu) {
303 conf->limit_cpu = new->limit_cpu;
307 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
308 if (new->limit_mem) {
309 conf->limit_mem = new->limit_mem;
314 if (new->limit_nproc) {
315 conf->limit_nproc = new->limit_nproc;
319 if (new->limit_req_body) {
320 conf->limit_req_body = new->limit_req_body;
323 if (new->limit_xml_body != AP_LIMIT_UNSET)
324 conf->limit_xml_body = new->limit_xml_body;
326 conf->limit_xml_body = base->limit_xml_body;
328 if (!conf->sec_file) {
329 conf->sec_file = new->sec_file;
331 else if (new->sec_file) {
332 /* If we merge, the merge-result must have it's own array
334 conf->sec_file = apr_array_append(a, base->sec_file, new->sec_file);
336 /* Otherwise we simply use the base->sec_file array
339 for (i = 0; i < METHODS; ++i) {
340 if (new->satisfy[i] != SATISFY_NOSPEC) {
341 conf->satisfy[i] = new->satisfy[i];
345 if (new->server_signature != srv_sig_unset) {
346 conf->server_signature = new->server_signature;
349 if (new->add_default_charset != ADD_DEFAULT_CHARSET_UNSET) {
350 conf->add_default_charset = new->add_default_charset;
351 conf->add_default_charset_name = new->add_default_charset_name;
354 /* Overriding all negotiation
356 if (new->mime_type) {
357 conf->mime_type = new->mime_type;
361 conf->handler = new->handler;
364 if (new->output_filters) {
365 conf->output_filters = new->output_filters;
368 if (new->input_filters) {
369 conf->input_filters = new->input_filters;
372 if (conf->ct_output_filters && new->ct_output_filters) {
373 conf->ct_output_filters = apr_hash_merge(a,
374 new->ct_output_filters,
375 conf->ct_output_filters,
379 else if (new->ct_output_filters) {
380 conf->ct_output_filters = apr_hash_copy(a, new->ct_output_filters);
382 else if (conf->ct_output_filters) {
383 /* That memcpy above isn't enough. */
384 conf->ct_output_filters = apr_hash_copy(a, base->ct_output_filters);
388 * Now merge the setting of the FileETag directive.
390 if (new->etag_bits == ETAG_UNSET) {
392 (conf->etag_add & (~ new->etag_remove)) | new->etag_add;
394 (conf->opts_remove & (~ new->etag_add)) | new->etag_remove;
396 (conf->etag_bits & (~ conf->etag_remove)) | conf->etag_add;
399 conf->etag_bits = new->etag_bits;
400 conf->etag_add = new->etag_add;
401 conf->etag_remove = new->etag_remove;
404 if (conf->etag_bits != ETAG_NONE) {
405 conf->etag_bits &= (~ ETAG_NONE);
408 if (new->enable_mmap != ENABLE_MMAP_UNSET) {
409 conf->enable_mmap = new->enable_mmap;
412 if (new->enable_sendfile != ENABLE_SENDFILE_UNSET) {
413 conf->enable_sendfile = new->enable_sendfile;
416 conf->allow_encoded_slashes = new->allow_encoded_slashes;
421 static void *create_core_server_config(apr_pool_t *a, server_rec *s)
423 core_server_config *conf;
424 int is_virtual = s->is_virtual;
426 conf = (core_server_config *)apr_pcalloc(a, sizeof(core_server_config));
429 conf->gprof_dir = NULL;
432 conf->access_name = is_virtual ? NULL : DEFAULT_ACCESS_FNAME;
433 conf->ap_document_root = is_virtual ? NULL : DOCUMENT_LOCATION;
434 conf->sec_dir = apr_array_make(a, 40, sizeof(ap_conf_vector_t *));
435 conf->sec_url = apr_array_make(a, 40, sizeof(ap_conf_vector_t *));
437 /* recursion stopper */
438 conf->redirect_limit = 0; /* 0 == unset */
439 conf->subreq_limit = 0;
444 static void *merge_core_server_configs(apr_pool_t *p, void *basev, void *virtv)
446 core_server_config *base = (core_server_config *)basev;
447 core_server_config *virt = (core_server_config *)virtv;
448 core_server_config *conf;
450 conf = (core_server_config *)apr_palloc(p, sizeof(core_server_config));
451 memcpy(conf, virt, sizeof(core_server_config));
453 if (!conf->access_name) {
454 conf->access_name = base->access_name;
457 if (!conf->ap_document_root) {
458 conf->ap_document_root = base->ap_document_root;
461 conf->sec_dir = apr_array_append(p, base->sec_dir, virt->sec_dir);
462 conf->sec_url = apr_array_append(p, base->sec_url, virt->sec_url);
464 conf->redirect_limit = virt->redirect_limit
465 ? virt->redirect_limit
466 : base->redirect_limit;
468 conf->subreq_limit = virt->subreq_limit
470 : base->subreq_limit;
475 /* Add per-directory configuration entry (for <directory> section);
476 * these are part of the core server config.
479 AP_CORE_DECLARE(void) ap_add_per_dir_conf(server_rec *s, void *dir_config)
481 core_server_config *sconf = ap_get_module_config(s->module_config,
483 void **new_space = (void **)apr_array_push(sconf->sec_dir);
485 *new_space = dir_config;
488 AP_CORE_DECLARE(void) ap_add_per_url_conf(server_rec *s, void *url_config)
490 core_server_config *sconf = ap_get_module_config(s->module_config,
492 void **new_space = (void **)apr_array_push(sconf->sec_url);
494 *new_space = url_config;
497 AP_CORE_DECLARE(void) ap_add_file_conf(core_dir_config *conf, void *url_config)
499 void **new_space = (void **)apr_array_push(conf->sec_file);
501 *new_space = url_config;
504 /* We need to do a stable sort, qsort isn't stable. So to make it stable
505 * we'll be maintaining the original index into the list, and using it
506 * as the minor key during sorting. The major key is the number of
507 * components (where the root component is zero).
509 struct reorder_sort_rec {
510 ap_conf_vector_t *elt;
514 static int reorder_sorter(const void *va, const void *vb)
516 const struct reorder_sort_rec *a = va;
517 const struct reorder_sort_rec *b = vb;
518 core_dir_config *core_a;
519 core_dir_config *core_b;
521 core_a = ap_get_module_config(a->elt, &core_module);
522 core_b = ap_get_module_config(b->elt, &core_module);
524 /* a regex always sorts after a non-regex
526 if (!core_a->r && core_b->r) {
529 else if (core_a->r && !core_b->r) {
533 /* we always sort next by the number of components
535 if (core_a->d_components < core_b->d_components) {
538 else if (core_a->d_components > core_b->d_components) {
542 /* They have the same number of components, we now have to compare
543 * the minor key to maintain the original order (from the config.)
545 return a->orig_index - b->orig_index;
548 void ap_core_reorder_directories(apr_pool_t *p, server_rec *s)
550 core_server_config *sconf;
551 apr_array_header_t *sec_dir;
552 struct reorder_sort_rec *sortbin;
554 ap_conf_vector_t **elts;
558 sconf = ap_get_module_config(s->module_config, &core_module);
559 sec_dir = sconf->sec_dir;
560 nelts = sec_dir->nelts;
561 elts = (ap_conf_vector_t **)sec_dir->elts;
564 /* simple case of already being sorted... */
565 /* We're not checking this condition to be fast... we're checking
566 * it to avoid trying to palloc zero bytes, which can trigger some
567 * memory debuggers to barf
572 /* we have to allocate tmp space to do a stable sort */
573 apr_pool_create(&tmp, p);
574 sortbin = apr_palloc(tmp, sec_dir->nelts * sizeof(*sortbin));
575 for (i = 0; i < nelts; ++i) {
576 sortbin[i].orig_index = i;
577 sortbin[i].elt = elts[i];
580 qsort(sortbin, nelts, sizeof(*sortbin), reorder_sorter);
582 /* and now copy back to the original array */
583 for (i = 0; i < nelts; ++i) {
584 elts[i] = sortbin[i].elt;
587 apr_pool_destroy(tmp);
590 /*****************************************************************
592 * There are some elements of the core config structures in which
593 * other modules have a legitimate interest (this is ugly, but necessary
594 * to preserve NCSA back-compatibility). So, we have a bunch of accessors
598 AP_DECLARE(int) ap_allow_options(request_rec *r)
600 core_dir_config *conf =
601 (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
606 AP_DECLARE(int) ap_allow_overrides(request_rec *r)
608 core_dir_config *conf;
609 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
612 return conf->override;
615 AP_DECLARE(const char *) ap_auth_type(request_rec *r)
617 core_dir_config *conf;
619 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
622 return conf->ap_auth_type;
625 AP_DECLARE(const char *) ap_auth_name(request_rec *r)
627 core_dir_config *conf;
629 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
632 return conf->ap_auth_name;
635 AP_DECLARE(const char *) ap_default_type(request_rec *r)
637 core_dir_config *conf;
639 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
642 return conf->ap_default_type
643 ? conf->ap_default_type
644 : DEFAULT_CONTENT_TYPE;
647 AP_DECLARE(const char *) ap_document_root(request_rec *r) /* Don't use this! */
649 core_server_config *conf;
651 conf = (core_server_config *)ap_get_module_config(r->server->module_config,
654 return conf->ap_document_root;
657 AP_DECLARE(const apr_array_header_t *) ap_requires(request_rec *r)
659 core_dir_config *conf;
661 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
664 return conf->ap_requires;
667 AP_DECLARE(int) ap_satisfies(request_rec *r)
669 core_dir_config *conf;
671 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
674 return conf->satisfy[r->method_number];
677 /* Should probably just get rid of this... the only code that cares is
678 * part of the core anyway (and in fact, it isn't publicised to other
682 char *ap_response_code_string(request_rec *r, int error_index)
684 core_dir_config *dirconf;
685 core_request_config *reqconf;
687 /* check for string registered via ap_custom_response() first */
688 reqconf = (core_request_config *)ap_get_module_config(r->request_config,
690 if (reqconf->response_code_strings != NULL &&
691 reqconf->response_code_strings[error_index] != NULL) {
692 return reqconf->response_code_strings[error_index];
695 /* check for string specified via ErrorDocument */
696 dirconf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
699 if (dirconf->response_code_strings == NULL) {
703 if (dirconf->response_code_strings[error_index] == &errordocument_default) {
707 return dirconf->response_code_strings[error_index];
711 /* Code from Harald Hanche-Olsen <hanche@imf.unit.no> */
712 static APR_INLINE void do_double_reverse (conn_rec *conn)
717 if (conn->double_reverse) {
722 if (conn->remote_host == NULL || conn->remote_host[0] == '\0') {
723 /* single reverse failed, so don't bother */
724 conn->double_reverse = -1;
728 rv = apr_sockaddr_info_get(&sa, conn->remote_host, APR_UNSPEC, 0, 0, conn->pool);
729 if (rv == APR_SUCCESS) {
731 if (apr_sockaddr_equal(sa, conn->remote_addr)) {
732 conn->double_reverse = 1;
740 conn->double_reverse = -1;
743 AP_DECLARE(const char *) ap_get_remote_host(conn_rec *conn, void *dir_config,
744 int type, int *str_is_ip)
746 int hostname_lookups;
747 int ignored_str_is_ip;
749 if (!str_is_ip) { /* caller doesn't want to know */
750 str_is_ip = &ignored_str_is_ip;
754 /* If we haven't checked the host name, and we want to */
757 ((core_dir_config *)ap_get_module_config(dir_config, &core_module))
760 if (hostname_lookups == HOSTNAME_LOOKUP_UNSET) {
761 hostname_lookups = HOSTNAME_LOOKUP_OFF;
766 hostname_lookups = HOSTNAME_LOOKUP_OFF;
769 if (type != REMOTE_NOLOOKUP
770 && conn->remote_host == NULL
771 && (type == REMOTE_DOUBLE_REV
772 || hostname_lookups != HOSTNAME_LOOKUP_OFF)) {
774 if (apr_getnameinfo(&conn->remote_host, conn->remote_addr, 0)
776 ap_str_tolower(conn->remote_host);
778 if (hostname_lookups == HOSTNAME_LOOKUP_DOUBLE) {
779 do_double_reverse(conn);
780 if (conn->double_reverse != 1) {
781 conn->remote_host = NULL;
786 /* if failed, set it to the NULL string to indicate error */
787 if (conn->remote_host == NULL) {
788 conn->remote_host = "";
792 if (type == REMOTE_DOUBLE_REV) {
793 do_double_reverse(conn);
794 if (conn->double_reverse == -1) {
800 * Return the desired information; either the remote DNS name, if found,
801 * or either NULL (if the hostname was requested) or the IP address
802 * (if any identifier was requested).
804 if (conn->remote_host != NULL && conn->remote_host[0] != '\0') {
805 return conn->remote_host;
808 if (type == REMOTE_HOST || type == REMOTE_DOUBLE_REV) {
813 return conn->remote_ip;
819 * Optional function coming from mod_ident, used for looking up ident user
821 static APR_OPTIONAL_FN_TYPE(ap_ident_lookup) *ident_lookup;
823 AP_DECLARE(const char *) ap_get_remote_logname(request_rec *r)
825 if (r->connection->remote_logname != NULL) {
826 return r->connection->remote_logname;
830 return ident_lookup(r);
836 /* There are two options regarding what the "name" of a server is. The
837 * "canonical" name as defined by ServerName and Port, or the "client's
838 * name" as supplied by a possible Host: header or full URI. We never
839 * trust the port passed in the client's headers, we always use the
840 * port of the actual socket.
842 * The DNS option to UseCanonicalName causes this routine to do a
843 * reverse lookup on the local IP address of the connection and use
844 * that for the ServerName. This makes its value more reliable while
845 * at the same time allowing Demon's magic virtual hosting to work.
846 * The assumption is that DNS lookups are sufficiently quick...
849 AP_DECLARE(const char *) ap_get_server_name(request_rec *r)
851 conn_rec *conn = r->connection;
854 d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
857 if (d->use_canonical_name == USE_CANONICAL_NAME_OFF) {
858 return r->hostname ? r->hostname : r->server->server_hostname;
861 if (d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
862 if (conn->local_host == NULL) {
863 if (apr_getnameinfo(&conn->local_host,
864 conn->local_addr, 0) != APR_SUCCESS)
865 conn->local_host = apr_pstrdup(conn->pool,
866 r->server->server_hostname);
868 ap_str_tolower(conn->local_host);
872 return conn->local_host;
876 return r->server->server_hostname;
880 * Get the current server name from the request for the purposes
881 * of using in a URL. If the server name is an IPv6 literal
882 * address, it will be returned in URL format (e.g., "[fe80::1]").
884 static const char *get_server_name_for_url(request_rec *r)
886 const char *plain_server_name = ap_get_server_name(r);
889 if (ap_strchr_c(plain_server_name, ':')) { /* IPv6 literal? */
890 return apr_psprintf(r->pool, "[%s]", plain_server_name);
893 return plain_server_name;
896 AP_DECLARE(apr_port_t) ap_get_server_port(const request_rec *r)
900 (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
902 if (d->use_canonical_name == USE_CANONICAL_NAME_OFF
903 || d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
905 /* With UseCanonicalName off Apache will form self-referential
906 * URLs using the hostname and port supplied by the client if
907 * any are supplied (otherwise it will use the canonical name).
909 port = r->parsed_uri.port_str ? r->parsed_uri.port :
910 r->connection->local_addr->port ? r->connection->local_addr->port :
911 r->server->port ? r->server->port :
914 else { /* d->use_canonical_name == USE_CANONICAL_NAME_ON */
916 /* With UseCanonicalName on (and in all versions prior to 1.3)
917 * Apache will use the hostname and port specified in the
918 * ServerName directive to construct a canonical name for the
919 * server. (If no port was specified in the ServerName
920 * directive, Apache uses the port supplied by the client if
921 * any is supplied, and finally the default port for the protocol
924 port = r->server->port ? r->server->port :
925 r->connection->local_addr->port ? r->connection->local_addr->port :
933 AP_DECLARE(char *) ap_construct_url(apr_pool_t *p, const char *uri,
936 unsigned port = ap_get_server_port(r);
937 const char *host = get_server_name_for_url(r);
939 if (ap_is_default_port(port, r)) {
940 return apr_pstrcat(p, ap_http_method(r), "://", host, uri, NULL);
943 return apr_psprintf(p, "%s://%s:%u%s", ap_http_method(r), host, port, uri);
946 AP_DECLARE(apr_off_t) ap_get_limit_req_body(const request_rec *r)
949 (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
951 return d->limit_req_body;
955 /*****************************************************************
957 * Commands... this module handles almost all of the NCSA httpd.conf
958 * commands, but most of the old srm.conf is in the the modules.
962 /* returns a parent if it matches the given directive */
963 static const ap_directive_t * find_parent(const ap_directive_t *dirp,
966 while (dirp->parent != NULL) {
969 /* ### it would be nice to have atom-ized directives */
970 if (strcasecmp(dirp->directive, what) == 0)
977 AP_DECLARE(const char *) ap_check_cmd_context(cmd_parms *cmd,
980 const char *gt = (cmd->cmd->name[0] == '<'
981 && cmd->cmd->name[strlen(cmd->cmd->name)-1] != '>')
983 const ap_directive_t *found;
985 if ((forbidden & NOT_IN_VIRTUALHOST) && cmd->server->is_virtual) {
986 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
987 " cannot occur within <VirtualHost> section", NULL);
990 if ((forbidden & NOT_IN_LIMIT) && cmd->limited != -1) {
991 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
992 " cannot occur within <Limit> section", NULL);
995 if ((forbidden & NOT_IN_DIR_LOC_FILE) == NOT_IN_DIR_LOC_FILE) {
996 if (cmd->path != NULL) {
997 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
998 " cannot occur within <Directory/Location/Files> "
1001 if (cmd->cmd->req_override & EXEC_ON_READ) {
1002 /* EXEC_ON_READ must be NOT_IN_DIR_LOC_FILE, if not, it will
1003 * (deliberately) segfault below in the individual tests...
1009 if (((forbidden & NOT_IN_DIRECTORY)
1010 && ((found = find_parent(cmd->directive, "<Directory"))
1011 || (found = find_parent(cmd->directive, "<DirectoryMatch"))))
1012 || ((forbidden & NOT_IN_LOCATION)
1013 && ((found = find_parent(cmd->directive, "<Location"))
1014 || (found = find_parent(cmd->directive, "<LocationMatch"))))
1015 || ((forbidden & NOT_IN_FILES)
1016 && ((found = find_parent(cmd->directive, "<Files"))
1017 || (found = find_parent(cmd->directive, "<FilesMatch"))))) {
1018 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1019 " cannot occur within ", found->directive,
1026 static const char *set_access_name(cmd_parms *cmd, void *dummy,
1029 void *sconf = cmd->server->module_config;
1030 core_server_config *conf = ap_get_module_config(sconf, &core_module);
1032 const char *err = ap_check_cmd_context(cmd,
1033 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1038 conf->access_name = apr_pstrdup(cmd->pool, arg);
1043 static const char *set_gprof_dir(cmd_parms *cmd, void *dummy, const char *arg)
1045 void *sconf = cmd->server->module_config;
1046 core_server_config *conf = ap_get_module_config(sconf, &core_module);
1048 const char *err = ap_check_cmd_context(cmd,
1049 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1054 conf->gprof_dir = apr_pstrdup(cmd->pool, arg);
1059 static const char *set_add_default_charset(cmd_parms *cmd,
1060 void *d_, const char *arg)
1062 core_dir_config *d = d_;
1064 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1069 if (!strcasecmp(arg, "Off")) {
1070 d->add_default_charset = ADD_DEFAULT_CHARSET_OFF;
1072 else if (!strcasecmp(arg, "On")) {
1073 d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1074 d->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
1077 d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1078 d->add_default_charset_name = arg;
1084 static const char *set_document_root(cmd_parms *cmd, void *dummy,
1087 void *sconf = cmd->server->module_config;
1088 core_server_config *conf = ap_get_module_config(sconf, &core_module);
1090 const char *err = ap_check_cmd_context(cmd,
1091 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1096 /* Make it absolute, relative to ServerRoot */
1097 arg = ap_server_root_relative(cmd->pool, arg);
1099 /* TODO: ap_configtestonly && ap_docrootcheck && */
1100 if (apr_filepath_merge((char**)&conf->ap_document_root, NULL, arg,
1101 APR_FILEPATH_TRUENAME, cmd->pool) != APR_SUCCESS
1102 || !ap_is_directory(cmd->pool, arg)) {
1103 if (cmd->server->is_virtual) {
1104 ap_log_perror(APLOG_MARK, APLOG_STARTUP, 0,
1106 "Warning: DocumentRoot [%s] does not exist",
1108 conf->ap_document_root = arg;
1111 return "DocumentRoot must be a directory";
1117 AP_DECLARE(void) ap_custom_response(request_rec *r, int status,
1120 core_request_config *conf =
1121 ap_get_module_config(r->request_config, &core_module);
1124 if (conf->response_code_strings == NULL) {
1125 conf->response_code_strings =
1126 apr_pcalloc(r->pool,
1127 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
1130 idx = ap_index_of_response(status);
1132 conf->response_code_strings[idx] =
1133 ((ap_is_url(string) || (*string == '/')) && (*string != '"')) ?
1134 apr_pstrdup(r->pool, string) : apr_pstrcat(r->pool, "\"", string, NULL);
1137 static const char *set_error_document(cmd_parms *cmd, void *conf_,
1138 const char *errno_str, const char *msg)
1140 core_dir_config *conf = conf_;
1141 int error_number, index_number, idx500;
1142 enum { MSG, LOCAL_PATH, REMOTE_PATH } what = MSG;
1144 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1149 /* 1st parameter should be a 3 digit number, which we recognize;
1150 * convert it into an array index
1152 error_number = atoi(errno_str);
1153 idx500 = ap_index_of_response(HTTP_INTERNAL_SERVER_ERROR);
1155 if (error_number == HTTP_INTERNAL_SERVER_ERROR) {
1156 index_number = idx500;
1158 else if ((index_number = ap_index_of_response(error_number)) == idx500) {
1159 return apr_pstrcat(cmd->pool, "Unsupported HTTP response code ",
1163 /* Heuristic to determine second argument. */
1164 if (ap_strchr_c(msg,' '))
1166 else if (msg[0] == '/')
1168 else if (ap_is_url(msg))
1173 /* The entry should be ignored if it is a full URL for a 401 error */
1175 if (error_number == 401 && what == REMOTE_PATH) {
1176 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, cmd->server,
1177 "cannot use a full URL in a 401 ErrorDocument "
1178 "directive --- ignoring!");
1180 else { /* Store it... */
1181 if (conf->response_code_strings == NULL) {
1182 conf->response_code_strings =
1183 apr_pcalloc(cmd->pool,
1184 sizeof(*conf->response_code_strings) *
1188 if (strcmp(msg, "default") == 0) {
1189 /* special case: ErrorDocument 404 default restores the
1190 * canned server error response
1192 conf->response_code_strings[index_number] = &errordocument_default;
1195 /* hack. Prefix a " if it is a msg; as that is what
1196 * http_protocol.c relies on to distinguish between
1197 * a msg and a (local) path.
1199 conf->response_code_strings[index_number] = (what == MSG) ?
1200 apr_pstrcat(cmd->pool, "\"",msg,NULL) :
1201 apr_pstrdup(cmd->pool, msg);
1208 static const char *set_override(cmd_parms *cmd, void *d_, const char *l)
1210 core_dir_config *d = d_;
1213 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1218 /* Throw a warning if we're in <Location> or <Files> */
1219 if (ap_check_cmd_context(cmd, NOT_IN_LOCATION | NOT_IN_FILES)) {
1220 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
1221 "Useless use of AllowOverride in line %d.",
1222 cmd->directive->line_num);
1225 d->override = OR_NONE;
1227 w = ap_getword_conf(cmd->pool, &l);
1228 if (!strcasecmp(w, "Limit")) {
1229 d->override |= OR_LIMIT;
1231 else if (!strcasecmp(w, "Options")) {
1232 d->override |= OR_OPTIONS;
1234 else if (!strcasecmp(w, "FileInfo")) {
1235 d->override |= OR_FILEINFO;
1237 else if (!strcasecmp(w, "AuthConfig")) {
1238 d->override |= OR_AUTHCFG;
1240 else if (!strcasecmp(w, "Indexes")) {
1241 d->override |= OR_INDEXES;
1243 else if (!strcasecmp(w, "None")) {
1244 d->override = OR_NONE;
1246 else if (!strcasecmp(w, "All")) {
1247 d->override = OR_ALL;
1250 return apr_pstrcat(cmd->pool, "Illegal override option ", w, NULL);
1253 d->override &= ~OR_UNSET;
1259 static const char *set_options(cmd_parms *cmd, void *d_, const char *l)
1261 core_dir_config *d = d_;
1262 allow_options_t opt;
1267 char *w = ap_getword_conf(cmd->pool, &l);
1270 if (*w == '+' || *w == '-') {
1278 if (!strcasecmp(w, "Indexes")) {
1281 else if (!strcasecmp(w, "Includes")) {
1284 else if (!strcasecmp(w, "IncludesNOEXEC")) {
1285 opt = (OPT_INCLUDES | OPT_INCNOEXEC);
1287 else if (!strcasecmp(w, "FollowSymLinks")) {
1288 opt = OPT_SYM_LINKS;
1290 else if (!strcasecmp(w, "SymLinksIfOwnerMatch")) {
1291 opt = OPT_SYM_OWNER;
1293 else if (!strcasecmp(w, "execCGI")) {
1296 else if (!strcasecmp(w, "MultiViews")) {
1299 else if (!strcasecmp(w, "RunScripts")) { /* AI backcompat. Yuck */
1300 opt = OPT_MULTI|OPT_EXECCGI;
1302 else if (!strcasecmp(w, "None")) {
1305 else if (!strcasecmp(w, "All")) {
1309 return apr_pstrcat(cmd->pool, "Illegal option ", w, NULL);
1312 /* we ensure the invariant (d->opts_add & d->opts_remove) == 0 */
1313 if (action == '-') {
1314 d->opts_remove |= opt;
1315 d->opts_add &= ~opt;
1318 else if (action == '+') {
1320 d->opts_remove &= ~opt;
1332 * Note what data should be used when forming file ETag values.
1333 * It would be nicer to do this as an ITERATE, but then we couldn't
1334 * remember the +/- state properly.
1336 static const char *set_etag_bits(cmd_parms *cmd, void *mconfig,
1339 core_dir_config *cfg;
1340 etag_components_t bit;
1348 cfg = (core_dir_config *)mconfig;
1353 while (args[0] != '\0') {
1357 token = ap_getword_conf(cmd->pool, &args);
1358 if ((*token == '+') || (*token == '-')) {
1364 * The occurrence of an absolute setting wipes
1365 * out any previous relative ones. The first such
1366 * occurrence forgets any inherited ones, too.
1369 cfg->etag_bits = ETAG_UNSET;
1370 cfg->etag_add = ETAG_UNSET;
1371 cfg->etag_remove = ETAG_UNSET;
1376 if (strcasecmp(token, "None") == 0) {
1377 if (action != '*') {
1381 cfg->etag_bits = bit = ETAG_NONE;
1385 else if (strcasecmp(token, "All") == 0) {
1386 if (action != '*') {
1391 cfg->etag_bits = bit = ETAG_ALL;
1394 else if (strcasecmp(token, "Size") == 0) {
1397 else if ((strcasecmp(token, "LMTime") == 0)
1398 || (strcasecmp(token, "MTime") == 0)
1399 || (strcasecmp(token, "LastModified") == 0)) {
1402 else if (strcasecmp(token, "INode") == 0) {
1406 return apr_pstrcat(cmd->pool, "Unknown keyword '",
1407 token, "' for ", cmd->cmd->name,
1408 " directive", NULL);
1412 return apr_pstrcat(cmd->pool, cmd->cmd->name, " keyword '",
1413 token, "' cannot be used with '+' or '-'",
1417 if (action == '+') {
1419 * Make sure it's in the 'add' list and absent from the
1422 cfg->etag_add |= bit;
1423 cfg->etag_remove &= (~ bit);
1425 else if (action == '-') {
1426 cfg->etag_remove |= bit;
1427 cfg->etag_add &= (~ bit);
1431 * Non-relative values wipe out any + or - values
1432 * accumulated so far.
1434 cfg->etag_bits |= bit;
1435 cfg->etag_add = ETAG_UNSET;
1436 cfg->etag_remove = ETAG_UNSET;
1442 * Any setting at all will clear the 'None' and 'Unset' bits.
1445 if (cfg->etag_add != ETAG_UNSET) {
1446 cfg->etag_add &= (~ ETAG_UNSET);
1449 if (cfg->etag_remove != ETAG_UNSET) {
1450 cfg->etag_remove &= (~ ETAG_UNSET);
1454 cfg->etag_bits &= (~ ETAG_UNSET);
1456 if ((cfg->etag_bits & ETAG_NONE) != ETAG_NONE) {
1457 cfg->etag_bits &= (~ ETAG_NONE);
1464 static const char *set_enable_mmap(cmd_parms *cmd, void *d_,
1467 core_dir_config *d = d_;
1468 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1474 if (strcasecmp(arg, "on") == 0) {
1475 d->enable_mmap = ENABLE_MMAP_ON;
1477 else if (strcasecmp(arg, "off") == 0) {
1478 d->enable_mmap = ENABLE_MMAP_OFF;
1481 return "parameter must be 'on' or 'off'";
1487 static const char *set_enable_sendfile(cmd_parms *cmd, void *d_,
1490 core_dir_config *d = d_;
1491 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1497 if (strcasecmp(arg, "on") == 0) {
1498 d->enable_sendfile = ENABLE_SENDFILE_ON;
1500 else if (strcasecmp(arg, "off") == 0) {
1501 d->enable_sendfile = ENABLE_SENDFILE_OFF;
1504 return "parameter must be 'on' or 'off'";
1510 static const char *satisfy(cmd_parms *cmd, void *c_, const char *arg)
1512 core_dir_config *c = c_;
1513 int satisfy = SATISFY_NOSPEC;
1516 if (!strcasecmp(arg, "all")) {
1517 satisfy = SATISFY_ALL;
1519 else if (!strcasecmp(arg, "any")) {
1520 satisfy = SATISFY_ANY;
1523 return "Satisfy either 'any' or 'all'.";
1526 for (i = 0; i < METHODS; ++i) {
1527 if (cmd->limited & (AP_METHOD_BIT << i)) {
1528 c->satisfy[i] = satisfy;
1535 static const char *require(cmd_parms *cmd, void *c_, const char *arg)
1538 core_dir_config *c = c_;
1540 if (!c->ap_requires) {
1541 c->ap_requires = apr_array_make(cmd->pool, 2, sizeof(require_line));
1544 r = (require_line *)apr_array_push(c->ap_requires);
1545 r->requirement = apr_pstrdup(cmd->pool, arg);
1546 r->method_mask = cmd->limited;
1552 * Report a missing-'>' syntax error.
1554 static char *unclosed_directive(cmd_parms *cmd)
1556 return apr_pstrcat(cmd->pool, cmd->cmd->name,
1557 "> directive missing closing '>'", NULL);
1560 AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd,
1564 const char *endp = ap_strrchr_c(arg, '>');
1565 const char *limited_methods;
1566 void *tog = cmd->cmd->cmd_data;
1567 apr_int64_t limited = 0;
1570 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1576 return unclosed_directive(cmd);
1579 limited_methods = apr_pstrndup(cmd->pool, arg, endp - arg);
1581 while (limited_methods[0]) {
1582 char *method = ap_getword_conf(cmd->pool, &limited_methods);
1585 /* check for builtin or module registered method number */
1586 methnum = ap_method_number_of(method);
1588 if (methnum == M_TRACE && !tog) {
1589 return "TRACE cannot be controlled by <Limit>";
1591 else if (methnum == M_INVALID) {
1592 /* method has not been registered yet, but resorce restriction
1593 * is always checked before method handling, so register it.
1595 methnum = ap_method_register(cmd->pool, method);
1598 limited |= (AP_METHOD_BIT << methnum);
1601 /* Killing two features with one function,
1602 * if (tog == NULL) <Limit>, else <LimitExcept>
1604 cmd->limited = tog ? ~limited : limited;
1606 errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context);
1613 /* XXX: Bogus - need to do this differently (at least OS2/Netware suffer
1614 * the same problem!!!
1615 * We use this in <DirectoryMatch> and <FilesMatch>, to ensure that
1616 * people don't get bitten by wrong-cased regex matches
1620 #define USE_ICASE REG_ICASE
1625 static const char *dirsection(cmd_parms *cmd, void *mconfig, const char *arg)
1628 const char *endp = ap_strrchr_c(arg, '>');
1629 int old_overrides = cmd->override;
1630 char *old_path = cmd->path;
1631 core_dir_config *conf;
1632 ap_conf_vector_t *new_dir_conf = ap_create_per_dir_config(cmd->pool);
1634 const command_rec *thiscmd = cmd->cmd;
1636 const char *err = ap_check_cmd_context(cmd,
1637 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1643 return unclosed_directive(cmd);
1646 arg = apr_pstrndup(cmd->pool, arg, endp - arg);
1649 if (thiscmd->cmd_data)
1650 return "<DirectoryMatch > block must specify a path";
1652 return "<Directory > block must specify a path";
1655 cmd->path = ap_getword_conf(cmd->pool, &arg);
1656 cmd->override = OR_ALL|ACCESS_CONF;
1658 if (!strcmp(cmd->path, "~")) {
1659 cmd->path = ap_getword_conf(cmd->pool, &arg);
1661 return "<Directory ~ > block must specify a path";
1662 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1664 return "Regex could not be compiled";
1667 else if (thiscmd->cmd_data) { /* <DirectoryMatch> */
1668 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1670 return "Regex could not be compiled";
1673 else if (!strcmp(cmd->path, "/") == 0)
1678 * Ensure that the pathname is canonical, and append the trailing /
1680 apr_status_t rv = apr_filepath_merge(&newpath, NULL, cmd->path,
1681 APR_FILEPATH_TRUENAME, cmd->pool);
1682 if (rv != APR_SUCCESS && rv != APR_EPATHWILD) {
1683 return apr_pstrcat(cmd->pool, "<Directory \"", cmd->path,
1684 "\"> path is invalid.", NULL);
1687 cmd->path = newpath;
1688 if (cmd->path[strlen(cmd->path) - 1] != '/')
1689 cmd->path = apr_pstrcat(cmd->pool, cmd->path, "/", NULL);
1692 /* initialize our config and fetch it */
1693 conf = ap_set_config_vectors(cmd->server, new_dir_conf, cmd->path,
1694 &core_module, cmd->pool);
1696 errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_dir_conf);
1701 conf->d = cmd->path;
1702 conf->d_is_fnmatch = (apr_fnmatch_test(conf->d) != 0);
1704 /* Make this explicit - the "/" root has 0 elements, that is, we
1705 * will always merge it, and it will always sort and merge first.
1706 * All others are sorted and tested by the number of slashes.
1708 if (strcmp(conf->d, "/") == 0)
1709 conf->d_components = 0;
1711 conf->d_components = ap_count_dirs(conf->d);
1713 ap_add_per_dir_conf(cmd->server, new_dir_conf);
1716 return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1717 "> arguments not (yet) supported.", NULL);
1720 cmd->path = old_path;
1721 cmd->override = old_overrides;
1726 static const char *urlsection(cmd_parms *cmd, void *mconfig, const char *arg)
1729 const char *endp = ap_strrchr_c(arg, '>');
1730 int old_overrides = cmd->override;
1731 char *old_path = cmd->path;
1732 core_dir_config *conf;
1734 const command_rec *thiscmd = cmd->cmd;
1735 ap_conf_vector_t *new_url_conf = ap_create_per_dir_config(cmd->pool);
1736 const char *err = ap_check_cmd_context(cmd,
1737 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1743 return unclosed_directive(cmd);
1746 arg = apr_pstrndup(cmd->pool, arg, endp - arg);
1748 cmd->path = ap_getword_conf(cmd->pool, &arg);
1749 cmd->override = OR_ALL|ACCESS_CONF;
1751 if (thiscmd->cmd_data) { /* <LocationMatch> */
1752 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1754 return "Regex could not be compiled";
1757 else if (!strcmp(cmd->path, "~")) {
1758 cmd->path = ap_getword_conf(cmd->pool, &arg);
1759 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1761 return "Regex could not be compiled";
1765 /* initialize our config and fetch it */
1766 conf = ap_set_config_vectors(cmd->server, new_url_conf, cmd->path,
1767 &core_module, cmd->pool);
1769 errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_url_conf);
1773 conf->d = apr_pstrdup(cmd->pool, cmd->path); /* No mangling, please */
1774 conf->d_is_fnmatch = apr_fnmatch_test(conf->d) != 0;
1777 ap_add_per_url_conf(cmd->server, new_url_conf);
1780 return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1781 "> arguments not (yet) supported.", NULL);
1784 cmd->path = old_path;
1785 cmd->override = old_overrides;
1790 static const char *filesection(cmd_parms *cmd, void *mconfig, const char *arg)
1793 const char *endp = ap_strrchr_c(arg, '>');
1794 int old_overrides = cmd->override;
1795 char *old_path = cmd->path;
1796 core_dir_config *conf;
1798 const command_rec *thiscmd = cmd->cmd;
1799 core_dir_config *c = mconfig;
1800 ap_conf_vector_t *new_file_conf = ap_create_per_dir_config(cmd->pool);
1801 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT|NOT_IN_LOCATION);
1808 return unclosed_directive(cmd);
1811 arg = apr_pstrndup(cmd->pool, arg, endp - arg);
1813 cmd->path = ap_getword_conf(cmd->pool, &arg);
1814 /* Only if not an .htaccess file */
1816 cmd->override = OR_ALL|ACCESS_CONF;
1819 if (thiscmd->cmd_data) { /* <FilesMatch> */
1820 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1822 return "Regex could not be compiled";
1825 else if (!strcmp(cmd->path, "~")) {
1826 cmd->path = ap_getword_conf(cmd->pool, &arg);
1827 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1829 return "Regex could not be compiled";
1834 /* Ensure that the pathname is canonical, but we
1835 * can't test the case/aliases without a fixed path */
1836 if (apr_filepath_merge(&newpath, "", cmd->path,
1837 0, cmd->pool) != APR_SUCCESS)
1838 return apr_pstrcat(cmd->pool, "<Files \"", cmd->path,
1839 "\"> is invalid.", NULL);
1840 cmd->path = newpath;
1843 /* initialize our config and fetch it */
1844 conf = ap_set_config_vectors(cmd->server, new_file_conf, cmd->path,
1845 &core_module, cmd->pool);
1847 errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_file_conf);
1851 conf->d = cmd->path;
1852 conf->d_is_fnmatch = apr_fnmatch_test(conf->d) != 0;
1855 ap_add_file_conf(c, new_file_conf);
1858 return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1859 "> arguments not (yet) supported.", NULL);
1862 cmd->path = old_path;
1863 cmd->override = old_overrides;
1868 static const char *start_ifmod(cmd_parms *cmd, void *mconfig, const char *arg)
1870 const char *endp = ap_strrchr_c(arg, '>');
1871 int not = (arg[0] == '!');
1875 return unclosed_directive(cmd);
1878 arg = apr_pstrndup(cmd->pool, arg, endp - arg);
1884 found = ap_find_linked_module(arg);
1886 if ((!not && found) || (not && !found)) {
1887 ap_directive_t *parent = NULL;
1888 ap_directive_t *current = NULL;
1891 retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd,
1892 ¤t, &parent, "<IfModule");
1893 *(ap_directive_t **)mconfig = current;
1897 *(ap_directive_t **)mconfig = NULL;
1898 return ap_soak_end_container(cmd, "<IfModule");
1902 AP_DECLARE(int) ap_exists_config_define(const char *name)
1907 defines = (char **)ap_server_config_defines->elts;
1908 for (i = 0; i < ap_server_config_defines->nelts; i++) {
1909 if (strcmp(defines[i], name) == 0) {
1917 static const char *start_ifdefine(cmd_parms *cmd, void *dummy, const char *arg)
1923 endp = ap_strrchr_c(arg, '>');
1925 return unclosed_directive(cmd);
1928 arg = apr_pstrndup(cmd->pool, arg, endp - arg);
1930 if (arg[0] == '!') {
1935 defined = ap_exists_config_define(arg);
1936 if ((!not && defined) || (not && !defined)) {
1937 ap_directive_t *parent = NULL;
1938 ap_directive_t *current = NULL;
1941 retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd,
1942 ¤t, &parent, "<IfDefine");
1943 *(ap_directive_t **)dummy = current;
1947 *(ap_directive_t **)dummy = NULL;
1948 return ap_soak_end_container(cmd, "<IfDefine");
1952 /* httpd.conf commands... beginning with the <VirtualHost> business */
1954 static const char *virtualhost_section(cmd_parms *cmd, void *dummy,
1957 server_rec *main_server = cmd->server, *s;
1959 const char *endp = ap_strrchr_c(arg, '>');
1960 apr_pool_t *p = cmd->pool;
1962 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1968 return unclosed_directive(cmd);
1971 arg = apr_pstrndup(cmd->pool, arg, endp - arg);
1973 /* FIXME: There's another feature waiting to happen here -- since you
1974 can now put multiple addresses/names on a single <VirtualHost>
1975 you might want to use it to group common definitions and then
1976 define other "subhosts" with their individual differences. But
1977 personally I'd rather just do it with a macro preprocessor. -djg */
1978 if (main_server->is_virtual) {
1979 return "<VirtualHost> doesn't nest!";
1982 errmsg = ap_init_virtual_host(p, arg, main_server, &s);
1987 s->next = main_server->next;
1988 main_server->next = s;
1990 s->defn_name = cmd->directive->filename;
1991 s->defn_line_number = cmd->directive->line_num;
1995 errmsg = ap_walk_config(cmd->directive->first_child, cmd,
1996 s->lookup_defaults);
1998 cmd->server = main_server;
2003 static const char *set_server_alias(cmd_parms *cmd, void *dummy,
2006 if (!cmd->server->names) {
2007 return "ServerAlias only used in <VirtualHost>";
2011 char **item, *name = ap_getword_conf(cmd->pool, &arg);
2013 if (ap_is_matchexp(name)) {
2014 item = (char **)apr_array_push(cmd->server->wild_names);
2017 item = (char **)apr_array_push(cmd->server->names);
2026 static const char *set_server_string_slot(cmd_parms *cmd, void *dummy,
2029 /* This one's pretty generic... */
2031 int offset = (int)(long)cmd->info;
2032 char *struct_ptr = (char *)cmd->server;
2034 const char *err = ap_check_cmd_context(cmd,
2035 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2040 *(const char **)(struct_ptr + offset) = arg;
2044 static const char *server_hostname_port(cmd_parms *cmd, void *dummy, const char *arg)
2046 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2047 const char *portstr;
2054 portstr = ap_strchr_c(arg, ':');
2056 cmd->server->server_hostname = apr_pstrndup(cmd->pool, arg,
2059 port = atoi(portstr);
2060 if (port <= 0 || port >= 65536) { /* 65536 == 1<<16 */
2061 return apr_pstrcat(cmd->temp_pool, "The port number \"", arg,
2062 "\" is outside the appropriate range "
2063 "(i.e., 1..65535).", NULL);
2067 cmd->server->server_hostname = apr_pstrdup(cmd->pool, arg);
2071 cmd->server->port = port;
2075 static const char *set_signature_flag(cmd_parms *cmd, void *d_,
2078 core_dir_config *d = d_;
2079 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2085 if (strcasecmp(arg, "On") == 0) {
2086 d->server_signature = srv_sig_on;
2088 else if (strcasecmp(arg, "Off") == 0) {
2089 d->server_signature = srv_sig_off;
2091 else if (strcasecmp(arg, "EMail") == 0) {
2092 d->server_signature = srv_sig_withmail;
2095 return "ServerSignature: use one of: off | on | email";
2101 static const char *set_server_root(cmd_parms *cmd, void *dummy,
2104 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2110 if ((apr_filepath_merge((char**)&ap_server_root, NULL, arg,
2111 APR_FILEPATH_TRUENAME, cmd->pool) != APR_SUCCESS)
2112 || !ap_is_directory(cmd->pool, ap_server_root)) {
2113 return "ServerRoot must be a valid directory";
2119 static const char *set_timeout(cmd_parms *cmd, void *dummy, const char *arg)
2121 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2127 cmd->server->timeout = apr_time_from_sec(atoi(arg));
2131 static const char *set_allow2f(cmd_parms *cmd, void *d_, int arg)
2133 core_dir_config *d = d_;
2134 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2140 d->allow_encoded_slashes = arg != 0;
2144 static const char *set_hostname_lookups(cmd_parms *cmd, void *d_,
2147 core_dir_config *d = d_;
2148 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2154 if (!strcasecmp(arg, "on")) {
2155 d->hostname_lookups = HOSTNAME_LOOKUP_ON;
2157 else if (!strcasecmp(arg, "off")) {
2158 d->hostname_lookups = HOSTNAME_LOOKUP_OFF;
2160 else if (!strcasecmp(arg, "double")) {
2161 d->hostname_lookups = HOSTNAME_LOOKUP_DOUBLE;
2164 return "parameter must be 'on', 'off', or 'double'";
2170 static const char *set_serverpath(cmd_parms *cmd, void *dummy,
2173 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2179 cmd->server->path = arg;
2180 cmd->server->pathlen = strlen(arg);
2184 static const char *set_content_md5(cmd_parms *cmd, void *d_, int arg)
2186 core_dir_config *d = d_;
2187 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2193 d->content_md5 = arg != 0;
2197 static const char *set_accept_path_info(cmd_parms *cmd, void *d_, const char *arg)
2199 core_dir_config *d = d_;
2201 if (strcasecmp(arg, "on") == 0) {
2202 d->accept_path_info = AP_REQ_ACCEPT_PATH_INFO;
2204 else if (strcasecmp(arg, "off") == 0) {
2205 d->accept_path_info = AP_REQ_REJECT_PATH_INFO;
2207 else if (strcasecmp(arg, "default") == 0) {
2208 d->accept_path_info = AP_REQ_DEFAULT_PATH_INFO;
2211 return "AcceptPathInfo must be set to on, off or default";
2217 static const char *set_use_canonical_name(cmd_parms *cmd, void *d_,
2220 core_dir_config *d = d_;
2221 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2227 if (strcasecmp(arg, "on") == 0) {
2228 d->use_canonical_name = USE_CANONICAL_NAME_ON;
2230 else if (strcasecmp(arg, "off") == 0) {
2231 d->use_canonical_name = USE_CANONICAL_NAME_OFF;
2233 else if (strcasecmp(arg, "dns") == 0) {
2234 d->use_canonical_name = USE_CANONICAL_NAME_DNS;
2237 return "parameter must be 'on', 'off', or 'dns'";
2244 static const char *include_config (cmd_parms *cmd, void *dummy,
2247 ap_directive_t *conftree = NULL;
2248 const char* conffile = ap_server_root_relative(cmd->pool, name);
2251 return apr_pstrcat(cmd->pool, "Invalid Include path ",
2255 ap_process_resource_config(cmd->server, conffile,
2256 &conftree, cmd->pool, cmd->temp_pool);
2257 *(ap_directive_t **)dummy = conftree;
2261 static const char *set_loglevel(cmd_parms *cmd, void *dummy, const char *arg)
2265 const char *err = ap_check_cmd_context(cmd,
2266 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2271 if ((str = ap_getword_conf(cmd->pool, &arg))) {
2272 if (!strcasecmp(str, "emerg")) {
2273 cmd->server->loglevel = APLOG_EMERG;
2275 else if (!strcasecmp(str, "alert")) {
2276 cmd->server->loglevel = APLOG_ALERT;
2278 else if (!strcasecmp(str, "crit")) {
2279 cmd->server->loglevel = APLOG_CRIT;
2281 else if (!strcasecmp(str, "error")) {
2282 cmd->server->loglevel = APLOG_ERR;
2284 else if (!strcasecmp(str, "warn")) {
2285 cmd->server->loglevel = APLOG_WARNING;
2287 else if (!strcasecmp(str, "notice")) {
2288 cmd->server->loglevel = APLOG_NOTICE;
2290 else if (!strcasecmp(str, "info")) {
2291 cmd->server->loglevel = APLOG_INFO;
2293 else if (!strcasecmp(str, "debug")) {
2294 cmd->server->loglevel = APLOG_DEBUG;
2297 return "LogLevel requires level keyword: one of "
2298 "emerg/alert/crit/error/warn/notice/info/debug";
2302 return "LogLevel requires level keyword";
2308 AP_DECLARE(const char *) ap_psignature(const char *prefix, request_rec *r)
2311 core_dir_config *conf;
2313 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
2315 if ((conf->server_signature == srv_sig_off)
2316 || (conf->server_signature == srv_sig_unset)) {
2320 apr_snprintf(sport, sizeof sport, "%u", (unsigned) ap_get_server_port(r));
2322 if (conf->server_signature == srv_sig_withmail) {
2323 return apr_pstrcat(r->pool, prefix, "<address>",
2324 ap_get_server_version(),
2325 " Server at <a href=\"",
2326 ap_is_url(r->server->server_admin) ? "" : "mailto:",
2327 ap_escape_html(r->pool, r->server->server_admin),
2329 ap_escape_html(r->pool, ap_get_server_name(r)),
2330 "</a> Port ", sport,
2331 "</address>\n", NULL);
2334 return apr_pstrcat(r->pool, prefix, "<address>", ap_get_server_version(),
2336 ap_escape_html(r->pool, ap_get_server_name(r)),
2338 "</address>\n", NULL);
2342 * Load an authorisation realm into our location configuration, applying the
2343 * usual rules that apply to realms.
2345 static const char *set_authname(cmd_parms *cmd, void *mconfig,
2348 core_dir_config *aconfig = (core_dir_config *)mconfig;
2350 aconfig->ap_auth_name = ap_escape_quotes(cmd->pool, word1);
2355 * Handle a request to include the server's OS platform in the Server
2356 * response header field (the ServerTokens directive). Unfortunately
2357 * this requires a new global in order to communicate the setting back to
2358 * http_main so it can insert the information in the right place in the
2362 static char *server_version = NULL;
2363 static int version_locked = 0;
2365 enum server_token_type {
2366 SrvTk_MAJOR, /* eg: Apache/2 */
2367 SrvTk_MINOR, /* eg. Apache/2.0 */
2368 SrvTk_MINIMAL, /* eg: Apache/2.0.41 */
2369 SrvTk_OS, /* eg: Apache/2.0.41 (UNIX) */
2370 SrvTk_FULL, /* eg: Apache/2.0.41 (UNIX) PHP/4.2.2 FooBar/1.2b */
2371 SrvTk_PRODUCT_ONLY /* eg: Apache */
2373 static enum server_token_type ap_server_tokens = SrvTk_FULL;
2375 static apr_status_t reset_version(void *dummy)
2378 ap_server_tokens = SrvTk_FULL;
2379 server_version = NULL;
2383 AP_DECLARE(void) ap_get_server_revision(ap_version_t *version)
2385 version->major = AP_SERVER_MAJORVERSION_NUMBER;
2386 version->minor = AP_SERVER_MINORVERSION_NUMBER;
2387 version->patch = AP_SERVER_PATCHLEVEL_NUMBER;
2388 version->add_string = AP_SERVER_ADD_STRING;
2391 AP_DECLARE(const char *) ap_get_server_version(void)
2393 return (server_version ? server_version : AP_SERVER_BASEVERSION);
2396 AP_DECLARE(void) ap_add_version_component(apr_pool_t *pconf, const char *component)
2398 if (! version_locked) {
2400 * If the version string is null, register our cleanup to reset the
2401 * pointer on pool destruction. We also know that, if NULL,
2402 * we are adding the original SERVER_BASEVERSION string.
2404 if (server_version == NULL) {
2405 apr_pool_cleanup_register(pconf, NULL, reset_version,
2406 apr_pool_cleanup_null);
2407 server_version = apr_pstrdup(pconf, component);
2411 * Tack the given component identifier to the end of
2412 * the existing string.
2414 server_version = apr_pstrcat(pconf, server_version, " ",
2421 * This routine adds the real server base identity to the version string,
2422 * and then locks out changes until the next reconfig.
2424 static void ap_set_version(apr_pool_t *pconf)
2426 if (ap_server_tokens == SrvTk_PRODUCT_ONLY) {
2427 ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT);
2429 else if (ap_server_tokens == SrvTk_MINIMAL) {
2430 ap_add_version_component(pconf, AP_SERVER_BASEVERSION);
2432 else if (ap_server_tokens == SrvTk_MINOR) {
2433 ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT "/" AP_SERVER_MINORREVISION);
2435 else if (ap_server_tokens == SrvTk_MAJOR) {
2436 ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT "/" AP_SERVER_MAJORVERSION);
2439 ap_add_version_component(pconf, AP_SERVER_BASEVERSION " (" PLATFORM ")");
2443 * Lock the server_version string if we're not displaying
2444 * the full set of tokens
2446 if (ap_server_tokens != SrvTk_FULL) {
2451 static const char *set_serv_tokens(cmd_parms *cmd, void *dummy,
2454 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2460 if (!strcasecmp(arg, "OS")) {
2461 ap_server_tokens = SrvTk_OS;
2463 else if (!strcasecmp(arg, "Min") || !strcasecmp(arg, "Minimal")) {
2464 ap_server_tokens = SrvTk_MINIMAL;
2466 else if (!strcasecmp(arg, "Major")) {
2467 ap_server_tokens = SrvTk_MAJOR;
2469 else if (!strcasecmp(arg, "Minor") ) {
2470 ap_server_tokens = SrvTk_MINOR;
2472 else if (!strcasecmp(arg, "Prod") || !strcasecmp(arg, "ProductOnly")) {
2473 ap_server_tokens = SrvTk_PRODUCT_ONLY;
2476 ap_server_tokens = SrvTk_FULL;
2482 static const char *set_limit_req_line(cmd_parms *cmd, void *dummy,
2485 const char *err = ap_check_cmd_context(cmd,
2486 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2495 return apr_pstrcat(cmd->temp_pool, "LimitRequestLine \"", arg,
2496 "\" must be a non-negative integer", NULL);
2499 cmd->server->limit_req_line = lim;
2503 static const char *set_limit_req_fieldsize(cmd_parms *cmd, void *dummy,
2506 const char *err = ap_check_cmd_context(cmd,
2507 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2516 return apr_pstrcat(cmd->temp_pool, "LimitRequestFieldsize \"", arg,
2517 "\" must be a non-negative integer (0 = no limit)",
2521 if (lim > DEFAULT_LIMIT_REQUEST_FIELDSIZE) {
2522 return apr_psprintf(cmd->temp_pool, "LimitRequestFieldsize \"%s\" "
2523 "must not exceed the precompiled maximum of %d",
2524 arg, DEFAULT_LIMIT_REQUEST_FIELDSIZE);
2527 cmd->server->limit_req_fieldsize = lim;
2531 static const char *set_limit_req_fields(cmd_parms *cmd, void *dummy,
2534 const char *err = ap_check_cmd_context(cmd,
2535 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2544 return apr_pstrcat(cmd->temp_pool, "LimitRequestFields \"", arg,
2545 "\" must be a non-negative integer (0 = no limit)",
2549 cmd->server->limit_req_fields = lim;
2553 static const char *set_limit_req_body(cmd_parms *cmd, void *conf_,
2556 core_dir_config *conf = conf_;
2557 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2564 /* WTF: If strtoul is not portable, then write a replacement.
2565 * Instead we have an idiotic define in httpd.h that prevents
2566 * it from being used even when it is available. Sheesh.
2568 conf->limit_req_body = (apr_off_t)strtol(arg, &errp, 10);
2569 if (*errp != '\0') {
2570 return "LimitRequestBody requires a non-negative integer.";
2576 static const char *set_limit_xml_req_body(cmd_parms *cmd, void *conf_,
2579 core_dir_config *conf = conf_;
2580 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2586 conf->limit_xml_body = atol(arg);
2587 if (conf->limit_xml_body < 0)
2588 return "LimitXMLRequestBody requires a non-negative integer.";
2593 AP_DECLARE(size_t) ap_get_limit_xml_body(const request_rec *r)
2595 core_dir_config *conf;
2597 conf = ap_get_module_config(r->per_dir_config, &core_module);
2598 if (conf->limit_xml_body == AP_LIMIT_UNSET)
2599 return AP_DEFAULT_LIMIT_XML_BODY;
2601 return (size_t)conf->limit_xml_body;
2604 #if !defined (RLIMIT_CPU) || !(defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)) || !defined (RLIMIT_NPROC)
2605 static const char *no_set_limit(cmd_parms *cmd, void *conf_,
2606 const char *arg, const char *arg2)
2608 ap_log_error(APLOG_MARK, APLOG_ERR, 0, cmd->server,
2609 "%s not supported on this platform", cmd->cmd->name);
2616 static const char *set_limit_cpu(cmd_parms *cmd, void *conf_,
2617 const char *arg, const char *arg2)
2619 core_dir_config *conf = conf_;
2621 unixd_set_rlimit(cmd, &conf->limit_cpu, arg, arg2, RLIMIT_CPU);
2626 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)
2627 static const char *set_limit_mem(cmd_parms *cmd, void *conf_,
2628 const char *arg, const char * arg2)
2630 core_dir_config *conf = conf_;
2632 #if defined(RLIMIT_AS)
2633 unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2 ,RLIMIT_AS);
2634 #elif defined(RLIMIT_DATA)
2635 unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_DATA);
2636 #elif defined(RLIMIT_VMEM)
2637 unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_VMEM);
2645 static const char *set_limit_nproc(cmd_parms *cmd, void *conf_,
2646 const char *arg, const char * arg2)
2648 core_dir_config *conf = conf_;
2650 unixd_set_rlimit(cmd, &conf->limit_nproc, arg, arg2, RLIMIT_NPROC);
2655 static const char *set_recursion_limit(cmd_parms *cmd, void *dummy,
2656 const char *arg1, const char *arg2)
2658 core_server_config *conf = ap_get_module_config(cmd->server->module_config,
2660 int limit = atoi(arg1);
2663 return "The recursion limit must be greater than zero.";
2666 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
2667 "Limiting internal redirects to very low numbers may "
2668 "cause normal requests to fail.");
2671 conf->redirect_limit = limit;
2677 return "The recursion limit must be greater than zero.";
2680 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
2681 "Limiting the subrequest depth to a very low level may"
2682 " cause normal requests to fail.");
2686 conf->subreq_limit = limit;
2691 static void log_backtrace(const request_rec *r)
2693 const request_rec *top = r;
2695 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
2696 "r->uri = %s", r->uri ? r->uri : "(unexpectedly NULL)");
2698 while (top && (top->prev || top->main)) {
2701 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
2702 "redirected from r->uri = %s",
2703 top->uri ? top->uri : "(unexpectedly NULL)");
2706 if (!top->prev && top->main) {
2708 ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
2709 "subrequested from r->uri = %s",
2710 top->uri ? top->uri : "(unexpectedly NULL)");
2716 * check whether redirect limit is reached
2718 AP_DECLARE(int) ap_is_recursion_limit_exceeded(const request_rec *r)
2720 core_server_config *conf = ap_get_module_config(r->server->module_config,
2722 const request_rec *top = r;
2723 int redirects = 0, subreqs = 0;
2724 int rlimit = conf->redirect_limit
2725 ? conf->redirect_limit
2726 : AP_DEFAULT_MAX_INTERNAL_REDIRECTS;
2727 int slimit = conf->subreq_limit
2728 ? conf->subreq_limit
2729 : AP_DEFAULT_MAX_SUBREQ_DEPTH;
2732 while (top->prev || top->main) {
2734 if (++redirects >= rlimit) {
2735 /* uuh, too much. */
2736 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
2737 "Request exceeded the limit of %d internal "
2738 "redirects due to probable configuration error. "
2739 "Use 'LimitInternalRecursion' to increase the "
2740 "limit if necessary. Use 'LogLevel debug' to get "
2741 "a backtrace.", rlimit);
2743 /* post backtrace */
2746 /* return failure */
2753 if (!top->prev && top->main) {
2754 if (++subreqs >= slimit) {
2755 /* uuh, too much. */
2756 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
2757 "Request exceeded the limit of %d subrequest "
2758 "nesting levels due to probable confguration "
2759 "error. Use 'LimitInternalRecursion' to increase "
2760 "the limit if necessary. Use 'LogLevel debug' to "
2761 "get a backtrace.", slimit);
2763 /* post backtrace */
2766 /* return failure */
2774 /* recursion state: ok */
2778 static const char *add_ct_output_filters(cmd_parms *cmd, void *conf_,
2779 const char *arg, const char *arg2)
2781 core_dir_config *conf = conf_;
2782 ap_filter_rec_t *old, *new = NULL;
2783 const char *filter_name;
2785 if (!conf->ct_output_filters) {
2786 conf->ct_output_filters = apr_hash_make(cmd->pool);
2790 old = (ap_filter_rec_t*) apr_hash_get(conf->ct_output_filters, arg2,
2791 APR_HASH_KEY_STRING);
2792 /* find last entry */
2801 (filter_name = ap_getword(cmd->pool, &arg, ';')) &&
2802 strcmp(filter_name, "")) {
2803 new = apr_pcalloc(cmd->pool, sizeof(ap_filter_rec_t));
2804 new->name = filter_name;
2806 /* We found something, so let's append it. */
2811 apr_hash_set(conf->ct_output_filters, arg2,
2812 APR_HASH_KEY_STRING, new);
2818 return "invalid filter name";
2824 * Insert filters requested by the AddOutputFilterByType
2825 * configuration directive. We cannot add filters based
2826 * on content-type until after the handler has started
2827 * to run. Only then do we reliably know the content-type.
2829 void ap_add_output_filters_by_type(request_rec *r)
2831 core_dir_config *conf;
2834 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
2837 /* We can't do anything with proxy requests, no content-types or if
2838 * we don't have a filter configured.
2840 if (r->proxyreq != PROXYREQ_NONE || !r->content_type ||
2841 !conf->ct_output_filters) {
2845 /* remove c-t decoration */
2846 ctype = ap_field_noparam(r->pool, r->content_type);
2848 ap_filter_rec_t *ct_filter;
2849 ct_filter = apr_hash_get(conf->ct_output_filters, ctype,
2850 APR_HASH_KEY_STRING);
2852 ap_add_output_filter(ct_filter->name, NULL, r, r->connection);
2853 ct_filter = ct_filter->next;
2860 static apr_status_t writev_it_all(apr_socket_t *s,
2861 struct iovec *vec, int nvec,
2862 apr_size_t len, apr_size_t *nbytes)
2864 apr_size_t bytes_written = 0;
2871 /* XXX handle checking for non-blocking socket */
2872 while (bytes_written != len) {
2873 rv = apr_socket_sendv(s, vec + i, nvec - i, &n);
2876 if (rv != APR_SUCCESS)
2879 /* If the write did not complete, adjust the iovecs and issue
2880 * apr_socket_sendv again
2882 if (bytes_written < len) {
2883 /* Skip over the vectors that have already been written */
2884 apr_size_t cnt = vec[i].iov_len;
2885 while (n >= cnt && i + 1 < nvec) {
2887 cnt += vec[i].iov_len;
2891 /* Handle partial write of vec i */
2892 vec[i].iov_base = (char *) vec[i].iov_base +
2893 (vec[i].iov_len - (cnt - n));
2894 vec[i].iov_len = cnt -n;
2898 n = len - bytes_written;
2904 /* sendfile_it_all()
2905 * send the entire file using sendfile()
2906 * handle partial writes
2907 * return only when all bytes have been sent or an error is encountered.
2910 #if APR_HAS_SENDFILE
2911 static apr_status_t sendfile_it_all(core_net_rec *c,
2914 apr_off_t file_offset,
2915 apr_size_t file_bytes_left,
2916 apr_size_t total_bytes_left,
2917 apr_size_t *bytes_sent,
2922 apr_interval_time_t timeout = 0;
2925 AP_DEBUG_ASSERT((apr_socket_timeout_get(c->client_socket, &timeout)
2927 && timeout > 0); /* socket must be in timeout mode */
2929 /* Reset the bytes_sent field */
2933 apr_size_t tmplen = file_bytes_left;
2935 rv = apr_socket_sendfile(c->client_socket, fd, hdtr, &file_offset, &tmplen,
2937 *bytes_sent += tmplen;
2938 total_bytes_left -= tmplen;
2939 if (!total_bytes_left || rv != APR_SUCCESS) {
2940 return rv; /* normal case & error exit */
2943 AP_DEBUG_ASSERT(total_bytes_left > 0 && tmplen > 0);
2945 /* partial write, oooh noooo...
2946 * Skip over any header data which was written
2948 while (tmplen && hdtr->numheaders) {
2949 if (tmplen >= hdtr->headers[0].iov_len) {
2950 tmplen -= hdtr->headers[0].iov_len;
2955 char *iov_base = (char *)hdtr->headers[0].iov_base;
2957 hdtr->headers[0].iov_len -= tmplen;
2959 hdtr->headers[0].iov_base = iov_base;
2964 /* Skip over any file data which was written */
2966 if (tmplen <= file_bytes_left) {
2967 file_offset += tmplen;
2968 file_bytes_left -= tmplen;
2972 tmplen -= file_bytes_left;
2973 file_bytes_left = 0;
2976 /* Skip over any trailer data which was written */
2978 while (tmplen && hdtr->numtrailers) {
2979 if (tmplen >= hdtr->trailers[0].iov_len) {
2980 tmplen -= hdtr->trailers[0].iov_len;
2981 --hdtr->numtrailers;
2985 char *iov_base = (char *)hdtr->trailers[0].iov_base;
2987 hdtr->trailers[0].iov_len -= tmplen;
2989 hdtr->trailers[0].iov_base = iov_base;
2998 * emulate_sendfile()
2999 * Sends the contents of file fd along with header/trailer bytes, if any,
3000 * to the network. emulate_sendfile will return only when all the bytes have been
3001 * sent (i.e., it handles partial writes) or on a network error condition.
3003 static apr_status_t emulate_sendfile(core_net_rec *c, apr_file_t *fd,
3004 apr_hdtr_t *hdtr, apr_off_t offset,
3005 apr_size_t length, apr_size_t *nbytes)
3007 apr_status_t rv = APR_SUCCESS;
3008 apr_int32_t togo; /* Remaining number of bytes in the file to send */
3009 apr_size_t sendlen = 0;
3010 apr_size_t bytes_sent;
3012 apr_off_t o; /* Track the file offset for partial writes */
3018 * writev_it_all handles partial writes.
3019 * XXX: optimization... if headers are less than MIN_WRITE_SIZE, copy
3022 if (hdtr && hdtr->numheaders > 0 ) {
3023 for (i = 0; i < hdtr->numheaders; i++) {
3024 sendlen += hdtr->headers[i].iov_len;
3027 rv = writev_it_all(c->client_socket, hdtr->headers, hdtr->numheaders,
3028 sendlen, &bytes_sent);
3029 *nbytes += bytes_sent; /* track total bytes sent */
3032 /* Seek the file to 'offset' */
3033 if (offset >= 0 && rv == APR_SUCCESS) {
3034 rv = apr_file_seek(fd, APR_SET, &offset);
3037 /* Send the file, making sure to handle partial writes */
3039 while (rv == APR_SUCCESS && togo) {
3040 sendlen = togo > sizeof(buffer) ? sizeof(buffer) : togo;
3042 rv = apr_file_read(fd, buffer, &sendlen);
3043 while (rv == APR_SUCCESS && sendlen) {
3044 bytes_sent = sendlen;
3045 rv = apr_socket_send(c->client_socket, &buffer[o], &bytes_sent);
3046 *nbytes += bytes_sent;
3047 if (rv == APR_SUCCESS) {
3048 sendlen -= bytes_sent; /* sendlen != bytes_sent ==> partial write */
3049 o += bytes_sent; /* o is where we are in the buffer */
3050 togo -= bytes_sent; /* track how much of the file we've sent */
3055 /* Send the trailers
3056 * XXX: optimization... if it will fit, send this on the last send in the
3060 if ( rv == APR_SUCCESS && hdtr && hdtr->numtrailers > 0 ) {
3061 for (i = 0; i < hdtr->numtrailers; i++) {
3062 sendlen += hdtr->trailers[i].iov_len;
3064 rv = writev_it_all(c->client_socket, hdtr->trailers, hdtr->numtrailers,
3065 sendlen, &bytes_sent);
3066 *nbytes += bytes_sent;
3072 /* Note --- ErrorDocument will now work from .htaccess files.
3073 * The AllowOverride of Fileinfo allows webmasters to turn it off
3076 static const command_rec core_cmds[] = {
3078 /* Old access config file commands */
3080 AP_INIT_RAW_ARGS("<Directory", dirsection, NULL, RSRC_CONF,
3081 "Container for directives affecting resources located in the specified "
3083 AP_INIT_RAW_ARGS("<Location", urlsection, NULL, RSRC_CONF,
3084 "Container for directives affecting resources accessed through the "
3085 "specified URL paths"),
3086 AP_INIT_RAW_ARGS("<VirtualHost", virtualhost_section, NULL, RSRC_CONF,
3087 "Container to map directives to a particular virtual host, takes one or "
3088 "more host addresses"),
3089 AP_INIT_RAW_ARGS("<Files", filesection, NULL, OR_ALL,
3090 "Container for directives affecting files matching specified patterns"),
3091 AP_INIT_RAW_ARGS("<Limit", ap_limit_section, NULL, OR_ALL,
3092 "Container for authentication directives when accessed using specified HTTP "
3094 AP_INIT_RAW_ARGS("<LimitExcept", ap_limit_section, (void*)1, OR_ALL,
3095 "Container for authentication directives to be applied when any HTTP "
3096 "method other than those specified is used to access the resource"),
3097 AP_INIT_TAKE1("<IfModule", start_ifmod, NULL, EXEC_ON_READ | OR_ALL,
3098 "Container for directives based on existance of specified modules"),
3099 AP_INIT_TAKE1("<IfDefine", start_ifdefine, NULL, EXEC_ON_READ | OR_ALL,
3100 "Container for directives based on existance of command line defines"),
3101 AP_INIT_RAW_ARGS("<DirectoryMatch", dirsection, (void*)1, RSRC_CONF,
3102 "Container for directives affecting resources located in the "
3103 "specified directories"),
3104 AP_INIT_RAW_ARGS("<LocationMatch", urlsection, (void*)1, RSRC_CONF,
3105 "Container for directives affecting resources accessed through the "
3106 "specified URL paths"),
3107 AP_INIT_RAW_ARGS("<FilesMatch", filesection, (void*)1, OR_ALL,
3108 "Container for directives affecting files matching specified patterns"),
3109 AP_INIT_TAKE1("AuthType", ap_set_string_slot,
3110 (void*)APR_OFFSETOF(core_dir_config, ap_auth_type), OR_AUTHCFG,
3111 "An HTTP authorization type (e.g., \"Basic\")"),
3112 AP_INIT_TAKE1("AuthName", set_authname, NULL, OR_AUTHCFG,
3113 "The authentication realm (e.g. \"Members Only\")"),
3114 AP_INIT_RAW_ARGS("Require", require, NULL, OR_AUTHCFG,
3115 "Selects which authenticated users or groups may access a protected space"),
3116 AP_INIT_TAKE1("Satisfy", satisfy, NULL, OR_AUTHCFG,
3117 "access policy if both allow and require used ('all' or 'any')"),
3119 AP_INIT_TAKE1("GprofDir", set_gprof_dir, NULL, RSRC_CONF,
3120 "Directory to plop gmon.out files"),
3122 AP_INIT_TAKE1("AddDefaultCharset", set_add_default_charset, NULL, OR_FILEINFO,
3123 "The name of the default charset to add to any Content-Type without one or 'Off' to disable"),
3124 AP_INIT_TAKE1("AcceptPathInfo", set_accept_path_info, NULL, OR_FILEINFO,
3125 "Set to on or off for PATH_INFO to be accepted by handlers, or default for the per-handler preference"),
3127 /* Old resource config file commands */
3129 AP_INIT_RAW_ARGS("AccessFileName", set_access_name, NULL, RSRC_CONF,
3130 "Name(s) of per-directory config files (default: .htaccess)"),
3131 AP_INIT_TAKE1("DocumentRoot", set_document_root, NULL, RSRC_CONF,
3132 "Root directory of the document tree"),
3133 AP_INIT_TAKE2("ErrorDocument", set_error_document, NULL, OR_FILEINFO,
3134 "Change responses for HTTP errors"),
3135 AP_INIT_RAW_ARGS("AllowOverride", set_override, NULL, ACCESS_CONF,
3136 "Controls what groups of directives can be configured by per-directory "
3138 AP_INIT_RAW_ARGS("Options", set_options, NULL, OR_OPTIONS,
3139 "Set a number of attributes for a given directory"),
3140 AP_INIT_TAKE1("DefaultType", ap_set_string_slot,
3141 (void*)APR_OFFSETOF(core_dir_config, ap_default_type),
3142 OR_FILEINFO, "the default MIME type for untypable files"),
3143 AP_INIT_RAW_ARGS("FileETag", set_etag_bits, NULL, OR_FILEINFO,
3144 "Specify components used to construct a file's ETag"),
3145 AP_INIT_TAKE1("EnableMMAP", set_enable_mmap, NULL, OR_FILEINFO,
3146 "Controls whether memory-mapping may be used to read files"),
3147 AP_INIT_TAKE1("EnableSendfile", set_enable_sendfile, NULL, OR_FILEINFO,
3148 "Controls whether sendfile may be used to transmit files"),
3150 /* Old server config file commands */
3152 AP_INIT_TAKE1("Port", ap_set_deprecated, NULL, RSRC_CONF,
3153 "Port was replaced with Listen in Apache 2.0"),
3154 AP_INIT_TAKE1("HostnameLookups", set_hostname_lookups, NULL,
3155 ACCESS_CONF|RSRC_CONF,
3156 "\"on\" to enable, \"off\" to disable reverse DNS lookups, or \"double\" to "
3157 "enable double-reverse DNS lookups"),
3158 AP_INIT_TAKE1("ServerAdmin", set_server_string_slot,
3159 (void *)APR_OFFSETOF(server_rec, server_admin), RSRC_CONF,
3160 "The email address of the server administrator"),
3161 AP_INIT_TAKE1("ServerName", server_hostname_port, NULL, RSRC_CONF,
3162 "The hostname and port of the server"),
3163 AP_INIT_TAKE1("ServerSignature", set_signature_flag, NULL, OR_ALL,
3164 "En-/disable server signature (on|off|email)"),
3165 AP_INIT_TAKE1("ServerRoot", set_server_root, NULL, RSRC_CONF | EXEC_ON_READ,
3166 "Common directory of server-related files (logs, confs, etc.)"),
3167 AP_INIT_TAKE1("ErrorLog", set_server_string_slot,
3168 (void *)APR_OFFSETOF(server_rec, error_fname), RSRC_CONF,
3169 "The filename of the error log"),
3170 AP_INIT_RAW_ARGS("ServerAlias", set_server_alias, NULL, RSRC_CONF,
3171 "A name or names alternately used to access the server"),
3172 AP_INIT_TAKE1("ServerPath", set_serverpath, NULL, RSRC_CONF,
3173 "The pathname the server can be reached at"),
3174 AP_INIT_TAKE1("Timeout", set_timeout, NULL, RSRC_CONF,
3175 "Timeout duration (sec)"),
3176 AP_INIT_FLAG("ContentDigest", set_content_md5, NULL, OR_OPTIONS,
3177 "whether or not to send a Content-MD5 header with each request"),
3178 AP_INIT_TAKE1("UseCanonicalName", set_use_canonical_name, NULL,
3179 RSRC_CONF|ACCESS_CONF,
3180 "How to work out the ServerName : Port when constructing URLs"),
3181 /* TODO: RlimitFoo should all be part of mod_cgi, not in the core */
3182 /* TODO: ListenBacklog in MPM */
3183 AP_INIT_TAKE1("Include", include_config, NULL,
3184 (RSRC_CONF | ACCESS_CONF | EXEC_ON_READ),
3185 "Name of the config file to be included"),
3186 AP_INIT_TAKE1("LogLevel", set_loglevel, NULL, RSRC_CONF,
3187 "Level of verbosity in error logging"),
3188 AP_INIT_TAKE1("NameVirtualHost", ap_set_name_virtual_host, NULL, RSRC_CONF,
3189 "A numeric IP address:port, or the name of a host"),
3190 AP_INIT_TAKE1("ServerTokens", set_serv_tokens, NULL, RSRC_CONF,
3191 "Determine tokens displayed in the Server: header - Min(imal), OS or Full"),
3192 AP_INIT_TAKE1("LimitRequestLine", set_limit_req_line, NULL, RSRC_CONF,
3193 "Limit on maximum size of an HTTP request line"),
3194 AP_INIT_TAKE1("LimitRequestFieldsize", set_limit_req_fieldsize, NULL,
3196 "Limit on maximum size of an HTTP request header field"),
3197 AP_INIT_TAKE1("LimitRequestFields", set_limit_req_fields, NULL, RSRC_CONF,
3198 "Limit (0 = unlimited) on max number of header fields in a request message"),
3199 AP_INIT_TAKE1("LimitRequestBody", set_limit_req_body,
3200 (void*)APR_OFFSETOF(core_dir_config, limit_req_body), OR_ALL,
3201 "Limit (in bytes) on maximum size of request message body"),
3202 AP_INIT_TAKE1("LimitXMLRequestBody", set_limit_xml_req_body, NULL, OR_ALL,
3203 "Limit (in bytes) on maximum size of an XML-based request "
3206 /* System Resource Controls */
3208 AP_INIT_TAKE12("RLimitCPU", set_limit_cpu,
3209 (void*)APR_OFFSETOF(core_dir_config, limit_cpu),
3210 OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
3212 AP_INIT_TAKE12("RLimitCPU", no_set_limit, NULL,
3213 OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
3215 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined (RLIMIT_AS)
3216 AP_INIT_TAKE12("RLimitMEM", set_limit_mem,
3217 (void*)APR_OFFSETOF(core_dir_config, limit_mem),
3218 OR_ALL, "Soft/hard limits for max memory usage per process"),
3220 AP_INIT_TAKE12("RLimitMEM", no_set_limit, NULL,
3221 OR_ALL, "Soft/hard limits for max memory usage per process"),
3224 AP_INIT_TAKE12("RLimitNPROC", set_limit_nproc,
3225 (void*)APR_OFFSETOF(core_dir_config, limit_nproc),
3226 OR_ALL, "soft/hard limits for max number of processes per uid"),
3228 AP_INIT_TAKE12("RLimitNPROC", no_set_limit, NULL,
3229 OR_ALL, "soft/hard limits for max number of processes per uid"),
3232 /* internal recursion stopper */
3233 AP_INIT_TAKE12("LimitInternalRecursion", set_recursion_limit, NULL, RSRC_CONF,
3234 "maximum recursion depth of internal redirects and subrequests"),
3236 AP_INIT_TAKE1("ForceType", ap_set_string_slot_lower,
3237 (void *)APR_OFFSETOF(core_dir_config, mime_type), OR_FILEINFO,
3238 "a mime type that overrides other configured type"),
3239 AP_INIT_TAKE1("SetHandler", ap_set_string_slot_lower,
3240 (void *)APR_OFFSETOF(core_dir_config, handler), OR_FILEINFO,
3241 "a handler name that overrides any other configured handler"),
3242 AP_INIT_TAKE1("SetOutputFilter", ap_set_string_slot,
3243 (void *)APR_OFFSETOF(core_dir_config, output_filters), OR_FILEINFO,
3244 "filter (or ; delimited list of filters) to be run on the request content"),
3245 AP_INIT_TAKE1("SetInputFilter", ap_set_string_slot,
3246 (void *)APR_OFFSETOF(core_dir_config, input_filters), OR_FILEINFO,
3247 "filter (or ; delimited list of filters) to be run on the request body"),
3248 AP_INIT_ITERATE2("AddOutputFilterByType", add_ct_output_filters,
3249 (void *)APR_OFFSETOF(core_dir_config, ct_output_filters), OR_FILEINFO,
3250 "output filter name followed by one or more content-types"),
3251 AP_INIT_FLAG("AllowEncodedSlashes", set_allow2f, NULL, RSRC_CONF,
3252 "Allow URLs containing '/' encoded as '%2F'"),
3255 * These are default configuration directives that mpms can/should
3256 * pay attention to. If an mpm wishes to use these, they should
3257 * #defined them in mpm.h.
3259 #ifdef AP_MPM_WANT_SET_PIDFILE
3260 AP_INIT_TAKE1("PidFile", ap_mpm_set_pidfile, NULL, RSRC_CONF,
3261 "A file for logging the server process ID"),
3263 #ifdef AP_MPM_WANT_SET_SCOREBOARD
3264 AP_INIT_TAKE1("ScoreBoardFile", ap_mpm_set_scoreboard, NULL, RSRC_CONF,
3265 "A file for Apache to maintain runtime process management information"),
3267 #ifdef AP_MPM_WANT_SET_LOCKFILE
3268 AP_INIT_TAKE1("LockFile", ap_mpm_set_lockfile, NULL, RSRC_CONF,
3269 "The lockfile used when Apache needs to lock the accept() call"),
3271 #ifdef AP_MPM_WANT_SET_MAX_REQUESTS
3272 AP_INIT_TAKE1("MaxRequestsPerChild", ap_mpm_set_max_requests, NULL, RSRC_CONF,
3273 "Maximum number of requests a particular child serves before dying."),
3275 #ifdef AP_MPM_WANT_SET_COREDUMPDIR
3276 AP_INIT_TAKE1("CoreDumpDirectory", ap_mpm_set_coredumpdir, NULL, RSRC_CONF,
3277 "The location of the directory Apache changes to before dumping core"),
3279 #ifdef AP_MPM_WANT_SET_ACCEPT_LOCK_MECH
3280 AP_INIT_TAKE1("AcceptMutex", ap_mpm_set_accept_lock_mech, NULL, RSRC_CONF,
3281 ap_valid_accept_mutex_string),
3283 #ifdef AP_MPM_WANT_SET_MAX_MEM_FREE
3284 AP_INIT_TAKE1("MaxMemFree", ap_mpm_set_max_mem_free, NULL, RSRC_CONF,
3285 "Maximum number of 1k blocks a particular childs allocator may hold."),
3287 #ifdef AP_MPM_WANT_SET_STACKSIZE
3288 AP_INIT_TAKE1("ThreadStackSize", ap_mpm_set_thread_stacksize, NULL, RSRC_CONF,
3289 "Size in bytes of stack used by threads handling client connections"),
3291 #if AP_ENABLE_EXCEPTION_HOOK
3292 AP_INIT_TAKE1("EnableExceptionHook", ap_mpm_set_exception_hook, NULL, RSRC_CONF,
3293 "Controls whether exception hook may be called after a crash"),
3298 /*****************************************************************
3300 * Core handlers for various phases of server operation...
3303 AP_DECLARE_NONSTD(int) ap_core_translate(request_rec *r)
3305 void *sconf = r->server->module_config;
3306 core_server_config *conf = ap_get_module_config(sconf, &core_module);
3309 /* XXX this seems too specific, this should probably become
3310 * some general-case test
3313 return HTTP_FORBIDDEN;
3315 if (!r->uri || ((r->uri[0] != '/') && strcmp(r->uri, "*"))) {
3316 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3317 "Invalid URI in request %s", r->the_request);
3318 return HTTP_BAD_REQUEST;
3322 && !strncmp(r->uri, r->server->path, r->server->pathlen)
3323 && (r->server->path[r->server->pathlen - 1] == '/'
3324 || r->uri[r->server->pathlen] == '/'
3325 || r->uri[r->server->pathlen] == '\0'))
3327 /* skip all leading /'s (e.g. http://localhost///foo)
3328 * so we are looking at only the relative path.
3330 char *path = r->uri + r->server->pathlen;
3331 while (*path == '/') {
3334 if ((rv = apr_filepath_merge(&r->filename, conf->ap_document_root, path,
3335 APR_FILEPATH_TRUENAME
3336 | APR_FILEPATH_SECUREROOT, r->pool))
3338 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
3339 "Cannot map %s to file", r->the_request);
3340 return HTTP_FORBIDDEN;
3342 r->canonical_filename = r->filename;
3346 * Make sure that we do not mess up the translation by adding two
3347 * /'s in a row. This happens under windows when the document
3348 * root ends with a /
3350 /* skip all leading /'s (e.g. http://localhost///foo)
3351 * so we are looking at only the relative path.
3353 char *path = r->uri;
3354 while (*path == '/') {
3357 if ((rv = apr_filepath_merge(&r->filename, conf->ap_document_root, path,
3358 APR_FILEPATH_TRUENAME
3359 | APR_FILEPATH_SECUREROOT, r->pool))
3361 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
3362 "Cannot map %s to file", r->the_request);
3363 return HTTP_FORBIDDEN;
3365 r->canonical_filename = r->filename;
3371 /*****************************************************************
3373 * Test the filesystem name through directory_walk and file_walk
3375 static int core_map_to_storage(request_rec *r)
3379 if ((access_status = ap_directory_walk(r))) {
3380 return access_status;
3383 if ((access_status = ap_file_walk(r))) {
3384 return access_status;
3391 static int do_nothing(request_rec *r) { return OK; }
3394 static int core_override_type(request_rec *r)
3396 core_dir_config *conf =
3397 (core_dir_config *)ap_get_module_config(r->per_dir_config,
3400 /* Check for overrides with ForceType / SetHandler
3402 if (conf->mime_type && strcmp(conf->mime_type, "none"))
3403 ap_set_content_type(r, (char*) conf->mime_type);
3405 if (conf->handler && strcmp(conf->handler, "none"))
3406 r->handler = conf->handler;
3408 /* Deal with the poor soul who is trying to force path_info to be
3409 * accepted within the core_handler, where they will let the subreq
3410 * address its contents. This is toggled by the user in the very
3411 * beginning of the fixup phase, so modules should override the user's
3412 * discretion in their own module fixup phase. It is tristate, if
3413 * the user doesn't specify, the result is 2 (which the module may
3414 * interpret to its own customary behavior.) It won't be touched
3415 * if the value is no longer undefined (2), so any module changing
3416 * the value prior to the fixup phase OVERRIDES the user's choice.
3418 if ((r->used_path_info == AP_REQ_DEFAULT_PATH_INFO)
3419 && (conf->accept_path_info != 3)) {
3420 r->used_path_info = conf->accept_path_info;
3428 static int default_handler(request_rec *r)
3430 conn_rec *c = r->connection;
3431 apr_bucket_brigade *bb;
3435 apr_file_t *fd = NULL;
3436 apr_status_t status;
3437 /* XXX if/when somebody writes a content-md5 filter we either need to
3438 * remove this support or coordinate when to use the filter vs.
3439 * when to use this code
3440 * The current choice of when to compute the md5 here matches the 1.3
3441 * support fairly closely (unlike 1.3, we don't handle computing md5
3442 * when the charset is translated).
3444 int bld_content_md5;
3446 d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
3448 bld_content_md5 = (d->content_md5 & 1)
3449 && r->output_filters->frec->ftype != AP_FTYPE_RESOURCE;
3451 ap_allow_standard_methods(r, MERGE_ALLOW, M_GET, M_OPTIONS, M_POST, -1);
3453 /* If filters intend to consume the request body, they must
3454 * register an InputFilter to slurp the contents of the POST
3455 * data from the POST input stream. It no longer exists when
3456 * the output filters are invoked by the default handler.
3458 if ((errstatus = ap_discard_request_body(r)) != OK) {
3462 if (r->method_number == M_GET || r->method_number == M_POST) {
3463 if (r->finfo.filetype == 0) {
3464 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3465 "File does not exist: %s", r->filename);
3466 return HTTP_NOT_FOUND;
3469 /* Don't try to serve a dir. Some OSs do weird things with
3472 if (r->finfo.filetype == APR_DIR) {
3473 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3474 "Attempt to serve directory: %s", r->filename);
3475 return HTTP_NOT_FOUND;
3478 if ((r->used_path_info != AP_REQ_ACCEPT_PATH_INFO) &&
3479 r->path_info && *r->path_info)
3481 /* default to reject */
3482 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3483 "File does not exist: %s",
3484 apr_pstrcat(r->pool, r->filename, r->path_info, NULL));
3485 return HTTP_NOT_FOUND;
3488 /* We understood the (non-GET) method, but it might not be legal for
3489 this particular resource. Check to see if the 'deliver_script'
3490 flag is set. If so, then we go ahead and deliver the file since
3491 it isn't really content (only GET normally returns content).
3493 Note: based on logic further above, the only possible non-GET
3494 method at this point is POST. In the future, we should enable
3495 script delivery for all methods. */
3496 if (r->method_number != M_GET) {
3497 core_request_config *req_cfg;
3499 req_cfg = ap_get_module_config(r->request_config, &core_module);
3500 if (!req_cfg->deliver_script) {
3501 /* The flag hasn't been set for this request. Punt. */
3502 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3503 "This resource does not accept the %s method.",
3505 return HTTP_METHOD_NOT_ALLOWED;
3510 if ((status = apr_file_open(&fd, r->filename, APR_READ | APR_BINARY
3511 #if APR_HAS_SENDFILE
3512 | ((d->enable_sendfile == ENABLE_SENDFILE_OFF)
3513 ? 0 : APR_SENDFILE_ENABLED)
3515 , 0, r->pool)) != APR_SUCCESS) {
3516 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r,
3517 "file permissions deny server access: %s", r->filename);
3518 return HTTP_FORBIDDEN;
3521 ap_update_mtime(r, r->finfo.mtime);
3522 ap_set_last_modified(r);
3524 apr_table_setn(r->headers_out, "Accept-Ranges", "bytes");
3525 ap_set_content_length(r, r->finfo.size);
3526 if ((errstatus = ap_meets_conditions(r)) != OK) {
3531 if (bld_content_md5) {
3532 apr_table_setn(r->headers_out, "Content-MD5",
3533 ap_md5digest(r->pool, fd));
3536 bb = apr_brigade_create(r->pool, c->bucket_alloc);
3537 #if APR_HAS_LARGE_FILES
3538 #if APR_HAS_SENDFILE
3539 if ((d->enable_sendfile != ENABLE_SENDFILE_OFF) &&
3543 (r->finfo.size > AP_MAX_SENDFILE)) {
3544 /* APR_HAS_LARGE_FILES issue; must split into mutiple buckets,
3545 * no greater than MAX(apr_size_t), and more granular than that
3546 * in case the brigade code/filters attempt to read it directly.
3548 apr_off_t fsize = r->finfo.size;
3549 e = apr_bucket_file_create(fd, 0, AP_MAX_SENDFILE, r->pool,
3551 while (fsize > AP_MAX_SENDFILE) {
3553 apr_bucket_copy(e, &ce);
3554 APR_BRIGADE_INSERT_TAIL(bb, ce);
3555 e->start += AP_MAX_SENDFILE;
3556 fsize -= AP_MAX_SENDFILE;
3558 e->length = (apr_size_t)fsize; /* Resize just the last bucket */
3562 e = apr_bucket_file_create(fd, 0, (apr_size_t)r->finfo.size,
3563 r->pool, c->bucket_alloc);
3566 if (d->enable_mmap == ENABLE_MMAP_OFF) {
3567 (void)apr_bucket_file_enable_mmap(e, 0);
3570 APR_BRIGADE_INSERT_TAIL(bb, e);
3571 e = apr_bucket_eos_create(c->bucket_alloc);
3572 APR_BRIGADE_INSERT_TAIL(bb, e);
3574 return ap_pass_brigade(r->output_filters, bb);
3576 else { /* unusual method (not GET or POST) */
3577 if (r->method_number == M_INVALID) {
3578 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3579 "Invalid method in request %s", r->the_request);
3580 return HTTP_NOT_IMPLEMENTED;
3583 if (r->method_number == M_OPTIONS) {
3584 return ap_send_http_options(r);
3586 return HTTP_METHOD_NOT_ALLOWED;
3590 typedef struct net_time_filter_ctx {
3593 } net_time_filter_ctx_t;
3594 static int net_time_filter(ap_filter_t *f, apr_bucket_brigade *b,
3595 ap_input_mode_t mode, apr_read_type_e block,
3596 apr_off_t readbytes)
3598 net_time_filter_ctx_t *ctx = f->ctx;
3599 int keptalive = f->c->keepalive == AP_CONN_KEEPALIVE;
3602 f->ctx = ctx = apr_palloc(f->r->pool, sizeof(*ctx));
3603 ctx->first_line = 1;
3604 ctx->csd = ap_get_module_config(f->c->conn_config, &core_module);
3607 if (mode != AP_MODE_INIT && mode != AP_MODE_EATCRLF) {
3608 if (ctx->first_line) {
3609 apr_socket_timeout_set(ctx->csd,
3611 ? f->c->base_server->keep_alive_timeout
3612 : f->c->base_server->timeout);
3613 ctx->first_line = 0;
3617 apr_socket_timeout_set(ctx->csd, f->c->base_server->timeout);
3621 return ap_get_brigade(f->next, b, mode, block, readbytes);
3625 * Remove all zero length buckets from the brigade.
3627 #define BRIGADE_NORMALIZE(b) \
3629 apr_bucket *e = APR_BRIGADE_FIRST(b); \
3631 if (e->length == 0 && !APR_BUCKET_IS_METADATA(e)) { \
3633 d = APR_BUCKET_NEXT(e); \
3634 apr_bucket_delete(e); \
3637 e = APR_BUCKET_NEXT(e); \
3638 } while (!APR_BRIGADE_EMPTY(b) && (e != APR_BRIGADE_SENTINEL(b))); \
3641 static int core_input_filter(ap_filter_t *f, apr_bucket_brigade *b,
3642 ap_input_mode_t mode, apr_read_type_e block,
3643 apr_off_t readbytes)
3647 core_net_rec *net = f->ctx;
3648 core_ctx_t *ctx = net->in_ctx;
3652 if (mode == AP_MODE_INIT) {
3654 * this mode is for filters that might need to 'initialize'
3655 * a connection before reading request data from a client.
3656 * NNTP over SSL for example needs to handshake before the
3657 * server sends the welcome message.
3658 * such filters would have changed the mode before this point
3659 * is reached. however, protocol modules such as NNTP should
3660 * not need to know anything about SSL. given the example, if
3661 * SSL is not in the filter chain, AP_MODE_INIT is a noop.
3668 ctx = apr_pcalloc(f->c->pool, sizeof(*ctx));
3669 ctx->b = apr_brigade_create(f->c->pool, f->c->bucket_alloc);
3671 /* seed the brigade with the client socket. */
3672 e = apr_bucket_socket_create(net->client_socket, f->c->bucket_alloc);
3673 APR_BRIGADE_INSERT_TAIL(ctx->b, e);
3676 else if (APR_BRIGADE_EMPTY(ctx->b)) {
3680 /* ### This is bad. */
3681 BRIGADE_NORMALIZE(ctx->b);
3683 /* check for empty brigade again *AFTER* BRIGADE_NORMALIZE()
3684 * If we have lost our socket bucket (see above), we are EOF.
3686 * Ideally, this should be returning SUCCESS with EOS bucket, but
3687 * some higher-up APIs (spec. read_request_line via ap_rgetline)
3688 * want an error code. */
3689 if (APR_BRIGADE_EMPTY(ctx->b)) {
3693 if (mode == AP_MODE_GETLINE) {
3694 /* we are reading a single LF line, e.g. the HTTP headers */
3695 rv = apr_brigade_split_line(b, ctx->b, block, HUGE_STRING_LEN);
3696 /* We should treat EAGAIN here the same as we do for EOF (brigade is
3697 * empty). We do this by returning whatever we have read. This may
3698 * or may not be bogus, but is consistent (for now) with EOF logic.
3700 if (APR_STATUS_IS_EAGAIN(rv)) {
3706 /* ### AP_MODE_PEEK is a horrific name for this mode because we also
3707 * eat any CRLFs that we see. That's not the obvious intention of
3708 * this mode. Determine whether anyone actually uses this or not. */
3709 if (mode == AP_MODE_EATCRLF) {
3713 /* The purpose of this loop is to ignore any CRLF (or LF) at the end
3714 * of a request. Many browsers send extra lines at the end of POST
3715 * requests. We use the PEEK method to determine if there is more
3716 * data on the socket, so that we know if we should delay sending the
3717 * end of one request until we have served the second request in a
3718 * pipelined situation. We don't want to actually delay sending a
3719 * response if the server finds a CRLF (or LF), becuause that doesn't
3720 * mean that there is another request, just a blank line.
3723 if (APR_BRIGADE_EMPTY(ctx->b))
3726 e = APR_BRIGADE_FIRST(ctx->b);
3728 rv = apr_bucket_read(e, &str, &len, APR_NONBLOCK_READ);
3730 if (rv != APR_SUCCESS)
3734 while (c < str + len) {
3735 if (*c == APR_ASCII_LF)
3737 else if (*c == APR_ASCII_CR && *(c + 1) == APR_ASCII_LF)
3743 /* If we reach here, we were a bucket just full of CRLFs, so
3744 * just toss the bucket. */
3745 /* FIXME: Is this the right thing to do in the core? */
3746 apr_bucket_delete(e);
3751 /* If mode is EXHAUSTIVE, we want to just read everything until the end
3752 * of the brigade, which in this case means the end of the socket.
3753 * To do this, we attach the brigade that has currently been setaside to
3754 * the brigade that was passed down, and send that brigade back.
3756 * NOTE: This is VERY dangerous to use, and should only be done with
3757 * extreme caution. However, the Perchild MPM needs this feature
3758 * if it is ever going to work correctly again. With this, the Perchild
3759 * MPM can easily request the socket and all data that has been read,
3760 * which means that it can pass it to the correct child process.
3762 if (mode == AP_MODE_EXHAUSTIVE) {
3765 /* Tack on any buckets that were set aside. */
3766 APR_BRIGADE_CONCAT(b, ctx->b);
3768 /* Since we've just added all potential buckets (which will most
3769 * likely simply be the socket bucket) we know this is the end,
3770 * so tack on an EOS too. */
3771 /* We have read until the brigade was empty, so we know that we
3773 e = apr_bucket_eos_create(f->c->bucket_alloc);
3774 APR_BRIGADE_INSERT_TAIL(b, e);
3778 /* read up to the amount they specified. */
3779 if (mode == AP_MODE_READBYTES || mode == AP_MODE_SPECULATIVE) {
3781 apr_bucket_brigade *newbb;
3783 AP_DEBUG_ASSERT(readbytes > 0);
3785 e = APR_BRIGADE_FIRST(ctx->b);
3786 rv = apr_bucket_read(e, &str, &len, block);
3788 if (APR_STATUS_IS_EAGAIN(rv)) {
3791 else if (rv != APR_SUCCESS) {
3794 else if (block == APR_BLOCK_READ && len == 0) {
3795 /* We wanted to read some bytes in blocking mode. We read
3796 * 0 bytes. Hence, we now assume we are EOS.
3798 * When we are in normal mode, return an EOS bucket to the
3800 * When we are in speculative mode, leave ctx->b empty, so
3801 * that the next call returns an EOS bucket.
3803 apr_bucket_delete(e);
3805 if (mode == AP_MODE_READBYTES) {
3806 e = apr_bucket_eos_create(f->c->bucket_alloc);
3807 APR_BRIGADE_INSERT_TAIL(b, e);
3812 /* We can only return at most what we read. */
3813 if (len < readbytes) {
3817 rv = apr_brigade_partition(ctx->b, readbytes, &e);
3818 if (rv != APR_SUCCESS) {
3822 /* Must do split before CONCAT */
3823 newbb = apr_brigade_split(ctx->b, e);
3825 if (mode == AP_MODE_READBYTES) {
3826 APR_BRIGADE_CONCAT(b, ctx->b);
3828 else if (mode == AP_MODE_SPECULATIVE) {
3829 apr_bucket *copy_bucket;
3831 for (e = APR_BRIGADE_FIRST(ctx->b);
3832 e != APR_BRIGADE_SENTINEL(ctx->b);
3833 e = APR_BUCKET_NEXT(e))
3835 rv = apr_bucket_copy(e, ©_bucket);
3836 if (rv != APR_SUCCESS) {
3839 APR_BRIGADE_INSERT_TAIL(b, copy_bucket);
3843 /* Take what was originally there and place it back on ctx->b */
3844 APR_BRIGADE_CONCAT(ctx->b, newbb);
3849 #define MAX_IOVEC_TO_WRITE 16
3851 /* Optional function coming from mod_logio, used for logging of output
3854 static APR_OPTIONAL_FN_TYPE(ap_logio_add_bytes_out) *logio_add_bytes_out;
3856 static apr_status_t core_output_filter(ap_filter_t *f, apr_bucket_brigade *b)
3859 apr_bucket_brigade *more;
3861 core_net_rec *net = f->ctx;
3862 core_output_filter_ctx_t *ctx = net->out_ctx;
3863 apr_read_type_e eblock = APR_NONBLOCK_READ;
3864 apr_pool_t *input_pool = b->p;
3867 ctx = apr_pcalloc(c->pool, sizeof(*ctx));
3871 /* If we have a saved brigade, concatenate the new brigade to it */
3873 APR_BRIGADE_CONCAT(ctx->b, b);
3878 /* Perform multiple passes over the brigade, sending batches of output
3879 to the connection. */
3880 while (b && !APR_BRIGADE_EMPTY(b)) {
3881 apr_size_t nbytes = 0;
3882 apr_bucket *last_e = NULL; /* initialized for debugging */
3885 /* one group of iovecs per pass over the brigade */
3886 apr_size_t nvec = 0;
3887 apr_size_t nvec_trailers = 0;
3888 struct iovec vec[MAX_IOVEC_TO_WRITE];
3889 struct iovec vec_trailers[MAX_IOVEC_TO_WRITE];
3891 /* one file per pass over the brigade */
3892 apr_file_t *fd = NULL;
3893 apr_size_t flen = 0;
3894 apr_off_t foffset = 0;
3896 /* keep track of buckets that we've concatenated
3897 * to avoid small writes
3899 apr_bucket *last_merged_bucket = NULL;
3901 /* tail of brigade if we need another pass */
3904 /* Iterate over the brigade: collect iovecs and/or a file */
3905 for (e = APR_BRIGADE_FIRST(b);
3906 e != APR_BRIGADE_SENTINEL(b);
3907 e = APR_BUCKET_NEXT(e))
3909 /* keep track of the last bucket processed */
3911 if (APR_BUCKET_IS_EOS(e)) {
3914 if (AP_BUCKET_IS_EOC(e)) {
3915 apr_bucket_delete(e);
3917 else if (APR_BUCKET_IS_FLUSH(e)) {
3918 if (e != APR_BRIGADE_LAST(b)) {
3919 more = apr_brigade_split(b, APR_BUCKET_NEXT(e));
3924 /* It doesn't make any sense to use sendfile for a file bucket
3925 * that represents 10 bytes.
3927 else if (APR_BUCKET_IS_FILE(e)
3928 && (e->length >= AP_MIN_SENDFILE_BYTES)) {
3929 apr_bucket_file *a = e->data;
3931 /* We can't handle more than one file bucket at a time
3932 * so we split here and send the file we have already
3936 more = apr_brigade_split(b, e);
3948 rv = apr_bucket_read(e, &str, &n, eblock);
3949 if (APR_STATUS_IS_EAGAIN(rv)) {
3950 /* send what we have so far since we shouldn't expect more
3951 * output for a while... next time we read, block
3953 more = apr_brigade_split(b, e);
3954 eblock = APR_BLOCK_READ;
3957 eblock = APR_NONBLOCK_READ;
3960 if (nvec == MAX_IOVEC_TO_WRITE) {
3961 /* woah! too many. buffer them up, for use later. */
3962 apr_bucket *temp, *next;
3963 apr_bucket_brigade *temp_brig;
3965 if (nbytes >= AP_MIN_BYTES_TO_WRITE) {
3966 /* We have enough data in the iovec
3967 * to justify doing a writev
3969 more = apr_brigade_split(b, e);
3973 /* Create a temporary brigade as a means
3974 * of concatenating a bunch of buckets together
3976 if (last_merged_bucket) {
3977 /* If we've concatenated together small
3978 * buckets already in a previous pass,
3979 * the initial buckets in this brigade
3980 * are heap buckets that may have extra
3981 * space left in them (because they
3982 * were created by apr_brigade_write()).
3983 * We can take advantage of this by
3984 * building the new temp brigade out of
3985 * these buckets, so that the content
3986 * in them doesn't have to be copied again.
3988 apr_bucket_brigade *bb;
3989 bb = apr_brigade_split(b,
3990 APR_BUCKET_NEXT(last_merged_bucket));
3995 temp_brig = apr_brigade_create(f->c->pool,
3996 f->c->bucket_alloc);
3999 temp = APR_BRIGADE_FIRST(b);
4002 rv = apr_bucket_read(temp, &str, &n, APR_BLOCK_READ);
4003 apr_brigade_write(temp_brig, NULL, NULL, str, n);
4005 temp = APR_BUCKET_NEXT(temp);
4006 apr_bucket_delete(d);
4011 temp = APR_BRIGADE_FIRST(temp_brig);
4012 APR_BUCKET_REMOVE(temp);
4013 APR_BRIGADE_INSERT_HEAD(b, temp);
4014 apr_bucket_read(temp, &str, &n, APR_BLOCK_READ);
4015 vec[nvec].iov_base = (char*) str;
4016 vec[nvec].iov_len = n;
4019 /* Just in case the temporary brigade has
4020 * multiple buckets, recover the rest of
4021 * them and put them in the brigade that
4024 for (next = APR_BRIGADE_FIRST(temp_brig);
4025 next != APR_BRIGADE_SENTINEL(temp_brig);
4026 next = APR_BRIGADE_FIRST(temp_brig)) {
4027 APR_BUCKET_REMOVE(next);
4028 APR_BUCKET_INSERT_AFTER(temp, next);
4030 apr_bucket_read(next, &str, &n,
4032 vec[nvec].iov_base = (char*) str;
4033 vec[nvec].iov_len = n;
4037 apr_brigade_destroy(temp_brig);
4039 last_merged_bucket = temp;
4044 vec[nvec].iov_base = (char*) str;
4045 vec[nvec].iov_len = n;
4050 /* The bucket is a trailer to a file bucket */
4052 if (nvec_trailers == MAX_IOVEC_TO_WRITE) {
4053 /* woah! too many. stop now. */
4054 more = apr_brigade_split(b, e);
4058 vec_trailers[nvec_trailers].iov_base = (char*) str;
4059 vec_trailers[nvec_trailers].iov_len = n;
4069 /* Completed iterating over the brigade, now determine if we want
4070 * to buffer the brigade or send the brigade out on the network.
4072 * Save if we haven't accumulated enough bytes to send, and:
4074 * 1) we didn't see a file, we don't have more passes over the
4075 * brigade to perform, AND we didn't stop at a FLUSH bucket.
4076 * (IOW, we will save plain old bytes such as HTTP headers)
4078 * 2) we hit the EOS and have a keep-alive connection
4079 * (IOW, this response is a bit more complex, but we save it
4080 * with the hope of concatenating with another response)
4082 if (nbytes + flen < AP_MIN_BYTES_TO_WRITE
4083 && ((!fd && !more && !APR_BUCKET_IS_FLUSH(last_e))
4084 || (APR_BUCKET_IS_EOS(last_e)
4085 && c->keepalive == AP_CONN_KEEPALIVE))) {
4087 /* NEVER save an EOS in here. If we are saving a brigade with
4088 * an EOS bucket, then we are doing keepalive connections, and
4089 * we want to process to second request fully.
4091 if (APR_BUCKET_IS_EOS(last_e)) {
4093 int file_bucket_saved = 0;
4094 apr_bucket_delete(last_e);
4095 for (bucket = APR_BRIGADE_FIRST(b);
4096 bucket != APR_BRIGADE_SENTINEL(b);
4097 bucket = APR_BUCKET_NEXT(bucket)) {
4099 /* Do a read on each bucket to pull in the
4100 * data from pipe and socket buckets, so
4101 * that we don't leave their file descriptors
4102 * open indefinitely. Do the same for file
4103 * buckets, with one exception: allow the
4104 * first file bucket in the brigade to remain
4105 * a file bucket, so that we don't end up
4106 * doing an mmap+memcpy every time a client
4107 * requests a <8KB file over a keepalive
4110 if (APR_BUCKET_IS_FILE(bucket) && !file_bucket_saved) {
4111 file_bucket_saved = 1;
4116 rv = apr_bucket_read(bucket, &buf, &len,
4118 if (rv != APR_SUCCESS) {
4119 ap_log_error(APLOG_MARK, APLOG_ERR, rv,
4120 c->base_server, "core_output_filter:"
4121 " Error reading from bucket.");
4122 return HTTP_INTERNAL_SERVER_ERROR;
4127 if (!ctx->deferred_write_pool) {
4128 apr_pool_create(&ctx->deferred_write_pool, c->pool);
4129 apr_pool_tag(ctx->deferred_write_pool, "deferred_write");
4131 ap_save_brigade(f, &ctx->b, &b, ctx->deferred_write_pool);
4138 apr_size_t bytes_sent;
4140 #if APR_HAS_SENDFILE
4141 apr_int32_t flags = 0;
4144 memset(&hdtr, '\0', sizeof(hdtr));
4146 hdtr.numheaders = nvec;
4150 if (nvec_trailers) {
4151 hdtr.numtrailers = nvec_trailers;
4152 hdtr.trailers = vec_trailers;
4155 #if APR_HAS_SENDFILE
4156 if (apr_file_flags_get(fd) & APR_SENDFILE_ENABLED) {
4158 if (c->keepalive == AP_CONN_CLOSE && APR_BUCKET_IS_EOS(last_e)) {
4159 /* Prepare the socket to be reused */
4160 flags |= APR_SENDFILE_DISCONNECT_SOCKET;
4163 rv = sendfile_it_all(net, /* the network information */
4164 fd, /* the file to send */
4165 &hdtr, /* header and trailer iovecs */
4166 foffset, /* offset in the file to begin
4168 flen, /* length of file */
4169 nbytes + flen, /* total length including
4171 &bytes_sent, /* how many bytes were
4173 flags); /* apr_sendfile flags */
4178 rv = emulate_sendfile(net, fd, &hdtr, foffset, flen,
4182 if (logio_add_bytes_out && bytes_sent > 0)
4183 logio_add_bytes_out(c, bytes_sent);
4188 apr_size_t bytes_sent;
4190 rv = writev_it_all(net->client_socket,
4192 nbytes, &bytes_sent);
4194 if (logio_add_bytes_out && bytes_sent > 0)
4195 logio_add_bytes_out(c, bytes_sent);
4198 apr_brigade_destroy(b);
4200 /* drive cleanups for resources which were set aside
4201 * this may occur before or after termination of the request which
4202 * created the resource
4204 if (ctx->deferred_write_pool) {
4205 if (more && more->p == ctx->deferred_write_pool) {
4206 /* "more" belongs to the deferred_write_pool,
4207 * which is about to be cleared.
4209 if (APR_BRIGADE_EMPTY(more)) {
4213 /* uh oh... change more's lifetime
4214 * to the input brigade's lifetime
4216 apr_bucket_brigade *tmp_more = more;
4218 ap_save_brigade(f, &more, &tmp_more, input_pool);
4221 apr_pool_clear(ctx->deferred_write_pool);
4224 if (rv != APR_SUCCESS) {
4225 ap_log_error(APLOG_MARK, APLOG_INFO, rv, c->base_server,
4226 "core_output_filter: writing data to the network");
4229 apr_brigade_destroy(more);
4231 /* No need to check for SUCCESS, we did that above. */
4232 if (!APR_STATUS_IS_EAGAIN(rv)) {
4236 /* The client has aborted, but the request was successful. We
4237 * will report success, and leave it to the access and error
4238 * logs to note that the connection was aborted.
4245 } /* end while () */
4250 static int core_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
4252 logio_add_bytes_out = APR_RETRIEVE_OPTIONAL_FN(ap_logio_add_bytes_out);
4253 ident_lookup = APR_RETRIEVE_OPTIONAL_FN(ap_ident_lookup);
4255 ap_set_version(pconf);
4256 ap_setup_make_content_type(pconf);
4260 static void core_insert_filter(request_rec *r)
4262 core_dir_config *conf = (core_dir_config *)
4263 ap_get_module_config(r->per_dir_config,
4265 const char *filter, *filters = conf->output_filters;
4268 while (*filters && (filter = ap_getword(r->pool, &filters, ';'))) {
4269 ap_add_output_filter(filter, NULL, r, r->connection);
4273 filters = conf->input_filters;
4275 while (*filters && (filter = ap_getword(r->pool, &filters, ';'))) {
4276 ap_add_input_filter(filter, NULL, r, r->connection);
4281 static apr_size_t num_request_notes = AP_NUM_STD_NOTES;
4283 static apr_status_t reset_request_notes(void *dummy)
4285 num_request_notes = AP_NUM_STD_NOTES;
4289 AP_DECLARE(apr_size_t) ap_register_request_note(void)
4291 apr_pool_cleanup_register(apr_hook_global_pool, NULL, reset_request_notes,
4292 apr_pool_cleanup_null);
4293 return num_request_notes++;
4296 AP_DECLARE(void **) ap_get_request_note(request_rec *r, apr_size_t note_num)
4298 core_request_config *req_cfg;
4300 if (note_num >= num_request_notes) {
4304 req_cfg = (core_request_config *)
4305 ap_get_module_config(r->request_config, &core_module);
4311 return &(req_cfg->notes[note_num]);
4314 static int core_create_req(request_rec *r)
4316 /* Alloc the config struct and the array of request notes in
4317 * a single block for efficiency
4319 core_request_config *req_cfg;
4321 req_cfg = apr_pcalloc(r->pool, sizeof(core_request_config) +
4322 sizeof(void *) * num_request_notes);
4323 req_cfg->notes = (void **)((char *)req_cfg + sizeof(core_request_config));
4325 /* ### temporarily enable script delivery as the default */
4326 req_cfg->deliver_script = 1;
4329 core_request_config *main_req_cfg = (core_request_config *)
4330 ap_get_module_config(r->main->request_config, &core_module);
4331 req_cfg->bb = main_req_cfg->bb;
4334 req_cfg->bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
4336 ap_add_input_filter_handle(ap_net_time_filter_handle,
4337 NULL, r, r->connection);
4341 ap_set_module_config(r->request_config, &core_module, req_cfg);
4343 /* Begin by presuming any module can make its own path_info assumptions,
4344 * until some module interjects and changes the value.
4346 r->used_path_info = AP_REQ_DEFAULT_PATH_INFO;
4351 static int core_create_proxy_req(request_rec *r, request_rec *pr)
4353 return core_create_req(pr);
4356 static conn_rec *core_create_conn(apr_pool_t *ptrans, server_rec *server,
4357 apr_socket_t *csd, long id, void *sbh,
4358 apr_bucket_alloc_t *alloc)
4361 conn_rec *c = (conn_rec *) apr_pcalloc(ptrans, sizeof(conn_rec));
4364 (void)ap_update_child_status(c->sbh, SERVER_BUSY_READ, (request_rec *)NULL);
4366 /* Got a connection structure, so initialize what fields we can
4367 * (the rest are zeroed out by pcalloc).
4369 c->conn_config = ap_create_conn_config(ptrans);
4370 c->notes = apr_table_make(ptrans, 5);
4373 if ((rv = apr_socket_addr_get(&c->local_addr, APR_LOCAL, csd))
4375 ap_log_error(APLOG_MARK, APLOG_INFO, rv, server,
4376 "apr_socket_addr_get(APR_LOCAL)");
4377 apr_socket_close(csd);
4381 apr_sockaddr_ip_get(&c->local_ip, c->local_addr);
4382 if ((rv = apr_socket_addr_get(&c->remote_addr, APR_REMOTE, csd))
4384 ap_log_error(APLOG_MARK, APLOG_INFO, rv, server,
4385 "apr_socket_addr_get(APR_REMOTE)");
4386 apr_socket_close(csd);
4390 apr_sockaddr_ip_get(&c->remote_ip, c->remote_addr);
4391 c->base_server = server;
4394 c->bucket_alloc = alloc;
4399 static int core_pre_connection(conn_rec *c, void *csd)
4401 core_net_rec *net = apr_palloc(c->pool, sizeof(*net));
4403 #ifdef AP_MPM_DISABLE_NAGLE_ACCEPTED_SOCK
4404 /* BillS says perhaps this should be moved to the MPMs. Some OSes
4405 * allow listening socket attributes to be inherited by the
4406 * accept sockets which means this call only needs to be made
4407 * once on the listener
4409 ap_sock_disable_nagle(csd);
4413 net->out_ctx = NULL;
4414 net->client_socket = csd;
4416 ap_set_module_config(net->c->conn_config, &core_module, csd);
4417 ap_add_input_filter_handle(ap_core_input_filter_handle, net, NULL, net->c);
4418 ap_add_output_filter_handle(ap_core_output_filter_handle, net, NULL, net->c);
4422 static void register_hooks(apr_pool_t *p)
4424 /* create_connection and install_transport_filters are
4425 * hooks that should always be APR_HOOK_REALLY_LAST to give other
4426 * modules the opportunity to install alternate network transports
4427 * and stop other functions from being run.
4429 ap_hook_create_connection(core_create_conn, NULL, NULL,
4430 APR_HOOK_REALLY_LAST);
4431 ap_hook_pre_connection(core_pre_connection, NULL, NULL,
4432 APR_HOOK_REALLY_LAST);
4434 ap_hook_post_config(core_post_config,NULL,NULL,APR_HOOK_REALLY_FIRST);
4435 ap_hook_translate_name(ap_core_translate,NULL,NULL,APR_HOOK_REALLY_LAST);
4436 ap_hook_map_to_storage(core_map_to_storage,NULL,NULL,APR_HOOK_REALLY_LAST);
4437 ap_hook_open_logs(ap_open_logs,NULL,NULL,APR_HOOK_REALLY_FIRST);
4438 ap_hook_handler(default_handler,NULL,NULL,APR_HOOK_REALLY_LAST);
4439 /* FIXME: I suspect we can eliminate the need for these do_nothings - Ben */
4440 ap_hook_type_checker(do_nothing,NULL,NULL,APR_HOOK_REALLY_LAST);
4441 ap_hook_fixups(core_override_type,NULL,NULL,APR_HOOK_REALLY_FIRST);
4442 ap_hook_access_checker(do_nothing,NULL,NULL,APR_HOOK_REALLY_LAST);
4443 ap_hook_create_request(core_create_req, NULL, NULL, APR_HOOK_MIDDLE);
4444 APR_OPTIONAL_HOOK(proxy, create_req, core_create_proxy_req, NULL, NULL,
4446 ap_hook_pre_mpm(ap_create_scoreboard, NULL, NULL, APR_HOOK_MIDDLE);
4448 /* register the core's insert_filter hook and register core-provided
4451 ap_hook_insert_filter(core_insert_filter, NULL, NULL, APR_HOOK_MIDDLE);
4453 ap_core_input_filter_handle =
4454 ap_register_input_filter("CORE_IN", core_input_filter,
4455 NULL, AP_FTYPE_NETWORK);
4456 ap_net_time_filter_handle =
4457 ap_register_input_filter("NET_TIME", net_time_filter,
4458 NULL, AP_FTYPE_PROTOCOL);
4459 ap_content_length_filter_handle =
4460 ap_register_output_filter("CONTENT_LENGTH", ap_content_length_filter,
4461 NULL, AP_FTYPE_PROTOCOL);
4462 ap_core_output_filter_handle =
4463 ap_register_output_filter("CORE", core_output_filter,
4464 NULL, AP_FTYPE_NETWORK);
4465 ap_subreq_core_filter_handle =
4466 ap_register_output_filter("SUBREQ_CORE", ap_sub_req_output_filter,
4467 NULL, AP_FTYPE_CONTENT_SET);
4469 ap_register_output_filter("OLD_WRITE", ap_old_write_filter,
4470 NULL, AP_FTYPE_RESOURCE - 10);
4473 AP_DECLARE_DATA module core_module = {
4474 STANDARD20_MODULE_STUFF,
4475 create_core_dir_config, /* create per-directory config structure */
4476 merge_core_dir_configs, /* merge per-directory config structures */
4477 create_core_server_config, /* create per-server config structure */
4478 merge_core_server_configs, /* merge per-server config structures */
4479 core_cmds, /* command apr_table_t */
4480 register_hooks /* register hooks */