1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000 The Apache Software Foundation. All rights
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
19 * 3. The end-user documentation included with the redistribution,
20 * if any, must include the following acknowledgment:
21 * "This product includes software developed by the
22 * Apache Software Foundation (http://www.apache.org/)."
23 * Alternately, this acknowledgment may appear in the software itself,
24 * if and wherever such third-party acknowledgments normally appear.
26 * 4. The names "Apache" and "Apache Software Foundation" must
27 * not be used to endorse or promote products derived from this
28 * software without prior written permission. For written
29 * permission, please contact apache@apache.org.
31 * 5. Products derived from this software may not be called "Apache",
32 * nor may "Apache" appear in their name, without prior written
33 * permission of the Apache Software Foundation.
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation. For more
51 * information on the Apache Software Foundation, please see
52 * <http://www.apache.org/>.
54 * Portions of this software are based upon public domain software
55 * originally written at the National Center for Supercomputing Applications,
56 * University of Illinois, Urbana-Champaign.
60 #include "ap_config.h"
61 #include "apr_strings.h"
64 #include "http_config.h"
65 #include "http_core.h"
66 #include "http_protocol.h" /* For index_of_response(). Grump. */
67 #include "http_request.h"
68 #include "http_vhost.h"
69 #include "http_main.h" /* For the default_handler below... */
73 #include "apr_fnmatch.h"
74 #include "http_connection.h"
75 #include "ap_buckets.h"
76 #include "util_filter.h"
77 #include "util_ebcdic.h"
82 #ifdef HAVE_SYS_SOCKET_H
83 #include <sys/socket.h>
85 #ifdef HAVE_ARPA_INET_H
86 #include <arpa/inet.h>
92 /* Make sure we don't write less than 4096 bytes at any one time.
94 #define MIN_BYTES_TO_WRITE 9000
96 /* LimitXMLRequestBody handling */
97 #define AP_LIMIT_UNSET ((long) -1)
98 #define AP_DEFAULT_LIMIT_XML_BODY ((size_t)1000000)
100 /* Server core module... This module provides support for really basic
101 * server operations, including options and commands which control the
102 * operation of other modules. Consider this the bureaucracy module.
104 * The core module also defines handlers, etc., do handle just enough
105 * to allow a server with the core module ONLY to actually serve documents
106 * (though it slaps DefaultType on all of 'em); this was useful in testing,
107 * but may not be worth preserving.
109 * This file could almost be mod_core.c, except for the stuff which affects
110 * the http_conf_globals.
113 static void *create_core_dir_config(apr_pool_t *a, char *dir)
115 core_dir_config *conf;
117 conf = (core_dir_config *)apr_pcalloc(a, sizeof(core_dir_config));
118 if (!dir || dir[strlen(dir) - 1] == '/') {
121 else if (strncmp(dir, "proxy:", 6) == 0) {
122 conf->d = apr_pstrdup(a, dir);
125 conf->d = apr_pstrcat(a, dir, "/", NULL);
127 conf->d_is_fnmatch = conf->d ? (apr_is_fnmatch(conf->d) != 0) : 0;
128 conf->d_components = conf->d ? ap_count_dirs(conf->d) : 0;
130 conf->opts = dir ? OPT_UNSET : OPT_UNSET|OPT_ALL;
131 conf->opts_add = conf->opts_remove = OPT_NONE;
132 conf->override = dir ? OR_UNSET : OR_UNSET|OR_ALL;
134 conf->content_md5 = 2;
136 conf->use_canonical_name = USE_CANONICAL_NAME_UNSET;
138 conf->hostname_lookups = HOSTNAME_LOOKUP_UNSET;
139 conf->do_rfc1413 = DEFAULT_RFC1413 | 2; /* set bit 1 to indicate default */
140 conf->satisfy = SATISFY_NOSPEC;
143 conf->limit_cpu = NULL;
145 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
146 conf->limit_mem = NULL;
149 conf->limit_nproc = NULL;
152 conf->limit_req_body = 0;
153 conf->limit_xml_body = AP_LIMIT_UNSET;
154 conf->sec = apr_make_array(a, 2, sizeof(void *));
156 conf->script_interpreter_source = INTERPRETER_SOURCE_UNSET;
159 conf->server_signature = srv_sig_unset;
161 conf->add_default_charset = ADD_DEFAULT_CHARSET_UNSET;
162 conf->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
164 conf->output_filters = apr_make_array(a, 2, sizeof(void *));
165 conf->input_filters = apr_make_array(a, 2, sizeof(void *));
169 static void *merge_core_dir_configs(apr_pool_t *a, void *basev, void *newv)
171 core_dir_config *base = (core_dir_config *)basev;
172 core_dir_config *new = (core_dir_config *)newv;
173 core_dir_config *conf;
176 conf = (core_dir_config *)apr_palloc(a, sizeof(core_dir_config));
177 memcpy((char *)conf, (const char *)base, sizeof(core_dir_config));
178 if (base->response_code_strings) {
179 conf->response_code_strings =
180 apr_palloc(a, sizeof(*conf->response_code_strings)
182 memcpy(conf->response_code_strings, base->response_code_strings,
183 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
187 conf->d_is_fnmatch = new->d_is_fnmatch;
188 conf->d_components = new->d_components;
191 if (new->opts & OPT_UNSET) {
192 /* there was no explicit setting of new->opts, so we merge
193 * preserve the invariant (opts_add & opts_remove) == 0
195 conf->opts_add = (conf->opts_add & ~new->opts_remove) | new->opts_add;
196 conf->opts_remove = (conf->opts_remove & ~new->opts_add)
198 conf->opts = (conf->opts & ~conf->opts_remove) | conf->opts_add;
199 if ((base->opts & OPT_INCNOEXEC) && (new->opts & OPT_INCLUDES)) {
200 conf->opts = (conf->opts & ~OPT_INCNOEXEC) | OPT_INCLUDES;
204 /* otherwise we just copy, because an explicit opts setting
205 * overrides all earlier +/- modifiers
207 conf->opts = new->opts;
208 conf->opts_add = new->opts_add;
209 conf->opts_remove = new->opts_remove;
212 if (!(new->override & OR_UNSET)) {
213 conf->override = new->override;
215 if (new->ap_default_type) {
216 conf->ap_default_type = new->ap_default_type;
219 if (new->ap_auth_type) {
220 conf->ap_auth_type = new->ap_auth_type;
222 if (new->ap_auth_name) {
223 conf->ap_auth_name = new->ap_auth_name;
225 if (new->ap_requires) {
226 conf->ap_requires = new->ap_requires;
229 if (new->response_code_strings) {
230 if (conf->response_code_strings == NULL) {
231 conf->response_code_strings = apr_palloc(a,
232 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
233 memcpy(conf->response_code_strings, new->response_code_strings,
234 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
237 for (i = 0; i < RESPONSE_CODES; ++i) {
238 if (new->response_code_strings[i] != NULL) {
239 conf->response_code_strings[i]
240 = new->response_code_strings[i];
245 if (new->hostname_lookups != HOSTNAME_LOOKUP_UNSET) {
246 conf->hostname_lookups = new->hostname_lookups;
248 if ((new->do_rfc1413 & 2) == 0) {
249 conf->do_rfc1413 = new->do_rfc1413;
251 if ((new->content_md5 & 2) == 0) {
252 conf->content_md5 = new->content_md5;
254 if (new->use_canonical_name != USE_CANONICAL_NAME_UNSET) {
255 conf->use_canonical_name = new->use_canonical_name;
259 if (new->limit_cpu) {
260 conf->limit_cpu = new->limit_cpu;
263 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
264 if (new->limit_mem) {
265 conf->limit_mem = new->limit_mem;
269 if (new->limit_nproc) {
270 conf->limit_nproc = new->limit_nproc;
274 if (new->limit_req_body) {
275 conf->limit_req_body = new->limit_req_body;
278 if (new->limit_xml_body != AP_LIMIT_UNSET)
279 conf->limit_xml_body = new->limit_xml_body;
281 conf->limit_xml_body = base->limit_xml_body;
283 conf->sec = apr_append_arrays(a, base->sec, new->sec);
285 if (new->satisfy != SATISFY_NOSPEC) {
286 conf->satisfy = new->satisfy;
290 if (new->script_interpreter_source != INTERPRETER_SOURCE_UNSET) {
291 conf->script_interpreter_source = new->script_interpreter_source;
295 if (new->server_signature != srv_sig_unset) {
296 conf->server_signature = new->server_signature;
299 if (new->add_default_charset != ADD_DEFAULT_CHARSET_UNSET) {
300 conf->add_default_charset = new->add_default_charset;
301 if (new->add_default_charset_name) {
302 conf->add_default_charset_name = new->add_default_charset_name;
305 conf->output_filters = apr_append_arrays(a, base->output_filters,
306 new->output_filters);
307 conf->input_filters = apr_append_arrays(a, base->input_filters,
313 static void *create_core_server_config(apr_pool_t *a, server_rec *s)
315 core_server_config *conf;
316 int is_virtual = s->is_virtual;
318 conf = (core_server_config *)apr_pcalloc(a, sizeof(core_server_config));
320 conf->gprof_dir = NULL;
322 conf->access_name = is_virtual ? NULL : DEFAULT_ACCESS_FNAME;
323 conf->ap_document_root = is_virtual ? NULL : DOCUMENT_LOCATION;
324 conf->sec = apr_make_array(a, 40, sizeof(void *));
325 conf->sec_url = apr_make_array(a, 40, sizeof(void *));
330 static void *merge_core_server_configs(apr_pool_t *p, void *basev, void *virtv)
332 core_server_config *base = (core_server_config *)basev;
333 core_server_config *virt = (core_server_config *)virtv;
334 core_server_config *conf;
336 conf = (core_server_config *)apr_pcalloc(p, sizeof(core_server_config));
338 if (!conf->access_name) {
339 conf->access_name = base->access_name;
341 if (!conf->ap_document_root) {
342 conf->ap_document_root = base->ap_document_root;
344 conf->sec = apr_append_arrays(p, base->sec, virt->sec);
345 conf->sec_url = apr_append_arrays(p, base->sec_url, virt->sec_url);
350 /* Add per-directory configuration entry (for <directory> section);
351 * these are part of the core server config.
354 AP_CORE_DECLARE(void) ap_add_per_dir_conf(server_rec *s, void *dir_config)
356 core_server_config *sconf = ap_get_module_config(s->module_config,
358 void **new_space = (void **)apr_push_array(sconf->sec);
360 *new_space = dir_config;
363 AP_CORE_DECLARE(void) ap_add_per_url_conf(server_rec *s, void *url_config)
365 core_server_config *sconf = ap_get_module_config(s->module_config,
367 void **new_space = (void **)apr_push_array(sconf->sec_url);
369 *new_space = url_config;
372 AP_CORE_DECLARE(void) ap_add_file_conf(core_dir_config *conf, void *url_config)
374 void **new_space = (void **)apr_push_array(conf->sec);
376 *new_space = url_config;
379 /* core_reorder_directories reorders the directory sections such that the
380 * 1-component sections come first, then the 2-component, and so on, finally
381 * followed by the "special" sections. A section is "special" if it's a regex,
382 * or if it doesn't start with / -- consider proxy: matching. All movements
383 * are in-order to preserve the ordering of the sections from the config files.
384 * See directory_walk().
387 #if defined(HAVE_DRIVE_LETTERS)
388 #define IS_SPECIAL(entry_core) \
389 ((entry_core)->r != NULL \
390 || ((entry_core)->d[0] != '/' && (entry_core)->d[1] != ':'))
391 #elif defined(NETWARE)
392 /* XXX: Fairly certain this is correct... '/' must prefix the path
393 * or else in the case xyz:/ or abc/xyz:/, '/' must follow the ':'.
394 * If there is no leading '/' or embedded ':/', then we are special.
396 #define IS_SPECIAL(entry_core) \
397 ((entry_core)->r != NULL \
398 || ((entry_core)->d[0] != '/' \
399 && strchr((entry_core)->d, ':') \
400 && *(strchr((entry_core)->d, ':') + 1) != '/'))
402 #define IS_SPECIAL(entry_core) \
403 ((entry_core)->r != NULL || (entry_core)->d[0] != '/')
406 /* We need to do a stable sort, qsort isn't stable. So to make it stable
407 * we'll be maintaining the original index into the list, and using it
408 * as the minor key during sorting. The major key is the number of
409 * components (where a "special" section has infinite components).
411 struct reorder_sort_rec {
416 static int reorder_sorter(const void *va, const void *vb)
418 const struct reorder_sort_rec *a = va;
419 const struct reorder_sort_rec *b = vb;
420 core_dir_config *core_a;
421 core_dir_config *core_b;
423 core_a = (core_dir_config *)ap_get_module_config(a->elt, &core_module);
424 core_b = (core_dir_config *)ap_get_module_config(b->elt, &core_module);
425 if (IS_SPECIAL(core_a)) {
426 if (!IS_SPECIAL(core_b)) {
430 else if (IS_SPECIAL(core_b)) {
434 /* we know they're both not special */
435 if (core_a->d_components < core_b->d_components) {
438 else if (core_a->d_components > core_b->d_components) {
442 /* Either they're both special, or they're both not special and have the
443 * same number of components. In any event, we now have to compare
445 return a->orig_index - b->orig_index;
448 void ap_core_reorder_directories(apr_pool_t *p, server_rec *s)
450 core_server_config *sconf;
451 apr_array_header_t *sec;
452 struct reorder_sort_rec *sortbin;
458 sconf = ap_get_module_config(s->module_config, &core_module);
461 elts = (void **)sec->elts;
463 /* we have to allocate tmp space to do a stable sort */
464 apr_create_pool(&tmp, p);
465 sortbin = apr_palloc(tmp, sec->nelts * sizeof(*sortbin));
466 for (i = 0; i < nelts; ++i) {
467 sortbin[i].orig_index = i;
468 sortbin[i].elt = elts[i];
471 qsort(sortbin, nelts, sizeof(*sortbin), reorder_sorter);
473 /* and now copy back to the original array */
474 for (i = 0; i < nelts; ++i) {
475 elts[i] = sortbin[i].elt;
478 apr_destroy_pool(tmp);
481 /*****************************************************************
483 * There are some elements of the core config structures in which
484 * other modules have a legitimate interest (this is ugly, but necessary
485 * to preserve NCSA back-compatibility). So, we have a bunch of accessors
489 AP_DECLARE(int) ap_allow_options(request_rec *r)
491 core_dir_config *conf =
492 (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
497 AP_DECLARE(int) ap_allow_overrides(request_rec *r)
499 core_dir_config *conf;
500 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
503 return conf->override;
506 AP_DECLARE(const char *) ap_auth_type(request_rec *r)
508 core_dir_config *conf;
510 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
512 return conf->ap_auth_type;
515 AP_DECLARE(const char *) ap_auth_name(request_rec *r)
517 core_dir_config *conf;
519 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
521 return conf->ap_auth_name;
524 AP_DECLARE(const char *) ap_default_type(request_rec *r)
526 core_dir_config *conf;
528 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
530 return conf->ap_default_type
531 ? conf->ap_default_type
532 : DEFAULT_CONTENT_TYPE;
535 AP_DECLARE(const char *) ap_document_root(request_rec *r) /* Don't use this! */
537 core_server_config *conf;
539 conf = (core_server_config *)ap_get_module_config(r->server->module_config,
541 return conf->ap_document_root;
544 AP_DECLARE(const apr_array_header_t *) ap_requires(request_rec *r)
546 core_dir_config *conf;
548 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
550 return conf->ap_requires;
553 AP_DECLARE(int) ap_satisfies(request_rec *r)
555 core_dir_config *conf;
557 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
560 return conf->satisfy;
563 /* Should probably just get rid of this... the only code that cares is
564 * part of the core anyway (and in fact, it isn't publicised to other
568 char *ap_response_code_string(request_rec *r, int error_index)
570 core_dir_config *conf;
572 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
575 if (conf->response_code_strings == NULL) {
578 return conf->response_code_strings[error_index];
582 /* Code from Harald Hanche-Olsen <hanche@imf.unit.no> */
583 static apr_inline void do_double_reverse (conn_rec *conn)
585 struct hostent *hptr;
587 if (conn->double_reverse) {
591 if (conn->remote_host == NULL || conn->remote_host[0] == '\0') {
592 /* single reverse failed, so don't bother */
593 conn->double_reverse = -1;
596 hptr = gethostbyname(conn->remote_host);
600 for (haddr = hptr->h_addr_list; *haddr; haddr++) {
601 if (((struct in_addr *)(*haddr))->s_addr
602 == conn->remote_addr.sin_addr.s_addr) {
603 conn->double_reverse = 1;
608 conn->double_reverse = -1;
611 AP_DECLARE(const char *) ap_get_remote_host(conn_rec *conn, void *dir_config,
614 int hostname_lookups;
616 /* If we haven't checked the host name, and we want to */
619 ((core_dir_config *)ap_get_module_config(dir_config, &core_module))
621 if (hostname_lookups == HOSTNAME_LOOKUP_UNSET) {
622 hostname_lookups = HOSTNAME_LOOKUP_OFF;
627 hostname_lookups = HOSTNAME_LOOKUP_OFF;
630 if (type != REMOTE_NOLOOKUP
631 && conn->remote_host == NULL
632 && (type == REMOTE_DOUBLE_REV
633 || hostname_lookups != HOSTNAME_LOOKUP_OFF)) {
634 if (apr_get_hostname(&conn->remote_host, APR_REMOTE, conn->client_socket)
636 ap_str_tolower(conn->remote_host);
638 if (hostname_lookups == HOSTNAME_LOOKUP_DOUBLE) {
639 do_double_reverse(conn);
640 if (conn->double_reverse != 1) {
641 conn->remote_host = NULL;
645 /* if failed, set it to the NULL string to indicate error */
646 if (conn->remote_host == NULL) {
647 conn->remote_host = "";
650 if (type == REMOTE_DOUBLE_REV) {
651 do_double_reverse(conn);
652 if (conn->double_reverse == -1) {
658 * Return the desired information; either the remote DNS name, if found,
659 * or either NULL (if the hostname was requested) or the IP address
660 * (if any identifier was requested).
662 if (conn->remote_host != NULL && conn->remote_host[0] != '\0') {
663 return conn->remote_host;
666 if (type == REMOTE_HOST || type == REMOTE_DOUBLE_REV) {
670 return conn->remote_ip;
675 AP_DECLARE(const char *) ap_get_remote_logname(request_rec *r)
677 core_dir_config *dir_conf;
679 if (r->connection->remote_logname != NULL) {
680 return r->connection->remote_logname;
683 /* If we haven't checked the identity, and we want to */
684 dir_conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
687 if (dir_conf->do_rfc1413 & 1) {
688 return ap_rfc1413(r->connection, r->server);
695 /* There are two options regarding what the "name" of a server is. The
696 * "canonical" name as defined by ServerName and Port, or the "client's
697 * name" as supplied by a possible Host: header or full URI. We never
698 * trust the port passed in the client's headers, we always use the
699 * port of the actual socket.
701 * The DNS option to UseCanonicalName causes this routine to do a
702 * reverse lookup on the local IP address of the connectiona and use
703 * that for the ServerName. This makes its value more reliable while
704 * at the same time allowing Demon's magic virtual hosting to work.
705 * The assumption is that DNS lookups are sufficiently quick...
708 AP_DECLARE(const char *) ap_get_server_name(request_rec *r)
710 conn_rec *conn = r->connection;
713 d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
716 if (d->use_canonical_name == USE_CANONICAL_NAME_OFF) {
717 return r->hostname ? r->hostname : r->server->server_hostname;
719 if (d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
720 if (conn->local_host == NULL) {
721 if (apr_get_hostname(&conn->local_host, APR_LOCAL, conn->client_socket) != APR_SUCCESS)
722 conn->local_host = apr_pstrdup(conn->pool, r->server->server_hostname);
724 ap_str_tolower(conn->local_host);
726 return conn->local_host;
729 return r->server->server_hostname;
732 AP_DECLARE(apr_port_t) ap_get_server_port(const request_rec *r)
736 (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
738 port = r->server->port ? r->server->port : ap_default_port(r);
740 if (d->use_canonical_name == USE_CANONICAL_NAME_OFF
741 || d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
743 apr_get_port(&port, APR_LOCAL, r->connection->client_socket);
749 AP_DECLARE(char *) ap_construct_url(apr_pool_t *p, const char *uri,
752 unsigned port = ap_get_server_port(r);
753 const char *host = ap_get_server_name(r);
755 if (ap_is_default_port(port, r)) {
756 return apr_pstrcat(p, ap_http_method(r), "://", host, uri, NULL);
758 return apr_psprintf(p, "%s://%s:%u%s", ap_http_method(r), host, port, uri);
761 AP_DECLARE(unsigned long) ap_get_limit_req_body(const request_rec *r)
764 (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
766 return d->limit_req_body;
770 static apr_status_t get_win32_registry_default_value(apr_pool_t *p, HKEY hkey,
777 DWORD result = RegOpenKeyEx(hkey, relativepath, 0,
778 KEY_QUERY_VALUE, &hkeyOpen);
780 if (result != ERROR_SUCCESS)
781 return APR_FROM_OS_ERROR(result);
783 /* Read to NULL buffer to determine value size */
784 result = RegQueryValueEx(hkeyOpen, "", 0, &type, NULL, &size);
786 if (result == ERROR_SUCCESS) {
787 if ((size < 2) || (type != REG_SZ && type != REG_EXPAND_SZ)) {
788 result = ERROR_INVALID_PARAMETER;
791 *value = apr_palloc(p, size);
792 /* Read value based on size query above */
793 result = RegQueryValueEx(hkeyOpen, "", 0, &type, *value, &size);
797 /* TODO: This might look fine, but we need to provide some warning
798 * somewhere that some environment variables may -not- be translated,
799 * seeing as we may have chopped the environment table down somewhat.
801 if ((result == ERROR_SUCCESS) && (type == REG_EXPAND_SZ))
804 size = ExpandEnvironmentStrings(tmp, *value, 0);
806 *value = apr_palloc(p, size);
807 size = ExpandEnvironmentStrings(tmp, *value, size);
811 RegCloseKey(hkeyOpen);
812 return APR_FROM_OS_ERROR(result);
815 static char* get_interpreter_from_win32_registry(apr_pool_t *p, const char* ext,
816 char** arguments, int strict)
818 char execcgi_path[] = "SHELL\\EXECCGI\\COMMAND";
819 char execopen_path[] = "SHELL\\OPEN\\COMMAND";
820 char typeName[MAX_PATH];
821 int cmdOfName = FALSE;
833 * Future optimization:
834 * When the registry is successfully searched, store the strings for
835 * interpreter and arguments in an ext hash to speed up subsequent look-ups
838 /* Open the key associated with the script filetype extension */
839 result = RegOpenKeyEx(HKEY_CLASSES_ROOT, ext, 0, KEY_QUERY_VALUE,
842 if (result != ERROR_SUCCESS)
845 /* Retrieve the name of the script filetype extension */
846 size = sizeof(typeName);
847 result = RegQueryValueEx(hkeyType, "", NULL, &type, typeName, &size);
849 if (result == ERROR_SUCCESS && type == REG_SZ && typeName[0]) {
850 /* Open the key associated with the script filetype extension */
851 result = RegOpenKeyEx(HKEY_CLASSES_ROOT, typeName, 0,
852 KEY_QUERY_VALUE, &hkeyName);
854 if (result == ERROR_SUCCESS)
858 /* Open the key for the script command path by:
860 * 1) the 'named' filetype key for ExecCGI/Command
861 * 2) the extension's type key for ExecCGI/Command
863 * and if the strict arg is false, then continue trying:
865 * 3) the 'named' filetype key for Open/Command
866 * 4) the extension's type key for Open/Command
870 result = get_win32_registry_default_value(p, hkeyName,
871 execcgi_path, &buffer);
874 if (!cmdOfName || (result != ERROR_SUCCESS)) {
875 result = get_win32_registry_default_value(p, hkeyType,
876 execcgi_path, &buffer);
879 if (!strict && cmdOfName && (result != ERROR_SUCCESS)) {
880 result = get_win32_registry_default_value(p, hkeyName,
881 execopen_path, &buffer);
884 if (!strict && (result != ERROR_SUCCESS)) {
885 result = get_win32_registry_default_value(p, hkeyType,
886 execopen_path, &buffer);
890 RegCloseKey(hkeyName);
892 RegCloseKey(hkeyType);
894 if (result != ERROR_SUCCESS)
898 * The canonical way shell command entries are entered in the Win32
899 * registry is as follows:
900 * shell [options] "%1" [args]
902 * shell - full path name to interpreter or shell to run.
903 * E.g., c:\usr\local\ntreskit\perl\bin\perl.exe
904 * options - optional switches
906 * "%1" - Place holder for file to run the shell against.
908 * options - additional arguments
911 * If we find a %1 or a quoted %1, lop off the remainder to arguments.
913 if (buffer && *buffer) {
914 if ((s = strstr(buffer, "\"%1")))
919 else if ((s = strstr(buffer, "%1")))
922 *arguments = buffer + 2;
925 *arguments = strchr(buffer, '\0');
926 while (**arguments && isspace(**arguments))
933 AP_DECLARE (file_type_e) ap_get_win32_interpreter(const request_rec *r,
943 file_type_e fileType = eFileTypeUNKNOWN;
945 char *exename = NULL;
947 d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
950 /* Find the file extension */
951 exename = strrchr(r->filename, '/');
953 exename = strrchr(r->filename, '\\');
956 exename = r->filename;
961 ext = strrchr(exename, '.');
963 if (ext && (!strcasecmp(ext,".bat") || !strcasecmp(ext,".cmd")))
965 char *comspec = getenv("COMSPEC");
967 *interpreter = apr_pstrcat(r->pool, "\"", comspec, "\" /c ", NULL);
968 return eFileTypeSCRIPT;
970 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r->server,
971 "Failed to start a '%s' file as a script." APR_EOL_STR
972 "\tCOMSPEC variable is missing from the environment.", ext);
973 return eFileTypeUNKNOWN;
976 /* If the file has an extension and it is not .com and not .exe and
977 * we've been instructed to search the registry, then do it!
979 if (ext && strcasecmp(ext,".exe") && strcasecmp(ext,".com") &&
980 (d->script_interpreter_source == INTERPRETER_SOURCE_REGISTRY ||
981 d->script_interpreter_source == INTERPRETER_SOURCE_REGISTRY_STRICT)) {
982 /* Check the registry */
983 int strict = (d->script_interpreter_source
984 == INTERPRETER_SOURCE_REGISTRY_STRICT);
985 *interpreter = get_interpreter_from_win32_registry(r->pool, ext,
988 return eFileTypeSCRIPT;
989 else if (d->script_interpreter_source == INTERPRETER_SOURCE_REGISTRY_STRICT) {
990 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r->server,
991 "ScriptInterpreterSource config directive set to \"registry-strict\"." APR_EOL_STR
992 "\tInterpreter not found for files of type '%s'.", ext);
993 return eFileTypeUNKNOWN;
997 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r->server,
998 "ScriptInterpreterSource config directive set to \"registry\"." APR_EOL_STR
999 "\tInterpreter not found for files of type '%s', "
1000 "trying \"script\" method...", ext);
1004 /* Need to peek into the file figure out what it really is... */
1005 hFile = CreateFile(r->filename, GENERIC_READ, FILE_SHARE_READ, NULL,
1006 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1007 if (hFile == INVALID_HANDLE_VALUE) {
1008 return eFileTypeUNKNOWN;
1010 bResult = ReadFile(hFile, (void*) &buffer, sizeof(buffer) - 1,
1012 if (!bResult || (nBytesRead == 0)) {
1013 ap_log_rerror(APLOG_MARK, APLOG_ERR, GetLastError(), r,
1014 "ReadFile(%s) failed", r->filename);
1016 return eFileTypeUNKNOWN;
1019 buffer[nBytesRead] = '\0';
1021 /* Script or executable, that is the question... */
1022 if ((buffer[0] == '#') && (buffer[1] == '!')) {
1023 /* Assuming file is a script since it starts with a shebang */
1024 fileType = eFileTypeSCRIPT;
1025 for (i = 2; i < sizeof(buffer); i++) {
1026 if ((buffer[i] == '\r')
1027 || (buffer[i] == '\n')) {
1032 for (i = 2; buffer[i] == ' ' ; ++i)
1034 *interpreter = apr_pstrdup(r->pool, buffer + i );
1037 /* Not a script, is it an executable? */
1038 IMAGE_DOS_HEADER *hdr = (IMAGE_DOS_HEADER*)buffer;
1039 if ((nBytesRead >= sizeof(IMAGE_DOS_HEADER)) && (hdr->e_magic == IMAGE_DOS_SIGNATURE)) {
1040 if (hdr->e_lfarlc < 0x40)
1041 fileType = eFileTypeEXE16;
1043 fileType = eFileTypeEXE32;
1046 fileType = eFileTypeUNKNOWN;
1053 /*****************************************************************
1055 * Commands... this module handles almost all of the NCSA httpd.conf
1056 * commands, but most of the old srm.conf is in the the modules.
1060 /* returns a parent if it matches the given directive */
1061 static const ap_directive_t * find_parent(const ap_directive_t *dirp,
1064 while (dirp->parent != NULL) {
1065 dirp = dirp->parent;
1066 /* ### it would be nice to have atom-ized directives */
1067 if (strcasecmp(dirp->directive, what) == 0)
1073 AP_DECLARE(const char *) ap_check_cmd_context(cmd_parms *cmd,
1076 const char *gt = (cmd->cmd->name[0] == '<'
1077 && cmd->cmd->name[strlen(cmd->cmd->name)-1] != '>')
1079 const ap_directive_t *found;
1081 if ((forbidden & NOT_IN_VIRTUALHOST) && cmd->server->is_virtual) {
1082 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1083 " cannot occur within <VirtualHost> section", NULL);
1086 if ((forbidden & NOT_IN_LIMIT) && cmd->limited != -1) {
1087 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1088 " cannot occur within <Limit> section", NULL);
1091 if ((forbidden & NOT_IN_DIR_LOC_FILE) == NOT_IN_DIR_LOC_FILE
1092 && cmd->path != NULL) {
1093 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1094 " cannot occur within <Directory/Location/Files> "
1098 if (((forbidden & NOT_IN_DIRECTORY)
1099 && ((found = find_parent(cmd->directive, "<Directory"))
1100 || (found = find_parent(cmd->directive, "<DirectoryMatch"))))
1101 || ((forbidden & NOT_IN_LOCATION)
1102 && ((found = find_parent(cmd->directive, "<Location"))
1103 || (found = find_parent(cmd->directive, "<LocationMatch"))))
1104 || ((forbidden & NOT_IN_FILES)
1105 && ((found = find_parent(cmd->directive, "<Files"))
1106 || (found = find_parent(cmd->directive, "<FilesMatch"))))) {
1107 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1108 " cannot occur within ", found->directive,
1115 static const char *set_access_name(cmd_parms *cmd, void *dummy,
1118 void *sconf = cmd->server->module_config;
1119 core_server_config *conf = ap_get_module_config(sconf, &core_module);
1121 const char *err = ap_check_cmd_context(cmd,
1122 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1127 conf->access_name = apr_pstrdup(cmd->pool, arg);
1132 static const char *set_gprof_dir(cmd_parms *cmd, void *dummy, char *arg)
1134 void *sconf = cmd->server->module_config;
1135 core_server_config *conf = ap_get_module_config(sconf, &core_module);
1137 const char *err = ap_check_cmd_context(cmd,
1138 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1143 conf->gprof_dir = apr_pstrdup(cmd->pool, arg);
1148 static const char *set_add_default_charset(cmd_parms *cmd,
1149 void *d_, const char *arg)
1151 core_dir_config *d=d_;
1153 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1157 if (!strcasecmp(arg, "Off")) {
1158 d->add_default_charset = ADD_DEFAULT_CHARSET_OFF;
1160 else if (!strcasecmp(arg, "On")) {
1161 d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1162 d->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
1165 d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1166 d->add_default_charset_name = arg;
1171 static const char *set_document_root(cmd_parms *cmd, void *dummy,
1174 void *sconf = cmd->server->module_config;
1175 core_server_config *conf = ap_get_module_config(sconf, &core_module);
1177 const char *err = ap_check_cmd_context(cmd,
1178 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1183 arg = ap_os_canonical_filename(cmd->pool, arg);
1184 if (/* TODO: ap_configtestonly && ap_docrootcheck && */ !ap_is_directory(arg)) {
1185 if (cmd->server->is_virtual) {
1186 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1187 "Warning: DocumentRoot [%s] does not exist",
1191 return "DocumentRoot must be a directory";
1195 conf->ap_document_root = arg;
1199 AP_DECLARE(void) ap_custom_response(request_rec *r, int status, char *string)
1201 core_dir_config *conf =
1202 ap_get_module_config(r->per_dir_config, &core_module);
1205 if(conf->response_code_strings == NULL) {
1206 conf->response_code_strings =
1207 apr_pcalloc(r->pool,
1208 sizeof(*conf->response_code_strings) *
1212 idx = ap_index_of_response(status);
1214 conf->response_code_strings[idx] =
1215 ((ap_is_url(string) || (*string == '/')) && (*string != '"')) ?
1216 apr_pstrdup(r->pool, string) : apr_pstrcat(r->pool, "\"", string, NULL);
1219 static const char *set_error_document(cmd_parms *cmd, void *conf_,
1220 const char *errno_str, const char *msg)
1222 core_dir_config *conf=conf_;
1223 int error_number, index_number, idx500;
1224 enum { MSG, LOCAL_PATH, REMOTE_PATH } what = MSG;
1226 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1231 /* 1st parameter should be a 3 digit number, which we recognize;
1232 * convert it into an array index
1234 error_number = atoi(errno_str);
1235 idx500 = ap_index_of_response(HTTP_INTERNAL_SERVER_ERROR);
1237 if (error_number == HTTP_INTERNAL_SERVER_ERROR) {
1238 index_number = idx500;
1240 else if ((index_number = ap_index_of_response(error_number)) == idx500) {
1241 return apr_pstrcat(cmd->pool, "Unsupported HTTP response code ",
1245 /* Heuristic to determine second argument. */
1246 if (ap_strchr_c(msg,' '))
1248 else if (msg[0] == '/')
1250 else if (ap_is_url(msg))
1255 /* The entry should be ignored if it is a full URL for a 401 error */
1257 if (error_number == 401 && what == REMOTE_PATH) {
1258 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, cmd->server,
1259 "cannot use a full URL in a 401 ErrorDocument "
1260 "directive --- ignoring!");
1262 else { /* Store it... */
1263 if (conf->response_code_strings == NULL) {
1264 conf->response_code_strings =
1265 apr_pcalloc(cmd->pool,
1266 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
1268 /* hack. Prefix a " if it is a msg; as that is what
1269 * http_protocol.c relies on to distinguish between
1270 * a msg and a (local) path.
1272 conf->response_code_strings[index_number] = (what == MSG) ?
1273 apr_pstrcat(cmd->pool, "\"",msg,NULL) :
1274 apr_pstrdup(cmd->pool, msg);
1280 static const char *set_override(cmd_parms *cmd, void *d_, const char *l)
1282 core_dir_config *d=d_;
1285 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1290 d->override = OR_NONE;
1292 w = ap_getword_conf(cmd->pool, &l);
1293 if (!strcasecmp(w, "Limit")) {
1294 d->override |= OR_LIMIT;
1296 else if (!strcasecmp(w, "Options")) {
1297 d->override |= OR_OPTIONS;
1299 else if (!strcasecmp(w, "FileInfo")) {
1300 d->override |= OR_FILEINFO;
1302 else if (!strcasecmp(w, "AuthConfig")) {
1303 d->override |= OR_AUTHCFG;
1305 else if (!strcasecmp(w, "Indexes")) {
1306 d->override |= OR_INDEXES;
1308 else if (!strcasecmp(w, "None")) {
1309 d->override = OR_NONE;
1311 else if (!strcasecmp(w, "All")) {
1312 d->override = OR_ALL;
1315 return apr_pstrcat(cmd->pool, "Illegal override option ", w, NULL);
1317 d->override &= ~OR_UNSET;
1323 static const char *set_options(cmd_parms *cmd, void *d_, const char *l)
1325 core_dir_config *d=d_;
1326 allow_options_t opt;
1331 char *w = ap_getword_conf(cmd->pool, &l);
1334 if (*w == '+' || *w == '-') {
1342 if (!strcasecmp(w, "Indexes")) {
1345 else if (!strcasecmp(w, "Includes")) {
1348 else if (!strcasecmp(w, "IncludesNOEXEC")) {
1349 opt = (OPT_INCLUDES | OPT_INCNOEXEC);
1351 else if (!strcasecmp(w, "FollowSymLinks")) {
1352 opt = OPT_SYM_LINKS;
1354 else if (!strcasecmp(w, "SymLinksIfOwnerMatch")) {
1355 opt = OPT_SYM_OWNER;
1357 else if (!strcasecmp(w, "execCGI")) {
1360 else if (!strcasecmp(w, "MultiViews")) {
1363 else if (!strcasecmp(w, "RunScripts")) { /* AI backcompat. Yuck */
1364 opt = OPT_MULTI|OPT_EXECCGI;
1366 else if (!strcasecmp(w, "None")) {
1369 else if (!strcasecmp(w, "All")) {
1373 return apr_pstrcat(cmd->pool, "Illegal option ", w, NULL);
1376 /* we ensure the invariant (d->opts_add & d->opts_remove) == 0 */
1377 if (action == '-') {
1378 d->opts_remove |= opt;
1379 d->opts_add &= ~opt;
1382 else if (action == '+') {
1384 d->opts_remove &= ~opt;
1395 static const char *satisfy(cmd_parms *cmd, void *c_, const char *arg)
1397 core_dir_config *c=c_;
1399 if (!strcasecmp(arg, "all")) {
1400 c->satisfy = SATISFY_ALL;
1402 else if (!strcasecmp(arg, "any")) {
1403 c->satisfy = SATISFY_ANY;
1406 return "Satisfy either 'any' or 'all'.";
1411 static const char *require(cmd_parms *cmd, void *c_, const char *arg)
1414 core_dir_config *c=c_;
1416 if (!c->ap_requires) {
1417 c->ap_requires = apr_make_array(cmd->pool, 2, sizeof(require_line));
1419 r = (require_line *)apr_push_array(c->ap_requires);
1420 r->requirement = apr_pstrdup(cmd->pool, arg);
1421 r->method_mask = cmd->limited;
1425 AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd, void *dummy,
1427 const char *limited_methods = ap_getword(cmd->pool, &arg, '>');
1428 void *tog = cmd->cmd->cmd_data;
1432 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1437 while (limited_methods[0]) {
1438 char *method = ap_getword_conf(cmd->pool, &limited_methods);
1439 int methnum = ap_method_number_of(method);
1441 if (methnum == M_TRACE && !tog) {
1442 return "TRACE cannot be controlled by <Limit>";
1444 else if (methnum == M_INVALID) {
1446 register int i, j, k;
1449 * Deal with <Limit> by adding the method to the list.
1452 if (cmd->limited_xmethods == NULL) {
1453 cmd->limited_xmethods = apr_make_array(cmd->pool, 2,
1456 xmethod = (char **) apr_push_array(cmd->limited_xmethods);
1457 *xmethod = apr_pstrdup(cmd->pool, method);
1460 * <LimitExcept>, so remove any/all occurrences of the method
1461 * in the extension array.
1463 else if ((cmd->limited_xmethods != NULL)
1464 && (cmd->limited_xmethods->nelts != 0)) {
1465 xmethod = (char **) cmd->limited_xmethods->elts;
1466 for (i = 0; i < cmd->limited_xmethods->nelts; ) {
1467 if (strcmp(xmethod[i], method) == 0) {
1468 for (j = i, k = i + 1;
1469 k < cmd->limited_xmethods->nelts;
1471 xmethod[j] = xmethod[k];
1473 cmd->limited_xmethods->nelts--;
1478 limited |= (1 << methnum);
1481 /* Killing two features with one function,
1482 * if (tog == NULL) <Limit>, else <LimitExcept>
1484 cmd->limited = tog ? ~limited : limited;
1486 errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context);
1493 /* We use this in <DirectoryMatch> and <FilesMatch>, to ensure that
1494 * people don't get bitten by wrong-cased regex matches
1498 #define USE_ICASE REG_ICASE
1504 * Report a missing-'>' syntax error.
1506 static char *unclosed_directive(cmd_parms *cmd)
1508 return apr_pstrcat(cmd->pool, cmd->cmd->name,
1509 "> directive missing closing '>'", NULL);
1512 static const char *dirsection(cmd_parms *cmd, void *mconfig, const char *arg)
1515 const char *endp = ap_strrchr_c(arg, '>');
1516 int old_overrides = cmd->override;
1517 char *old_path = cmd->path;
1518 core_dir_config *conf;
1519 void *new_dir_conf = ap_create_per_dir_config(cmd->pool);
1521 const command_rec *thiscmd = cmd->cmd;
1523 const char *err = ap_check_cmd_context(cmd,
1524 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1530 return unclosed_directive(cmd);
1533 arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1535 cmd->path = ap_getword_conf(cmd->pool, &arg);
1536 cmd->override = OR_ALL|ACCESS_CONF;
1538 if (thiscmd->cmd_data) { /* <DirectoryMatch> */
1539 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1541 else if (!strcmp(cmd->path, "~")) {
1542 cmd->path = ap_getword_conf(cmd->pool, &arg);
1543 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1545 #if defined(HAVE_DRIVE_LETTERS) || defined(NETWARE)
1546 else if (strcmp(cmd->path, "/") == 0) {
1547 /* Treat 'default' path / as an inalienable root */
1548 cmd->path = apr_pstrdup(cmd->pool, cmd->path);
1551 #if defined(HAVE_UNC_PATHS)
1552 else if (strcmp(cmd->path, "//") == 0) {
1553 /* Treat UNC path // as an inalienable root */
1554 cmd->path = apr_pstrdup(cmd->pool, cmd->path);
1558 /* Ensure that the pathname is canonical */
1559 cmd->path = ap_os_canonical_filename(cmd->pool, cmd->path);
1562 /* initialize our config and fetch it */
1563 conf = (core_dir_config *)ap_set_config_vectors(cmd, new_dir_conf,
1566 errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_dir_conf);
1572 ap_add_per_dir_conf(cmd->server, new_dir_conf);
1575 return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1576 "> arguments not (yet) supported.", NULL);
1579 cmd->path = old_path;
1580 cmd->override = old_overrides;
1585 static const char *urlsection(cmd_parms *cmd, void *mconfig, const char *arg)
1588 const char *endp = ap_strrchr_c(arg, '>');
1589 int old_overrides = cmd->override;
1590 char *old_path = cmd->path;
1591 core_dir_config *conf;
1593 const command_rec *thiscmd = cmd->cmd;
1595 void *new_url_conf = ap_create_per_dir_config(cmd->pool);
1597 const char *err = ap_check_cmd_context(cmd,
1598 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1604 return unclosed_directive(cmd);
1607 arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1609 cmd->path = ap_getword_conf(cmd->pool, &arg);
1610 cmd->override = OR_ALL|ACCESS_CONF;
1612 if (thiscmd->cmd_data) { /* <LocationMatch> */
1613 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1615 else if (!strcmp(cmd->path, "~")) {
1616 cmd->path = ap_getword_conf(cmd->pool, &arg);
1617 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1620 /* initialize our config and fetch it */
1621 conf = (core_dir_config *)ap_set_config_vectors(cmd, new_url_conf,
1624 errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_url_conf);
1628 conf->d = apr_pstrdup(cmd->pool, cmd->path); /* No mangling, please */
1629 conf->d_is_fnmatch = apr_is_fnmatch(conf->d) != 0;
1632 ap_add_per_url_conf(cmd->server, new_url_conf);
1635 return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1636 "> arguments not (yet) supported.", NULL);
1639 cmd->path = old_path;
1640 cmd->override = old_overrides;
1645 static const char *filesection(cmd_parms *cmd, void *mconfig, const char *arg)
1648 const char *endp = ap_strrchr_c(arg, '>');
1649 int old_overrides = cmd->override;
1650 char *old_path = cmd->path;
1651 core_dir_config *conf;
1653 const command_rec *thiscmd = cmd->cmd;
1654 core_dir_config *c=mconfig;
1656 void *new_file_conf = ap_create_per_dir_config(cmd->pool);
1658 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT|NOT_IN_LOCATION);
1664 return unclosed_directive(cmd);
1667 arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1669 cmd->path = ap_getword_conf(cmd->pool, &arg);
1670 /* Only if not an .htaccess file */
1672 cmd->override = OR_ALL|ACCESS_CONF;
1675 if (thiscmd->cmd_data) { /* <FilesMatch> */
1676 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1678 else if (!strcmp(cmd->path, "~")) {
1679 cmd->path = ap_getword_conf(cmd->pool, &arg);
1680 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1683 /* Ensure that the pathname is canonical */
1684 cmd->path = ap_os_canonical_filename(cmd->pool, cmd->path);
1687 /* initialize our config and fetch it */
1688 conf = (core_dir_config *)ap_set_config_vectors(cmd, new_file_conf,
1691 errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_file_conf);
1695 conf->d = cmd->path;
1696 conf->d_is_fnmatch = apr_is_fnmatch(conf->d) != 0;
1699 ap_add_file_conf(c, new_file_conf);
1702 return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1703 "> arguments not (yet) supported.", NULL);
1706 cmd->path = old_path;
1707 cmd->override = old_overrides;
1712 static const char *start_ifmod(cmd_parms *cmd, void *mconfig, const char *arg)
1714 const char *endp = ap_strrchr_c(arg, '>');
1715 int not = (arg[0] == '!');
1719 return unclosed_directive(cmd);
1722 arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1728 found = ap_find_linked_module(arg);
1730 if ((!not && found) || (not && !found)) {
1731 ap_directive_t *parent = NULL;
1732 ap_directive_t *current = NULL;
1735 retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd,
1736 ¤t, &parent, "<IfModule");
1737 *(ap_directive_t **)mconfig = current;
1741 *(ap_directive_t **)mconfig = NULL;
1742 return ap_soak_end_container(cmd, "<IfModule");
1746 AP_DECLARE(int) ap_exists_config_define(const char *name)
1751 defines = (char **)ap_server_config_defines->elts;
1752 for (i = 0; i < ap_server_config_defines->nelts; i++) {
1753 if (strcmp(defines[i], name) == 0) {
1760 static const char *start_ifdefine(cmd_parms *cmd, void *dummy, const char *arg)
1766 endp = ap_strrchr_c(arg, '>');
1768 return unclosed_directive(cmd);
1771 arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1773 if (arg[0] == '!') {
1778 defined = ap_exists_config_define(arg);
1779 if ((!not && defined) || (not && !defined)) {
1780 ap_directive_t *parent = NULL;
1781 ap_directive_t *current = NULL;
1784 retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd,
1785 ¤t, &parent, "<IfDefine");
1786 *(ap_directive_t **)dummy = current;
1790 *(ap_directive_t **)dummy = NULL;
1791 return ap_soak_end_container(cmd, "<IfDefine");
1795 /* httpd.conf commands... beginning with the <VirtualHost> business */
1797 static const char *virtualhost_section(cmd_parms *cmd, void *dummy,
1800 server_rec *main_server = cmd->server, *s;
1802 const char *endp = ap_strrchr_c(arg, '>');
1803 apr_pool_t *p = cmd->pool;
1805 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1811 return unclosed_directive(cmd);
1814 arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1816 /* FIXME: There's another feature waiting to happen here -- since you
1817 can now put multiple addresses/names on a single <VirtualHost>
1818 you might want to use it to group common definitions and then
1819 define other "subhosts" with their individual differences. But
1820 personally I'd rather just do it with a macro preprocessor. -djg */
1821 if (main_server->is_virtual) {
1822 return "<VirtualHost> doesn't nest!";
1825 errmsg = ap_init_virtual_host(p, arg, main_server, &s);
1830 s->next = main_server->next;
1831 main_server->next = s;
1833 s->defn_name = cmd->directive->filename;
1834 s->defn_line_number = cmd->directive->line_num;
1838 errmsg = ap_walk_config(cmd->directive->first_child, cmd,
1839 s->lookup_defaults);
1841 cmd->server = main_server;
1846 static const char *set_server_alias(cmd_parms *cmd, void *dummy,
1849 if (!cmd->server->names) {
1850 return "ServerAlias only used in <VirtualHost>";
1853 char **item, *name = ap_getword_conf(cmd->pool, &arg);
1854 if (ap_is_matchexp(name)) {
1855 item = (char **)apr_push_array(cmd->server->wild_names);
1858 item = (char **)apr_push_array(cmd->server->names);
1865 static const char *add_filter(cmd_parms *cmd, void *dummy, const char *arg)
1867 core_dir_config *conf = dummy;
1870 newfilter = (char **)apr_push_array(conf->output_filters);
1871 *newfilter = apr_pstrdup(cmd->pool, arg);
1875 static const char *add_input_filter(cmd_parms *cmd, void *dummy, const char *arg)
1877 core_dir_config *conf = dummy;
1880 newfilter = (char **)apr_push_array(conf->input_filters);
1881 *newfilter = apr_pstrdup(cmd->pool, arg);
1885 static const char *add_module_command(cmd_parms *cmd, void *dummy,
1888 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1893 if (!ap_add_named_module(arg)) {
1894 return apr_pstrcat(cmd->pool, "Cannot add module via name '", arg,
1895 "': not in list of loaded modules", NULL);
1897 *(ap_directive_t **)dummy = NULL;
1901 static const char *clear_module_list_command(cmd_parms *cmd, void *dummy)
1903 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1908 ap_clear_module_list();
1909 *(ap_directive_t **)dummy = NULL;
1913 static const char *set_server_string_slot(cmd_parms *cmd, void *dummy,
1916 /* This one's pretty generic... */
1918 int offset = (int)(long)cmd->info;
1919 char *struct_ptr = (char *)cmd->server;
1921 const char *err = ap_check_cmd_context(cmd,
1922 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1927 *(const char **)(struct_ptr + offset) = arg;
1931 static const char *server_port(cmd_parms *cmd, void *dummy, const char *arg)
1933 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1940 if (port <= 0 || port >= 65536) { /* 65536 == 1<<16 */
1941 return apr_pstrcat(cmd->temp_pool, "The port number \"", arg,
1942 "\" is outside the appropriate range "
1943 "(i.e., 1..65535).", NULL);
1945 cmd->server->port = port;
1949 static const char *set_signature_flag(cmd_parms *cmd, void *d_,
1952 core_dir_config *d=d_;
1954 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1959 if (strcasecmp(arg, "On") == 0) {
1960 d->server_signature = srv_sig_on;
1962 else if (strcasecmp(arg, "Off") == 0) {
1963 d->server_signature = srv_sig_off;
1965 else if (strcasecmp(arg, "EMail") == 0) {
1966 d->server_signature = srv_sig_withmail;
1969 return "ServerSignature: use one of: off | on | email";
1974 static const char *set_server_root(cmd_parms *cmd, void *dummy,
1977 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1983 arg = ap_os_canonical_filename(cmd->pool, arg);
1985 if (!ap_is_directory(arg)) {
1986 return "ServerRoot must be a valid directory";
1988 ap_server_root = arg;
1992 static const char *set_timeout(cmd_parms *cmd, void *dummy, const char *arg)
1994 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1999 cmd->server->timeout = atoi(arg);
2003 static const char *set_keep_alive_timeout(cmd_parms *cmd, void *dummy,
2006 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2011 cmd->server->keep_alive_timeout = atoi(arg);
2015 static const char *set_keep_alive(cmd_parms *cmd, void *dummy,
2018 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2023 /* We've changed it to On/Off, but used to use numbers
2024 * so we accept anything but "Off" or "0" as "On"
2026 if (!strcasecmp(arg, "off") || !strcmp(arg, "0")) {
2027 cmd->server->keep_alive = 0;
2030 cmd->server->keep_alive = 1;
2035 static const char *set_keep_alive_max(cmd_parms *cmd, void *dummy,
2038 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2043 cmd->server->keep_alive_max = atoi(arg);
2047 static const char *set_idcheck(cmd_parms *cmd, void *d_, int arg)
2049 core_dir_config *d=d_;
2050 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2055 d->do_rfc1413 = arg != 0;
2059 static const char *set_hostname_lookups(cmd_parms *cmd, void *d_,
2062 core_dir_config *d=d_;
2064 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2069 if (!strcasecmp(arg, "on")) {
2070 d->hostname_lookups = HOSTNAME_LOOKUP_ON;
2072 else if (!strcasecmp(arg, "off")) {
2073 d->hostname_lookups = HOSTNAME_LOOKUP_OFF;
2075 else if (!strcasecmp(arg, "double")) {
2076 d->hostname_lookups = HOSTNAME_LOOKUP_DOUBLE;
2079 return "parameter must be 'on', 'off', or 'double'";
2084 static const char *set_serverpath(cmd_parms *cmd, void *dummy,
2087 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2092 cmd->server->path = arg;
2093 cmd->server->pathlen = strlen(arg);
2097 static const char *set_content_md5(cmd_parms *cmd, void *d_, int arg)
2099 core_dir_config *d=d_;
2100 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2105 d->content_md5 = arg != 0;
2109 static const char *set_use_canonical_name(cmd_parms *cmd, void *d_,
2112 core_dir_config *d=d_;
2113 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2118 if (strcasecmp(arg, "on") == 0) {
2119 d->use_canonical_name = USE_CANONICAL_NAME_ON;
2121 else if (strcasecmp(arg, "off") == 0) {
2122 d->use_canonical_name = USE_CANONICAL_NAME_OFF;
2124 else if (strcasecmp(arg, "dns") == 0) {
2125 d->use_canonical_name = USE_CANONICAL_NAME_DNS;
2128 return "parameter must be 'on', 'off', or 'dns'";
2134 static const char *include_config (cmd_parms *cmd, void *dummy,
2137 ap_directive_t *conftree = NULL;
2139 ap_process_resource_config(cmd->server,
2140 ap_server_root_relative(cmd->pool, name),
2141 &conftree, cmd->pool, cmd->temp_pool);
2142 *(ap_directive_t **)dummy = conftree;
2146 static const char *set_loglevel(cmd_parms *cmd, void *dummy, const char *arg)
2150 const char *err = ap_check_cmd_context(cmd,
2151 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2156 if ((str = ap_getword_conf(cmd->pool, &arg))) {
2157 if (!strcasecmp(str, "emerg")) {
2158 cmd->server->loglevel = APLOG_EMERG;
2160 else if (!strcasecmp(str, "alert")) {
2161 cmd->server->loglevel = APLOG_ALERT;
2163 else if (!strcasecmp(str, "crit")) {
2164 cmd->server->loglevel = APLOG_CRIT;
2166 else if (!strcasecmp(str, "error")) {
2167 cmd->server->loglevel = APLOG_ERR;
2169 else if (!strcasecmp(str, "warn")) {
2170 cmd->server->loglevel = APLOG_WARNING;
2172 else if (!strcasecmp(str, "notice")) {
2173 cmd->server->loglevel = APLOG_NOTICE;
2175 else if (!strcasecmp(str, "info")) {
2176 cmd->server->loglevel = APLOG_INFO;
2178 else if (!strcasecmp(str, "debug")) {
2179 cmd->server->loglevel = APLOG_DEBUG;
2182 return "LogLevel requires level keyword: one of "
2183 "emerg/alert/crit/error/warn/notice/info/debug";
2187 return "LogLevel requires level keyword";
2193 AP_DECLARE(const char *) ap_psignature(const char *prefix, request_rec *r)
2196 core_dir_config *conf;
2198 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
2200 if ((conf->server_signature == srv_sig_off)
2201 || (conf->server_signature == srv_sig_unset)) {
2205 apr_snprintf(sport, sizeof sport, "%u", (unsigned) ap_get_server_port(r));
2207 if (conf->server_signature == srv_sig_withmail) {
2208 return apr_pstrcat(r->pool, prefix, "<ADDRESS>" AP_SERVER_BASEVERSION
2209 " Server at <A HREF=\"mailto:",
2210 r->server->server_admin, "\">",
2211 ap_get_server_name(r), "</A> Port ", sport,
2212 "</ADDRESS>\n", NULL);
2214 return apr_pstrcat(r->pool, prefix, "<ADDRESS>" AP_SERVER_BASEVERSION
2215 " Server at ", ap_get_server_name(r), " Port ", sport,
2216 "</ADDRESS>\n", NULL);
2220 * Load an authorisation realm into our location configuration, applying the
2221 * usual rules that apply to realms.
2223 static const char *set_authname(cmd_parms *cmd, void *mconfig,
2226 core_dir_config *aconfig = (core_dir_config *)mconfig;
2228 aconfig->ap_auth_name = ap_escape_quotes(cmd->pool, word1);
2232 #ifdef _OSD_POSIX /* BS2000 Logon Passwd file */
2233 static const char *set_bs2000_account(cmd_parms *cmd, void *dummy, char *name)
2235 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2240 return os_set_account(cmd->pool, name);
2242 #endif /*_OSD_POSIX*/
2245 * Handle a request to include the server's OS platform in the Server
2246 * response header field (the ServerTokens directive). Unfortunately
2247 * this requires a new global in order to communicate the setting back to
2248 * http_main so it can insert the information in the right place in the
2252 static char *server_version = NULL;
2253 static int version_locked = 0;
2255 enum server_token_type {
2256 SrvTk_MIN, /* eg: Apache/1.3.0 */
2257 SrvTk_OS, /* eg: Apache/1.3.0 (UNIX) */
2258 SrvTk_FULL, /* eg: Apache/1.3.0 (UNIX) PHP/3.0 FooBar/1.2b */
2259 SrvTk_PRODUCT_ONLY /* eg: Apache */
2261 static enum server_token_type ap_server_tokens = SrvTk_FULL;
2263 static apr_status_t reset_version(void *dummy)
2266 ap_server_tokens = SrvTk_FULL;
2267 server_version = NULL;
2271 AP_DECLARE(const char *) ap_get_server_version(void)
2273 return (server_version ? server_version : AP_SERVER_BASEVERSION);
2276 AP_DECLARE(void) ap_add_version_component(apr_pool_t *pconf, const char *component)
2278 if (! version_locked) {
2280 * If the version string is null, register our cleanup to reset the
2281 * pointer on pool destruction. We also know that, if NULL,
2282 * we are adding the original SERVER_BASEVERSION string.
2284 if (server_version == NULL) {
2285 apr_register_cleanup(pconf, NULL, reset_version,
2287 server_version = apr_pstrdup(pconf, component);
2291 * Tack the given component identifier to the end of
2292 * the existing string.
2294 server_version = apr_pstrcat(pconf, server_version, " ",
2301 * This routine adds the real server base identity to the version string,
2302 * and then locks out changes until the next reconfig.
2304 static void ap_set_version(apr_pool_t *pconf)
2306 if (ap_server_tokens == SrvTk_PRODUCT_ONLY) {
2307 ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT);
2309 else if (ap_server_tokens == SrvTk_MIN) {
2310 ap_add_version_component(pconf, AP_SERVER_BASEVERSION);
2313 ap_add_version_component(pconf, AP_SERVER_BASEVERSION " (" PLATFORM ")");
2316 * Lock the server_version string if we're not displaying
2317 * the full set of tokens
2319 if (ap_server_tokens != SrvTk_FULL) {
2324 static const char *set_serv_tokens(cmd_parms *cmd, void *dummy,
2327 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2332 if (!strcasecmp(arg, "OS")) {
2333 ap_server_tokens = SrvTk_OS;
2335 else if (!strcasecmp(arg, "Min") || !strcasecmp(arg, "Minimal")) {
2336 ap_server_tokens = SrvTk_MIN;
2338 else if (!strcasecmp(arg, "Prod") || !strcasecmp(arg, "ProductOnly")) {
2339 ap_server_tokens = SrvTk_PRODUCT_ONLY;
2342 ap_server_tokens = SrvTk_FULL;
2347 static const char *set_limit_req_line(cmd_parms *cmd, void *dummy,
2350 const char *err = ap_check_cmd_context(cmd,
2351 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2359 return apr_pstrcat(cmd->temp_pool, "LimitRequestLine \"", arg,
2360 "\" must be a non-negative integer", NULL);
2362 if (lim > DEFAULT_LIMIT_REQUEST_LINE) {
2363 return apr_psprintf(cmd->temp_pool, "LimitRequestLine \"%s\" "
2364 "must not exceed the precompiled maximum of %d",
2365 arg, DEFAULT_LIMIT_REQUEST_LINE);
2367 cmd->server->limit_req_line = lim;
2371 static const char *set_limit_req_fieldsize(cmd_parms *cmd, void *dummy,
2374 const char *err = ap_check_cmd_context(cmd,
2375 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2383 return apr_pstrcat(cmd->temp_pool, "LimitRequestFieldsize \"", arg,
2384 "\" must be a non-negative integer (0 = no limit)",
2387 if (lim > DEFAULT_LIMIT_REQUEST_FIELDSIZE) {
2388 return apr_psprintf(cmd->temp_pool, "LimitRequestFieldsize \"%s\" "
2389 "must not exceed the precompiled maximum of %d",
2390 arg, DEFAULT_LIMIT_REQUEST_FIELDSIZE);
2392 cmd->server->limit_req_fieldsize = lim;
2396 static const char *set_limit_req_fields(cmd_parms *cmd, void *dummy,
2399 const char *err = ap_check_cmd_context(cmd,
2400 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2408 return apr_pstrcat(cmd->temp_pool, "LimitRequestFields \"", arg,
2409 "\" must be a non-negative integer (0 = no limit)",
2412 cmd->server->limit_req_fields = lim;
2416 static const char *set_limit_req_body(cmd_parms *cmd, void *conf_,
2419 core_dir_config *conf=conf_;
2420 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2425 /* WTF: If strtoul is not portable, then write a replacement.
2426 * Instead we have an idiotic define in httpd.h that prevents
2427 * it from being used even when it is available. Sheesh.
2429 conf->limit_req_body = (unsigned long)strtol(arg, (char **)NULL, 10);
2433 static const char *set_limit_xml_req_body(cmd_parms *cmd, void *conf_,
2436 core_dir_config *conf = conf_;
2437 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2442 conf->limit_xml_body = atol(arg);
2443 if (conf->limit_xml_body < 0)
2444 return "LimitXMLRequestBody requires a non-negative integer.";
2449 AP_DECLARE(size_t) ap_get_limit_xml_body(const request_rec *r)
2451 core_dir_config *conf;
2453 conf = ap_get_module_config(r->per_dir_config, &core_module);
2454 if (conf->limit_xml_body == AP_LIMIT_UNSET)
2455 return AP_DEFAULT_LIMIT_XML_BODY;
2456 return (size_t)conf->limit_xml_body;
2460 static const char *set_interpreter_source(cmd_parms *cmd, core_dir_config *d,
2463 if (!strcasecmp(arg, "registry")) {
2464 d->script_interpreter_source = INTERPRETER_SOURCE_REGISTRY;
2465 } else if (!strcasecmp(arg, "registry-strict")) {
2466 d->script_interpreter_source = INTERPRETER_SOURCE_REGISTRY_STRICT;
2467 } else if (!strcasecmp(arg, "script")) {
2468 d->script_interpreter_source = INTERPRETER_SOURCE_SHEBANG;
2470 return apr_pstrcat(cmd->temp_pool, "ScriptInterpreterSource \"", arg,
2471 "\" must be \"registry\", \"registry-strict\" or "
2472 "\"script\"", NULL);
2478 #if !defined (RLIMIT_CPU) || !(defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)) || !defined (RLIMIT_NPROC)
2479 static const char *no_set_limit(cmd_parms *cmd, void *conf_,
2480 const char *arg, const char *arg2)
2482 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, cmd->server,
2483 "%s not supported on this platform", cmd->cmd->name);
2489 static const char *set_limit_cpu(cmd_parms *cmd, void *conf_,
2490 const char *arg, const char *arg2)
2492 core_dir_config *conf=conf_;
2494 unixd_set_rlimit(cmd, &conf->limit_cpu, arg, arg2, RLIMIT_CPU);
2499 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)
2500 static const char *set_limit_mem(cmd_parms *cmd, void *conf_,
2501 const char *arg, const char * arg2)
2503 core_dir_config *conf=conf_;
2505 #if defined(RLIMIT_AS)
2506 unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2 ,RLIMIT_AS);
2507 #elif defined(RLIMIT_DATA)
2508 unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_DATA);
2509 #elif defined(RLIMIT_VMEM)
2510 unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_VMEM);
2517 static const char *set_limit_nproc(cmd_parms *cmd, void *conf_,
2518 const char *arg, const char * arg2)
2520 core_dir_config *conf=conf_;
2522 unixd_set_rlimit(cmd, &conf->limit_nproc, arg, arg2, RLIMIT_NPROC);
2527 static apr_status_t writev_it_all(apr_socket_t *s, struct iovec *vec, int nvec,
2528 apr_size_t len, apr_size_t *nbytes)
2530 apr_size_t bytes_written = 0;
2537 /* XXX handle checking for non-blocking socket */
2538 while (bytes_written != len) {
2539 rv = apr_sendv(s, vec + i, nvec - i, &n);
2541 if (rv != APR_SUCCESS)
2545 /* If the write did not complete, adjust the iovecs and issue
2548 if (bytes_written < len) {
2549 /* Skip over the vectors that have already been written */
2550 apr_size_t cnt = vec[i].iov_len;
2551 while (n >= cnt && i + 1 < nvec) {
2553 cnt += vec[i].iov_len;
2556 /* Handle partial write of vec i */
2557 vec[i].iov_base = (char *) vec[i].iov_base +
2558 (vec[i].iov_len - (cnt - n));
2559 vec[i].iov_len = cnt -n;
2562 n = len - bytes_written;
2569 * Sends the contents of file fd along with header/trailer bytes, if any,
2570 * to the network. send_the_file will return only when all the bytes have been
2571 * sent (i.e., it handles partial writes) or on a network error condition.
2573 static apr_status_t send_the_file(conn_rec *c, apr_file_t *fd,
2574 apr_hdtr_t *hdtr, apr_off_t offset,
2575 apr_size_t length, apr_size_t *nbytes)
2577 apr_status_t rv = APR_SUCCESS;
2578 apr_int32_t togo; /* Remaining number of bytes in the file to send */
2579 apr_size_t sendlen = 0;
2580 apr_size_t bytes_sent;
2582 apr_off_t o; /* Track the file offset for partial writes */
2588 * writev_it_all handles partial writes.
2589 * XXX: optimization... if headers are less than MIN_WRITE_SIZE, copy
2592 if ( hdtr && hdtr->numheaders > 0 ) {
2593 for (i = 0; i < hdtr->numheaders; i++) {
2594 sendlen += hdtr->headers[i].iov_len;
2596 rv = writev_it_all(c->client_socket, hdtr->headers, hdtr->numheaders,
2597 sendlen, &bytes_sent);
2598 if (rv == APR_SUCCESS)
2599 *nbytes += bytes_sent; /* track total bytes sent */
2602 /* Seek the file to 'offset' */
2603 if (offset != 0 && rv == APR_SUCCESS) {
2604 rv = apr_seek(fd, APR_SET, &offset);
2607 /* Send the file, making sure to handle partial writes */
2609 while (rv == APR_SUCCESS && togo) {
2610 sendlen = togo > sizeof(buffer) ? sizeof(buffer) : togo;
2612 rv = apr_read(fd, buffer, &sendlen);
2613 while (rv == APR_SUCCESS && sendlen) {
2614 bytes_sent = sendlen;
2615 rv = apr_send(c->client_socket, &buffer[o], &bytes_sent);
2616 if (rv == APR_SUCCESS) {
2617 sendlen -= bytes_sent; /* sendlen != bytes_sent ==> partial write */
2618 o += bytes_sent; /* o is where we are in the buffer */
2619 *nbytes += bytes_sent;
2620 togo -= bytes_sent; /* track how much of the file we've sent */
2625 /* Send the trailers
2626 * XXX: optimization... if it will fit, send this on the last send in the
2630 if ( rv == APR_SUCCESS && hdtr && hdtr->numtrailers > 0 ) {
2631 for (i = 0; i < hdtr->numtrailers; i++) {
2632 sendlen += hdtr->trailers[i].iov_len;
2634 rv = writev_it_all(c->client_socket, hdtr->trailers, hdtr->numtrailers,
2635 sendlen, &bytes_sent);
2636 if (rv == APR_SUCCESS)
2637 *nbytes += bytes_sent;
2643 /* Note --- ErrorDocument will now work from .htaccess files.
2644 * The AllowOverride of Fileinfo allows webmasters to turn it off
2647 static const command_rec core_cmds[] = {
2649 /* Old access config file commands */
2651 AP_INIT_RAW_ARGS("<Directory", dirsection, NULL, RSRC_CONF,
2652 "Container for directives affecting resources located in the specified "
2654 AP_INIT_RAW_ARGS("<Location", urlsection, NULL, RSRC_CONF,
2655 "Container for directives affecting resources accessed through the "
2656 "specified URL paths"),
2657 AP_INIT_RAW_ARGS("<VirtualHost", virtualhost_section, NULL, RSRC_CONF,
2658 "Container to map directives to a particular virtual host, takes one or "
2659 "more host addresses"),
2660 AP_INIT_RAW_ARGS("<Files", filesection, NULL, OR_ALL,
2661 "Container for directives affecting files matching specified patterns"),
2662 AP_INIT_RAW_ARGS("<Limit", ap_limit_section, NULL, OR_ALL,
2663 "Container for authentication directives when accessed using specified HTTP "
2665 AP_INIT_RAW_ARGS("<LimitExcept", ap_limit_section, (void*)1, OR_ALL,
2666 "Container for authentication directives to be applied when any HTTP "
2667 "method other than those specified is used to access the resource"),
2668 AP_INIT_TAKE1("<IfModule", start_ifmod, NULL, EXEC_ON_READ | OR_ALL,
2669 "Container for directives based on existance of specified modules"),
2670 AP_INIT_TAKE1("<IfDefine", start_ifdefine, NULL, EXEC_ON_READ | OR_ALL,
2671 "Container for directives based on existance of command line defines"),
2672 AP_INIT_RAW_ARGS("<DirectoryMatch", dirsection, (void*)1, RSRC_CONF,
2673 "Container for directives affecting resources located in the "
2674 "specified directories"),
2675 AP_INIT_RAW_ARGS("<LocationMatch", urlsection, (void*)1, RSRC_CONF,
2676 "Container for directives affecting resources accessed through the "
2677 "specified URL paths"),
2678 AP_INIT_RAW_ARGS("<FilesMatch", filesection, (void*)1, OR_ALL,
2679 "Container for directives affecting files matching specified patterns"),
2680 AP_INIT_TAKE1("AuthType", ap_set_string_slot,
2681 (void*)XtOffsetOf(core_dir_config, ap_auth_type), OR_AUTHCFG,
2682 "An HTTP authorization type (e.g., \"Basic\")"),
2683 AP_INIT_TAKE1("AuthName", set_authname, NULL, OR_AUTHCFG,
2684 "The authentication realm (e.g. \"Members Only\")"),
2685 AP_INIT_RAW_ARGS("Require", require, NULL, OR_AUTHCFG,
2686 "Selects which authenticated users or groups may access a protected space"),
2687 AP_INIT_TAKE1("Satisfy", satisfy, NULL, OR_AUTHCFG,
2688 "access policy if both allow and require used ('all' or 'any')"),
2690 AP_INIT_TAKE1("GprofDir", set_gprof_dir, NULL, RSRC_CONF,
2691 "Directory to plop gmon.out files"),
2693 AP_INIT_TAKE1("AddDefaultCharset", set_add_default_charset, NULL, OR_FILEINFO,
2694 "The name of the default charset to add to any Content-Type without one or 'Off' to disable"),
2696 /* Old resource config file commands */
2698 AP_INIT_RAW_ARGS("AccessFileName", set_access_name, NULL, RSRC_CONF,
2699 "Name(s) of per-directory config files (default: .htaccess)"),
2700 AP_INIT_TAKE1("DocumentRoot", set_document_root, NULL, RSRC_CONF,
2701 "Root directory of the document tree"),
2702 AP_INIT_TAKE2("ErrorDocument", set_error_document, NULL, OR_FILEINFO,
2703 "Change responses for HTTP errors"),
2704 AP_INIT_RAW_ARGS("AllowOverride", set_override, NULL, ACCESS_CONF,
2705 "Controls what groups of directives can be configured by per-directory "
2707 AP_INIT_RAW_ARGS("Options", set_options, NULL, OR_OPTIONS,
2708 "Set a number of attributes for a given directory"),
2709 AP_INIT_TAKE1("DefaultType", ap_set_string_slot,
2710 (void*)XtOffsetOf (core_dir_config, ap_default_type),
2711 OR_FILEINFO, "the default MIME type for untypable files"),
2713 /* Old server config file commands */
2715 AP_INIT_TAKE1("Port", server_port, NULL, RSRC_CONF, "A TCP port number"),
2716 AP_INIT_TAKE1("HostnameLookups", set_hostname_lookups, NULL,
2717 ACCESS_CONF|RSRC_CONF,
2718 "\"on\" to enable, \"off\" to disable reverse DNS lookups, or \"double\" to "
2719 "enable double-reverse DNS lookups"),
2720 AP_INIT_TAKE1("ServerAdmin", set_server_string_slot,
2721 (void *)XtOffsetOf (server_rec, server_admin), RSRC_CONF,
2722 "The email address of the server administrator"),
2723 AP_INIT_TAKE1("ServerName", set_server_string_slot,
2724 (void *)XtOffsetOf (server_rec, server_hostname), RSRC_CONF,
2725 "The hostname of the server"),
2726 AP_INIT_TAKE1("ServerSignature", set_signature_flag, NULL, OR_ALL,
2727 "En-/disable server signature (on|off|email)"),
2728 AP_INIT_TAKE1("ServerRoot", set_server_root, NULL, RSRC_CONF,
2729 "Common directory of server-related files (logs, confs, etc.)"),
2730 AP_INIT_TAKE1("ErrorLog", set_server_string_slot,
2731 (void *)XtOffsetOf (server_rec, error_fname), RSRC_CONF,
2732 "The filename of the error log"),
2733 AP_INIT_RAW_ARGS("ServerAlias", set_server_alias, NULL, RSRC_CONF,
2734 "A name or names alternately used to access the server"),
2735 AP_INIT_TAKE1("ServerPath", set_serverpath, NULL, RSRC_CONF,
2736 "The pathname the server can be reached at"),
2737 AP_INIT_TAKE1("Timeout", set_timeout, NULL, RSRC_CONF,
2738 "Timeout duration (sec)"),
2739 AP_INIT_TAKE1("KeepAliveTimeout", set_keep_alive_timeout, NULL, RSRC_CONF,
2740 "Keep-Alive timeout duration (sec)"),
2741 AP_INIT_TAKE1("MaxKeepAliveRequests", set_keep_alive_max, NULL, RSRC_CONF,
2742 "Maximum number of Keep-Alive requests per connection, or 0 for infinite"),
2743 AP_INIT_TAKE1("KeepAlive", set_keep_alive, NULL, RSRC_CONF,
2744 "Whether persistent connections should be On or Off"),
2745 AP_INIT_FLAG("IdentityCheck", set_idcheck, NULL, RSRC_CONF|ACCESS_CONF,
2746 "Enable identd (RFC 1413) user lookups - SLOW"),
2747 AP_INIT_FLAG("ContentDigest", set_content_md5, NULL, OR_OPTIONS,
2748 "whether or not to send a Content-MD5 header with each request"),
2749 AP_INIT_TAKE1("UseCanonicalName", set_use_canonical_name, NULL,
2750 RSRC_CONF|ACCESS_CONF,
2751 "How to work out the ServerName : Port when constructing URLs"),
2752 /* TODO: RlimitFoo should all be part of mod_cgi, not in the core */
2753 AP_INIT_ITERATE("AddModule", add_module_command, NULL,
2754 RSRC_CONF, "The name of a module"),
2755 AP_INIT_NO_ARGS("ClearModuleList", clear_module_list_command, NULL,
2757 /* TODO: ListenBacklog in MPM */
2758 AP_INIT_TAKE1("Include", include_config, NULL,
2759 (RSRC_CONF | ACCESS_CONF | EXEC_ON_READ),
2760 "Name of the config file to be included"),
2761 AP_INIT_TAKE1("LogLevel", set_loglevel, NULL, RSRC_CONF,
2762 "Level of verbosity in error logging"),
2763 AP_INIT_TAKE1("NameVirtualHost", ap_set_name_virtual_host, NULL, RSRC_CONF,
2764 "A numeric IP address:port, or the name of a host"),
2766 AP_INIT_TAKE1("BS2000Account", set_bs2000_account, NULL, RSRC_CONF,
2767 "Name of server User's bs2000 logon account name"),
2770 AP_INIT_TAKE1("ScriptInterpreterSource", set_interpreter_source, NULL,
2772 "Where to find interpreter to run Win32 scripts (Registry or script shebang line)"),
2774 AP_INIT_TAKE1("ServerTokens", set_serv_tokens, NULL, RSRC_CONF,
2775 "Determine tokens displayed in the Server: header - Min(imal), OS or Full"),
2776 AP_INIT_TAKE1("LimitRequestLine", set_limit_req_line, NULL, RSRC_CONF,
2777 "Limit on maximum size of an HTTP request line"),
2778 AP_INIT_TAKE1("LimitRequestFieldsize", set_limit_req_fieldsize, NULL,
2780 "Limit on maximum size of an HTTP request header field"),
2781 AP_INIT_TAKE1("LimitRequestFields", set_limit_req_fields, NULL, RSRC_CONF,
2782 "Limit (0 = unlimited) on max number of header fields in a request message"),
2783 AP_INIT_TAKE1("LimitRequestBody", set_limit_req_body,
2784 (void*)XtOffsetOf(core_dir_config, limit_req_body), OR_ALL,
2785 "Limit (in bytes) on maximum size of request message body"),
2786 AP_INIT_TAKE1("LimitXMLRequestBody", set_limit_xml_req_body, NULL, OR_ALL,
2787 "Limit (in bytes) on maximum size of an XML-based request "
2790 /* System Resource Controls */
2792 AP_INIT_TAKE12("RLimitCPU", set_limit_cpu,
2793 (void*)XtOffsetOf(core_dir_config, limit_cpu),
2794 OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
2796 AP_INIT_TAKE12("RLimitCPU", no_set_limit, NULL,
2797 OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
2799 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined (RLIMIT_AS)
2800 AP_INIT_TAKE12("RLimitMEM", set_limit_mem,
2801 (void*)XtOffsetOf(core_dir_config, limit_mem),
2802 OR_ALL, "Soft/hard limits for max memory usage per process"),
2804 AP_INIT_TAKE12("RLimitMEM", no_set_limit, NULL,
2805 OR_ALL, "Soft/hard limits for max memory usage per process"),
2808 AP_INIT_TAKE12("RLimitNPROC", set_limit_nproc,
2809 (void*)XtOffsetOf(core_dir_config, limit_nproc),
2810 OR_ALL, "soft/hard limits for max number of processes per uid"),
2812 AP_INIT_TAKE12("RLimitNPROC", no_set_limit, NULL,
2813 OR_ALL, "soft/hard limits for max number of processes per uid"),
2815 /* XXX These should be allowable in .htaccess files, but currently it won't
2816 * play well with the Options stuff. Until that is fixed, I would prefer
2817 * to leave it just in the conf file. Other should feel free to disagree
2820 AP_INIT_ITERATE("AddOutputFilter", add_filter, NULL, ACCESS_CONF,
2821 "filters to be run"),
2822 AP_INIT_ITERATE("AddInputFilter", add_input_filter, NULL, ACCESS_CONF,
2823 "filters to be run on the request body"),
2827 /*****************************************************************
2829 * Core handlers for various phases of server operation...
2832 AP_DECLARE_NONSTD(int) ap_core_translate(request_rec *r)
2834 void *sconf = r->server->module_config;
2835 core_server_config *conf = ap_get_module_config(sconf, &core_module);
2838 return HTTP_FORBIDDEN;
2840 if ((r->uri[0] != '/') && strcmp(r->uri, "*")) {
2841 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2842 "Invalid URI in request %s", r->the_request);
2843 return HTTP_BAD_REQUEST;
2847 && !strncmp(r->uri, r->server->path, r->server->pathlen)
2848 && (r->server->path[r->server->pathlen - 1] == '/'
2849 || r->uri[r->server->pathlen] == '/'
2850 || r->uri[r->server->pathlen] == '\0')) {
2851 r->filename = apr_pstrcat(r->pool, conf->ap_document_root,
2852 (r->uri + r->server->pathlen), NULL);
2856 * Make sure that we do not mess up the translation by adding two
2857 * /'s in a row. This happens under windows when the document
2858 * root ends with a /
2860 if ((conf->ap_document_root[strlen(conf->ap_document_root)-1] == '/')
2861 && (*(r->uri) == '/')) {
2862 r->filename = apr_pstrcat(r->pool, conf->ap_document_root, r->uri+1,
2866 r->filename = apr_pstrcat(r->pool, conf->ap_document_root, r->uri,
2874 static int do_nothing(request_rec *r) { return OK; }
2876 static int default_handler(request_rec *r)
2878 ap_bucket_brigade *bb;
2880 core_dir_config *d =
2881 (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
2883 apr_file_t *fd = NULL;
2884 apr_status_t status;
2885 /* XXX if/when somebody writes a content-md5 filter we either need to
2886 * remove this support or coordinate when to use the filter vs.
2887 * when to use this code
2888 * The current choice of when to compute the md5 here matches the 1.3
2889 * support fairly closely (unlike 1.3, we don't handle computing md5
2890 * when the charset is translated).
2892 int bld_content_md5 =
2893 (d->content_md5 & 1) && r->output_filters->frec->ftype != AP_FTYPE_CONTENT;
2895 ap_allow_methods(r, MERGE_ALLOW, "GET", "OPTIONS", "POST", NULL);
2897 if ((errstatus = ap_discard_request_body(r)) != OK) {
2901 if (r->method_number == M_INVALID) {
2902 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2903 "Invalid method in request %s", r->the_request);
2904 return HTTP_NOT_IMPLEMENTED;
2906 if (r->method_number == M_OPTIONS) {
2907 return ap_send_http_options(r);
2909 if (r->method_number == M_PUT) {
2910 return HTTP_METHOD_NOT_ALLOWED;
2912 if (r->finfo.protection == 0 || (r->path_info && *r->path_info)) {
2913 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r,
2914 "File does not exist: %s",r->path_info ?
2915 apr_pstrcat(r->pool, r->filename, r->path_info, NULL)
2917 return HTTP_NOT_FOUND;
2920 if (r->method_number != M_GET && r->method_number != M_POST) {
2921 return HTTP_METHOD_NOT_ALLOWED;
2924 if ((status = apr_open(&fd, r->filename, APR_READ | APR_BINARY, 0, r->connection->pool)) != APR_SUCCESS) {
2925 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r,
2926 "file permissions deny server access: %s", r->filename);
2927 return HTTP_FORBIDDEN;
2929 ap_update_mtime(r, r->finfo.mtime);
2930 ap_set_last_modified(r);
2932 apr_table_setn(r->headers_out, "Accept-Ranges", "bytes");
2933 ap_set_content_length(r, r->finfo.size);
2934 if ((errstatus = ap_meets_conditions(r)) != OK) {
2939 if (bld_content_md5) {
2940 apr_table_setn(r->headers_out, "Content-MD5",
2941 ap_md5digest(r->pool, fd));
2944 bb = ap_brigade_create(r->pool);
2945 e = ap_bucket_create_file(fd, 0, r->finfo.size);
2947 AP_BRIGADE_INSERT_HEAD(bb, e);
2948 e = ap_bucket_create_eos();
2949 AP_BRIGADE_INSERT_TAIL(bb, e);
2951 return ap_pass_brigade(r->output_filters, bb);
2956 * This is a simple filter to coalesce many small buckets into one large
2960 * This implementation of coalesce_filter will only coalesce a single
2961 * contiguous string of coalesable buckets. It will not coalesce multiple
2962 * non-contiguous buckets. For example, if a brigade contains 10 small
2963 * buckets followed by a large bucket (or a pipe or file bucket) followed
2964 * by more small buckets, only the first 10 buckets will be coalesced.
2966 typedef struct COALESCE_FILTER_CTX {
2967 char *buf; /* Start of buffer */
2968 char *cur; /* Pointer to next location to write */
2969 apr_size_t cnt; /* Number of bytes put in buf */
2970 apr_size_t avail; /* Number of bytes available in the buf */
2971 } coalesce_filter_ctx_t;
2972 #define MIN_BUCKET_SIZE 200
2973 static apr_status_t coalesce_filter(ap_filter_t *f, ap_bucket_brigade *b)
2976 apr_pool_t *p = f->r->pool;
2977 ap_bucket *e, *insert_before = NULL, *destroy_me = NULL;
2978 coalesce_filter_ctx_t *ctx = f->ctx;
2979 int pass_the_brigade = 0, insert_first = 0;
2982 f->ctx = ctx = apr_pcalloc(p, sizeof(coalesce_filter_ctx_t));
2983 ctx->avail = MIN_BYTES_TO_WRITE;
2990 /* Iterate across the buckets, coalescing the small buckets into a
2993 AP_BRIGADE_FOREACH(e, b) {
2995 ap_bucket_destroy(destroy_me);
2998 if (AP_BUCKET_IS_EOS(e) || AP_BUCKET_IS_FILE(e) ||
2999 AP_BUCKET_IS_PIPE(e) || AP_BUCKET_IS_FLUSH(e)) {
3000 pass_the_brigade = 1;
3005 rv = ap_bucket_read(e, &str, &n, AP_BLOCK_READ);
3006 if (rv != APR_SUCCESS) {
3007 /* XXX: log error */
3010 if ((n < MIN_BUCKET_SIZE) && (n < ctx->avail)) {
3011 /* Coalesce this bucket into the buffer */
3012 if (ctx->buf == NULL) {
3013 ctx->buf = apr_palloc(p, MIN_BYTES_TO_WRITE);
3014 ctx->cur = ctx->buf;
3017 memcpy(ctx->cur, str, n);
3021 /* If this is the first bucket to be coalesced, don't remove it
3022 * from the brigade. Save it as a marker for where to insert
3023 * ctx->buf into the brigade when we're done.
3025 if (insert_before || insert_first){
3026 AP_BUCKET_REMOVE(e);
3033 else if (insert_before || insert_first) {
3034 /* This bucket was not able to be coalesced because it either
3035 * exceeds MIN_BUCKET_SIZE or its contents will not fit into
3036 * buf. We're done...
3038 pass_the_brigade = 1;
3042 /* If there is even a single bucket that cannot be coalesced,
3043 * then we must pass the brigade down to the next filter.
3045 pass_the_brigade = 1;
3051 ap_bucket_destroy(destroy_me);
3055 if (pass_the_brigade) {
3056 /* Insert ctx->buf into the correct spot in the brigade */
3057 e = ap_bucket_create_pool(ctx->buf, ctx->cnt, p);
3059 AP_BRIGADE_INSERT_HEAD(b, e);
3061 else if (insert_before) {
3062 AP_BUCKET_INSERT_BEFORE(e, insert_before);
3063 AP_BUCKET_REMOVE(insert_before);
3064 ap_bucket_destroy(insert_before);
3065 insert_before = NULL;
3067 rv = ap_pass_brigade(f->next, b);
3068 if (rv != APR_SUCCESS) {
3069 /* XXX: Log the error */
3072 /* Get ctx->buf ready for the next brigade */
3074 ctx->cur = ctx->buf;
3076 ctx->avail = MIN_BYTES_TO_WRITE;
3080 if (insert_before) {
3081 AP_BUCKET_REMOVE(insert_before);
3082 ap_bucket_destroy(insert_before);
3084 /* The brigade should be empty now because all the buckets
3085 * were coalesced into the coalesce_filter buf
3092 * HTTP/1.1 chunked transfer encoding filter.
3094 static apr_status_t chunk_filter(ap_filter_t *f, ap_bucket_brigade *b)
3096 #define ASCII_CRLF "\015\012"
3097 #define ASCII_ZERO "\060"
3098 ap_bucket_brigade *more = NULL;
3102 for (more = NULL; b; b = more, more = NULL) {
3103 apr_off_t bytes = 0;
3104 ap_bucket *eos = NULL;
3105 char chunk_hdr[20]; /* enough space for the snprintf below */
3107 AP_BRIGADE_FOREACH(e, b) {
3108 if (AP_BUCKET_IS_EOS(e)) {
3109 /* there shouldn't be anything after the eos */
3113 else if (e->length == -1) {
3114 /* unknown amount of data (e.g. a pipe) */
3118 rv = ap_bucket_read(e, &data, &len, AP_BLOCK_READ);
3119 if (rv != APR_SUCCESS) {
3124 * There may be a new next bucket representing the
3125 * rest of the data stream on which a read() may
3126 * block so we pass down what we have so far.
3129 more = ap_brigade_split(b, AP_BUCKET_NEXT(e));
3133 /* If there was nothing in this bucket then we can
3134 * safely move on to the next one without pausing
3135 * to pass down what we have counted up so far.
3146 * XXX: if there aren't very many bytes at this point it may
3147 * be a good idea to set them aside and return for more,
3148 * unless we haven't finished counting this brigade yet.
3151 /* if there are content bytes, then wrap them in a chunk */
3156 * Insert the chunk header, specifying the number of bytes in
3159 /* XXX might be nice to have APR_OFF_T_FMT_HEX */
3160 hdr_len = apr_snprintf(chunk_hdr, sizeof(chunk_hdr),
3161 "%qx" CRLF, (apr_uint64_t)bytes);
3162 ap_xlate_proto_to_ascii(chunk_hdr, hdr_len);
3163 e = ap_bucket_create_transient(chunk_hdr, hdr_len);
3164 AP_BRIGADE_INSERT_HEAD(b, e);
3167 * Insert the end-of-chunk CRLF before the EOS bucket, or
3168 * appended to the brigade
3170 e = ap_bucket_create_immortal(ASCII_CRLF, 2);
3172 AP_BUCKET_INSERT_BEFORE(eos, e);
3175 AP_BRIGADE_INSERT_TAIL(b, e);
3179 /* RFC 2616, Section 3.6.1
3181 * If there is an EOS bucket, then prefix it with:
3182 * 1) the last-chunk marker ("0" CRLF)
3184 * 3) the end-of-chunked body CRLF
3186 * If there is no EOS bucket, then do nothing.
3188 * XXX: it would be nice to combine this with the end-of-chunk
3189 * marker above, but this is a bit more straight-forward for
3193 /* XXX: (2) trailers ... does not yet exist */
3194 e = ap_bucket_create_immortal(ASCII_ZERO ASCII_CRLF /* <trailers> */ ASCII_CRLF, 5);
3195 AP_BUCKET_INSERT_BEFORE(eos, e);
3198 /* pass the brigade to the next filter. */
3199 rv = ap_pass_brigade(f->next, b);
3200 if (rv != APR_SUCCESS || eos != NULL) {
3208 static int core_input_filter(ap_filter_t *f, ap_bucket_brigade *b, ap_input_mode_t mode)
3212 if (!f->ctx) { /* If we haven't passed up the socket yet... */
3214 e = ap_bucket_create_socket(f->c->client_socket);
3215 AP_BRIGADE_INSERT_TAIL(b, e);
3219 /* Either some code lost track of the socket
3220 * bucket or we already found out that the
3227 /* Default filter. This filter should almost always be used. Its only job
3228 * is to send the headers if they haven't already been sent, and then send
3231 typedef struct CORE_OUTPUT_FILTER_CTX {
3232 ap_bucket_brigade *b;
3233 } core_output_filter_ctx_t;
3234 #define MAX_IOVEC_TO_WRITE 16
3235 static apr_status_t core_output_filter(ap_filter_t *f, ap_bucket_brigade *b)
3238 ap_bucket_brigade *more = NULL;
3239 apr_size_t bytes_sent = 0, nbytes;
3242 core_output_filter_ctx_t *ctx = f->ctx;
3244 apr_size_t nvec = 0;
3245 apr_size_t nvec_trailers= 0;
3246 struct iovec vec[MAX_IOVEC_TO_WRITE];
3247 struct iovec vec_trailers[MAX_IOVEC_TO_WRITE];
3249 apr_file_t *fd = NULL;
3250 apr_size_t flen = 0;
3251 apr_off_t foffset = 0;
3254 f->ctx = ctx = apr_pcalloc(c->pool, sizeof(core_output_filter_ctx_t));
3256 /* If we have a saved brigade, concatenate the new brigade to it */
3258 AP_BRIGADE_CONCAT(ctx->b, b);
3263 /* Iterate over the brigade collecting iovecs */
3265 nbytes = 0; /* in case more points to another brigade */
3267 AP_BRIGADE_FOREACH(e, b) {
3268 if (AP_BUCKET_IS_EOS(e) || AP_BUCKET_IS_FLUSH(e)) {
3271 else if (AP_BUCKET_IS_FILE(e)) {
3272 ap_bucket_file *a = e->data;
3273 /* Assume there is at most one AP_BUCKET_FILE in the brigade */
3276 foffset = a->offset;
3281 rv = ap_bucket_read(e, &str, &n, AP_BLOCK_READ);
3285 vec[nvec].iov_base = (char*) str;
3286 vec[nvec].iov_len = n;
3290 /* The bucket is a trailer to a file bucket */
3291 vec_trailers[nvec_trailers].iov_base = (char*) str;
3292 vec_trailers[nvec_trailers].iov_len = n;
3298 if ((nvec == MAX_IOVEC_TO_WRITE) || (nvec_trailers == MAX_IOVEC_TO_WRITE)) {
3299 /* Split the brigade and break */
3300 if (AP_BUCKET_NEXT(e) != AP_BRIGADE_SENTINEL(b)) {
3301 more = ap_brigade_split(b, AP_BUCKET_NEXT(e));
3307 /* Completed iterating over the brigades, now determine if we want to
3308 * buffer the brigade or send the brigade out on the network
3310 if ((!fd && (!more) && (nbytes < MIN_BYTES_TO_WRITE) && !AP_BUCKET_IS_FLUSH(e))
3311 || (AP_BUCKET_IS_EOS(e) && c->keepalive)) {
3313 /* NEVER save an EOS in here. If we are saving a brigade with an
3314 * EOS bucket, then we are doing keepalive connections, and we want
3315 * to process to second request fully.
3317 if (AP_BUCKET_IS_EOS(e)) {
3318 AP_BUCKET_REMOVE(e);
3319 ap_bucket_destroy(e);
3321 ap_save_brigade(f, &ctx->b, &b);
3326 #if APR_HAS_SENDFILE
3327 apr_int32_t flags = 0;
3330 memset(&hdtr, '\0', sizeof(hdtr));
3332 hdtr.numheaders = nvec;
3335 if (nvec_trailers) {
3336 hdtr.numtrailers = nvec_trailers;
3337 hdtr.trailers = vec_trailers;
3339 #if APR_HAS_SENDFILE
3340 if (!c->keepalive) {
3341 /* Prepare the socket to be reused */
3342 flags |= APR_SENDFILE_DISCONNECT_SOCKET;
3345 rv = apr_sendfile(c->client_socket,
3346 fd, /* The file to send */
3347 &hdtr, /* Header and trailer iovecs */
3348 &foffset, /* Offset in file to begin sending from */
3351 bytes_sent = nbytes;
3353 /* If apr_sendfile() returns APR_ENOTIMPL, call send_the_file() to
3354 * loop on apr_read/apr_send to send the file. Our Windows binary
3355 * distributions (which work on Windows 9x/NT) are compiled on
3356 * Windows NT. TransmitFile is not available on Windows 95/98 and
3357 * we discover this at runtime when apr_sendfile() returns
3358 * APR_ENOTIMPL. Having apr_sendfile() return APR_ENOTIMPL seems
3359 * the cleanest way to handle this case.
3361 if (rv == APR_ENOTIMPL) {
3364 rv = send_the_file(c, fd, &hdtr, foffset, flen, &bytes_sent);
3366 #if APR_HAS_SENDFILE
3371 rv = writev_it_all(c->client_socket,
3373 nbytes, &bytes_sent);
3376 ap_brigade_destroy(b);
3377 if (rv != APR_SUCCESS) {
3378 /* XXX: log the error */
3380 ap_brigade_destroy(more);
3387 } /* end while () */
3392 static const handler_rec core_handlers[] = {
3393 { "*/*", default_handler },
3394 { "default-handler", default_handler },
3398 static void core_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
3400 ap_init_bucket_types(pconf);
3403 static void core_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
3405 ap_set_version(pconf);
3408 static void core_open_logs(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
3410 ap_open_logs(s, pconf);
3413 static const char *core_method(const request_rec *r)
3416 static unsigned short core_port(const request_rec *r)
3417 { return DEFAULT_HTTP_PORT; }
3419 static void core_insert_filter(request_rec *r)
3422 core_dir_config *conf = (core_dir_config *)
3423 ap_get_module_config(r->per_dir_config,
3425 char **items = (char **)conf->output_filters->elts;
3427 for (i = 0; i < conf->output_filters->nelts; i++) {
3428 char *foobar = items[i];
3429 ap_add_output_filter(foobar, NULL, r, r->connection);
3432 items = (char **)conf->input_filters->elts;
3433 for (i = 0; i < conf->input_filters->nelts; i++) {
3434 char *foobar = items[i];
3435 ap_add_input_filter(foobar, NULL, r, r->connection);
3439 static void register_hooks(void)
3441 ap_hook_pre_config(core_pre_config, NULL, NULL, AP_HOOK_REALLY_FIRST);
3442 ap_hook_post_config(core_post_config,NULL,NULL,AP_HOOK_REALLY_FIRST);
3443 ap_hook_translate_name(ap_core_translate,NULL,NULL,AP_HOOK_REALLY_LAST);
3444 ap_hook_pre_connection(ap_pre_http_connection,NULL,NULL,
3445 AP_HOOK_REALLY_LAST);
3446 ap_hook_process_connection(ap_process_http_connection,NULL,NULL,
3447 AP_HOOK_REALLY_LAST);
3448 ap_hook_http_method(core_method,NULL,NULL,AP_HOOK_REALLY_LAST);
3449 ap_hook_default_port(core_port,NULL,NULL,AP_HOOK_REALLY_LAST);
3450 ap_hook_open_logs(core_open_logs,NULL,NULL,AP_HOOK_MIDDLE);
3451 /* FIXME: I suspect we can eliminate the need for these - Ben */
3452 ap_hook_type_checker(do_nothing,NULL,NULL,AP_HOOK_REALLY_LAST);
3453 ap_hook_access_checker(do_nothing,NULL,NULL,AP_HOOK_REALLY_LAST);
3455 /* register the core's insert_filter hook and register core-provided
3458 ap_hook_insert_filter(core_insert_filter, NULL, NULL, AP_HOOK_MIDDLE);
3460 ap_register_input_filter("HTTP_IN", ap_http_filter, AP_FTYPE_CONNECTION);
3461 ap_register_input_filter("DECHUNK", ap_dechunk_filter, AP_FTYPE_TRANSCODE);
3462 ap_register_input_filter("CORE_IN", core_input_filter, AP_FTYPE_NETWORK);
3463 ap_register_output_filter("HTTP_HEADER", ap_http_header_filter,
3464 AP_FTYPE_HTTP_HEADER);
3465 ap_register_output_filter("CONTENT_LENGTH", ap_content_length_filter,
3466 AP_FTYPE_HTTP_HEADER);
3467 ap_register_output_filter("BYTERANGE", ap_byterange_filter,
3468 AP_FTYPE_HTTP_HEADER);
3469 ap_register_output_filter("CORE", core_output_filter, AP_FTYPE_NETWORK);
3470 ap_register_output_filter("SUBREQ_CORE", ap_sub_req_output_filter,
3472 ap_register_output_filter("CHUNK", chunk_filter, AP_FTYPE_TRANSCODE);
3473 ap_register_output_filter("COALESCE", coalesce_filter, AP_FTYPE_CONTENT);
3476 AP_DECLARE_DATA module core_module = {
3477 STANDARD20_MODULE_STUFF,
3478 create_core_dir_config, /* create per-directory config structure */
3479 merge_core_dir_configs, /* merge per-directory config structures */
3480 create_core_server_config, /* create per-server config structure */
3481 merge_core_server_configs, /* merge per-server config structures */
3482 core_cmds, /* command apr_table_t */
3483 core_handlers, /* handlers */
3484 register_hooks /* register hooks */