1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000-2001 The Apache Software Foundation. All rights
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
19 * 3. The end-user documentation included with the redistribution,
20 * if any, must include the following acknowledgment:
21 * "This product includes software developed by the
22 * Apache Software Foundation (http://www.apache.org/)."
23 * Alternately, this acknowledgment may appear in the software itself,
24 * if and wherever such third-party acknowledgments normally appear.
26 * 4. The names "Apache" and "Apache Software Foundation" must
27 * not be used to endorse or promote products derived from this
28 * software without prior written permission. For written
29 * permission, please contact apache@apache.org.
31 * 5. Products derived from this software may not be called "Apache",
32 * nor may "Apache" appear in their name, without prior written
33 * permission of the Apache Software Foundation.
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation. For more
51 * information on the Apache Software Foundation, please see
52 * <http://www.apache.org/>.
54 * Portions of this software are based upon public domain software
55 * originally written at the National Center for Supercomputing Applications,
56 * University of Illinois, Urbana-Champaign.
60 #include "apr_strings.h"
62 #include "apr_fnmatch.h"
63 #include "apr_thread_proc.h" /* for RLIMIT stuff */
65 #define APR_WANT_IOVEC
66 #define APR_WANT_STRFUNC
67 #define APR_WANT_MEMFUNC
71 #include "ap_config.h"
73 #include "http_config.h"
74 #include "http_core.h"
75 #include "http_protocol.h" /* For index_of_response(). Grump. */
76 #include "http_request.h"
77 #include "http_vhost.h"
78 #include "http_main.h" /* For the default_handler below... */
82 #include "http_connection.h"
83 #include "apr_buckets.h"
84 #include "util_filter.h"
85 #include "util_ebcdic.h"
91 /* LimitXMLRequestBody handling */
92 #define AP_LIMIT_UNSET ((long) -1)
93 #define AP_DEFAULT_LIMIT_XML_BODY ((size_t)1000000)
95 #define AP_MIN_SENDFILE_BYTES (256)
97 /* Server core module... This module provides support for really basic
98 * server operations, including options and commands which control the
99 * operation of other modules. Consider this the bureaucracy module.
101 * The core module also defines handlers, etc., do handle just enough
102 * to allow a server with the core module ONLY to actually serve documents
103 * (though it slaps DefaultType on all of 'em); this was useful in testing,
104 * but may not be worth preserving.
106 * This file could almost be mod_core.c, except for the stuff which affects
107 * the http_conf_globals.
110 static void *create_core_dir_config(apr_pool_t *a, char *dir)
112 core_dir_config *conf;
114 conf = (core_dir_config *)apr_pcalloc(a, sizeof(core_dir_config));
115 if (!dir || dir[strlen(dir) - 1] == '/') {
118 else if (strncmp(dir, "proxy:", 6) == 0) {
119 conf->d = apr_pstrdup(a, dir);
122 conf->d = apr_pstrcat(a, dir, "/", NULL);
124 conf->d_is_fnmatch = conf->d ? (apr_is_fnmatch(conf->d) != 0) : 0;
125 conf->d_components = conf->d ? ap_count_dirs(conf->d) : 0;
127 conf->opts = dir ? OPT_UNSET : OPT_UNSET|OPT_ALL;
128 conf->opts_add = conf->opts_remove = OPT_NONE;
129 conf->override = dir ? OR_UNSET : OR_UNSET|OR_ALL;
131 conf->content_md5 = 2;
133 conf->use_canonical_name = USE_CANONICAL_NAME_UNSET;
135 conf->hostname_lookups = HOSTNAME_LOOKUP_UNSET;
136 conf->do_rfc1413 = DEFAULT_RFC1413 | 2; /* set bit 1 to indicate default */
137 conf->satisfy = SATISFY_NOSPEC;
140 conf->limit_cpu = NULL;
142 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
143 conf->limit_mem = NULL;
146 conf->limit_nproc = NULL;
149 conf->limit_req_body = 0;
150 conf->limit_xml_body = AP_LIMIT_UNSET;
151 conf->sec = apr_array_make(a, 2, sizeof(ap_conf_vector_t *));
153 conf->script_interpreter_source = INTERPRETER_SOURCE_UNSET;
156 conf->server_signature = srv_sig_unset;
158 conf->add_default_charset = ADD_DEFAULT_CHARSET_UNSET;
159 conf->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
161 conf->output_filters = apr_array_make(a, 2, sizeof(void *));
162 conf->input_filters = apr_array_make(a, 2, sizeof(void *));
166 static void *merge_core_dir_configs(apr_pool_t *a, void *basev, void *newv)
168 core_dir_config *base = (core_dir_config *)basev;
169 core_dir_config *new = (core_dir_config *)newv;
170 core_dir_config *conf;
173 conf = (core_dir_config *)apr_palloc(a, sizeof(core_dir_config));
174 memcpy((char *)conf, (const char *)base, sizeof(core_dir_config));
175 if (base->response_code_strings) {
176 conf->response_code_strings =
177 apr_palloc(a, sizeof(*conf->response_code_strings)
179 memcpy(conf->response_code_strings, base->response_code_strings,
180 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
184 conf->d_is_fnmatch = new->d_is_fnmatch;
185 conf->d_components = new->d_components;
188 if (new->opts & OPT_UNSET) {
189 /* there was no explicit setting of new->opts, so we merge
190 * preserve the invariant (opts_add & opts_remove) == 0
192 conf->opts_add = (conf->opts_add & ~new->opts_remove) | new->opts_add;
193 conf->opts_remove = (conf->opts_remove & ~new->opts_add)
195 conf->opts = (conf->opts & ~conf->opts_remove) | conf->opts_add;
196 if ((base->opts & OPT_INCNOEXEC) && (new->opts & OPT_INCLUDES)) {
197 conf->opts = (conf->opts & ~OPT_INCNOEXEC) | OPT_INCLUDES;
201 /* otherwise we just copy, because an explicit opts setting
202 * overrides all earlier +/- modifiers
204 conf->opts = new->opts;
205 conf->opts_add = new->opts_add;
206 conf->opts_remove = new->opts_remove;
209 if (!(new->override & OR_UNSET)) {
210 conf->override = new->override;
212 if (new->ap_default_type) {
213 conf->ap_default_type = new->ap_default_type;
216 if (new->ap_auth_type) {
217 conf->ap_auth_type = new->ap_auth_type;
219 if (new->ap_auth_name) {
220 conf->ap_auth_name = new->ap_auth_name;
222 if (new->ap_requires) {
223 conf->ap_requires = new->ap_requires;
226 if (new->response_code_strings) {
227 if (conf->response_code_strings == NULL) {
228 conf->response_code_strings = apr_palloc(a,
229 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
230 memcpy(conf->response_code_strings, new->response_code_strings,
231 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
234 for (i = 0; i < RESPONSE_CODES; ++i) {
235 if (new->response_code_strings[i] != NULL) {
236 conf->response_code_strings[i]
237 = new->response_code_strings[i];
242 if (new->hostname_lookups != HOSTNAME_LOOKUP_UNSET) {
243 conf->hostname_lookups = new->hostname_lookups;
245 if ((new->do_rfc1413 & 2) == 0) {
246 conf->do_rfc1413 = new->do_rfc1413;
248 if ((new->content_md5 & 2) == 0) {
249 conf->content_md5 = new->content_md5;
251 if (new->use_canonical_name != USE_CANONICAL_NAME_UNSET) {
252 conf->use_canonical_name = new->use_canonical_name;
256 if (new->limit_cpu) {
257 conf->limit_cpu = new->limit_cpu;
260 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
261 if (new->limit_mem) {
262 conf->limit_mem = new->limit_mem;
266 if (new->limit_nproc) {
267 conf->limit_nproc = new->limit_nproc;
271 if (new->limit_req_body) {
272 conf->limit_req_body = new->limit_req_body;
275 if (new->limit_xml_body != AP_LIMIT_UNSET)
276 conf->limit_xml_body = new->limit_xml_body;
278 conf->limit_xml_body = base->limit_xml_body;
280 conf->sec = apr_array_append(a, base->sec, new->sec);
282 if (new->satisfy != SATISFY_NOSPEC) {
283 conf->satisfy = new->satisfy;
287 if (new->script_interpreter_source != INTERPRETER_SOURCE_UNSET) {
288 conf->script_interpreter_source = new->script_interpreter_source;
292 if (new->server_signature != srv_sig_unset) {
293 conf->server_signature = new->server_signature;
296 if (new->add_default_charset != ADD_DEFAULT_CHARSET_UNSET) {
297 conf->add_default_charset = new->add_default_charset;
298 if (new->add_default_charset_name) {
299 conf->add_default_charset_name = new->add_default_charset_name;
302 conf->output_filters = apr_array_append(a, base->output_filters,
303 new->output_filters);
304 conf->input_filters = apr_array_append(a, base->input_filters,
310 static void *create_core_server_config(apr_pool_t *a, server_rec *s)
312 core_server_config *conf;
313 int is_virtual = s->is_virtual;
315 conf = (core_server_config *)apr_pcalloc(a, sizeof(core_server_config));
317 conf->gprof_dir = NULL;
319 conf->access_name = is_virtual ? NULL : DEFAULT_ACCESS_FNAME;
320 conf->ap_document_root = is_virtual ? NULL : DOCUMENT_LOCATION;
321 conf->sec = apr_array_make(a, 40, sizeof(ap_conf_vector_t *));
322 conf->sec_url = apr_array_make(a, 40, sizeof(ap_conf_vector_t *));
327 static void *merge_core_server_configs(apr_pool_t *p, void *basev, void *virtv)
329 core_server_config *base = (core_server_config *)basev;
330 core_server_config *virt = (core_server_config *)virtv;
331 core_server_config *conf;
333 conf = (core_server_config *)apr_pcalloc(p, sizeof(core_server_config));
335 if (!conf->access_name) {
336 conf->access_name = base->access_name;
338 if (!conf->ap_document_root) {
339 conf->ap_document_root = base->ap_document_root;
341 conf->sec = apr_array_append(p, base->sec, virt->sec);
342 conf->sec_url = apr_array_append(p, base->sec_url, virt->sec_url);
347 /* Add per-directory configuration entry (for <directory> section);
348 * these are part of the core server config.
351 AP_CORE_DECLARE(void) ap_add_per_dir_conf(server_rec *s, void *dir_config)
353 core_server_config *sconf = ap_get_module_config(s->module_config,
355 void **new_space = (void **)apr_array_push(sconf->sec);
357 *new_space = dir_config;
360 AP_CORE_DECLARE(void) ap_add_per_url_conf(server_rec *s, void *url_config)
362 core_server_config *sconf = ap_get_module_config(s->module_config,
364 void **new_space = (void **)apr_array_push(sconf->sec_url);
366 *new_space = url_config;
369 AP_CORE_DECLARE(void) ap_add_file_conf(core_dir_config *conf, void *url_config)
371 void **new_space = (void **)apr_array_push(conf->sec);
373 *new_space = url_config;
376 /* core_reorder_directories reorders the directory sections such that the
377 * 1-component sections come first, then the 2-component, and so on, finally
378 * followed by the "special" sections. A section is "special" if it's a regex,
379 * or if it doesn't start with / -- consider proxy: matching. All movements
380 * are in-order to preserve the ordering of the sections from the config files.
381 * See directory_walk().
384 #if defined(HAVE_DRIVE_LETTERS)
385 #define IS_SPECIAL(entry_core) \
386 ((entry_core)->r != NULL \
387 || ((entry_core)->d[0] != '/' && (entry_core)->d[1] != ':'))
388 #elif defined(NETWARE)
389 /* XXX: Fairly certain this is correct... '/' must prefix the path
390 * or else in the case xyz:/ or abc/xyz:/, '/' must follow the ':'.
391 * If there is no leading '/' or embedded ':/', then we are special.
393 #define IS_SPECIAL(entry_core) \
394 ((entry_core)->r != NULL \
395 || ((entry_core)->d[0] != '/' \
396 && strchr((entry_core)->d, ':') \
397 && *(strchr((entry_core)->d, ':') + 1) != '/'))
399 #define IS_SPECIAL(entry_core) \
400 ((entry_core)->r != NULL || (entry_core)->d[0] != '/')
403 /* We need to do a stable sort, qsort isn't stable. So to make it stable
404 * we'll be maintaining the original index into the list, and using it
405 * as the minor key during sorting. The major key is the number of
406 * components (where a "special" section has infinite components).
408 struct reorder_sort_rec {
409 ap_conf_vector_t *elt;
413 static int reorder_sorter(const void *va, const void *vb)
415 const struct reorder_sort_rec *a = va;
416 const struct reorder_sort_rec *b = vb;
417 core_dir_config *core_a;
418 core_dir_config *core_b;
420 core_a = ap_get_module_config(a->elt, &core_module);
421 core_b = ap_get_module_config(b->elt, &core_module);
422 if (IS_SPECIAL(core_a)) {
423 if (!IS_SPECIAL(core_b)) {
427 else if (IS_SPECIAL(core_b)) {
431 /* we know they're both not special */
432 if (core_a->d_components < core_b->d_components) {
435 else if (core_a->d_components > core_b->d_components) {
439 /* Either they're both special, or they're both not special and have the
440 * same number of components. In any event, we now have to compare
442 return a->orig_index - b->orig_index;
445 void ap_core_reorder_directories(apr_pool_t *p, server_rec *s)
447 core_server_config *sconf;
448 apr_array_header_t *sec;
449 struct reorder_sort_rec *sortbin;
451 ap_conf_vector_t **elts;
455 sconf = ap_get_module_config(s->module_config, &core_module);
458 elts = (ap_conf_vector_t **)sec->elts;
460 /* we have to allocate tmp space to do a stable sort */
461 apr_pool_create(&tmp, p);
462 sortbin = apr_palloc(tmp, sec->nelts * sizeof(*sortbin));
463 for (i = 0; i < nelts; ++i) {
464 sortbin[i].orig_index = i;
465 sortbin[i].elt = elts[i];
468 qsort(sortbin, nelts, sizeof(*sortbin), reorder_sorter);
470 /* and now copy back to the original array */
471 for (i = 0; i < nelts; ++i) {
472 elts[i] = sortbin[i].elt;
475 apr_pool_destroy(tmp);
478 /*****************************************************************
480 * There are some elements of the core config structures in which
481 * other modules have a legitimate interest (this is ugly, but necessary
482 * to preserve NCSA back-compatibility). So, we have a bunch of accessors
486 AP_DECLARE(int) ap_allow_options(request_rec *r)
488 core_dir_config *conf =
489 (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
494 AP_DECLARE(int) ap_allow_overrides(request_rec *r)
496 core_dir_config *conf;
497 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
500 return conf->override;
503 AP_DECLARE(const char *) ap_auth_type(request_rec *r)
505 core_dir_config *conf;
507 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
509 return conf->ap_auth_type;
512 AP_DECLARE(const char *) ap_auth_name(request_rec *r)
514 core_dir_config *conf;
516 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
518 return conf->ap_auth_name;
521 AP_DECLARE(const char *) ap_default_type(request_rec *r)
523 core_dir_config *conf;
525 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
527 return conf->ap_default_type
528 ? conf->ap_default_type
529 : DEFAULT_CONTENT_TYPE;
532 AP_DECLARE(const char *) ap_document_root(request_rec *r) /* Don't use this! */
534 core_server_config *conf;
536 conf = (core_server_config *)ap_get_module_config(r->server->module_config,
538 return conf->ap_document_root;
541 AP_DECLARE(const apr_array_header_t *) ap_requires(request_rec *r)
543 core_dir_config *conf;
545 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
547 return conf->ap_requires;
550 AP_DECLARE(int) ap_satisfies(request_rec *r)
552 core_dir_config *conf;
554 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
557 return conf->satisfy;
560 /* Should probably just get rid of this... the only code that cares is
561 * part of the core anyway (and in fact, it isn't publicised to other
565 char *ap_response_code_string(request_rec *r, int error_index)
567 core_dir_config *conf;
569 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
572 if (conf->response_code_strings == NULL) {
575 return conf->response_code_strings[error_index];
579 /* Code from Harald Hanche-Olsen <hanche@imf.unit.no> */
580 static apr_inline void do_double_reverse (conn_rec *conn)
585 if (conn->double_reverse) {
589 if (conn->remote_host == NULL || conn->remote_host[0] == '\0') {
590 /* single reverse failed, so don't bother */
591 conn->double_reverse = -1;
594 rv = apr_sockaddr_info_get(&sa, conn->remote_host, APR_UNSPEC, 0, 0, conn->pool);
595 if (rv == APR_SUCCESS) {
597 if (sa->ipaddr_len == conn->remote_addr->ipaddr_len &&
598 !memcmp(sa->ipaddr_ptr, conn->remote_addr->ipaddr_ptr,
600 conn->double_reverse = 1;
606 conn->double_reverse = -1;
609 AP_DECLARE(const char *) ap_get_remote_host(conn_rec *conn, void *dir_config,
612 int hostname_lookups;
614 /* If we haven't checked the host name, and we want to */
617 ((core_dir_config *)ap_get_module_config(dir_config, &core_module))
619 if (hostname_lookups == HOSTNAME_LOOKUP_UNSET) {
620 hostname_lookups = HOSTNAME_LOOKUP_OFF;
625 hostname_lookups = HOSTNAME_LOOKUP_OFF;
628 if (type != REMOTE_NOLOOKUP
629 && conn->remote_host == NULL
630 && (type == REMOTE_DOUBLE_REV
631 || hostname_lookups != HOSTNAME_LOOKUP_OFF)) {
632 apr_sockaddr_t *remote_addr;
634 apr_socket_addr_get(&remote_addr, APR_REMOTE, conn->client_socket);
635 if (apr_getnameinfo(&conn->remote_host, remote_addr, 0) == APR_SUCCESS) {
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 connection 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 apr_sockaddr_t *local_addr;
723 apr_socket_addr_get(&local_addr, APR_LOCAL, conn->client_socket);
724 if (apr_getnameinfo(&conn->local_host, local_addr, 0) != APR_SUCCESS)
725 conn->local_host = apr_pstrdup(conn->pool, r->server->server_hostname);
727 ap_str_tolower(conn->local_host);
730 return conn->local_host;
733 return r->server->server_hostname;
736 AP_DECLARE(apr_port_t) ap_get_server_port(const request_rec *r)
740 (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
742 port = r->server->port ? r->server->port : ap_default_port(r);
744 if (d->use_canonical_name == USE_CANONICAL_NAME_OFF
745 || d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
747 apr_sockaddr_t *localsa;
749 apr_socket_addr_get(&localsa, APR_LOCAL, r->connection->client_socket);
750 apr_sockaddr_port_get(&port, localsa);
757 AP_DECLARE(char *) ap_construct_url(apr_pool_t *p, const char *uri,
760 unsigned port = ap_get_server_port(r);
761 const char *host = ap_get_server_name(r);
763 if (ap_is_default_port(port, r)) {
764 return apr_pstrcat(p, ap_http_method(r), "://", host, uri, NULL);
766 return apr_psprintf(p, "%s://%s:%u%s", ap_http_method(r), host, port, uri);
769 AP_DECLARE(unsigned long) ap_get_limit_req_body(const request_rec *r)
772 (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
774 return d->limit_req_body;
778 static apr_status_t get_win32_registry_default_value(apr_pool_t *p, HKEY hkey,
785 DWORD result = RegOpenKeyEx(hkey, relativepath, 0,
786 KEY_QUERY_VALUE, &hkeyOpen);
788 if (result != ERROR_SUCCESS)
789 return APR_FROM_OS_ERROR(result);
791 /* Read to NULL buffer to determine value size */
792 result = RegQueryValueEx(hkeyOpen, "", 0, &type, NULL, &size);
794 if (result == ERROR_SUCCESS) {
795 if ((size < 2) || (type != REG_SZ && type != REG_EXPAND_SZ)) {
796 result = ERROR_INVALID_PARAMETER;
799 *value = apr_palloc(p, size);
800 /* Read value based on size query above */
801 result = RegQueryValueEx(hkeyOpen, "", 0, &type, *value, &size);
805 /* TODO: This might look fine, but we need to provide some warning
806 * somewhere that some environment variables may -not- be translated,
807 * seeing as we may have chopped the environment table down somewhat.
809 if ((result == ERROR_SUCCESS) && (type == REG_EXPAND_SZ))
812 size = ExpandEnvironmentStrings(tmp, *value, 0);
814 *value = apr_palloc(p, size);
815 size = ExpandEnvironmentStrings(tmp, *value, size);
819 RegCloseKey(hkeyOpen);
820 return APR_FROM_OS_ERROR(result);
823 static char* get_interpreter_from_win32_registry(apr_pool_t *p, const char* ext,
824 char** arguments, int strict)
826 char execcgi_path[] = "SHELL\\EXECCGI\\COMMAND";
827 char execopen_path[] = "SHELL\\OPEN\\COMMAND";
828 char typeName[MAX_PATH];
829 int cmdOfName = FALSE;
841 * Future optimization:
842 * When the registry is successfully searched, store the strings for
843 * interpreter and arguments in an ext hash to speed up subsequent look-ups
846 /* Open the key associated with the script filetype extension */
847 result = RegOpenKeyEx(HKEY_CLASSES_ROOT, ext, 0, KEY_QUERY_VALUE,
850 if (result != ERROR_SUCCESS)
853 /* Retrieve the name of the script filetype extension */
854 size = sizeof(typeName);
855 result = RegQueryValueEx(hkeyType, "", NULL, &type, typeName, &size);
857 if (result == ERROR_SUCCESS && type == REG_SZ && typeName[0]) {
858 /* Open the key associated with the script filetype extension */
859 result = RegOpenKeyEx(HKEY_CLASSES_ROOT, typeName, 0,
860 KEY_QUERY_VALUE, &hkeyName);
862 if (result == ERROR_SUCCESS)
866 /* Open the key for the script command path by:
868 * 1) the 'named' filetype key for ExecCGI/Command
869 * 2) the extension's type key for ExecCGI/Command
871 * and if the strict arg is false, then continue trying:
873 * 3) the 'named' filetype key for Open/Command
874 * 4) the extension's type key for Open/Command
878 result = get_win32_registry_default_value(p, hkeyName,
879 execcgi_path, &buffer);
882 if (!cmdOfName || (result != ERROR_SUCCESS)) {
883 result = get_win32_registry_default_value(p, hkeyType,
884 execcgi_path, &buffer);
887 if (!strict && cmdOfName && (result != ERROR_SUCCESS)) {
888 result = get_win32_registry_default_value(p, hkeyName,
889 execopen_path, &buffer);
892 if (!strict && (result != ERROR_SUCCESS)) {
893 result = get_win32_registry_default_value(p, hkeyType,
894 execopen_path, &buffer);
898 RegCloseKey(hkeyName);
900 RegCloseKey(hkeyType);
902 if (result != ERROR_SUCCESS)
906 * The canonical way shell command entries are entered in the Win32
907 * registry is as follows:
908 * shell [options] "%1" [args]
910 * shell - full path name to interpreter or shell to run.
911 * E.g., c:\usr\local\ntreskit\perl\bin\perl.exe
912 * options - optional switches
914 * "%1" - Place holder for file to run the shell against.
916 * options - additional arguments
919 * If we find a %1 or a quoted %1, lop off the remainder to arguments.
921 if (buffer && *buffer) {
922 if ((s = strstr(buffer, "\"%1")))
927 else if ((s = strstr(buffer, "%1")))
930 *arguments = buffer + 2;
933 *arguments = strchr(buffer, '\0');
934 while (**arguments && isspace(**arguments))
941 AP_DECLARE (file_type_e) ap_get_win32_interpreter(const request_rec *r,
951 file_type_e fileType = eFileTypeUNKNOWN;
953 char *exename = NULL;
955 d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
958 /* Find the file extension */
959 exename = strrchr(r->filename, '/');
961 exename = strrchr(r->filename, '\\');
964 exename = r->filename;
969 ext = strrchr(exename, '.');
971 if (ext && (!strcasecmp(ext,".bat") || !strcasecmp(ext,".cmd")))
973 char *comspec = getenv("COMSPEC");
975 *interpreter = apr_pstrcat(r->pool, "\"", comspec, "\" /c ", NULL);
976 return eFileTypeSCRIPT;
978 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r->server,
979 "Failed to start a '%s' file as a script." APR_EOL_STR
980 "\tCOMSPEC variable is missing from the environment.", ext);
981 return eFileTypeUNKNOWN;
984 /* If the file has an extension and it is not .com and not .exe and
985 * we've been instructed to search the registry, then do it!
987 if (ext && strcasecmp(ext,".exe") && strcasecmp(ext,".com") &&
988 (d->script_interpreter_source == INTERPRETER_SOURCE_REGISTRY ||
989 d->script_interpreter_source == INTERPRETER_SOURCE_REGISTRY_STRICT)) {
990 /* Check the registry */
991 int strict = (d->script_interpreter_source
992 == INTERPRETER_SOURCE_REGISTRY_STRICT);
993 *interpreter = get_interpreter_from_win32_registry(r->pool, ext,
996 return eFileTypeSCRIPT;
997 else if (d->script_interpreter_source == INTERPRETER_SOURCE_REGISTRY_STRICT) {
998 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r->server,
999 "ScriptInterpreterSource config directive set to \"registry-strict\"." APR_EOL_STR
1000 "\tInterpreter not found for files of type '%s'.", ext);
1001 return eFileTypeUNKNOWN;
1005 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r->server,
1006 "ScriptInterpreterSource config directive set to \"registry\"." APR_EOL_STR
1007 "\tInterpreter not found for files of type '%s', "
1008 "trying \"script\" method...", ext);
1012 /* Need to peek into the file figure out what it really is... */
1013 /* This is wrong for Unicode FS ... should move to APR */
1014 hFile = CreateFile(r->filename, GENERIC_READ, FILE_SHARE_READ, NULL,
1015 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1016 if (hFile == INVALID_HANDLE_VALUE) {
1017 return eFileTypeUNKNOWN;
1019 bResult = ReadFile(hFile, (void*) &buffer, sizeof(buffer) - 1,
1021 if (!bResult || (nBytesRead == 0)) {
1022 ap_log_rerror(APLOG_MARK, APLOG_ERR, GetLastError(), r,
1023 "ReadFile(%s) failed", r->filename);
1025 return eFileTypeUNKNOWN;
1028 buffer[nBytesRead] = '\0';
1030 /* Script or executable, that is the question... */
1031 if ((buffer[0] == '#') && (buffer[1] == '!')) {
1032 /* Assuming file is a script since it starts with a shebang */
1033 fileType = eFileTypeSCRIPT;
1034 for (i = 2; i < sizeof(buffer); i++) {
1035 if ((buffer[i] == '\r')
1036 || (buffer[i] == '\n')) {
1041 for (i = 2; buffer[i] == ' ' ; ++i)
1043 *interpreter = apr_pstrdup(r->pool, buffer + i );
1046 /* Not a script, is it an executable? */
1047 IMAGE_DOS_HEADER *hdr = (IMAGE_DOS_HEADER*)buffer;
1048 if ((nBytesRead >= sizeof(IMAGE_DOS_HEADER)) && (hdr->e_magic == IMAGE_DOS_SIGNATURE)) {
1049 if (hdr->e_lfarlc < 0x40)
1050 fileType = eFileTypeEXE16;
1052 fileType = eFileTypeEXE32;
1055 fileType = eFileTypeUNKNOWN;
1062 /*****************************************************************
1064 * Commands... this module handles almost all of the NCSA httpd.conf
1065 * commands, but most of the old srm.conf is in the the modules.
1069 /* returns a parent if it matches the given directive */
1070 static const ap_directive_t * find_parent(const ap_directive_t *dirp,
1073 while (dirp->parent != NULL) {
1074 dirp = dirp->parent;
1075 /* ### it would be nice to have atom-ized directives */
1076 if (strcasecmp(dirp->directive, what) == 0)
1082 AP_DECLARE(const char *) ap_check_cmd_context(cmd_parms *cmd,
1085 const char *gt = (cmd->cmd->name[0] == '<'
1086 && cmd->cmd->name[strlen(cmd->cmd->name)-1] != '>')
1088 const ap_directive_t *found;
1090 if ((forbidden & NOT_IN_VIRTUALHOST) && cmd->server->is_virtual) {
1091 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1092 " cannot occur within <VirtualHost> section", NULL);
1095 if ((forbidden & NOT_IN_LIMIT) && cmd->limited != -1) {
1096 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1097 " cannot occur within <Limit> section", NULL);
1100 if ((forbidden & NOT_IN_DIR_LOC_FILE) == NOT_IN_DIR_LOC_FILE
1101 && cmd->path != NULL) {
1102 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1103 " cannot occur within <Directory/Location/Files> "
1107 if (((forbidden & NOT_IN_DIRECTORY)
1108 && ((found = find_parent(cmd->directive, "<Directory"))
1109 || (found = find_parent(cmd->directive, "<DirectoryMatch"))))
1110 || ((forbidden & NOT_IN_LOCATION)
1111 && ((found = find_parent(cmd->directive, "<Location"))
1112 || (found = find_parent(cmd->directive, "<LocationMatch"))))
1113 || ((forbidden & NOT_IN_FILES)
1114 && ((found = find_parent(cmd->directive, "<Files"))
1115 || (found = find_parent(cmd->directive, "<FilesMatch"))))) {
1116 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1117 " cannot occur within ", found->directive,
1124 static const char *set_access_name(cmd_parms *cmd, void *dummy,
1127 void *sconf = cmd->server->module_config;
1128 core_server_config *conf = ap_get_module_config(sconf, &core_module);
1130 const char *err = ap_check_cmd_context(cmd,
1131 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1136 conf->access_name = apr_pstrdup(cmd->pool, arg);
1141 static const char *set_gprof_dir(cmd_parms *cmd, void *dummy, const char *arg)
1143 void *sconf = cmd->server->module_config;
1144 core_server_config *conf = ap_get_module_config(sconf, &core_module);
1146 const char *err = ap_check_cmd_context(cmd,
1147 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1152 conf->gprof_dir = apr_pstrdup(cmd->pool, arg);
1157 static const char *set_add_default_charset(cmd_parms *cmd,
1158 void *d_, const char *arg)
1160 core_dir_config *d=d_;
1162 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1166 if (!strcasecmp(arg, "Off")) {
1167 d->add_default_charset = ADD_DEFAULT_CHARSET_OFF;
1169 else if (!strcasecmp(arg, "On")) {
1170 d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1171 d->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
1174 d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1175 d->add_default_charset_name = arg;
1180 static const char *set_document_root(cmd_parms *cmd, void *dummy,
1183 void *sconf = cmd->server->module_config;
1184 core_server_config *conf = ap_get_module_config(sconf, &core_module);
1186 const char *err = ap_check_cmd_context(cmd,
1187 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1192 arg = ap_os_canonical_filename(cmd->pool, arg);
1193 if (/* TODO: ap_configtestonly && ap_docrootcheck && */ !ap_is_directory(cmd->pool, arg)) {
1194 if (cmd->server->is_virtual) {
1195 ap_log_perror(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, cmd->pool,
1196 "Warning: DocumentRoot [%s] does not exist",
1200 return "DocumentRoot must be a directory";
1204 conf->ap_document_root = arg;
1208 AP_DECLARE(void) ap_custom_response(request_rec *r, int status, char *string)
1210 core_dir_config *conf =
1211 ap_get_module_config(r->per_dir_config, &core_module);
1214 if(conf->response_code_strings == NULL) {
1215 conf->response_code_strings =
1216 apr_pcalloc(r->pool,
1217 sizeof(*conf->response_code_strings) *
1221 idx = ap_index_of_response(status);
1223 conf->response_code_strings[idx] =
1224 ((ap_is_url(string) || (*string == '/')) && (*string != '"')) ?
1225 apr_pstrdup(r->pool, string) : apr_pstrcat(r->pool, "\"", string, NULL);
1228 static const char *set_error_document(cmd_parms *cmd, void *conf_,
1229 const char *errno_str, const char *msg)
1231 core_dir_config *conf=conf_;
1232 int error_number, index_number, idx500;
1233 enum { MSG, LOCAL_PATH, REMOTE_PATH } what = MSG;
1235 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1240 /* 1st parameter should be a 3 digit number, which we recognize;
1241 * convert it into an array index
1243 error_number = atoi(errno_str);
1244 idx500 = ap_index_of_response(HTTP_INTERNAL_SERVER_ERROR);
1246 if (error_number == HTTP_INTERNAL_SERVER_ERROR) {
1247 index_number = idx500;
1249 else if ((index_number = ap_index_of_response(error_number)) == idx500) {
1250 return apr_pstrcat(cmd->pool, "Unsupported HTTP response code ",
1254 /* Heuristic to determine second argument. */
1255 if (ap_strchr_c(msg,' '))
1257 else if (msg[0] == '/')
1259 else if (ap_is_url(msg))
1264 /* The entry should be ignored if it is a full URL for a 401 error */
1266 if (error_number == 401 && what == REMOTE_PATH) {
1267 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, cmd->server,
1268 "cannot use a full URL in a 401 ErrorDocument "
1269 "directive --- ignoring!");
1271 else { /* Store it... */
1272 if (conf->response_code_strings == NULL) {
1273 conf->response_code_strings =
1274 apr_pcalloc(cmd->pool,
1275 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
1277 /* hack. Prefix a " if it is a msg; as that is what
1278 * http_protocol.c relies on to distinguish between
1279 * a msg and a (local) path.
1281 conf->response_code_strings[index_number] = (what == MSG) ?
1282 apr_pstrcat(cmd->pool, "\"",msg,NULL) :
1283 apr_pstrdup(cmd->pool, msg);
1289 static const char *set_override(cmd_parms *cmd, void *d_, const char *l)
1291 core_dir_config *d=d_;
1294 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1299 d->override = OR_NONE;
1301 w = ap_getword_conf(cmd->pool, &l);
1302 if (!strcasecmp(w, "Limit")) {
1303 d->override |= OR_LIMIT;
1305 else if (!strcasecmp(w, "Options")) {
1306 d->override |= OR_OPTIONS;
1308 else if (!strcasecmp(w, "FileInfo")) {
1309 d->override |= OR_FILEINFO;
1311 else if (!strcasecmp(w, "AuthConfig")) {
1312 d->override |= OR_AUTHCFG;
1314 else if (!strcasecmp(w, "Indexes")) {
1315 d->override |= OR_INDEXES;
1317 else if (!strcasecmp(w, "None")) {
1318 d->override = OR_NONE;
1320 else if (!strcasecmp(w, "All")) {
1321 d->override = OR_ALL;
1324 return apr_pstrcat(cmd->pool, "Illegal override option ", w, NULL);
1326 d->override &= ~OR_UNSET;
1332 static const char *set_options(cmd_parms *cmd, void *d_, const char *l)
1334 core_dir_config *d=d_;
1335 allow_options_t opt;
1340 char *w = ap_getword_conf(cmd->pool, &l);
1343 if (*w == '+' || *w == '-') {
1351 if (!strcasecmp(w, "Indexes")) {
1354 else if (!strcasecmp(w, "Includes")) {
1357 else if (!strcasecmp(w, "IncludesNOEXEC")) {
1358 opt = (OPT_INCLUDES | OPT_INCNOEXEC);
1360 else if (!strcasecmp(w, "FollowSymLinks")) {
1361 opt = OPT_SYM_LINKS;
1363 else if (!strcasecmp(w, "SymLinksIfOwnerMatch")) {
1364 opt = OPT_SYM_OWNER;
1366 else if (!strcasecmp(w, "execCGI")) {
1369 else if (!strcasecmp(w, "MultiViews")) {
1372 else if (!strcasecmp(w, "RunScripts")) { /* AI backcompat. Yuck */
1373 opt = OPT_MULTI|OPT_EXECCGI;
1375 else if (!strcasecmp(w, "None")) {
1378 else if (!strcasecmp(w, "All")) {
1382 return apr_pstrcat(cmd->pool, "Illegal option ", w, NULL);
1385 /* we ensure the invariant (d->opts_add & d->opts_remove) == 0 */
1386 if (action == '-') {
1387 d->opts_remove |= opt;
1388 d->opts_add &= ~opt;
1391 else if (action == '+') {
1393 d->opts_remove &= ~opt;
1404 static const char *satisfy(cmd_parms *cmd, void *c_, const char *arg)
1406 core_dir_config *c=c_;
1408 if (!strcasecmp(arg, "all")) {
1409 c->satisfy = SATISFY_ALL;
1411 else if (!strcasecmp(arg, "any")) {
1412 c->satisfy = SATISFY_ANY;
1415 return "Satisfy either 'any' or 'all'.";
1420 static const char *require(cmd_parms *cmd, void *c_, const char *arg)
1423 core_dir_config *c=c_;
1425 if (!c->ap_requires) {
1426 c->ap_requires = apr_array_make(cmd->pool, 2, sizeof(require_line));
1428 r = (require_line *)apr_array_push(c->ap_requires);
1429 r->requirement = apr_pstrdup(cmd->pool, arg);
1430 r->method_mask = cmd->limited;
1434 AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd, void *dummy,
1436 const char *limited_methods = ap_getword(cmd->pool, &arg, '>');
1437 void *tog = cmd->cmd->cmd_data;
1441 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1446 while (limited_methods[0]) {
1447 char *method = ap_getword_conf(cmd->pool, &limited_methods);
1448 int methnum = ap_method_number_of(method);
1450 if (methnum == M_TRACE && !tog) {
1451 return "TRACE cannot be controlled by <Limit>";
1453 else if (methnum == M_INVALID) {
1455 register int i, j, k;
1458 * Deal with <Limit> by adding the method to the list.
1461 if (cmd->limited_xmethods == NULL) {
1462 cmd->limited_xmethods = apr_array_make(cmd->pool, 2,
1465 xmethod = (char **) apr_array_push(cmd->limited_xmethods);
1466 *xmethod = apr_pstrdup(cmd->pool, method);
1469 * <LimitExcept>, so remove any/all occurrences of the method
1470 * in the extension array.
1472 else if ((cmd->limited_xmethods != NULL)
1473 && (cmd->limited_xmethods->nelts != 0)) {
1474 xmethod = (char **) cmd->limited_xmethods->elts;
1475 for (i = 0; i < cmd->limited_xmethods->nelts; ) {
1476 if (strcmp(xmethod[i], method) == 0) {
1477 for (j = i, k = i + 1;
1478 k < cmd->limited_xmethods->nelts;
1480 xmethod[j] = xmethod[k];
1482 cmd->limited_xmethods->nelts--;
1487 limited |= (1 << methnum);
1490 /* Killing two features with one function,
1491 * if (tog == NULL) <Limit>, else <LimitExcept>
1493 cmd->limited = tog ? ~limited : limited;
1495 errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context);
1502 /* We use this in <DirectoryMatch> and <FilesMatch>, to ensure that
1503 * people don't get bitten by wrong-cased regex matches
1507 #define USE_ICASE REG_ICASE
1513 * Report a missing-'>' syntax error.
1515 static char *unclosed_directive(cmd_parms *cmd)
1517 return apr_pstrcat(cmd->pool, cmd->cmd->name,
1518 "> directive missing closing '>'", NULL);
1521 static const char *dirsection(cmd_parms *cmd, void *mconfig, const char *arg)
1524 const char *endp = ap_strrchr_c(arg, '>');
1525 int old_overrides = cmd->override;
1526 char *old_path = cmd->path;
1527 core_dir_config *conf;
1528 void *new_dir_conf = ap_create_per_dir_config(cmd->pool);
1530 const command_rec *thiscmd = cmd->cmd;
1532 const char *err = ap_check_cmd_context(cmd,
1533 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1539 return unclosed_directive(cmd);
1542 arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1544 cmd->path = ap_getword_conf(cmd->pool, &arg);
1545 cmd->override = OR_ALL|ACCESS_CONF;
1547 if (thiscmd->cmd_data) { /* <DirectoryMatch> */
1548 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1550 else if (!strcmp(cmd->path, "~")) {
1551 cmd->path = ap_getword_conf(cmd->pool, &arg);
1552 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1554 #if defined(HAVE_DRIVE_LETTERS) || defined(NETWARE)
1555 else if (strcmp(cmd->path, "/") == 0) {
1556 /* Treat 'default' path / as an inalienable root */
1557 cmd->path = apr_pstrdup(cmd->pool, cmd->path);
1560 #if defined(HAVE_UNC_PATHS)
1561 else if (strcmp(cmd->path, "//") == 0) {
1562 /* Treat UNC path // as an inalienable root */
1563 cmd->path = apr_pstrdup(cmd->pool, cmd->path);
1567 /* Ensure that the pathname is canonical */
1568 cmd->path = ap_os_canonical_filename(cmd->pool, cmd->path);
1571 /* initialize our config and fetch it */
1572 conf = (core_dir_config *)ap_set_config_vectors(cmd, new_dir_conf,
1575 errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_dir_conf);
1581 ap_add_per_dir_conf(cmd->server, new_dir_conf);
1584 return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1585 "> arguments not (yet) supported.", NULL);
1588 cmd->path = old_path;
1589 cmd->override = old_overrides;
1594 static const char *urlsection(cmd_parms *cmd, void *mconfig, const char *arg)
1597 const char *endp = ap_strrchr_c(arg, '>');
1598 int old_overrides = cmd->override;
1599 char *old_path = cmd->path;
1600 core_dir_config *conf;
1602 const command_rec *thiscmd = cmd->cmd;
1604 void *new_url_conf = ap_create_per_dir_config(cmd->pool);
1606 const char *err = ap_check_cmd_context(cmd,
1607 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1613 return unclosed_directive(cmd);
1616 arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1618 cmd->path = ap_getword_conf(cmd->pool, &arg);
1619 cmd->override = OR_ALL|ACCESS_CONF;
1621 if (thiscmd->cmd_data) { /* <LocationMatch> */
1622 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1624 else if (!strcmp(cmd->path, "~")) {
1625 cmd->path = ap_getword_conf(cmd->pool, &arg);
1626 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1629 /* initialize our config and fetch it */
1630 conf = (core_dir_config *)ap_set_config_vectors(cmd, new_url_conf,
1633 errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_url_conf);
1637 conf->d = apr_pstrdup(cmd->pool, cmd->path); /* No mangling, please */
1638 conf->d_is_fnmatch = apr_is_fnmatch(conf->d) != 0;
1641 ap_add_per_url_conf(cmd->server, new_url_conf);
1644 return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1645 "> arguments not (yet) supported.", NULL);
1648 cmd->path = old_path;
1649 cmd->override = old_overrides;
1654 static const char *filesection(cmd_parms *cmd, void *mconfig, const char *arg)
1657 const char *endp = ap_strrchr_c(arg, '>');
1658 int old_overrides = cmd->override;
1659 char *old_path = cmd->path;
1660 core_dir_config *conf;
1662 const command_rec *thiscmd = cmd->cmd;
1663 core_dir_config *c=mconfig;
1665 void *new_file_conf = ap_create_per_dir_config(cmd->pool);
1667 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT|NOT_IN_LOCATION);
1673 return unclosed_directive(cmd);
1676 arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1678 cmd->path = ap_getword_conf(cmd->pool, &arg);
1679 /* Only if not an .htaccess file */
1681 cmd->override = OR_ALL|ACCESS_CONF;
1684 if (thiscmd->cmd_data) { /* <FilesMatch> */
1685 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1687 else if (!strcmp(cmd->path, "~")) {
1688 cmd->path = ap_getword_conf(cmd->pool, &arg);
1689 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1692 /* Ensure that the pathname is canonical */
1693 cmd->path = ap_os_canonical_filename(cmd->pool, cmd->path);
1696 /* initialize our config and fetch it */
1697 conf = (core_dir_config *)ap_set_config_vectors(cmd, new_file_conf,
1700 errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_file_conf);
1704 conf->d = cmd->path;
1705 conf->d_is_fnmatch = apr_is_fnmatch(conf->d) != 0;
1708 ap_add_file_conf(c, new_file_conf);
1711 return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1712 "> arguments not (yet) supported.", NULL);
1715 cmd->path = old_path;
1716 cmd->override = old_overrides;
1721 static const char *start_ifmod(cmd_parms *cmd, void *mconfig, const char *arg)
1723 const char *endp = ap_strrchr_c(arg, '>');
1724 int not = (arg[0] == '!');
1728 return unclosed_directive(cmd);
1731 arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1737 found = ap_find_linked_module(arg);
1739 if ((!not && found) || (not && !found)) {
1740 ap_directive_t *parent = NULL;
1741 ap_directive_t *current = NULL;
1744 retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd,
1745 ¤t, &parent, "<IfModule");
1746 *(ap_directive_t **)mconfig = current;
1750 *(ap_directive_t **)mconfig = NULL;
1751 return ap_soak_end_container(cmd, "<IfModule");
1755 AP_DECLARE(int) ap_exists_config_define(const char *name)
1760 defines = (char **)ap_server_config_defines->elts;
1761 for (i = 0; i < ap_server_config_defines->nelts; i++) {
1762 if (strcmp(defines[i], name) == 0) {
1769 static const char *start_ifdefine(cmd_parms *cmd, void *dummy, const char *arg)
1775 endp = ap_strrchr_c(arg, '>');
1777 return unclosed_directive(cmd);
1780 arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1782 if (arg[0] == '!') {
1787 defined = ap_exists_config_define(arg);
1788 if ((!not && defined) || (not && !defined)) {
1789 ap_directive_t *parent = NULL;
1790 ap_directive_t *current = NULL;
1793 retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd,
1794 ¤t, &parent, "<IfDefine");
1795 *(ap_directive_t **)dummy = current;
1799 *(ap_directive_t **)dummy = NULL;
1800 return ap_soak_end_container(cmd, "<IfDefine");
1804 /* httpd.conf commands... beginning with the <VirtualHost> business */
1806 static const char *virtualhost_section(cmd_parms *cmd, void *dummy,
1809 server_rec *main_server = cmd->server, *s;
1811 const char *endp = ap_strrchr_c(arg, '>');
1812 apr_pool_t *p = cmd->pool;
1814 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1820 return unclosed_directive(cmd);
1823 arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1825 /* FIXME: There's another feature waiting to happen here -- since you
1826 can now put multiple addresses/names on a single <VirtualHost>
1827 you might want to use it to group common definitions and then
1828 define other "subhosts" with their individual differences. But
1829 personally I'd rather just do it with a macro preprocessor. -djg */
1830 if (main_server->is_virtual) {
1831 return "<VirtualHost> doesn't nest!";
1834 errmsg = ap_init_virtual_host(p, arg, main_server, &s);
1839 s->next = main_server->next;
1840 main_server->next = s;
1842 s->defn_name = cmd->directive->filename;
1843 s->defn_line_number = cmd->directive->line_num;
1847 errmsg = ap_walk_config(cmd->directive->first_child, cmd,
1848 s->lookup_defaults);
1850 cmd->server = main_server;
1855 static const char *set_server_alias(cmd_parms *cmd, void *dummy,
1858 if (!cmd->server->names) {
1859 return "ServerAlias only used in <VirtualHost>";
1862 char **item, *name = ap_getword_conf(cmd->pool, &arg);
1863 if (ap_is_matchexp(name)) {
1864 item = (char **)apr_array_push(cmd->server->wild_names);
1867 item = (char **)apr_array_push(cmd->server->names);
1874 static const char *add_filter(cmd_parms *cmd, void *dummy, const char *arg)
1876 core_dir_config *conf = dummy;
1879 newfilter = (char **)apr_array_push(conf->output_filters);
1880 *newfilter = apr_pstrdup(cmd->pool, arg);
1884 static const char *add_input_filter(cmd_parms *cmd, void *dummy, const char *arg)
1886 core_dir_config *conf = dummy;
1889 newfilter = (char **)apr_array_push(conf->input_filters);
1890 *newfilter = apr_pstrdup(cmd->pool, arg);
1894 static const char *set_server_string_slot(cmd_parms *cmd, void *dummy,
1897 /* This one's pretty generic... */
1899 int offset = (int)(long)cmd->info;
1900 char *struct_ptr = (char *)cmd->server;
1902 const char *err = ap_check_cmd_context(cmd,
1903 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1908 *(const char **)(struct_ptr + offset) = arg;
1912 static const char *server_port(cmd_parms *cmd, void *dummy, const char *arg)
1914 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1921 if (port <= 0 || port >= 65536) { /* 65536 == 1<<16 */
1922 return apr_pstrcat(cmd->temp_pool, "The port number \"", arg,
1923 "\" is outside the appropriate range "
1924 "(i.e., 1..65535).", NULL);
1926 cmd->server->port = port;
1930 static const char *set_signature_flag(cmd_parms *cmd, void *d_,
1933 core_dir_config *d=d_;
1935 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1940 if (strcasecmp(arg, "On") == 0) {
1941 d->server_signature = srv_sig_on;
1943 else if (strcasecmp(arg, "Off") == 0) {
1944 d->server_signature = srv_sig_off;
1946 else if (strcasecmp(arg, "EMail") == 0) {
1947 d->server_signature = srv_sig_withmail;
1950 return "ServerSignature: use one of: off | on | email";
1955 static const char *set_server_root(cmd_parms *cmd, void *dummy,
1958 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1964 arg = ap_os_canonical_filename(cmd->pool, arg);
1966 if (!ap_is_directory(cmd->pool, arg)) {
1967 return "ServerRoot must be a valid directory";
1969 ap_server_root = arg;
1973 static const char *set_timeout(cmd_parms *cmd, void *dummy, const char *arg)
1975 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1980 cmd->server->timeout = atoi(arg);
1984 static const char *set_keep_alive_timeout(cmd_parms *cmd, void *dummy,
1987 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1992 cmd->server->keep_alive_timeout = atoi(arg);
1996 static const char *set_keep_alive(cmd_parms *cmd, void *dummy,
1999 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2004 /* We've changed it to On/Off, but used to use numbers
2005 * so we accept anything but "Off" or "0" as "On"
2007 if (!strcasecmp(arg, "off") || !strcmp(arg, "0")) {
2008 cmd->server->keep_alive = 0;
2011 cmd->server->keep_alive = 1;
2016 static const char *set_keep_alive_max(cmd_parms *cmd, void *dummy,
2019 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2024 cmd->server->keep_alive_max = atoi(arg);
2028 static const char *set_idcheck(cmd_parms *cmd, void *d_, int arg)
2030 core_dir_config *d=d_;
2031 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2036 d->do_rfc1413 = arg != 0;
2040 static const char *set_hostname_lookups(cmd_parms *cmd, void *d_,
2043 core_dir_config *d=d_;
2045 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2050 if (!strcasecmp(arg, "on")) {
2051 d->hostname_lookups = HOSTNAME_LOOKUP_ON;
2053 else if (!strcasecmp(arg, "off")) {
2054 d->hostname_lookups = HOSTNAME_LOOKUP_OFF;
2056 else if (!strcasecmp(arg, "double")) {
2057 d->hostname_lookups = HOSTNAME_LOOKUP_DOUBLE;
2060 return "parameter must be 'on', 'off', or 'double'";
2065 static const char *set_serverpath(cmd_parms *cmd, void *dummy,
2068 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2073 cmd->server->path = arg;
2074 cmd->server->pathlen = strlen(arg);
2078 static const char *set_content_md5(cmd_parms *cmd, void *d_, int arg)
2080 core_dir_config *d=d_;
2081 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2086 d->content_md5 = arg != 0;
2090 static const char *set_use_canonical_name(cmd_parms *cmd, void *d_,
2093 core_dir_config *d=d_;
2094 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2099 if (strcasecmp(arg, "on") == 0) {
2100 d->use_canonical_name = USE_CANONICAL_NAME_ON;
2102 else if (strcasecmp(arg, "off") == 0) {
2103 d->use_canonical_name = USE_CANONICAL_NAME_OFF;
2105 else if (strcasecmp(arg, "dns") == 0) {
2106 d->use_canonical_name = USE_CANONICAL_NAME_DNS;
2109 return "parameter must be 'on', 'off', or 'dns'";
2115 static const char *include_config (cmd_parms *cmd, void *dummy,
2118 ap_directive_t *conftree = NULL;
2120 ap_process_resource_config(cmd->server,
2121 ap_server_root_relative(cmd->pool, name),
2122 &conftree, cmd->pool, cmd->temp_pool);
2123 *(ap_directive_t **)dummy = conftree;
2127 static const char *set_loglevel(cmd_parms *cmd, void *dummy, const char *arg)
2131 const char *err = ap_check_cmd_context(cmd,
2132 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2137 if ((str = ap_getword_conf(cmd->pool, &arg))) {
2138 if (!strcasecmp(str, "emerg")) {
2139 cmd->server->loglevel = APLOG_EMERG;
2141 else if (!strcasecmp(str, "alert")) {
2142 cmd->server->loglevel = APLOG_ALERT;
2144 else if (!strcasecmp(str, "crit")) {
2145 cmd->server->loglevel = APLOG_CRIT;
2147 else if (!strcasecmp(str, "error")) {
2148 cmd->server->loglevel = APLOG_ERR;
2150 else if (!strcasecmp(str, "warn")) {
2151 cmd->server->loglevel = APLOG_WARNING;
2153 else if (!strcasecmp(str, "notice")) {
2154 cmd->server->loglevel = APLOG_NOTICE;
2156 else if (!strcasecmp(str, "info")) {
2157 cmd->server->loglevel = APLOG_INFO;
2159 else if (!strcasecmp(str, "debug")) {
2160 cmd->server->loglevel = APLOG_DEBUG;
2163 return "LogLevel requires level keyword: one of "
2164 "emerg/alert/crit/error/warn/notice/info/debug";
2168 return "LogLevel requires level keyword";
2174 AP_DECLARE(const char *) ap_psignature(const char *prefix, request_rec *r)
2177 core_dir_config *conf;
2179 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
2181 if ((conf->server_signature == srv_sig_off)
2182 || (conf->server_signature == srv_sig_unset)) {
2186 apr_snprintf(sport, sizeof sport, "%u", (unsigned) ap_get_server_port(r));
2188 if (conf->server_signature == srv_sig_withmail) {
2189 return apr_pstrcat(r->pool, prefix, "<ADDRESS>" AP_SERVER_BASEVERSION
2190 " Server at <A HREF=\"mailto:",
2191 r->server->server_admin, "\">",
2192 ap_get_server_name(r), "</A> Port ", sport,
2193 "</ADDRESS>\n", NULL);
2195 return apr_pstrcat(r->pool, prefix, "<ADDRESS>" AP_SERVER_BASEVERSION
2196 " Server at ", ap_get_server_name(r), " Port ", sport,
2197 "</ADDRESS>\n", NULL);
2201 * Load an authorisation realm into our location configuration, applying the
2202 * usual rules that apply to realms.
2204 static const char *set_authname(cmd_parms *cmd, void *mconfig,
2207 core_dir_config *aconfig = (core_dir_config *)mconfig;
2209 aconfig->ap_auth_name = ap_escape_quotes(cmd->pool, word1);
2213 #ifdef _OSD_POSIX /* BS2000 Logon Passwd file */
2214 static const char *set_bs2000_account(cmd_parms *cmd, void *dummy, char *name)
2216 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2221 return os_set_account(cmd->pool, name);
2223 #endif /*_OSD_POSIX*/
2226 * Handle a request to include the server's OS platform in the Server
2227 * response header field (the ServerTokens directive). Unfortunately
2228 * this requires a new global in order to communicate the setting back to
2229 * http_main so it can insert the information in the right place in the
2233 static char *server_version = NULL;
2234 static int version_locked = 0;
2236 enum server_token_type {
2237 SrvTk_MIN, /* eg: Apache/1.3.0 */
2238 SrvTk_OS, /* eg: Apache/1.3.0 (UNIX) */
2239 SrvTk_FULL, /* eg: Apache/1.3.0 (UNIX) PHP/3.0 FooBar/1.2b */
2240 SrvTk_PRODUCT_ONLY /* eg: Apache */
2242 static enum server_token_type ap_server_tokens = SrvTk_FULL;
2244 static apr_status_t reset_version(void *dummy)
2247 ap_server_tokens = SrvTk_FULL;
2248 server_version = NULL;
2252 AP_DECLARE(const char *) ap_get_server_version(void)
2254 return (server_version ? server_version : AP_SERVER_BASEVERSION);
2257 AP_DECLARE(void) ap_add_version_component(apr_pool_t *pconf, const char *component)
2259 if (! version_locked) {
2261 * If the version string is null, register our cleanup to reset the
2262 * pointer on pool destruction. We also know that, if NULL,
2263 * we are adding the original SERVER_BASEVERSION string.
2265 if (server_version == NULL) {
2266 apr_pool_cleanup_register(pconf, NULL, reset_version,
2267 apr_pool_cleanup_null);
2268 server_version = apr_pstrdup(pconf, component);
2272 * Tack the given component identifier to the end of
2273 * the existing string.
2275 server_version = apr_pstrcat(pconf, server_version, " ",
2282 * This routine adds the real server base identity to the version string,
2283 * and then locks out changes until the next reconfig.
2285 static void ap_set_version(apr_pool_t *pconf)
2287 if (ap_server_tokens == SrvTk_PRODUCT_ONLY) {
2288 ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT);
2290 else if (ap_server_tokens == SrvTk_MIN) {
2291 ap_add_version_component(pconf, AP_SERVER_BASEVERSION);
2294 ap_add_version_component(pconf, AP_SERVER_BASEVERSION " (" PLATFORM ")");
2297 * Lock the server_version string if we're not displaying
2298 * the full set of tokens
2300 if (ap_server_tokens != SrvTk_FULL) {
2305 static const char *set_serv_tokens(cmd_parms *cmd, void *dummy,
2308 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2313 if (!strcasecmp(arg, "OS")) {
2314 ap_server_tokens = SrvTk_OS;
2316 else if (!strcasecmp(arg, "Min") || !strcasecmp(arg, "Minimal")) {
2317 ap_server_tokens = SrvTk_MIN;
2319 else if (!strcasecmp(arg, "Prod") || !strcasecmp(arg, "ProductOnly")) {
2320 ap_server_tokens = SrvTk_PRODUCT_ONLY;
2323 ap_server_tokens = SrvTk_FULL;
2328 static const char *set_limit_req_line(cmd_parms *cmd, void *dummy,
2331 const char *err = ap_check_cmd_context(cmd,
2332 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2340 return apr_pstrcat(cmd->temp_pool, "LimitRequestLine \"", arg,
2341 "\" must be a non-negative integer", NULL);
2343 if (lim > DEFAULT_LIMIT_REQUEST_LINE) {
2344 return apr_psprintf(cmd->temp_pool, "LimitRequestLine \"%s\" "
2345 "must not exceed the precompiled maximum of %d",
2346 arg, DEFAULT_LIMIT_REQUEST_LINE);
2348 cmd->server->limit_req_line = lim;
2352 static const char *set_limit_req_fieldsize(cmd_parms *cmd, void *dummy,
2355 const char *err = ap_check_cmd_context(cmd,
2356 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2364 return apr_pstrcat(cmd->temp_pool, "LimitRequestFieldsize \"", arg,
2365 "\" must be a non-negative integer (0 = no limit)",
2368 if (lim > DEFAULT_LIMIT_REQUEST_FIELDSIZE) {
2369 return apr_psprintf(cmd->temp_pool, "LimitRequestFieldsize \"%s\" "
2370 "must not exceed the precompiled maximum of %d",
2371 arg, DEFAULT_LIMIT_REQUEST_FIELDSIZE);
2373 cmd->server->limit_req_fieldsize = lim;
2377 static const char *set_limit_req_fields(cmd_parms *cmd, void *dummy,
2380 const char *err = ap_check_cmd_context(cmd,
2381 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2389 return apr_pstrcat(cmd->temp_pool, "LimitRequestFields \"", arg,
2390 "\" must be a non-negative integer (0 = no limit)",
2393 cmd->server->limit_req_fields = lim;
2397 static const char *set_limit_req_body(cmd_parms *cmd, void *conf_,
2400 core_dir_config *conf=conf_;
2401 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2406 /* WTF: If strtoul is not portable, then write a replacement.
2407 * Instead we have an idiotic define in httpd.h that prevents
2408 * it from being used even when it is available. Sheesh.
2410 conf->limit_req_body = (unsigned long)strtol(arg, (char **)NULL, 10);
2414 static const char *set_limit_xml_req_body(cmd_parms *cmd, void *conf_,
2417 core_dir_config *conf = conf_;
2418 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2423 conf->limit_xml_body = atol(arg);
2424 if (conf->limit_xml_body < 0)
2425 return "LimitXMLRequestBody requires a non-negative integer.";
2430 AP_DECLARE(size_t) ap_get_limit_xml_body(const request_rec *r)
2432 core_dir_config *conf;
2434 conf = ap_get_module_config(r->per_dir_config, &core_module);
2435 if (conf->limit_xml_body == AP_LIMIT_UNSET)
2436 return AP_DEFAULT_LIMIT_XML_BODY;
2437 return (size_t)conf->limit_xml_body;
2441 static const char *set_interpreter_source(cmd_parms *cmd, core_dir_config *d,
2444 if (!strcasecmp(arg, "registry")) {
2445 d->script_interpreter_source = INTERPRETER_SOURCE_REGISTRY;
2446 } else if (!strcasecmp(arg, "registry-strict")) {
2447 d->script_interpreter_source = INTERPRETER_SOURCE_REGISTRY_STRICT;
2448 } else if (!strcasecmp(arg, "script")) {
2449 d->script_interpreter_source = INTERPRETER_SOURCE_SHEBANG;
2451 return apr_pstrcat(cmd->temp_pool, "ScriptInterpreterSource \"", arg,
2452 "\" must be \"registry\", \"registry-strict\" or "
2453 "\"script\"", NULL);
2459 #if !defined (RLIMIT_CPU) || !(defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)) || !defined (RLIMIT_NPROC)
2460 static const char *no_set_limit(cmd_parms *cmd, void *conf_,
2461 const char *arg, const char *arg2)
2463 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, cmd->server,
2464 "%s not supported on this platform", cmd->cmd->name);
2470 static const char *set_limit_cpu(cmd_parms *cmd, void *conf_,
2471 const char *arg, const char *arg2)
2473 core_dir_config *conf=conf_;
2475 unixd_set_rlimit(cmd, &conf->limit_cpu, arg, arg2, RLIMIT_CPU);
2480 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)
2481 static const char *set_limit_mem(cmd_parms *cmd, void *conf_,
2482 const char *arg, const char * arg2)
2484 core_dir_config *conf=conf_;
2486 #if defined(RLIMIT_AS)
2487 unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2 ,RLIMIT_AS);
2488 #elif defined(RLIMIT_DATA)
2489 unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_DATA);
2490 #elif defined(RLIMIT_VMEM)
2491 unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_VMEM);
2498 static const char *set_limit_nproc(cmd_parms *cmd, void *conf_,
2499 const char *arg, const char * arg2)
2501 core_dir_config *conf=conf_;
2503 unixd_set_rlimit(cmd, &conf->limit_nproc, arg, arg2, RLIMIT_NPROC);
2508 static apr_status_t writev_it_all(apr_socket_t *s,
2509 struct iovec *vec, int nvec,
2510 apr_size_t len, apr_size_t *nbytes)
2512 apr_size_t bytes_written = 0;
2519 /* XXX handle checking for non-blocking socket */
2520 while (bytes_written != len) {
2521 rv = apr_sendv(s, vec + i, nvec - i, &n);
2523 if (rv != APR_SUCCESS)
2527 /* If the write did not complete, adjust the iovecs and issue
2530 if (bytes_written < len) {
2531 /* Skip over the vectors that have already been written */
2532 apr_size_t cnt = vec[i].iov_len;
2533 while (n >= cnt && i + 1 < nvec) {
2535 cnt += vec[i].iov_len;
2538 /* Handle partial write of vec i */
2539 vec[i].iov_base = (char *) vec[i].iov_base +
2540 (vec[i].iov_len - (cnt - n));
2541 vec[i].iov_len = cnt -n;
2544 n = len - bytes_written;
2550 /* sendfile_it_all()
2551 * send the entire file using sendfile()
2552 * handle partial writes
2553 * return only when all bytes have been sent or an error is encountered.
2556 #if APR_HAS_SENDFILE
2557 static apr_status_t sendfile_it_all(conn_rec *c,
2560 apr_off_t file_offset,
2561 apr_size_t file_bytes_left,
2562 apr_size_t total_bytes_left,
2567 apr_int32_t timeout = 0;
2570 AP_DEBUG_ASSERT((apr_getsocketopt(c->client_socket, APR_SO_TIMEOUT,
2571 &timeout) == APR_SUCCESS) &&
2572 timeout > 0); /* socket must be in timeout mode */
2574 apr_size_t tmplen = file_bytes_left;
2576 rv = apr_sendfile(c->client_socket, fd, hdtr, &file_offset, &tmplen,
2578 total_bytes_left -= tmplen;
2579 if (!total_bytes_left || rv != APR_SUCCESS) {
2580 return rv; /* normal case & error exit */
2583 AP_DEBUG_ASSERT(total_bytes_left > 0 && tmplen > 0);
2585 /* partial write, oooh noooo...
2586 * Skip over any header data which was written
2588 while (tmplen && hdtr->numheaders) {
2589 if (tmplen >= hdtr->headers[0].iov_len) {
2590 tmplen -= hdtr->headers[0].iov_len;
2595 char *iov_base = (char *)hdtr->headers[0].iov_base;
2597 hdtr->headers[0].iov_len -= tmplen;
2599 hdtr->headers[0].iov_base = iov_base;
2604 /* Skip over any file data which was written */
2606 if (tmplen <= file_bytes_left) {
2607 file_offset += tmplen;
2608 file_bytes_left -= tmplen;
2611 tmplen -= file_bytes_left;
2612 file_bytes_left = 0;
2615 /* Skip over any trailer data which was written */
2617 while (tmplen && hdtr->numtrailers) {
2618 if (tmplen >= hdtr->trailers[0].iov_len) {
2619 tmplen -= hdtr->trailers[0].iov_len;
2620 --hdtr->numtrailers;
2624 char *iov_base = (char *)hdtr->trailers[0].iov_base;
2626 hdtr->trailers[0].iov_len -= tmplen;
2628 hdtr->trailers[0].iov_base = iov_base;
2638 * Sends the contents of file fd along with header/trailer bytes, if any,
2639 * to the network. send_the_file will return only when all the bytes have been
2640 * sent (i.e., it handles partial writes) or on a network error condition.
2642 static apr_status_t send_the_file(conn_rec *c, apr_file_t *fd,
2643 apr_hdtr_t *hdtr, apr_off_t offset,
2644 apr_size_t length, apr_size_t *nbytes)
2646 apr_status_t rv = APR_SUCCESS;
2647 apr_int32_t togo; /* Remaining number of bytes in the file to send */
2648 apr_size_t sendlen = 0;
2649 apr_size_t bytes_sent;
2651 apr_off_t o; /* Track the file offset for partial writes */
2657 * writev_it_all handles partial writes.
2658 * XXX: optimization... if headers are less than MIN_WRITE_SIZE, copy
2661 if ( hdtr && hdtr->numheaders > 0 ) {
2662 for (i = 0; i < hdtr->numheaders; i++) {
2663 sendlen += hdtr->headers[i].iov_len;
2665 rv = writev_it_all(c->client_socket, hdtr->headers, hdtr->numheaders,
2666 sendlen, &bytes_sent);
2667 if (rv == APR_SUCCESS)
2668 *nbytes += bytes_sent; /* track total bytes sent */
2671 /* Seek the file to 'offset' */
2672 if (offset != 0 && rv == APR_SUCCESS) {
2673 rv = apr_file_seek(fd, APR_SET, &offset);
2676 /* Send the file, making sure to handle partial writes */
2678 while (rv == APR_SUCCESS && togo) {
2679 sendlen = togo > sizeof(buffer) ? sizeof(buffer) : togo;
2681 rv = apr_file_read(fd, buffer, &sendlen);
2682 while (rv == APR_SUCCESS && sendlen) {
2683 bytes_sent = sendlen;
2684 rv = apr_send(c->client_socket, &buffer[o], &bytes_sent);
2685 if (rv == APR_SUCCESS) {
2686 sendlen -= bytes_sent; /* sendlen != bytes_sent ==> partial write */
2687 o += bytes_sent; /* o is where we are in the buffer */
2688 *nbytes += bytes_sent;
2689 togo -= bytes_sent; /* track how much of the file we've sent */
2694 /* Send the trailers
2695 * XXX: optimization... if it will fit, send this on the last send in the
2699 if ( rv == APR_SUCCESS && hdtr && hdtr->numtrailers > 0 ) {
2700 for (i = 0; i < hdtr->numtrailers; i++) {
2701 sendlen += hdtr->trailers[i].iov_len;
2703 rv = writev_it_all(c->client_socket, hdtr->trailers, hdtr->numtrailers,
2704 sendlen, &bytes_sent);
2705 if (rv == APR_SUCCESS)
2706 *nbytes += bytes_sent;
2712 /* Note --- ErrorDocument will now work from .htaccess files.
2713 * The AllowOverride of Fileinfo allows webmasters to turn it off
2716 static const command_rec core_cmds[] = {
2718 /* Old access config file commands */
2720 AP_INIT_RAW_ARGS("<Directory", dirsection, NULL, RSRC_CONF,
2721 "Container for directives affecting resources located in the specified "
2723 AP_INIT_RAW_ARGS("<Location", urlsection, NULL, RSRC_CONF,
2724 "Container for directives affecting resources accessed through the "
2725 "specified URL paths"),
2726 AP_INIT_RAW_ARGS("<VirtualHost", virtualhost_section, NULL, RSRC_CONF,
2727 "Container to map directives to a particular virtual host, takes one or "
2728 "more host addresses"),
2729 AP_INIT_RAW_ARGS("<Files", filesection, NULL, OR_ALL,
2730 "Container for directives affecting files matching specified patterns"),
2731 AP_INIT_RAW_ARGS("<Limit", ap_limit_section, NULL, OR_ALL,
2732 "Container for authentication directives when accessed using specified HTTP "
2734 AP_INIT_RAW_ARGS("<LimitExcept", ap_limit_section, (void*)1, OR_ALL,
2735 "Container for authentication directives to be applied when any HTTP "
2736 "method other than those specified is used to access the resource"),
2737 AP_INIT_TAKE1("<IfModule", start_ifmod, NULL, EXEC_ON_READ | OR_ALL,
2738 "Container for directives based on existance of specified modules"),
2739 AP_INIT_TAKE1("<IfDefine", start_ifdefine, NULL, EXEC_ON_READ | OR_ALL,
2740 "Container for directives based on existance of command line defines"),
2741 AP_INIT_RAW_ARGS("<DirectoryMatch", dirsection, (void*)1, RSRC_CONF,
2742 "Container for directives affecting resources located in the "
2743 "specified directories"),
2744 AP_INIT_RAW_ARGS("<LocationMatch", urlsection, (void*)1, RSRC_CONF,
2745 "Container for directives affecting resources accessed through the "
2746 "specified URL paths"),
2747 AP_INIT_RAW_ARGS("<FilesMatch", filesection, (void*)1, OR_ALL,
2748 "Container for directives affecting files matching specified patterns"),
2749 AP_INIT_TAKE1("AuthType", ap_set_string_slot,
2750 (void*)XtOffsetOf(core_dir_config, ap_auth_type), OR_AUTHCFG,
2751 "An HTTP authorization type (e.g., \"Basic\")"),
2752 AP_INIT_TAKE1("AuthName", set_authname, NULL, OR_AUTHCFG,
2753 "The authentication realm (e.g. \"Members Only\")"),
2754 AP_INIT_RAW_ARGS("Require", require, NULL, OR_AUTHCFG,
2755 "Selects which authenticated users or groups may access a protected space"),
2756 AP_INIT_TAKE1("Satisfy", satisfy, NULL, OR_AUTHCFG,
2757 "access policy if both allow and require used ('all' or 'any')"),
2759 AP_INIT_TAKE1("GprofDir", set_gprof_dir, NULL, RSRC_CONF,
2760 "Directory to plop gmon.out files"),
2762 AP_INIT_TAKE1("AddDefaultCharset", set_add_default_charset, NULL, OR_FILEINFO,
2763 "The name of the default charset to add to any Content-Type without one or 'Off' to disable"),
2765 /* Old resource config file commands */
2767 AP_INIT_RAW_ARGS("AccessFileName", set_access_name, NULL, RSRC_CONF,
2768 "Name(s) of per-directory config files (default: .htaccess)"),
2769 AP_INIT_TAKE1("DocumentRoot", set_document_root, NULL, RSRC_CONF,
2770 "Root directory of the document tree"),
2771 AP_INIT_TAKE2("ErrorDocument", set_error_document, NULL, OR_FILEINFO,
2772 "Change responses for HTTP errors"),
2773 AP_INIT_RAW_ARGS("AllowOverride", set_override, NULL, ACCESS_CONF,
2774 "Controls what groups of directives can be configured by per-directory "
2776 AP_INIT_RAW_ARGS("Options", set_options, NULL, OR_OPTIONS,
2777 "Set a number of attributes for a given directory"),
2778 AP_INIT_TAKE1("DefaultType", ap_set_string_slot,
2779 (void*)XtOffsetOf (core_dir_config, ap_default_type),
2780 OR_FILEINFO, "the default MIME type for untypable files"),
2782 /* Old server config file commands */
2784 AP_INIT_TAKE1("Port", server_port, NULL, RSRC_CONF, "A TCP port number"),
2785 AP_INIT_TAKE1("HostnameLookups", set_hostname_lookups, NULL,
2786 ACCESS_CONF|RSRC_CONF,
2787 "\"on\" to enable, \"off\" to disable reverse DNS lookups, or \"double\" to "
2788 "enable double-reverse DNS lookups"),
2789 AP_INIT_TAKE1("ServerAdmin", set_server_string_slot,
2790 (void *)XtOffsetOf (server_rec, server_admin), RSRC_CONF,
2791 "The email address of the server administrator"),
2792 AP_INIT_TAKE1("ServerName", set_server_string_slot,
2793 (void *)XtOffsetOf (server_rec, server_hostname), RSRC_CONF,
2794 "The hostname of the server"),
2795 AP_INIT_TAKE1("ServerSignature", set_signature_flag, NULL, OR_ALL,
2796 "En-/disable server signature (on|off|email)"),
2797 AP_INIT_TAKE1("ServerRoot", set_server_root, NULL, RSRC_CONF,
2798 "Common directory of server-related files (logs, confs, etc.)"),
2799 AP_INIT_TAKE1("ErrorLog", set_server_string_slot,
2800 (void *)XtOffsetOf (server_rec, error_fname), RSRC_CONF,
2801 "The filename of the error log"),
2802 AP_INIT_RAW_ARGS("ServerAlias", set_server_alias, NULL, RSRC_CONF,
2803 "A name or names alternately used to access the server"),
2804 AP_INIT_TAKE1("ServerPath", set_serverpath, NULL, RSRC_CONF,
2805 "The pathname the server can be reached at"),
2806 AP_INIT_TAKE1("Timeout", set_timeout, NULL, RSRC_CONF,
2807 "Timeout duration (sec)"),
2808 AP_INIT_TAKE1("KeepAliveTimeout", set_keep_alive_timeout, NULL, RSRC_CONF,
2809 "Keep-Alive timeout duration (sec)"),
2810 AP_INIT_TAKE1("MaxKeepAliveRequests", set_keep_alive_max, NULL, RSRC_CONF,
2811 "Maximum number of Keep-Alive requests per connection, or 0 for infinite"),
2812 AP_INIT_TAKE1("KeepAlive", set_keep_alive, NULL, RSRC_CONF,
2813 "Whether persistent connections should be On or Off"),
2814 AP_INIT_FLAG("IdentityCheck", set_idcheck, NULL, RSRC_CONF|ACCESS_CONF,
2815 "Enable identd (RFC 1413) user lookups - SLOW"),
2816 AP_INIT_FLAG("ContentDigest", set_content_md5, NULL, OR_OPTIONS,
2817 "whether or not to send a Content-MD5 header with each request"),
2818 AP_INIT_TAKE1("UseCanonicalName", set_use_canonical_name, NULL,
2819 RSRC_CONF|ACCESS_CONF,
2820 "How to work out the ServerName : Port when constructing URLs"),
2821 /* TODO: RlimitFoo should all be part of mod_cgi, not in the core */
2822 /* TODO: ListenBacklog in MPM */
2823 AP_INIT_TAKE1("Include", include_config, NULL,
2824 (RSRC_CONF | ACCESS_CONF | EXEC_ON_READ),
2825 "Name of the config file to be included"),
2826 AP_INIT_TAKE1("LogLevel", set_loglevel, NULL, RSRC_CONF,
2827 "Level of verbosity in error logging"),
2828 AP_INIT_TAKE1("NameVirtualHost", ap_set_name_virtual_host, NULL, RSRC_CONF,
2829 "A numeric IP address:port, or the name of a host"),
2831 AP_INIT_TAKE1("BS2000Account", set_bs2000_account, NULL, RSRC_CONF,
2832 "Name of server User's bs2000 logon account name"),
2835 AP_INIT_TAKE1("ScriptInterpreterSource", set_interpreter_source, NULL,
2837 "Where to find interpreter to run Win32 scripts (Registry or script shebang line)"),
2839 AP_INIT_TAKE1("ServerTokens", set_serv_tokens, NULL, RSRC_CONF,
2840 "Determine tokens displayed in the Server: header - Min(imal), OS or Full"),
2841 AP_INIT_TAKE1("LimitRequestLine", set_limit_req_line, NULL, RSRC_CONF,
2842 "Limit on maximum size of an HTTP request line"),
2843 AP_INIT_TAKE1("LimitRequestFieldsize", set_limit_req_fieldsize, NULL,
2845 "Limit on maximum size of an HTTP request header field"),
2846 AP_INIT_TAKE1("LimitRequestFields", set_limit_req_fields, NULL, RSRC_CONF,
2847 "Limit (0 = unlimited) on max number of header fields in a request message"),
2848 AP_INIT_TAKE1("LimitRequestBody", set_limit_req_body,
2849 (void*)XtOffsetOf(core_dir_config, limit_req_body), OR_ALL,
2850 "Limit (in bytes) on maximum size of request message body"),
2851 AP_INIT_TAKE1("LimitXMLRequestBody", set_limit_xml_req_body, NULL, OR_ALL,
2852 "Limit (in bytes) on maximum size of an XML-based request "
2855 /* System Resource Controls */
2857 AP_INIT_TAKE12("RLimitCPU", set_limit_cpu,
2858 (void*)XtOffsetOf(core_dir_config, limit_cpu),
2859 OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
2861 AP_INIT_TAKE12("RLimitCPU", no_set_limit, NULL,
2862 OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
2864 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined (RLIMIT_AS)
2865 AP_INIT_TAKE12("RLimitMEM", set_limit_mem,
2866 (void*)XtOffsetOf(core_dir_config, limit_mem),
2867 OR_ALL, "Soft/hard limits for max memory usage per process"),
2869 AP_INIT_TAKE12("RLimitMEM", no_set_limit, NULL,
2870 OR_ALL, "Soft/hard limits for max memory usage per process"),
2873 AP_INIT_TAKE12("RLimitNPROC", set_limit_nproc,
2874 (void*)XtOffsetOf(core_dir_config, limit_nproc),
2875 OR_ALL, "soft/hard limits for max number of processes per uid"),
2877 AP_INIT_TAKE12("RLimitNPROC", no_set_limit, NULL,
2878 OR_ALL, "soft/hard limits for max number of processes per uid"),
2880 /* XXX These should be allowable in .htaccess files, but currently it won't
2881 * play well with the Options stuff. Until that is fixed, I would prefer
2882 * to leave it just in the conf file. Other should feel free to disagree
2885 AP_INIT_ITERATE("SetOutputFilter", add_filter, NULL, ACCESS_CONF,
2886 "filters to be run"),
2887 AP_INIT_ITERATE("SetInputFilter", add_input_filter, NULL, ACCESS_CONF,
2888 "filters to be run on the request body"),
2892 /*****************************************************************
2894 * Core handlers for various phases of server operation...
2897 AP_DECLARE_NONSTD(int) ap_core_translate(request_rec *r)
2899 void *sconf = r->server->module_config;
2900 core_server_config *conf = ap_get_module_config(sconf, &core_module);
2903 return HTTP_FORBIDDEN;
2905 if ((r->uri[0] != '/') && strcmp(r->uri, "*")) {
2906 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2907 "Invalid URI in request %s", r->the_request);
2908 return HTTP_BAD_REQUEST;
2912 && !strncmp(r->uri, r->server->path, r->server->pathlen)
2913 && (r->server->path[r->server->pathlen - 1] == '/'
2914 || r->uri[r->server->pathlen] == '/'
2915 || r->uri[r->server->pathlen] == '\0')) {
2916 r->filename = apr_pstrcat(r->pool, conf->ap_document_root,
2917 (r->uri + r->server->pathlen), NULL);
2921 * Make sure that we do not mess up the translation by adding two
2922 * /'s in a row. This happens under windows when the document
2923 * root ends with a /
2925 if ((conf->ap_document_root[strlen(conf->ap_document_root)-1] == '/')
2926 && (*(r->uri) == '/')) {
2927 r->filename = apr_pstrcat(r->pool, conf->ap_document_root, r->uri+1,
2931 r->filename = apr_pstrcat(r->pool, conf->ap_document_root, r->uri,
2939 static int do_nothing(request_rec *r) { return OK; }
2941 static int default_handler(request_rec *r)
2943 apr_bucket_brigade *bb;
2947 apr_file_t *fd = NULL;
2948 apr_status_t status;
2949 /* XXX if/when somebody writes a content-md5 filter we either need to
2950 * remove this support or coordinate when to use the filter vs.
2951 * when to use this code
2952 * The current choice of when to compute the md5 here matches the 1.3
2953 * support fairly closely (unlike 1.3, we don't handle computing md5
2954 * when the charset is translated).
2956 int bld_content_md5;
2959 * The old way of doing handlers meant that this handler would
2960 * match literally anything - this way will require handler to
2961 * have a / in the middle, which probably captures the original
2962 * intent, but may cause problems at first - Ben 7th Jan 01
2964 if(strcmp(r->handler,"default-handler")
2965 && ap_strcmp_match(r->handler,"*/*"))
2968 d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
2970 bld_content_md5 = (d->content_md5 & 1)
2971 && r->output_filters->frec->ftype != AP_FTYPE_CONTENT;
2973 ap_allow_methods(r, MERGE_ALLOW, "GET", "OPTIONS", "POST", NULL);
2975 if ((errstatus = ap_discard_request_body(r)) != OK) {
2979 if (r->method_number == M_INVALID) {
2980 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2981 "Invalid method in request %s", r->the_request);
2982 return HTTP_NOT_IMPLEMENTED;
2984 if (r->method_number == M_OPTIONS) {
2985 return ap_send_http_options(r);
2987 if (r->method_number == M_PUT) {
2988 return HTTP_METHOD_NOT_ALLOWED;
2990 if (r->finfo.filetype == 0 || (r->path_info && *r->path_info)) {
2991 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r,
2992 "File does not exist: %s",r->path_info ?
2993 apr_pstrcat(r->pool, r->filename, r->path_info, NULL)
2995 return HTTP_NOT_FOUND;
2998 if (r->method_number != M_GET && r->method_number != M_POST) {
2999 return HTTP_METHOD_NOT_ALLOWED;
3002 if ((status = apr_file_open(&fd, r->filename, APR_READ | APR_BINARY, 0, r->connection->pool)) != APR_SUCCESS) {
3003 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r,
3004 "file permissions deny server access: %s", r->filename);
3005 return HTTP_FORBIDDEN;
3007 ap_update_mtime(r, r->finfo.mtime);
3008 ap_set_last_modified(r);
3010 apr_table_setn(r->headers_out, "Accept-Ranges", "bytes");
3011 ap_set_content_length(r, r->finfo.size);
3012 if ((errstatus = ap_meets_conditions(r)) != OK) {
3017 if (bld_content_md5) {
3018 apr_table_setn(r->headers_out, "Content-MD5",
3019 ap_md5digest(r->pool, fd));
3022 bb = apr_brigade_create(r->pool);
3023 e = apr_bucket_file_create(fd, 0, r->finfo.size);
3025 APR_BRIGADE_INSERT_HEAD(bb, e);
3026 e = apr_bucket_eos_create();
3027 APR_BRIGADE_INSERT_TAIL(bb, e);
3029 return ap_pass_brigade(r->output_filters, bb);
3033 * HTTP/1.1 chunked transfer encoding filter.
3035 static apr_status_t chunk_filter(ap_filter_t *f, apr_bucket_brigade *b)
3037 #define ASCII_CRLF "\015\012"
3038 #define ASCII_ZERO "\060"
3039 apr_bucket_brigade *more = NULL;
3043 for (more = NULL; b; b = more, more = NULL) {
3044 apr_off_t bytes = 0;
3045 apr_bucket *eos = NULL;
3046 char chunk_hdr[20]; /* enough space for the snprintf below */
3048 APR_BRIGADE_FOREACH(e, b) {
3049 if (APR_BUCKET_IS_EOS(e)) {
3050 /* there shouldn't be anything after the eos */
3054 else if (e->length == -1) {
3055 /* unknown amount of data (e.g. a pipe) */
3059 rv = apr_bucket_read(e, &data, &len, APR_BLOCK_READ);
3060 if (rv != APR_SUCCESS) {
3065 * There may be a new next bucket representing the
3066 * rest of the data stream on which a read() may
3067 * block so we pass down what we have so far.
3070 more = apr_brigade_split(b, APR_BUCKET_NEXT(e));
3074 /* If there was nothing in this bucket then we can
3075 * safely move on to the next one without pausing
3076 * to pass down what we have counted up so far.
3087 * XXX: if there aren't very many bytes at this point it may
3088 * be a good idea to set them aside and return for more,
3089 * unless we haven't finished counting this brigade yet.
3092 /* if there are content bytes, then wrap them in a chunk */
3097 * Insert the chunk header, specifying the number of bytes in
3100 /* XXX might be nice to have APR_OFF_T_FMT_HEX */
3101 hdr_len = apr_snprintf(chunk_hdr, sizeof(chunk_hdr),
3102 "%qx" CRLF, (apr_uint64_t)bytes);
3103 ap_xlate_proto_to_ascii(chunk_hdr, hdr_len);
3104 e = apr_bucket_transient_create(chunk_hdr, hdr_len);
3105 APR_BRIGADE_INSERT_HEAD(b, e);
3108 * Insert the end-of-chunk CRLF before the EOS bucket, or
3109 * appended to the brigade
3111 e = apr_bucket_immortal_create(ASCII_CRLF, 2);
3113 APR_BUCKET_INSERT_BEFORE(eos, e);
3116 APR_BRIGADE_INSERT_TAIL(b, e);
3120 /* RFC 2616, Section 3.6.1
3122 * If there is an EOS bucket, then prefix it with:
3123 * 1) the last-chunk marker ("0" CRLF)
3125 * 3) the end-of-chunked body CRLF
3127 * If there is no EOS bucket, then do nothing.
3129 * XXX: it would be nice to combine this with the end-of-chunk
3130 * marker above, but this is a bit more straight-forward for
3134 /* XXX: (2) trailers ... does not yet exist */
3135 e = apr_bucket_immortal_create(ASCII_ZERO ASCII_CRLF /* <trailers> */ ASCII_CRLF, 5);
3136 APR_BUCKET_INSERT_BEFORE(eos, e);
3139 /* pass the brigade to the next filter. */
3140 rv = ap_pass_brigade(f->next, b);
3141 if (rv != APR_SUCCESS || eos != NULL) {
3149 static int core_input_filter(ap_filter_t *f, apr_bucket_brigade *b, ap_input_mode_t mode)
3153 if (!f->ctx) { /* If we haven't passed up the socket yet... */
3155 e = apr_bucket_socket_create(f->c->client_socket);
3156 APR_BRIGADE_INSERT_TAIL(b, e);
3160 /* Either some code lost track of the socket
3161 * bucket or we already found out that the
3168 /* Default filter. This filter should almost always be used. Its only job
3169 * is to send the headers if they haven't already been sent, and then send
3172 typedef struct CORE_OUTPUT_FILTER_CTX {
3173 apr_bucket_brigade *b;
3174 } core_output_filter_ctx_t;
3176 #define MAX_IOVEC_TO_WRITE 16
3178 static apr_status_t core_output_filter(ap_filter_t *f, apr_bucket_brigade *b)
3182 core_output_filter_ctx_t *ctx = f->ctx;
3185 f->ctx = ctx = apr_pcalloc(c->pool, sizeof(core_output_filter_ctx_t));
3188 /* If we have a saved brigade, concatenate the new brigade to it */
3190 APR_BRIGADE_CONCAT(ctx->b, b);
3195 /* Perform multiple passes over the brigade, sending batches of output
3196 to the connection. */
3198 apr_size_t nbytes = 0;
3201 /* tail of brigade if we need another pass */
3202 apr_bucket_brigade *more = NULL;
3204 /* one group of iovecs per pass over the brigade */
3205 apr_size_t nvec = 0;
3206 apr_size_t nvec_trailers = 0;
3207 struct iovec vec[MAX_IOVEC_TO_WRITE];
3208 struct iovec vec_trailers[MAX_IOVEC_TO_WRITE];
3210 /* one file per pass over the brigade */
3211 apr_file_t *fd = NULL;
3212 apr_size_t flen = 0;
3213 apr_off_t foffset = 0;
3215 /* Iterate over the brigade: collect iovecs and/or a file */
3216 APR_BRIGADE_FOREACH(e, b) {
3217 if (APR_BUCKET_IS_EOS(e) || APR_BUCKET_IS_FLUSH(e)) {
3220 /* It doesn't make any sense to use sendfile for a file bucket
3221 * that represents 10 bytes.
3223 else if (APR_BUCKET_IS_FILE(e)
3224 && (e->length >= AP_MIN_SENDFILE_BYTES)) {
3225 apr_bucket_shared *s = e->data;
3226 apr_bucket_file *a = s->data;
3228 /* We can't handle more than one file bucket at a time
3229 * so we split here and send the file we have already
3233 more = apr_brigade_split(b, e);
3245 rv = apr_bucket_read(e, &str, &n, APR_BLOCK_READ);
3249 vec[nvec].iov_base = (char*) str;
3250 vec[nvec].iov_len = n;
3254 /* The bucket is a trailer to a file bucket */
3255 vec_trailers[nvec_trailers].iov_base = (char*) str;
3256 vec_trailers[nvec_trailers].iov_len = n;
3262 if ((nvec == MAX_IOVEC_TO_WRITE) ||
3263 (nvec_trailers == MAX_IOVEC_TO_WRITE)) {
3264 /* Split the brigade and break */
3265 if (APR_BUCKET_NEXT(e) != APR_BRIGADE_SENTINEL(b)) {
3266 more = apr_brigade_split(b, APR_BUCKET_NEXT(e));
3272 /* Completed iterating over the brigades, now determine if we want
3273 * to buffer the brigade or send the brigade out on the network.
3277 * 1) we didn't see a file, we don't have more passes over the
3278 * brigade to perform, we haven't accumulated enough bytes to
3279 * send, AND we didn't stop at a FLUSH bucket.
3280 * (IOW, we will save away plain old bytes)
3282 * 2) we hit the EOS and have a keep-alive connection
3283 * (IOW, this response is a bit more complex, but we save it
3284 * with the hope of concatenating with another response)
3286 if ((!fd && !more &&
3287 (nbytes < AP_MIN_BYTES_TO_WRITE) && !APR_BUCKET_IS_FLUSH(e))
3288 || (APR_BUCKET_IS_EOS(e) && c->keepalive)) {
3290 /* NEVER save an EOS in here. If we are saving a brigade with
3291 * an EOS bucket, then we are doing keepalive connections, and
3292 * we want to process to second request fully.
3294 if (APR_BUCKET_IS_EOS(e)) {
3295 APR_BUCKET_REMOVE(e);
3296 apr_bucket_destroy(e);
3298 ap_save_brigade(f, &ctx->b, &b);
3304 #if APR_HAS_SENDFILE
3305 apr_int32_t flags = 0;
3308 memset(&hdtr, '\0', sizeof(hdtr));
3310 hdtr.numheaders = nvec;
3313 if (nvec_trailers) {
3314 hdtr.numtrailers = nvec_trailers;
3315 hdtr.trailers = vec_trailers;
3317 #if APR_HAS_SENDFILE
3318 if (!c->keepalive) {
3319 /* Prepare the socket to be reused */
3320 flags |= APR_SENDFILE_DISCONNECT_SOCKET;
3322 rv = sendfile_it_all(c, /* the connection */
3323 fd, /* the file to send */
3324 &hdtr, /* header and trailer iovecs */
3325 foffset, /* offset in the file to begin
3327 flen, /* length of file */
3328 nbytes + flen, /* total length including
3330 flags); /* apr_sendfile flags */
3332 /* If apr_sendfile() returns APR_ENOTIMPL, call send_the_file()
3333 * to loop on apr_file_read/apr_send to send the file. Our Windows
3334 * binary distributions (which work on Windows 9x/NT) are
3335 * compiled on Windows NT. TransmitFile is not available on
3336 * Windows 95/98 and we discover this at runtime when
3337 * apr_sendfile() returns APR_ENOTIMPL. Having apr_sendfile()
3338 * return APR_ENOTIMPL seems the cleanest way to handle this
3341 if (rv == APR_ENOTIMPL)
3344 apr_size_t unused_bytes_sent;
3346 rv = send_the_file(c, fd, &hdtr, foffset, flen,
3347 &unused_bytes_sent);
3352 apr_size_t unused_bytes_sent;
3354 rv = writev_it_all(c->client_socket,
3356 nbytes, &unused_bytes_sent);
3359 apr_brigade_destroy(b);
3360 if (rv != APR_SUCCESS) {
3361 /* XXX: log the error */
3363 apr_brigade_destroy(more);
3369 } /* end while () */
3374 static void core_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
3376 apr_bucket_init_types(pconf);
3377 apr_bucket_insert_type(&ap_bucket_type_error);
3380 static void core_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
3382 ap_set_version(pconf);
3385 static void core_open_logs(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
3387 ap_open_logs(s, pconf);
3390 static const char *core_method(const request_rec *r)
3393 static unsigned short core_port(const request_rec *r)
3394 { return DEFAULT_HTTP_PORT; }
3396 static void core_insert_filter(request_rec *r)
3399 core_dir_config *conf = (core_dir_config *)
3400 ap_get_module_config(r->per_dir_config,
3402 char **items = (char **)conf->output_filters->elts;
3404 for (i = 0; i < conf->output_filters->nelts; i++) {
3405 char *foobar = items[i];
3406 ap_add_output_filter(foobar, NULL, r, r->connection);
3409 items = (char **)conf->input_filters->elts;
3410 for (i = 0; i < conf->input_filters->nelts; i++) {
3411 char *foobar = items[i];
3412 ap_add_input_filter(foobar, NULL, r, r->connection);
3416 static void register_hooks(apr_pool_t *p)
3418 ap_hook_pre_config(core_pre_config, NULL, NULL, APR_HOOK_REALLY_FIRST);
3419 ap_hook_post_config(core_post_config,NULL,NULL,APR_HOOK_REALLY_FIRST);
3420 ap_hook_translate_name(ap_core_translate,NULL,NULL,APR_HOOK_REALLY_LAST);
3421 ap_hook_pre_connection(ap_pre_http_connection,NULL,NULL,
3422 APR_HOOK_REALLY_LAST);
3423 ap_hook_process_connection(ap_process_http_connection,NULL,NULL,
3424 APR_HOOK_REALLY_LAST);
3425 ap_hook_http_method(core_method,NULL,NULL,APR_HOOK_REALLY_LAST);
3426 ap_hook_default_port(core_port,NULL,NULL,APR_HOOK_REALLY_LAST);
3427 ap_hook_open_logs(core_open_logs,NULL,NULL,APR_HOOK_MIDDLE);
3428 ap_hook_handler(default_handler,NULL,NULL,APR_HOOK_REALLY_LAST);
3429 /* FIXME: I suspect we can eliminate the need for these - Ben */
3430 ap_hook_type_checker(do_nothing,NULL,NULL,APR_HOOK_REALLY_LAST);
3431 ap_hook_access_checker(do_nothing,NULL,NULL,APR_HOOK_REALLY_LAST);
3433 /* register the core's insert_filter hook and register core-provided
3436 ap_hook_insert_filter(core_insert_filter, NULL, NULL, APR_HOOK_MIDDLE);
3438 ap_register_input_filter("HTTP_IN", ap_http_filter, AP_FTYPE_CONNECTION);
3439 ap_register_input_filter("DECHUNK", ap_dechunk_filter, AP_FTYPE_TRANSCODE);
3440 ap_register_input_filter("CORE_IN", core_input_filter, AP_FTYPE_NETWORK);
3441 ap_register_output_filter("HTTP_HEADER", ap_http_header_filter,
3442 AP_FTYPE_HTTP_HEADER);
3443 ap_register_output_filter("CONTENT_LENGTH", ap_content_length_filter,
3444 AP_FTYPE_HTTP_HEADER);
3445 ap_register_output_filter("BYTERANGE", ap_byterange_filter,
3446 AP_FTYPE_HTTP_HEADER);
3447 ap_register_output_filter("CORE", core_output_filter, AP_FTYPE_NETWORK);
3448 ap_register_output_filter("SUBREQ_CORE", ap_sub_req_output_filter,
3450 ap_register_output_filter("CHUNK", chunk_filter, AP_FTYPE_TRANSCODE);
3451 ap_register_output_filter("OLD_WRITE", ap_old_write_filter,
3452 AP_FTYPE_CONTENT - 1);
3455 AP_DECLARE_DATA module core_module = {
3456 STANDARD20_MODULE_STUFF,
3457 create_core_dir_config, /* create per-directory config structure */
3458 merge_core_dir_configs, /* merge per-directory config structures */
3459 create_core_server_config, /* create per-server config structure */
3460 merge_core_server_configs, /* merge per-server config structures */
3461 core_cmds, /* command apr_table_t */
3462 register_hooks /* register hooks */