]> granicus.if.org Git - apache/blob - server/core.c
We also need to increment *readbytes when we find a match in the middle of
[apache] / server / core.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2001 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
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
17  *    distribution.
18  *
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.
25  *
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.
30  *
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.
34  *
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
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
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/>.
53  *
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.
57  */
58
59 #include "apr.h"
60 #include "apr_strings.h"
61 #include "apr_lib.h"
62 #include "apr_fnmatch.h"
63 #include "apr_hash.h"
64 #include "apr_thread_proc.h"    /* for RLIMIT stuff */
65
66 #define APR_WANT_IOVEC
67 #define APR_WANT_STRFUNC
68 #define APR_WANT_MEMFUNC
69 #include "apr_want.h"
70
71 #define CORE_PRIVATE
72 #include "ap_config.h"
73 #include "httpd.h"
74 #include "http_config.h"
75 #include "http_core.h"
76 #include "http_protocol.h"      /* For index_of_response().  Grump. */
77 #include "http_request.h"
78 #include "http_vhost.h"
79 #include "http_main.h"          /* For the default_handler below... */
80 #include "http_log.h"
81 #include "rfc1413.h"
82 #include "util_md5.h"
83 #include "http_connection.h"
84 #include "apr_buckets.h"
85 #include "util_filter.h"
86 #include "util_ebcdic.h"
87 #include "mpm.h"
88 #include "mpm_common.h"
89 #include "scoreboard.h"
90 #include "mod_core.h"
91
92
93 /* LimitXMLRequestBody handling */
94 #define AP_LIMIT_UNSET                  ((long) -1)
95 #define AP_DEFAULT_LIMIT_XML_BODY       ((size_t)1000000)
96
97 #define AP_MIN_SENDFILE_BYTES           (256)
98
99 APR_HOOK_STRUCT(
100     APR_HOOK_LINK(get_mgmt_items)
101 )
102
103 AP_IMPLEMENT_HOOK_RUN_ALL(int, get_mgmt_items,
104                           (apr_pool_t *p, const char *val, apr_hash_t *ht),
105                           (p, val, ht), OK, DECLINED)
106
107
108 /* Server core module... This module provides support for really basic
109  * server operations, including options and commands which control the
110  * operation of other modules.  Consider this the bureaucracy module.
111  *
112  * The core module also defines handlers, etc., do handle just enough
113  * to allow a server with the core module ONLY to actually serve documents
114  * (though it slaps DefaultType on all of 'em); this was useful in testing,
115  * but may not be worth preserving.
116  *
117  * This file could almost be mod_core.c, except for the stuff which affects
118  * the http_conf_globals.
119  */
120
121 static void *create_core_dir_config(apr_pool_t *a, char *dir)
122 {
123     core_dir_config *conf;
124
125     conf = (core_dir_config *)apr_pcalloc(a, sizeof(core_dir_config));
126     
127     /* conf->r and conf->d[_*] are initialized in */
128
129     conf->opts = dir ? OPT_UNSET : OPT_UNSET|OPT_ALL;
130     conf->opts_add = conf->opts_remove = OPT_NONE;
131     conf->override = dir ? OR_UNSET : OR_UNSET|OR_ALL;
132
133     conf->content_md5 = 2;
134
135     conf->use_canonical_name = USE_CANONICAL_NAME_UNSET;
136
137     conf->hostname_lookups = HOSTNAME_LOOKUP_UNSET;
138     conf->do_rfc1413 = DEFAULT_RFC1413 | 2; /* set bit 1 to indicate default */
139     conf->satisfy = SATISFY_NOSPEC;
140
141 #ifdef RLIMIT_CPU
142     conf->limit_cpu = NULL;
143 #endif
144 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
145     conf->limit_mem = NULL;
146 #endif
147 #ifdef RLIMIT_NPROC
148     conf->limit_nproc = NULL;
149 #endif
150
151     conf->limit_req_body = 0;
152     conf->limit_xml_body = AP_LIMIT_UNSET;
153     conf->sec_file = apr_array_make(a, 2, sizeof(ap_conf_vector_t *));
154
155     conf->server_signature = srv_sig_unset;
156
157     conf->add_default_charset = ADD_DEFAULT_CHARSET_UNSET;
158     conf->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
159
160     /* Overriding all negotiation 
161      */
162     conf->mime_type = NULL;
163     conf->handler = NULL;
164     conf->output_filters = NULL;
165     conf->input_filters = NULL;
166     return (void *)conf;
167 }
168
169 static void *merge_core_dir_configs(apr_pool_t *a, void *basev, void *newv)
170 {
171     core_dir_config *base = (core_dir_config *)basev;
172     core_dir_config *new = (core_dir_config *)newv;
173     core_dir_config *conf;
174     int i;
175   
176     conf = (core_dir_config *)apr_palloc(a, sizeof(core_dir_config));
177     memcpy((char *)conf, (const char *)base, sizeof(core_dir_config));
178     if (base->response_code_strings) {
179         conf->response_code_strings =
180             apr_palloc(a, sizeof(*conf->response_code_strings)
181                       * RESPONSE_CODES);
182         memcpy(conf->response_code_strings, base->response_code_strings,
183                sizeof(*conf->response_code_strings) * RESPONSE_CODES);
184     }
185     
186     conf->d = new->d;
187     conf->d_is_fnmatch = new->d_is_fnmatch;
188     conf->d_components = new->d_components;
189     conf->r = new->r;
190     
191     if (new->opts & OPT_UNSET) {
192         /* there was no explicit setting of new->opts, so we merge
193          * preserve the invariant (opts_add & opts_remove) == 0
194          */
195         conf->opts_add = (conf->opts_add & ~new->opts_remove) | new->opts_add;
196         conf->opts_remove = (conf->opts_remove & ~new->opts_add)
197                             | new->opts_remove;
198         conf->opts = (conf->opts & ~conf->opts_remove) | conf->opts_add;
199         if ((base->opts & OPT_INCNOEXEC) && (new->opts & OPT_INCLUDES)) {
200             conf->opts = (conf->opts & ~OPT_INCNOEXEC) | OPT_INCLUDES;
201         }
202     }
203     else {
204         /* otherwise we just copy, because an explicit opts setting
205          * overrides all earlier +/- modifiers
206          */
207         conf->opts = new->opts;
208         conf->opts_add = new->opts_add;
209         conf->opts_remove = new->opts_remove;
210     }
211
212     if (!(new->override & OR_UNSET)) {
213         conf->override = new->override;
214     }
215     if (new->ap_default_type) {
216         conf->ap_default_type = new->ap_default_type;
217     }
218     
219     if (new->ap_auth_type) {
220         conf->ap_auth_type = new->ap_auth_type;
221     }
222     if (new->ap_auth_name) {
223         conf->ap_auth_name = new->ap_auth_name;
224     }
225     if (new->ap_requires) {
226         conf->ap_requires = new->ap_requires;
227     }
228
229     if (new->response_code_strings) {
230         if (conf->response_code_strings == NULL) {
231             conf->response_code_strings = apr_palloc(a,
232                 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
233             memcpy(conf->response_code_strings, new->response_code_strings,
234                    sizeof(*conf->response_code_strings) * RESPONSE_CODES);
235         }
236         else {
237             for (i = 0; i < RESPONSE_CODES; ++i) {
238                 if (new->response_code_strings[i] != NULL) {
239                     conf->response_code_strings[i]
240                         = new->response_code_strings[i];
241                 }
242             }
243         }
244     }
245     if (new->hostname_lookups != HOSTNAME_LOOKUP_UNSET) {
246         conf->hostname_lookups = new->hostname_lookups;
247     }
248     if ((new->do_rfc1413 & 2) == 0) {
249         conf->do_rfc1413 = new->do_rfc1413;
250     }
251     if ((new->content_md5 & 2) == 0) {
252         conf->content_md5 = new->content_md5;
253     }
254     if (new->use_canonical_name != USE_CANONICAL_NAME_UNSET) {
255         conf->use_canonical_name = new->use_canonical_name;
256     }
257
258 #ifdef RLIMIT_CPU
259     if (new->limit_cpu) {
260         conf->limit_cpu = new->limit_cpu;
261     }
262 #endif
263 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
264     if (new->limit_mem) {
265         conf->limit_mem = new->limit_mem;
266     }
267 #endif
268 #ifdef RLIMIT_NPROC
269     if (new->limit_nproc) {
270         conf->limit_nproc = new->limit_nproc;
271     }
272 #endif
273
274     if (new->limit_req_body) {
275         conf->limit_req_body = new->limit_req_body;
276     }
277
278     if (new->limit_xml_body != AP_LIMIT_UNSET)
279         conf->limit_xml_body = new->limit_xml_body;
280     else
281         conf->limit_xml_body = base->limit_xml_body;
282
283     conf->sec_file = apr_array_append(a, base->sec_file, new->sec_file);
284
285     if (new->satisfy != SATISFY_NOSPEC) {
286         conf->satisfy = new->satisfy;
287     }
288
289     if (new->server_signature != srv_sig_unset) {
290         conf->server_signature = new->server_signature;
291     }
292
293     if (new->add_default_charset != ADD_DEFAULT_CHARSET_UNSET) {
294         conf->add_default_charset = new->add_default_charset;
295         if (new->add_default_charset_name) {
296             conf->add_default_charset_name = new->add_default_charset_name;
297         }
298     }
299
300     /* Overriding all negotiation 
301      */
302     if (new->mime_type) {
303         conf->mime_type = new->mime_type;
304     }
305     if (new->handler) {
306         conf->handler = new->handler;
307     }
308     if (new->output_filters) {
309         conf->output_filters = new->output_filters;
310     }
311     if (new->input_filters) {
312         conf->input_filters = new->input_filters;
313     }
314     return (void*)conf;
315 }
316
317 static void *create_core_server_config(apr_pool_t *a, server_rec *s)
318 {
319     core_server_config *conf;
320     int is_virtual = s->is_virtual;
321   
322     conf = (core_server_config *)apr_pcalloc(a, sizeof(core_server_config));
323 #ifdef GPROF
324     conf->gprof_dir = NULL;
325 #endif
326     conf->access_name = is_virtual ? NULL : DEFAULT_ACCESS_FNAME;
327     conf->ap_document_root = is_virtual ? NULL : DOCUMENT_LOCATION;
328     conf->sec_dir = apr_array_make(a, 40, sizeof(ap_conf_vector_t *));
329     conf->sec_url = apr_array_make(a, 40, sizeof(ap_conf_vector_t *));
330     
331     return (void *)conf;
332 }
333
334 static void *merge_core_server_configs(apr_pool_t *p, void *basev, void *virtv)
335 {
336     core_server_config *base = (core_server_config *)basev;
337     core_server_config *virt = (core_server_config *)virtv;
338     core_server_config *conf;
339
340     conf = (core_server_config *)apr_pcalloc(p, sizeof(core_server_config));
341     *conf = *virt;
342     if (!conf->access_name) {
343         conf->access_name = base->access_name;
344     }
345     if (!conf->ap_document_root) {
346         conf->ap_document_root = base->ap_document_root;
347     }
348     conf->sec_dir = apr_array_append(p, base->sec_dir, virt->sec_dir);
349     conf->sec_url = apr_array_append(p, base->sec_url, virt->sec_url);
350
351     return conf;
352 }
353
354 /* Add per-directory configuration entry (for <directory> section);
355  * these are part of the core server config.
356  */
357
358 AP_CORE_DECLARE(void) ap_add_per_dir_conf(server_rec *s, void *dir_config)
359 {
360     core_server_config *sconf = ap_get_module_config(s->module_config,
361                                                      &core_module);
362     void **new_space = (void **)apr_array_push(sconf->sec_dir);
363     
364     *new_space = dir_config;
365 }
366
367 AP_CORE_DECLARE(void) ap_add_per_url_conf(server_rec *s, void *url_config)
368 {
369     core_server_config *sconf = ap_get_module_config(s->module_config,
370                                                      &core_module);
371     void **new_space = (void **)apr_array_push(sconf->sec_url);
372     
373     *new_space = url_config;
374 }
375
376 AP_CORE_DECLARE(void) ap_add_file_conf(core_dir_config *conf, void *url_config)
377 {
378     void **new_space = (void **)apr_array_push(conf->sec_file);
379     
380     *new_space = url_config;
381 }
382
383 /* We need to do a stable sort, qsort isn't stable.  So to make it stable
384  * we'll be maintaining the original index into the list, and using it
385  * as the minor key during sorting.  The major key is the number of
386  * components (where the root component is zero).
387  */
388 struct reorder_sort_rec {
389     ap_conf_vector_t *elt;
390     int orig_index;
391 };
392
393 static int reorder_sorter(const void *va, const void *vb)
394 {
395     const struct reorder_sort_rec *a = va;
396     const struct reorder_sort_rec *b = vb;
397     core_dir_config *core_a;
398     core_dir_config *core_b;
399
400     core_a = ap_get_module_config(a->elt, &core_module);
401     core_b = ap_get_module_config(b->elt, &core_module);
402
403     /* a regex always sorts after a non-regex
404      */
405     if (!core_a->r && core_b->r) {
406         return -1;
407     }
408     else if (core_a->r && !core_b->r) {
409         return 1;
410     }
411     /* we always sort next by the number of components
412      */
413     if (core_a->d_components < core_b->d_components) {
414         return -1;
415     }
416     else if (core_a->d_components > core_b->d_components) {
417         return 1;
418     }
419     /* They have the same number of components, we now have to compare
420      * the minor key to maintain the original order (from the config.) 
421      */
422     return a->orig_index - b->orig_index;
423 }
424
425 void ap_core_reorder_directories(apr_pool_t *p, server_rec *s)
426 {
427     core_server_config *sconf;
428     apr_array_header_t *sec_dir;
429     struct reorder_sort_rec *sortbin;
430     int nelts;
431     ap_conf_vector_t **elts;
432     int i;
433     apr_pool_t *tmp;
434
435     sconf = ap_get_module_config(s->module_config, &core_module);
436     sec_dir = sconf->sec_dir;
437     nelts = sec_dir->nelts;
438     elts = (ap_conf_vector_t **)sec_dir->elts;
439
440     /* we have to allocate tmp space to do a stable sort */
441     apr_pool_create(&tmp, p);
442     sortbin = apr_palloc(tmp, sec_dir->nelts * sizeof(*sortbin));
443     for (i = 0; i < nelts; ++i) {
444         sortbin[i].orig_index = i;
445         sortbin[i].elt = elts[i];
446     }
447
448     qsort(sortbin, nelts, sizeof(*sortbin), reorder_sorter);
449
450     /* and now copy back to the original array */
451     for (i = 0; i < nelts; ++i) {
452       elts[i] = sortbin[i].elt;
453     }
454
455     apr_pool_destroy(tmp);
456 }
457
458 /*****************************************************************
459  *
460  * There are some elements of the core config structures in which
461  * other modules have a legitimate interest (this is ugly, but necessary
462  * to preserve NCSA back-compatibility).  So, we have a bunch of accessors
463  * here...
464  */
465
466 AP_DECLARE(int) ap_allow_options(request_rec *r)
467 {
468     core_dir_config *conf = 
469       (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module); 
470
471     return conf->opts; 
472
473
474 AP_DECLARE(int) ap_allow_overrides(request_rec *r) 
475
476     core_dir_config *conf;
477     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
478                                                    &core_module); 
479
480     return conf->override; 
481
482
483 AP_DECLARE(const char *) ap_auth_type(request_rec *r)
484 {
485     core_dir_config *conf;
486
487     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
488                                                    &core_module); 
489     return conf->ap_auth_type;
490 }
491
492 AP_DECLARE(const char *) ap_auth_name(request_rec *r)
493 {
494     core_dir_config *conf;
495
496     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
497                                                    &core_module); 
498     return conf->ap_auth_name;
499 }
500
501 AP_DECLARE(const char *) ap_default_type(request_rec *r)
502 {
503     core_dir_config *conf;
504
505     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
506                                                    &core_module); 
507     return conf->ap_default_type 
508                ? conf->ap_default_type 
509                : DEFAULT_CONTENT_TYPE;
510 }
511
512 AP_DECLARE(const char *) ap_document_root(request_rec *r) /* Don't use this! */
513 {
514     core_server_config *conf;
515
516     conf = (core_server_config *)ap_get_module_config(r->server->module_config,
517                                                       &core_module); 
518     return conf->ap_document_root;
519 }
520
521 AP_DECLARE(const apr_array_header_t *) ap_requires(request_rec *r)
522 {
523     core_dir_config *conf;
524
525     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
526                                                    &core_module); 
527     return conf->ap_requires;
528 }
529
530 AP_DECLARE(int) ap_satisfies(request_rec *r)
531 {
532     core_dir_config *conf;
533
534     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
535                                                    &core_module);
536
537     return conf->satisfy;
538 }
539
540 /* Should probably just get rid of this... the only code that cares is
541  * part of the core anyway (and in fact, it isn't publicised to other
542  * modules).
543  */
544
545 char *ap_response_code_string(request_rec *r, int error_index)
546 {
547     core_dir_config *conf;
548
549     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
550                                                    &core_module); 
551
552     if (conf->response_code_strings == NULL) {
553         return NULL;
554     }
555     return conf->response_code_strings[error_index];
556 }
557
558
559 /* Code from Harald Hanche-Olsen <hanche@imf.unit.no> */
560 static APR_INLINE void do_double_reverse (conn_rec *conn)
561 {
562     apr_sockaddr_t *sa;
563     apr_status_t rv;
564
565     if (conn->double_reverse) {
566         /* already done */
567         return;
568     }
569     if (conn->remote_host == NULL || conn->remote_host[0] == '\0') {
570         /* single reverse failed, so don't bother */
571         conn->double_reverse = -1;
572         return;
573     }
574     rv = apr_sockaddr_info_get(&sa, conn->remote_host, APR_UNSPEC, 0, 0, conn->pool);
575     if (rv == APR_SUCCESS) {
576         while (sa) {
577             if (sa->ipaddr_len == conn->remote_addr->ipaddr_len &&
578                 !memcmp(sa->ipaddr_ptr, conn->remote_addr->ipaddr_ptr,
579                         sa->ipaddr_len)) {
580                 conn->double_reverse = 1;
581                 return;
582             }
583 #if APR_HAVE_IPV6
584             /* match IPv4-mapped IPv6 addresses with IPv4 A record */
585             if (conn->remote_addr->sa.sin.sin_family == APR_INET6 &&
586                 sa->sa.sin.sin_family == APR_INET &&
587                 IN6_IS_ADDR_V4MAPPED((struct in6_addr *)conn->remote_addr->ipaddr_ptr) &&
588                 !memcmp(&((struct in6_addr *)conn->remote_addr->ipaddr_ptr)->s6_addr[12],
589                         sa->ipaddr_ptr,
590                         sizeof (((struct in_addr *)0)->s_addr))) {
591                 conn->double_reverse = 1;
592                 return;
593             }
594 #endif
595             sa = sa->next;
596         }
597     }
598     conn->double_reverse = -1;
599 }
600
601 AP_DECLARE(const char *) ap_get_remote_host(conn_rec *conn, void *dir_config,
602                                             int type, int *str_is_ip)
603 {
604     int hostname_lookups;
605
606     if (str_is_ip) { /* if caller wants to know */
607         *str_is_ip = 0;
608     }
609
610     /* If we haven't checked the host name, and we want to */
611     if (dir_config) {
612         hostname_lookups =
613             ((core_dir_config *)ap_get_module_config(dir_config, &core_module))
614                 ->hostname_lookups;
615         if (hostname_lookups == HOSTNAME_LOOKUP_UNSET) {
616             hostname_lookups = HOSTNAME_LOOKUP_OFF;
617         }
618     }
619     else {
620         /* the default */
621         hostname_lookups = HOSTNAME_LOOKUP_OFF;
622     }
623
624     if (type != REMOTE_NOLOOKUP
625         && conn->remote_host == NULL
626         && (type == REMOTE_DOUBLE_REV
627             || hostname_lookups != HOSTNAME_LOOKUP_OFF)) {
628         apr_sockaddr_t *remote_addr;
629
630         apr_socket_addr_get(&remote_addr, APR_REMOTE, conn->client_socket);
631         if (apr_getnameinfo(&conn->remote_host, remote_addr, 0) == APR_SUCCESS) {
632             ap_str_tolower(conn->remote_host);
633            
634             if (hostname_lookups == HOSTNAME_LOOKUP_DOUBLE) {
635                 do_double_reverse(conn);
636                 if (conn->double_reverse != 1) {
637                     conn->remote_host = NULL;
638                 }
639             }
640         }
641         /* if failed, set it to the NULL string to indicate error */
642         if (conn->remote_host == NULL) {
643             conn->remote_host = "";
644         }
645     }
646     if (type == REMOTE_DOUBLE_REV) {
647         do_double_reverse(conn);
648         if (conn->double_reverse == -1) {
649             return NULL;
650         }
651     }
652
653 /*
654  * Return the desired information; either the remote DNS name, if found,
655  * or either NULL (if the hostname was requested) or the IP address
656  * (if any identifier was requested).
657  */
658     if (conn->remote_host != NULL && conn->remote_host[0] != '\0') {
659         return conn->remote_host;
660     }
661     else {
662         if (type == REMOTE_HOST || type == REMOTE_DOUBLE_REV) {
663             return NULL;
664         }
665         else {
666             if (str_is_ip) { /* if caller wants to know */
667                 *str_is_ip = 1;
668             }
669             return conn->remote_ip;
670         }
671     }
672 }
673
674 AP_DECLARE(const char *) ap_get_remote_logname(request_rec *r)
675 {
676     core_dir_config *dir_conf;
677
678     if (r->connection->remote_logname != NULL) {
679         return r->connection->remote_logname;
680     }
681
682 /* If we haven't checked the identity, and we want to */
683     dir_conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
684                                                        &core_module);
685
686     if (dir_conf->do_rfc1413 & 1) {
687         return ap_rfc1413(r->connection, r->server);
688     }
689     else {
690         return NULL;
691     }
692 }
693
694 /* There are two options regarding what the "name" of a server is.  The
695  * "canonical" name as defined by ServerName and Port, or the "client's
696  * name" as supplied by a possible Host: header or full URI.  We never
697  * trust the port passed in the client's headers, we always use the
698  * port of the actual socket.
699  *
700  * The DNS option to UseCanonicalName causes this routine to do a
701  * reverse lookup on the local IP address of the connection and use
702  * that for the ServerName. This makes its value more reliable while
703  * at the same time allowing Demon's magic virtual hosting to work.
704  * The assumption is that DNS lookups are sufficiently quick...
705  * -- fanf 1998-10-03
706  */
707 AP_DECLARE(const char *) ap_get_server_name(request_rec *r)
708 {
709     conn_rec *conn = r->connection;
710     core_dir_config *d;
711
712     d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
713                                                 &core_module);
714
715     if (d->use_canonical_name == USE_CANONICAL_NAME_OFF) {
716         return r->hostname ? r->hostname : r->server->server_hostname;
717     }
718     if (d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
719         if (conn->local_host == NULL) {
720             apr_sockaddr_t *local_addr;
721
722             apr_socket_addr_get(&local_addr, APR_LOCAL, conn->client_socket);
723             if (apr_getnameinfo(&conn->local_host, local_addr, 0) != APR_SUCCESS)
724                 conn->local_host = apr_pstrdup(conn->pool, r->server->server_hostname);
725             else {
726                 ap_str_tolower(conn->local_host);
727             }
728         }
729         return conn->local_host;
730     }
731     /* default */
732     return r->server->server_hostname;
733 }
734
735 AP_DECLARE(apr_port_t) ap_get_server_port(const request_rec *r)
736 {
737     apr_port_t port;
738     core_dir_config *d =
739       (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
740     
741     port = r->server->port ? r->server->port : ap_default_port(r);
742
743     if (d->use_canonical_name == USE_CANONICAL_NAME_OFF
744         || d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
745         if (r->hostname) {
746             apr_sockaddr_t *localsa;
747
748             apr_socket_addr_get(&localsa, APR_LOCAL, r->connection->client_socket);
749             apr_sockaddr_port_get(&port, localsa);
750         }
751     }
752     /* default */
753     return port;
754 }
755
756 AP_DECLARE(char *) ap_construct_url(apr_pool_t *p, const char *uri,
757                                     request_rec *r)
758 {
759     unsigned port = ap_get_server_port(r);
760     const char *host = ap_get_server_name(r);
761
762     if (ap_is_default_port(port, r)) {
763         return apr_pstrcat(p, ap_http_method(r), "://", host, uri, NULL);
764     }
765     return apr_psprintf(p, "%s://%s:%u%s", ap_http_method(r), host, port, uri);
766 }
767
768 AP_DECLARE(unsigned long) ap_get_limit_req_body(const request_rec *r)
769 {
770     core_dir_config *d =
771       (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
772     
773     return d->limit_req_body;
774 }
775
776
777 /*****************************************************************
778  *
779  * Commands... this module handles almost all of the NCSA httpd.conf
780  * commands, but most of the old srm.conf is in the the modules.
781  */
782
783
784 /* returns a parent if it matches the given directive */
785 static const ap_directive_t * find_parent(const ap_directive_t *dirp,
786                                           const char *what)
787 {
788     while (dirp->parent != NULL) {
789         dirp = dirp->parent;
790         /* ### it would be nice to have atom-ized directives */
791         if (strcasecmp(dirp->directive, what) == 0)
792             return dirp;
793     }
794     return NULL;
795 }
796
797 AP_DECLARE(const char *) ap_check_cmd_context(cmd_parms *cmd,
798                                               unsigned forbidden)
799 {
800     const char *gt = (cmd->cmd->name[0] == '<'
801                       && cmd->cmd->name[strlen(cmd->cmd->name)-1] != '>')
802                          ? ">" : "";
803     const ap_directive_t *found;
804
805     if ((forbidden & NOT_IN_VIRTUALHOST) && cmd->server->is_virtual) {
806         return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
807                           " cannot occur within <VirtualHost> section", NULL);
808     }
809
810     if ((forbidden & NOT_IN_LIMIT) && cmd->limited != -1) {
811         return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
812                           " cannot occur within <Limit> section", NULL);
813     }
814
815     if ((forbidden & NOT_IN_DIR_LOC_FILE) == NOT_IN_DIR_LOC_FILE
816         && cmd->path != NULL) {
817         return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
818                           " cannot occur within <Directory/Location/Files> "
819                           "section", NULL);
820     }
821     
822     if (((forbidden & NOT_IN_DIRECTORY)
823          && ((found = find_parent(cmd->directive, "<Directory"))
824              || (found = find_parent(cmd->directive, "<DirectoryMatch"))))
825         || ((forbidden & NOT_IN_LOCATION)
826             && ((found = find_parent(cmd->directive, "<Location"))
827                 || (found = find_parent(cmd->directive, "<LocationMatch"))))
828         || ((forbidden & NOT_IN_FILES)
829             && ((found = find_parent(cmd->directive, "<Files"))
830                 || (found = find_parent(cmd->directive, "<FilesMatch"))))) {
831         return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
832                           " cannot occur within ", found->directive,
833                           "> section", NULL);
834     }
835
836     return NULL;
837 }
838
839 static const char *set_access_name(cmd_parms *cmd, void *dummy,
840                                    const char *arg)
841 {
842     void *sconf = cmd->server->module_config;
843     core_server_config *conf = ap_get_module_config(sconf, &core_module);
844
845     const char *err = ap_check_cmd_context(cmd,
846                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
847     if (err != NULL) {
848         return err;
849     }
850
851     conf->access_name = apr_pstrdup(cmd->pool, arg);
852     return NULL;
853 }
854
855 #ifdef GPROF
856 static const char *set_gprof_dir(cmd_parms *cmd, void *dummy, const char *arg)
857 {
858     void *sconf = cmd->server->module_config;
859     core_server_config *conf = ap_get_module_config(sconf, &core_module);
860
861     const char *err = ap_check_cmd_context(cmd,
862                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
863     if (err != NULL) {
864         return err;
865     }
866
867     conf->gprof_dir = apr_pstrdup(cmd->pool, arg);
868     return NULL;
869 }
870 #endif /*GPROF*/
871
872 static const char *set_add_default_charset(cmd_parms *cmd, 
873                                            void *d_, const char *arg)
874 {
875     core_dir_config *d=d_;
876
877     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
878     if (err != NULL) {
879         return err;
880     }
881     if (!strcasecmp(arg, "Off")) {
882        d->add_default_charset = ADD_DEFAULT_CHARSET_OFF;
883     }
884     else if (!strcasecmp(arg, "On")) {
885        d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
886        d->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
887     }
888     else {
889        d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
890        d->add_default_charset_name = arg;
891     }
892     return NULL;
893 }
894
895 static const char *set_document_root(cmd_parms *cmd, void *dummy,
896                                      const char *arg)
897 {
898     void *sconf = cmd->server->module_config;
899     core_server_config *conf = ap_get_module_config(sconf, &core_module);
900   
901     const char *err = ap_check_cmd_context(cmd,
902                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
903     if (err != NULL) {
904         return err;
905     }
906
907     /* TODO: ap_configtestonly && ap_docrootcheck && */
908     /* XXX Shouldn't this be relative to ServerRoot ??? */
909     if (apr_filepath_merge((char**)&conf->ap_document_root, NULL, arg,
910                            APR_FILEPATH_TRUENAME, cmd->pool) != APR_SUCCESS
911         || !ap_is_directory(cmd->pool, arg)) {
912         if (cmd->server->is_virtual) {
913             ap_log_perror(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, cmd->pool,
914                          "Warning: DocumentRoot [%s] does not exist",
915                          arg);
916             conf->ap_document_root = arg;
917         }
918         else {
919             return "DocumentRoot must be a directory";
920         }
921     }
922     return NULL;
923 }
924
925 AP_DECLARE(void) ap_custom_response(request_rec *r, int status, char *string)
926 {
927     core_dir_config *conf = 
928         ap_get_module_config(r->per_dir_config, &core_module);
929     int idx;
930
931     if(conf->response_code_strings == NULL) {
932         conf->response_code_strings = 
933             apr_pcalloc(r->pool,
934                     sizeof(*conf->response_code_strings) * 
935                     RESPONSE_CODES);
936     }
937
938     idx = ap_index_of_response(status);
939
940     conf->response_code_strings[idx] = 
941        ((ap_is_url(string) || (*string == '/')) && (*string != '"')) ? 
942        apr_pstrdup(r->pool, string) : apr_pstrcat(r->pool, "\"", string, NULL);
943 }
944
945 static const char *set_error_document(cmd_parms *cmd, void *conf_,
946                                       const char *errno_str, const char *msg)
947 {
948     core_dir_config *conf=conf_;
949     int error_number, index_number, idx500;
950     enum { MSG, LOCAL_PATH, REMOTE_PATH } what = MSG;
951                 
952     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
953     if (err != NULL) {
954         return err;
955     }
956
957     /* 1st parameter should be a 3 digit number, which we recognize;
958      * convert it into an array index
959      */
960     error_number = atoi(errno_str);
961     idx500 = ap_index_of_response(HTTP_INTERNAL_SERVER_ERROR);
962
963     if (error_number == HTTP_INTERNAL_SERVER_ERROR) {
964         index_number = idx500;
965     }
966     else if ((index_number = ap_index_of_response(error_number)) == idx500) {
967         return apr_pstrcat(cmd->pool, "Unsupported HTTP response code ",
968                           errno_str, NULL);
969     }
970
971     /* Heuristic to determine second argument. */
972     if (ap_strchr_c(msg,' ')) 
973         what = MSG;
974     else if (msg[0] == '/')
975         what = LOCAL_PATH;
976     else if (ap_is_url(msg))
977         what = REMOTE_PATH;
978     else
979         what = MSG;
980    
981     /* The entry should be ignored if it is a full URL for a 401 error */
982
983     if (error_number == 401 && what == REMOTE_PATH) {
984         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, cmd->server,
985                      "cannot use a full URL in a 401 ErrorDocument "
986                      "directive --- ignoring!");
987     }
988     else { /* Store it... */
989         if (conf->response_code_strings == NULL) {
990             conf->response_code_strings =
991                 apr_pcalloc(cmd->pool,
992                            sizeof(*conf->response_code_strings) * RESPONSE_CODES);
993         }
994         /* hack. Prefix a " if it is a msg; as that is what
995          * http_protocol.c relies on to distinguish between
996          * a msg and a (local) path.
997          */
998         conf->response_code_strings[index_number] = (what == MSG) ?
999                 apr_pstrcat(cmd->pool, "\"",msg,NULL) :
1000                 apr_pstrdup(cmd->pool, msg);
1001     }   
1002
1003     return NULL;
1004 }
1005
1006 static const char *set_override(cmd_parms *cmd, void *d_, const char *l)
1007 {
1008     core_dir_config *d=d_;
1009     char *w;
1010   
1011     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1012     if (err != NULL) {
1013         return err;
1014     }
1015
1016     d->override = OR_NONE;
1017     while (l[0]) {
1018         w = ap_getword_conf(cmd->pool, &l);
1019         if (!strcasecmp(w, "Limit")) {
1020             d->override |= OR_LIMIT;
1021         }
1022         else if (!strcasecmp(w, "Options")) {
1023             d->override |= OR_OPTIONS;
1024         }
1025         else if (!strcasecmp(w, "FileInfo")) {
1026             d->override |= OR_FILEINFO;
1027         }
1028         else if (!strcasecmp(w, "AuthConfig")) {
1029             d->override |= OR_AUTHCFG;
1030         }
1031         else if (!strcasecmp(w, "Indexes")) {
1032             d->override |= OR_INDEXES;
1033         }
1034         else if (!strcasecmp(w, "None")) {
1035             d->override = OR_NONE;
1036         }
1037         else if (!strcasecmp(w, "All")) {
1038             d->override = OR_ALL;
1039         }
1040         else {
1041             return apr_pstrcat(cmd->pool, "Illegal override option ", w, NULL);
1042         }
1043         d->override &= ~OR_UNSET;
1044     }
1045
1046     return NULL;
1047 }
1048
1049 static const char *set_options(cmd_parms *cmd, void *d_, const char *l)
1050 {
1051     core_dir_config *d=d_;
1052     allow_options_t opt;
1053     int first = 1;
1054     char action;
1055
1056     while (l[0]) {
1057         char *w = ap_getword_conf(cmd->pool, &l);
1058         action = '\0';
1059
1060         if (*w == '+' || *w == '-') {
1061             action = *(w++);
1062         }
1063         else if (first) {
1064             d->opts = OPT_NONE;
1065             first = 0;
1066         }
1067             
1068         if (!strcasecmp(w, "Indexes")) {
1069             opt = OPT_INDEXES;
1070         }
1071         else if (!strcasecmp(w, "Includes")) {
1072             opt = OPT_INCLUDES;
1073         }
1074         else if (!strcasecmp(w, "IncludesNOEXEC")) {
1075             opt = (OPT_INCLUDES | OPT_INCNOEXEC);
1076         }
1077         else if (!strcasecmp(w, "FollowSymLinks")) {
1078             opt = OPT_SYM_LINKS;
1079         }
1080         else if (!strcasecmp(w, "SymLinksIfOwnerMatch")) {
1081             opt = OPT_SYM_OWNER;
1082         }
1083         else if (!strcasecmp(w, "execCGI")) {
1084             opt = OPT_EXECCGI;
1085         }
1086         else if (!strcasecmp(w, "MultiViews")) {
1087             opt = OPT_MULTI;
1088         }
1089         else if (!strcasecmp(w, "RunScripts")) { /* AI backcompat. Yuck */
1090             opt = OPT_MULTI|OPT_EXECCGI;
1091         }
1092         else if (!strcasecmp(w, "None")) {
1093             opt = OPT_NONE;
1094         }
1095         else if (!strcasecmp(w, "All")) {
1096             opt = OPT_ALL;
1097         }
1098         else {
1099             return apr_pstrcat(cmd->pool, "Illegal option ", w, NULL);
1100         }
1101
1102         /* we ensure the invariant (d->opts_add & d->opts_remove) == 0 */
1103         if (action == '-') {
1104             d->opts_remove |= opt;
1105             d->opts_add &= ~opt;
1106             d->opts &= ~opt;
1107         }
1108         else if (action == '+') {
1109             d->opts_add |= opt;
1110             d->opts_remove &= ~opt;
1111             d->opts |= opt;
1112         }
1113         else {
1114             d->opts |= opt;
1115         }
1116     }
1117
1118     return NULL;
1119 }
1120
1121 static const char *satisfy(cmd_parms *cmd, void *c_, const char *arg)
1122 {
1123     core_dir_config *c=c_;
1124
1125     if (!strcasecmp(arg, "all")) {
1126         c->satisfy = SATISFY_ALL;
1127     }
1128     else if (!strcasecmp(arg, "any")) {
1129         c->satisfy = SATISFY_ANY;
1130     }
1131     else {
1132         return "Satisfy either 'any' or 'all'.";
1133     }
1134     return NULL;
1135 }
1136
1137 static const char *require(cmd_parms *cmd, void *c_, const char *arg)
1138 {
1139     require_line *r;
1140     core_dir_config *c=c_;
1141
1142     if (!c->ap_requires) {
1143         c->ap_requires = apr_array_make(cmd->pool, 2, sizeof(require_line));
1144     }
1145     r = (require_line *)apr_array_push(c->ap_requires);
1146     r->requirement = apr_pstrdup(cmd->pool, arg);
1147     r->method_mask = cmd->limited;
1148     return NULL;
1149 }
1150
1151 AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd, void *dummy,
1152                                                   const char *arg) {
1153     const char *limited_methods = ap_getword(cmd->pool, &arg, '>');
1154     void *tog = cmd->cmd->cmd_data;
1155     apr_int64_t limited = 0;
1156     const char *errmsg;
1157   
1158     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1159     if (err != NULL) {
1160         return err;
1161     }
1162
1163     while (limited_methods[0]) {
1164         char *method = ap_getword_conf(cmd->pool, &limited_methods);
1165         int methnum;
1166
1167         /* check for builtin or module registered method number */
1168         methnum = ap_method_number_of(method);
1169
1170         if (methnum == M_TRACE && !tog) {
1171             return "TRACE cannot be controlled by <Limit>";
1172         }
1173         else if (methnum == M_INVALID) {
1174             /* method has not been registered yet, but resorce restriction
1175              * is always checked before method handling, so register it.
1176              */
1177             methnum = ap_method_register(cmd->pool, method);
1178         }
1179         limited |= (AP_METHOD_BIT << methnum);
1180     }
1181
1182     /* Killing two features with one function,
1183      * if (tog == NULL) <Limit>, else <LimitExcept>
1184      */
1185     cmd->limited = tog ? ~limited : limited;
1186
1187     errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context);
1188
1189     cmd->limited = -1;
1190
1191     return errmsg;
1192 }
1193
1194 /* XXX: Bogus - need to do this differently (at least OS2/Netware suffer
1195  * the same problem!!!
1196  * We use this in <DirectoryMatch> and <FilesMatch>, to ensure that 
1197  * people don't get bitten by wrong-cased regex matches
1198  */
1199
1200 #ifdef WIN32
1201 #define USE_ICASE REG_ICASE
1202 #else
1203 #define USE_ICASE 0
1204 #endif
1205
1206 /*
1207  * Report a missing-'>' syntax error.
1208  */
1209 static char *unclosed_directive(cmd_parms *cmd)
1210 {
1211     return apr_pstrcat(cmd->pool, cmd->cmd->name,
1212                       "> directive missing closing '>'", NULL);
1213 }
1214
1215 static const char *dirsection(cmd_parms *cmd, void *mconfig, const char *arg)
1216 {
1217     const char *errmsg;
1218     const char *endp = ap_strrchr_c(arg, '>');
1219     int old_overrides = cmd->override;
1220     char *old_path = cmd->path;
1221     core_dir_config *conf;
1222     ap_conf_vector_t *new_dir_conf = ap_create_per_dir_config(cmd->pool);
1223     regex_t *r = NULL;
1224     const command_rec *thiscmd = cmd->cmd;
1225
1226     const char *err = ap_check_cmd_context(cmd,
1227                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1228     if (err != NULL) {
1229         return err;
1230     }
1231
1232     if (endp == NULL) {
1233         return unclosed_directive(cmd);
1234     }
1235
1236     arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1237
1238     if (!arg) {
1239         if (thiscmd->cmd_data)
1240             return "<DirectoryMatch > block must specify a path";
1241         else
1242             return "<Directory > block must specify a path";
1243     }
1244
1245     cmd->path = ap_getword_conf(cmd->pool, &arg);
1246     cmd->override = OR_ALL|ACCESS_CONF;
1247
1248     if (!strcmp(cmd->path, "~")) {
1249         cmd->path = ap_getword_conf(cmd->pool, &arg);
1250         if (!cmd->path)
1251             return "<Directory ~ > block must specify a path";
1252     }
1253     else if (thiscmd->cmd_data) { /* <DirectoryMatch> */
1254         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1255     }
1256     else if (cmd->path[strlen(cmd->path) - 1] != '/') {
1257         cmd->path = apr_pstrcat(cmd->pool, cmd->path, "/", NULL);
1258
1259         if (!strcmp(cmd->path, "/") == 0) 
1260         {
1261             char *newpath;
1262             /* Ensure that the pathname is canonical */
1263             if (apr_filepath_merge(&newpath, NULL, cmd->path, 
1264                                    APR_FILEPATH_TRUENAME, cmd->pool) != APR_SUCCESS) {
1265                 return apr_pstrcat(cmd->pool, "<Directory \"", cmd->path,
1266                                    "\"> path is invalid.", NULL);
1267             }
1268             cmd->path = newpath;
1269         }
1270     }
1271     /* initialize our config and fetch it */
1272     conf = ap_set_config_vectors(cmd->server, new_dir_conf, cmd->path,
1273                                  &core_module, cmd->pool);
1274
1275     errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_dir_conf);
1276     if (errmsg != NULL)
1277         return errmsg;
1278
1279     conf->r = r;
1280     conf->d = cmd->path;
1281     conf->d_is_fnmatch = (apr_is_fnmatch(conf->d) != 0);
1282
1283     /* Make this explicit - the "/" root has 0 elements, that is, we
1284      * will always merge it, and it will always sort and merge first.
1285      * All others are sorted and tested by the number of slashes.
1286      */
1287     if (strcmp(conf->d, "/") == 0)
1288         conf->d_components = 0;
1289     else
1290         conf->d_components = ap_count_dirs(conf->d);
1291
1292     ap_add_per_dir_conf(cmd->server, new_dir_conf);
1293
1294     if (*arg != '\0') {
1295         return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1296                           "> arguments not (yet) supported.", NULL);
1297     }
1298
1299     cmd->path = old_path;
1300     cmd->override = old_overrides;
1301
1302     return NULL;
1303 }
1304
1305 static const char *urlsection(cmd_parms *cmd, void *mconfig, const char *arg)
1306 {
1307     const char *errmsg;
1308     const char *endp = ap_strrchr_c(arg, '>');
1309     int old_overrides = cmd->override;
1310     char *old_path = cmd->path;
1311     core_dir_config *conf;
1312     regex_t *r = NULL;
1313     const command_rec *thiscmd = cmd->cmd;
1314     ap_conf_vector_t *new_url_conf = ap_create_per_dir_config(cmd->pool);
1315     const char *err = ap_check_cmd_context(cmd,
1316                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1317     if (err != NULL) {
1318         return err;
1319     }
1320
1321     if (endp == NULL) {
1322         return unclosed_directive(cmd);
1323     }
1324
1325     arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1326
1327     cmd->path = ap_getword_conf(cmd->pool, &arg);
1328     cmd->override = OR_ALL|ACCESS_CONF;
1329
1330     if (thiscmd->cmd_data) { /* <LocationMatch> */
1331         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1332     }
1333     else if (!strcmp(cmd->path, "~")) {
1334         cmd->path = ap_getword_conf(cmd->pool, &arg);
1335         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1336     }
1337
1338     /* initialize our config and fetch it */
1339     conf = ap_set_config_vectors(cmd->server, new_url_conf, cmd->path,
1340                                  &core_module, cmd->pool);
1341
1342     errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_url_conf);
1343     if (errmsg != NULL)
1344         return errmsg;
1345
1346     conf->d = apr_pstrdup(cmd->pool, cmd->path);     /* No mangling, please */
1347     conf->d_is_fnmatch = apr_is_fnmatch(conf->d) != 0;
1348     conf->r = r;
1349
1350     ap_add_per_url_conf(cmd->server, new_url_conf);
1351     
1352     if (*arg != '\0') {
1353         return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1354                           "> arguments not (yet) supported.", NULL);
1355     }
1356
1357     cmd->path = old_path;
1358     cmd->override = old_overrides;
1359
1360     return NULL;
1361 }
1362
1363 static const char *filesection(cmd_parms *cmd, void *mconfig, const char *arg)
1364 {
1365     const char *errmsg;
1366     const char *endp = ap_strrchr_c(arg, '>');
1367     int old_overrides = cmd->override;
1368     char *old_path = cmd->path;
1369     core_dir_config *conf;
1370     regex_t *r = NULL;
1371     const command_rec *thiscmd = cmd->cmd;
1372     core_dir_config *c=mconfig;
1373     ap_conf_vector_t *new_file_conf = ap_create_per_dir_config(cmd->pool);
1374     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT|NOT_IN_LOCATION);
1375
1376     if (err != NULL) {
1377         return err;
1378     }
1379
1380     if (endp == NULL) {
1381         return unclosed_directive(cmd);
1382     }
1383
1384     arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1385
1386     cmd->path = ap_getword_conf(cmd->pool, &arg);
1387     /* Only if not an .htaccess file */
1388     if (!old_path) {
1389         cmd->override = OR_ALL|ACCESS_CONF;
1390     }
1391
1392     if (thiscmd->cmd_data) { /* <FilesMatch> */
1393         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1394     }
1395     else if (!strcmp(cmd->path, "~")) {
1396         cmd->path = ap_getword_conf(cmd->pool, &arg);
1397         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1398     }
1399     else {
1400         char *newpath;
1401         /* Ensure that the pathname is canonical, but we
1402          * can't test the case/aliases without a fixed path */
1403         if (apr_filepath_merge(&newpath, "", cmd->path, 
1404                                0, cmd->pool) != APR_SUCCESS)
1405             return apr_pstrcat(cmd->pool, "<Files \"", cmd->path,
1406                                "\"> is invalid.", NULL);
1407         cmd->path = newpath;
1408     }
1409
1410     /* initialize our config and fetch it */
1411     conf = ap_set_config_vectors(cmd->server, new_file_conf, cmd->path,
1412                                  &core_module, cmd->pool);
1413
1414     errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_file_conf);
1415     if (errmsg != NULL)
1416         return errmsg;
1417
1418     conf->d = cmd->path;
1419     conf->d_is_fnmatch = apr_is_fnmatch(conf->d) != 0;
1420     conf->r = r;
1421
1422     ap_add_file_conf(c, new_file_conf);
1423
1424     if (*arg != '\0') {
1425         return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1426                           "> arguments not (yet) supported.", NULL);
1427     }
1428
1429     cmd->path = old_path;
1430     cmd->override = old_overrides;
1431
1432     return NULL;
1433 }
1434
1435 static const char *start_ifmod(cmd_parms *cmd, void *mconfig, const char *arg)
1436 {
1437     const char *endp = ap_strrchr_c(arg, '>');
1438     int not = (arg[0] == '!');
1439     module *found;
1440
1441     if (endp == NULL) {
1442         return unclosed_directive(cmd);
1443     }
1444
1445     arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1446
1447     if (not) {
1448         arg++;
1449     }
1450
1451     found = ap_find_linked_module(arg);
1452
1453     if ((!not && found) || (not && !found)) {
1454         ap_directive_t *parent = NULL;
1455         ap_directive_t *current = NULL;
1456         const char *retval;
1457
1458         retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd, 
1459                                       &current, &parent, "<IfModule");
1460         *(ap_directive_t **)mconfig = current;
1461         return retval;
1462     }
1463     else { 
1464         *(ap_directive_t **)mconfig = NULL;
1465         return ap_soak_end_container(cmd, "<IfModule");
1466     }
1467 }
1468
1469 AP_DECLARE(int) ap_exists_config_define(const char *name)
1470 {
1471     char **defines;
1472     int i;
1473
1474     defines = (char **)ap_server_config_defines->elts;
1475     for (i = 0; i < ap_server_config_defines->nelts; i++) {
1476         if (strcmp(defines[i], name) == 0) {
1477             return 1;
1478         }
1479     }
1480     return 0;
1481 }
1482
1483 static const char *start_ifdefine(cmd_parms *cmd, void *dummy, const char *arg)
1484 {
1485     const char *endp;
1486     int defined;
1487     int not = 0;
1488
1489     endp = ap_strrchr_c(arg, '>');
1490     if (endp == NULL) {
1491         return unclosed_directive(cmd);
1492     }
1493
1494     arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1495
1496     if (arg[0] == '!') {
1497         not = 1;
1498         arg++;
1499     }
1500
1501     defined = ap_exists_config_define(arg);
1502     if ((!not && defined) || (not && !defined)) {
1503         ap_directive_t *parent = NULL;
1504         ap_directive_t *current = NULL;
1505         const char *retval;
1506
1507         retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd, 
1508                                       &current, &parent, "<IfDefine");
1509         *(ap_directive_t **)dummy = current;
1510         return retval;
1511     }
1512     else { 
1513         *(ap_directive_t **)dummy = NULL;
1514         return ap_soak_end_container(cmd, "<IfDefine");
1515     }
1516 }
1517
1518 /* httpd.conf commands... beginning with the <VirtualHost> business */
1519
1520 static const char *virtualhost_section(cmd_parms *cmd, void *dummy,
1521                                        const char *arg)
1522 {
1523     server_rec *main_server = cmd->server, *s;
1524     const char *errmsg;
1525     const char *endp = ap_strrchr_c(arg, '>');
1526     apr_pool_t *p = cmd->pool;
1527
1528     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1529     if (err != NULL) {
1530         return err;
1531     }
1532
1533     if (endp == NULL) {
1534         return unclosed_directive(cmd);
1535     }
1536
1537     arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1538     
1539     /* FIXME: There's another feature waiting to happen here -- since you
1540         can now put multiple addresses/names on a single <VirtualHost>
1541         you might want to use it to group common definitions and then
1542         define other "subhosts" with their individual differences.  But
1543         personally I'd rather just do it with a macro preprocessor. -djg */
1544     if (main_server->is_virtual) {
1545         return "<VirtualHost> doesn't nest!";
1546     }
1547     
1548     errmsg = ap_init_virtual_host(p, arg, main_server, &s);
1549     if (errmsg) {
1550         return errmsg;
1551     }
1552
1553     s->next = main_server->next;
1554     main_server->next = s;
1555
1556     s->defn_name = cmd->directive->filename;
1557     s->defn_line_number = cmd->directive->line_num;
1558
1559     cmd->server = s;
1560
1561     errmsg = ap_walk_config(cmd->directive->first_child, cmd,
1562                             s->lookup_defaults);
1563
1564     cmd->server = main_server;
1565
1566     return errmsg;
1567 }
1568
1569 static const char *set_server_alias(cmd_parms *cmd, void *dummy,
1570                                     const char *arg)
1571 {
1572     if (!cmd->server->names) {
1573         return "ServerAlias only used in <VirtualHost>";
1574     }
1575     while (*arg) {
1576         char **item, *name = ap_getword_conf(cmd->pool, &arg);
1577         if (ap_is_matchexp(name)) {
1578             item = (char **)apr_array_push(cmd->server->wild_names);
1579         }
1580         else {
1581             item = (char **)apr_array_push(cmd->server->names);
1582         }
1583         *item = name;
1584     }
1585     return NULL;
1586 }
1587
1588 static const char *set_server_string_slot(cmd_parms *cmd, void *dummy,
1589                                           const char *arg)
1590 {
1591     /* This one's pretty generic... */
1592   
1593     int offset = (int)(long)cmd->info;
1594     char *struct_ptr = (char *)cmd->server;
1595     
1596     const char *err = ap_check_cmd_context(cmd, 
1597                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1598     if (err != NULL) {
1599         return err;
1600     }
1601
1602     *(const char **)(struct_ptr + offset) = arg;
1603     return NULL;
1604 }
1605
1606 static const char *server_hostname_port(cmd_parms *cmd, void *dummy, const char *arg)
1607 {
1608     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1609     const char *portstr;
1610     int port;
1611
1612     if (err != NULL) {
1613         return err;
1614     }
1615     portstr = ap_strchr_c(arg, ':');
1616     if (portstr) {
1617         cmd->server->server_hostname = apr_pstrndup(cmd->pool, arg, 
1618                                                     portstr - arg);
1619         portstr++;
1620         port = atoi(portstr);
1621     }
1622     else {
1623         cmd->server->server_hostname = apr_pstrdup(cmd->pool, arg);
1624         port = 80;
1625     }
1626     if (port <= 0 || port >= 65536) { /* 65536 == 1<<16 */
1627         return apr_pstrcat(cmd->temp_pool, "The port number \"", arg, 
1628                           "\" is outside the appropriate range "
1629                           "(i.e., 1..65535).", NULL);
1630     }
1631     cmd->server->port = port;
1632     return NULL;
1633 }
1634
1635 static const char *set_signature_flag(cmd_parms *cmd, void *d_,
1636                                       const char *arg)
1637 {
1638     core_dir_config *d=d_;
1639
1640     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1641     if (err != NULL) {
1642         return err;
1643     }
1644
1645     if (strcasecmp(arg, "On") == 0) {
1646         d->server_signature = srv_sig_on;
1647     }
1648     else if (strcasecmp(arg, "Off") == 0) {
1649         d->server_signature = srv_sig_off;
1650     }
1651     else if (strcasecmp(arg, "EMail") == 0) {
1652         d->server_signature = srv_sig_withmail;
1653     }
1654     else {
1655         return "ServerSignature: use one of: off | on | email";
1656     }
1657     return NULL;
1658 }
1659
1660 static const char *set_server_root(cmd_parms *cmd, void *dummy,
1661                                    const char *arg) 
1662 {
1663     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1664
1665     if (err != NULL) {
1666         return err;
1667     }
1668
1669     if ((apr_filepath_merge((char**)&ap_server_root, NULL, arg, 
1670                             APR_FILEPATH_TRUENAME, cmd->pool) != APR_SUCCESS)
1671         || !ap_is_directory(cmd->pool, ap_server_root)) {
1672         return "ServerRoot must be a valid directory";
1673     }
1674     return NULL;
1675 }
1676
1677 static const char *set_timeout(cmd_parms *cmd, void *dummy, const char *arg)
1678 {
1679     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1680     if (err != NULL) {
1681         return err;
1682     }
1683
1684     cmd->server->timeout = atoi(arg);
1685     return NULL;
1686 }
1687
1688 static const char *set_idcheck(cmd_parms *cmd, void *d_, int arg) 
1689 {
1690     core_dir_config *d=d_;
1691     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1692     if (err != NULL) {
1693         return err;
1694     }
1695
1696     d->do_rfc1413 = arg != 0;
1697     return NULL;
1698 }
1699
1700 static const char *set_hostname_lookups(cmd_parms *cmd, void *d_,
1701                                         const char *arg)
1702 {
1703     core_dir_config *d=d_;
1704
1705     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1706     if (err != NULL) {
1707         return err;
1708     }
1709
1710     if (!strcasecmp(arg, "on")) {
1711         d->hostname_lookups = HOSTNAME_LOOKUP_ON;
1712     }
1713     else if (!strcasecmp(arg, "off")) {
1714         d->hostname_lookups = HOSTNAME_LOOKUP_OFF;
1715     }
1716     else if (!strcasecmp(arg, "double")) {
1717         d->hostname_lookups = HOSTNAME_LOOKUP_DOUBLE;
1718     }
1719     else {
1720         return "parameter must be 'on', 'off', or 'double'";
1721     }
1722     return NULL;
1723 }
1724
1725 static const char *set_serverpath(cmd_parms *cmd, void *dummy,
1726                                   const char *arg) 
1727 {
1728     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1729     if (err != NULL) {
1730         return err;
1731     }
1732
1733     cmd->server->path = arg;
1734     cmd->server->pathlen = strlen(arg);
1735     return NULL;
1736 }
1737
1738 static const char *set_content_md5(cmd_parms *cmd, void *d_, int arg)
1739 {
1740     core_dir_config *d=d_;
1741     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1742     if (err != NULL) {
1743         return err;
1744     }
1745
1746     d->content_md5 = arg != 0;
1747     return NULL;
1748 }
1749
1750 static const char *set_use_canonical_name(cmd_parms *cmd, void *d_,
1751                                           const char *arg)
1752 {
1753     core_dir_config *d=d_;
1754     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1755     if (err != NULL) {
1756         return err;
1757     }
1758
1759     if (strcasecmp(arg, "on") == 0) {
1760         d->use_canonical_name = USE_CANONICAL_NAME_ON;
1761     }
1762     else if (strcasecmp(arg, "off") == 0) {
1763         d->use_canonical_name = USE_CANONICAL_NAME_OFF;
1764     }
1765     else if (strcasecmp(arg, "dns") == 0) {
1766         d->use_canonical_name = USE_CANONICAL_NAME_DNS;
1767     }
1768     else {
1769         return "parameter must be 'on', 'off', or 'dns'";
1770     }
1771     return NULL;
1772 }
1773
1774
1775 static const char *include_config (cmd_parms *cmd, void *dummy,
1776                                    const char *name)
1777 {
1778     ap_directive_t *conftree = NULL;
1779
1780     ap_process_resource_config(cmd->server,
1781                                ap_server_root_relative(cmd->pool, name),
1782                                &conftree, cmd->pool, cmd->temp_pool);
1783     *(ap_directive_t **)dummy = conftree;
1784     return NULL;
1785 }
1786
1787 static const char *set_loglevel(cmd_parms *cmd, void *dummy, const char *arg) 
1788 {
1789     char *str;
1790     
1791     const char *err = ap_check_cmd_context(cmd,
1792                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1793     if (err != NULL) {
1794         return err;
1795     }
1796
1797     if ((str = ap_getword_conf(cmd->pool, &arg))) {
1798         if (!strcasecmp(str, "emerg")) {
1799             cmd->server->loglevel = APLOG_EMERG;
1800         }
1801         else if (!strcasecmp(str, "alert")) {
1802             cmd->server->loglevel = APLOG_ALERT;
1803         }
1804         else if (!strcasecmp(str, "crit")) {
1805             cmd->server->loglevel = APLOG_CRIT;
1806         }
1807         else if (!strcasecmp(str, "error")) {
1808             cmd->server->loglevel = APLOG_ERR;
1809         }
1810         else if (!strcasecmp(str, "warn")) {
1811             cmd->server->loglevel = APLOG_WARNING;
1812         }
1813         else if (!strcasecmp(str, "notice")) {
1814             cmd->server->loglevel = APLOG_NOTICE;
1815         }
1816         else if (!strcasecmp(str, "info")) {
1817             cmd->server->loglevel = APLOG_INFO;
1818         }
1819         else if (!strcasecmp(str, "debug")) {
1820             cmd->server->loglevel = APLOG_DEBUG;
1821         }
1822         else {
1823             return "LogLevel requires level keyword: one of "
1824                    "emerg/alert/crit/error/warn/notice/info/debug";
1825         }
1826     }
1827     else {
1828         return "LogLevel requires level keyword";
1829     }
1830
1831     return NULL;
1832 }
1833
1834 AP_DECLARE(const char *) ap_psignature(const char *prefix, request_rec *r)
1835 {
1836     char sport[20];
1837     core_dir_config *conf;
1838
1839     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
1840                                                    &core_module);
1841     if ((conf->server_signature == srv_sig_off)
1842             || (conf->server_signature == srv_sig_unset)) {
1843         return "";
1844     }
1845
1846     apr_snprintf(sport, sizeof sport, "%u", (unsigned) ap_get_server_port(r));
1847
1848     if (conf->server_signature == srv_sig_withmail) {
1849         return apr_pstrcat(r->pool, prefix, "<address>" AP_SERVER_BASEVERSION
1850                           " Server at <a href=\"mailto:",
1851                           r->server->server_admin, "\">",
1852                           ap_get_server_name(r), "</a> Port ", sport,
1853                           "</address>\n", NULL);
1854     }
1855     return apr_pstrcat(r->pool, prefix, "<address>" AP_SERVER_BASEVERSION
1856                       " Server at ", ap_get_server_name(r), " Port ", sport,
1857                       "</address>\n", NULL);
1858 }
1859
1860 /*
1861  * Load an authorisation realm into our location configuration, applying the
1862  * usual rules that apply to realms.
1863  */
1864 static const char *set_authname(cmd_parms *cmd, void *mconfig,
1865                                 const char *word1)
1866 {
1867     core_dir_config *aconfig = (core_dir_config *)mconfig;
1868
1869     aconfig->ap_auth_name = ap_escape_quotes(cmd->pool, word1);
1870     return NULL;
1871 }
1872
1873 #ifdef _OSD_POSIX /* BS2000 Logon Passwd file */
1874 static const char *set_bs2000_account(cmd_parms *cmd, void *dummy, char *name)
1875 {
1876     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1877     if (err != NULL) {
1878         return err;
1879     }
1880
1881     return os_set_account(cmd->pool, name);
1882 }
1883 #endif /*_OSD_POSIX*/
1884
1885 /*
1886  * Handle a request to include the server's OS platform in the Server
1887  * response header field (the ServerTokens directive).  Unfortunately
1888  * this requires a new global in order to communicate the setting back to
1889  * http_main so it can insert the information in the right place in the
1890  * string.
1891  */
1892
1893 static char *server_version = NULL;
1894 static int version_locked = 0; 
1895
1896 enum server_token_type {
1897     SrvTk_MIN,          /* eg: Apache/1.3.0 */
1898     SrvTk_OS,           /* eg: Apache/1.3.0 (UNIX) */
1899     SrvTk_FULL,         /* eg: Apache/1.3.0 (UNIX) PHP/3.0 FooBar/1.2b */
1900     SrvTk_PRODUCT_ONLY  /* eg: Apache */
1901 };
1902 static enum server_token_type ap_server_tokens = SrvTk_FULL;
1903
1904 static apr_status_t reset_version(void *dummy)
1905 {
1906     version_locked = 0;
1907     ap_server_tokens = SrvTk_FULL;
1908     server_version = NULL;
1909     return APR_SUCCESS;
1910 }
1911
1912 AP_DECLARE(const char *) ap_get_server_version(void)
1913 {
1914     return (server_version ? server_version : AP_SERVER_BASEVERSION);
1915 }
1916
1917 AP_DECLARE(void) ap_add_version_component(apr_pool_t *pconf, const char *component)
1918 {
1919     if (! version_locked) {
1920         /*
1921          * If the version string is null, register our cleanup to reset the
1922          * pointer on pool destruction. We also know that, if NULL,
1923          * we are adding the original SERVER_BASEVERSION string.
1924          */
1925         if (server_version == NULL) {
1926             apr_pool_cleanup_register(pconf, NULL, reset_version,
1927                                 apr_pool_cleanup_null);
1928             server_version = apr_pstrdup(pconf, component);
1929         }
1930         else {
1931             /*
1932              * Tack the given component identifier to the end of
1933              * the existing string.
1934              */
1935             server_version = apr_pstrcat(pconf, server_version, " ",
1936                                         component, NULL);
1937         }
1938     }
1939 }
1940
1941 /*
1942  * This routine adds the real server base identity to the version string,
1943  * and then locks out changes until the next reconfig.
1944  */
1945 static void ap_set_version(apr_pool_t *pconf)
1946 {
1947     if (ap_server_tokens == SrvTk_PRODUCT_ONLY) {
1948         ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT);
1949     }
1950     else if (ap_server_tokens == SrvTk_MIN) {
1951         ap_add_version_component(pconf, AP_SERVER_BASEVERSION);
1952     }
1953     else {
1954         ap_add_version_component(pconf, AP_SERVER_BASEVERSION " (" PLATFORM ")");
1955     }
1956     /*
1957      * Lock the server_version string if we're not displaying
1958      * the full set of tokens
1959      */
1960     if (ap_server_tokens != SrvTk_FULL) {
1961         version_locked++;
1962     }
1963 }
1964
1965 static const char *set_serv_tokens(cmd_parms *cmd, void *dummy,
1966                                    const char *arg)
1967 {
1968     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1969     if (err != NULL) {
1970         return err;
1971     }
1972
1973     if (!strcasecmp(arg, "OS")) {
1974         ap_server_tokens = SrvTk_OS;
1975     }
1976     else if (!strcasecmp(arg, "Min") || !strcasecmp(arg, "Minimal")) {
1977         ap_server_tokens = SrvTk_MIN;
1978     }
1979     else if (!strcasecmp(arg, "Prod") || !strcasecmp(arg, "ProductOnly")) {
1980         ap_server_tokens = SrvTk_PRODUCT_ONLY;
1981     }
1982     else {
1983         ap_server_tokens = SrvTk_FULL;
1984     }
1985     return NULL;
1986 }
1987
1988 static const char *set_limit_req_line(cmd_parms *cmd, void *dummy,
1989                                       const char *arg)
1990 {
1991     const char *err = ap_check_cmd_context(cmd,
1992                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1993     int lim;
1994
1995     if (err != NULL) {
1996         return err;
1997     }
1998     lim = atoi(arg);
1999     if (lim < 0) {
2000         return apr_pstrcat(cmd->temp_pool, "LimitRequestLine \"", arg, 
2001                           "\" must be a non-negative integer", NULL);
2002     }
2003     if (lim > DEFAULT_LIMIT_REQUEST_LINE) {
2004         return apr_psprintf(cmd->temp_pool, "LimitRequestLine \"%s\" "
2005                            "must not exceed the precompiled maximum of %d",
2006                            arg, DEFAULT_LIMIT_REQUEST_LINE);
2007     }
2008     cmd->server->limit_req_line = lim;
2009     return NULL;
2010 }
2011
2012 static const char *set_limit_req_fieldsize(cmd_parms *cmd, void *dummy,
2013                                            const char *arg)
2014 {
2015     const char *err = ap_check_cmd_context(cmd,
2016                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2017     int lim;
2018
2019     if (err != NULL) {
2020         return err;
2021     }
2022     lim = atoi(arg);
2023     if (lim < 0) {
2024         return apr_pstrcat(cmd->temp_pool, "LimitRequestFieldsize \"", arg, 
2025                           "\" must be a non-negative integer (0 = no limit)",
2026                           NULL);
2027     }
2028     if (lim > DEFAULT_LIMIT_REQUEST_FIELDSIZE) {
2029         return apr_psprintf(cmd->temp_pool, "LimitRequestFieldsize \"%s\" "
2030                           "must not exceed the precompiled maximum of %d",
2031                            arg, DEFAULT_LIMIT_REQUEST_FIELDSIZE);
2032     }
2033     cmd->server->limit_req_fieldsize = lim;
2034     return NULL;
2035 }
2036
2037 static const char *set_limit_req_fields(cmd_parms *cmd, void *dummy,
2038                                         const char *arg)
2039 {
2040     const char *err = ap_check_cmd_context(cmd,
2041                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2042     int lim;
2043
2044     if (err != NULL) {
2045         return err;
2046     }
2047     lim = atoi(arg);
2048     if (lim < 0) {
2049         return apr_pstrcat(cmd->temp_pool, "LimitRequestFields \"", arg, 
2050                           "\" must be a non-negative integer (0 = no limit)",
2051                           NULL);
2052     }
2053     cmd->server->limit_req_fields = lim;
2054     return NULL;
2055 }
2056
2057 static const char *set_limit_req_body(cmd_parms *cmd, void *conf_,
2058                                       const char *arg) 
2059 {
2060     core_dir_config *conf=conf_;
2061     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2062     if (err != NULL) {
2063         return err;
2064     }
2065
2066     /* WTF: If strtoul is not portable, then write a replacement.
2067      *      Instead we have an idiotic define in httpd.h that prevents
2068      *      it from being used even when it is available. Sheesh.
2069      */
2070     conf->limit_req_body = (unsigned long)strtol(arg, (char **)NULL, 10);
2071     return NULL;
2072 }
2073
2074 static const char *set_limit_xml_req_body(cmd_parms *cmd, void *conf_,
2075                                           const char *arg) 
2076 {
2077     core_dir_config *conf = conf_;
2078     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2079     if (err != NULL) {
2080         return err;
2081     }
2082
2083     conf->limit_xml_body = atol(arg);
2084     if (conf->limit_xml_body < 0)
2085         return "LimitXMLRequestBody requires a non-negative integer.";
2086
2087     return NULL;
2088 }
2089
2090 AP_DECLARE(size_t) ap_get_limit_xml_body(const request_rec *r)
2091 {
2092     core_dir_config *conf;
2093
2094     conf = ap_get_module_config(r->per_dir_config, &core_module);
2095     if (conf->limit_xml_body == AP_LIMIT_UNSET)
2096         return AP_DEFAULT_LIMIT_XML_BODY;
2097     return (size_t)conf->limit_xml_body;
2098 }
2099
2100 #if !defined (RLIMIT_CPU) || !(defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)) || !defined (RLIMIT_NPROC)
2101 static const char *no_set_limit(cmd_parms *cmd, void *conf_,
2102                                 const char *arg, const char *arg2)
2103 {
2104     ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, cmd->server,
2105                 "%s not supported on this platform", cmd->cmd->name);
2106     return NULL;
2107 }
2108 #endif
2109
2110 #ifdef RLIMIT_CPU
2111 static const char *set_limit_cpu(cmd_parms *cmd, void *conf_,
2112                                  const char *arg, const char *arg2)
2113 {
2114     core_dir_config *conf=conf_;
2115
2116     unixd_set_rlimit(cmd, &conf->limit_cpu, arg, arg2, RLIMIT_CPU);
2117     return NULL;
2118 }
2119 #endif
2120
2121 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)
2122 static const char *set_limit_mem(cmd_parms *cmd, void *conf_,
2123                                  const char *arg, const char * arg2)
2124 {
2125     core_dir_config *conf=conf_;
2126
2127 #if defined(RLIMIT_AS)
2128     unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2 ,RLIMIT_AS);
2129 #elif defined(RLIMIT_DATA)
2130     unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_DATA);
2131 #elif defined(RLIMIT_VMEM)
2132     unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_VMEM);
2133 #endif
2134     return NULL;
2135 }
2136 #endif
2137
2138 #ifdef RLIMIT_NPROC
2139 static const char *set_limit_nproc(cmd_parms *cmd, void *conf_,
2140                                    const char *arg, const char * arg2)
2141 {
2142     core_dir_config *conf=conf_;
2143
2144     unixd_set_rlimit(cmd, &conf->limit_nproc, arg, arg2, RLIMIT_NPROC);
2145     return NULL;
2146 }
2147 #endif
2148
2149 static apr_status_t writev_it_all(apr_socket_t *s,
2150                                   struct iovec *vec, int nvec,
2151                                   apr_size_t len, apr_size_t *nbytes)
2152 {
2153     apr_size_t bytes_written = 0;
2154     apr_status_t rv;
2155     apr_size_t n = len;
2156     int i = 0;
2157
2158     *nbytes = 0;
2159
2160     /* XXX handle checking for non-blocking socket */
2161     while (bytes_written != len) {
2162         rv = apr_sendv(s, vec + i, nvec - i, &n);
2163         bytes_written += n;
2164         if (rv != APR_SUCCESS)
2165             return rv;
2166         *nbytes += n;
2167
2168         /* If the write did not complete, adjust the iovecs and issue
2169          * apr_sendv again
2170          */
2171         if (bytes_written < len) {
2172             /* Skip over the vectors that have already been written */
2173             apr_size_t cnt = vec[i].iov_len;
2174             while (n >= cnt && i + 1 < nvec) {
2175                 i++;
2176                 cnt += vec[i].iov_len;
2177             }
2178             if (n < cnt) {
2179                 /* Handle partial write of vec i */
2180                 vec[i].iov_base = (char *) vec[i].iov_base + 
2181                     (vec[i].iov_len - (cnt - n));
2182                 vec[i].iov_len = cnt -n;
2183             }
2184         }
2185         n = len - bytes_written;
2186     }
2187
2188     return APR_SUCCESS;
2189 }
2190
2191 /* sendfile_it_all()
2192  *  send the entire file using sendfile()
2193  *  handle partial writes
2194  *  return only when all bytes have been sent or an error is encountered.
2195  */
2196
2197 #if APR_HAS_SENDFILE
2198 static apr_status_t sendfile_it_all(conn_rec   *c, 
2199                                     apr_file_t *fd,
2200                                     apr_hdtr_t *hdtr, 
2201                                     apr_off_t   file_offset,
2202                                     apr_size_t  file_bytes_left, 
2203                                     apr_size_t  total_bytes_left,
2204                                     apr_int32_t flags)
2205 {
2206     apr_status_t rv;
2207 #ifdef AP_DEBUG
2208     apr_int32_t timeout = 0;
2209 #endif
2210
2211     AP_DEBUG_ASSERT((apr_getsocketopt(c->client_socket, APR_SO_TIMEOUT, 
2212                        &timeout) == APR_SUCCESS) && 
2213                      timeout > 0);  /* socket must be in timeout mode */ 
2214     do {
2215         apr_size_t tmplen = file_bytes_left;
2216         
2217         rv = apr_sendfile(c->client_socket, fd, hdtr, &file_offset, &tmplen, 
2218                           flags);
2219         total_bytes_left -= tmplen;
2220         if (!total_bytes_left || rv != APR_SUCCESS) {
2221             return rv;        /* normal case & error exit */ 
2222         }
2223
2224         AP_DEBUG_ASSERT(total_bytes_left > 0 && tmplen > 0);
2225         
2226         /* partial write, oooh noooo... 
2227          * Skip over any header data which was written
2228          */
2229         while (tmplen && hdtr->numheaders) {
2230             if (tmplen >= hdtr->headers[0].iov_len) {
2231                 tmplen -= hdtr->headers[0].iov_len;
2232                 --hdtr->numheaders;
2233                 ++hdtr->headers;
2234             }
2235             else {
2236                 char *iov_base = (char *)hdtr->headers[0].iov_base;
2237
2238                 hdtr->headers[0].iov_len -= tmplen;
2239                 iov_base += tmplen;
2240                 hdtr->headers[0].iov_base = iov_base;
2241                 tmplen = 0;
2242             }
2243         }
2244
2245         /* Skip over any file data which was written */
2246
2247         if (tmplen <= file_bytes_left) {
2248             file_offset += tmplen;
2249             file_bytes_left -= tmplen;
2250             continue; 
2251         }
2252         tmplen -= file_bytes_left;
2253         file_bytes_left = 0;
2254         file_offset = 0;
2255         
2256         /* Skip over any trailer data which was written */
2257         
2258         while (tmplen && hdtr->numtrailers) {
2259             if (tmplen >= hdtr->trailers[0].iov_len) {
2260                 tmplen -= hdtr->trailers[0].iov_len;
2261                 --hdtr->numtrailers;
2262                 ++hdtr->trailers;
2263             }
2264             else {
2265                 char *iov_base = (char *)hdtr->trailers[0].iov_base;
2266
2267                 hdtr->trailers[0].iov_len -= tmplen;
2268                 iov_base += tmplen;
2269                 hdtr->trailers[0].iov_base = iov_base;
2270                 tmplen = 0;
2271             }
2272         }
2273     } while (1);
2274 }
2275 #endif
2276         
2277 /*
2278  * emulate_sendfile()
2279  * Sends the contents of file fd along with header/trailer bytes, if any,
2280  * to the network. emulate_sendfile will return only when all the bytes have been
2281  * sent (i.e., it handles partial writes) or on a network error condition.
2282  */
2283 static apr_status_t emulate_sendfile(conn_rec *c, apr_file_t *fd, 
2284                                      apr_hdtr_t *hdtr, apr_off_t offset, 
2285                                      apr_size_t length, apr_size_t *nbytes) 
2286 {
2287     apr_status_t rv = APR_SUCCESS;
2288     apr_int32_t togo;        /* Remaining number of bytes in the file to send */
2289     apr_size_t sendlen = 0;
2290     apr_size_t bytes_sent;
2291     apr_int32_t i;
2292     apr_off_t o;             /* Track the file offset for partial writes */
2293     char buffer[8192];
2294
2295     *nbytes = 0;
2296
2297     /* Send the headers 
2298      * writev_it_all handles partial writes.
2299      * XXX: optimization... if headers are less than MIN_WRITE_SIZE, copy 
2300      * them into buffer
2301      */
2302     if ( hdtr && hdtr->numheaders > 0 ) {
2303         for (i = 0; i < hdtr->numheaders; i++) {
2304             sendlen += hdtr->headers[i].iov_len;
2305         }
2306         rv = writev_it_all(c->client_socket, hdtr->headers, hdtr->numheaders,
2307                            sendlen, &bytes_sent);
2308         if (rv == APR_SUCCESS)
2309             *nbytes += bytes_sent;     /* track total bytes sent */
2310     }
2311
2312     /* Seek the file to 'offset' */
2313     if (offset != 0 && rv == APR_SUCCESS) {
2314         rv = apr_file_seek(fd, APR_SET, &offset);
2315     }
2316
2317     /* Send the file, making sure to handle partial writes */
2318     togo = length;
2319     while (rv == APR_SUCCESS && togo) {
2320         sendlen = togo > sizeof(buffer) ? sizeof(buffer) : togo;
2321         o = 0;
2322         rv = apr_file_read(fd, buffer, &sendlen);
2323         while (rv == APR_SUCCESS && sendlen) {
2324             bytes_sent = sendlen;
2325             rv = apr_send(c->client_socket, &buffer[o], &bytes_sent);
2326             if (rv == APR_SUCCESS) {
2327                 sendlen -= bytes_sent; /* sendlen != bytes_sent ==> partial write */
2328                 o += bytes_sent;       /* o is where we are in the buffer */
2329                 *nbytes += bytes_sent;
2330                 togo -= bytes_sent;    /* track how much of the file we've sent */
2331             }
2332         }
2333     }
2334
2335     /* Send the trailers 
2336      * XXX: optimization... if it will fit, send this on the last send in the 
2337      * loop above
2338      */
2339     sendlen = 0;
2340     if ( rv == APR_SUCCESS && hdtr && hdtr->numtrailers > 0 ) {
2341         for (i = 0; i < hdtr->numtrailers; i++) {
2342             sendlen += hdtr->trailers[i].iov_len;
2343         }
2344         rv = writev_it_all(c->client_socket, hdtr->trailers, hdtr->numtrailers,
2345                            sendlen, &bytes_sent);
2346         if (rv == APR_SUCCESS)
2347             *nbytes += bytes_sent;
2348     }
2349
2350     return rv;
2351 }
2352
2353 /* Note --- ErrorDocument will now work from .htaccess files.  
2354  * The AllowOverride of Fileinfo allows webmasters to turn it off
2355  */
2356
2357 static const command_rec core_cmds[] = {
2358
2359 /* Old access config file commands */
2360
2361 AP_INIT_RAW_ARGS("<Directory", dirsection, NULL, RSRC_CONF, 
2362   "Container for directives affecting resources located in the specified "
2363   "directories"),
2364 AP_INIT_RAW_ARGS("<Location", urlsection, NULL, RSRC_CONF,
2365   "Container for directives affecting resources accessed through the "
2366   "specified URL paths"),
2367 AP_INIT_RAW_ARGS("<VirtualHost", virtualhost_section, NULL, RSRC_CONF,
2368   "Container to map directives to a particular virtual host, takes one or "
2369   "more host addresses"),
2370 AP_INIT_RAW_ARGS("<Files", filesection, NULL, OR_ALL,
2371   "Container for directives affecting files matching specified patterns"),
2372 AP_INIT_RAW_ARGS("<Limit", ap_limit_section, NULL, OR_ALL,
2373   "Container for authentication directives when accessed using specified HTTP "
2374   "methods"),
2375 AP_INIT_RAW_ARGS("<LimitExcept", ap_limit_section, (void*)1, OR_ALL,
2376   "Container for authentication directives to be applied when any HTTP "
2377   "method other than those specified is used to access the resource"),
2378 AP_INIT_TAKE1("<IfModule", start_ifmod, NULL, EXEC_ON_READ | OR_ALL,
2379   "Container for directives based on existance of specified modules"),
2380 AP_INIT_TAKE1("<IfDefine", start_ifdefine, NULL, EXEC_ON_READ | OR_ALL,
2381   "Container for directives based on existance of command line defines"),
2382 AP_INIT_RAW_ARGS("<DirectoryMatch", dirsection, (void*)1, RSRC_CONF,
2383   "Container for directives affecting resources located in the "
2384   "specified directories"),
2385 AP_INIT_RAW_ARGS("<LocationMatch", urlsection, (void*)1, RSRC_CONF,
2386   "Container for directives affecting resources accessed through the "
2387   "specified URL paths"),
2388 AP_INIT_RAW_ARGS("<FilesMatch", filesection, (void*)1, OR_ALL,
2389   "Container for directives affecting files matching specified patterns"),
2390 AP_INIT_TAKE1("AuthType", ap_set_string_slot,
2391   (void*)APR_XtOffsetOf(core_dir_config, ap_auth_type), OR_AUTHCFG, 
2392   "An HTTP authorization type (e.g., \"Basic\")"),
2393 AP_INIT_TAKE1("AuthName", set_authname, NULL, OR_AUTHCFG,
2394   "The authentication realm (e.g. \"Members Only\")"),
2395 AP_INIT_RAW_ARGS("Require", require, NULL, OR_AUTHCFG,
2396   "Selects which authenticated users or groups may access a protected space"),
2397 AP_INIT_TAKE1("Satisfy", satisfy, NULL, OR_AUTHCFG,
2398   "access policy if both allow and require used ('all' or 'any')"),
2399 #ifdef GPROF
2400 AP_INIT_TAKE1("GprofDir", set_gprof_dir, NULL, RSRC_CONF,
2401   "Directory to plop gmon.out files"),
2402 #endif
2403 AP_INIT_TAKE1("AddDefaultCharset", set_add_default_charset, NULL, OR_FILEINFO, 
2404   "The name of the default charset to add to any Content-Type without one or 'Off' to disable"),
2405
2406 /* Old resource config file commands */
2407   
2408 AP_INIT_RAW_ARGS("AccessFileName", set_access_name, NULL, RSRC_CONF,
2409   "Name(s) of per-directory config files (default: .htaccess)"),
2410 AP_INIT_TAKE1("DocumentRoot", set_document_root, NULL, RSRC_CONF,
2411   "Root directory of the document tree"),
2412 AP_INIT_TAKE2("ErrorDocument", set_error_document, NULL, OR_FILEINFO,
2413   "Change responses for HTTP errors"),
2414 AP_INIT_RAW_ARGS("AllowOverride", set_override, NULL, ACCESS_CONF,
2415   "Controls what groups of directives can be configured by per-directory "
2416   "config files"),
2417 AP_INIT_RAW_ARGS("Options", set_options, NULL, OR_OPTIONS,
2418   "Set a number of attributes for a given directory"),
2419 AP_INIT_TAKE1("DefaultType", ap_set_string_slot,
2420   (void*)APR_XtOffsetOf (core_dir_config, ap_default_type),
2421   OR_FILEINFO, "the default MIME type for untypable files"),
2422
2423 /* Old server config file commands */
2424
2425 AP_INIT_TAKE1("Port", ap_set_deprecated, NULL, RSRC_CONF, 
2426   "Port was replaced with Listen in Apache 2.0"),
2427 AP_INIT_TAKE1("HostnameLookups", set_hostname_lookups, NULL,
2428   ACCESS_CONF|RSRC_CONF,
2429   "\"on\" to enable, \"off\" to disable reverse DNS lookups, or \"double\" to "
2430   "enable double-reverse DNS lookups"),
2431 AP_INIT_TAKE1("ServerAdmin", set_server_string_slot,
2432   (void *)APR_XtOffsetOf (server_rec, server_admin), RSRC_CONF,
2433   "The email address of the server administrator"),
2434 AP_INIT_TAKE1("ServerName", server_hostname_port, NULL, RSRC_CONF,
2435   "The hostname and port of the server"),
2436 AP_INIT_TAKE1("ServerSignature", set_signature_flag, NULL, OR_ALL,
2437   "En-/disable server signature (on|off|email)"),
2438 AP_INIT_TAKE1("ServerRoot", set_server_root, NULL, RSRC_CONF,
2439   "Common directory of server-related files (logs, confs, etc.)"),
2440 AP_INIT_TAKE1("ErrorLog", set_server_string_slot,
2441   (void *)APR_XtOffsetOf (server_rec, error_fname), RSRC_CONF,
2442   "The filename of the error log"),
2443 AP_INIT_RAW_ARGS("ServerAlias", set_server_alias, NULL, RSRC_CONF,
2444   "A name or names alternately used to access the server"),
2445 AP_INIT_TAKE1("ServerPath", set_serverpath, NULL, RSRC_CONF,
2446   "The pathname the server can be reached at"),
2447 AP_INIT_TAKE1("Timeout", set_timeout, NULL, RSRC_CONF,
2448   "Timeout duration (sec)"),
2449 AP_INIT_FLAG("IdentityCheck", set_idcheck, NULL, RSRC_CONF|ACCESS_CONF,
2450   "Enable identd (RFC 1413) user lookups - SLOW"),
2451 AP_INIT_FLAG("ContentDigest", set_content_md5, NULL, OR_OPTIONS,
2452   "whether or not to send a Content-MD5 header with each request"),
2453 AP_INIT_TAKE1("UseCanonicalName", set_use_canonical_name, NULL,
2454   RSRC_CONF|ACCESS_CONF,
2455   "How to work out the ServerName : Port when constructing URLs"),
2456 /* TODO: RlimitFoo should all be part of mod_cgi, not in the core */
2457 /* TODO: ListenBacklog in MPM */
2458 AP_INIT_TAKE1("Include", include_config, NULL,
2459   (RSRC_CONF | ACCESS_CONF | EXEC_ON_READ),
2460   "Name of the config file to be included"),
2461 AP_INIT_TAKE1("LogLevel", set_loglevel, NULL, RSRC_CONF,
2462   "Level of verbosity in error logging"),
2463 AP_INIT_TAKE1("NameVirtualHost", ap_set_name_virtual_host, NULL, RSRC_CONF,
2464   "A numeric IP address:port, or the name of a host"),
2465 #ifdef _OSD_POSIX
2466 AP_INIT_TAKE1("BS2000Account", set_bs2000_account, NULL, RSRC_CONF,
2467   "Name of server User's bs2000 logon account name"),
2468 #endif
2469 AP_INIT_TAKE1("ServerTokens", set_serv_tokens, NULL, RSRC_CONF,
2470   "Determine tokens displayed in the Server: header - Min(imal), OS or Full"),
2471 AP_INIT_TAKE1("LimitRequestLine", set_limit_req_line, NULL, RSRC_CONF,
2472   "Limit on maximum size of an HTTP request line"),
2473 AP_INIT_TAKE1("LimitRequestFieldsize", set_limit_req_fieldsize, NULL,
2474   RSRC_CONF,
2475   "Limit on maximum size of an HTTP request header field"),
2476 AP_INIT_TAKE1("LimitRequestFields", set_limit_req_fields, NULL, RSRC_CONF,
2477   "Limit (0 = unlimited) on max number of header fields in a request message"),
2478 AP_INIT_TAKE1("LimitRequestBody", set_limit_req_body,
2479   (void*)APR_XtOffsetOf(core_dir_config, limit_req_body), OR_ALL,
2480   "Limit (in bytes) on maximum size of request message body"),
2481 AP_INIT_TAKE1("LimitXMLRequestBody", set_limit_xml_req_body, NULL, OR_ALL,
2482               "Limit (in bytes) on maximum size of an XML-based request "
2483               "body"),
2484
2485 /* System Resource Controls */
2486 #ifdef RLIMIT_CPU
2487 AP_INIT_TAKE12("RLimitCPU", set_limit_cpu,
2488   (void*)APR_XtOffsetOf(core_dir_config, limit_cpu),
2489   OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
2490 #else
2491 AP_INIT_TAKE12("RLimitCPU", no_set_limit, NULL,
2492   OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
2493 #endif
2494 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined (RLIMIT_AS)
2495 AP_INIT_TAKE12("RLimitMEM", set_limit_mem,
2496   (void*)APR_XtOffsetOf(core_dir_config, limit_mem),
2497   OR_ALL, "Soft/hard limits for max memory usage per process"),
2498 #else
2499 AP_INIT_TAKE12("RLimitMEM", no_set_limit, NULL,
2500   OR_ALL, "Soft/hard limits for max memory usage per process"),
2501 #endif
2502 #ifdef RLIMIT_NPROC
2503 AP_INIT_TAKE12("RLimitNPROC", set_limit_nproc,
2504   (void*)APR_XtOffsetOf(core_dir_config, limit_nproc),
2505   OR_ALL, "soft/hard limits for max number of processes per uid"),
2506 #else
2507 AP_INIT_TAKE12("RLimitNPROC", no_set_limit, NULL,
2508    OR_ALL, "soft/hard limits for max number of processes per uid"),
2509 #endif
2510
2511 AP_INIT_TAKE1("ForceType", ap_set_string_slot_lower, 
2512        (void *)APR_XtOffsetOf(core_dir_config, mime_type), OR_FILEINFO,
2513      "a mime type that overrides other configured type"),
2514 AP_INIT_TAKE1("SetHandler", ap_set_string_slot_lower, 
2515        (void *)APR_XtOffsetOf(core_dir_config, handler), OR_FILEINFO,
2516    "a handler name that overrides any other configured handler"),
2517 AP_INIT_TAKE1("SetOutputFilter", ap_set_string_slot, 
2518        (void *)APR_XtOffsetOf(core_dir_config, output_filters), OR_FILEINFO,
2519    "filter (or ; delimited list of filters) to be run on the request content"),
2520 AP_INIT_TAKE1("SetInputFilter", ap_set_string_slot, 
2521        (void *)APR_XtOffsetOf(core_dir_config, input_filters), OR_FILEINFO,
2522    "filter (or ; delimited list of filters) to be run on the request body"),
2523
2524 /*
2525  * These are default configuration directives that mpms can/should
2526  * pay attention to. If an mpm wishes to use these, they should
2527  * #defined them in mpm.h.
2528  */
2529 #ifdef AP_MPM_WANT_SET_PIDFILE
2530 AP_INIT_TAKE1("PidFile",  ap_mpm_set_pidfile, NULL, RSRC_CONF, \
2531               "A file for logging the server process ID"),
2532 #endif
2533 #ifdef AP_MPM_WANT_SET_SCOREBOARD
2534 AP_INIT_TAKE1("ScoreBoardFile", ap_mpm_set_scoreboard, NULL, RSRC_CONF, \
2535               "A file for Apache to maintain runtime process management information"),
2536 #endif
2537 #ifdef AP_MPM_WANT_SET_LOCKFILE
2538 AP_INIT_TAKE1("LockFile",  ap_mpm_set_lockfile, NULL, RSRC_CONF, \
2539               "The lockfile used when Apache needs to lock the accept() call"),
2540 #endif
2541 #ifdef AP_MPM_WANT_SET_MAX_REQUESTS
2542 AP_INIT_TAKE1("MaxRequestsPerChild", ap_mpm_set_max_requests, NULL, RSRC_CONF,\
2543               "Maximum number of requests a particular child serves before dying."),
2544 #endif
2545 #ifdef AP_MPM_WANT_SET_COREDUMPDIR
2546 AP_INIT_TAKE1("CoreDumpDirectory", ap_mpm_set_coredumpdir, NULL, RSRC_CONF, \
2547               "The location of the directory Apache changes to before dumping core"),
2548 #endif
2549 #ifdef AP_MPM_WANT_SET_ACCEPT_LOCK_MECH
2550 AP_INIT_TAKE1("AcceptMutex", ap_mpm_set_accept_lock_mech, NULL, RSRC_CONF, \
2551               "The system mutex implementation to use for the accept mutex"),
2552 #endif
2553 { NULL }
2554 };
2555
2556 /*****************************************************************
2557  *
2558  * Core handlers for various phases of server operation...
2559  */
2560
2561 AP_DECLARE_NONSTD(int) ap_core_translate(request_rec *r)
2562 {
2563     void *sconf = r->server->module_config;
2564     core_server_config *conf = ap_get_module_config(sconf, &core_module);
2565   
2566     /* XXX this seems too specific, this should probably become
2567      * some general-case test 
2568      */
2569     if (r->proxyreq) {
2570         return HTTP_FORBIDDEN;
2571     }
2572     if (!r->uri || ((r->uri[0] != '/') && strcmp(r->uri, "*"))) {
2573         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2574                      "Invalid URI in request %s", r->the_request);
2575         return HTTP_BAD_REQUEST;
2576     }
2577     
2578     if (r->server->path 
2579         && !strncmp(r->uri, r->server->path, r->server->pathlen)
2580         && (r->server->path[r->server->pathlen - 1] == '/'
2581             || r->uri[r->server->pathlen] == '/'
2582             || r->uri[r->server->pathlen] == '\0')) {
2583         if (apr_filepath_merge(&r->filename, conf->ap_document_root,
2584                                r->uri + r->server->pathlen, 
2585                                APR_FILEPATH_TRUENAME 
2586                              | APR_FILEPATH_SECUREROOT, r->pool)
2587                     != APR_SUCCESS) {
2588             return HTTP_FORBIDDEN;
2589         }
2590         r->canonical_filename = r->filename;
2591     }
2592     else {
2593         /*
2594          * Make sure that we do not mess up the translation by adding two
2595          * /'s in a row.  This happens under windows when the document
2596          * root ends with a /
2597          */
2598         if (apr_filepath_merge(&r->filename, conf->ap_document_root,
2599                                r->uri + ((*(r->uri) == '/') ? 1 : 0),
2600                                APR_FILEPATH_TRUENAME
2601                              | APR_FILEPATH_SECUREROOT, r->pool)
2602                     != APR_SUCCESS) {
2603             return HTTP_FORBIDDEN;
2604         }
2605         r->canonical_filename = r->filename;
2606     }
2607
2608     return OK;
2609 }
2610
2611 /*****************************************************************
2612  *
2613  * Test the filesystem name through directory_walk and file_walk
2614  */
2615 static int core_map_to_storage(request_rec *r)
2616 {
2617     int access_status;
2618
2619     if ((access_status = ap_directory_walk(r))) {
2620         return access_status;
2621     }
2622
2623     if ((access_status = ap_file_walk(r))) {
2624         return access_status;
2625     }
2626
2627     return OK;
2628 }
2629
2630
2631 static int do_nothing(request_rec *r) { return OK; }
2632
2633
2634 static int core_override_type(request_rec *r)
2635 {
2636     core_dir_config *conf = 
2637         (core_dir_config *)ap_get_module_config(r->per_dir_config,
2638                                                 &core_module);
2639
2640     /* Check for overrides with ForceType / SetHandler
2641      */
2642     if (conf->mime_type && strcmp(conf->mime_type, "none"))
2643         r->content_type = conf->mime_type;
2644
2645     if (conf->handler && strcmp(conf->handler, "none"))
2646         r->handler = conf->handler;
2647
2648     return OK;
2649 }
2650
2651
2652 static int default_handler(request_rec *r)
2653 {
2654     apr_bucket_brigade *bb;
2655     apr_bucket *e;
2656     core_dir_config *d;
2657     int errstatus;
2658     apr_file_t *fd = NULL;
2659     apr_status_t status;
2660     /* XXX if/when somebody writes a content-md5 filter we either need to
2661      *     remove this support or coordinate when to use the filter vs.
2662      *     when to use this code
2663      *     The current choice of when to compute the md5 here matches the 1.3
2664      *     support fairly closely (unlike 1.3, we don't handle computing md5
2665      *     when the charset is translated).
2666      */
2667     int bld_content_md5;
2668
2669     /*
2670      * The old way of doing handlers meant that this handler would
2671      * match literally anything - this way will require handler to
2672      * have a / in the middle, which probably captures the original
2673      * intent, but may cause problems at first - Ben 7th Jan 01
2674      */
2675     if(strcmp(r->handler,"default-handler")
2676        && ap_strcmp_match(r->handler,"*/*"))
2677         return DECLINED;
2678
2679     d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
2680                                                 &core_module);
2681     bld_content_md5 = (d->content_md5 & 1)
2682       && r->output_filters->frec->ftype != AP_FTYPE_CONTENT;
2683
2684     ap_allow_standard_methods(r, MERGE_ALLOW, M_GET, M_OPTIONS, M_POST, -1);
2685
2686     if ((errstatus = ap_discard_request_body(r)) != OK) {
2687         return errstatus;
2688     }
2689     
2690     if (r->method_number == M_INVALID) {
2691         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2692                     "Invalid method in request %s", r->the_request);
2693         return HTTP_NOT_IMPLEMENTED;
2694     }
2695     if (r->method_number == M_OPTIONS) {
2696         return ap_send_http_options(r);
2697     }
2698     if (r->method_number == M_PUT) {
2699         return HTTP_METHOD_NOT_ALLOWED;
2700     }
2701     if (r->finfo.filetype == 0 || (r->path_info && *r->path_info)) {
2702         ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r,
2703                       "File does not exist: %s",r->path_info ?
2704                       apr_pstrcat(r->pool, r->filename, r->path_info, NULL)
2705                       : r->filename);
2706         return HTTP_NOT_FOUND;
2707     }
2708     
2709     if (r->method_number != M_GET && r->method_number != M_POST) {
2710         return HTTP_METHOD_NOT_ALLOWED;
2711     }
2712
2713     if ((status = apr_file_open(&fd, r->filename, APR_READ | APR_BINARY, 0, r->pool)) != APR_SUCCESS) {
2714         ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r,
2715                      "file permissions deny server access: %s", r->filename);
2716         return HTTP_FORBIDDEN;
2717     }
2718     ap_update_mtime(r, r->finfo.mtime);
2719     ap_set_last_modified(r);
2720     ap_set_etag(r);
2721     apr_table_setn(r->headers_out, "Accept-Ranges", "bytes");
2722     ap_set_content_length(r, r->finfo.size); 
2723     if ((errstatus = ap_meets_conditions(r)) != OK) {
2724         apr_file_close(fd);
2725         return errstatus;
2726     }
2727
2728     if (bld_content_md5) {
2729         apr_table_setn(r->headers_out, "Content-MD5",
2730                        ap_md5digest(r->pool, fd));
2731     }
2732
2733     bb = apr_brigade_create(r->pool);
2734 #if APR_HAS_LARGE_FILES
2735     if (r->finfo.size > AP_MAX_SENDFILE) {
2736         /* APR_HAS_LARGE_FILES issue; must split into mutiple buckets, 
2737          * no greater than MAX(apr_size_t), and more granular than that
2738          * in case the brigade code/filters attempt to read it directly.
2739          */
2740         apr_off_t fsize = r->finfo.size;
2741         e = apr_bucket_file_create(fd, 0, AP_MAX_SENDFILE, r->pool);
2742         while (fsize > AP_MAX_SENDFILE) {
2743             APR_BRIGADE_INSERT_TAIL(bb, e);
2744             apr_bucket_copy(e, &e);
2745             e->start += AP_MAX_SENDFILE;
2746             fsize -= AP_MAX_SENDFILE;
2747         }
2748         e->length = (apr_size_t)fsize; /* Resize just the last bucket */
2749     }
2750     else
2751 #endif
2752         e = apr_bucket_file_create(fd, 0, (apr_size_t)r->finfo.size, r->pool);
2753
2754     APR_BRIGADE_INSERT_TAIL(bb, e);
2755     e = apr_bucket_eos_create();
2756     APR_BRIGADE_INSERT_TAIL(bb, e);
2757
2758     return ap_pass_brigade(r->output_filters, bb);
2759 }
2760
2761 typedef struct core_filter_ctx {
2762     apr_bucket_brigade *b;
2763 } core_ctx_t;
2764
2765 static int core_input_filter(ap_filter_t *f, apr_bucket_brigade *b, ap_input_mode_t mode, apr_off_t *readbytes)
2766 {
2767     apr_bucket *e;
2768     apr_status_t rv;
2769     core_ctx_t *ctx = f->ctx;
2770     const char *str;
2771     apr_size_t len;
2772
2773     if (!ctx)
2774     {
2775         f->ctx = ctx = apr_pcalloc(f->c->pool, sizeof(*ctx));
2776         ctx->b = apr_brigade_create(f->c->pool);
2777
2778         /* seed the brigade with the client socket. */
2779         e = apr_bucket_socket_create(f->c->client_socket);
2780         APR_BRIGADE_INSERT_TAIL(ctx->b, e);
2781     }
2782
2783     /* ### AP_MODE_PEEK is a horrific name for this mode because we also
2784      * eat any CRLFs that we see.  That's not the obvious intention of
2785      * this mode.  Determine whether anyone actually uses this or not. */
2786     if (mode == AP_MODE_PEEK) {
2787         apr_bucket *e;
2788         const char *c;
2789
2790         /* The purpose of this loop is to ignore any CRLF (or LF) at the end
2791          * of a request.  Many browsers send extra lines at the end of POST
2792          * requests.  We use the PEEK method to determine if there is more
2793          * data on the socket, so that we know if we should delay sending the
2794          * end of one request until we have served the second request in a
2795          * pipelined situation.  We don't want to actually delay sending a
2796          * response if the server finds a CRLF (or LF), becuause that doesn't
2797          * mean that there is another request, just a blank line.
2798          */
2799         while (1) {
2800
2801             if (APR_BRIGADE_EMPTY(ctx->b))
2802                 return APR_EOF;
2803
2804             e = APR_BRIGADE_FIRST(ctx->b);
2805
2806             rv = apr_bucket_read(e, &str, &len, APR_NONBLOCK_READ);
2807
2808             if (rv != APR_SUCCESS)
2809                 return rv;
2810
2811             c = str;
2812             while (c < str + len) {
2813                 if (*c == APR_ASCII_LF)
2814                     c++;
2815                 else if (*c == APR_ASCII_CR && *(c + 1) == APR_ASCII_LF)
2816                     c += 2;
2817                 else 
2818                     return APR_SUCCESS;
2819             }
2820             /* If we reach here, we were a bucket just full of CRLFs, so
2821              * just toss the bucket. */
2822             /* FIXME: Is this the right thing to do in the core? */
2823             apr_bucket_delete(e);
2824         }
2825     }
2826
2827     /* If readbytes is -1, we want to just read everything until the end
2828      * of the brigade, which in this case means the end of the socket.  To
2829      * do this, we loop through the entire brigade, until the socket is
2830      * exhausted, at which point, it will automagically remove itself from
2831      * the brigade.
2832      * ### No one in their right mind should be calling this with -1.
2833      *     This is just an all-around bad idea.  We may be better off by 
2834      *     just closing the socket.  Determine whether anyone uses this.
2835      */
2836     if (*readbytes == -1) {
2837         apr_bucket *e;
2838         apr_off_t total;
2839
2840         /* Force a recompute of the length and force a read-all */
2841         apr_brigade_length(ctx->b, 1, &total);
2842         APR_BRIGADE_CONCAT(b, ctx->b);
2843         *readbytes = total;
2844         /* We have read until the brigade was empty, so we know that we 
2845          * must be EOS. */
2846         e = apr_bucket_eos_create();
2847         APR_BRIGADE_INSERT_TAIL(b, e);
2848         return APR_SUCCESS;
2849     }
2850     /* readbytes == 0 is "read a single line". otherwise, read a block. */
2851     if (*readbytes) {
2852         apr_off_t total;
2853         apr_bucket *e;
2854         apr_bucket_brigade *newbb;
2855
2856         e = APR_BRIGADE_FIRST(ctx->b);
2857         rv = apr_bucket_read(e, &str, &len, mode);
2858
2859         if (APR_STATUS_IS_EAGAIN(rv)) {
2860             *readbytes = 0;
2861             e = apr_bucket_immortal_create("", 0);
2862             APR_BRIGADE_INSERT_TAIL(b, e);
2863             return APR_SUCCESS;
2864         }
2865         else if (rv != APR_SUCCESS) {
2866             return rv;
2867         }
2868
2869         /* We can only return at most what the user asked for. */
2870         if (len < *readbytes) {
2871             *readbytes = len;
2872         }
2873
2874         apr_brigade_partition(ctx->b, *readbytes, &e);
2875
2876         /* Must do split before CONCAT */
2877         newbb = apr_brigade_split(ctx->b, e);
2878         APR_BRIGADE_CONCAT(b, ctx->b);
2879         /* Take what was originally there and place it back on ctx->b */
2880         APR_BRIGADE_CONCAT(ctx->b, newbb);
2881
2882         apr_brigade_length(b, 1, &total);
2883         *readbytes = total;
2884
2885         return APR_SUCCESS;
2886     }
2887
2888     /* we are reading a single LF line, e.g. the HTTP headers */
2889     while (!APR_BRIGADE_EMPTY(ctx->b)) {
2890         const char *pos;
2891
2892         e = APR_BRIGADE_FIRST(ctx->b);
2893         rv = apr_bucket_read(e, &str, &len, mode);
2894
2895         /* We should treat EAGAIN here the same as we do for EOF (brigade is
2896          * empty).  We do this by returning whatever we have read.  This may 
2897          * or may not be bogus, but is consistent (for now) with EOF logic.
2898          */
2899         if (APR_STATUS_IS_EAGAIN(rv)) {
2900             break;
2901         }
2902         else if (rv != APR_SUCCESS) {
2903             return rv;
2904         }
2905
2906         pos = memchr(str, APR_ASCII_LF, len);
2907         /* We found a match. */
2908         if (pos != NULL) {
2909             apr_bucket_split(e, pos - str + 1);
2910             APR_BUCKET_REMOVE(e);
2911             APR_BRIGADE_INSERT_TAIL(b, e);
2912             *readbytes += pos - str;
2913             return APR_SUCCESS;
2914         }
2915         APR_BUCKET_REMOVE(e);
2916         APR_BRIGADE_INSERT_TAIL(b, e);
2917         *readbytes += len;
2918     }
2919
2920     return APR_SUCCESS;
2921 }
2922
2923 /* Default filter.  This filter should almost always be used.  Its only job
2924  * is to send the headers if they haven't already been sent, and then send
2925  * the actual data.
2926  */
2927 typedef struct CORE_OUTPUT_FILTER_CTX {
2928     apr_bucket_brigade *b;
2929     apr_pool_t *subpool; /* subpool of c->pool used for data saved after a
2930                           * request is finished
2931                           */
2932     int subpool_has_stuff; /* anything in the subpool? */
2933 } core_output_filter_ctx_t;
2934
2935 #define MAX_IOVEC_TO_WRITE 16
2936
2937 static apr_status_t core_output_filter(ap_filter_t *f, apr_bucket_brigade *b)
2938 {
2939     apr_status_t rv;
2940     conn_rec *c = f->c;
2941     core_output_filter_ctx_t *ctx = f->ctx;
2942
2943     if (ctx == NULL) {
2944         f->ctx = ctx = apr_pcalloc(c->pool, sizeof(core_output_filter_ctx_t));
2945     }
2946
2947     /* If we have a saved brigade, concatenate the new brigade to it */
2948     if (ctx->b) {
2949         APR_BRIGADE_CONCAT(ctx->b, b);
2950         b = ctx->b;
2951         ctx->b = NULL;
2952     }
2953
2954     /* Perform multiple passes over the brigade, sending batches of output
2955        to the connection. */
2956     while (b) {
2957         apr_size_t nbytes = 0;
2958         apr_bucket *last_e = NULL; /* initialized for debugging */
2959         apr_bucket *e;
2960
2961         /* tail of brigade if we need another pass */
2962         apr_bucket_brigade *more = NULL;
2963
2964         /* one group of iovecs per pass over the brigade */
2965         apr_size_t nvec = 0;
2966         apr_size_t nvec_trailers = 0;
2967         struct iovec vec[MAX_IOVEC_TO_WRITE];
2968         struct iovec vec_trailers[MAX_IOVEC_TO_WRITE];
2969
2970         /* one file per pass over the brigade */
2971         apr_file_t *fd = NULL;
2972         apr_size_t flen = 0;
2973         apr_off_t foffset = 0;
2974
2975         /* Iterate over the brigade: collect iovecs and/or a file */
2976         APR_BRIGADE_FOREACH(e, b) {
2977             /* XXX: APR_BRIGADE_FOREACH breaks the value of e! 
2978              * is that the expected behavior?
2979              */
2980             last_e = e;
2981             if (APR_BUCKET_IS_EOS(e) || APR_BUCKET_IS_FLUSH(e)) {
2982                 break;
2983             }
2984             /* It doesn't make any sense to use sendfile for a file bucket
2985              * that represents 10 bytes.
2986              */
2987             else if (APR_BUCKET_IS_FILE(e)
2988                      && (e->length >= AP_MIN_SENDFILE_BYTES)) {
2989                 apr_bucket_file *a = e->data;
2990     
2991                 /* We can't handle more than one file bucket at a time
2992                  * so we split here and send the file we have already
2993                  * found.
2994                  */
2995                 if (fd) {
2996                     more = apr_brigade_split(b, e);
2997                     break;
2998                 }
2999     
3000                 fd = a->fd;
3001                 flen = e->length;
3002                 foffset = e->start;
3003             }
3004             else {
3005                 const char *str;
3006                 apr_size_t n;
3007
3008                 rv = apr_bucket_read(e, &str, &n, APR_BLOCK_READ);
3009                 if (n) {
3010                     if (!fd) {
3011                         if (nvec == MAX_IOVEC_TO_WRITE) {
3012                             /* woah! too many. stop now. */
3013                             more = apr_brigade_split(b, e);
3014                             break;
3015                         }
3016                         vec[nvec].iov_base = (char*) str;
3017                         vec[nvec].iov_len = n;
3018                         nvec++;
3019                     }
3020                     else {
3021                         /* The bucket is a trailer to a file bucket */
3022
3023                         if (nvec_trailers == MAX_IOVEC_TO_WRITE) {
3024                             /* woah! too many. stop now. */
3025                             more = apr_brigade_split(b, e);
3026                             break;
3027                         }
3028                         vec_trailers[nvec_trailers].iov_base = (char*) str;
3029                         vec_trailers[nvec_trailers].iov_len = n;
3030                         nvec_trailers++;
3031                     }
3032                     nbytes += n;
3033                 }
3034             }
3035         }
3036     
3037         /* Completed iterating over the brigades, now determine if we want 
3038          * to buffer the brigade or send the brigade out on the network.
3039          *
3040          * Save if:
3041          *
3042          *   1) we didn't see a file, we don't have more passes over the
3043          *      brigade to perform, we haven't accumulated enough bytes to
3044          *      send, AND we didn't stop at a FLUSH bucket.
3045          *      (IOW, we will save away plain old bytes)
3046          * or
3047          *   2) we hit the EOS and have a keep-alive connection
3048          *      (IOW, this response is a bit more complex, but we save it
3049          *       with the hope of concatenating with another response)
3050          */
3051         if ((!fd && !more && 
3052             (nbytes + flen < AP_MIN_BYTES_TO_WRITE) && !APR_BUCKET_IS_FLUSH(last_e))
3053             || (nbytes + flen < AP_MIN_BYTES_TO_WRITE && APR_BUCKET_IS_EOS(last_e) && c->keepalive)) {
3054
3055             if (ctx->subpool == NULL) {
3056                 apr_pool_create(&ctx->subpool, f->c->pool);
3057             }
3058
3059             /* NEVER save an EOS in here.  If we are saving a brigade with 
3060              * an EOS bucket, then we are doing keepalive connections, and 
3061              * we want to process to second request fully.
3062              */
3063             if (APR_BUCKET_IS_EOS(last_e)) {
3064                 apr_bucket *bucket = NULL;
3065                 /* If we are in here, then this request is a keepalive.  We
3066                  * need to be certain that any data in a bucket is valid
3067                  * after the request_pool is cleared.
3068                  */ 
3069                 if (ctx->b == NULL) {
3070                     ctx->b = apr_brigade_create(ctx->subpool);
3071                 }
3072
3073                 APR_BRIGADE_FOREACH(bucket, b) {
3074                     const char *str;
3075                     apr_size_t n;
3076
3077                     rv = apr_bucket_read(bucket, &str, &n, APR_BLOCK_READ);
3078
3079                     /* This apr_brigade_write does not use a flush function
3080                        because we assume that we will not write enough data
3081                        into it to cause a flush. However, if we *do* write
3082                        "too much", then we could end up with transient
3083                        buckets which would suck. This works for now, but is
3084                        a bit shaky if changes are made to some of the
3085                        buffering sizes. Let's do an assert to prevent
3086                        potential future problems... */
3087                     AP_DEBUG_ASSERT(AP_MIN_BYTES_TO_WRITE <=
3088                                     APR_BUCKET_BUFF_SIZE);
3089                     if (rv != APR_SUCCESS) {
3090                         ap_log_error(APLOG_MARK, APLOG_ERR, rv, c->base_server,
3091                                      "core_output_filter: Error reading from bucket.");
3092                         return rv;
3093                     }
3094                     apr_brigade_write(ctx->b, NULL, NULL, str, n);
3095                     ctx->subpool_has_stuff = 1;
3096                 }
3097                 apr_brigade_destroy(b);
3098             }
3099             else {
3100                 ap_save_brigade(f, &ctx->b, &b, ctx->subpool);
3101                 ctx->subpool_has_stuff = 1;
3102             }
3103             return APR_SUCCESS;
3104         }
3105
3106         if (fd) {
3107             apr_hdtr_t hdtr;
3108 #if APR_HAS_SENDFILE
3109             apr_int32_t flags = 0;
3110 #endif
3111     
3112             memset(&hdtr, '\0', sizeof(hdtr));
3113             if (nvec) {
3114                 hdtr.numheaders = nvec;
3115                 hdtr.headers = vec;
3116             }
3117             if (nvec_trailers) {
3118                 hdtr.numtrailers = nvec_trailers;
3119                 hdtr.trailers = vec_trailers;
3120             }
3121 #if APR_HAS_SENDFILE
3122             if (!c->keepalive) {
3123                 /* Prepare the socket to be reused */
3124                 flags |= APR_SENDFILE_DISCONNECT_SOCKET;
3125             }
3126             rv = sendfile_it_all(c,        /* the connection            */
3127                                  fd,       /* the file to send          */
3128                                  &hdtr,    /* header and trailer iovecs */
3129                                  foffset,  /* offset in the file to begin
3130                                               sending from              */
3131                                  flen,     /* length of file            */
3132                                  nbytes + flen, /* total length including
3133                                                    headers                */
3134                                  flags);   /* apr_sendfile flags        */
3135     
3136             /* If apr_sendfile() returns APR_ENOTIMPL, call emulate_sendfile().
3137              * emulate_sendfile() is useful to enable the same Apache binary 
3138              * distribution to support Windows NT/2000 (supports TransmitFile) 
3139              * and Win95/98 (do not support TransmitFile)
3140              */
3141             if (rv == APR_ENOTIMPL)
3142 #endif
3143             {
3144                 apr_size_t unused_bytes_sent;
3145                 rv = emulate_sendfile(c, fd, &hdtr, foffset, flen, 
3146                                       &unused_bytes_sent);
3147             }
3148             fd = NULL;
3149         }
3150         else {
3151             apr_size_t unused_bytes_sent;
3152
3153             rv = writev_it_all(c->client_socket, 
3154                                vec, nvec, 
3155                                nbytes, &unused_bytes_sent);
3156         }
3157
3158         apr_brigade_destroy(b);
3159         if (rv != APR_SUCCESS) {
3160             ap_log_error(APLOG_MARK, APLOG_INFO, rv, c->base_server,
3161                "core_output_filter: writing data to the network");
3162             if (more)
3163                 apr_brigade_destroy(more);
3164             if (APR_STATUS_IS_ECONNABORTED(rv) ||
3165                 APR_STATUS_IS_ECONNRESET(rv)) {
3166                 c->aborted = 1;
3167             }
3168             return rv;
3169         }
3170     
3171         b = more;
3172         more = NULL;
3173     }  /* end while () */
3174
3175     if (ctx->subpool && ctx->subpool_has_stuff) {
3176         apr_pool_clear(ctx->subpool);
3177         ctx->subpool_has_stuff = 0;
3178     }
3179
3180     return APR_SUCCESS;
3181 }
3182
3183 static void core_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
3184 {
3185     ap_set_version(pconf);
3186 }
3187
3188 static void core_open_logs(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
3189 {
3190     ap_open_logs(s, pconf);
3191 }
3192
3193 static void core_insert_filter(request_rec *r)
3194 {
3195     core_dir_config *conf = (core_dir_config *)
3196                             ap_get_module_config(r->per_dir_config,
3197                                                    &core_module); 
3198     const char *filter, *filters = conf->output_filters;
3199
3200     if (filters) {
3201         while (*filters && (filter = ap_getword(r->pool, &filters, ';'))) {
3202             ap_add_output_filter(filter, NULL, r, r->connection);
3203         }
3204     }
3205
3206     filters = conf->input_filters;
3207     if (filters) {
3208         while (*filters && (filter = ap_getword(r->pool, &filters, ';'))) {
3209             ap_add_input_filter(filter, NULL, r, r->connection);
3210         }
3211     }
3212 }
3213
3214 static int core_create_req(request_rec *r)
3215 {
3216     if (r->main) {
3217         ap_set_module_config(r->request_config, &core_module,
3218               ap_get_module_config(r->main->request_config, &core_module));
3219     }
3220     else {
3221         core_request_config *req_cfg;
3222
3223         req_cfg = apr_pcalloc(r->pool, sizeof(core_request_config));
3224         req_cfg->bb = apr_brigade_create(r->pool);
3225         ap_set_module_config(r->request_config, &core_module, req_cfg);
3226     }
3227     return OK;
3228 }
3229
3230 static void register_hooks(apr_pool_t *p)
3231 {
3232     ap_hook_post_config(core_post_config,NULL,NULL,APR_HOOK_REALLY_FIRST);
3233     ap_hook_translate_name(ap_core_translate,NULL,NULL,APR_HOOK_REALLY_LAST);
3234     ap_hook_map_to_storage(core_map_to_storage,NULL,NULL,APR_HOOK_REALLY_LAST);
3235     ap_hook_open_logs(core_open_logs,NULL,NULL,APR_HOOK_MIDDLE);
3236     ap_hook_handler(default_handler,NULL,NULL,APR_HOOK_REALLY_LAST);
3237     /* FIXME: I suspect we can eliminate the need for these do_nothings - Ben */
3238     ap_hook_type_checker(do_nothing,NULL,NULL,APR_HOOK_REALLY_LAST);
3239     ap_hook_fixups(core_override_type,NULL,NULL,APR_HOOK_REALLY_FIRST);
3240     ap_hook_access_checker(do_nothing,NULL,NULL,APR_HOOK_REALLY_LAST);
3241     ap_hook_create_request(core_create_req, NULL, NULL, APR_HOOK_MIDDLE);
3242     ap_hook_pre_mpm(ap_create_scoreboard, NULL, NULL, APR_HOOK_MIDDLE);
3243
3244     /* register the core's insert_filter hook and register core-provided
3245      * filters
3246      */
3247     ap_hook_insert_filter(core_insert_filter, NULL, NULL, APR_HOOK_MIDDLE);
3248
3249     ap_register_input_filter("CORE_IN", core_input_filter, AP_FTYPE_NETWORK);
3250     ap_register_output_filter("CONTENT_LENGTH", ap_content_length_filter, 
3251                               AP_FTYPE_HTTP_HEADER);
3252     ap_register_output_filter("CORE", core_output_filter, AP_FTYPE_NETWORK);
3253     ap_register_output_filter("SUBREQ_CORE", ap_sub_req_output_filter, 
3254                               AP_FTYPE_CONTENT);
3255     ap_old_write_func = ap_register_output_filter("OLD_WRITE", 
3256                                    ap_old_write_filter, AP_FTYPE_CONTENT - 1);
3257 }
3258
3259 AP_DECLARE_DATA module core_module = {
3260     STANDARD20_MODULE_STUFF,
3261     create_core_dir_config,     /* create per-directory config structure */
3262     merge_core_dir_configs,     /* merge per-directory config structures */
3263     create_core_server_config,  /* create per-server config structure */
3264     merge_core_server_configs,  /* merge per-server config structures */
3265     core_cmds,                  /* command apr_table_t */
3266     register_hooks              /* register hooks */
3267 };