1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000 The Apache Software Foundation. All rights
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
19 * 3. The end-user documentation included with the redistribution,
20 * if any, must include the following acknowledgment:
21 * "This product includes software developed by the
22 * Apache Software Foundation (http://www.apache.org/)."
23 * Alternately, this acknowledgment may appear in the software itself,
24 * if and wherever such third-party acknowledgments normally appear.
26 * 4. The names "Apache" and "Apache Software Foundation" must
27 * not be used to endorse or promote products derived from this
28 * software without prior written permission. For written
29 * permission, please contact apache@apache.org.
31 * 5. Products derived from this software may not be called "Apache",
32 * nor may "Apache" appear in their name, without prior written
33 * permission of the Apache Software Foundation.
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation. For more
51 * information on the Apache Software Foundation, please see
52 * <http://www.apache.org/>.
54 * Portions of this software are based upon public domain software
55 * originally written at the National Center for Supercomputing Applications,
56 * University of Illinois, Urbana-Champaign.
60 #include "ap_config.h"
61 #include "apr_strings.h"
64 #include "http_config.h"
65 #include "http_core.h"
66 #include "http_protocol.h" /* For index_of_response(). Grump. */
67 #include "http_request.h"
68 #include "http_vhost.h"
69 #include "http_main.h" /* For the default_handler below... */
73 #include "apr_fnmatch.h"
74 #include "http_connection.h"
75 #include "ap_buckets.h"
76 #include "util_filter.h"
77 #include "util_ebcdic.h"
82 #ifdef HAVE_SYS_SOCKET_H
83 #include <sys/socket.h>
85 #ifdef HAVE_ARPA_INET_H
86 #include <arpa/inet.h>
92 /* Make sure we don't write less than 4096 bytes at any one time.
94 #define MIN_SIZE_TO_WRITE 4096
96 /* Allow Apache to use ap_mmap */
100 /* mmap support for static files based on ideas from John Heidemann's
101 * patch against 1.0.5. See
102 * <http://www.isi.edu/~johnh/SOFTWARE/APACHE/index.html>.
105 /* Files have to be at least this big before they're mmap()d. This is to deal
106 * with systems where the expense of doing an mmap() and an munmap() outweighs
107 * the benefit for small files. It shouldn't be set lower than 1.
109 #ifndef MMAP_THRESHOLD
111 #define MMAP_THRESHOLD (8*1024)
113 #define MMAP_THRESHOLD 1
115 #endif /* MMAP_THRESHOLD */
117 #define MMAP_LIMIT (4*1024*1024)
119 #endif /* USE_MMAP_FILES */
121 /* LimitXMLRequestBody handling */
122 #define AP_LIMIT_UNSET ((long) -1)
123 #define AP_DEFAULT_LIMIT_XML_BODY ((size_t)1000000)
125 /* Server core module... This module provides support for really basic
126 * server operations, including options and commands which control the
127 * operation of other modules. Consider this the bureaucracy module.
129 * The core module also defines handlers, etc., do handle just enough
130 * to allow a server with the core module ONLY to actually serve documents
131 * (though it slaps DefaultType on all of 'em); this was useful in testing,
132 * but may not be worth preserving.
134 * This file could almost be mod_core.c, except for the stuff which affects
135 * the http_conf_globals.
138 static void *create_core_dir_config(apr_pool_t *a, char *dir)
140 core_dir_config *conf;
142 conf = (core_dir_config *)apr_pcalloc(a, sizeof(core_dir_config));
143 if (!dir || dir[strlen(dir) - 1] == '/') {
146 else if (strncmp(dir, "proxy:", 6) == 0) {
147 conf->d = apr_pstrdup(a, dir);
150 conf->d = apr_pstrcat(a, dir, "/", NULL);
152 conf->d_is_fnmatch = conf->d ? (apr_is_fnmatch(conf->d) != 0) : 0;
153 conf->d_components = conf->d ? ap_count_dirs(conf->d) : 0;
155 conf->opts = dir ? OPT_UNSET : OPT_UNSET|OPT_ALL;
156 conf->opts_add = conf->opts_remove = OPT_NONE;
157 conf->override = dir ? OR_UNSET : OR_UNSET|OR_ALL;
159 conf->content_md5 = 2;
161 conf->use_canonical_name = USE_CANONICAL_NAME_UNSET;
163 conf->hostname_lookups = HOSTNAME_LOOKUP_UNSET;
164 conf->do_rfc1413 = DEFAULT_RFC1413 | 2; /* set bit 1 to indicate default */
165 conf->satisfy = SATISFY_NOSPEC;
168 conf->limit_cpu = NULL;
170 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
171 conf->limit_mem = NULL;
174 conf->limit_nproc = NULL;
177 conf->limit_req_body = 0;
178 conf->limit_xml_body = AP_LIMIT_UNSET;
179 conf->sec = apr_make_array(a, 2, sizeof(void *));
181 conf->script_interpreter_source = INTERPRETER_SOURCE_UNSET;
184 conf->server_signature = srv_sig_unset;
186 conf->add_default_charset = ADD_DEFAULT_CHARSET_UNSET;
187 conf->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
189 conf->filters = apr_make_array(a, 2, sizeof(void *));
193 static void *merge_core_dir_configs(apr_pool_t *a, void *basev, void *newv)
195 core_dir_config *base = (core_dir_config *)basev;
196 core_dir_config *new = (core_dir_config *)newv;
197 core_dir_config *conf;
200 conf = (core_dir_config *)apr_palloc(a, sizeof(core_dir_config));
201 memcpy((char *)conf, (const char *)base, sizeof(core_dir_config));
202 if (base->response_code_strings) {
203 conf->response_code_strings =
204 apr_palloc(a, sizeof(*conf->response_code_strings)
206 memcpy(conf->response_code_strings, base->response_code_strings,
207 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
211 conf->d_is_fnmatch = new->d_is_fnmatch;
212 conf->d_components = new->d_components;
215 if (new->opts & OPT_UNSET) {
216 /* there was no explicit setting of new->opts, so we merge
217 * preserve the invariant (opts_add & opts_remove) == 0
219 conf->opts_add = (conf->opts_add & ~new->opts_remove) | new->opts_add;
220 conf->opts_remove = (conf->opts_remove & ~new->opts_add)
222 conf->opts = (conf->opts & ~conf->opts_remove) | conf->opts_add;
223 if ((base->opts & OPT_INCNOEXEC) && (new->opts & OPT_INCLUDES)) {
224 conf->opts = (conf->opts & ~OPT_INCNOEXEC) | OPT_INCLUDES;
228 /* otherwise we just copy, because an explicit opts setting
229 * overrides all earlier +/- modifiers
231 conf->opts = new->opts;
232 conf->opts_add = new->opts_add;
233 conf->opts_remove = new->opts_remove;
236 if (!(new->override & OR_UNSET)) {
237 conf->override = new->override;
239 if (new->ap_default_type) {
240 conf->ap_default_type = new->ap_default_type;
243 if (new->ap_auth_type) {
244 conf->ap_auth_type = new->ap_auth_type;
246 if (new->ap_auth_name) {
247 conf->ap_auth_name = new->ap_auth_name;
249 if (new->ap_requires) {
250 conf->ap_requires = new->ap_requires;
253 if (new->response_code_strings) {
254 if (conf->response_code_strings == NULL) {
255 conf->response_code_strings = apr_palloc(a,
256 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
257 memcpy(conf->response_code_strings, new->response_code_strings,
258 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
261 for (i = 0; i < RESPONSE_CODES; ++i) {
262 if (new->response_code_strings[i] != NULL) {
263 conf->response_code_strings[i]
264 = new->response_code_strings[i];
269 if (new->hostname_lookups != HOSTNAME_LOOKUP_UNSET) {
270 conf->hostname_lookups = new->hostname_lookups;
272 if ((new->do_rfc1413 & 2) == 0) {
273 conf->do_rfc1413 = new->do_rfc1413;
275 if ((new->content_md5 & 2) == 0) {
276 conf->content_md5 = new->content_md5;
278 if (new->use_canonical_name != USE_CANONICAL_NAME_UNSET) {
279 conf->use_canonical_name = new->use_canonical_name;
283 if (new->limit_cpu) {
284 conf->limit_cpu = new->limit_cpu;
287 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
288 if (new->limit_mem) {
289 conf->limit_mem = new->limit_mem;
293 if (new->limit_nproc) {
294 conf->limit_nproc = new->limit_nproc;
298 if (new->limit_req_body) {
299 conf->limit_req_body = new->limit_req_body;
302 if (new->limit_xml_body != AP_LIMIT_UNSET)
303 conf->limit_xml_body = new->limit_xml_body;
305 conf->limit_xml_body = base->limit_xml_body;
307 conf->sec = apr_append_arrays(a, base->sec, new->sec);
309 if (new->satisfy != SATISFY_NOSPEC) {
310 conf->satisfy = new->satisfy;
314 if (new->script_interpreter_source != INTERPRETER_SOURCE_UNSET) {
315 conf->script_interpreter_source = new->script_interpreter_source;
319 if (new->server_signature != srv_sig_unset) {
320 conf->server_signature = new->server_signature;
323 if (new->add_default_charset != ADD_DEFAULT_CHARSET_UNSET) {
324 conf->add_default_charset = new->add_default_charset;
325 if (new->add_default_charset_name) {
326 conf->add_default_charset_name = new->add_default_charset_name;
329 conf->filters = apr_append_arrays(a, base->filters, new->filters);
334 static void *create_core_server_config(apr_pool_t *a, server_rec *s)
336 core_server_config *conf;
337 int is_virtual = s->is_virtual;
339 conf = (core_server_config *)apr_pcalloc(a, sizeof(core_server_config));
341 conf->gprof_dir = NULL;
343 conf->access_name = is_virtual ? NULL : DEFAULT_ACCESS_FNAME;
344 conf->ap_document_root = is_virtual ? NULL : DOCUMENT_LOCATION;
345 conf->sec = apr_make_array(a, 40, sizeof(void *));
346 conf->sec_url = apr_make_array(a, 40, sizeof(void *));
351 static void *merge_core_server_configs(apr_pool_t *p, void *basev, void *virtv)
353 core_server_config *base = (core_server_config *)basev;
354 core_server_config *virt = (core_server_config *)virtv;
355 core_server_config *conf;
357 conf = (core_server_config *)apr_pcalloc(p, sizeof(core_server_config));
359 if (!conf->access_name) {
360 conf->access_name = base->access_name;
362 if (!conf->ap_document_root) {
363 conf->ap_document_root = base->ap_document_root;
365 conf->sec = apr_append_arrays(p, base->sec, virt->sec);
366 conf->sec_url = apr_append_arrays(p, base->sec_url, virt->sec_url);
371 /* Add per-directory configuration entry (for <directory> section);
372 * these are part of the core server config.
375 CORE_EXPORT(void) ap_add_per_dir_conf(server_rec *s, void *dir_config)
377 core_server_config *sconf = ap_get_module_config(s->module_config,
379 void **new_space = (void **)apr_push_array(sconf->sec);
381 *new_space = dir_config;
384 CORE_EXPORT(void) ap_add_per_url_conf(server_rec *s, void *url_config)
386 core_server_config *sconf = ap_get_module_config(s->module_config,
388 void **new_space = (void **)apr_push_array(sconf->sec_url);
390 *new_space = url_config;
393 CORE_EXPORT(void) ap_add_file_conf(core_dir_config *conf, void *url_config)
395 void **new_space = (void **)apr_push_array(conf->sec);
397 *new_space = url_config;
400 /* core_reorder_directories reorders the directory sections such that the
401 * 1-component sections come first, then the 2-component, and so on, finally
402 * followed by the "special" sections. A section is "special" if it's a regex,
403 * or if it doesn't start with / -- consider proxy: matching. All movements
404 * are in-order to preserve the ordering of the sections from the config files.
405 * See directory_walk().
408 #ifdef HAVE_DRIVE_LETTERS
409 #define IS_SPECIAL(entry_core) \
410 ((entry_core)->r != NULL \
411 || ((entry_core)->d[0] != '/' && (entry_core)->d[1] != ':'))
413 #define IS_SPECIAL(entry_core) \
414 ((entry_core)->r != NULL || (entry_core)->d[0] != '/')
417 /* We need to do a stable sort, qsort isn't stable. So to make it stable
418 * we'll be maintaining the original index into the list, and using it
419 * as the minor key during sorting. The major key is the number of
420 * components (where a "special" section has infinite components).
422 struct reorder_sort_rec {
427 static int reorder_sorter(const void *va, const void *vb)
429 const struct reorder_sort_rec *a = va;
430 const struct reorder_sort_rec *b = vb;
431 core_dir_config *core_a;
432 core_dir_config *core_b;
434 core_a = (core_dir_config *)ap_get_module_config(a->elt, &core_module);
435 core_b = (core_dir_config *)ap_get_module_config(b->elt, &core_module);
436 if (IS_SPECIAL(core_a)) {
437 if (!IS_SPECIAL(core_b)) {
441 else if (IS_SPECIAL(core_b)) {
445 /* we know they're both not special */
446 if (core_a->d_components < core_b->d_components) {
449 else if (core_a->d_components > core_b->d_components) {
453 /* Either they're both special, or they're both not special and have the
454 * same number of components. In any event, we now have to compare
456 return a->orig_index - b->orig_index;
459 void ap_core_reorder_directories(apr_pool_t *p, server_rec *s)
461 core_server_config *sconf;
462 apr_array_header_t *sec;
463 struct reorder_sort_rec *sortbin;
469 sconf = ap_get_module_config(s->module_config, &core_module);
472 elts = (void **)sec->elts;
474 /* we have to allocate tmp space to do a stable sort */
475 apr_create_pool(&tmp, p);
476 sortbin = apr_palloc(tmp, sec->nelts * sizeof(*sortbin));
477 for (i = 0; i < nelts; ++i) {
478 sortbin[i].orig_index = i;
479 sortbin[i].elt = elts[i];
482 qsort(sortbin, nelts, sizeof(*sortbin), reorder_sorter);
484 /* and now copy back to the original array */
485 for (i = 0; i < nelts; ++i) {
486 elts[i] = sortbin[i].elt;
489 apr_destroy_pool(tmp);
492 /*****************************************************************
494 * There are some elements of the core config structures in which
495 * other modules have a legitimate interest (this is ugly, but necessary
496 * to preserve NCSA back-compatibility). So, we have a bunch of accessors
500 API_EXPORT(int) ap_allow_options(request_rec *r)
502 core_dir_config *conf =
503 (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
508 API_EXPORT(int) ap_allow_overrides(request_rec *r)
510 core_dir_config *conf;
511 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
514 return conf->override;
517 API_EXPORT(const char *) ap_auth_type(request_rec *r)
519 core_dir_config *conf;
521 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
523 return conf->ap_auth_type;
526 API_EXPORT(const char *) ap_auth_name(request_rec *r)
528 core_dir_config *conf;
530 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
532 return conf->ap_auth_name;
535 API_EXPORT(const char *) ap_default_type(request_rec *r)
537 core_dir_config *conf;
539 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
541 return conf->ap_default_type
542 ? conf->ap_default_type
543 : DEFAULT_CONTENT_TYPE;
546 API_EXPORT(const char *) ap_document_root(request_rec *r) /* Don't use this! */
548 core_server_config *conf;
550 conf = (core_server_config *)ap_get_module_config(r->server->module_config,
552 return conf->ap_document_root;
555 API_EXPORT(const apr_array_header_t *) ap_requires(request_rec *r)
557 core_dir_config *conf;
559 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
561 return conf->ap_requires;
564 API_EXPORT(int) ap_satisfies(request_rec *r)
566 core_dir_config *conf;
568 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
571 return conf->satisfy;
574 /* Should probably just get rid of this... the only code that cares is
575 * part of the core anyway (and in fact, it isn't publicised to other
579 char *ap_response_code_string(request_rec *r, int error_index)
581 core_dir_config *conf;
583 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
586 if (conf->response_code_strings == NULL) {
589 return conf->response_code_strings[error_index];
593 /* Code from Harald Hanche-Olsen <hanche@imf.unit.no> */
594 static apr_inline void do_double_reverse (conn_rec *conn)
596 struct hostent *hptr;
598 if (conn->double_reverse) {
602 if (conn->remote_host == NULL || conn->remote_host[0] == '\0') {
603 /* single reverse failed, so don't bother */
604 conn->double_reverse = -1;
607 hptr = gethostbyname(conn->remote_host);
611 for (haddr = hptr->h_addr_list; *haddr; haddr++) {
612 if (((struct in_addr *)(*haddr))->s_addr
613 == conn->remote_addr.sin_addr.s_addr) {
614 conn->double_reverse = 1;
619 conn->double_reverse = -1;
622 API_EXPORT(const char *) ap_get_remote_host(conn_rec *conn, void *dir_config,
625 struct in_addr *iaddr;
626 struct hostent *hptr;
627 int hostname_lookups;
629 /* If we haven't checked the host name, and we want to */
632 ((core_dir_config *)ap_get_module_config(dir_config, &core_module))
634 if (hostname_lookups == HOSTNAME_LOOKUP_UNSET) {
635 hostname_lookups = HOSTNAME_LOOKUP_OFF;
640 hostname_lookups = HOSTNAME_LOOKUP_OFF;
643 if (type != REMOTE_NOLOOKUP
644 && conn->remote_host == NULL
645 && (type == REMOTE_DOUBLE_REV
646 || hostname_lookups != HOSTNAME_LOOKUP_OFF)) {
647 iaddr = &(conn->remote_addr.sin_addr);
648 hptr = gethostbyaddr((char *)iaddr, sizeof(struct in_addr), AF_INET);
650 conn->remote_host = apr_pstrdup(conn->pool, (void *)hptr->h_name);
651 ap_str_tolower(conn->remote_host);
653 if (hostname_lookups == HOSTNAME_LOOKUP_DOUBLE) {
654 do_double_reverse(conn);
655 if (conn->double_reverse != 1) {
656 conn->remote_host = NULL;
660 /* if failed, set it to the NULL string to indicate error */
661 if (conn->remote_host == NULL) {
662 conn->remote_host = "";
665 if (type == REMOTE_DOUBLE_REV) {
666 do_double_reverse(conn);
667 if (conn->double_reverse == -1) {
673 * Return the desired information; either the remote DNS name, if found,
674 * or either NULL (if the hostname was requested) or the IP address
675 * (if any identifier was requested).
677 if (conn->remote_host != NULL && conn->remote_host[0] != '\0') {
678 return conn->remote_host;
681 if (type == REMOTE_HOST || type == REMOTE_DOUBLE_REV) {
685 return conn->remote_ip;
690 API_EXPORT(const char *) ap_get_remote_logname(request_rec *r)
692 core_dir_config *dir_conf;
694 if (r->connection->remote_logname != NULL) {
695 return r->connection->remote_logname;
698 /* If we haven't checked the identity, and we want to */
699 dir_conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
702 if (dir_conf->do_rfc1413 & 1) {
703 return ap_rfc1413(r->connection, r->server);
710 /* There are two options regarding what the "name" of a server is. The
711 * "canonical" name as defined by ServerName and Port, or the "client's
712 * name" as supplied by a possible Host: header or full URI. We never
713 * trust the port passed in the client's headers, we always use the
714 * port of the actual socket.
716 * The DNS option to UseCanonicalName causes this routine to do a
717 * reverse lookup on the local IP address of the connectiona and use
718 * that for the ServerName. This makes its value more reliable while
719 * at the same time allowing Demon's magic virtual hosting to work.
720 * The assumption is that DNS lookups are sufficiently quick...
723 API_EXPORT(const char *) ap_get_server_name(request_rec *r)
725 conn_rec *conn = r->connection;
728 d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
731 if (d->use_canonical_name == USE_CANONICAL_NAME_OFF) {
732 return r->hostname ? r->hostname : r->server->server_hostname;
734 if (d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
735 if (conn->local_host == NULL) {
736 struct in_addr *iaddr;
737 struct hostent *hptr;
738 iaddr = &(conn->local_addr.sin_addr);
739 hptr = gethostbyaddr((char *)iaddr, sizeof(struct in_addr),
742 conn->local_host = apr_pstrdup(conn->pool,
743 (void *)hptr->h_name);
744 ap_str_tolower(conn->local_host);
747 conn->local_host = apr_pstrdup(conn->pool,
748 r->server->server_hostname);
751 return conn->local_host;
754 return r->server->server_hostname;
757 API_EXPORT(unsigned) ap_get_server_port(const request_rec *r)
761 (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
763 port = r->server->port ? r->server->port : ap_default_port(r);
765 if (d->use_canonical_name == USE_CANONICAL_NAME_OFF
766 || d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
767 return r->hostname ? ntohs(r->connection->local_addr.sin_port)
774 API_EXPORT(char *) ap_construct_url(apr_pool_t *p, const char *uri,
777 unsigned port = ap_get_server_port(r);
778 const char *host = ap_get_server_name(r);
780 if (ap_is_default_port(port, r)) {
781 return apr_pstrcat(p, ap_http_method(r), "://", host, uri, NULL);
783 return apr_psprintf(p, "%s://%s:%u%s", ap_http_method(r), host, port, uri);
786 API_EXPORT(unsigned long) ap_get_limit_req_body(const request_rec *r)
789 (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
791 return d->limit_req_body;
795 static DWORD get_win32_registry_default_value(apr_pool_t *p, HKEY hkey,
796 char* relativepath, char **value)
801 DWORD result = RegOpenKeyEx(hkey, relativepath, 0,
802 KEY_QUERY_VALUE, &hkeyOpen);
804 if (result != ERROR_SUCCESS)
807 /* Read to NULL buffer to determine value size */
808 result = RegQueryValueEx(hkeyOpen, "", 0, &type, NULL, &size);
810 if (result == ERROR_SUCCESS) {
811 if ((size < 2) || (type != REG_SZ && type != REG_EXPAND_SZ)) {
812 result = ERROR_INVALID_PARAMETER;
815 *value = apr_palloc(p, size);
816 /* Read value based on size query above */
817 result = RegQueryValueEx(hkeyOpen, "", 0, &type, *value, &size);
821 /* TODO: This might look fine, but we need to provide some warning
822 * somewhere that some environment variables may -not- be translated,
823 * seeing as we may have chopped the environment table down somewhat.
825 if ((result == ERROR_SUCCESS) && (type == REG_EXPAND_SZ))
828 size = ExpandEnvironmentStrings(tmp, *value, 0);
830 *value = apr_palloc(p, size);
831 size = ExpandEnvironmentStrings(tmp, *value, size);
835 RegCloseKey(hkeyOpen);
839 static char* get_interpreter_from_win32_registry(apr_pool_t *p, const char* ext,
840 char** arguments, int strict)
842 char execcgi_path[] = "SHELL\\EXECCGI\\COMMAND";
843 char execopen_path[] = "SHELL\\OPEN\\COMMAND";
844 char typeName[MAX_PATH];
845 int cmdOfName = FALSE;
857 * Future optimization:
858 * When the registry is successfully searched, store the strings for
859 * interpreter and arguments in an ext hash to speed up subsequent look-ups
862 /* Open the key associated with the script filetype extension */
863 result = RegOpenKeyEx(HKEY_CLASSES_ROOT, ext, 0, KEY_QUERY_VALUE,
866 if (result != ERROR_SUCCESS)
869 /* Retrieve the name of the script filetype extension */
870 size = sizeof(typeName);
871 result = RegQueryValueEx(hkeyType, "", NULL, &type, typeName, &size);
873 if (result == ERROR_SUCCESS && type == REG_SZ && typeName[0]) {
874 /* Open the key associated with the script filetype extension */
875 result = RegOpenKeyEx(HKEY_CLASSES_ROOT, typeName, 0,
876 KEY_QUERY_VALUE, &hkeyName);
878 if (result == ERROR_SUCCESS)
882 /* Open the key for the script command path by:
884 * 1) the 'named' filetype key for ExecCGI/Command
885 * 2) the extension's type key for ExecCGI/Command
887 * and if the strict arg is false, then continue trying:
889 * 3) the 'named' filetype key for Open/Command
890 * 4) the extension's type key for Open/Command
894 result = get_win32_registry_default_value(p, hkeyName,
895 execcgi_path, &buffer);
898 if (!cmdOfName || (result != ERROR_SUCCESS)) {
899 result = get_win32_registry_default_value(p, hkeyType,
900 execcgi_path, &buffer);
903 if (!strict && cmdOfName && (result != ERROR_SUCCESS)) {
904 result = get_win32_registry_default_value(p, hkeyName,
905 execopen_path, &buffer);
908 if (!strict && (result != ERROR_SUCCESS)) {
909 result = get_win32_registry_default_value(p, hkeyType,
910 execopen_path, &buffer);
914 RegCloseKey(hkeyName);
916 RegCloseKey(hkeyType);
918 if (result != ERROR_SUCCESS)
922 * The canonical way shell command entries are entered in the Win32
923 * registry is as follows:
924 * shell [options] "%1" [args]
926 * shell - full path name to interpreter or shell to run.
927 * E.g., c:\usr\local\ntreskit\perl\bin\perl.exe
928 * options - optional switches
930 * "%1" - Place holder for file to run the shell against.
932 * options - additional arguments
935 * If we find a %1 or a quoted %1, lop off the remainder to arguments.
937 if (buffer && *buffer) {
938 if ((s = strstr(buffer, "\"%1")))
943 else if ((s = strstr(buffer, "%1")))
946 *arguments = buffer + 2;
949 *arguments = strchr(buffer, '\0');
950 while (**arguments && isspace(**arguments))
957 API_EXPORT (file_type_e) ap_get_win32_interpreter(const request_rec *r,
967 file_type_e fileType = eFileTypeUNKNOWN;
969 char *exename = NULL;
971 d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
974 /* Find the file extension */
975 exename = strrchr(r->filename, '/');
977 exename = strrchr(r->filename, '\\');
980 exename = r->filename;
985 ext = strrchr(exename, '.');
987 if (ext && (!strcasecmp(ext,".bat") || !strcasecmp(ext,".cmd")))
989 char *comspec = getenv("COMSPEC");
991 *interpreter = apr_pstrcat(r->pool, "\"", comspec, "\" /c ", NULL);
992 return eFileTypeSCRIPT;
994 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r->server,
995 "Failed to start a '%s' file as a script." APR_EOL_STR
996 "\tCOMSPEC variable is missing from the environment.", ext);
997 return eFileTypeUNKNOWN;
1000 /* If the file has an extension and it is not .com and not .exe and
1001 * we've been instructed to search the registry, then do it!
1003 if (ext && strcasecmp(ext,".exe") && strcasecmp(ext,".com") &&
1004 (d->script_interpreter_source == INTERPRETER_SOURCE_REGISTRY ||
1005 d->script_interpreter_source == INTERPRETER_SOURCE_REGISTRY_STRICT)) {
1006 /* Check the registry */
1007 int strict = (d->script_interpreter_source
1008 == INTERPRETER_SOURCE_REGISTRY_STRICT);
1009 *interpreter = get_interpreter_from_win32_registry(r->pool, ext,
1012 return eFileTypeSCRIPT;
1013 else if (d->script_interpreter_source == INTERPRETER_SOURCE_REGISTRY_STRICT) {
1014 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r->server,
1015 "ScriptInterpreterSource config directive set to \"registry-strict\"." APR_EOL_STR
1016 "\tInterpreter not found for files of type '%s'.", ext);
1017 return eFileTypeUNKNOWN;
1021 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r->server,
1022 "ScriptInterpreterSource config directive set to \"registry\"." APR_EOL_STR
1023 "\tInterpreter not found for files of type '%s', "
1024 "trying \"script\" method...", ext);
1028 /* Need to peek into the file figure out what it really is... */
1029 hFile = CreateFile(r->filename, GENERIC_READ, FILE_SHARE_READ, NULL,
1030 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1031 if (hFile == INVALID_HANDLE_VALUE) {
1032 return eFileTypeUNKNOWN;
1034 bResult = ReadFile(hFile, (void*) &buffer, sizeof(buffer) - 1,
1036 if (!bResult || (nBytesRead == 0)) {
1037 ap_log_rerror(APLOG_MARK, APLOG_ERR, GetLastError(), r,
1038 "ReadFile(%s) failed", r->filename);
1040 return eFileTypeUNKNOWN;
1043 buffer[nBytesRead] = '\0';
1045 /* Script or executable, that is the question... */
1046 if ((buffer[0] == '#') && (buffer[1] == '!')) {
1047 /* Assuming file is a script since it starts with a shebang */
1048 fileType = eFileTypeSCRIPT;
1049 for (i = 2; i < sizeof(buffer); i++) {
1050 if ((buffer[i] == '\r')
1051 || (buffer[i] == '\n')) {
1056 for (i = 2; buffer[i] == ' ' ; ++i)
1058 *interpreter = apr_pstrdup(r->pool, buffer + i );
1061 /* Not a script, is it an executable? */
1062 IMAGE_DOS_HEADER *hdr = (IMAGE_DOS_HEADER*)buffer;
1063 if ((nBytesRead >= sizeof(IMAGE_DOS_HEADER)) && (hdr->e_magic == IMAGE_DOS_SIGNATURE)) {
1064 if (hdr->e_lfarlc < 0x40)
1065 fileType = eFileTypeEXE16;
1067 fileType = eFileTypeEXE32;
1070 fileType = eFileTypeUNKNOWN;
1077 /*****************************************************************
1079 * Commands... this module handles almost all of the NCSA httpd.conf
1080 * commands, but most of the old srm.conf is in the the modules.
1084 /* returns a parent if it matches the given directive */
1085 static const ap_directive_t * find_parent(const ap_directive_t *dirp,
1088 while (dirp->parent != NULL) {
1089 dirp = dirp->parent;
1090 /* ### it would be nice to have atom-ized directives */
1091 if (strcasecmp(dirp->directive, what) == 0)
1097 API_EXPORT(const char *) ap_check_cmd_context(cmd_parms *cmd,
1100 const char *gt = (cmd->cmd->name[0] == '<'
1101 && cmd->cmd->name[strlen(cmd->cmd->name)-1] != '>')
1103 const ap_directive_t *found;
1105 if ((forbidden & NOT_IN_VIRTUALHOST) && cmd->server->is_virtual) {
1106 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1107 " cannot occur within <VirtualHost> section", NULL);
1110 if ((forbidden & NOT_IN_LIMIT) && cmd->limited != -1) {
1111 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1112 " cannot occur within <Limit> section", NULL);
1115 if ((forbidden & NOT_IN_DIR_LOC_FILE) == NOT_IN_DIR_LOC_FILE
1116 && cmd->path != NULL) {
1117 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1118 " cannot occur within <Directory/Location/Files> "
1122 if (((forbidden & NOT_IN_DIRECTORY)
1123 && ((found = find_parent(cmd->directive, "<Directory"))
1124 || (found = find_parent(cmd->directive, "<DirectoryMatch"))))
1125 || ((forbidden & NOT_IN_LOCATION)
1126 && ((found = find_parent(cmd->directive, "<Location"))
1127 || (found = find_parent(cmd->directive, "<LocationMatch"))))
1128 || ((forbidden & NOT_IN_FILES)
1129 && ((found = find_parent(cmd->directive, "<Files"))
1130 || (found = find_parent(cmd->directive, "<FilesMatch"))))) {
1131 return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1132 " cannot occur within ", found->directive,
1139 static const char *set_access_name(cmd_parms *cmd, void *dummy,
1142 void *sconf = cmd->server->module_config;
1143 core_server_config *conf = ap_get_module_config(sconf, &core_module);
1145 const char *err = ap_check_cmd_context(cmd,
1146 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1151 conf->access_name = apr_pstrdup(cmd->pool, arg);
1156 static const char *set_gprof_dir(cmd_parms *cmd, void *dummy, char *arg)
1158 void *sconf = cmd->server->module_config;
1159 core_server_config *conf = ap_get_module_config(sconf, &core_module);
1161 const char *err = ap_check_cmd_context(cmd,
1162 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1167 conf->gprof_dir = apr_pstrdup(cmd->pool, arg);
1172 static const char *set_add_default_charset(cmd_parms *cmd,
1173 void *d_, const char *arg)
1175 core_dir_config *d=d_;
1177 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1181 if (!strcasecmp(arg, "Off")) {
1182 d->add_default_charset = ADD_DEFAULT_CHARSET_OFF;
1184 else if (!strcasecmp(arg, "On")) {
1185 d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1186 d->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
1189 d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1190 d->add_default_charset_name = arg;
1195 static const char *set_document_root(cmd_parms *cmd, void *dummy,
1198 void *sconf = cmd->server->module_config;
1199 core_server_config *conf = ap_get_module_config(sconf, &core_module);
1201 const char *err = ap_check_cmd_context(cmd,
1202 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1207 arg = ap_os_canonical_filename(cmd->pool, arg);
1208 if (/* TODO: ap_configtestonly && ap_docrootcheck && */ !ap_is_directory(arg)) {
1209 if (cmd->server->is_virtual) {
1210 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1211 "Warning: DocumentRoot [%s] does not exist",
1215 return "DocumentRoot must be a directory";
1219 conf->ap_document_root = arg;
1223 API_EXPORT(void) ap_custom_response(request_rec *r, int status, char *string)
1225 core_dir_config *conf =
1226 ap_get_module_config(r->per_dir_config, &core_module);
1229 if(conf->response_code_strings == NULL) {
1230 conf->response_code_strings =
1231 apr_pcalloc(r->pool,
1232 sizeof(*conf->response_code_strings) *
1236 idx = ap_index_of_response(status);
1238 conf->response_code_strings[idx] =
1239 ((ap_is_url(string) || (*string == '/')) && (*string != '"')) ?
1240 apr_pstrdup(r->pool, string) : apr_pstrcat(r->pool, "\"", string, NULL);
1243 static const char *set_error_document(cmd_parms *cmd, void *conf_,
1244 const char *errno_str, const char *msg)
1246 core_dir_config *conf=conf_;
1247 int error_number, index_number, idx500;
1248 enum { MSG, LOCAL_PATH, REMOTE_PATH } what = MSG;
1250 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1255 /* 1st parameter should be a 3 digit number, which we recognize;
1256 * convert it into an array index
1258 error_number = atoi(errno_str);
1259 idx500 = ap_index_of_response(HTTP_INTERNAL_SERVER_ERROR);
1261 if (error_number == HTTP_INTERNAL_SERVER_ERROR) {
1262 index_number = idx500;
1264 else if ((index_number = ap_index_of_response(error_number)) == idx500) {
1265 return apr_pstrcat(cmd->pool, "Unsupported HTTP response code ",
1269 /* Heuristic to determine second argument. */
1270 if (ap_strchr_c(msg,' '))
1272 else if (msg[0] == '/')
1274 else if (ap_is_url(msg))
1279 /* The entry should be ignored if it is a full URL for a 401 error */
1281 if (error_number == 401 && what == REMOTE_PATH) {
1282 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, cmd->server,
1283 "cannot use a full URL in a 401 ErrorDocument "
1284 "directive --- ignoring!");
1286 else { /* Store it... */
1287 if (conf->response_code_strings == NULL) {
1288 conf->response_code_strings =
1289 apr_pcalloc(cmd->pool,
1290 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
1292 /* hack. Prefix a " if it is a msg; as that is what
1293 * http_protocol.c relies on to distinguish between
1294 * a msg and a (local) path.
1296 conf->response_code_strings[index_number] = (what == MSG) ?
1297 apr_pstrcat(cmd->pool, "\"",msg,NULL) :
1298 apr_pstrdup(cmd->pool, msg);
1304 static const char *set_override(cmd_parms *cmd, void *d_, const char *l)
1306 core_dir_config *d=d_;
1309 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1314 d->override = OR_NONE;
1316 w = ap_getword_conf(cmd->pool, &l);
1317 if (!strcasecmp(w, "Limit")) {
1318 d->override |= OR_LIMIT;
1320 else if (!strcasecmp(w, "Options")) {
1321 d->override |= OR_OPTIONS;
1323 else if (!strcasecmp(w, "FileInfo")) {
1324 d->override |= OR_FILEINFO;
1326 else if (!strcasecmp(w, "AuthConfig")) {
1327 d->override |= OR_AUTHCFG;
1329 else if (!strcasecmp(w, "Indexes")) {
1330 d->override |= OR_INDEXES;
1332 else if (!strcasecmp(w, "None")) {
1333 d->override = OR_NONE;
1335 else if (!strcasecmp(w, "All")) {
1336 d->override = OR_ALL;
1339 return apr_pstrcat(cmd->pool, "Illegal override option ", w, NULL);
1341 d->override &= ~OR_UNSET;
1347 static const char *set_options(cmd_parms *cmd, void *d_, const char *l)
1349 core_dir_config *d=d_;
1350 allow_options_t opt;
1355 char *w = ap_getword_conf(cmd->pool, &l);
1358 if (*w == '+' || *w == '-') {
1366 if (!strcasecmp(w, "Indexes")) {
1369 else if (!strcasecmp(w, "Includes")) {
1372 else if (!strcasecmp(w, "IncludesNOEXEC")) {
1373 opt = (OPT_INCLUDES | OPT_INCNOEXEC);
1375 else if (!strcasecmp(w, "FollowSymLinks")) {
1376 opt = OPT_SYM_LINKS;
1378 else if (!strcasecmp(w, "SymLinksIfOwnerMatch")) {
1379 opt = OPT_SYM_OWNER;
1381 else if (!strcasecmp(w, "execCGI")) {
1384 else if (!strcasecmp(w, "MultiViews")) {
1387 else if (!strcasecmp(w, "RunScripts")) { /* AI backcompat. Yuck */
1388 opt = OPT_MULTI|OPT_EXECCGI;
1390 else if (!strcasecmp(w, "None")) {
1393 else if (!strcasecmp(w, "All")) {
1397 return apr_pstrcat(cmd->pool, "Illegal option ", w, NULL);
1400 /* we ensure the invariant (d->opts_add & d->opts_remove) == 0 */
1401 if (action == '-') {
1402 d->opts_remove |= opt;
1403 d->opts_add &= ~opt;
1406 else if (action == '+') {
1408 d->opts_remove &= ~opt;
1419 static const char *satisfy(cmd_parms *cmd, void *c_, const char *arg)
1421 core_dir_config *c=c_;
1423 if (!strcasecmp(arg, "all")) {
1424 c->satisfy = SATISFY_ALL;
1426 else if (!strcasecmp(arg, "any")) {
1427 c->satisfy = SATISFY_ANY;
1430 return "Satisfy either 'any' or 'all'.";
1435 static const char *require(cmd_parms *cmd, void *c_, const char *arg)
1438 core_dir_config *c=c_;
1440 if (!c->ap_requires) {
1441 c->ap_requires = apr_make_array(cmd->pool, 2, sizeof(require_line));
1443 r = (require_line *)apr_push_array(c->ap_requires);
1444 r->requirement = apr_pstrdup(cmd->pool, arg);
1445 r->method_mask = cmd->limited;
1449 CORE_EXPORT_NONSTD(const char *) ap_limit_section(cmd_parms *cmd, void *dummy,
1451 const char *limited_methods = ap_getword(cmd->pool, &arg, '>');
1452 void *tog = cmd->cmd->cmd_data;
1456 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1461 while (limited_methods[0]) {
1462 char *method = ap_getword_conf(cmd->pool, &limited_methods);
1463 int methnum = ap_method_number_of(method);
1465 if (methnum == M_TRACE && !tog) {
1466 return "TRACE cannot be controlled by <Limit>";
1468 else if (methnum == M_INVALID) {
1470 register int i, j, k;
1473 * Deal with <Limit> by adding the method to the list.
1476 if (cmd->limited_xmethods == NULL) {
1477 cmd->limited_xmethods = apr_make_array(cmd->pool, 2,
1480 xmethod = (char **) apr_push_array(cmd->limited_xmethods);
1481 *xmethod = apr_pstrdup(cmd->pool, method);
1484 * <LimitExcept>, so remove any/all occurrences of the method
1485 * in the extension array.
1487 else if ((cmd->limited_xmethods != NULL)
1488 && (cmd->limited_xmethods->nelts != 0)) {
1489 xmethod = (char **) cmd->limited_xmethods->elts;
1490 for (i = 0; i < cmd->limited_xmethods->nelts; ) {
1491 if (strcmp(xmethod[i], method) == 0) {
1492 for (j = i, k = i + 1;
1493 k < cmd->limited_xmethods->nelts;
1495 xmethod[j] = xmethod[k];
1497 cmd->limited_xmethods->nelts--;
1502 limited |= (1 << methnum);
1505 /* Killing two features with one function,
1506 * if (tog == NULL) <Limit>, else <LimitExcept>
1508 cmd->limited = tog ? ~limited : limited;
1510 errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context);
1517 /* We use this in <DirectoryMatch> and <FilesMatch>, to ensure that
1518 * people don't get bitten by wrong-cased regex matches
1522 #define USE_ICASE REG_ICASE
1528 * Report a missing-'>' syntax error.
1530 static char *unclosed_directive(cmd_parms *cmd)
1532 return apr_pstrcat(cmd->pool, cmd->cmd->name,
1533 "> directive missing closing '>'", NULL);
1536 static const char *dirsection(cmd_parms *cmd, void *mconfig, const char *arg)
1539 const char *endp = ap_strrchr_c(arg, '>');
1540 int old_overrides = cmd->override;
1541 char *old_path = cmd->path;
1542 core_dir_config *conf;
1543 void *new_dir_conf = ap_create_per_dir_config(cmd->pool);
1545 const command_rec *thiscmd = cmd->cmd;
1547 const char *err = ap_check_cmd_context(cmd,
1548 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1554 return unclosed_directive(cmd);
1557 arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1559 cmd->path = ap_getword_conf(cmd->pool, &arg);
1560 cmd->override = OR_ALL|ACCESS_CONF;
1562 if (thiscmd->cmd_data) { /* <DirectoryMatch> */
1563 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1565 else if (!strcmp(cmd->path, "~")) {
1566 cmd->path = ap_getword_conf(cmd->pool, &arg);
1567 r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
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 API_EXPORT(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->filters);
1883 *newfilter = apr_pstrdup(cmd->pool, arg);
1887 static const char *add_module_command(cmd_parms *cmd, void *dummy,
1890 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1895 if (!ap_add_named_module(arg)) {
1896 return apr_pstrcat(cmd->pool, "Cannot add module via name '", arg,
1897 "': not in list of loaded modules", NULL);
1899 *(ap_directive_t **)dummy = NULL;
1903 static const char *clear_module_list_command(cmd_parms *cmd, void *dummy)
1905 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1910 ap_clear_module_list();
1911 *(ap_directive_t **)dummy = NULL;
1915 static const char *set_server_string_slot(cmd_parms *cmd, void *dummy,
1918 /* This one's pretty generic... */
1920 int offset = (int)(long)cmd->info;
1921 char *struct_ptr = (char *)cmd->server;
1923 const char *err = ap_check_cmd_context(cmd,
1924 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1929 *(const char **)(struct_ptr + offset) = arg;
1933 static const char *server_port(cmd_parms *cmd, void *dummy, const char *arg)
1935 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1942 if (port <= 0 || port >= 65536) { /* 65536 == 1<<16 */
1943 return apr_pstrcat(cmd->temp_pool, "The port number \"", arg,
1944 "\" is outside the appropriate range "
1945 "(i.e., 1..65535).", NULL);
1947 cmd->server->port = port;
1951 static const char *set_signature_flag(cmd_parms *cmd, void *d_,
1954 core_dir_config *d=d_;
1956 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1961 if (strcasecmp(arg, "On") == 0) {
1962 d->server_signature = srv_sig_on;
1964 else if (strcasecmp(arg, "Off") == 0) {
1965 d->server_signature = srv_sig_off;
1967 else if (strcasecmp(arg, "EMail") == 0) {
1968 d->server_signature = srv_sig_withmail;
1971 return "ServerSignature: use one of: off | on | email";
1976 static const char *set_server_root(cmd_parms *cmd, void *dummy,
1979 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1985 arg = ap_os_canonical_filename(cmd->pool, arg);
1987 if (!ap_is_directory(arg)) {
1988 return "ServerRoot must be a valid directory";
1990 ap_server_root = arg;
1994 static const char *set_timeout(cmd_parms *cmd, void *dummy, const char *arg)
1996 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2001 cmd->server->timeout = atoi(arg);
2005 static const char *set_keep_alive_timeout(cmd_parms *cmd, void *dummy,
2008 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2013 cmd->server->keep_alive_timeout = atoi(arg);
2017 static const char *set_keep_alive(cmd_parms *cmd, void *dummy,
2020 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2025 /* We've changed it to On/Off, but used to use numbers
2026 * so we accept anything but "Off" or "0" as "On"
2028 if (!strcasecmp(arg, "off") || !strcmp(arg, "0")) {
2029 cmd->server->keep_alive = 0;
2032 cmd->server->keep_alive = 1;
2037 static const char *set_keep_alive_max(cmd_parms *cmd, void *dummy,
2040 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2045 cmd->server->keep_alive_max = atoi(arg);
2049 static const char *set_idcheck(cmd_parms *cmd, void *d_, int arg)
2051 core_dir_config *d=d_;
2052 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2057 d->do_rfc1413 = arg != 0;
2061 static const char *set_hostname_lookups(cmd_parms *cmd, void *d_,
2064 core_dir_config *d=d_;
2066 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2071 if (!strcasecmp(arg, "on")) {
2072 d->hostname_lookups = HOSTNAME_LOOKUP_ON;
2074 else if (!strcasecmp(arg, "off")) {
2075 d->hostname_lookups = HOSTNAME_LOOKUP_OFF;
2077 else if (!strcasecmp(arg, "double")) {
2078 d->hostname_lookups = HOSTNAME_LOOKUP_DOUBLE;
2081 return "parameter must be 'on', 'off', or 'double'";
2086 static const char *set_serverpath(cmd_parms *cmd, void *dummy,
2089 const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2094 cmd->server->path = arg;
2095 cmd->server->pathlen = strlen(arg);
2099 static const char *set_content_md5(cmd_parms *cmd, void *d_, int arg)
2101 core_dir_config *d=d_;
2102 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2107 d->content_md5 = arg != 0;
2111 static const char *set_use_canonical_name(cmd_parms *cmd, void *d_,
2114 core_dir_config *d=d_;
2115 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2120 if (strcasecmp(arg, "on") == 0) {
2121 d->use_canonical_name = USE_CANONICAL_NAME_ON;
2123 else if (strcasecmp(arg, "off") == 0) {
2124 d->use_canonical_name = USE_CANONICAL_NAME_OFF;
2126 else if (strcasecmp(arg, "dns") == 0) {
2127 d->use_canonical_name = USE_CANONICAL_NAME_DNS;
2130 return "parameter must be 'on', 'off', or 'dns'";
2136 static const char *include_config (cmd_parms *cmd, void *dummy,
2139 ap_directive_t *conftree = NULL;
2141 ap_process_resource_config(cmd->server,
2142 ap_server_root_relative(cmd->pool, name),
2143 &conftree, cmd->pool, cmd->temp_pool);
2144 *(ap_directive_t **)dummy = conftree;
2148 static const char *set_loglevel(cmd_parms *cmd, void *dummy, const char *arg)
2152 const char *err = ap_check_cmd_context(cmd,
2153 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2158 if ((str = ap_getword_conf(cmd->pool, &arg))) {
2159 if (!strcasecmp(str, "emerg")) {
2160 cmd->server->loglevel = APLOG_EMERG;
2162 else if (!strcasecmp(str, "alert")) {
2163 cmd->server->loglevel = APLOG_ALERT;
2165 else if (!strcasecmp(str, "crit")) {
2166 cmd->server->loglevel = APLOG_CRIT;
2168 else if (!strcasecmp(str, "error")) {
2169 cmd->server->loglevel = APLOG_ERR;
2171 else if (!strcasecmp(str, "warn")) {
2172 cmd->server->loglevel = APLOG_WARNING;
2174 else if (!strcasecmp(str, "notice")) {
2175 cmd->server->loglevel = APLOG_NOTICE;
2177 else if (!strcasecmp(str, "info")) {
2178 cmd->server->loglevel = APLOG_INFO;
2180 else if (!strcasecmp(str, "debug")) {
2181 cmd->server->loglevel = APLOG_DEBUG;
2184 return "LogLevel requires level keyword: one of "
2185 "emerg/alert/crit/error/warn/notice/info/debug";
2189 return "LogLevel requires level keyword";
2195 API_EXPORT(const char *) ap_psignature(const char *prefix, request_rec *r)
2198 core_dir_config *conf;
2200 conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
2202 if ((conf->server_signature == srv_sig_off)
2203 || (conf->server_signature == srv_sig_unset)) {
2207 apr_snprintf(sport, sizeof sport, "%u", (unsigned) ap_get_server_port(r));
2209 if (conf->server_signature == srv_sig_withmail) {
2210 return apr_pstrcat(r->pool, prefix, "<ADDRESS>" AP_SERVER_BASEVERSION
2211 " Server at <A HREF=\"mailto:",
2212 r->server->server_admin, "\">",
2213 ap_get_server_name(r), "</A> Port ", sport,
2214 "</ADDRESS>\n", NULL);
2216 return apr_pstrcat(r->pool, prefix, "<ADDRESS>" AP_SERVER_BASEVERSION
2217 " Server at ", ap_get_server_name(r), " Port ", sport,
2218 "</ADDRESS>\n", NULL);
2222 * Load an authorisation realm into our location configuration, applying the
2223 * usual rules that apply to realms.
2225 static const char *set_authname(cmd_parms *cmd, void *mconfig,
2228 core_dir_config *aconfig = (core_dir_config *)mconfig;
2230 aconfig->ap_auth_name = ap_escape_quotes(cmd->pool, word1);
2234 #ifdef _OSD_POSIX /* BS2000 Logon Passwd file */
2235 static const char *set_bs2000_account(cmd_parms *cmd, void *dummy, char *name)
2237 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2242 return os_set_account(cmd->pool, name);
2244 #endif /*_OSD_POSIX*/
2247 * Handle a request to include the server's OS platform in the Server
2248 * response header field (the ServerTokens directive). Unfortunately
2249 * this requires a new global in order to communicate the setting back to
2250 * http_main so it can insert the information in the right place in the
2254 static char *server_version = NULL;
2255 static int version_locked = 0;
2257 enum server_token_type {
2258 SrvTk_MIN, /* eg: Apache/1.3.0 */
2259 SrvTk_OS, /* eg: Apache/1.3.0 (UNIX) */
2260 SrvTk_FULL, /* eg: Apache/1.3.0 (UNIX) PHP/3.0 FooBar/1.2b */
2261 SrvTk_PRODUCT_ONLY /* eg: Apache */
2263 static enum server_token_type ap_server_tokens = SrvTk_FULL;
2265 static apr_status_t reset_version(void *dummy)
2268 ap_server_tokens = SrvTk_FULL;
2269 server_version = NULL;
2273 API_EXPORT(const char *) ap_get_server_version(void)
2275 return (server_version ? server_version : AP_SERVER_BASEVERSION);
2278 API_EXPORT(void) ap_add_version_component(apr_pool_t *pconf, const char *component)
2280 if (! version_locked) {
2282 * If the version string is null, register our cleanup to reset the
2283 * pointer on pool destruction. We also know that, if NULL,
2284 * we are adding the original SERVER_BASEVERSION string.
2286 if (server_version == NULL) {
2287 apr_register_cleanup(pconf, NULL, reset_version,
2289 server_version = apr_pstrdup(pconf, component);
2293 * Tack the given component identifier to the end of
2294 * the existing string.
2296 server_version = apr_pstrcat(pconf, server_version, " ",
2303 * This routine adds the real server base identity to the version string,
2304 * and then locks out changes until the next reconfig.
2306 static void ap_set_version(apr_pool_t *pconf)
2308 if (ap_server_tokens == SrvTk_PRODUCT_ONLY) {
2309 ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT);
2311 else if (ap_server_tokens == SrvTk_MIN) {
2312 ap_add_version_component(pconf, AP_SERVER_BASEVERSION);
2315 ap_add_version_component(pconf, AP_SERVER_BASEVERSION " (" PLATFORM ")");
2318 * Lock the server_version string if we're not displaying
2319 * the full set of tokens
2321 if (ap_server_tokens != SrvTk_FULL) {
2326 static const char *set_serv_tokens(cmd_parms *cmd, void *dummy,
2329 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2334 if (!strcasecmp(arg, "OS")) {
2335 ap_server_tokens = SrvTk_OS;
2337 else if (!strcasecmp(arg, "Min") || !strcasecmp(arg, "Minimal")) {
2338 ap_server_tokens = SrvTk_MIN;
2340 else if (!strcasecmp(arg, "Prod") || !strcasecmp(arg, "ProductOnly")) {
2341 ap_server_tokens = SrvTk_PRODUCT_ONLY;
2344 ap_server_tokens = SrvTk_FULL;
2349 static const char *set_limit_req_line(cmd_parms *cmd, void *dummy,
2352 const char *err = ap_check_cmd_context(cmd,
2353 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2361 return apr_pstrcat(cmd->temp_pool, "LimitRequestLine \"", arg,
2362 "\" must be a non-negative integer", NULL);
2364 if (lim > DEFAULT_LIMIT_REQUEST_LINE) {
2365 return apr_psprintf(cmd->temp_pool, "LimitRequestLine \"%s\" "
2366 "must not exceed the precompiled maximum of %d",
2367 arg, DEFAULT_LIMIT_REQUEST_LINE);
2369 cmd->server->limit_req_line = lim;
2373 static const char *set_limit_req_fieldsize(cmd_parms *cmd, void *dummy,
2376 const char *err = ap_check_cmd_context(cmd,
2377 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2385 return apr_pstrcat(cmd->temp_pool, "LimitRequestFieldsize \"", arg,
2386 "\" must be a non-negative integer (0 = no limit)",
2389 if (lim > DEFAULT_LIMIT_REQUEST_FIELDSIZE) {
2390 return apr_psprintf(cmd->temp_pool, "LimitRequestFieldsize \"%s\" "
2391 "must not exceed the precompiled maximum of %d",
2392 arg, DEFAULT_LIMIT_REQUEST_FIELDSIZE);
2394 cmd->server->limit_req_fieldsize = lim;
2398 static const char *set_limit_req_fields(cmd_parms *cmd, void *dummy,
2401 const char *err = ap_check_cmd_context(cmd,
2402 NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2410 return apr_pstrcat(cmd->temp_pool, "LimitRequestFields \"", arg,
2411 "\" must be a non-negative integer (0 = no limit)",
2414 cmd->server->limit_req_fields = lim;
2418 static const char *set_limit_req_body(cmd_parms *cmd, void *conf_,
2421 core_dir_config *conf=conf_;
2422 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2427 /* WTF: If strtoul is not portable, then write a replacement.
2428 * Instead we have an idiotic define in httpd.h that prevents
2429 * it from being used even when it is available. Sheesh.
2431 conf->limit_req_body = (unsigned long)strtol(arg, (char **)NULL, 10);
2435 static const char *set_limit_xml_req_body(cmd_parms *cmd, void *conf_,
2438 core_dir_config *conf = conf_;
2439 const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2444 conf->limit_xml_body = atol(arg);
2445 if (conf->limit_xml_body < 0)
2446 return "LimitXMLRequestBody requires a non-negative integer.";
2451 API_EXPORT(size_t) ap_get_limit_xml_body(const request_rec *r)
2453 core_dir_config *conf;
2455 conf = ap_get_module_config(r->per_dir_config, &core_module);
2456 if (conf->limit_xml_body == AP_LIMIT_UNSET)
2457 return AP_DEFAULT_LIMIT_XML_BODY;
2458 return (size_t)conf->limit_xml_body;
2462 static const char *set_interpreter_source(cmd_parms *cmd, core_dir_config *d,
2465 if (!strcasecmp(arg, "registry")) {
2466 d->script_interpreter_source = INTERPRETER_SOURCE_REGISTRY;
2467 } else if (!strcasecmp(arg, "registry-strict")) {
2468 d->script_interpreter_source = INTERPRETER_SOURCE_REGISTRY_STRICT;
2469 } else if (!strcasecmp(arg, "script")) {
2470 d->script_interpreter_source = INTERPRETER_SOURCE_SHEBANG;
2472 return apr_pstrcat(cmd->temp_pool, "ScriptInterpreterSource \"", arg,
2473 "\" must be \"registry\", \"registry-strict\" or "
2474 "\"script\"", NULL);
2480 #if !defined (RLIMIT_CPU) || !(defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)) || !defined (RLIMIT_NPROC)
2481 static const char *no_set_limit(cmd_parms *cmd, core_dir_config *conf,
2482 char *arg, char *arg2)
2484 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, cmd->server,
2485 "%s not supported on this platform", cmd->cmd->name);
2491 static const char *set_limit_cpu(cmd_parms *cmd, void *conf_,
2492 const char *arg, const char *arg2)
2494 core_dir_config *conf=conf_;
2496 unixd_set_rlimit(cmd, &conf->limit_cpu, arg, arg2, RLIMIT_CPU);
2501 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)
2502 static const char *set_limit_mem(cmd_parms *cmd, void *conf_,
2503 const char *arg, const char * arg2)
2505 core_dir_config *conf=conf_;
2507 #if defined(RLIMIT_AS)
2508 unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2 ,RLIMIT_AS);
2509 #elif defined(RLIMIT_DATA)
2510 unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_DATA);
2511 #elif defined(RLIMIT_VMEM)
2512 unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_VMEM);
2519 static const char *set_limit_nproc(cmd_parms *cmd, void *conf_,
2520 const char *arg, const char * arg2)
2522 core_dir_config *conf=conf_;
2524 unixd_set_rlimit(cmd, &conf->limit_nproc, arg, arg2, RLIMIT_NPROC);
2529 #if APR_HAS_SENDFILE
2530 /* XXX handle partial writes */
2531 static apr_status_t send_the_file(request_rec *r, apr_file_t *fd,
2532 apr_hdtr_t *hdtr, apr_off_t offset,
2533 apr_size_t length, apr_size_t *nbytes)
2535 apr_int32_t flags = 0;
2537 apr_size_t n = length;
2539 if (!r->connection->keepalive) {
2540 /* Prepare the socket to be reused */
2541 flags |= APR_SENDFILE_DISCONNECT_SOCKET;
2544 rv = apr_sendfile(r->connection->client->bsock,
2545 fd, /* The file to send */
2546 hdtr, /* Header and trailer iovecs */
2547 &offset, /* Offset in file to begin sending from */
2555 static apr_status_t writev_it_all(apr_socket_t *s, struct iovec *vec, int nvec,
2556 apr_size_t len, apr_ssize_t *nbytes)
2558 apr_size_t bytes_written = 0;
2560 apr_ssize_t n = len;
2563 /* XXX handle checking for non-blocking socket */
2564 while (bytes_written != len) {
2565 rv = apr_sendv(s, vec + i, nvec - i, &n);
2567 if (rv != APR_SUCCESS)
2570 /* If the write did not complete, adjust the iovecs and issue
2573 if (bytes_written < len) {
2574 /* Skip over the vectors that have already been written */
2575 apr_size_t cnt = vec[i].iov_len;
2578 cnt += vec[i].iov_len;
2582 /* Handle partial write of vec i */
2583 vec[i].iov_base = (char *) vec[i].iov_base +
2584 (vec[i].iov_len - (cnt - n));
2585 vec[i].iov_len = cnt -n;
2588 n = len - bytes_written;
2593 /* Note --- ErrorDocument will now work from .htaccess files.
2594 * The AllowOverride of Fileinfo allows webmasters to turn it off
2597 static const command_rec core_cmds[] = {
2599 /* Old access config file commands */
2601 AP_INIT_RAW_ARGS("<Directory", dirsection, NULL, RSRC_CONF,
2602 "Container for directives affecting resources located in the specified "
2604 AP_INIT_RAW_ARGS("<Location", urlsection, NULL, RSRC_CONF,
2605 "Container for directives affecting resources accessed through the "
2606 "specified URL paths"),
2607 AP_INIT_RAW_ARGS("<VirtualHost", virtualhost_section, NULL, RSRC_CONF,
2608 "Container to map directives to a particular virtual host, takes one or "
2609 "more host addresses"),
2610 AP_INIT_RAW_ARGS("<Files", filesection, NULL, OR_ALL,
2611 "Container for directives affecting files matching specified patterns"),
2612 AP_INIT_RAW_ARGS("<Limit", ap_limit_section, NULL, OR_ALL,
2613 "Container for authentication directives when accessed using specified HTTP "
2615 AP_INIT_RAW_ARGS("<LimitExcept", ap_limit_section, (void*)1, OR_ALL,
2616 "Container for authentication directives to be applied when any HTTP "
2617 "method other than those specified is used to access the resource"),
2618 AP_INIT_TAKE1("<IfModule", start_ifmod, NULL, EXEC_ON_READ | OR_ALL,
2619 "Container for directives based on existance of specified modules"),
2620 AP_INIT_TAKE1("<IfDefine", start_ifdefine, NULL, EXEC_ON_READ | OR_ALL,
2621 "Container for directives based on existance of command line defines"),
2622 AP_INIT_RAW_ARGS("<DirectoryMatch", dirsection, (void*)1, RSRC_CONF,
2623 "Container for directives affecting resources located in the "
2624 "specified directories"),
2625 AP_INIT_RAW_ARGS("<LocationMatch", urlsection, (void*)1, RSRC_CONF,
2626 "Container for directives affecting resources accessed through the "
2627 "specified URL paths"),
2628 AP_INIT_RAW_ARGS("<FilesMatch", filesection, (void*)1, OR_ALL,
2629 "Container for directives affecting files matching specified patterns"),
2630 AP_INIT_TAKE1("AuthType", ap_set_string_slot,
2631 (void*)XtOffsetOf(core_dir_config, ap_auth_type), OR_AUTHCFG,
2632 "An HTTP authorization type (e.g., \"Basic\")"),
2633 AP_INIT_TAKE1("AuthName", set_authname, NULL, OR_AUTHCFG,
2634 "The authentication realm (e.g. \"Members Only\")"),
2635 AP_INIT_RAW_ARGS("Require", require, NULL, OR_AUTHCFG,
2636 "Selects which authenticated users or groups may access a protected space"),
2637 AP_INIT_TAKE1("Satisfy", satisfy, NULL, OR_AUTHCFG,
2638 "access policy if both allow and require used ('all' or 'any')"),
2640 AP_INIT_TAKE1("GprofDir", set_gprof_dir, NULL, RSRC_CONF,
2641 "Directory to plop gmon.out files"),
2643 AP_INIT_TAKE1("AddDefaultCharset", set_add_default_charset, NULL, OR_FILEINFO,
2644 "The name of the default charset to add to any Content-Type without one or 'Off' to disable"),
2646 /* Old resource config file commands */
2648 AP_INIT_RAW_ARGS("AccessFileName", set_access_name, NULL, RSRC_CONF,
2649 "Name(s) of per-directory config files (default: .htaccess)"),
2650 AP_INIT_TAKE1("DocumentRoot", set_document_root, NULL, RSRC_CONF,
2651 "Root directory of the document tree"),
2652 AP_INIT_TAKE2("ErrorDocument", set_error_document, NULL, OR_FILEINFO,
2653 "Change responses for HTTP errors"),
2654 AP_INIT_RAW_ARGS("AllowOverride", set_override, NULL, ACCESS_CONF,
2655 "Controls what groups of directives can be configured by per-directory "
2657 AP_INIT_RAW_ARGS("Options", set_options, NULL, OR_OPTIONS,
2658 "Set a number of attributes for a given directory"),
2659 AP_INIT_TAKE1("DefaultType", ap_set_string_slot,
2660 (void*)XtOffsetOf (core_dir_config, ap_default_type),
2661 OR_FILEINFO, "the default MIME type for untypable files"),
2663 /* Old server config file commands */
2665 AP_INIT_TAKE1("Port", server_port, NULL, RSRC_CONF, "A TCP port number"),
2666 AP_INIT_TAKE1("HostnameLookups", set_hostname_lookups, NULL,
2667 ACCESS_CONF|RSRC_CONF,
2668 "\"on\" to enable, \"off\" to disable reverse DNS lookups, or \"double\" to "
2669 "enable double-reverse DNS lookups"),
2670 AP_INIT_TAKE1("ServerAdmin", set_server_string_slot,
2671 (void *)XtOffsetOf (server_rec, server_admin), RSRC_CONF,
2672 "The email address of the server administrator"),
2673 AP_INIT_TAKE1("ServerName", set_server_string_slot,
2674 (void *)XtOffsetOf (server_rec, server_hostname), RSRC_CONF,
2675 "The hostname of the server"),
2676 AP_INIT_TAKE1("ServerSignature", set_signature_flag, NULL, OR_ALL,
2677 "En-/disable server signature (on|off|email)"),
2678 AP_INIT_TAKE1("ServerRoot", set_server_root, NULL, RSRC_CONF,
2679 "Common directory of server-related files (logs, confs, etc.)"),
2680 AP_INIT_TAKE1("ErrorLog", set_server_string_slot,
2681 (void *)XtOffsetOf (server_rec, error_fname), RSRC_CONF,
2682 "The filename of the error log"),
2683 AP_INIT_RAW_ARGS("ServerAlias", set_server_alias, NULL, RSRC_CONF,
2684 "A name or names alternately used to access the server"),
2685 AP_INIT_TAKE1("ServerPath", set_serverpath, NULL, RSRC_CONF,
2686 "The pathname the server can be reached at"),
2687 AP_INIT_TAKE1("Timeout", set_timeout, NULL, RSRC_CONF,
2688 "Timeout duration (sec)"),
2689 AP_INIT_TAKE1("KeepAliveTimeout", set_keep_alive_timeout, NULL, RSRC_CONF,
2690 "Keep-Alive timeout duration (sec)"),
2691 AP_INIT_TAKE1("MaxKeepAliveRequests", set_keep_alive_max, NULL, RSRC_CONF,
2692 "Maximum number of Keep-Alive requests per connection, or 0 for infinite"),
2693 AP_INIT_TAKE1("KeepAlive", set_keep_alive, NULL, RSRC_CONF,
2694 "Whether persistent connections should be On or Off"),
2695 AP_INIT_FLAG("IdentityCheck", set_idcheck, NULL, RSRC_CONF|ACCESS_CONF,
2696 "Enable identd (RFC 1413) user lookups - SLOW"),
2697 AP_INIT_FLAG("ContentDigest", set_content_md5, NULL, OR_OPTIONS,
2698 "whether or not to send a Content-MD5 header with each request"),
2699 AP_INIT_TAKE1("UseCanonicalName", set_use_canonical_name, NULL,
2700 RSRC_CONF|ACCESS_CONF,
2701 "How to work out the ServerName : Port when constructing URLs"),
2702 /* TODO: RlimitFoo should all be part of mod_cgi, not in the core */
2703 AP_INIT_ITERATE("AddModule", add_module_command, NULL,
2704 RSRC_CONF, "The name of a module"),
2705 AP_INIT_NO_ARGS("ClearModuleList", clear_module_list_command, NULL,
2707 /* TODO: ListenBacklog in MPM */
2708 AP_INIT_TAKE1("Include", include_config, NULL,
2709 (RSRC_CONF | ACCESS_CONF | EXEC_ON_READ),
2710 "Name of the config file to be included"),
2711 AP_INIT_TAKE1("LogLevel", set_loglevel, NULL, RSRC_CONF,
2712 "Level of verbosity in error logging"),
2713 AP_INIT_TAKE1("NameVirtualHost", ap_set_name_virtual_host, NULL, RSRC_CONF,
2714 "A numeric IP address:port, or the name of a host"),
2716 AP_INIT_TAKE1("BS2000Account", set_bs2000_account, NULL, RSRC_CONF,
2717 "Name of server User's bs2000 logon account name"),
2720 AP_INIT_TAKE1("ScriptInterpreterSource", set_interpreter_source, NULL,
2722 "Where to find interpreter to run Win32 scripts (Registry or script shebang line)"),
2724 AP_INIT_TAKE1("ServerTokens", set_serv_tokens, NULL, RSRC_CONF,
2725 "Determine tokens displayed in the Server: header - Min(imal), OS or Full"),
2726 AP_INIT_TAKE1("LimitRequestLine", set_limit_req_line, NULL, RSRC_CONF,
2727 "Limit on maximum size of an HTTP request line"),
2728 AP_INIT_TAKE1("LimitRequestFieldsize", set_limit_req_fieldsize, NULL,
2730 "Limit on maximum size of an HTTP request header field"),
2731 AP_INIT_TAKE1("LimitRequestFields", set_limit_req_fields, NULL, RSRC_CONF,
2732 "Limit (0 = unlimited) on max number of header fields in a request message"),
2733 AP_INIT_TAKE1("LimitRequestBody", set_limit_req_body,
2734 (void*)XtOffsetOf(core_dir_config, limit_req_body), OR_ALL,
2735 "Limit (in bytes) on maximum size of request message body"),
2736 AP_INIT_TAKE1("LimitXMLRequestBody", set_limit_xml_req_body, NULL, OR_ALL,
2737 "Limit (in bytes) on maximum size of an XML-based request "
2740 /* System Resource Controls */
2742 AP_INIT_TAKE12("RLimitCPU", set_limit_cpu,
2743 (void*)XtOffsetOf(core_dir_config, limit_cpu),
2744 OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
2746 AP_INIT_TAKE12("RLimitCPU", no_set_limit, NULL,
2747 OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
2749 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined (RLIMIT_AS)
2750 AP_INIT_TAKE12("RLimitMEM", set_limit_mem,
2751 (void*)XtOffsetOf(core_dir_config, limit_mem),
2752 OR_ALL, "Soft/hard limits for max memory usage per process"),
2754 AP_INIT_TAKE12("RLimitMEM", no_set_limit, NULL,
2755 OR_ALL, "Soft/hard limits for max memory usage per process"),
2758 AP_INIT_TAKE12("RLimitNPROC", set_limit_nproc,
2759 (void*)XtOffsetOf(core_dir_config, limit_nproc),
2760 OR_ALL, "soft/hard limits for max number of processes per uid"),
2762 AP_INIT_TAKE12("RLimitNPROC", no_set_limit, NULL,
2763 OR_ALL, "soft/hard limits for max number of processes per uid"),
2765 /* XXX This should be allowable in .htaccess files, but currently it won't
2766 * play well with the Options stuff. Until that is fixed, I would prefer
2767 * to leave it just in the conf file. Other should feel free to disagree
2770 AP_INIT_ITERATE("AddOutputFilter", add_filter, NULL, ACCESS_CONF,
2771 "filters to be run"),
2775 /*****************************************************************
2777 * Core handlers for various phases of server operation...
2780 API_EXPORT_NONSTD(int) ap_core_translate(request_rec *r)
2782 void *sconf = r->server->module_config;
2783 core_server_config *conf = ap_get_module_config(sconf, &core_module);
2786 return HTTP_FORBIDDEN;
2788 if ((r->uri[0] != '/') && strcmp(r->uri, "*")) {
2789 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2790 "Invalid URI in request %s", r->the_request);
2791 return HTTP_BAD_REQUEST;
2795 && !strncmp(r->uri, r->server->path, r->server->pathlen)
2796 && (r->server->path[r->server->pathlen - 1] == '/'
2797 || r->uri[r->server->pathlen] == '/'
2798 || r->uri[r->server->pathlen] == '\0')) {
2799 r->filename = apr_pstrcat(r->pool, conf->ap_document_root,
2800 (r->uri + r->server->pathlen), NULL);
2804 * Make sure that we do not mess up the translation by adding two
2805 * /'s in a row. This happens under windows when the document
2806 * root ends with a /
2808 if ((conf->ap_document_root[strlen(conf->ap_document_root)-1] == '/')
2809 && (*(r->uri) == '/')) {
2810 r->filename = apr_pstrcat(r->pool, conf->ap_document_root, r->uri+1,
2814 r->filename = apr_pstrcat(r->pool, conf->ap_document_root, r->uri,
2822 static int do_nothing(request_rec *r) { return OK; }
2825 * Default handler for MIME types without other handlers. Only GET
2826 * and OPTIONS at this point... anyone who wants to write a generic
2827 * handler for PUT or POST is free to do so, but it seems unwise to provide
2828 * any defaults yet... So, for now, we assume that this will always be
2829 * the last handler called and return 405 or 501.
2832 static int default_handler(request_rec *r)
2834 core_dir_config *d =
2835 (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
2836 int rangestatus, errstatus;
2837 apr_file_t *fd = NULL;
2838 apr_status_t status;
2839 #ifdef USE_MMAP_FILES
2840 apr_mmap_t *mm = NULL;
2843 /* This handler has no use for a request body (yet), but we still
2844 * need to read and discard it if the client sent one.
2846 if ((errstatus = ap_discard_request_body(r)) != OK) {
2850 ap_allow_methods(r, MERGE_ALLOW, "GET", "OPTIONS", NULL);
2852 if (r->method_number == M_INVALID) {
2853 ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2854 "Invalid method in request %s", r->the_request);
2855 return HTTP_NOT_IMPLEMENTED;
2857 if (r->method_number == M_OPTIONS) {
2858 return ap_send_http_options(r);
2860 if (r->method_number == M_PUT) {
2861 return HTTP_METHOD_NOT_ALLOWED;
2863 if (r->finfo.protection == 0 || (r->path_info && *r->path_info)) {
2864 ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r,
2865 "File does not exist: %s",r->path_info ?
2866 apr_pstrcat(r->pool, r->filename, r->path_info, NULL)
2868 return HTTP_NOT_FOUND;
2870 if (r->method_number != M_GET) {
2871 return HTTP_METHOD_NOT_ALLOWED;
2874 if ((status = apr_open(&fd, r->filename, APR_READ | APR_BINARY, 0, r->pool)) != APR_SUCCESS) {
2875 ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r,
2876 "file permissions deny server access: %s", r->filename);
2877 return HTTP_FORBIDDEN;
2879 ap_update_mtime(r, r->finfo.mtime);
2880 ap_set_last_modified(r);
2882 apr_table_setn(r->headers_out, "Accept-Ranges", "bytes");
2883 if (((errstatus = ap_meets_conditions(r)) != OK)
2884 || (errstatus = ap_set_content_length(r, r->finfo.size))) {
2889 #ifdef CHARSET_EBCDIC
2890 if (d->content_md5 & 1) {
2891 /* The call to ap_checkconv() in ap_send_http_header() is
2892 * sufficient for most paths. Sending the MD5 digest in a
2893 * header is special in that any change to translation decided
2894 * by ap_checkconv() must be done before building that header,
2895 * and thus before calling ap_send_http_header().
2899 #endif /* CHARSET_EBCDIC */
2901 #ifdef USE_MMAP_FILES
2902 if ((r->finfo.size >= MMAP_THRESHOLD)
2903 && (r->finfo.size < MMAP_LIMIT)
2904 && (!r->header_only || (d->content_md5 & 1))) {
2905 /* we need to protect ourselves in case we die while we've got the
2907 apr_status_t status;
2908 if ((status = apr_mmap_create(&mm, fd, 0, r->finfo.size, r->pool)) != APR_SUCCESS) {
2909 ap_log_rerror(APLOG_MARK, APLOG_CRIT, status, r,
2910 "default_handler: mmap failed: %s", r->filename);
2922 if (d->content_md5 & 1) {
2923 apr_table_setn(r->headers_out, "Content-MD5",
2924 ap_md5digest(r->pool, fd,
2928 if (d->content_md5 & 1) {
2929 apr_table_setn(r->headers_out, "Content-MD5",
2930 ap_md5digest(r->pool, fd));
2932 #endif /* APACHE_XLATE */
2934 rangestatus = ap_set_byterange(r);
2936 ap_send_http_header(r);
2938 if (!r->header_only) {
2939 apr_size_t length = r->finfo.size;
2940 apr_off_t offset = 0;
2941 apr_size_t nbytes = 0;
2944 ap_send_fd(fd, r, offset, length, &nbytes);
2947 while (ap_each_byterange(r, &offset, &length)) {
2948 if ((status = ap_send_fd(fd, r, offset, length, &nbytes)) != APR_SUCCESS) {
2949 ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
2950 "error byteserving file: %s", r->filename);
2951 return HTTP_INTERNAL_SERVER_ERROR;
2957 #ifdef USE_MMAP_FILES
2960 unsigned char *addr;
2961 apr_mmap_offset((void**)&addr, mm ,0);
2963 if (d->content_md5 & 1) {
2964 apr_md5_ctx_t context;
2966 apr_MD5Init(&context);
2968 if (r->rrx->to_net) {
2969 apr_MD5SetXlate(&context, r->rrx->to_net);
2972 apr_MD5Update(&context, addr, (unsigned int)r->finfo.size);
2973 apr_table_setn(r->headers_out, "Content-MD5",
2974 ap_md5contextTo64(r->pool, &context));
2977 rangestatus = ap_set_byterange(r);
2978 ap_send_http_header(r);
2980 if (!r->header_only) {
2982 ap_send_mmap(mm, r, 0, r->finfo.size);
2987 while (ap_each_byterange(r, &offset, &length)) {
2988 ap_send_mmap(mm, r, offset, length);
2999 * This is a relatively simple filter to coalesce many small buckets into
3000 * one large bucket. This implementation of buffer_filter will only coalesce
3001 * a single contiguous string of coalesable buckets. It will not coalesce
3002 * multiple non-contiguous buckets.
3004 * For example, if a brigade contains 10 small buckets followed by a
3005 * large bucket (or a pipe or file bucket) followed by more small buckets,
3006 * only the first 10 buckets will be coalesced.
3008 typedef struct BUFFER_FILTER_CTX {
3009 char *buf; /* Start of buffer */
3010 char *cur; /* Pointer to next location to write */
3011 apr_ssize_t cnt; /* Number of bytes put in buf */
3012 apr_ssize_t avail; /* Number of bytes available in the buf */
3013 } buffer_filter_ctx_t;
3014 #define FILTER_BUFF_SIZE 8192
3015 #define MIN_BUCKET_SIZE 200
3016 static apr_status_t buffer_filter(ap_filter_t *f, ap_bucket_brigade *b)
3019 apr_pool_t *p = f->r->pool;
3020 ap_bucket *e, *insert_before = NULL, *destroy_me = NULL;
3021 buffer_filter_ctx_t *ctx = f->ctx;
3022 int pass_the_brigade = 0, insert_first = 0;
3025 f->ctx = ctx = apr_pcalloc(p, sizeof(buffer_filter_ctx_t));
3026 ctx->avail = FILTER_BUFF_SIZE;
3033 /* Iterate across the buckets, coalescing the small buckets into a
3036 AP_BRIGADE_FOREACH(e, b) {
3038 ap_bucket_destroy(destroy_me);
3041 if ((e->type == AP_BUCKET_EOS) || (e->type == AP_BUCKET_FILE) ||
3042 (e->type == AP_BUCKET_PIPE)) {
3043 pass_the_brigade = 1;
3048 rv = e->read(e, &str, &n, 0);
3049 if (rv != APR_SUCCESS) {
3050 /* XXX: log error */
3053 if ((n < MIN_BUCKET_SIZE) && (n < ctx->avail)) {
3054 /* Coalesce this bucket into the buffer */
3055 if (ctx->buf == NULL) {
3056 ctx->buf = apr_palloc(p, FILTER_BUFF_SIZE);
3057 ctx->cur = ctx->buf;
3060 memcpy(ctx->cur, str, n);
3064 /* If this is the first bucket to be coalesced, don't remove it
3065 * from the brigade. Save it as a marker for where to insert
3066 * ctx->buf into the brigade when we're done.
3068 if (insert_before || insert_first){
3069 AP_BUCKET_REMOVE(e);
3076 else if (insert_before || insert_first) {
3077 /* This bucket was not able to be coalesced because it either
3078 * exceeds MIN_BUCKET_SIZE or its contents will not fit into
3079 * buf. We're done...
3081 pass_the_brigade = 1;
3085 /* If there is even a single bucket that cannot be coalesced,
3086 * then we must pass the brigade down to the next filter.
3088 pass_the_brigade = 1;
3094 ap_bucket_destroy(destroy_me);
3098 if (pass_the_brigade) {
3099 /* Insert ctx->buf into the correct spotin the brigade */
3101 e = ap_bucket_create_transient(ctx->buf, ctx->cnt);
3102 AP_BRIGADE_INSERT_HEAD(b, e);
3104 else if (insert_before) {
3105 e = ap_bucket_create_transient(ctx->buf, ctx->cnt);
3106 AP_BUCKET_INSERT_BEFORE(e, insert_before);
3107 AP_BUCKET_REMOVE(insert_before);
3108 ap_bucket_destroy(insert_before);
3109 insert_before = NULL;
3111 rv = ap_pass_brigade(f->next, b);
3112 if (rv != APR_SUCCESS) {
3113 /* XXX: Log the error */
3116 /* Get ctx->buf ready for the next brigade */
3118 ctx->cur = ctx->buf;
3120 ctx->avail = FILTER_BUFF_SIZE;
3124 if (insert_before) {
3125 AP_BUCKET_REMOVE(insert_before);
3126 ap_bucket_destroy(insert_before);
3128 /* The brigade should be empty now because all the buckets
3129 * were coalesced into the buffer_filter buf
3136 * HTTP/1.1 chunked transfer encoding filter.
3138 static apr_status_t chunk_filter(ap_filter_t *f, ap_bucket_brigade *b)
3140 ap_bucket_brigade *more = NULL;
3144 for (more = NULL; b; b = more, more = NULL) {
3145 apr_off_t bytes = 0;
3146 ap_bucket *eos = NULL;
3147 char chunk_hdr[20]; /* enough space for the snprintf below */
3149 AP_BRIGADE_FOREACH(e, b) {
3150 if (e->type == AP_BUCKET_EOS) {
3151 /* there shouldn't be anything after the eos */
3155 else if (e->length == -1) {
3156 /* unknown amount of data (e.g. a pipe) */
3160 rv = e->read(e, &data, &len, 1);
3161 if (rv != APR_SUCCESS) {
3166 * There may be a new next bucket representing the
3167 * rest of the data stream on which a read() may
3168 * block so we pass down what we have so far.
3171 more = ap_brigade_split(b, AP_BUCKET_NEXT(e));
3175 /* If there was nothing in this bucket then we can
3176 * safely move on to the next one without pausing
3177 * to pass down what we have counted up so far.
3188 * XXX: if there aren't very many bytes at this point it may
3189 * be a good idea to set them aside and return for more,
3190 * unless we haven't finished counting this brigade yet.
3193 /* if there are content bytes, then wrap them in a chunk */
3198 * Insert the chunk header, specifying the number of bytes in
3201 /* XXX might be nice to have APR_OFF_T_FMT_HEX */
3202 hdr_len = apr_snprintf(chunk_hdr, sizeof(chunk_hdr),
3203 "%qx" CRLF, (apr_uint64_t)bytes);
3204 e = ap_bucket_create_transient(chunk_hdr, hdr_len);
3205 AP_BRIGADE_INSERT_HEAD(b, e);
3208 * Insert the end-of-chunk CRLF before the EOS bucket, or
3209 * appended to the brigade
3211 e = ap_bucket_create_immortal(CRLF, 2);
3213 AP_BUCKET_INSERT_BEFORE(eos, e);
3216 AP_BRIGADE_INSERT_TAIL(b, e);
3220 /* RFC 2616, Section 3.6.1
3222 * If there is an EOS bucket, then prefix it with:
3223 * 1) the last-chunk marker ("0" CRLF)
3225 * 3) the end-of-chunked body CRLF
3227 * If there is no EOS bucket, then do nothing.
3229 * XXX: it would be nice to combine this with the end-of-chunk
3230 * marker above, but this is a bit more straight-forward for
3234 /* XXX: (2) trailers ... does not yet exist */
3235 e = ap_bucket_create_immortal("0" CRLF /* <trailers> */ CRLF, 5);
3236 AP_BUCKET_INSERT_BEFORE(eos, e);
3239 /* pass the brigade to the next filter. */
3240 rv = ap_pass_brigade(f->next, b);
3241 if (rv != APR_SUCCESS || eos != NULL) {
3249 static int core_input_filter(ap_filter_t *f, ap_bucket_brigade *b)
3252 apr_size_t length = HUGE_STRING_LEN;
3253 apr_socket_t *csock = NULL;
3256 /* As soon as we have pool buckets, this should become a palloc. */
3257 buff = apr_palloc(f->c->pool, HUGE_STRING_LEN);
3258 ap_bpop_socket(&csock, f->c->client);
3260 if (apr_recv(csock, buff, &length) == APR_SUCCESS) {
3261 /* This should probably be a pool bucket, but using a transient is
3262 * actually okay here too. We know the pool we are using will always
3263 * be available as long as the connection is open.
3265 e = ap_bucket_create_transient(buff, length);
3266 AP_BRIGADE_INSERT_TAIL(b, e);
3271 /* Default filter. This filter should almost always be used. Its only job
3272 * is to send the headers if they haven't already been sent, and then send
3275 static int core_output_filter(ap_filter_t *f, ap_bucket_brigade *b)
3277 request_rec *r = f->r;
3278 apr_pool_t *p = r->pool;
3280 apr_ssize_t bytes_sent = 0, len = 0;
3284 #if 0 /* XXX: bit rot! */
3285 /* This will all be needed once BUFF is removed from the code */
3286 /* At this point we need to discover if there was any data saved from
3287 * the last call to core_output_filter.
3289 b = ap_get_saved_data(f, &b);
3291 /* It is very obvious that we need to make sure it makes sense to send data
3292 * out at this point.
3296 len += dptr->length;
3299 if (len < MIN_SIZE_TO_WRITE && b->tail->color != AP_BUCKET_EOS) {
3300 ap_save_data_to_filter(f, &b);
3306 apr_array_header_t *vec_trailers = NULL;
3307 int nvec_trailers= 0;
3308 apr_array_header_t *vec;
3311 apr_file_t *fd = NULL;
3312 apr_ssize_t flen = 0;
3313 apr_off_t foffset = 0;
3315 vec = apr_make_array(p, 1, sizeof(struct iovec));
3317 /* Hijack the data in BUFF to send on apr_sendv */
3318 iov = (struct iovec *) apr_push_array(vec);
3319 iov->iov_base = r->connection->client->outbase;
3320 iov->iov_len = r->connection->client->outcnt;
3321 r->connection->client->outcnt = 0;
3325 /* Iterate across the buckets and build an iovec array.
3326 * XXX The chunk filter gives us some very small chunks to send.
3327 * Consider buffering some of these chunks into a contiguous piece
3330 AP_BRIGADE_FOREACH(e, b) {
3334 case AP_BUCKET_FILE:
3335 /* Assume there is at most one AP_BUCKET_FILE in the brigade */
3338 foffset = e->offset;
3344 rv = e->read(e, &str, &n, 0);
3350 iov = (struct iovec *) apr_push_array(vec);
3353 /* The bucket is a trailer to a file bucket */
3355 if (vec_trailers == NULL) {
3356 vec_trailers = apr_make_array(p, 1, sizeof(struct iovec));
3358 iov = (struct iovec *) apr_push_array(vec_trailers);
3360 iov->iov_base = (char *)str;
3367 /* there shouldn't be anything after the eos */
3368 if (e->type == AP_BUCKET_EOS) {
3373 /* We're done iterating across the buckets. Time to do network i/o.
3374 * XXX Set socket i/o timeout and blocking characteristics.
3375 * XXX We should consider eliminating ap_send_mmap and using ap_send_fd
3376 * instead. Defer the decision on whether to use sendfile, mmap, or
3377 * buffered file reads to the core filter.
3380 #if APR_HAS_SENDFILE
3382 apr_hdtr_t *hdtr = apr_pcalloc(r->pool, sizeof(*hdtr));
3384 hdtr->numheaders = nvec;
3385 hdtr->headers = (struct iovec *) vec->elts;
3387 if (nvec_trailers) {
3388 hdtr->numtrailers = nvec_trailers;
3389 hdtr->trailers = (struct iovec *) vec_trailers->elts;
3392 rv = send_the_file(r, fd, hdtr, foffset, flen, &bytes_sent);
3394 if (rv == APR_SUCCESS) {
3395 ap_brigade_destroy(b);
3398 /* If apr_sendfile is not implemented (e.g. Win95/98), then
3399 * use apr_senv() to send the content.
3401 if (rv != APR_ENOTIMPL) {
3402 ap_brigade_destroy(b);
3403 /* check_first_conn_error(r, "send_fd", rv); */
3406 /* XXX: If we made it this far, sendfile must have failed with
3407 * APR_ENOTIMPL. Read the file into an iovec array to prepare
3412 rv = writev_it_all(r->connection->client->bsock,
3413 (struct iovec*) vec->elts, nvec,
3416 ap_brigade_destroy(b);
3424 static const handler_rec core_handlers[] = {
3425 { "*/*", default_handler },
3426 { "default-handler", default_handler },
3430 static void core_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
3432 ap_set_version(pconf);
3435 static void core_open_logs(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
3437 ap_open_logs(s, pconf);
3440 static const char *core_method(const request_rec *r)
3443 static unsigned short core_port(const request_rec *r)
3444 { return DEFAULT_HTTP_PORT; }
3446 static int core_post_read_req(request_rec *r)
3448 ap_add_filter("CORE", NULL, r);
3452 static void core_register_filter(request_rec *r)
3455 core_dir_config *conf = (core_dir_config *)
3456 ap_get_module_config(r->per_dir_config,
3458 char **items = (char **)conf->filters->elts;
3460 for (i = 0; i < conf->filters->nelts; i++) {
3461 char *foobar = items[i];
3462 ap_add_filter(foobar, NULL, r);
3466 static void register_hooks(void)
3468 ap_hook_post_config(core_post_config,NULL,NULL,AP_HOOK_REALLY_FIRST);
3469 ap_hook_translate_name(ap_core_translate,NULL,NULL,AP_HOOK_REALLY_LAST);
3470 ap_hook_process_connection(ap_process_http_connection,NULL,NULL,
3471 AP_HOOK_REALLY_LAST);
3472 ap_hook_http_method(core_method,NULL,NULL,AP_HOOK_REALLY_LAST);
3473 ap_hook_default_port(core_port,NULL,NULL,AP_HOOK_REALLY_LAST);
3474 ap_hook_open_logs(core_open_logs,NULL,NULL,AP_HOOK_MIDDLE);
3475 /* FIXME: I suspect we can eliminate the need for these - Ben */
3476 ap_hook_type_checker(do_nothing,NULL,NULL,AP_HOOK_REALLY_LAST);
3477 ap_hook_access_checker(do_nothing,NULL,NULL,AP_HOOK_REALLY_LAST);
3478 ap_hook_post_read_request(core_post_read_req, NULL, NULL, AP_HOOK_REALLY_FIRST);
3480 /* define the CORE filter, then register a hook to insert it at
3481 * request-processing time.
3483 ap_hook_insert_filter(core_register_filter, NULL, NULL, AP_HOOK_MIDDLE);
3484 ap_register_input_filter("CORE_IN", core_input_filter, AP_FTYPE_CONNECTION);
3485 ap_register_output_filter("CORE", core_output_filter, AP_FTYPE_CONNECTION + 1);
3486 ap_register_output_filter("CHUNK", chunk_filter, AP_FTYPE_CONNECTION);
3487 ap_register_output_filter("BUFFER", buffer_filter, AP_FTYPE_CONNECTION);
3490 API_VAR_EXPORT module core_module = {
3491 STANDARD20_MODULE_STUFF,
3492 create_core_dir_config, /* create per-directory config structure */
3493 merge_core_dir_configs, /* merge per-directory config structures */
3494 create_core_server_config, /* create per-server config structure */
3495 merge_core_server_configs, /* merge per-server config structures */
3496 core_cmds, /* command apr_table_t */
3497 core_handlers, /* handlers */
3498 register_hooks /* register hooks */