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 "apr_strings.h"
62 #include "apr_fnmatch.h"
63 #include "apr_thread_proc.h" /* for RLIMIT stuff */
65 #if APR_HAVE_SYS_UIO_H
66 #include <sys/uio.h> /* for iovec */
70 #include "ap_config.h"
72 #include "http_config.h"
73 #include "http_core.h"
74 #include "http_protocol.h" /* For index_of_response(). Grump. */
75 #include "http_request.h"
76 #include "http_vhost.h"
77 #include "http_main.h" /* For the default_handler below... */
81 #include "http_connection.h"
82 #include "ap_buckets.h"
83 #include "util_filter.h"
84 #include "util_ebcdic.h"
87 #ifdef HAVE_SYS_SOCKET_H
88 #include <sys/socket.h>
90 #ifdef HAVE_ARPA_INET_H
91 #include <arpa/inet.h>
97 /* LimitXMLRequestBody handling */
98 #define AP_LIMIT_UNSET ((long) -1)
99 #define AP_DEFAULT_LIMIT_XML_BODY ((size_t)1000000)
101 /* Server core module... This module provides support for really basic
102 * server operations, including options and commands which control the
103 * operation of other modules. Consider this the bureaucracy module.
105 * The core module also defines handlers, etc., do handle just enough
106 * to allow a server with the core module ONLY to actually serve documents
107 * (though it slaps DefaultType on all of 'em); this was useful in testing,
108 * but may not be worth preserving.
110 * This file could almost be mod_core.c, except for the stuff which affects
111 * the http_conf_globals.
114 static void *create_core_dir_config(apr_pool_t *a, char *dir)
116 core_dir_config *conf;
118 conf = (core_dir_config *)apr_pcalloc(a, sizeof(core_dir_config));
119 if (!dir || dir[strlen(dir) - 1] == '/') {
122 else if (strncmp(dir, "proxy:", 6) == 0) {
123 conf->d = apr_pstrdup(a, dir);
126 conf->d = apr_pstrcat(a, dir, "/", NULL);
128 conf->d_is_fnmatch = conf->d ? (apr_is_fnmatch(conf->d) != 0) : 0;
129 conf->d_components = conf->d ? ap_count_dirs(conf->d) : 0;
131 conf->opts = dir ? OPT_UNSET : OPT_UNSET|OPT_ALL;
132 conf->opts_add = conf->opts_remove = OPT_NONE;
133 conf->override = dir ? OR_UNSET : OR_UNSET|OR_ALL;
135 conf->content_md5 = 2;
137 conf->use_canonical_name = USE_CANONICAL_NAME_UNSET;
139 conf->hostname_lookups = HOSTNAME_LOOKUP_UNSET;
140 conf->do_rfc1413 = DEFAULT_RFC1413 | 2; /* set bit 1 to indicate default */
141 conf->satisfy = SATISFY_NOSPEC;
144 conf->limit_cpu = NULL;
146 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
147 conf->limit_mem = NULL;
150 conf->limit_nproc = NULL;
153 conf->limit_req_body = 0;
154 conf->limit_xml_body = AP_LIMIT_UNSET;
155 conf->sec = apr_make_array(a, 2, sizeof(void *));
157 conf->script_interpreter_source = INTERPRETER_SOURCE_UNSET;
160 conf->server_signature = srv_sig_unset;
162 conf->add_default_charset = ADD_DEFAULT_CHARSET_UNSET;
163 conf->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
165 conf->output_filters = apr_make_array(a, 2, sizeof(void *));
166 conf->input_filters = apr_make_array(a, 2, sizeof(void *));
170 static void *merge_core_dir_configs(apr_pool_t *a, void *basev, void *newv)
172 core_dir_config *base = (core_dir_config *)basev;
173 core_dir_config *new = (core_dir_config *)newv;
174 core_dir_config *conf;
177 conf = (core_dir_config *)apr_palloc(a, sizeof(core_dir_config));
178 memcpy((char *)conf, (const char *)base, sizeof(core_dir_config));
179 if (base->response_code_strings) {
180 conf->response_code_strings =
181 apr_palloc(a, sizeof(*conf->response_code_strings)
183 memcpy(conf->response_code_strings, base->response_code_strings,
184 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
188 conf->d_is_fnmatch = new->d_is_fnmatch;
189 conf->d_components = new->d_components;
192 if (new->opts & OPT_UNSET) {
193 /* there was no explicit setting of new->opts, so we merge
194 * preserve the invariant (opts_add & opts_remove) == 0
196 conf->opts_add = (conf->opts_add & ~new->opts_remove) | new->opts_add;
197 conf->opts_remove = (conf->opts_remove & ~new->opts_add)
199 conf->opts = (conf->opts & ~conf->opts_remove) | conf->opts_add;
200 if ((base->opts & OPT_INCNOEXEC) && (new->opts & OPT_INCLUDES)) {
201 conf->opts = (conf->opts & ~OPT_INCNOEXEC) | OPT_INCLUDES;
205 /* otherwise we just copy, because an explicit opts setting
206 * overrides all earlier +/- modifiers
208 conf->opts = new->opts;
209 conf->opts_add = new->opts_add;
210 conf->opts_remove = new->opts_remove;
213 if (!(new->override & OR_UNSET)) {
214 conf->override = new->override;
216 if (new->ap_default_type) {
217 conf->ap_default_type = new->ap_default_type;
220 if (new->ap_auth_type) {
221 conf->ap_auth_type = new->ap_auth_type;
223 if (new->ap_auth_name) {
224 conf->ap_auth_name = new->ap_auth_name;
226 if (new->ap_requires) {
227 conf->ap_requires = new->ap_requires;
230 if (new->response_code_strings) {
231 if (conf->response_code_strings == NULL) {
232 conf->response_code_strings = apr_palloc(a,
233 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
234 memcpy(conf->response_code_strings, new->response_code_strings,
235 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
238 for (i = 0; i < RESPONSE_CODES; ++i) {
239 if (new->response_code_strings[i] != NULL) {
240 conf->response_code_strings[i]
241 = new->response_code_strings[i];
246 if (new->hostname_lookups != HOSTNAME_LOOKUP_UNSET) {
247 conf->hostname_lookups = new->hostname_lookups;
249 if ((new->do_rfc1413 & 2) == 0) {
250 conf->do_rfc1413 = new->do_rfc1413;
252 if ((new->content_md5 & 2) == 0) {
253 conf->content_md5 = new->content_md5;
255 if (new->use_canonical_name != USE_CANONICAL_NAME_UNSET) {
256 conf->use_canonical_name = new->use_canonical_name;
260 if (new->limit_cpu) {
261 conf->limit_cpu = new->limit_cpu;
264 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
265 if (new->limit_mem) {
266 conf->limit_mem = new->limit_mem;
270 if (new->limit_nproc) {
271 conf->limit_nproc = new->limit_nproc;
275 if (new->limit_req_body) {
276 conf->limit_req_body = new->limit_req_body;
279 if (new->limit_xml_body != AP_LIMIT_UNSET)
280 conf->limit_xml_body = new->limit_xml_body;
282 conf->limit_xml_body = base->limit_xml_body;
284 conf->sec = apr_append_arrays(a, base->sec, new->sec);
286 if (new->satisfy != SATISFY_NOSPEC) {
287 conf->satisfy = new->satisfy;
291 if (new->script_interpreter_source != INTERPRETER_SOURCE_UNSET) {
292 conf->script_interpreter_source = new->script_interpreter_source;
296 if (new->server_signature != srv_sig_unset) {
297 conf->server_signature = new->server_signature;
300 if (new->add_default_charset != ADD_DEFAULT_CHARSET_UNSET) {
301 conf->add_default_charset = new->add_default_charset;
302 if (new->add_default_charset_name) {
303 conf->add_default_charset_name = new->add_default_charset_name;
306 conf->output_filters = apr_append_arrays(a, base->output_filters,
307 new->output_filters);
308 conf->input_filters = apr_append_arrays(a, base->input_filters,
314 static void *create_core_server_config(apr_pool_t *a, server_rec *s)
316 core_server_config *conf;
317 int is_virtual = s->is_virtual;
319 conf = (core_server_config *)apr_pcalloc(a, sizeof(core_server_config));
321 conf->gprof_dir = NULL;
323 conf->access_name = is_virtual ? NULL : DEFAULT_ACCESS_FNAME;
324 conf->ap_document_root = is_virtual ? NULL : DOCUMENT_LOCATION;
325 conf->sec = apr_make_array(a, 40, sizeof(void *));
326 conf->sec_url = apr_make_array(a, 40, sizeof(void *));
331 static void *merge_core_server_configs(apr_pool_t *p, void *basev, void *virtv)
333 core_server_config *base = (core_server_config *)basev;
334 core_server_config *virt = (core_server_config *)virtv;
335 core_server_config *conf;
337 conf = (core_server_config *)apr_pcalloc(p, sizeof(core_server_config));
339 if (!conf->access_name) {
340 conf->access_name = base->access_name;
342 if (!conf->ap_document_root) {
343 conf->ap_document_root = base->ap_document_root;
345 conf->sec = apr_append_arrays(p, base->sec, virt->sec);
346 conf->sec_url = apr_append_arrays(p, base->sec_url, virt->sec_url);
351 /* Add per-directory configuration entry (for <directory> section);
352 * these are part of the core server config.
355 AP_CORE_DECLARE(void) ap_add_per_dir_conf(server_rec *s, void *dir_config)
357 core_server_config *sconf = ap_get_module_config(s->module_config,
359 void **new_space = (void **)apr_push_array(sconf->sec);
361 *new_space = dir_config;
364 AP_CORE_DECLARE(void) ap_add_per_url_conf(server_rec *s, void *url_config)
366 core_server_config *sconf = ap_get_module_config(s->module_config,
368 void **new_space = (void **)apr_push_array(sconf->sec_url);
370 *new_space = url_config;
373 AP_CORE_DECLARE(void) ap_add_file_conf(core_dir_config *conf, void *url_config)
375 void **new_space = (void **)apr_push_array(conf->sec);
377 *new_space = url_config;
380 /* core_reorder_directories reorders the directory sections such that the
381 * 1-component sections come first, then the 2-component, and so on, finally
382 * followed by the "special" sections. A section is "special" if it's a regex,
383 * or if it doesn't start with / -- consider proxy: matching. All movements
384 * are in-order to preserve the ordering of the sections from the config files.
385 * See directory_walk().
388 #if defined(HAVE_DRIVE_LETTERS)
389 #define IS_SPECIAL(entry_core) \
390 ((entry_core)->r != NULL \
391 || ((entry_core)->d[0] != '/' && (entry_core)->d[1] != ':'))
392 #elif defined(NETWARE)
393 /* XXX: Fairly certain this is correct... '/' must prefix the path
394 * or else in the case xyz:/ or abc/xyz:/, '/' must follow the ':'.
395 * If there is no leading '/' or embedded ':/', then we are special.
397 #define IS_SPECIAL(entry_core) \
398 ((entry_core)->r != NULL \
399 || ((entry_core)->d[0] != '/' \
400 && strchr((entry_core)->d, ':') \
401 && *(strchr((entry_core)->d, ':') + 1) != '/'))
403 #define IS_SPECIAL(entry_core) \
404 ((entry_core)->r != NULL || (entry_core)->d[0] != '/')
407 /* We need to do a stable sort, qsort isn't stable. So to make it stable
408 * we'll be maintaining the original index into the list, and using it
409 * as the minor key during sorting. The major key is the number of
410 * components (where a "special" section has infinite components).
412 struct reorder_sort_rec {
417 static int reorder_sorter(const void *va, const void *vb)
419 const struct reorder_sort_rec *a = va;
420 const struct reorder_sort_rec *b = vb;
421 core_dir_config *core_a;
422 core_dir_config *core_b;
424 core_a = (core_dir_config *)ap_get_module_config(a->elt, &core_module);
425 core_b = (core_dir_config *)ap_get_module_config(b->elt, &core_module);
426 if (IS_SPECIAL(core_a)) {
427 if (!IS_SPECIAL(core_b)) {
431 else if (IS_SPECIAL(core_b)) {
435 /* we know they're both not special */
436 if (core_a->d_components < core_b->d_components) {
439 else if (core_a->d_components > core_b->d_components) {
443 /* Either they're both special, or they're both not special and have the
444 * same number of components. In any event, we now have to compare
446 return a->orig_index - b->orig_index;
449 void ap_core_reorder_directories(apr_pool_t *p, server_rec *s)
451 core_server_config *sconf;
452 apr_array_header_t *sec;
453 struct reorder_sort_rec *sortbin;
459 sconf = ap_get_module_config(s->module_config, &core_module);
462 elts = (void **)sec->elts;
464 /* we have to allocate tmp space to do a stable sort */
465 apr_create_pool(&tmp, p);
466 sortbin = apr_palloc(tmp, sec->nelts * sizeof(*sortbin));
467 for (i = 0; i < nelts; ++i) {
468 sortbin[i].orig_index = i;
469 sortbin[i].elt = elts[i];
472 qsort(sortbin, nelts, sizeof(*sortbin), reorder_sorter);
474 /* and now copy back to the original array */
475 for (i = 0; i < nelts; ++i) {
476 elts[i] = sortbin[i].elt;
479 apr_destroy_pool(tmp);
482 /*****************************************************************
484 * There are some elements of the core config structures in which
485 * other modules have a legitimate interest (this is ugly, but necessary
486 * to preserve NCSA back-compatibility). So, we have a bunch of accessors
490 AP_DECLARE(int) ap_allow_options(request_rec *r)
492 core_dir_config *conf =
493 (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
498 AP_DECLARE(int) ap_allow_overrides(request_rec *r)
500 core_dir_config *conf;
501 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
504 return conf->override;
507 AP_DECLARE(const char *) ap_auth_type(request_rec *r)
509 core_dir_config *conf;
511 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
513 return conf->ap_auth_type;
516 AP_DECLARE(const char *) ap_auth_name(request_rec *r)
518 core_dir_config *conf;
520 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
522 return conf->ap_auth_name;
525 AP_DECLARE(const char *) ap_default_type(request_rec *r)
527 core_dir_config *conf;
529 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
531 return conf->ap_default_type
532 ? conf->ap_default_type
533 : DEFAULT_CONTENT_TYPE;
536 AP_DECLARE(const char *) ap_document_root(request_rec *r) /* Don't use this! */
538 core_server_config *conf;
540 conf = (core_server_config *)ap_get_module_config(r->server->module_config,
542 return conf->ap_document_root;
545 AP_DECLARE(const apr_array_header_t *) ap_requires(request_rec *r)
547 core_dir_config *conf;
549 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
551 return conf->ap_requires;
554 AP_DECLARE(int) ap_satisfies(request_rec *r)
556 core_dir_config *conf;
558 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
561 return conf->satisfy;
564 /* Should probably just get rid of this... the only code that cares is
565 * part of the core anyway (and in fact, it isn't publicised to other
569 char *ap_response_code_string(request_rec *r, int error_index)
571 core_dir_config *conf;
573 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
576 if (conf->response_code_strings == NULL) {
579 return conf->response_code_strings[error_index];
583 /* Code from Harald Hanche-Olsen <hanche@imf.unit.no> */
584 static apr_inline void do_double_reverse (conn_rec *conn)
589 if (conn->double_reverse) {
593 if (conn->remote_host == NULL || conn->remote_host[0] == '\0') {
594 /* single reverse failed, so don't bother */
595 conn->double_reverse = -1;
598 rv = apr_getaddrinfo(&sa, conn->remote_host, APR_UNSPEC, 0, 0, conn->pool);
599 if (rv == APR_SUCCESS) {
601 if (sa->ipaddr_len == conn->remote_addr->ipaddr_len &&
602 !memcmp(sa->ipaddr_ptr, conn->remote_addr->ipaddr_ptr,
604 conn->double_reverse = 1;
610 conn->double_reverse = -1;
613 AP_DECLARE(const char *) ap_get_remote_host(conn_rec *conn, void *dir_config,
616 int hostname_lookups;
618 /* If we haven't checked the host name, and we want to */
621 ((core_dir_config *)ap_get_module_config(dir_config, &core_module))
623 if (hostname_lookups == HOSTNAME_LOOKUP_UNSET) {
624 hostname_lookups = HOSTNAME_LOOKUP_OFF;
629 hostname_lookups = HOSTNAME_LOOKUP_OFF;
632 if (type != REMOTE_NOLOOKUP
633 && conn->remote_host == NULL
634 && (type == REMOTE_DOUBLE_REV
635 || hostname_lookups != HOSTNAME_LOOKUP_OFF)) {
636 apr_sockaddr_t *remote_addr;
638 apr_get_sockaddr(&remote_addr, APR_REMOTE, conn->client_socket);
639 if (apr_getnameinfo(&conn->remote_host, remote_addr, 0) == APR_SUCCESS) {
640 ap_str_tolower(conn->remote_host);
642 if (hostname_lookups == HOSTNAME_LOOKUP_DOUBLE) {
643 do_double_reverse(conn);
644 if (conn->double_reverse != 1) {
645 conn->remote_host = NULL;
649 /* if failed, set it to the NULL string to indicate error */
650 if (conn->remote_host == NULL) {
651 conn->remote_host = "";
654 if (type == REMOTE_DOUBLE_REV) {
655 do_double_reverse(conn);
656 if (conn->double_reverse == -1) {
662 * Return the desired information; either the remote DNS name, if found,
663 * or either NULL (if the hostname was requested) or the IP address
664 * (if any identifier was requested).
666 if (conn->remote_host != NULL && conn->remote_host[0] != '\0') {
667 return conn->remote_host;
670 if (type == REMOTE_HOST || type == REMOTE_DOUBLE_REV) {
674 return conn->remote_ip;
679 AP_DECLARE(const char *) ap_get_remote_logname(request_rec *r)
681 core_dir_config *dir_conf;
683 if (r->connection->remote_logname != NULL) {
684 return r->connection->remote_logname;
687 /* If we haven't checked the identity, and we want to */
688 dir_conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
691 if (dir_conf->do_rfc1413 & 1) {
692 return ap_rfc1413(r->connection, r->server);
699 /* There are two options regarding what the "name" of a server is. The
700 * "canonical" name as defined by ServerName and Port, or the "client's
701 * name" as supplied by a possible Host: header or full URI. We never
702 * trust the port passed in the client's headers, we always use the
703 * port of the actual socket.
705 * The DNS option to UseCanonicalName causes this routine to do a
706 * reverse lookup on the local IP address of the connection and use
707 * that for the ServerName. This makes its value more reliable while
708 * at the same time allowing Demon's magic virtual hosting to work.
709 * The assumption is that DNS lookups are sufficiently quick...
712 AP_DECLARE(const char *) ap_get_server_name(request_rec *r)
714 conn_rec *conn = r->connection;
717 d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
720 if (d->use_canonical_name == USE_CANONICAL_NAME_OFF) {
721 return r->hostname ? r->hostname : r->server->server_hostname;
723 if (d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
724 if (conn->local_host == NULL) {
725 apr_sockaddr_t *local_addr;
727 apr_get_sockaddr(&local_addr, APR_LOCAL, conn->client_socket);
728 if (apr_getnameinfo(&conn->local_host, local_addr, 0) != APR_SUCCESS)
729 conn->local_host = apr_pstrdup(conn->pool, r->server->server_hostname);
731 ap_str_tolower(conn->local_host);
734 return conn->local_host;
737 return r->server->server_hostname;
740 AP_DECLARE(apr_port_t) ap_get_server_port(const request_rec *r)
744 (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
746 port = r->server->port ? r->server->port : ap_default_port(r);
748 if (d->use_canonical_name == USE_CANONICAL_NAME_OFF
749 || d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
751 apr_sockaddr_t *localsa;
753 apr_get_sockaddr(&localsa, APR_LOCAL, r->connection->client_socket);
754 apr_get_port(&port, localsa);
761 AP_DECLARE(char *) ap_construct_url(apr_pool_t *p, const char *uri,
764 unsigned port = ap_get_server_port(r);
765 const char *host = ap_get_server_name(r);
767 if (ap_is_default_port(port, r)) {
768 return apr_pstrcat(p, ap_http_method(r), "://", host, uri, NULL);
770 return apr_psprintf(p, "%s://%s:%u%s", ap_http_method(r), host, port, uri);
773 AP_DECLARE(unsigned long) ap_get_limit_req_body(const request_rec *r)
776 (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
778 return d->limit_req_body;
782 static apr_status_t get_win32_registry_default_value(apr_pool_t *p, HKEY hkey,
789 DWORD result = RegOpenKeyEx(hkey, relativepath, 0,
790 KEY_QUERY_VALUE, &hkeyOpen);
792 if (result != ERROR_SUCCESS)
793 return APR_FROM_OS_ERROR(result);
795 /* Read to NULL buffer to determine value size */
796 result = RegQueryValueEx(hkeyOpen, "", 0, &type, NULL, &size);
798 if (result == ERROR_SUCCESS) {
799 if ((size < 2) || (type != REG_SZ && type != REG_EXPAND_SZ)) {
800 result = ERROR_INVALID_PARAMETER;
803 *value = apr_palloc(p, size);
804 /* Read value based on size query above */
805 result = RegQueryValueEx(hkeyOpen, "", 0, &type, *value, &size);
809 /* TODO: This might look fine, but we need to provide some warning
810 * somewhere that some environment variables may -not- be translated,
811 * seeing as we may have chopped the environment table down somewhat.
813 if ((result == ERROR_SUCCESS) && (type == REG_EXPAND_SZ))
816 size = ExpandEnvironmentStrings(tmp, *value, 0);
818 *value = apr_palloc(p, size);
819 size = ExpandEnvironmentStrings(tmp, *value, size);
823 RegCloseKey(hkeyOpen);
824 return APR_FROM_OS_ERROR(result);
827 static char* get_interpreter_from_win32_registry(apr_pool_t *p, const char* ext,
828 char** arguments, int strict)
830 char execcgi_path[] = "SHELL\\EXECCGI\\COMMAND";
831 char execopen_path[] = "SHELL\\OPEN\\COMMAND";
832 char typeName[MAX_PATH];
833 int cmdOfName = FALSE;
845 * Future optimization:
846 * When the registry is successfully searched, store the strings for
847 * interpreter and arguments in an ext hash to speed up subsequent look-ups
850 /* Open the key associated with the script filetype extension */
851 result = RegOpenKeyEx(HKEY_CLASSES_ROOT, ext, 0, KEY_QUERY_VALUE,
854 if (result != ERROR_SUCCESS)
857 /* Retrieve the name of the script filetype extension */
858 size = sizeof(typeName);
859 result = RegQueryValueEx(hkeyType, "", NULL, &type, typeName, &size);
861 if (result == ERROR_SUCCESS && type == REG_SZ && typeName[0]) {
862 /* Open the key associated with the script filetype extension */
863 result = RegOpenKeyEx(HKEY_CLASSES_ROOT, typeName, 0,
864 KEY_QUERY_VALUE, &hkeyName);
866 if (result == ERROR_SUCCESS)
870 /* Open the key for the script command path by:
872 * 1) the 'named' filetype key for ExecCGI/Command
873 * 2) the extension's type key for ExecCGI/Command
875 * and if the strict arg is false, then continue trying:
877 * 3) the 'named' filetype key for Open/Command
878 * 4) the extension's type key for Open/Command
882 result = get_win32_registry_default_value(p, hkeyName,
883 execcgi_path, &buffer);
886 if (!cmdOfName || (result != ERROR_SUCCESS)) {
887 result = get_win32_registry_default_value(p, hkeyType,
888 execcgi_path, &buffer);
891 if (!strict && cmdOfName && (result != ERROR_SUCCESS)) {
892 result = get_win32_registry_default_value(p, hkeyName,
893 execopen_path, &buffer);
896 if (!strict && (result != ERROR_SUCCESS)) {
897 result = get_win32_registry_default_value(p, hkeyType,
898 execopen_path, &buffer);
902 RegCloseKey(hkeyName);
904 RegCloseKey(hkeyType);
906 if (result != ERROR_SUCCESS)
910 * The canonical way shell command entries are entered in the Win32
911 * registry is as follows:
912 * shell [options] "%1" [args]
914 * shell - full path name to interpreter or shell to run.
915 * E.g., c:\usr\local\ntreskit\perl\bin\perl.exe
916 * options - optional switches
918 * "%1" - Place holder for file to run the shell against.
920 * options - additional arguments
923 * If we find a %1 or a quoted %1, lop off the remainder to arguments.
925 if (buffer && *buffer) {
926 if ((s = strstr(buffer, "\"%1")))
931 else if ((s = strstr(buffer, "%1")))
934 *arguments = buffer + 2;
937 *arguments = strchr(buffer, '\0');
938 while (**arguments && isspace(**arguments))
945 AP_DECLARE (file_type_e) ap_get_win32_interpreter(const request_rec *r,
955 file_type_e fileType = eFileTypeUNKNOWN;
957 char *exename = NULL;
959 d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
962 /* Find the file extension */
963 exename = strrchr(r->filename, '/');
965 exename = strrchr(r->filename, '\\');
968 exename = r->filename;
973 ext = strrchr(exename, '.');
975 if (ext && (!strcasecmp(ext,".bat") || !strcasecmp(ext,".cmd")))
977 char *comspec = getenv("COMSPEC");
979 *interpreter = apr_pstrcat(r->pool, "\"", comspec, "\" /c ", NULL);
980 return eFileTypeSCRIPT;
982 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r->server,
983 "Failed to start a '%s' file as a script." APR_EOL_STR
984 "\tCOMSPEC variable is missing from the environment.", ext);
985 return eFileTypeUNKNOWN;
988 /* If the file has an extension and it is not .com and not .exe and
989 * we've been instructed to search the registry, then do it!
991 if (ext && strcasecmp(ext,".exe") && strcasecmp(ext,".com") &&
992 (d->script_interpreter_source == INTERPRETER_SOURCE_REGISTRY ||
993 d->script_interpreter_source == INTERPRETER_SOURCE_REGISTRY_STRICT)) {
994 /* Check the registry */
995 int strict = (d->script_interpreter_source
996 == INTERPRETER_SOURCE_REGISTRY_STRICT);
997 *interpreter = get_interpreter_from_win32_registry(r->pool, ext,
1000 return eFileTypeSCRIPT;
1001 else if (d->script_interpreter_source == INTERPRETER_SOURCE_REGISTRY_STRICT) {
1002 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r->server,
1003 "ScriptInterpreterSource config directive set to \"registry-strict\"." APR_EOL_STR
1004 "\tInterpreter not found for files of type '%s'.", ext);
1005 return eFileTypeUNKNOWN;
1009 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r->server,
1010 "ScriptInterpreterSource config directive set to \"registry\"." APR_EOL_STR
1011 "\tInterpreter not found for files of type '%s', "
1012 "trying \"script\" method...", ext);
1016 /* Need to peek into the file figure out what it really is... */
1017 hFile = CreateFile(r->filename, GENERIC_READ, FILE_SHARE_READ, NULL,
1018 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1019 if (hFile == INVALID_HANDLE_VALUE) {
1020 return eFileTypeUNKNOWN;
1022 bResult = ReadFile(hFile, (void*) &buffer, sizeof(buffer) - 1,
1024 if (!bResult || (nBytesRead == 0)) {
1025 ap_log_rerror(APLOG_MARK, APLOG_ERR, GetLastError(), r,
1026 "ReadFile(%s) failed", r->filename);
1028 return eFileTypeUNKNOWN;
1031 buffer[nBytesRead] = '\0';
1033 /* Script or executable, that is the question... */
1034 if ((buffer[0] == '#') && (buffer[1] == '!')) {
1035 /* Assuming file is a script since it starts with a shebang */
1036 fileType = eFileTypeSCRIPT;
1037 for (i = 2; i < sizeof(buffer); i++) {
1038 if ((buffer[i] == '\r')
1039 || (buffer[i] == '\n')) {
1044 for (i = 2; buffer[i] == ' ' ; ++i)
1046 *interpreter = apr_pstrdup(r->pool, buffer + i );
1049 /* Not a script, is it an executable? */
1050 IMAGE_DOS_HEADER *hdr = (IMAGE_DOS_HEADER*)buffer;
1051 if ((nBytesRead >= sizeof(IMAGE_DOS_HEADER)) && (hdr->e_magic == IMAGE_DOS_SIGNATURE)) {
1052 if (hdr->e_lfarlc < 0x40)
1053 fileType = eFileTypeEXE16;
1055 fileType = eFileTypeEXE32;
1058 fileType = eFileTypeUNKNOWN;
1065 /*****************************************************************
1067 * Commands... this module handles almost all of the NCSA httpd.conf
1068 * commands, but most of the old srm.conf is in the the modules.
1072 /* returns a parent if it matches the given directive */
1073 static const ap_directive_t * find_parent(const ap_directive_t *dirp,
1076 while (dirp->parent != NULL) {
1077 dirp = dirp->parent;
1078 /* ### it would be nice to have atom-ized directives */
1079 if (strcasecmp(dirp->directive, what) == 0)
1085 AP_DECLARE(const char *) ap_check_cmd_context(cmd_parms *cmd,
1088 const char *gt = (cmd->cmd->name[0] == '<'
1089 && cmd->cmd->name[strlen(cmd->cmd->name)-1] != '>')
1091 const ap_directive_t *found;
1093 if ((forbidden & NOT_IN_VIRTUALHOST) && cmd->server->is_virtual) {
1094 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1095 " cannot occur within <VirtualHost> section", NULL);
1098 if ((forbidden & NOT_IN_LIMIT) && cmd->limited != -1) {
1099 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1100 " cannot occur within <Limit> section", NULL);
1103 if ((forbidden & NOT_IN_DIR_LOC_FILE) == NOT_IN_DIR_LOC_FILE
1104 && cmd->path != NULL) {
1105 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1106 " cannot occur within <Directory/Location/Files> "
1110 if (((forbidden & NOT_IN_DIRECTORY)
1111 && ((found = find_parent(cmd->directive, "<Directory"))
1112 || (found = find_parent(cmd->directive, "<DirectoryMatch"))))
1113 || ((forbidden & NOT_IN_LOCATION)
1114 && ((found = find_parent(cmd->directive, "<Location"))
1115 || (found = find_parent(cmd->directive, "<LocationMatch"))))
1116 || ((forbidden & NOT_IN_FILES)
1117 && ((found = find_parent(cmd->directive, "<Files"))
1118 || (found = find_parent(cmd->directive, "<FilesMatch"))))) {
1119 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1120 " cannot occur within ", found->directive,
1127 static const char *set_access_name(cmd_parms *cmd, void *dummy,
1130 void *sconf = cmd->server->module_config;
1131 core_server_config *conf = ap_get_module_config(sconf, &core_module);
1133 const char *err = ap_check_cmd_context(cmd,
1134 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1139 conf->access_name = apr_pstrdup(cmd->pool, arg);
1144 static const char *set_gprof_dir(cmd_parms *cmd, void *dummy, char *arg)
1146 void *sconf = cmd->server->module_config;
1147 core_server_config *conf = ap_get_module_config(sconf, &core_module);
1149 const char *err = ap_check_cmd_context(cmd,
1150 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1155 conf->gprof_dir = apr_pstrdup(cmd->pool, arg);
1160 static const char *set_add_default_charset(cmd_parms *cmd,
1161 void *d_, const char *arg)
1163 core_dir_config *d=d_;
1165 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1169 if (!strcasecmp(arg, "Off")) {
1170 d->add_default_charset = ADD_DEFAULT_CHARSET_OFF;
1172 else if (!strcasecmp(arg, "On")) {
1173 d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1174 d->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
1177 d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1178 d->add_default_charset_name = arg;
1183 static const char *set_document_root(cmd_parms *cmd, void *dummy,
1186 void *sconf = cmd->server->module_config;
1187 core_server_config *conf = ap_get_module_config(sconf, &core_module);
1189 const char *err = ap_check_cmd_context(cmd,
1190 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1195 arg = ap_os_canonical_filename(cmd->pool, arg);
1196 if (/* TODO: ap_configtestonly && ap_docrootcheck && */ !ap_is_directory(cmd->pool, arg)) {
1197 if (cmd->server->is_virtual) {
1198 ap_log_perror(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, cmd->pool,
1199 "Warning: DocumentRoot [%s] does not exist",
1203 return "DocumentRoot must be a directory";
1207 conf->ap_document_root = arg;
1211 AP_DECLARE(void) ap_custom_response(request_rec *r, int status, char *string)
1213 core_dir_config *conf =
1214 ap_get_module_config(r->per_dir_config, &core_module);
1217 if(conf->response_code_strings == NULL) {
1218 conf->response_code_strings =
1219 apr_pcalloc(r->pool,
1220 sizeof(*conf->response_code_strings) *
1224 idx = ap_index_of_response(status);
1226 conf->response_code_strings[idx] =
1227 ((ap_is_url(string) || (*string == '/')) && (*string != '"')) ?
1228 apr_pstrdup(r->pool, string) : apr_pstrcat(r->pool, "\"", string, NULL);
1231 static const char *set_error_document(cmd_parms *cmd, void *conf_,
1232 const char *errno_str, const char *msg)
1234 core_dir_config *conf=conf_;
1235 int error_number, index_number, idx500;
1236 enum { MSG, LOCAL_PATH, REMOTE_PATH } what = MSG;
1238 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1243 /* 1st parameter should be a 3 digit number, which we recognize;
1244 * convert it into an array index
1246 error_number = atoi(errno_str);
1247 idx500 = ap_index_of_response(HTTP_INTERNAL_SERVER_ERROR);
1249 if (error_number == HTTP_INTERNAL_SERVER_ERROR) {
1250 index_number = idx500;
1252 else if ((index_number = ap_index_of_response(error_number)) == idx500) {
1253 return apr_pstrcat(cmd->pool, "Unsupported HTTP response code ",
1257 /* Heuristic to determine second argument. */
1258 if (ap_strchr_c(msg,' '))
1260 else if (msg[0] == '/')
1262 else if (ap_is_url(msg))
1267 /* The entry should be ignored if it is a full URL for a 401 error */
1269 if (error_number == 401 && what == REMOTE_PATH) {
1270 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, cmd->server,
1271 "cannot use a full URL in a 401 ErrorDocument "
1272 "directive --- ignoring!");
1274 else { /* Store it... */
1275 if (conf->response_code_strings == NULL) {
1276 conf->response_code_strings =
1277 apr_pcalloc(cmd->pool,
1278 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
1280 /* hack. Prefix a " if it is a msg; as that is what
1281 * http_protocol.c relies on to distinguish between
1282 * a msg and a (local) path.
1284 conf->response_code_strings[index_number] = (what == MSG) ?
1285 apr_pstrcat(cmd->pool, "\"",msg,NULL) :
1286 apr_pstrdup(cmd->pool, msg);
1292 static const char *set_override(cmd_parms *cmd, void *d_, const char *l)
1294 core_dir_config *d=d_;
1297 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1302 d->override = OR_NONE;
1304 w = ap_getword_conf(cmd->pool, &l);
1305 if (!strcasecmp(w, "Limit")) {
1306 d->override |= OR_LIMIT;
1308 else if (!strcasecmp(w, "Options")) {
1309 d->override |= OR_OPTIONS;
1311 else if (!strcasecmp(w, "FileInfo")) {
1312 d->override |= OR_FILEINFO;
1314 else if (!strcasecmp(w, "AuthConfig")) {
1315 d->override |= OR_AUTHCFG;
1317 else if (!strcasecmp(w, "Indexes")) {
1318 d->override |= OR_INDEXES;
1320 else if (!strcasecmp(w, "None")) {
1321 d->override = OR_NONE;
1323 else if (!strcasecmp(w, "All")) {
1324 d->override = OR_ALL;
1327 return apr_pstrcat(cmd->pool, "Illegal override option ", w, NULL);
1329 d->override &= ~OR_UNSET;
1335 static const char *set_options(cmd_parms *cmd, void *d_, const char *l)
1337 core_dir_config *d=d_;
1338 allow_options_t opt;
1343 char *w = ap_getword_conf(cmd->pool, &l);
1346 if (*w == '+' || *w == '-') {
1354 if (!strcasecmp(w, "Indexes")) {
1357 else if (!strcasecmp(w, "Includes")) {
1360 else if (!strcasecmp(w, "IncludesNOEXEC")) {
1361 opt = (OPT_INCLUDES | OPT_INCNOEXEC);
1363 else if (!strcasecmp(w, "FollowSymLinks")) {
1364 opt = OPT_SYM_LINKS;
1366 else if (!strcasecmp(w, "SymLinksIfOwnerMatch")) {
1367 opt = OPT_SYM_OWNER;
1369 else if (!strcasecmp(w, "execCGI")) {
1372 else if (!strcasecmp(w, "MultiViews")) {
1375 else if (!strcasecmp(w, "RunScripts")) { /* AI backcompat. Yuck */
1376 opt = OPT_MULTI|OPT_EXECCGI;
1378 else if (!strcasecmp(w, "None")) {
1381 else if (!strcasecmp(w, "All")) {
1385 return apr_pstrcat(cmd->pool, "Illegal option ", w, NULL);
1388 /* we ensure the invariant (d->opts_add & d->opts_remove) == 0 */
1389 if (action == '-') {
1390 d->opts_remove |= opt;
1391 d->opts_add &= ~opt;
1394 else if (action == '+') {
1396 d->opts_remove &= ~opt;
1407 static const char *satisfy(cmd_parms *cmd, void *c_, const char *arg)
1409 core_dir_config *c=c_;
1411 if (!strcasecmp(arg, "all")) {
1412 c->satisfy = SATISFY_ALL;
1414 else if (!strcasecmp(arg, "any")) {
1415 c->satisfy = SATISFY_ANY;
1418 return "Satisfy either 'any' or 'all'.";
1423 static const char *require(cmd_parms *cmd, void *c_, const char *arg)
1426 core_dir_config *c=c_;
1428 if (!c->ap_requires) {
1429 c->ap_requires = apr_make_array(cmd->pool, 2, sizeof(require_line));
1431 r = (require_line *)apr_push_array(c->ap_requires);
1432 r->requirement = apr_pstrdup(cmd->pool, arg);
1433 r->method_mask = cmd->limited;
1437 AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd, void *dummy,
1439 const char *limited_methods = ap_getword(cmd->pool, &arg, '>');
1440 void *tog = cmd->cmd->cmd_data;
1444 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1449 while (limited_methods[0]) {
1450 char *method = ap_getword_conf(cmd->pool, &limited_methods);
1451 int methnum = ap_method_number_of(method);
1453 if (methnum == M_TRACE && !tog) {
1454 return "TRACE cannot be controlled by <Limit>";
1456 else if (methnum == M_INVALID) {
1458 register int i, j, k;
1461 * Deal with <Limit> by adding the method to the list.
1464 if (cmd->limited_xmethods == NULL) {
1465 cmd->limited_xmethods = apr_make_array(cmd->pool, 2,
1468 xmethod = (char **) apr_push_array(cmd->limited_xmethods);
1469 *xmethod = apr_pstrdup(cmd->pool, method);
1472 * <LimitExcept>, so remove any/all occurrences of the method
1473 * in the extension array.
1475 else if ((cmd->limited_xmethods != NULL)
1476 && (cmd->limited_xmethods->nelts != 0)) {
1477 xmethod = (char **) cmd->limited_xmethods->elts;
1478 for (i = 0; i < cmd->limited_xmethods->nelts; ) {
1479 if (strcmp(xmethod[i], method) == 0) {
1480 for (j = i, k = i + 1;
1481 k < cmd->limited_xmethods->nelts;
1483 xmethod[j] = xmethod[k];
1485 cmd->limited_xmethods->nelts--;
1490 limited |= (1 << methnum);
1493 /* Killing two features with one function,
1494 * if (tog == NULL) <Limit>, else <LimitExcept>
1496 cmd->limited = tog ? ~limited : limited;
1498 errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context);
1505 /* We use this in <DirectoryMatch> and <FilesMatch>, to ensure that
1506 * people don't get bitten by wrong-cased regex matches
1510 #define USE_ICASE REG_ICASE
1516 * Report a missing-'>' syntax error.
1518 static char *unclosed_directive(cmd_parms *cmd)
1520 return apr_pstrcat(cmd->pool, cmd->cmd->name,
1521 "> directive missing closing '>'", NULL);
1524 static const char *dirsection(cmd_parms *cmd, void *mconfig, const char *arg)
1527 const char *endp = ap_strrchr_c(arg, '>');
1528 int old_overrides = cmd->override;
1529 char *old_path = cmd->path;
1530 core_dir_config *conf;
1531 void *new_dir_conf = ap_create_per_dir_config(cmd->pool);
1533 const command_rec *thiscmd = cmd->cmd;
1535 const char *err = ap_check_cmd_context(cmd,
1536 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1542 return unclosed_directive(cmd);
1545 arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1547 cmd->path = ap_getword_conf(cmd->pool, &arg);
1548 cmd->override = OR_ALL|ACCESS_CONF;
1550 if (thiscmd->cmd_data) { /* <DirectoryMatch> */
1551 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1553 else if (!strcmp(cmd->path, "~")) {
1554 cmd->path = ap_getword_conf(cmd->pool, &arg);
1555 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1557 #if defined(HAVE_DRIVE_LETTERS) || defined(NETWARE)
1558 else if (strcmp(cmd->path, "/") == 0) {
1559 /* Treat 'default' path / as an inalienable root */
1560 cmd->path = apr_pstrdup(cmd->pool, cmd->path);
1563 #if defined(HAVE_UNC_PATHS)
1564 else if (strcmp(cmd->path, "//") == 0) {
1565 /* Treat UNC path // as an inalienable root */
1566 cmd->path = apr_pstrdup(cmd->pool, cmd->path);
1570 /* Ensure that the pathname is canonical */
1571 cmd->path = ap_os_canonical_filename(cmd->pool, cmd->path);
1574 /* initialize our config and fetch it */
1575 conf = (core_dir_config *)ap_set_config_vectors(cmd, new_dir_conf,
1578 errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_dir_conf);
1584 ap_add_per_dir_conf(cmd->server, new_dir_conf);
1587 return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1588 "> arguments not (yet) supported.", NULL);
1591 cmd->path = old_path;
1592 cmd->override = old_overrides;
1597 static const char *urlsection(cmd_parms *cmd, void *mconfig, const char *arg)
1600 const char *endp = ap_strrchr_c(arg, '>');
1601 int old_overrides = cmd->override;
1602 char *old_path = cmd->path;
1603 core_dir_config *conf;
1605 const command_rec *thiscmd = cmd->cmd;
1607 void *new_url_conf = ap_create_per_dir_config(cmd->pool);
1609 const char *err = ap_check_cmd_context(cmd,
1610 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1616 return unclosed_directive(cmd);
1619 arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1621 cmd->path = ap_getword_conf(cmd->pool, &arg);
1622 cmd->override = OR_ALL|ACCESS_CONF;
1624 if (thiscmd->cmd_data) { /* <LocationMatch> */
1625 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1627 else if (!strcmp(cmd->path, "~")) {
1628 cmd->path = ap_getword_conf(cmd->pool, &arg);
1629 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1632 /* initialize our config and fetch it */
1633 conf = (core_dir_config *)ap_set_config_vectors(cmd, new_url_conf,
1636 errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_url_conf);
1640 conf->d = apr_pstrdup(cmd->pool, cmd->path); /* No mangling, please */
1641 conf->d_is_fnmatch = apr_is_fnmatch(conf->d) != 0;
1644 ap_add_per_url_conf(cmd->server, new_url_conf);
1647 return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1648 "> arguments not (yet) supported.", NULL);
1651 cmd->path = old_path;
1652 cmd->override = old_overrides;
1657 static const char *filesection(cmd_parms *cmd, void *mconfig, const char *arg)
1660 const char *endp = ap_strrchr_c(arg, '>');
1661 int old_overrides = cmd->override;
1662 char *old_path = cmd->path;
1663 core_dir_config *conf;
1665 const command_rec *thiscmd = cmd->cmd;
1666 core_dir_config *c=mconfig;
1668 void *new_file_conf = ap_create_per_dir_config(cmd->pool);
1670 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT|NOT_IN_LOCATION);
1676 return unclosed_directive(cmd);
1679 arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1681 cmd->path = ap_getword_conf(cmd->pool, &arg);
1682 /* Only if not an .htaccess file */
1684 cmd->override = OR_ALL|ACCESS_CONF;
1687 if (thiscmd->cmd_data) { /* <FilesMatch> */
1688 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1690 else if (!strcmp(cmd->path, "~")) {
1691 cmd->path = ap_getword_conf(cmd->pool, &arg);
1692 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1695 /* Ensure that the pathname is canonical */
1696 cmd->path = ap_os_canonical_filename(cmd->pool, cmd->path);
1699 /* initialize our config and fetch it */
1700 conf = (core_dir_config *)ap_set_config_vectors(cmd, new_file_conf,
1703 errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_file_conf);
1707 conf->d = cmd->path;
1708 conf->d_is_fnmatch = apr_is_fnmatch(conf->d) != 0;
1711 ap_add_file_conf(c, new_file_conf);
1714 return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1715 "> arguments not (yet) supported.", NULL);
1718 cmd->path = old_path;
1719 cmd->override = old_overrides;
1724 static const char *start_ifmod(cmd_parms *cmd, void *mconfig, const char *arg)
1726 const char *endp = ap_strrchr_c(arg, '>');
1727 int not = (arg[0] == '!');
1731 return unclosed_directive(cmd);
1734 arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1740 found = ap_find_linked_module(arg);
1742 if ((!not && found) || (not && !found)) {
1743 ap_directive_t *parent = NULL;
1744 ap_directive_t *current = NULL;
1747 retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd,
1748 ¤t, &parent, "<IfModule");
1749 *(ap_directive_t **)mconfig = current;
1753 *(ap_directive_t **)mconfig = NULL;
1754 return ap_soak_end_container(cmd, "<IfModule");
1758 AP_DECLARE(int) ap_exists_config_define(const char *name)
1763 defines = (char **)ap_server_config_defines->elts;
1764 for (i = 0; i < ap_server_config_defines->nelts; i++) {
1765 if (strcmp(defines[i], name) == 0) {
1772 static const char *start_ifdefine(cmd_parms *cmd, void *dummy, const char *arg)
1778 endp = ap_strrchr_c(arg, '>');
1780 return unclosed_directive(cmd);
1783 arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1785 if (arg[0] == '!') {
1790 defined = ap_exists_config_define(arg);
1791 if ((!not && defined) || (not && !defined)) {
1792 ap_directive_t *parent = NULL;
1793 ap_directive_t *current = NULL;
1796 retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd,
1797 ¤t, &parent, "<IfDefine");
1798 *(ap_directive_t **)dummy = current;
1802 *(ap_directive_t **)dummy = NULL;
1803 return ap_soak_end_container(cmd, "<IfDefine");
1807 /* httpd.conf commands... beginning with the <VirtualHost> business */
1809 static const char *virtualhost_section(cmd_parms *cmd, void *dummy,
1812 server_rec *main_server = cmd->server, *s;
1814 const char *endp = ap_strrchr_c(arg, '>');
1815 apr_pool_t *p = cmd->pool;
1817 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1823 return unclosed_directive(cmd);
1826 arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1828 /* FIXME: There's another feature waiting to happen here -- since you
1829 can now put multiple addresses/names on a single <VirtualHost>
1830 you might want to use it to group common definitions and then
1831 define other "subhosts" with their individual differences. But
1832 personally I'd rather just do it with a macro preprocessor. -djg */
1833 if (main_server->is_virtual) {
1834 return "<VirtualHost> doesn't nest!";
1837 errmsg = ap_init_virtual_host(p, arg, main_server, &s);
1842 s->next = main_server->next;
1843 main_server->next = s;
1845 s->defn_name = cmd->directive->filename;
1846 s->defn_line_number = cmd->directive->line_num;
1850 errmsg = ap_walk_config(cmd->directive->first_child, cmd,
1851 s->lookup_defaults);
1853 cmd->server = main_server;
1858 static const char *set_server_alias(cmd_parms *cmd, void *dummy,
1861 if (!cmd->server->names) {
1862 return "ServerAlias only used in <VirtualHost>";
1865 char **item, *name = ap_getword_conf(cmd->pool, &arg);
1866 if (ap_is_matchexp(name)) {
1867 item = (char **)apr_push_array(cmd->server->wild_names);
1870 item = (char **)apr_push_array(cmd->server->names);
1877 static const char *add_filter(cmd_parms *cmd, void *dummy, const char *arg)
1879 core_dir_config *conf = dummy;
1882 newfilter = (char **)apr_push_array(conf->output_filters);
1883 *newfilter = apr_pstrdup(cmd->pool, arg);
1887 static const char *add_input_filter(cmd_parms *cmd, void *dummy, const char *arg)
1889 core_dir_config *conf = dummy;
1892 newfilter = (char **)apr_push_array(conf->input_filters);
1893 *newfilter = apr_pstrdup(cmd->pool, arg);
1897 static const char *add_module_command(cmd_parms *cmd, void *dummy,
1900 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1905 if (!ap_add_named_module(arg)) {
1906 return apr_pstrcat(cmd->pool, "Cannot add module via name '", arg,
1907 "': not in list of loaded modules", NULL);
1909 *(ap_directive_t **)dummy = NULL;
1913 static const char *clear_module_list_command(cmd_parms *cmd, void *dummy)
1915 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1920 ap_clear_module_list();
1921 *(ap_directive_t **)dummy = NULL;
1925 static const char *set_server_string_slot(cmd_parms *cmd, void *dummy,
1928 /* This one's pretty generic... */
1930 int offset = (int)(long)cmd->info;
1931 char *struct_ptr = (char *)cmd->server;
1933 const char *err = ap_check_cmd_context(cmd,
1934 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1939 *(const char **)(struct_ptr + offset) = arg;
1943 static const char *server_port(cmd_parms *cmd, void *dummy, const char *arg)
1945 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1952 if (port <= 0 || port >= 65536) { /* 65536 == 1<<16 */
1953 return apr_pstrcat(cmd->temp_pool, "The port number \"", arg,
1954 "\" is outside the appropriate range "
1955 "(i.e., 1..65535).", NULL);
1957 cmd->server->port = port;
1961 static const char *set_signature_flag(cmd_parms *cmd, void *d_,
1964 core_dir_config *d=d_;
1966 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1971 if (strcasecmp(arg, "On") == 0) {
1972 d->server_signature = srv_sig_on;
1974 else if (strcasecmp(arg, "Off") == 0) {
1975 d->server_signature = srv_sig_off;
1977 else if (strcasecmp(arg, "EMail") == 0) {
1978 d->server_signature = srv_sig_withmail;
1981 return "ServerSignature: use one of: off | on | email";
1986 static const char *set_server_root(cmd_parms *cmd, void *dummy,
1989 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1995 arg = ap_os_canonical_filename(cmd->pool, arg);
1997 if (!ap_is_directory(cmd->pool, arg)) {
1998 return "ServerRoot must be a valid directory";
2000 ap_server_root = arg;
2004 static const char *set_timeout(cmd_parms *cmd, void *dummy, const char *arg)
2006 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2011 cmd->server->timeout = atoi(arg);
2015 static const char *set_keep_alive_timeout(cmd_parms *cmd, void *dummy,
2018 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2023 cmd->server->keep_alive_timeout = atoi(arg);
2027 static const char *set_keep_alive(cmd_parms *cmd, void *dummy,
2030 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2035 /* We've changed it to On/Off, but used to use numbers
2036 * so we accept anything but "Off" or "0" as "On"
2038 if (!strcasecmp(arg, "off") || !strcmp(arg, "0")) {
2039 cmd->server->keep_alive = 0;
2042 cmd->server->keep_alive = 1;
2047 static const char *set_keep_alive_max(cmd_parms *cmd, void *dummy,
2050 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2055 cmd->server->keep_alive_max = atoi(arg);
2059 static const char *set_idcheck(cmd_parms *cmd, void *d_, int arg)
2061 core_dir_config *d=d_;
2062 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2067 d->do_rfc1413 = arg != 0;
2071 static const char *set_hostname_lookups(cmd_parms *cmd, void *d_,
2074 core_dir_config *d=d_;
2076 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2081 if (!strcasecmp(arg, "on")) {
2082 d->hostname_lookups = HOSTNAME_LOOKUP_ON;
2084 else if (!strcasecmp(arg, "off")) {
2085 d->hostname_lookups = HOSTNAME_LOOKUP_OFF;
2087 else if (!strcasecmp(arg, "double")) {
2088 d->hostname_lookups = HOSTNAME_LOOKUP_DOUBLE;
2091 return "parameter must be 'on', 'off', or 'double'";
2096 static const char *set_serverpath(cmd_parms *cmd, void *dummy,
2099 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2104 cmd->server->path = arg;
2105 cmd->server->pathlen = strlen(arg);
2109 static const char *set_content_md5(cmd_parms *cmd, void *d_, int arg)
2111 core_dir_config *d=d_;
2112 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2117 d->content_md5 = arg != 0;
2121 static const char *set_use_canonical_name(cmd_parms *cmd, void *d_,
2124 core_dir_config *d=d_;
2125 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2130 if (strcasecmp(arg, "on") == 0) {
2131 d->use_canonical_name = USE_CANONICAL_NAME_ON;
2133 else if (strcasecmp(arg, "off") == 0) {
2134 d->use_canonical_name = USE_CANONICAL_NAME_OFF;
2136 else if (strcasecmp(arg, "dns") == 0) {
2137 d->use_canonical_name = USE_CANONICAL_NAME_DNS;
2140 return "parameter must be 'on', 'off', or 'dns'";
2146 static const char *include_config (cmd_parms *cmd, void *dummy,
2149 ap_directive_t *conftree = NULL;
2151 ap_process_resource_config(cmd->server,
2152 ap_server_root_relative(cmd->pool, name),
2153 &conftree, cmd->pool, cmd->temp_pool);
2154 *(ap_directive_t **)dummy = conftree;
2158 static const char *set_loglevel(cmd_parms *cmd, void *dummy, const char *arg)
2162 const char *err = ap_check_cmd_context(cmd,
2163 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2168 if ((str = ap_getword_conf(cmd->pool, &arg))) {
2169 if (!strcasecmp(str, "emerg")) {
2170 cmd->server->loglevel = APLOG_EMERG;
2172 else if (!strcasecmp(str, "alert")) {
2173 cmd->server->loglevel = APLOG_ALERT;
2175 else if (!strcasecmp(str, "crit")) {
2176 cmd->server->loglevel = APLOG_CRIT;
2178 else if (!strcasecmp(str, "error")) {
2179 cmd->server->loglevel = APLOG_ERR;
2181 else if (!strcasecmp(str, "warn")) {
2182 cmd->server->loglevel = APLOG_WARNING;
2184 else if (!strcasecmp(str, "notice")) {
2185 cmd->server->loglevel = APLOG_NOTICE;
2187 else if (!strcasecmp(str, "info")) {
2188 cmd->server->loglevel = APLOG_INFO;
2190 else if (!strcasecmp(str, "debug")) {
2191 cmd->server->loglevel = APLOG_DEBUG;
2194 return "LogLevel requires level keyword: one of "
2195 "emerg/alert/crit/error/warn/notice/info/debug";
2199 return "LogLevel requires level keyword";
2205 AP_DECLARE(const char *) ap_psignature(const char *prefix, request_rec *r)
2208 core_dir_config *conf;
2210 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
2212 if ((conf->server_signature == srv_sig_off)
2213 || (conf->server_signature == srv_sig_unset)) {
2217 apr_snprintf(sport, sizeof sport, "%u", (unsigned) ap_get_server_port(r));
2219 if (conf->server_signature == srv_sig_withmail) {
2220 return apr_pstrcat(r->pool, prefix, "<ADDRESS>" AP_SERVER_BASEVERSION
2221 " Server at <A HREF=\"mailto:",
2222 r->server->server_admin, "\">",
2223 ap_get_server_name(r), "</A> Port ", sport,
2224 "</ADDRESS>\n", NULL);
2226 return apr_pstrcat(r->pool, prefix, "<ADDRESS>" AP_SERVER_BASEVERSION
2227 " Server at ", ap_get_server_name(r), " Port ", sport,
2228 "</ADDRESS>\n", NULL);
2232 * Load an authorisation realm into our location configuration, applying the
2233 * usual rules that apply to realms.
2235 static const char *set_authname(cmd_parms *cmd, void *mconfig,
2238 core_dir_config *aconfig = (core_dir_config *)mconfig;
2240 aconfig->ap_auth_name = ap_escape_quotes(cmd->pool, word1);
2244 #ifdef _OSD_POSIX /* BS2000 Logon Passwd file */
2245 static const char *set_bs2000_account(cmd_parms *cmd, void *dummy, char *name)
2247 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2252 return os_set_account(cmd->pool, name);
2254 #endif /*_OSD_POSIX*/
2257 * Handle a request to include the server's OS platform in the Server
2258 * response header field (the ServerTokens directive). Unfortunately
2259 * this requires a new global in order to communicate the setting back to
2260 * http_main so it can insert the information in the right place in the
2264 static char *server_version = NULL;
2265 static int version_locked = 0;
2267 enum server_token_type {
2268 SrvTk_MIN, /* eg: Apache/1.3.0 */
2269 SrvTk_OS, /* eg: Apache/1.3.0 (UNIX) */
2270 SrvTk_FULL, /* eg: Apache/1.3.0 (UNIX) PHP/3.0 FooBar/1.2b */
2271 SrvTk_PRODUCT_ONLY /* eg: Apache */
2273 static enum server_token_type ap_server_tokens = SrvTk_FULL;
2275 static apr_status_t reset_version(void *dummy)
2278 ap_server_tokens = SrvTk_FULL;
2279 server_version = NULL;
2283 AP_DECLARE(const char *) ap_get_server_version(void)
2285 return (server_version ? server_version : AP_SERVER_BASEVERSION);
2288 AP_DECLARE(void) ap_add_version_component(apr_pool_t *pconf, const char *component)
2290 if (! version_locked) {
2292 * If the version string is null, register our cleanup to reset the
2293 * pointer on pool destruction. We also know that, if NULL,
2294 * we are adding the original SERVER_BASEVERSION string.
2296 if (server_version == NULL) {
2297 apr_register_cleanup(pconf, NULL, reset_version,
2299 server_version = apr_pstrdup(pconf, component);
2303 * Tack the given component identifier to the end of
2304 * the existing string.
2306 server_version = apr_pstrcat(pconf, server_version, " ",
2313 * This routine adds the real server base identity to the version string,
2314 * and then locks out changes until the next reconfig.
2316 static void ap_set_version(apr_pool_t *pconf)
2318 if (ap_server_tokens == SrvTk_PRODUCT_ONLY) {
2319 ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT);
2321 else if (ap_server_tokens == SrvTk_MIN) {
2322 ap_add_version_component(pconf, AP_SERVER_BASEVERSION);
2325 ap_add_version_component(pconf, AP_SERVER_BASEVERSION " (" PLATFORM ")");
2328 * Lock the server_version string if we're not displaying
2329 * the full set of tokens
2331 if (ap_server_tokens != SrvTk_FULL) {
2336 static const char *set_serv_tokens(cmd_parms *cmd, void *dummy,
2339 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2344 if (!strcasecmp(arg, "OS")) {
2345 ap_server_tokens = SrvTk_OS;
2347 else if (!strcasecmp(arg, "Min") || !strcasecmp(arg, "Minimal")) {
2348 ap_server_tokens = SrvTk_MIN;
2350 else if (!strcasecmp(arg, "Prod") || !strcasecmp(arg, "ProductOnly")) {
2351 ap_server_tokens = SrvTk_PRODUCT_ONLY;
2354 ap_server_tokens = SrvTk_FULL;
2359 static const char *set_limit_req_line(cmd_parms *cmd, void *dummy,
2362 const char *err = ap_check_cmd_context(cmd,
2363 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2371 return apr_pstrcat(cmd->temp_pool, "LimitRequestLine \"", arg,
2372 "\" must be a non-negative integer", NULL);
2374 if (lim > DEFAULT_LIMIT_REQUEST_LINE) {
2375 return apr_psprintf(cmd->temp_pool, "LimitRequestLine \"%s\" "
2376 "must not exceed the precompiled maximum of %d",
2377 arg, DEFAULT_LIMIT_REQUEST_LINE);
2379 cmd->server->limit_req_line = lim;
2383 static const char *set_limit_req_fieldsize(cmd_parms *cmd, void *dummy,
2386 const char *err = ap_check_cmd_context(cmd,
2387 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2395 return apr_pstrcat(cmd->temp_pool, "LimitRequestFieldsize \"", arg,
2396 "\" must be a non-negative integer (0 = no limit)",
2399 if (lim > DEFAULT_LIMIT_REQUEST_FIELDSIZE) {
2400 return apr_psprintf(cmd->temp_pool, "LimitRequestFieldsize \"%s\" "
2401 "must not exceed the precompiled maximum of %d",
2402 arg, DEFAULT_LIMIT_REQUEST_FIELDSIZE);
2404 cmd->server->limit_req_fieldsize = lim;
2408 static const char *set_limit_req_fields(cmd_parms *cmd, void *dummy,
2411 const char *err = ap_check_cmd_context(cmd,
2412 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2420 return apr_pstrcat(cmd->temp_pool, "LimitRequestFields \"", arg,
2421 "\" must be a non-negative integer (0 = no limit)",
2424 cmd->server->limit_req_fields = lim;
2428 static const char *set_limit_req_body(cmd_parms *cmd, void *conf_,
2431 core_dir_config *conf=conf_;
2432 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2437 /* WTF: If strtoul is not portable, then write a replacement.
2438 * Instead we have an idiotic define in httpd.h that prevents
2439 * it from being used even when it is available. Sheesh.
2441 conf->limit_req_body = (unsigned long)strtol(arg, (char **)NULL, 10);
2445 static const char *set_limit_xml_req_body(cmd_parms *cmd, void *conf_,
2448 core_dir_config *conf = conf_;
2449 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2454 conf->limit_xml_body = atol(arg);
2455 if (conf->limit_xml_body < 0)
2456 return "LimitXMLRequestBody requires a non-negative integer.";
2461 AP_DECLARE(size_t) ap_get_limit_xml_body(const request_rec *r)
2463 core_dir_config *conf;
2465 conf = ap_get_module_config(r->per_dir_config, &core_module);
2466 if (conf->limit_xml_body == AP_LIMIT_UNSET)
2467 return AP_DEFAULT_LIMIT_XML_BODY;
2468 return (size_t)conf->limit_xml_body;
2472 static const char *set_interpreter_source(cmd_parms *cmd, core_dir_config *d,
2475 if (!strcasecmp(arg, "registry")) {
2476 d->script_interpreter_source = INTERPRETER_SOURCE_REGISTRY;
2477 } else if (!strcasecmp(arg, "registry-strict")) {
2478 d->script_interpreter_source = INTERPRETER_SOURCE_REGISTRY_STRICT;
2479 } else if (!strcasecmp(arg, "script")) {
2480 d->script_interpreter_source = INTERPRETER_SOURCE_SHEBANG;
2482 return apr_pstrcat(cmd->temp_pool, "ScriptInterpreterSource \"", arg,
2483 "\" must be \"registry\", \"registry-strict\" or "
2484 "\"script\"", NULL);
2490 #if !defined (RLIMIT_CPU) || !(defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)) || !defined (RLIMIT_NPROC)
2491 static const char *no_set_limit(cmd_parms *cmd, void *conf_,
2492 const char *arg, const char *arg2)
2494 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, cmd->server,
2495 "%s not supported on this platform", cmd->cmd->name);
2501 static const char *set_limit_cpu(cmd_parms *cmd, void *conf_,
2502 const char *arg, const char *arg2)
2504 core_dir_config *conf=conf_;
2506 unixd_set_rlimit(cmd, &conf->limit_cpu, arg, arg2, RLIMIT_CPU);
2511 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)
2512 static const char *set_limit_mem(cmd_parms *cmd, void *conf_,
2513 const char *arg, const char * arg2)
2515 core_dir_config *conf=conf_;
2517 #if defined(RLIMIT_AS)
2518 unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2 ,RLIMIT_AS);
2519 #elif defined(RLIMIT_DATA)
2520 unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_DATA);
2521 #elif defined(RLIMIT_VMEM)
2522 unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_VMEM);
2529 static const char *set_limit_nproc(cmd_parms *cmd, void *conf_,
2530 const char *arg, const char * arg2)
2532 core_dir_config *conf=conf_;
2534 unixd_set_rlimit(cmd, &conf->limit_nproc, arg, arg2, RLIMIT_NPROC);
2539 static apr_status_t writev_it_all(apr_socket_t *s,
2540 struct iovec *vec, int nvec,
2541 apr_size_t len, apr_size_t *nbytes)
2543 apr_size_t bytes_written = 0;
2550 /* XXX handle checking for non-blocking socket */
2551 while (bytes_written != len) {
2552 rv = apr_sendv(s, vec + i, nvec - i, &n);
2554 if (rv != APR_SUCCESS)
2558 /* If the write did not complete, adjust the iovecs and issue
2561 if (bytes_written < len) {
2562 /* Skip over the vectors that have already been written */
2563 apr_size_t cnt = vec[i].iov_len;
2564 while (n >= cnt && i + 1 < nvec) {
2566 cnt += vec[i].iov_len;
2569 /* Handle partial write of vec i */
2570 vec[i].iov_base = (char *) vec[i].iov_base +
2571 (vec[i].iov_len - (cnt - n));
2572 vec[i].iov_len = cnt -n;
2575 n = len - bytes_written;
2581 /* sendfile_it_all()
2582 * send the entire file using sendfile()
2583 * handle partial writes
2584 * return only when all bytes have been sent or an error is encountered.
2587 #if APR_HAS_SENDFILE
2588 static apr_status_t sendfile_it_all(conn_rec *c,
2591 apr_off_t file_offset,
2592 apr_size_t file_bytes_left,
2593 apr_size_t total_bytes_left,
2597 apr_int32_t timeout = 0;
2599 AP_DEBUG_ASSERT((apr_getsocketopt(c->client_socket, APR_SO_TIMEOUT,
2600 &timeout) == APR_SUCCESS) &&
2601 timeout > 0); /* socket must be in timeout mode */
2603 apr_size_t tmplen = file_bytes_left;
2605 rv = apr_sendfile(c->client_socket, fd, hdtr, &file_offset, &tmplen,
2607 total_bytes_left -= tmplen;
2608 if (!total_bytes_left || rv != APR_SUCCESS) {
2609 return rv; /* normal case & error exit */
2612 AP_DEBUG_ASSERT(total_bytes_left > 0 && tmplen > 0);
2614 /* partial write, oooh noooo...
2615 * Skip over any header data which was written
2617 while (tmplen && hdtr->numheaders) {
2618 if (tmplen >= hdtr->headers[0].iov_len) {
2619 tmplen -= hdtr->headers[0].iov_len;
2624 char *iov_base = (char *)hdtr->headers[0].iov_base;
2626 hdtr->headers[0].iov_len -= tmplen;
2628 hdtr->headers[0].iov_base = iov_base;
2633 /* Skip over any file data which was written */
2635 if (tmplen <= file_bytes_left) {
2636 file_offset += tmplen;
2637 file_bytes_left -= tmplen;
2640 tmplen -= file_bytes_left;
2641 file_bytes_left = 0;
2644 /* Skip over any trailer data which was written */
2646 while (tmplen && hdtr->numtrailers) {
2647 if (tmplen >= hdtr->trailers[0].iov_len) {
2648 tmplen -= hdtr->trailers[0].iov_len;
2649 --hdtr->numtrailers;
2653 char *iov_base = (char *)hdtr->trailers[0].iov_base;
2655 hdtr->trailers[0].iov_len -= tmplen;
2657 hdtr->trailers[0].iov_base = iov_base;
2667 * Sends the contents of file fd along with header/trailer bytes, if any,
2668 * to the network. send_the_file will return only when all the bytes have been
2669 * sent (i.e., it handles partial writes) or on a network error condition.
2671 static apr_status_t send_the_file(conn_rec *c, apr_file_t *fd,
2672 apr_hdtr_t *hdtr, apr_off_t offset,
2673 apr_size_t length, apr_size_t *nbytes)
2675 apr_status_t rv = APR_SUCCESS;
2676 apr_int32_t togo; /* Remaining number of bytes in the file to send */
2677 apr_size_t sendlen = 0;
2678 apr_size_t bytes_sent;
2680 apr_off_t o; /* Track the file offset for partial writes */
2686 * writev_it_all handles partial writes.
2687 * XXX: optimization... if headers are less than MIN_WRITE_SIZE, copy
2690 if ( hdtr && hdtr->numheaders > 0 ) {
2691 for (i = 0; i < hdtr->numheaders; i++) {
2692 sendlen += hdtr->headers[i].iov_len;
2694 rv = writev_it_all(c->client_socket, hdtr->headers, hdtr->numheaders,
2695 sendlen, &bytes_sent);
2696 if (rv == APR_SUCCESS)
2697 *nbytes += bytes_sent; /* track total bytes sent */
2700 /* Seek the file to 'offset' */
2701 if (offset != 0 && rv == APR_SUCCESS) {
2702 rv = apr_seek(fd, APR_SET, &offset);
2705 /* Send the file, making sure to handle partial writes */
2707 while (rv == APR_SUCCESS && togo) {
2708 sendlen = togo > sizeof(buffer) ? sizeof(buffer) : togo;
2710 rv = apr_read(fd, buffer, &sendlen);
2711 while (rv == APR_SUCCESS && sendlen) {
2712 bytes_sent = sendlen;
2713 rv = apr_send(c->client_socket, &buffer[o], &bytes_sent);
2714 if (rv == APR_SUCCESS) {
2715 sendlen -= bytes_sent; /* sendlen != bytes_sent ==> partial write */
2716 o += bytes_sent; /* o is where we are in the buffer */
2717 *nbytes += bytes_sent;
2718 togo -= bytes_sent; /* track how much of the file we've sent */
2723 /* Send the trailers
2724 * XXX: optimization... if it will fit, send this on the last send in the
2728 if ( rv == APR_SUCCESS && hdtr && hdtr->numtrailers > 0 ) {
2729 for (i = 0; i < hdtr->numtrailers; i++) {
2730 sendlen += hdtr->trailers[i].iov_len;
2732 rv = writev_it_all(c->client_socket, hdtr->trailers, hdtr->numtrailers,
2733 sendlen, &bytes_sent);
2734 if (rv == APR_SUCCESS)
2735 *nbytes += bytes_sent;
2741 /* Note --- ErrorDocument will now work from .htaccess files.
2742 * The AllowOverride of Fileinfo allows webmasters to turn it off
2745 static const command_rec core_cmds[] = {
2747 /* Old access config file commands */
2749 AP_INIT_RAW_ARGS("<Directory", dirsection, NULL, RSRC_CONF,
2750 "Container for directives affecting resources located in the specified "
2752 AP_INIT_RAW_ARGS("<Location", urlsection, NULL, RSRC_CONF,
2753 "Container for directives affecting resources accessed through the "
2754 "specified URL paths"),
2755 AP_INIT_RAW_ARGS("<VirtualHost", virtualhost_section, NULL, RSRC_CONF,
2756 "Container to map directives to a particular virtual host, takes one or "
2757 "more host addresses"),
2758 AP_INIT_RAW_ARGS("<Files", filesection, NULL, OR_ALL,
2759 "Container for directives affecting files matching specified patterns"),
2760 AP_INIT_RAW_ARGS("<Limit", ap_limit_section, NULL, OR_ALL,
2761 "Container for authentication directives when accessed using specified HTTP "
2763 AP_INIT_RAW_ARGS("<LimitExcept", ap_limit_section, (void*)1, OR_ALL,
2764 "Container for authentication directives to be applied when any HTTP "
2765 "method other than those specified is used to access the resource"),
2766 AP_INIT_TAKE1("<IfModule", start_ifmod, NULL, EXEC_ON_READ | OR_ALL,
2767 "Container for directives based on existance of specified modules"),
2768 AP_INIT_TAKE1("<IfDefine", start_ifdefine, NULL, EXEC_ON_READ | OR_ALL,
2769 "Container for directives based on existance of command line defines"),
2770 AP_INIT_RAW_ARGS("<DirectoryMatch", dirsection, (void*)1, RSRC_CONF,
2771 "Container for directives affecting resources located in the "
2772 "specified directories"),
2773 AP_INIT_RAW_ARGS("<LocationMatch", urlsection, (void*)1, RSRC_CONF,
2774 "Container for directives affecting resources accessed through the "
2775 "specified URL paths"),
2776 AP_INIT_RAW_ARGS("<FilesMatch", filesection, (void*)1, OR_ALL,
2777 "Container for directives affecting files matching specified patterns"),
2778 AP_INIT_TAKE1("AuthType", ap_set_string_slot,
2779 (void*)XtOffsetOf(core_dir_config, ap_auth_type), OR_AUTHCFG,
2780 "An HTTP authorization type (e.g., \"Basic\")"),
2781 AP_INIT_TAKE1("AuthName", set_authname, NULL, OR_AUTHCFG,
2782 "The authentication realm (e.g. \"Members Only\")"),
2783 AP_INIT_RAW_ARGS("Require", require, NULL, OR_AUTHCFG,
2784 "Selects which authenticated users or groups may access a protected space"),
2785 AP_INIT_TAKE1("Satisfy", satisfy, NULL, OR_AUTHCFG,
2786 "access policy if both allow and require used ('all' or 'any')"),
2788 AP_INIT_TAKE1("GprofDir", set_gprof_dir, NULL, RSRC_CONF,
2789 "Directory to plop gmon.out files"),
2791 AP_INIT_TAKE1("AddDefaultCharset", set_add_default_charset, NULL, OR_FILEINFO,
2792 "The name of the default charset to add to any Content-Type without one or 'Off' to disable"),
2794 /* Old resource config file commands */
2796 AP_INIT_RAW_ARGS("AccessFileName", set_access_name, NULL, RSRC_CONF,
2797 "Name(s) of per-directory config files (default: .htaccess)"),
2798 AP_INIT_TAKE1("DocumentRoot", set_document_root, NULL, RSRC_CONF,
2799 "Root directory of the document tree"),
2800 AP_INIT_TAKE2("ErrorDocument", set_error_document, NULL, OR_FILEINFO,
2801 "Change responses for HTTP errors"),
2802 AP_INIT_RAW_ARGS("AllowOverride", set_override, NULL, ACCESS_CONF,
2803 "Controls what groups of directives can be configured by per-directory "
2805 AP_INIT_RAW_ARGS("Options", set_options, NULL, OR_OPTIONS,
2806 "Set a number of attributes for a given directory"),
2807 AP_INIT_TAKE1("DefaultType", ap_set_string_slot,
2808 (void*)XtOffsetOf (core_dir_config, ap_default_type),
2809 OR_FILEINFO, "the default MIME type for untypable files"),
2811 /* Old server config file commands */
2813 AP_INIT_TAKE1("Port", server_port, NULL, RSRC_CONF, "A TCP port number"),
2814 AP_INIT_TAKE1("HostnameLookups", set_hostname_lookups, NULL,
2815 ACCESS_CONF|RSRC_CONF,
2816 "\"on\" to enable, \"off\" to disable reverse DNS lookups, or \"double\" to "
2817 "enable double-reverse DNS lookups"),
2818 AP_INIT_TAKE1("ServerAdmin", set_server_string_slot,
2819 (void *)XtOffsetOf (server_rec, server_admin), RSRC_CONF,
2820 "The email address of the server administrator"),
2821 AP_INIT_TAKE1("ServerName", set_server_string_slot,
2822 (void *)XtOffsetOf (server_rec, server_hostname), RSRC_CONF,
2823 "The hostname of the server"),
2824 AP_INIT_TAKE1("ServerSignature", set_signature_flag, NULL, OR_ALL,
2825 "En-/disable server signature (on|off|email)"),
2826 AP_INIT_TAKE1("ServerRoot", set_server_root, NULL, RSRC_CONF,
2827 "Common directory of server-related files (logs, confs, etc.)"),
2828 AP_INIT_TAKE1("ErrorLog", set_server_string_slot,
2829 (void *)XtOffsetOf (server_rec, error_fname), RSRC_CONF,
2830 "The filename of the error log"),
2831 AP_INIT_RAW_ARGS("ServerAlias", set_server_alias, NULL, RSRC_CONF,
2832 "A name or names alternately used to access the server"),
2833 AP_INIT_TAKE1("ServerPath", set_serverpath, NULL, RSRC_CONF,
2834 "The pathname the server can be reached at"),
2835 AP_INIT_TAKE1("Timeout", set_timeout, NULL, RSRC_CONF,
2836 "Timeout duration (sec)"),
2837 AP_INIT_TAKE1("KeepAliveTimeout", set_keep_alive_timeout, NULL, RSRC_CONF,
2838 "Keep-Alive timeout duration (sec)"),
2839 AP_INIT_TAKE1("MaxKeepAliveRequests", set_keep_alive_max, NULL, RSRC_CONF,
2840 "Maximum number of Keep-Alive requests per connection, or 0 for infinite"),
2841 AP_INIT_TAKE1("KeepAlive", set_keep_alive, NULL, RSRC_CONF,
2842 "Whether persistent connections should be On or Off"),
2843 AP_INIT_FLAG("IdentityCheck", set_idcheck, NULL, RSRC_CONF|ACCESS_CONF,
2844 "Enable identd (RFC 1413) user lookups - SLOW"),
2845 AP_INIT_FLAG("ContentDigest", set_content_md5, NULL, OR_OPTIONS,
2846 "whether or not to send a Content-MD5 header with each request"),
2847 AP_INIT_TAKE1("UseCanonicalName", set_use_canonical_name, NULL,
2848 RSRC_CONF|ACCESS_CONF,
2849 "How to work out the ServerName : Port when constructing URLs"),
2850 /* TODO: RlimitFoo should all be part of mod_cgi, not in the core */
2851 AP_INIT_ITERATE("AddModule", add_module_command, NULL,
2852 RSRC_CONF, "The name of a module"),
2853 AP_INIT_NO_ARGS("ClearModuleList", clear_module_list_command, NULL,
2855 /* TODO: ListenBacklog in MPM */
2856 AP_INIT_TAKE1("Include", include_config, NULL,
2857 (RSRC_CONF | ACCESS_CONF | EXEC_ON_READ),
2858 "Name of the config file to be included"),
2859 AP_INIT_TAKE1("LogLevel", set_loglevel, NULL, RSRC_CONF,
2860 "Level of verbosity in error logging"),
2861 AP_INIT_TAKE1("NameVirtualHost", ap_set_name_virtual_host, NULL, RSRC_CONF,
2862 "A numeric IP address:port, or the name of a host"),
2864 AP_INIT_TAKE1("BS2000Account", set_bs2000_account, NULL, RSRC_CONF,
2865 "Name of server User's bs2000 logon account name"),
2868 AP_INIT_TAKE1("ScriptInterpreterSource", set_interpreter_source, NULL,
2870 "Where to find interpreter to run Win32 scripts (Registry or script shebang line)"),
2872 AP_INIT_TAKE1("ServerTokens", set_serv_tokens, NULL, RSRC_CONF,
2873 "Determine tokens displayed in the Server: header - Min(imal), OS or Full"),
2874 AP_INIT_TAKE1("LimitRequestLine", set_limit_req_line, NULL, RSRC_CONF,
2875 "Limit on maximum size of an HTTP request line"),
2876 AP_INIT_TAKE1("LimitRequestFieldsize", set_limit_req_fieldsize, NULL,
2878 "Limit on maximum size of an HTTP request header field"),
2879 AP_INIT_TAKE1("LimitRequestFields", set_limit_req_fields, NULL, RSRC_CONF,
2880 "Limit (0 = unlimited) on max number of header fields in a request message"),
2881 AP_INIT_TAKE1("LimitRequestBody", set_limit_req_body,
2882 (void*)XtOffsetOf(core_dir_config, limit_req_body), OR_ALL,
2883 "Limit (in bytes) on maximum size of request message body"),
2884 AP_INIT_TAKE1("LimitXMLRequestBody", set_limit_xml_req_body, NULL, OR_ALL,
2885 "Limit (in bytes) on maximum size of an XML-based request "
2888 /* System Resource Controls */
2890 AP_INIT_TAKE12("RLimitCPU", set_limit_cpu,
2891 (void*)XtOffsetOf(core_dir_config, limit_cpu),
2892 OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
2894 AP_INIT_TAKE12("RLimitCPU", no_set_limit, NULL,
2895 OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
2897 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined (RLIMIT_AS)
2898 AP_INIT_TAKE12("RLimitMEM", set_limit_mem,
2899 (void*)XtOffsetOf(core_dir_config, limit_mem),
2900 OR_ALL, "Soft/hard limits for max memory usage per process"),
2902 AP_INIT_TAKE12("RLimitMEM", no_set_limit, NULL,
2903 OR_ALL, "Soft/hard limits for max memory usage per process"),
2906 AP_INIT_TAKE12("RLimitNPROC", set_limit_nproc,
2907 (void*)XtOffsetOf(core_dir_config, limit_nproc),
2908 OR_ALL, "soft/hard limits for max number of processes per uid"),
2910 AP_INIT_TAKE12("RLimitNPROC", no_set_limit, NULL,
2911 OR_ALL, "soft/hard limits for max number of processes per uid"),
2913 /* XXX These should be allowable in .htaccess files, but currently it won't
2914 * play well with the Options stuff. Until that is fixed, I would prefer
2915 * to leave it just in the conf file. Other should feel free to disagree
2918 AP_INIT_ITERATE("AddOutputFilter", add_filter, NULL, ACCESS_CONF,
2919 "filters to be run"),
2920 AP_INIT_ITERATE("AddInputFilter", add_input_filter, NULL, ACCESS_CONF,
2921 "filters to be run on the request body"),
2925 /*****************************************************************
2927 * Core handlers for various phases of server operation...
2930 AP_DECLARE_NONSTD(int) ap_core_translate(request_rec *r)
2932 void *sconf = r->server->module_config;
2933 core_server_config *conf = ap_get_module_config(sconf, &core_module);
2936 return HTTP_FORBIDDEN;
2938 if ((r->uri[0] != '/') && strcmp(r->uri, "*")) {
2939 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2940 "Invalid URI in request %s", r->the_request);
2941 return HTTP_BAD_REQUEST;
2945 && !strncmp(r->uri, r->server->path, r->server->pathlen)
2946 && (r->server->path[r->server->pathlen - 1] == '/'
2947 || r->uri[r->server->pathlen] == '/'
2948 || r->uri[r->server->pathlen] == '\0')) {
2949 r->filename = apr_pstrcat(r->pool, conf->ap_document_root,
2950 (r->uri + r->server->pathlen), NULL);
2954 * Make sure that we do not mess up the translation by adding two
2955 * /'s in a row. This happens under windows when the document
2956 * root ends with a /
2958 if ((conf->ap_document_root[strlen(conf->ap_document_root)-1] == '/')
2959 && (*(r->uri) == '/')) {
2960 r->filename = apr_pstrcat(r->pool, conf->ap_document_root, r->uri+1,
2964 r->filename = apr_pstrcat(r->pool, conf->ap_document_root, r->uri,
2972 static int do_nothing(request_rec *r) { return OK; }
2974 static int default_handler(const char *handler, request_rec *r)
2976 ap_bucket_brigade *bb;
2980 apr_file_t *fd = NULL;
2981 apr_status_t status;
2982 /* XXX if/when somebody writes a content-md5 filter we either need to
2983 * remove this support or coordinate when to use the filter vs.
2984 * when to use this code
2985 * The current choice of when to compute the md5 here matches the 1.3
2986 * support fairly closely (unlike 1.3, we don't handle computing md5
2987 * when the charset is translated).
2989 int bld_content_md5;
2992 * The old way of doing handlers meant that this handler would
2993 * match literally anything - this way will require handler to
2994 * have a / in the middle, which probably captures the original
2995 * intent, but may cause problems at first - Ben 7th Jan 01
2997 if(strcmp(handler,"request-handler")
2998 && ap_strcmp_match(handler,"*/*"))
3001 d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
3003 bld_content_md5 = (d->content_md5 & 1)
3004 && r->output_filters->frec->ftype != AP_FTYPE_CONTENT;
3006 ap_allow_methods(r, MERGE_ALLOW, "GET", "OPTIONS", "POST", NULL);
3008 if ((errstatus = ap_discard_request_body(r)) != OK) {
3012 if (r->method_number == M_INVALID) {
3013 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
3014 "Invalid method in request %s", r->the_request);
3015 return HTTP_NOT_IMPLEMENTED;
3017 if (r->method_number == M_OPTIONS) {
3018 return ap_send_http_options(r);
3020 if (r->method_number == M_PUT) {
3021 return HTTP_METHOD_NOT_ALLOWED;
3023 if (r->finfo.protection == 0 || (r->path_info && *r->path_info)) {
3024 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r,
3025 "File does not exist: %s",r->path_info ?
3026 apr_pstrcat(r->pool, r->filename, r->path_info, NULL)
3028 return HTTP_NOT_FOUND;
3031 if (r->method_number != M_GET && r->method_number != M_POST) {
3032 return HTTP_METHOD_NOT_ALLOWED;
3035 if ((status = apr_open(&fd, r->filename, APR_READ | APR_BINARY, 0, r->connection->pool)) != APR_SUCCESS) {
3036 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r,
3037 "file permissions deny server access: %s", r->filename);
3038 return HTTP_FORBIDDEN;
3040 ap_update_mtime(r, r->finfo.mtime);
3041 ap_set_last_modified(r);
3043 apr_table_setn(r->headers_out, "Accept-Ranges", "bytes");
3044 ap_set_content_length(r, r->finfo.size);
3045 if ((errstatus = ap_meets_conditions(r)) != OK) {
3050 if (bld_content_md5) {
3051 apr_table_setn(r->headers_out, "Content-MD5",
3052 ap_md5digest(r->pool, fd));
3055 bb = ap_brigade_create(r->pool);
3056 e = ap_bucket_create_file(fd, 0, r->finfo.size);
3058 AP_BRIGADE_INSERT_HEAD(bb, e);
3059 e = ap_bucket_create_eos();
3060 AP_BRIGADE_INSERT_TAIL(bb, e);
3062 return ap_pass_brigade(r->output_filters, bb);
3067 * This is a simple filter to coalesce many small buckets into one large
3071 * This implementation of coalesce_filter will only coalesce a single
3072 * contiguous string of coalesable buckets. It will not coalesce multiple
3073 * non-contiguous buckets. For example, if a brigade contains 10 small
3074 * buckets followed by a large bucket (or a pipe or file bucket) followed
3075 * by more small buckets, only the first 10 buckets will be coalesced.
3077 typedef struct COALESCE_FILTER_CTX {
3078 char *buf; /* Start of buffer */
3079 char *cur; /* Pointer to next location to write */
3080 apr_size_t cnt; /* Number of bytes put in buf */
3081 apr_size_t avail; /* Number of bytes available in the buf */
3082 } coalesce_filter_ctx_t;
3083 #define MIN_BUCKET_SIZE 200
3084 static apr_status_t coalesce_filter(ap_filter_t *f, ap_bucket_brigade *b)
3087 apr_pool_t *p = f->r->pool;
3088 ap_bucket *e, *insert_before = NULL, *destroy_me = NULL;
3089 coalesce_filter_ctx_t *ctx = f->ctx;
3090 int pass_the_brigade = 0, insert_first = 0;
3093 f->ctx = ctx = apr_pcalloc(p, sizeof(coalesce_filter_ctx_t));
3094 ctx->avail = AP_MIN_BYTES_TO_WRITE;
3101 /* Iterate across the buckets, coalescing the small buckets into a
3104 AP_BRIGADE_FOREACH(e, b) {
3106 ap_bucket_destroy(destroy_me);
3109 if (AP_BUCKET_IS_EOS(e) || AP_BUCKET_IS_FILE(e) ||
3110 AP_BUCKET_IS_PIPE(e) || AP_BUCKET_IS_FLUSH(e)) {
3111 pass_the_brigade = 1;
3116 rv = ap_bucket_read(e, &str, &n, AP_BLOCK_READ);
3117 if (rv != APR_SUCCESS) {
3118 /* XXX: log error */
3121 if ((n < MIN_BUCKET_SIZE) && (n < ctx->avail)) {
3122 /* Coalesce this bucket into the buffer */
3123 if (ctx->buf == NULL) {
3124 ctx->buf = apr_palloc(p, AP_MIN_BYTES_TO_WRITE);
3125 ctx->cur = ctx->buf;
3128 memcpy(ctx->cur, str, n);
3132 /* If this is the first bucket to be coalesced, don't remove it
3133 * from the brigade. Save it as a marker for where to insert
3134 * ctx->buf into the brigade when we're done.
3136 if (insert_before || insert_first){
3137 AP_BUCKET_REMOVE(e);
3144 else if (insert_before || insert_first) {
3145 /* This bucket was not able to be coalesced because it either
3146 * exceeds MIN_BUCKET_SIZE or its contents will not fit into
3147 * buf. We're done...
3149 pass_the_brigade = 1;
3153 /* If there is even a single bucket that cannot be coalesced,
3154 * then we must pass the brigade down to the next filter.
3156 pass_the_brigade = 1;
3162 ap_bucket_destroy(destroy_me);
3166 if (pass_the_brigade) {
3167 /* Insert ctx->buf into the correct spot in the brigade */
3168 e = ap_bucket_create_pool(ctx->buf, ctx->cnt, p);
3170 AP_BRIGADE_INSERT_HEAD(b, e);
3172 else if (insert_before) {
3173 AP_BUCKET_INSERT_BEFORE(e, insert_before);
3174 AP_BUCKET_REMOVE(insert_before);
3175 ap_bucket_destroy(insert_before);
3176 insert_before = NULL;
3178 rv = ap_pass_brigade(f->next, b);
3179 if (rv != APR_SUCCESS) {
3180 /* XXX: Log the error */
3183 /* Get ctx->buf ready for the next brigade */
3185 ctx->cur = ctx->buf;
3187 ctx->avail = AP_MIN_BYTES_TO_WRITE;
3191 if (insert_before) {
3192 AP_BUCKET_REMOVE(insert_before);
3193 ap_bucket_destroy(insert_before);
3195 /* The brigade should be empty now because all the buckets
3196 * were coalesced into the coalesce_filter buf
3203 * HTTP/1.1 chunked transfer encoding filter.
3205 static apr_status_t chunk_filter(ap_filter_t *f, ap_bucket_brigade *b)
3207 #define ASCII_CRLF "\015\012"
3208 #define ASCII_ZERO "\060"
3209 ap_bucket_brigade *more = NULL;
3213 for (more = NULL; b; b = more, more = NULL) {
3214 apr_off_t bytes = 0;
3215 ap_bucket *eos = NULL;
3216 char chunk_hdr[20]; /* enough space for the snprintf below */
3218 AP_BRIGADE_FOREACH(e, b) {
3219 if (AP_BUCKET_IS_EOS(e)) {
3220 /* there shouldn't be anything after the eos */
3224 else if (e->length == -1) {
3225 /* unknown amount of data (e.g. a pipe) */
3229 rv = ap_bucket_read(e, &data, &len, AP_BLOCK_READ);
3230 if (rv != APR_SUCCESS) {
3235 * There may be a new next bucket representing the
3236 * rest of the data stream on which a read() may
3237 * block so we pass down what we have so far.
3240 more = ap_brigade_split(b, AP_BUCKET_NEXT(e));
3244 /* If there was nothing in this bucket then we can
3245 * safely move on to the next one without pausing
3246 * to pass down what we have counted up so far.
3257 * XXX: if there aren't very many bytes at this point it may
3258 * be a good idea to set them aside and return for more,
3259 * unless we haven't finished counting this brigade yet.
3262 /* if there are content bytes, then wrap them in a chunk */
3267 * Insert the chunk header, specifying the number of bytes in
3270 /* XXX might be nice to have APR_OFF_T_FMT_HEX */
3271 hdr_len = apr_snprintf(chunk_hdr, sizeof(chunk_hdr),
3272 "%qx" CRLF, (apr_uint64_t)bytes);
3273 ap_xlate_proto_to_ascii(chunk_hdr, hdr_len);
3274 e = ap_bucket_create_transient(chunk_hdr, hdr_len);
3275 AP_BRIGADE_INSERT_HEAD(b, e);
3278 * Insert the end-of-chunk CRLF before the EOS bucket, or
3279 * appended to the brigade
3281 e = ap_bucket_create_immortal(ASCII_CRLF, 2);
3283 AP_BUCKET_INSERT_BEFORE(eos, e);
3286 AP_BRIGADE_INSERT_TAIL(b, e);
3290 /* RFC 2616, Section 3.6.1
3292 * If there is an EOS bucket, then prefix it with:
3293 * 1) the last-chunk marker ("0" CRLF)
3295 * 3) the end-of-chunked body CRLF
3297 * If there is no EOS bucket, then do nothing.
3299 * XXX: it would be nice to combine this with the end-of-chunk
3300 * marker above, but this is a bit more straight-forward for
3304 /* XXX: (2) trailers ... does not yet exist */
3305 e = ap_bucket_create_immortal(ASCII_ZERO ASCII_CRLF /* <trailers> */ ASCII_CRLF, 5);
3306 AP_BUCKET_INSERT_BEFORE(eos, e);
3309 /* pass the brigade to the next filter. */
3310 rv = ap_pass_brigade(f->next, b);
3311 if (rv != APR_SUCCESS || eos != NULL) {
3319 static int core_input_filter(ap_filter_t *f, ap_bucket_brigade *b, ap_input_mode_t mode)
3323 if (!f->ctx) { /* If we haven't passed up the socket yet... */
3325 e = ap_bucket_create_socket(f->c->client_socket);
3326 AP_BRIGADE_INSERT_TAIL(b, e);
3330 /* Either some code lost track of the socket
3331 * bucket or we already found out that the
3338 /* Default filter. This filter should almost always be used. Its only job
3339 * is to send the headers if they haven't already been sent, and then send
3342 typedef struct CORE_OUTPUT_FILTER_CTX {
3343 ap_bucket_brigade *b;
3344 } core_output_filter_ctx_t;
3345 #define MAX_IOVEC_TO_WRITE 16
3346 static apr_status_t core_output_filter(ap_filter_t *f, ap_bucket_brigade *b)
3349 ap_bucket_brigade *more = NULL;
3350 apr_size_t bytes_sent = 0, nbytes;
3353 core_output_filter_ctx_t *ctx = f->ctx;
3355 apr_size_t nvec = 0;
3356 apr_size_t nvec_trailers= 0;
3357 struct iovec vec[MAX_IOVEC_TO_WRITE];
3358 struct iovec vec_trailers[MAX_IOVEC_TO_WRITE];
3360 apr_file_t *fd = NULL;
3361 apr_size_t flen = 0;
3362 apr_off_t foffset = 0;
3365 f->ctx = ctx = apr_pcalloc(c->pool, sizeof(core_output_filter_ctx_t));
3367 /* If we have a saved brigade, concatenate the new brigade to it */
3369 AP_BRIGADE_CONCAT(ctx->b, b);
3374 /* Iterate over the brigade collecting iovecs */
3376 nbytes = 0; /* in case more points to another brigade */
3378 AP_BRIGADE_FOREACH(e, b) {
3379 if (AP_BUCKET_IS_EOS(e) || AP_BUCKET_IS_FLUSH(e)) {
3382 else if (AP_BUCKET_IS_FILE(e)) {
3383 ap_bucket_file *a = e->data;
3384 /* Assume there is at most one AP_BUCKET_FILE in the brigade */
3387 foffset = a->offset;
3392 rv = ap_bucket_read(e, &str, &n, AP_BLOCK_READ);
3396 vec[nvec].iov_base = (char*) str;
3397 vec[nvec].iov_len = n;
3401 /* The bucket is a trailer to a file bucket */
3402 vec_trailers[nvec_trailers].iov_base = (char*) str;
3403 vec_trailers[nvec_trailers].iov_len = n;
3409 if ((nvec == MAX_IOVEC_TO_WRITE) || (nvec_trailers == MAX_IOVEC_TO_WRITE)) {
3410 /* Split the brigade and break */
3411 if (AP_BUCKET_NEXT(e) != AP_BRIGADE_SENTINEL(b)) {
3412 more = ap_brigade_split(b, AP_BUCKET_NEXT(e));
3418 /* Completed iterating over the brigades, now determine if we want to
3419 * buffer the brigade or send the brigade out on the network
3421 if ((!fd && (!more) && (nbytes < AP_MIN_BYTES_TO_WRITE) && !AP_BUCKET_IS_FLUSH(e))
3422 || (AP_BUCKET_IS_EOS(e) && c->keepalive)) {
3424 /* NEVER save an EOS in here. If we are saving a brigade with an
3425 * EOS bucket, then we are doing keepalive connections, and we want
3426 * to process to second request fully.
3428 if (AP_BUCKET_IS_EOS(e)) {
3429 AP_BUCKET_REMOVE(e);
3430 ap_bucket_destroy(e);
3432 ap_save_brigade(f, &ctx->b, &b);
3437 #if APR_HAS_SENDFILE
3438 apr_int32_t flags = 0;
3441 memset(&hdtr, '\0', sizeof(hdtr));
3443 hdtr.numheaders = nvec;
3446 if (nvec_trailers) {
3447 hdtr.numtrailers = nvec_trailers;
3448 hdtr.trailers = vec_trailers;
3450 #if APR_HAS_SENDFILE
3451 if (!c->keepalive) {
3452 /* Prepare the socket to be reused */
3453 flags |= APR_SENDFILE_DISCONNECT_SOCKET;
3455 rv = sendfile_it_all(c, /* the connection */
3456 fd, /* the file to send */
3457 &hdtr, /* header and trailer iovecs */
3458 foffset, /* offset in the file to begin
3460 flen, /* length of file */
3461 nbytes + flen, /* total length including
3463 flags); /* apr_sendfile flags */
3465 /* If apr_sendfile() returns APR_ENOTIMPL, call send_the_file() to
3466 * loop on apr_read/apr_send to send the file. Our Windows binary
3467 * distributions (which work on Windows 9x/NT) are compiled on
3468 * Windows NT. TransmitFile is not available on Windows 95/98 and
3469 * we discover this at runtime when apr_sendfile() returns
3470 * APR_ENOTIMPL. Having apr_sendfile() return APR_ENOTIMPL seems
3471 * the cleanest way to handle this case.
3473 if (rv == APR_ENOTIMPL) {
3476 rv = send_the_file(c, fd, &hdtr, foffset, flen, &bytes_sent);
3478 #if APR_HAS_SENDFILE
3483 rv = writev_it_all(c->client_socket,
3485 nbytes, &bytes_sent);
3488 ap_brigade_destroy(b);
3489 if (rv != APR_SUCCESS) {
3490 /* XXX: log the error */
3492 ap_brigade_destroy(more);
3499 } /* end while () */
3504 static void core_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
3506 ap_init_bucket_types(pconf);
3509 static void core_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
3511 ap_set_version(pconf);
3514 static void core_open_logs(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
3516 ap_open_logs(s, pconf);
3519 static const char *core_method(const request_rec *r)
3522 static unsigned short core_port(const request_rec *r)
3523 { return DEFAULT_HTTP_PORT; }
3525 static void core_insert_filter(request_rec *r)
3528 core_dir_config *conf = (core_dir_config *)
3529 ap_get_module_config(r->per_dir_config,
3531 char **items = (char **)conf->output_filters->elts;
3533 for (i = 0; i < conf->output_filters->nelts; i++) {
3534 char *foobar = items[i];
3535 ap_add_output_filter(foobar, NULL, r, r->connection);
3538 items = (char **)conf->input_filters->elts;
3539 for (i = 0; i < conf->input_filters->nelts; i++) {
3540 char *foobar = items[i];
3541 ap_add_input_filter(foobar, NULL, r, r->connection);
3545 static void register_hooks(void)
3547 ap_hook_pre_config(core_pre_config, NULL, NULL, AP_HOOK_REALLY_FIRST);
3548 ap_hook_post_config(core_post_config,NULL,NULL,AP_HOOK_REALLY_FIRST);
3549 ap_hook_translate_name(ap_core_translate,NULL,NULL,AP_HOOK_REALLY_LAST);
3550 ap_hook_pre_connection(ap_pre_http_connection,NULL,NULL,
3551 AP_HOOK_REALLY_LAST);
3552 ap_hook_process_connection(ap_process_http_connection,NULL,NULL,
3553 AP_HOOK_REALLY_LAST);
3554 ap_hook_http_method(core_method,NULL,NULL,AP_HOOK_REALLY_LAST);
3555 ap_hook_default_port(core_port,NULL,NULL,AP_HOOK_REALLY_LAST);
3556 ap_hook_open_logs(core_open_logs,NULL,NULL,AP_HOOK_MIDDLE);
3557 ap_hook_handler(default_handler,NULL,NULL,AP_HOOK_REALLY_LAST);
3558 /* FIXME: I suspect we can eliminate the need for these - Ben */
3559 ap_hook_type_checker(do_nothing,NULL,NULL,AP_HOOK_REALLY_LAST);
3560 ap_hook_access_checker(do_nothing,NULL,NULL,AP_HOOK_REALLY_LAST);
3562 /* register the core's insert_filter hook and register core-provided
3565 ap_hook_insert_filter(core_insert_filter, NULL, NULL, AP_HOOK_MIDDLE);
3567 ap_register_input_filter("HTTP_IN", ap_http_filter, AP_FTYPE_CONNECTION);
3568 ap_register_input_filter("DECHUNK", ap_dechunk_filter, AP_FTYPE_TRANSCODE);
3569 ap_register_input_filter("CORE_IN", core_input_filter, AP_FTYPE_NETWORK);
3570 ap_register_output_filter("HTTP_HEADER", ap_http_header_filter,
3571 AP_FTYPE_HTTP_HEADER);
3572 ap_register_output_filter("CONTENT_LENGTH", ap_content_length_filter,
3573 AP_FTYPE_HTTP_HEADER);
3574 ap_register_output_filter("BYTERANGE", ap_byterange_filter,
3575 AP_FTYPE_HTTP_HEADER);
3576 ap_register_output_filter("CORE", core_output_filter, AP_FTYPE_NETWORK);
3577 ap_register_output_filter("SUBREQ_CORE", ap_sub_req_output_filter,
3579 ap_register_output_filter("CHUNK", chunk_filter, AP_FTYPE_TRANSCODE);
3580 ap_register_output_filter("COALESCE", coalesce_filter, AP_FTYPE_CONTENT);
3583 AP_DECLARE_DATA module core_module = {
3584 STANDARD20_MODULE_STUFF,
3585 create_core_dir_config, /* create per-directory config structure */
3586 merge_core_dir_configs, /* merge per-directory config structures */
3587 create_core_server_config, /* create per-server config structure */
3588 merge_core_server_configs, /* merge per-server config structures */
3589 core_cmds, /* command apr_table_t */
3590 register_hooks /* register hooks */