]> granicus.if.org Git - apache/blob - modules/http/http_core.c
Clean up blocking and non-blocking reads from buckets. The only bucket
[apache] / modules / http / http_core.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000 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 #define CORE_PRIVATE
60 #include "ap_config.h"
61 #include "apr_strings.h"
62 #include "apr_lib.h"
63 #include "httpd.h"
64 #include "http_config.h"
65 #include "http_core.h"
66 #include "http_protocol.h"      /* For index_of_response().  Grump. */
67 #include "http_request.h"
68 #include "http_vhost.h"
69 #include "http_main.h"          /* For the default_handler below... */
70 #include "http_log.h"
71 #include "rfc1413.h"
72 #include "util_md5.h"
73 #include "apr_fnmatch.h"
74 #include "http_connection.h"
75 #include "ap_buckets.h"
76 #include "util_filter.h"
77 #include "util_ebcdic.h"
78 #include "mpm.h"
79 #ifdef HAVE_NETDB_H
80 #include <netdb.h>
81 #endif
82 #ifdef HAVE_SYS_SOCKET_H
83 #include <sys/socket.h>
84 #endif
85 #ifdef HAVE_ARPA_INET_H
86 #include <arpa/inet.h>
87 #endif
88 #ifdef HAVE_STRINGS_H
89 #include <strings.h>
90 #endif
91
92 /* Make sure we don't write less than 4096 bytes at any one time.
93  */
94 #define MIN_SIZE_TO_WRITE  9000
95
96 /* Allow Apache to use ap_mmap */
97 #ifdef AP_USE_MMAP_FILES
98 #include "apr_mmap.h"
99
100 /* mmap support for static files based on ideas from John Heidemann's
101  * patch against 1.0.5.  See
102  * <http://www.isi.edu/~johnh/SOFTWARE/APACHE/index.html>.
103  */
104
105 /* Files have to be at least this big before they're mmap()d.  This is to deal
106  * with systems where the expense of doing an mmap() and an munmap() outweighs
107  * the benefit for small files.  It shouldn't be set lower than 1.
108  */
109 #ifndef MMAP_THRESHOLD
110 #  ifdef SUNOS4
111 #  define MMAP_THRESHOLD                (8*1024)
112 #  else
113 #  define MMAP_THRESHOLD                1
114 #  endif /* SUNOS4 */
115 #endif /* MMAP_THRESHOLD */
116 #ifndef MMAP_LIMIT
117 #define MMAP_LIMIT              (4*1024*1024)
118 #endif
119 #endif /* AP_USE_MMAP_FILES */
120
121 /* LimitXMLRequestBody handling */
122 #define AP_LIMIT_UNSET                  ((long) -1)
123 #define AP_DEFAULT_LIMIT_XML_BODY       ((size_t)1000000)
124
125 /* Server core module... This module provides support for really basic
126  * server operations, including options and commands which control the
127  * operation of other modules.  Consider this the bureaucracy module.
128  *
129  * The core module also defines handlers, etc., do handle just enough
130  * to allow a server with the core module ONLY to actually serve documents
131  * (though it slaps DefaultType on all of 'em); this was useful in testing,
132  * but may not be worth preserving.
133  *
134  * This file could almost be mod_core.c, except for the stuff which affects
135  * the http_conf_globals.
136  */
137
138 static void *create_core_dir_config(apr_pool_t *a, char *dir)
139 {
140     core_dir_config *conf;
141
142     conf = (core_dir_config *)apr_pcalloc(a, sizeof(core_dir_config));
143     if (!dir || dir[strlen(dir) - 1] == '/') {
144         conf->d = dir;
145     }
146     else if (strncmp(dir, "proxy:", 6) == 0) {
147         conf->d = apr_pstrdup(a, dir);
148     }
149     else {
150         conf->d = apr_pstrcat(a, dir, "/", NULL);
151     }
152     conf->d_is_fnmatch = conf->d ? (apr_is_fnmatch(conf->d) != 0) : 0;
153     conf->d_components = conf->d ? ap_count_dirs(conf->d) : 0;
154
155     conf->opts = dir ? OPT_UNSET : OPT_UNSET|OPT_ALL;
156     conf->opts_add = conf->opts_remove = OPT_NONE;
157     conf->override = dir ? OR_UNSET : OR_UNSET|OR_ALL;
158
159     conf->content_md5 = 2;
160
161     conf->use_canonical_name = USE_CANONICAL_NAME_UNSET;
162
163     conf->hostname_lookups = HOSTNAME_LOOKUP_UNSET;
164     conf->do_rfc1413 = DEFAULT_RFC1413 | 2; /* set bit 1 to indicate default */
165     conf->satisfy = SATISFY_NOSPEC;
166
167 #ifdef RLIMIT_CPU
168     conf->limit_cpu = NULL;
169 #endif
170 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
171     conf->limit_mem = NULL;
172 #endif
173 #ifdef RLIMIT_NPROC
174     conf->limit_nproc = NULL;
175 #endif
176
177     conf->limit_req_body = 0;
178     conf->limit_xml_body = AP_LIMIT_UNSET;
179     conf->sec = apr_make_array(a, 2, sizeof(void *));
180 #ifdef WIN32
181     conf->script_interpreter_source = INTERPRETER_SOURCE_UNSET;
182 #endif
183
184     conf->server_signature = srv_sig_unset;
185
186     conf->add_default_charset = ADD_DEFAULT_CHARSET_UNSET;
187     conf->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
188
189     conf->output_filters = apr_make_array(a, 2, sizeof(void *));
190     conf->input_filters = apr_make_array(a, 2, sizeof(void *));
191     return (void *)conf;
192 }
193
194 static void *merge_core_dir_configs(apr_pool_t *a, void *basev, void *newv)
195 {
196     core_dir_config *base = (core_dir_config *)basev;
197     core_dir_config *new = (core_dir_config *)newv;
198     core_dir_config *conf;
199     int i;
200   
201     conf = (core_dir_config *)apr_palloc(a, sizeof(core_dir_config));
202     memcpy((char *)conf, (const char *)base, sizeof(core_dir_config));
203     if (base->response_code_strings) {
204         conf->response_code_strings =
205             apr_palloc(a, sizeof(*conf->response_code_strings)
206                       * RESPONSE_CODES);
207         memcpy(conf->response_code_strings, base->response_code_strings,
208                sizeof(*conf->response_code_strings) * RESPONSE_CODES);
209     }
210     
211     conf->d = new->d;
212     conf->d_is_fnmatch = new->d_is_fnmatch;
213     conf->d_components = new->d_components;
214     conf->r = new->r;
215     
216     if (new->opts & OPT_UNSET) {
217         /* there was no explicit setting of new->opts, so we merge
218          * preserve the invariant (opts_add & opts_remove) == 0
219          */
220         conf->opts_add = (conf->opts_add & ~new->opts_remove) | new->opts_add;
221         conf->opts_remove = (conf->opts_remove & ~new->opts_add)
222                             | new->opts_remove;
223         conf->opts = (conf->opts & ~conf->opts_remove) | conf->opts_add;
224         if ((base->opts & OPT_INCNOEXEC) && (new->opts & OPT_INCLUDES)) {
225             conf->opts = (conf->opts & ~OPT_INCNOEXEC) | OPT_INCLUDES;
226         }
227     }
228     else {
229         /* otherwise we just copy, because an explicit opts setting
230          * overrides all earlier +/- modifiers
231          */
232         conf->opts = new->opts;
233         conf->opts_add = new->opts_add;
234         conf->opts_remove = new->opts_remove;
235     }
236
237     if (!(new->override & OR_UNSET)) {
238         conf->override = new->override;
239     }
240     if (new->ap_default_type) {
241         conf->ap_default_type = new->ap_default_type;
242     }
243     
244     if (new->ap_auth_type) {
245         conf->ap_auth_type = new->ap_auth_type;
246     }
247     if (new->ap_auth_name) {
248         conf->ap_auth_name = new->ap_auth_name;
249     }
250     if (new->ap_requires) {
251         conf->ap_requires = new->ap_requires;
252     }
253
254     if (new->response_code_strings) {
255         if (conf->response_code_strings == NULL) {
256             conf->response_code_strings = apr_palloc(a,
257                 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
258             memcpy(conf->response_code_strings, new->response_code_strings,
259                    sizeof(*conf->response_code_strings) * RESPONSE_CODES);
260         }
261         else {
262             for (i = 0; i < RESPONSE_CODES; ++i) {
263                 if (new->response_code_strings[i] != NULL) {
264                     conf->response_code_strings[i]
265                         = new->response_code_strings[i];
266                 }
267             }
268         }
269     }
270     if (new->hostname_lookups != HOSTNAME_LOOKUP_UNSET) {
271         conf->hostname_lookups = new->hostname_lookups;
272     }
273     if ((new->do_rfc1413 & 2) == 0) {
274         conf->do_rfc1413 = new->do_rfc1413;
275     }
276     if ((new->content_md5 & 2) == 0) {
277         conf->content_md5 = new->content_md5;
278     }
279     if (new->use_canonical_name != USE_CANONICAL_NAME_UNSET) {
280         conf->use_canonical_name = new->use_canonical_name;
281     }
282
283 #ifdef RLIMIT_CPU
284     if (new->limit_cpu) {
285         conf->limit_cpu = new->limit_cpu;
286     }
287 #endif
288 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
289     if (new->limit_mem) {
290         conf->limit_mem = new->limit_mem;
291     }
292 #endif
293 #ifdef RLIMIT_NPROC
294     if (new->limit_nproc) {
295         conf->limit_nproc = new->limit_nproc;
296     }
297 #endif
298
299     if (new->limit_req_body) {
300         conf->limit_req_body = new->limit_req_body;
301     }
302
303     if (new->limit_xml_body != AP_LIMIT_UNSET)
304         conf->limit_xml_body = new->limit_xml_body;
305     else
306         conf->limit_xml_body = base->limit_xml_body;
307
308     conf->sec = apr_append_arrays(a, base->sec, new->sec);
309
310     if (new->satisfy != SATISFY_NOSPEC) {
311         conf->satisfy = new->satisfy;
312     }
313
314 #ifdef WIN32
315     if (new->script_interpreter_source != INTERPRETER_SOURCE_UNSET) {
316         conf->script_interpreter_source = new->script_interpreter_source;
317     }
318 #endif
319
320     if (new->server_signature != srv_sig_unset) {
321         conf->server_signature = new->server_signature;
322     }
323
324     if (new->add_default_charset != ADD_DEFAULT_CHARSET_UNSET) {
325         conf->add_default_charset = new->add_default_charset;
326         if (new->add_default_charset_name) {
327             conf->add_default_charset_name = new->add_default_charset_name;
328         }
329     }
330     conf->output_filters = apr_append_arrays(a, base->output_filters, 
331                                              new->output_filters);
332     conf->input_filters = apr_append_arrays(a, base->input_filters,
333                                             new->input_filters);
334
335     return (void*)conf;
336 }
337
338 static void *create_core_server_config(apr_pool_t *a, server_rec *s)
339 {
340     core_server_config *conf;
341     int is_virtual = s->is_virtual;
342   
343     conf = (core_server_config *)apr_pcalloc(a, sizeof(core_server_config));
344 #ifdef GPROF
345     conf->gprof_dir = NULL;
346 #endif
347     conf->access_name = is_virtual ? NULL : DEFAULT_ACCESS_FNAME;
348     conf->ap_document_root = is_virtual ? NULL : DOCUMENT_LOCATION;
349     conf->sec = apr_make_array(a, 40, sizeof(void *));
350     conf->sec_url = apr_make_array(a, 40, sizeof(void *));
351     
352     return (void *)conf;
353 }
354
355 static void *merge_core_server_configs(apr_pool_t *p, void *basev, void *virtv)
356 {
357     core_server_config *base = (core_server_config *)basev;
358     core_server_config *virt = (core_server_config *)virtv;
359     core_server_config *conf;
360
361     conf = (core_server_config *)apr_pcalloc(p, sizeof(core_server_config));
362     *conf = *virt;
363     if (!conf->access_name) {
364         conf->access_name = base->access_name;
365     }
366     if (!conf->ap_document_root) {
367         conf->ap_document_root = base->ap_document_root;
368     }
369     conf->sec = apr_append_arrays(p, base->sec, virt->sec);
370     conf->sec_url = apr_append_arrays(p, base->sec_url, virt->sec_url);
371
372     return conf;
373 }
374
375 /* Add per-directory configuration entry (for <directory> section);
376  * these are part of the core server config.
377  */
378
379 AP_CORE_DECLARE(void) ap_add_per_dir_conf(server_rec *s, void *dir_config)
380 {
381     core_server_config *sconf = ap_get_module_config(s->module_config,
382                                                      &core_module);
383     void **new_space = (void **)apr_push_array(sconf->sec);
384     
385     *new_space = dir_config;
386 }
387
388 AP_CORE_DECLARE(void) ap_add_per_url_conf(server_rec *s, void *url_config)
389 {
390     core_server_config *sconf = ap_get_module_config(s->module_config,
391                                                      &core_module);
392     void **new_space = (void **)apr_push_array(sconf->sec_url);
393     
394     *new_space = url_config;
395 }
396
397 AP_CORE_DECLARE(void) ap_add_file_conf(core_dir_config *conf, void *url_config)
398 {
399     void **new_space = (void **)apr_push_array(conf->sec);
400     
401     *new_space = url_config;
402 }
403
404 /* core_reorder_directories reorders the directory sections such that the
405  * 1-component sections come first, then the 2-component, and so on, finally
406  * followed by the "special" sections.  A section is "special" if it's a regex,
407  * or if it doesn't start with / -- consider proxy: matching.  All movements
408  * are in-order to preserve the ordering of the sections from the config files.
409  * See directory_walk().
410  */
411
412 #if defined(HAVE_DRIVE_LETTERS)
413 #define IS_SPECIAL(entry_core)  \
414     ((entry_core)->r != NULL \
415         || ((entry_core)->d[0] != '/' && (entry_core)->d[1] != ':'))
416 #elif defined(NETWARE)
417 /* XXX: Fairly certain this is correct... '/' must prefix the path
418  *      or else in the case xyz:/ or abc/xyz:/, '/' must follow the ':'.
419  *      If there is no leading '/' or embedded ':/', then we are special.
420  */
421 #define IS_SPECIAL(entry_core)  \
422     ((entry_core)->r != NULL \
423         || ((entry_core)->d[0] != '/' \
424             && strchr((entry_core)->d, ':') \
425             && *(strchr((entry_core)->d, ':') + 1) != '/'))
426 #else
427 #define IS_SPECIAL(entry_core)  \
428     ((entry_core)->r != NULL || (entry_core)->d[0] != '/')
429 #endif
430
431 /* We need to do a stable sort, qsort isn't stable.  So to make it stable
432  * we'll be maintaining the original index into the list, and using it
433  * as the minor key during sorting.  The major key is the number of
434  * components (where a "special" section has infinite components).
435  */
436 struct reorder_sort_rec {
437     void *elt;
438     int orig_index;
439 };
440
441 static int reorder_sorter(const void *va, const void *vb)
442 {
443     const struct reorder_sort_rec *a = va;
444     const struct reorder_sort_rec *b = vb;
445     core_dir_config *core_a;
446     core_dir_config *core_b;
447
448     core_a = (core_dir_config *)ap_get_module_config(a->elt, &core_module);
449     core_b = (core_dir_config *)ap_get_module_config(b->elt, &core_module);
450     if (IS_SPECIAL(core_a)) {
451         if (!IS_SPECIAL(core_b)) {
452             return 1;
453         }
454     }
455     else if (IS_SPECIAL(core_b)) {
456         return -1;
457     }
458     else {
459         /* we know they're both not special */
460         if (core_a->d_components < core_b->d_components) {
461             return -1;
462         }
463         else if (core_a->d_components > core_b->d_components) {
464             return 1;
465         }
466     }
467     /* Either they're both special, or they're both not special and have the
468      * same number of components.  In any event, we now have to compare
469      * the minor key. */
470     return a->orig_index - b->orig_index;
471 }
472
473 void ap_core_reorder_directories(apr_pool_t *p, server_rec *s)
474 {
475     core_server_config *sconf;
476     apr_array_header_t *sec;
477     struct reorder_sort_rec *sortbin;
478     int nelts;
479     void **elts;
480     int i;
481     apr_pool_t *tmp;
482
483     sconf = ap_get_module_config(s->module_config, &core_module);
484     sec = sconf->sec;
485     nelts = sec->nelts;
486     elts = (void **)sec->elts;
487
488     /* we have to allocate tmp space to do a stable sort */
489     apr_create_pool(&tmp, p);
490     sortbin = apr_palloc(tmp, sec->nelts * sizeof(*sortbin));
491     for (i = 0; i < nelts; ++i) {
492         sortbin[i].orig_index = i;
493         sortbin[i].elt = elts[i];
494     }
495
496     qsort(sortbin, nelts, sizeof(*sortbin), reorder_sorter);
497
498     /* and now copy back to the original array */
499     for (i = 0; i < nelts; ++i) {
500       elts[i] = sortbin[i].elt;
501     }
502
503     apr_destroy_pool(tmp);
504 }
505
506 /*****************************************************************
507  *
508  * There are some elements of the core config structures in which
509  * other modules have a legitimate interest (this is ugly, but necessary
510  * to preserve NCSA back-compatibility).  So, we have a bunch of accessors
511  * here...
512  */
513
514 AP_DECLARE(int) ap_allow_options(request_rec *r)
515 {
516     core_dir_config *conf = 
517       (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module); 
518
519     return conf->opts; 
520
521
522 AP_DECLARE(int) ap_allow_overrides(request_rec *r) 
523
524     core_dir_config *conf;
525     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
526                                                    &core_module); 
527
528     return conf->override; 
529
530
531 AP_DECLARE(const char *) ap_auth_type(request_rec *r)
532 {
533     core_dir_config *conf;
534
535     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
536                                                    &core_module); 
537     return conf->ap_auth_type;
538 }
539
540 AP_DECLARE(const char *) ap_auth_name(request_rec *r)
541 {
542     core_dir_config *conf;
543
544     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
545                                                    &core_module); 
546     return conf->ap_auth_name;
547 }
548
549 AP_DECLARE(const char *) ap_default_type(request_rec *r)
550 {
551     core_dir_config *conf;
552
553     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
554                                                    &core_module); 
555     return conf->ap_default_type 
556                ? conf->ap_default_type 
557                : DEFAULT_CONTENT_TYPE;
558 }
559
560 AP_DECLARE(const char *) ap_document_root(request_rec *r) /* Don't use this! */
561 {
562     core_server_config *conf;
563
564     conf = (core_server_config *)ap_get_module_config(r->server->module_config,
565                                                       &core_module); 
566     return conf->ap_document_root;
567 }
568
569 AP_DECLARE(const apr_array_header_t *) ap_requires(request_rec *r)
570 {
571     core_dir_config *conf;
572
573     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
574                                                    &core_module); 
575     return conf->ap_requires;
576 }
577
578 AP_DECLARE(int) ap_satisfies(request_rec *r)
579 {
580     core_dir_config *conf;
581
582     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
583                                                    &core_module);
584
585     return conf->satisfy;
586 }
587
588 /* Should probably just get rid of this... the only code that cares is
589  * part of the core anyway (and in fact, it isn't publicised to other
590  * modules).
591  */
592
593 char *ap_response_code_string(request_rec *r, int error_index)
594 {
595     core_dir_config *conf;
596
597     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
598                                                    &core_module); 
599
600     if (conf->response_code_strings == NULL) {
601         return NULL;
602     }
603     return conf->response_code_strings[error_index];
604 }
605
606
607 /* Code from Harald Hanche-Olsen <hanche@imf.unit.no> */
608 static apr_inline void do_double_reverse (conn_rec *conn)
609 {
610     struct hostent *hptr;
611
612     if (conn->double_reverse) {
613         /* already done */
614         return;
615     }
616     if (conn->remote_host == NULL || conn->remote_host[0] == '\0') {
617         /* single reverse failed, so don't bother */
618         conn->double_reverse = -1;
619         return;
620     }
621     hptr = gethostbyname(conn->remote_host);   
622     if (hptr) {          
623         char **haddr;
624
625         for (haddr = hptr->h_addr_list; *haddr; haddr++) {
626             if (((struct in_addr *)(*haddr))->s_addr
627                 == conn->remote_addr.sin_addr.s_addr) {
628                 conn->double_reverse = 1;
629                 return;
630             }
631         }
632     }
633     conn->double_reverse = -1;
634 }
635
636 AP_DECLARE(const char *) ap_get_remote_host(conn_rec *conn, void *dir_config,
637                                             int type)
638 {
639     int hostname_lookups;
640
641     /* If we haven't checked the host name, and we want to */
642     if (dir_config) {
643         hostname_lookups =
644             ((core_dir_config *)ap_get_module_config(dir_config, &core_module))
645                 ->hostname_lookups;
646         if (hostname_lookups == HOSTNAME_LOOKUP_UNSET) {
647             hostname_lookups = HOSTNAME_LOOKUP_OFF;
648         }
649     }
650     else {
651         /* the default */
652         hostname_lookups = HOSTNAME_LOOKUP_OFF;
653     }
654
655     if (type != REMOTE_NOLOOKUP
656         && conn->remote_host == NULL
657         && (type == REMOTE_DOUBLE_REV
658             || hostname_lookups != HOSTNAME_LOOKUP_OFF)) {
659         if (apr_get_remote_hostname(&conn->remote_host, conn->client_socket)
660             == APR_SUCCESS){
661             ap_str_tolower(conn->remote_host);
662            
663             if (hostname_lookups == HOSTNAME_LOOKUP_DOUBLE) {
664                 do_double_reverse(conn);
665                 if (conn->double_reverse != 1) {
666                     conn->remote_host = NULL;
667                 }
668             }
669         }
670         /* if failed, set it to the NULL string to indicate error */
671         if (conn->remote_host == NULL) {
672             conn->remote_host = "";
673         }
674     }
675     if (type == REMOTE_DOUBLE_REV) {
676         do_double_reverse(conn);
677         if (conn->double_reverse == -1) {
678             return NULL;
679         }
680     }
681
682 /*
683  * Return the desired information; either the remote DNS name, if found,
684  * or either NULL (if the hostname was requested) or the IP address
685  * (if any identifier was requested).
686  */
687     if (conn->remote_host != NULL && conn->remote_host[0] != '\0') {
688         return conn->remote_host;
689     }
690     else {
691         if (type == REMOTE_HOST || type == REMOTE_DOUBLE_REV) {
692             return NULL;
693         }
694         else {
695             return conn->remote_ip;
696         }
697     }
698 }
699
700 AP_DECLARE(const char *) ap_get_remote_logname(request_rec *r)
701 {
702     core_dir_config *dir_conf;
703
704     if (r->connection->remote_logname != NULL) {
705         return r->connection->remote_logname;
706     }
707
708 /* If we haven't checked the identity, and we want to */
709     dir_conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
710                                                        &core_module);
711
712     if (dir_conf->do_rfc1413 & 1) {
713         return ap_rfc1413(r->connection, r->server);
714     }
715     else {
716         return NULL;
717     }
718 }
719
720 /* There are two options regarding what the "name" of a server is.  The
721  * "canonical" name as defined by ServerName and Port, or the "client's
722  * name" as supplied by a possible Host: header or full URI.  We never
723  * trust the port passed in the client's headers, we always use the
724  * port of the actual socket.
725  *
726  * The DNS option to UseCanonicalName causes this routine to do a
727  * reverse lookup on the local IP address of the connectiona and use
728  * that for the ServerName. This makes its value more reliable while
729  * at the same time allowing Demon's magic virtual hosting to work.
730  * The assumption is that DNS lookups are sufficiently quick...
731  * -- fanf 1998-10-03
732  */
733 AP_DECLARE(const char *) ap_get_server_name(request_rec *r)
734 {
735     conn_rec *conn = r->connection;
736     core_dir_config *d;
737
738     d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
739                                                 &core_module);
740
741     if (d->use_canonical_name == USE_CANONICAL_NAME_OFF) {
742         return r->hostname ? r->hostname : r->server->server_hostname;
743     }
744     if (d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
745         if (conn->local_host == NULL) {
746             struct in_addr *iaddr;
747             struct hostent *hptr;
748             iaddr = &(conn->local_addr.sin_addr);
749             hptr = gethostbyaddr((char *)iaddr, sizeof(struct in_addr),
750                                  AF_INET);
751             if (hptr != NULL) {
752                 conn->local_host = apr_pstrdup(conn->pool,
753                                               (void *)hptr->h_name);
754                 ap_str_tolower(conn->local_host);
755             }
756             else {
757                 conn->local_host = apr_pstrdup(conn->pool,
758                                               r->server->server_hostname);
759             }
760         }
761         return conn->local_host;
762     }
763     /* default */
764     return r->server->server_hostname;
765 }
766
767 AP_DECLARE(unsigned) ap_get_server_port(const request_rec *r)
768 {
769     unsigned port;
770     core_dir_config *d =
771       (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
772     
773     port = r->server->port ? r->server->port : ap_default_port(r);
774
775     if (d->use_canonical_name == USE_CANONICAL_NAME_OFF
776         || d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
777         if (r->hostname)
778            apr_get_local_port(&port, r->connection->client_socket);
779     }
780     /* default */
781     return port;
782 }
783
784 AP_DECLARE(char *) ap_construct_url(apr_pool_t *p, const char *uri,
785                                     request_rec *r)
786 {
787     unsigned port = ap_get_server_port(r);
788     const char *host = ap_get_server_name(r);
789
790     if (ap_is_default_port(port, r)) {
791         return apr_pstrcat(p, ap_http_method(r), "://", host, uri, NULL);
792     }
793     return apr_psprintf(p, "%s://%s:%u%s", ap_http_method(r), host, port, uri);
794 }
795
796 AP_DECLARE(unsigned long) ap_get_limit_req_body(const request_rec *r)
797 {
798     core_dir_config *d =
799       (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
800     
801     return d->limit_req_body;
802 }
803
804 #ifdef WIN32
805 static apr_status_t get_win32_registry_default_value(apr_pool_t *p, HKEY hkey,
806                                                      char* relativepath, 
807                                                      char **value)
808 {
809     HKEY hkeyOpen;
810     DWORD type;
811     DWORD size = 0;
812     DWORD result = RegOpenKeyEx(hkey, relativepath, 0, 
813                                 KEY_QUERY_VALUE, &hkeyOpen);
814     
815     if (result != ERROR_SUCCESS) 
816         return APR_FROM_OS_ERROR(result);
817
818     /* Read to NULL buffer to determine value size */
819     result = RegQueryValueEx(hkeyOpen, "", 0, &type, NULL, &size);
820     
821    if (result == ERROR_SUCCESS) {
822         if ((size < 2) || (type != REG_SZ && type != REG_EXPAND_SZ)) {
823             result = ERROR_INVALID_PARAMETER;
824         }
825         else {
826             *value = apr_palloc(p, size);
827             /* Read value based on size query above */
828             result = RegQueryValueEx(hkeyOpen, "", 0, &type, *value, &size);
829         }
830     }
831
832     /* TODO: This might look fine, but we need to provide some warning
833      * somewhere that some environment variables may -not- be translated,
834      * seeing as we may have chopped the environment table down somewhat.
835      */
836     if ((result == ERROR_SUCCESS) && (type == REG_EXPAND_SZ)) 
837     {
838         char *tmp = *value;
839         size = ExpandEnvironmentStrings(tmp, *value, 0);
840         if (size) {
841             *value = apr_palloc(p, size);
842             size = ExpandEnvironmentStrings(tmp, *value, size);
843         }
844     }
845
846     RegCloseKey(hkeyOpen);
847     return APR_FROM_OS_ERROR(result);
848 }
849
850 static char* get_interpreter_from_win32_registry(apr_pool_t *p, const char* ext,
851                                                  char** arguments, int strict)
852 {
853     char execcgi_path[] = "SHELL\\EXECCGI\\COMMAND";
854     char execopen_path[] = "SHELL\\OPEN\\COMMAND";
855     char typeName[MAX_PATH];
856     int cmdOfName = FALSE;
857     HKEY hkeyName;
858     HKEY hkeyType;
859     DWORD type;
860     int size;
861     int result;
862     char *buffer;
863     char *s;
864     
865     if (!ext)
866         return NULL;
867     /* 
868      * Future optimization:
869      * When the registry is successfully searched, store the strings for
870      * interpreter and arguments in an ext hash to speed up subsequent look-ups
871      */
872
873     /* Open the key associated with the script filetype extension */
874     result = RegOpenKeyEx(HKEY_CLASSES_ROOT, ext, 0, KEY_QUERY_VALUE, 
875                           &hkeyType);
876
877     if (result != ERROR_SUCCESS) 
878         return NULL;
879
880     /* Retrieve the name of the script filetype extension */
881     size = sizeof(typeName);
882     result = RegQueryValueEx(hkeyType, "", NULL, &type, typeName, &size);
883     
884     if (result == ERROR_SUCCESS && type == REG_SZ && typeName[0]) {
885         /* Open the key associated with the script filetype extension */
886         result = RegOpenKeyEx(HKEY_CLASSES_ROOT, typeName, 0, 
887                               KEY_QUERY_VALUE, &hkeyName);
888
889         if (result == ERROR_SUCCESS)
890             cmdOfName = TRUE;
891     }
892
893     /* Open the key for the script command path by:
894      * 
895      *   1) the 'named' filetype key for ExecCGI/Command
896      *   2) the extension's type key for ExecCGI/Command
897      *
898      * and if the strict arg is false, then continue trying:
899      *
900      *   3) the 'named' filetype key for Open/Command
901      *   4) the extension's type key for Open/Command
902      */
903
904     if (cmdOfName) {
905         result = get_win32_registry_default_value(p, hkeyName, 
906                                                   execcgi_path, &buffer);
907     }
908
909     if (!cmdOfName || (result != ERROR_SUCCESS)) {
910         result = get_win32_registry_default_value(p, hkeyType, 
911                                                   execcgi_path, &buffer);
912     }
913
914     if (!strict && cmdOfName && (result != ERROR_SUCCESS)) {
915         result = get_win32_registry_default_value(p, hkeyName, 
916                                                   execopen_path, &buffer);
917     }
918
919     if (!strict && (result != ERROR_SUCCESS)) {
920         result = get_win32_registry_default_value(p, hkeyType, 
921                                                   execopen_path, &buffer);
922     }
923
924     if (cmdOfName)
925         RegCloseKey(hkeyName);
926
927     RegCloseKey(hkeyType);
928
929     if (result != ERROR_SUCCESS)
930         return NULL;
931
932     /*
933      * The canonical way shell command entries are entered in the Win32 
934      * registry is as follows:
935      *   shell [options] "%1" [args]
936      * where
937      *   shell - full path name to interpreter or shell to run.
938      *           E.g., c:\usr\local\ntreskit\perl\bin\perl.exe
939      *   options - optional switches
940      *              E.g., \C
941      *   "%1" - Place holder for file to run the shell against. 
942      *          Typically quoted.
943      *   options - additional arguments
944      *              E.g., /silent
945      *
946      * If we find a %1 or a quoted %1, lop off the remainder to arguments. 
947      */
948     if (buffer && *buffer) {
949         if ((s = strstr(buffer, "\"%1")))
950         {
951             *s = '\0';
952             *arguments = s + 4;
953         }
954         else if ((s = strstr(buffer, "%1"))) 
955         {
956             *s = '\0';
957             *arguments = buffer + 2;
958         }
959         else
960             *arguments = strchr(buffer, '\0');
961         while (**arguments && isspace(**arguments))
962             ++*arguments;
963     }
964
965     return buffer;
966 }
967
968 AP_DECLARE (file_type_e) ap_get_win32_interpreter(const  request_rec *r, 
969                                                   char** interpreter,
970                                                   char** arguments)
971 {
972     HANDLE hFile;
973     DWORD nBytesRead;
974     BOOLEAN bResult;
975     char buffer[1024];
976     core_dir_config *d;
977     int i;
978     file_type_e fileType = eFileTypeUNKNOWN;
979     char *ext = NULL;
980     char *exename = NULL;
981
982     d = (core_dir_config *)ap_get_module_config(r->per_dir_config, 
983                                                 &core_module);
984
985     /* Find the file extension */
986     exename = strrchr(r->filename, '/');
987     if (!exename) {
988         exename = strrchr(r->filename, '\\');
989     }
990     if (!exename) {
991         exename = r->filename;
992     }
993     else {
994         exename++;
995     }
996     ext = strrchr(exename, '.');
997
998     if (ext && (!strcasecmp(ext,".bat") || !strcasecmp(ext,".cmd"))) 
999     {
1000         char *comspec = getenv("COMSPEC");
1001         if (comspec) {
1002             *interpreter = apr_pstrcat(r->pool, "\"", comspec, "\" /c ", NULL);
1003             return eFileTypeSCRIPT;
1004         }
1005         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r->server,
1006          "Failed to start a '%s' file as a script." APR_EOL_STR
1007          "\tCOMSPEC variable is missing from the environment.", ext);
1008         return eFileTypeUNKNOWN;
1009     }
1010
1011     /* If the file has an extension and it is not .com and not .exe and
1012      * we've been instructed to search the registry, then do it!
1013      */
1014     if (ext && strcasecmp(ext,".exe") && strcasecmp(ext,".com") &&
1015         (d->script_interpreter_source == INTERPRETER_SOURCE_REGISTRY ||
1016          d->script_interpreter_source == INTERPRETER_SOURCE_REGISTRY_STRICT)) {
1017          /* Check the registry */
1018         int strict = (d->script_interpreter_source 
1019                             == INTERPRETER_SOURCE_REGISTRY_STRICT);
1020         *interpreter = get_interpreter_from_win32_registry(r->pool, ext, 
1021                                                            arguments, strict);
1022         if (*interpreter)
1023             return eFileTypeSCRIPT;
1024         else if (d->script_interpreter_source == INTERPRETER_SOURCE_REGISTRY_STRICT) {
1025             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r->server,
1026              "ScriptInterpreterSource config directive set to \"registry-strict\"." APR_EOL_STR
1027              "\tInterpreter not found for files of type '%s'.", ext);
1028              return eFileTypeUNKNOWN;
1029         }
1030         else
1031         {
1032             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r->server,
1033              "ScriptInterpreterSource config directive set to \"registry\"." APR_EOL_STR
1034              "\tInterpreter not found for files of type '%s', "
1035              "trying \"script\" method...", ext);
1036         }
1037     }        
1038
1039     /* Need to peek into the file figure out what it really is... */
1040     hFile = CreateFile(r->filename, GENERIC_READ, FILE_SHARE_READ, NULL,
1041                        OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1042     if (hFile == INVALID_HANDLE_VALUE) {
1043         return eFileTypeUNKNOWN;
1044     }
1045     bResult = ReadFile(hFile, (void*) &buffer, sizeof(buffer) - 1, 
1046                        &nBytesRead, NULL);
1047     if (!bResult || (nBytesRead == 0)) {
1048         ap_log_rerror(APLOG_MARK, APLOG_ERR, GetLastError(), r,
1049                       "ReadFile(%s) failed", r->filename);
1050         CloseHandle(hFile);
1051         return eFileTypeUNKNOWN;
1052     }
1053     CloseHandle(hFile);
1054     buffer[nBytesRead] = '\0';
1055
1056     /* Script or executable, that is the question... */
1057     if ((buffer[0] == '#') && (buffer[1] == '!')) {
1058         /* Assuming file is a script since it starts with a shebang */
1059         fileType = eFileTypeSCRIPT;
1060         for (i = 2; i < sizeof(buffer); i++) {
1061             if ((buffer[i] == '\r')
1062                 || (buffer[i] == '\n')) {
1063                 break;
1064             }
1065         }
1066         buffer[i] = '\0';
1067         for (i = 2; buffer[i] == ' ' ; ++i)
1068             ;
1069         *interpreter = apr_pstrdup(r->pool, buffer + i ); 
1070     }
1071     else {
1072         /* Not a script, is it an executable? */
1073         IMAGE_DOS_HEADER *hdr = (IMAGE_DOS_HEADER*)buffer;    
1074         if ((nBytesRead >= sizeof(IMAGE_DOS_HEADER)) && (hdr->e_magic == IMAGE_DOS_SIGNATURE)) {
1075             if (hdr->e_lfarlc < 0x40)
1076                 fileType = eFileTypeEXE16;
1077             else
1078                 fileType = eFileTypeEXE32;
1079         }
1080         else
1081             fileType = eFileTypeUNKNOWN;
1082     }
1083
1084     return fileType;
1085 }
1086 #endif
1087
1088 /*****************************************************************
1089  *
1090  * Commands... this module handles almost all of the NCSA httpd.conf
1091  * commands, but most of the old srm.conf is in the the modules.
1092  */
1093
1094
1095 /* returns a parent if it matches the given directive */
1096 static const ap_directive_t * find_parent(const ap_directive_t *dirp,
1097                                           const char *what)
1098 {
1099     while (dirp->parent != NULL) {
1100         dirp = dirp->parent;
1101         /* ### it would be nice to have atom-ized directives */
1102         if (strcasecmp(dirp->directive, what) == 0)
1103             return dirp;
1104     }
1105     return NULL;
1106 }
1107
1108 AP_DECLARE(const char *) ap_check_cmd_context(cmd_parms *cmd,
1109                                               unsigned forbidden)
1110 {
1111     const char *gt = (cmd->cmd->name[0] == '<'
1112                       && cmd->cmd->name[strlen(cmd->cmd->name)-1] != '>')
1113                          ? ">" : "";
1114     const ap_directive_t *found;
1115
1116     if ((forbidden & NOT_IN_VIRTUALHOST) && cmd->server->is_virtual) {
1117         return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1118                           " cannot occur within <VirtualHost> section", NULL);
1119     }
1120
1121     if ((forbidden & NOT_IN_LIMIT) && cmd->limited != -1) {
1122         return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1123                           " cannot occur within <Limit> section", NULL);
1124     }
1125
1126     if ((forbidden & NOT_IN_DIR_LOC_FILE) == NOT_IN_DIR_LOC_FILE
1127         && cmd->path != NULL) {
1128         return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1129                           " cannot occur within <Directory/Location/Files> "
1130                           "section", NULL);
1131     }
1132     
1133     if (((forbidden & NOT_IN_DIRECTORY)
1134          && ((found = find_parent(cmd->directive, "<Directory"))
1135              || (found = find_parent(cmd->directive, "<DirectoryMatch"))))
1136         || ((forbidden & NOT_IN_LOCATION)
1137             && ((found = find_parent(cmd->directive, "<Location"))
1138                 || (found = find_parent(cmd->directive, "<LocationMatch"))))
1139         || ((forbidden & NOT_IN_FILES)
1140             && ((found = find_parent(cmd->directive, "<Files"))
1141                 || (found = find_parent(cmd->directive, "<FilesMatch"))))) {
1142         return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1143                           " cannot occur within ", found->directive,
1144                           "> section", NULL);
1145     }
1146
1147     return NULL;
1148 }
1149
1150 static const char *set_access_name(cmd_parms *cmd, void *dummy,
1151                                    const char *arg)
1152 {
1153     void *sconf = cmd->server->module_config;
1154     core_server_config *conf = ap_get_module_config(sconf, &core_module);
1155
1156     const char *err = ap_check_cmd_context(cmd,
1157                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1158     if (err != NULL) {
1159         return err;
1160     }
1161
1162     conf->access_name = apr_pstrdup(cmd->pool, arg);
1163     return NULL;
1164 }
1165
1166 #ifdef GPROF
1167 static const char *set_gprof_dir(cmd_parms *cmd, void *dummy, char *arg)
1168 {
1169     void *sconf = cmd->server->module_config;
1170     core_server_config *conf = ap_get_module_config(sconf, &core_module);
1171
1172     const char *err = ap_check_cmd_context(cmd,
1173                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1174     if (err != NULL) {
1175         return err;
1176     }
1177
1178     conf->gprof_dir = apr_pstrdup(cmd->pool, arg);
1179     return NULL;
1180 }
1181 #endif /*GPROF*/
1182
1183 static const char *set_add_default_charset(cmd_parms *cmd, 
1184                                            void *d_, const char *arg)
1185 {
1186     core_dir_config *d=d_;
1187
1188     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1189     if (err != NULL) {
1190         return err;
1191     }
1192     if (!strcasecmp(arg, "Off")) {
1193        d->add_default_charset = ADD_DEFAULT_CHARSET_OFF;
1194     }
1195     else if (!strcasecmp(arg, "On")) {
1196        d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1197        d->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
1198     }
1199     else {
1200        d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1201        d->add_default_charset_name = arg;
1202     }
1203     return NULL;
1204 }
1205
1206 static const char *set_document_root(cmd_parms *cmd, void *dummy,
1207                                      const char *arg)
1208 {
1209     void *sconf = cmd->server->module_config;
1210     core_server_config *conf = ap_get_module_config(sconf, &core_module);
1211   
1212     const char *err = ap_check_cmd_context(cmd,
1213                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1214     if (err != NULL) {
1215         return err;
1216     }
1217
1218     arg = ap_os_canonical_filename(cmd->pool, arg);
1219     if (/* TODO: ap_configtestonly && ap_docrootcheck && */ !ap_is_directory(arg)) {
1220         if (cmd->server->is_virtual) {
1221             ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1222                          "Warning: DocumentRoot [%s] does not exist",
1223                          arg);
1224         }
1225         else {
1226             return "DocumentRoot must be a directory";
1227         }
1228     }
1229     
1230     conf->ap_document_root = arg;
1231     return NULL;
1232 }
1233
1234 AP_DECLARE(void) ap_custom_response(request_rec *r, int status, char *string)
1235 {
1236     core_dir_config *conf = 
1237         ap_get_module_config(r->per_dir_config, &core_module);
1238     int idx;
1239
1240     if(conf->response_code_strings == NULL) {
1241         conf->response_code_strings = 
1242             apr_pcalloc(r->pool,
1243                     sizeof(*conf->response_code_strings) * 
1244                     RESPONSE_CODES);
1245     }
1246
1247     idx = ap_index_of_response(status);
1248
1249     conf->response_code_strings[idx] = 
1250        ((ap_is_url(string) || (*string == '/')) && (*string != '"')) ? 
1251        apr_pstrdup(r->pool, string) : apr_pstrcat(r->pool, "\"", string, NULL);
1252 }
1253
1254 static const char *set_error_document(cmd_parms *cmd, void *conf_,
1255                                       const char *errno_str, const char *msg)
1256 {
1257     core_dir_config *conf=conf_;
1258     int error_number, index_number, idx500;
1259     enum { MSG, LOCAL_PATH, REMOTE_PATH } what = MSG;
1260                 
1261     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1262     if (err != NULL) {
1263         return err;
1264     }
1265
1266     /* 1st parameter should be a 3 digit number, which we recognize;
1267      * convert it into an array index
1268      */
1269     error_number = atoi(errno_str);
1270     idx500 = ap_index_of_response(HTTP_INTERNAL_SERVER_ERROR);
1271
1272     if (error_number == HTTP_INTERNAL_SERVER_ERROR) {
1273         index_number = idx500;
1274     }
1275     else if ((index_number = ap_index_of_response(error_number)) == idx500) {
1276         return apr_pstrcat(cmd->pool, "Unsupported HTTP response code ",
1277                           errno_str, NULL);
1278     }
1279
1280     /* Heuristic to determine second argument. */
1281     if (ap_strchr_c(msg,' ')) 
1282         what = MSG;
1283     else if (msg[0] == '/')
1284         what = LOCAL_PATH;
1285     else if (ap_is_url(msg))
1286         what = REMOTE_PATH;
1287     else
1288         what = MSG;
1289    
1290     /* The entry should be ignored if it is a full URL for a 401 error */
1291
1292     if (error_number == 401 && what == REMOTE_PATH) {
1293         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, cmd->server,
1294                      "cannot use a full URL in a 401 ErrorDocument "
1295                      "directive --- ignoring!");
1296     }
1297     else { /* Store it... */
1298         if (conf->response_code_strings == NULL) {
1299             conf->response_code_strings =
1300                 apr_pcalloc(cmd->pool,
1301                            sizeof(*conf->response_code_strings) * RESPONSE_CODES);
1302         }
1303         /* hack. Prefix a " if it is a msg; as that is what
1304          * http_protocol.c relies on to distinguish between
1305          * a msg and a (local) path.
1306          */
1307         conf->response_code_strings[index_number] = (what == MSG) ?
1308                 apr_pstrcat(cmd->pool, "\"",msg,NULL) :
1309                 apr_pstrdup(cmd->pool, msg);
1310     }   
1311
1312     return NULL;
1313 }
1314
1315 static const char *set_override(cmd_parms *cmd, void *d_, const char *l)
1316 {
1317     core_dir_config *d=d_;
1318     char *w;
1319   
1320     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1321     if (err != NULL) {
1322         return err;
1323     }
1324
1325     d->override = OR_NONE;
1326     while (l[0]) {
1327         w = ap_getword_conf(cmd->pool, &l);
1328         if (!strcasecmp(w, "Limit")) {
1329             d->override |= OR_LIMIT;
1330         }
1331         else if (!strcasecmp(w, "Options")) {
1332             d->override |= OR_OPTIONS;
1333         }
1334         else if (!strcasecmp(w, "FileInfo")) {
1335             d->override |= OR_FILEINFO;
1336         }
1337         else if (!strcasecmp(w, "AuthConfig")) {
1338             d->override |= OR_AUTHCFG;
1339         }
1340         else if (!strcasecmp(w, "Indexes")) {
1341             d->override |= OR_INDEXES;
1342         }
1343         else if (!strcasecmp(w, "None")) {
1344             d->override = OR_NONE;
1345         }
1346         else if (!strcasecmp(w, "All")) {
1347             d->override = OR_ALL;
1348         }
1349         else {
1350             return apr_pstrcat(cmd->pool, "Illegal override option ", w, NULL);
1351         }
1352         d->override &= ~OR_UNSET;
1353     }
1354
1355     return NULL;
1356 }
1357
1358 static const char *set_options(cmd_parms *cmd, void *d_, const char *l)
1359 {
1360     core_dir_config *d=d_;
1361     allow_options_t opt;
1362     int first = 1;
1363     char action;
1364
1365     while (l[0]) {
1366         char *w = ap_getword_conf(cmd->pool, &l);
1367         action = '\0';
1368
1369         if (*w == '+' || *w == '-') {
1370             action = *(w++);
1371         }
1372         else if (first) {
1373             d->opts = OPT_NONE;
1374             first = 0;
1375         }
1376             
1377         if (!strcasecmp(w, "Indexes")) {
1378             opt = OPT_INDEXES;
1379         }
1380         else if (!strcasecmp(w, "Includes")) {
1381             opt = OPT_INCLUDES;
1382         }
1383         else if (!strcasecmp(w, "IncludesNOEXEC")) {
1384             opt = (OPT_INCLUDES | OPT_INCNOEXEC);
1385         }
1386         else if (!strcasecmp(w, "FollowSymLinks")) {
1387             opt = OPT_SYM_LINKS;
1388         }
1389         else if (!strcasecmp(w, "SymLinksIfOwnerMatch")) {
1390             opt = OPT_SYM_OWNER;
1391         }
1392         else if (!strcasecmp(w, "execCGI")) {
1393             opt = OPT_EXECCGI;
1394         }
1395         else if (!strcasecmp(w, "MultiViews")) {
1396             opt = OPT_MULTI;
1397         }
1398         else if (!strcasecmp(w, "RunScripts")) { /* AI backcompat. Yuck */
1399             opt = OPT_MULTI|OPT_EXECCGI;
1400         }
1401         else if (!strcasecmp(w, "None")) {
1402             opt = OPT_NONE;
1403         }
1404         else if (!strcasecmp(w, "All")) {
1405             opt = OPT_ALL;
1406         }
1407         else {
1408             return apr_pstrcat(cmd->pool, "Illegal option ", w, NULL);
1409         }
1410
1411         /* we ensure the invariant (d->opts_add & d->opts_remove) == 0 */
1412         if (action == '-') {
1413             d->opts_remove |= opt;
1414             d->opts_add &= ~opt;
1415             d->opts &= ~opt;
1416         }
1417         else if (action == '+') {
1418             d->opts_add |= opt;
1419             d->opts_remove &= ~opt;
1420             d->opts |= opt;
1421         }
1422         else {
1423             d->opts |= opt;
1424         }
1425     }
1426
1427     return NULL;
1428 }
1429
1430 static const char *satisfy(cmd_parms *cmd, void *c_, const char *arg)
1431 {
1432     core_dir_config *c=c_;
1433
1434     if (!strcasecmp(arg, "all")) {
1435         c->satisfy = SATISFY_ALL;
1436     }
1437     else if (!strcasecmp(arg, "any")) {
1438         c->satisfy = SATISFY_ANY;
1439     }
1440     else {
1441         return "Satisfy either 'any' or 'all'.";
1442     }
1443     return NULL;
1444 }
1445
1446 static const char *require(cmd_parms *cmd, void *c_, const char *arg)
1447 {
1448     require_line *r;
1449     core_dir_config *c=c_;
1450
1451     if (!c->ap_requires) {
1452         c->ap_requires = apr_make_array(cmd->pool, 2, sizeof(require_line));
1453     }
1454     r = (require_line *)apr_push_array(c->ap_requires);
1455     r->requirement = apr_pstrdup(cmd->pool, arg);
1456     r->method_mask = cmd->limited;
1457     return NULL;
1458 }
1459
1460 AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd, void *dummy,
1461                                                   const char *arg) {
1462     const char *limited_methods = ap_getword(cmd->pool, &arg, '>');
1463     void *tog = cmd->cmd->cmd_data;
1464     int limited = 0;
1465     const char *errmsg;
1466   
1467     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1468     if (err != NULL) {
1469         return err;
1470     }
1471
1472     while (limited_methods[0]) {
1473         char *method = ap_getword_conf(cmd->pool, &limited_methods);
1474         int  methnum = ap_method_number_of(method);
1475
1476         if (methnum == M_TRACE && !tog) {
1477             return "TRACE cannot be controlled by <Limit>";
1478         }
1479         else if (methnum == M_INVALID) {
1480             char **xmethod;
1481             register int i, j, k;
1482
1483             /*
1484              * Deal with <Limit> by adding the method to the list.
1485              */
1486             if (!tog) {
1487                 if (cmd->limited_xmethods == NULL) {
1488                     cmd->limited_xmethods = apr_make_array(cmd->pool, 2,
1489                                                            sizeof(char *));
1490                 }
1491                 xmethod = (char **) apr_push_array(cmd->limited_xmethods);
1492                 *xmethod = apr_pstrdup(cmd->pool, method);
1493             }
1494             /*
1495              * <LimitExcept>, so remove any/all occurrences of the method
1496              * in the extension array.
1497              */
1498             else if ((cmd->limited_xmethods != NULL)
1499                      && (cmd->limited_xmethods->nelts != 0)) {
1500                 xmethod = (char **) cmd->limited_xmethods->elts;
1501                 for (i = 0; i < cmd->limited_xmethods->nelts; ) {
1502                     if (strcmp(xmethod[i], method) == 0) {
1503                         for (j = i, k = i + 1;
1504                              k < cmd->limited_xmethods->nelts;
1505                              ++j, ++k) {
1506                             xmethod[j] = xmethod[k];
1507                         }
1508                         cmd->limited_xmethods->nelts--;
1509                     }
1510                 }
1511             }
1512         }
1513         limited |= (1 << methnum);
1514     }
1515
1516     /* Killing two features with one function,
1517      * if (tog == NULL) <Limit>, else <LimitExcept>
1518      */
1519     cmd->limited = tog ? ~limited : limited;
1520
1521     errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context);
1522
1523     cmd->limited = -1;
1524
1525     return errmsg;
1526 }
1527
1528 /* We use this in <DirectoryMatch> and <FilesMatch>, to ensure that 
1529  * people don't get bitten by wrong-cased regex matches
1530  */
1531
1532 #ifdef WIN32
1533 #define USE_ICASE REG_ICASE
1534 #else
1535 #define USE_ICASE 0
1536 #endif
1537
1538 /*
1539  * Report a missing-'>' syntax error.
1540  */
1541 static char *unclosed_directive(cmd_parms *cmd)
1542 {
1543     return apr_pstrcat(cmd->pool, cmd->cmd->name,
1544                       "> directive missing closing '>'", NULL);
1545 }
1546
1547 static const char *dirsection(cmd_parms *cmd, void *mconfig, const char *arg)
1548 {
1549     const char *errmsg;
1550     const char *endp = ap_strrchr_c(arg, '>');
1551     int old_overrides = cmd->override;
1552     char *old_path = cmd->path;
1553     core_dir_config *conf;
1554     void *new_dir_conf = ap_create_per_dir_config(cmd->pool);
1555     regex_t *r = NULL;
1556     const command_rec *thiscmd = cmd->cmd;
1557
1558     const char *err = ap_check_cmd_context(cmd,
1559                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1560     if (err != NULL) {
1561         return err;
1562     }
1563
1564     if (endp == NULL) {
1565         return unclosed_directive(cmd);
1566     }
1567
1568     arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1569
1570     cmd->path = ap_getword_conf(cmd->pool, &arg);
1571     cmd->override = OR_ALL|ACCESS_CONF;
1572
1573     if (thiscmd->cmd_data) { /* <DirectoryMatch> */
1574         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1575     }
1576     else if (!strcmp(cmd->path, "~")) {
1577         cmd->path = ap_getword_conf(cmd->pool, &arg);
1578         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1579     }
1580 #if defined(HAVE_DRIVE_LETTERS) || defined(NETWARE)
1581     else if (strcmp(cmd->path, "/") == 0) {
1582         /* Treat 'default' path / as an inalienable root */
1583         cmd->path = apr_pstrdup(cmd->pool, cmd->path);
1584     }
1585 #endif
1586 #if defined(HAVE_UNC_PATHS)
1587     else if (strcmp(cmd->path, "//") == 0) {
1588         /* Treat UNC path // as an inalienable root */
1589         cmd->path = apr_pstrdup(cmd->pool, cmd->path);
1590     }
1591 #endif
1592     else {
1593         /* Ensure that the pathname is canonical */
1594         cmd->path = ap_os_canonical_filename(cmd->pool, cmd->path);
1595     }
1596
1597     /* initialize our config and fetch it */
1598     conf = (core_dir_config *)ap_set_config_vectors(cmd, new_dir_conf,
1599                                                     &core_module);
1600
1601     errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_dir_conf);
1602     if (errmsg != NULL)
1603         return errmsg;
1604
1605     conf->r = r;
1606
1607     ap_add_per_dir_conf(cmd->server, new_dir_conf);
1608
1609     if (*arg != '\0') {
1610         return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1611                           "> arguments not (yet) supported.", NULL);
1612     }
1613
1614     cmd->path = old_path;
1615     cmd->override = old_overrides;
1616
1617     return NULL;
1618 }
1619
1620 static const char *urlsection(cmd_parms *cmd, void *mconfig, const char *arg)
1621 {
1622     const char *errmsg;
1623     const char *endp = ap_strrchr_c(arg, '>');
1624     int old_overrides = cmd->override;
1625     char *old_path = cmd->path;
1626     core_dir_config *conf;
1627     regex_t *r = NULL;
1628     const command_rec *thiscmd = cmd->cmd;
1629
1630     void *new_url_conf = ap_create_per_dir_config(cmd->pool);
1631
1632     const char *err = ap_check_cmd_context(cmd,
1633                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1634     if (err != NULL) {
1635         return err;
1636     }
1637
1638     if (endp == NULL) {
1639         return unclosed_directive(cmd);
1640     }
1641
1642     arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1643
1644     cmd->path = ap_getword_conf(cmd->pool, &arg);
1645     cmd->override = OR_ALL|ACCESS_CONF;
1646
1647     if (thiscmd->cmd_data) { /* <LocationMatch> */
1648         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1649     }
1650     else if (!strcmp(cmd->path, "~")) {
1651         cmd->path = ap_getword_conf(cmd->pool, &arg);
1652         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1653     }
1654
1655     /* initialize our config and fetch it */
1656     conf = (core_dir_config *)ap_set_config_vectors(cmd, new_url_conf,
1657                                                     &core_module);
1658
1659     errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_url_conf);
1660     if (errmsg != NULL)
1661         return errmsg;
1662
1663     conf->d = apr_pstrdup(cmd->pool, cmd->path);        /* No mangling, please */
1664     conf->d_is_fnmatch = apr_is_fnmatch(conf->d) != 0;
1665     conf->r = r;
1666
1667     ap_add_per_url_conf(cmd->server, new_url_conf);
1668     
1669     if (*arg != '\0') {
1670         return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1671                           "> arguments not (yet) supported.", NULL);
1672     }
1673
1674     cmd->path = old_path;
1675     cmd->override = old_overrides;
1676
1677     return NULL;
1678 }
1679
1680 static const char *filesection(cmd_parms *cmd, void *mconfig, const char *arg)
1681 {
1682     const char *errmsg;
1683     const char *endp = ap_strrchr_c(arg, '>');
1684     int old_overrides = cmd->override;
1685     char *old_path = cmd->path;
1686     core_dir_config *conf;
1687     regex_t *r = NULL;
1688     const command_rec *thiscmd = cmd->cmd;
1689     core_dir_config *c=mconfig;
1690
1691     void *new_file_conf = ap_create_per_dir_config(cmd->pool);
1692
1693     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT|NOT_IN_LOCATION);
1694     if (err != NULL) {
1695         return err;
1696     }
1697
1698     if (endp == NULL) {
1699         return unclosed_directive(cmd);
1700     }
1701
1702     arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1703
1704     cmd->path = ap_getword_conf(cmd->pool, &arg);
1705     /* Only if not an .htaccess file */
1706     if (!old_path) {
1707         cmd->override = OR_ALL|ACCESS_CONF;
1708     }
1709
1710     if (thiscmd->cmd_data) { /* <FilesMatch> */
1711         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1712     }
1713     else if (!strcmp(cmd->path, "~")) {
1714         cmd->path = ap_getword_conf(cmd->pool, &arg);
1715         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1716     }
1717     else {
1718         /* Ensure that the pathname is canonical */
1719         cmd->path = ap_os_canonical_filename(cmd->pool, cmd->path);
1720     }
1721
1722     /* initialize our config and fetch it */
1723     conf = (core_dir_config *)ap_set_config_vectors(cmd, new_file_conf,
1724                                                     &core_module);
1725
1726     errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_file_conf);
1727     if (errmsg != NULL)
1728         return errmsg;
1729
1730     conf->d = cmd->path;
1731     conf->d_is_fnmatch = apr_is_fnmatch(conf->d) != 0;
1732     conf->r = r;
1733
1734     ap_add_file_conf(c, new_file_conf);
1735
1736     if (*arg != '\0') {
1737         return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1738                           "> arguments not (yet) supported.", NULL);
1739     }
1740
1741     cmd->path = old_path;
1742     cmd->override = old_overrides;
1743
1744     return NULL;
1745 }
1746
1747 static const char *start_ifmod(cmd_parms *cmd, void *mconfig, const char *arg)
1748 {
1749     const char *endp = ap_strrchr_c(arg, '>');
1750     int not = (arg[0] == '!');
1751     module *found;
1752
1753     if (endp == NULL) {
1754         return unclosed_directive(cmd);
1755     }
1756
1757     arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1758
1759     if (not) {
1760         arg++;
1761     }
1762
1763     found = ap_find_linked_module(arg);
1764
1765     if ((!not && found) || (not && !found)) {
1766         ap_directive_t *parent = NULL;
1767         ap_directive_t *current = NULL;
1768         const char *retval;
1769
1770         retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd, 
1771                                       &current, &parent, "<IfModule");
1772         *(ap_directive_t **)mconfig = current;
1773         return retval;
1774     }
1775     else { 
1776         *(ap_directive_t **)mconfig = NULL;
1777         return ap_soak_end_container(cmd, "<IfModule");
1778     }
1779 }
1780
1781 AP_DECLARE(int) ap_exists_config_define(const char *name)
1782 {
1783     char **defines;
1784     int i;
1785
1786     defines = (char **)ap_server_config_defines->elts;
1787     for (i = 0; i < ap_server_config_defines->nelts; i++) {
1788         if (strcmp(defines[i], name) == 0) {
1789             return 1;
1790         }
1791     }
1792     return 0;
1793 }
1794
1795 static const char *start_ifdefine(cmd_parms *cmd, void *dummy, const char *arg)
1796 {
1797     const char *endp;
1798     int defined;
1799     int not = 0;
1800
1801     endp = ap_strrchr_c(arg, '>');
1802     if (endp == NULL) {
1803         return unclosed_directive(cmd);
1804     }
1805
1806     arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1807
1808     if (arg[0] == '!') {
1809         not = 1;
1810         arg++;
1811     }
1812
1813     defined = ap_exists_config_define(arg);
1814     if ((!not && defined) || (not && !defined)) {
1815         ap_directive_t *parent = NULL;
1816         ap_directive_t *current = NULL;
1817         const char *retval;
1818
1819         retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd, 
1820                                       &current, &parent, "<IfDefine");
1821         *(ap_directive_t **)dummy = current;
1822         return retval;
1823     }
1824     else { 
1825         *(ap_directive_t **)dummy = NULL;
1826         return ap_soak_end_container(cmd, "<IfDefine");
1827     }
1828 }
1829
1830 /* httpd.conf commands... beginning with the <VirtualHost> business */
1831
1832 static const char *virtualhost_section(cmd_parms *cmd, void *dummy,
1833                                        const char *arg)
1834 {
1835     server_rec *main_server = cmd->server, *s;
1836     const char *errmsg;
1837     const char *endp = ap_strrchr_c(arg, '>');
1838     apr_pool_t *p = cmd->pool;
1839
1840     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1841     if (err != NULL) {
1842         return err;
1843     }
1844
1845     if (endp == NULL) {
1846         return unclosed_directive(cmd);
1847     }
1848
1849     arg=apr_pstrndup(cmd->pool, arg, endp-arg);
1850     
1851     /* FIXME: There's another feature waiting to happen here -- since you
1852         can now put multiple addresses/names on a single <VirtualHost>
1853         you might want to use it to group common definitions and then
1854         define other "subhosts" with their individual differences.  But
1855         personally I'd rather just do it with a macro preprocessor. -djg */
1856     if (main_server->is_virtual) {
1857         return "<VirtualHost> doesn't nest!";
1858     }
1859     
1860     errmsg = ap_init_virtual_host(p, arg, main_server, &s);
1861     if (errmsg) {
1862         return errmsg;
1863     }
1864
1865     s->next = main_server->next;
1866     main_server->next = s;
1867
1868     s->defn_name = cmd->directive->filename;
1869     s->defn_line_number = cmd->directive->line_num;
1870
1871     cmd->server = s;
1872
1873     errmsg = ap_walk_config(cmd->directive->first_child, cmd,
1874                             s->lookup_defaults);
1875
1876     cmd->server = main_server;
1877
1878     return errmsg;
1879 }
1880
1881 static const char *set_server_alias(cmd_parms *cmd, void *dummy,
1882                                     const char *arg)
1883 {
1884     if (!cmd->server->names) {
1885         return "ServerAlias only used in <VirtualHost>";
1886     }
1887     while (*arg) {
1888         char **item, *name = ap_getword_conf(cmd->pool, &arg);
1889         if (ap_is_matchexp(name)) {
1890             item = (char **)apr_push_array(cmd->server->wild_names);
1891         }
1892         else {
1893             item = (char **)apr_push_array(cmd->server->names);
1894         }
1895         *item = name;
1896     }
1897     return NULL;
1898 }
1899
1900 static const char *add_filter(cmd_parms *cmd, void *dummy, const char *arg)
1901 {
1902     core_dir_config *conf = dummy;
1903     char **newfilter;
1904     
1905     newfilter = (char **)apr_push_array(conf->output_filters);
1906     *newfilter = apr_pstrdup(cmd->pool, arg);
1907     return NULL;
1908 }
1909
1910 static const char *add_input_filter(cmd_parms *cmd, void *dummy, const char *arg)
1911 {
1912     core_dir_config *conf = dummy;
1913     char **newfilter;
1914     
1915     newfilter = (char **)apr_push_array(conf->input_filters);
1916     *newfilter = apr_pstrdup(cmd->pool, arg);
1917     return NULL;
1918 }
1919
1920 static const char *add_module_command(cmd_parms *cmd, void *dummy,
1921                                       const char *arg)
1922 {
1923     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1924     if (err != NULL) {
1925         return err;
1926     }
1927
1928     if (!ap_add_named_module(arg)) {
1929         return apr_pstrcat(cmd->pool, "Cannot add module via name '", arg, 
1930                           "': not in list of loaded modules", NULL);
1931     }
1932     *(ap_directive_t **)dummy = NULL;
1933     return NULL;
1934 }
1935
1936 static const char *clear_module_list_command(cmd_parms *cmd, void *dummy)
1937 {
1938     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1939     if (err != NULL) {
1940         return err;
1941     }
1942
1943     ap_clear_module_list();
1944     *(ap_directive_t **)dummy = NULL;
1945     return NULL;
1946 }
1947
1948 static const char *set_server_string_slot(cmd_parms *cmd, void *dummy,
1949                                           const char *arg)
1950 {
1951     /* This one's pretty generic... */
1952   
1953     int offset = (int)(long)cmd->info;
1954     char *struct_ptr = (char *)cmd->server;
1955     
1956     const char *err = ap_check_cmd_context(cmd, 
1957                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1958     if (err != NULL) {
1959         return err;
1960     }
1961
1962     *(const char **)(struct_ptr + offset) = arg;
1963     return NULL;
1964 }
1965
1966 static const char *server_port(cmd_parms *cmd, void *dummy, const char *arg)
1967 {
1968     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1969     int port;
1970
1971     if (err != NULL) {
1972         return err;
1973     }
1974     port = atoi(arg);
1975     if (port <= 0 || port >= 65536) { /* 65536 == 1<<16 */
1976         return apr_pstrcat(cmd->temp_pool, "The port number \"", arg, 
1977                           "\" is outside the appropriate range "
1978                           "(i.e., 1..65535).", NULL);
1979     }
1980     cmd->server->port = port;
1981     return NULL;
1982 }
1983
1984 static const char *set_signature_flag(cmd_parms *cmd, void *d_,
1985                                       const char *arg)
1986 {
1987     core_dir_config *d=d_;
1988
1989     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1990     if (err != NULL) {
1991         return err;
1992     }
1993
1994     if (strcasecmp(arg, "On") == 0) {
1995         d->server_signature = srv_sig_on;
1996     }
1997     else if (strcasecmp(arg, "Off") == 0) {
1998         d->server_signature = srv_sig_off;
1999     }
2000     else if (strcasecmp(arg, "EMail") == 0) {
2001         d->server_signature = srv_sig_withmail;
2002     }
2003     else {
2004         return "ServerSignature: use one of: off | on | email";
2005     }
2006     return NULL;
2007 }
2008
2009 static const char *set_server_root(cmd_parms *cmd, void *dummy,
2010                                    const char *arg) 
2011 {
2012     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2013
2014     if (err != NULL) {
2015         return err;
2016     }
2017
2018     arg = ap_os_canonical_filename(cmd->pool, arg);
2019
2020     if (!ap_is_directory(arg)) {
2021         return "ServerRoot must be a valid directory";
2022     }
2023     ap_server_root = arg;
2024     return NULL;
2025 }
2026
2027 static const char *set_timeout(cmd_parms *cmd, void *dummy, const char *arg)
2028 {
2029     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2030     if (err != NULL) {
2031         return err;
2032     }
2033
2034     cmd->server->timeout = atoi(arg);
2035     return NULL;
2036 }
2037
2038 static const char *set_keep_alive_timeout(cmd_parms *cmd, void *dummy,
2039                                           const char *arg)
2040 {
2041     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2042     if (err != NULL) {
2043         return err;
2044     }
2045
2046     cmd->server->keep_alive_timeout = atoi(arg);
2047     return NULL;
2048 }
2049
2050 static const char *set_keep_alive(cmd_parms *cmd, void *dummy,
2051                                   const char *arg) 
2052 {
2053     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2054     if (err != NULL) {
2055         return err;
2056     }
2057
2058     /* We've changed it to On/Off, but used to use numbers
2059      * so we accept anything but "Off" or "0" as "On"
2060      */
2061     if (!strcasecmp(arg, "off") || !strcmp(arg, "0")) {
2062         cmd->server->keep_alive = 0;
2063     }
2064     else {
2065         cmd->server->keep_alive = 1;
2066     }
2067     return NULL;
2068 }
2069
2070 static const char *set_keep_alive_max(cmd_parms *cmd, void *dummy,
2071                                       const char *arg)
2072 {
2073     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2074     if (err != NULL) {
2075         return err;
2076     }
2077
2078     cmd->server->keep_alive_max = atoi(arg);
2079     return NULL;
2080 }
2081
2082 static const char *set_idcheck(cmd_parms *cmd, void *d_, int arg) 
2083 {
2084     core_dir_config *d=d_;
2085     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2086     if (err != NULL) {
2087         return err;
2088     }
2089
2090     d->do_rfc1413 = arg != 0;
2091     return NULL;
2092 }
2093
2094 static const char *set_hostname_lookups(cmd_parms *cmd, void *d_,
2095                                         const char *arg)
2096 {
2097     core_dir_config *d=d_;
2098
2099     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2100     if (err != NULL) {
2101         return err;
2102     }
2103
2104     if (!strcasecmp(arg, "on")) {
2105         d->hostname_lookups = HOSTNAME_LOOKUP_ON;
2106     }
2107     else if (!strcasecmp(arg, "off")) {
2108         d->hostname_lookups = HOSTNAME_LOOKUP_OFF;
2109     }
2110     else if (!strcasecmp(arg, "double")) {
2111         d->hostname_lookups = HOSTNAME_LOOKUP_DOUBLE;
2112     }
2113     else {
2114         return "parameter must be 'on', 'off', or 'double'";
2115     }
2116     return NULL;
2117 }
2118
2119 static const char *set_serverpath(cmd_parms *cmd, void *dummy,
2120                                   const char *arg) 
2121 {
2122     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2123     if (err != NULL) {
2124         return err;
2125     }
2126
2127     cmd->server->path = arg;
2128     cmd->server->pathlen = strlen(arg);
2129     return NULL;
2130 }
2131
2132 static const char *set_content_md5(cmd_parms *cmd, void *d_, int arg)
2133 {
2134     core_dir_config *d=d_;
2135     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2136     if (err != NULL) {
2137         return err;
2138     }
2139
2140     d->content_md5 = arg != 0;
2141     return NULL;
2142 }
2143
2144 static const char *set_use_canonical_name(cmd_parms *cmd, void *d_,
2145                                           const char *arg)
2146 {
2147     core_dir_config *d=d_;
2148     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2149     if (err != NULL) {
2150         return err;
2151     }
2152
2153     if (strcasecmp(arg, "on") == 0) {
2154         d->use_canonical_name = USE_CANONICAL_NAME_ON;
2155     }
2156     else if (strcasecmp(arg, "off") == 0) {
2157         d->use_canonical_name = USE_CANONICAL_NAME_OFF;
2158     }
2159     else if (strcasecmp(arg, "dns") == 0) {
2160         d->use_canonical_name = USE_CANONICAL_NAME_DNS;
2161     }
2162     else {
2163         return "parameter must be 'on', 'off', or 'dns'";
2164     }
2165     return NULL;
2166 }
2167
2168
2169 static const char *include_config (cmd_parms *cmd, void *dummy,
2170                                    const char *name)
2171 {
2172     ap_directive_t *conftree = NULL;
2173
2174     ap_process_resource_config(cmd->server,
2175         ap_server_root_relative(cmd->pool, name),
2176                                  &conftree, cmd->pool, cmd->temp_pool);
2177     *(ap_directive_t **)dummy = conftree;
2178     return NULL;
2179 }
2180
2181 static const char *set_loglevel(cmd_parms *cmd, void *dummy, const char *arg) 
2182 {
2183     char *str;
2184     
2185     const char *err = ap_check_cmd_context(cmd,
2186                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2187     if (err != NULL) {
2188         return err;
2189     }
2190
2191     if ((str = ap_getword_conf(cmd->pool, &arg))) {
2192         if (!strcasecmp(str, "emerg")) {
2193             cmd->server->loglevel = APLOG_EMERG;
2194         }
2195         else if (!strcasecmp(str, "alert")) {
2196             cmd->server->loglevel = APLOG_ALERT;
2197         }
2198         else if (!strcasecmp(str, "crit")) {
2199             cmd->server->loglevel = APLOG_CRIT;
2200         }
2201         else if (!strcasecmp(str, "error")) {
2202             cmd->server->loglevel = APLOG_ERR;
2203         }
2204         else if (!strcasecmp(str, "warn")) {
2205             cmd->server->loglevel = APLOG_WARNING;
2206         }
2207         else if (!strcasecmp(str, "notice")) {
2208             cmd->server->loglevel = APLOG_NOTICE;
2209         }
2210         else if (!strcasecmp(str, "info")) {
2211             cmd->server->loglevel = APLOG_INFO;
2212         }
2213         else if (!strcasecmp(str, "debug")) {
2214             cmd->server->loglevel = APLOG_DEBUG;
2215         }
2216         else {
2217             return "LogLevel requires level keyword: one of "
2218                    "emerg/alert/crit/error/warn/notice/info/debug";
2219         }
2220     }
2221     else {
2222         return "LogLevel requires level keyword";
2223     }
2224
2225     return NULL;
2226 }
2227
2228 AP_DECLARE(const char *) ap_psignature(const char *prefix, request_rec *r)
2229 {
2230     char sport[20];
2231     core_dir_config *conf;
2232
2233     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
2234                                                    &core_module);
2235     if ((conf->server_signature == srv_sig_off)
2236             || (conf->server_signature == srv_sig_unset)) {
2237         return "";
2238     }
2239
2240     apr_snprintf(sport, sizeof sport, "%u", (unsigned) ap_get_server_port(r));
2241
2242     if (conf->server_signature == srv_sig_withmail) {
2243         return apr_pstrcat(r->pool, prefix, "<ADDRESS>" AP_SERVER_BASEVERSION
2244                           " Server at <A HREF=\"mailto:",
2245                           r->server->server_admin, "\">",
2246                           ap_get_server_name(r), "</A> Port ", sport,
2247                           "</ADDRESS>\n", NULL);
2248     }
2249     return apr_pstrcat(r->pool, prefix, "<ADDRESS>" AP_SERVER_BASEVERSION
2250                       " Server at ", ap_get_server_name(r), " Port ", sport,
2251                       "</ADDRESS>\n", NULL);
2252 }
2253
2254 /*
2255  * Load an authorisation realm into our location configuration, applying the
2256  * usual rules that apply to realms.
2257  */
2258 static const char *set_authname(cmd_parms *cmd, void *mconfig,
2259                                 const char *word1)
2260 {
2261     core_dir_config *aconfig = (core_dir_config *)mconfig;
2262
2263     aconfig->ap_auth_name = ap_escape_quotes(cmd->pool, word1);
2264     return NULL;
2265 }
2266
2267 #ifdef _OSD_POSIX /* BS2000 Logon Passwd file */
2268 static const char *set_bs2000_account(cmd_parms *cmd, void *dummy, char *name)
2269 {
2270     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2271     if (err != NULL) {
2272         return err;
2273     }
2274
2275     return os_set_account(cmd->pool, name);
2276 }
2277 #endif /*_OSD_POSIX*/
2278
2279 /*
2280  * Handle a request to include the server's OS platform in the Server
2281  * response header field (the ServerTokens directive).  Unfortunately
2282  * this requires a new global in order to communicate the setting back to
2283  * http_main so it can insert the information in the right place in the
2284  * string.
2285  */
2286
2287 static char *server_version = NULL;
2288 static int version_locked = 0; 
2289
2290 enum server_token_type {
2291     SrvTk_MIN,          /* eg: Apache/1.3.0 */
2292     SrvTk_OS,           /* eg: Apache/1.3.0 (UNIX) */
2293     SrvTk_FULL,         /* eg: Apache/1.3.0 (UNIX) PHP/3.0 FooBar/1.2b */
2294     SrvTk_PRODUCT_ONLY  /* eg: Apache */
2295 };
2296 static enum server_token_type ap_server_tokens = SrvTk_FULL;
2297
2298 static apr_status_t reset_version(void *dummy)
2299 {
2300     version_locked = 0;
2301     ap_server_tokens = SrvTk_FULL;
2302     server_version = NULL;
2303     return APR_SUCCESS;
2304 }
2305
2306 AP_DECLARE(const char *) ap_get_server_version(void)
2307 {
2308     return (server_version ? server_version : AP_SERVER_BASEVERSION);
2309 }
2310
2311 AP_DECLARE(void) ap_add_version_component(apr_pool_t *pconf, const char *component)
2312 {
2313     if (! version_locked) {
2314         /*
2315          * If the version string is null, register our cleanup to reset the
2316          * pointer on pool destruction. We also know that, if NULL,
2317          * we are adding the original SERVER_BASEVERSION string.
2318          */
2319         if (server_version == NULL) {
2320             apr_register_cleanup(pconf, NULL, reset_version,
2321                                 apr_null_cleanup);
2322             server_version = apr_pstrdup(pconf, component);
2323         }
2324         else {
2325             /*
2326              * Tack the given component identifier to the end of
2327              * the existing string.
2328              */
2329             server_version = apr_pstrcat(pconf, server_version, " ",
2330                                         component, NULL);
2331         }
2332     }
2333 }
2334
2335 /*
2336  * This routine adds the real server base identity to the version string,
2337  * and then locks out changes until the next reconfig.
2338  */
2339 static void ap_set_version(apr_pool_t *pconf)
2340 {
2341     if (ap_server_tokens == SrvTk_PRODUCT_ONLY) {
2342         ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT);
2343     }
2344     else if (ap_server_tokens == SrvTk_MIN) {
2345         ap_add_version_component(pconf, AP_SERVER_BASEVERSION);
2346     }
2347     else {
2348         ap_add_version_component(pconf, AP_SERVER_BASEVERSION " (" PLATFORM ")");
2349     }
2350     /*
2351      * Lock the server_version string if we're not displaying
2352      * the full set of tokens
2353      */
2354     if (ap_server_tokens != SrvTk_FULL) {
2355         version_locked++;
2356     }
2357 }
2358
2359 static const char *set_serv_tokens(cmd_parms *cmd, void *dummy,
2360                                    const char *arg)
2361 {
2362     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2363     if (err != NULL) {
2364         return err;
2365     }
2366
2367     if (!strcasecmp(arg, "OS")) {
2368         ap_server_tokens = SrvTk_OS;
2369     }
2370     else if (!strcasecmp(arg, "Min") || !strcasecmp(arg, "Minimal")) {
2371         ap_server_tokens = SrvTk_MIN;
2372     }
2373     else if (!strcasecmp(arg, "Prod") || !strcasecmp(arg, "ProductOnly")) {
2374         ap_server_tokens = SrvTk_PRODUCT_ONLY;
2375     }
2376     else {
2377         ap_server_tokens = SrvTk_FULL;
2378     }
2379     return NULL;
2380 }
2381
2382 static const char *set_limit_req_line(cmd_parms *cmd, void *dummy,
2383                                       const char *arg)
2384 {
2385     const char *err = ap_check_cmd_context(cmd,
2386                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2387     int lim;
2388
2389     if (err != NULL) {
2390         return err;
2391     }
2392     lim = atoi(arg);
2393     if (lim < 0) {
2394         return apr_pstrcat(cmd->temp_pool, "LimitRequestLine \"", arg, 
2395                           "\" must be a non-negative integer", NULL);
2396     }
2397     if (lim > DEFAULT_LIMIT_REQUEST_LINE) {
2398         return apr_psprintf(cmd->temp_pool, "LimitRequestLine \"%s\" "
2399                            "must not exceed the precompiled maximum of %d",
2400                            arg, DEFAULT_LIMIT_REQUEST_LINE);
2401     }
2402     cmd->server->limit_req_line = lim;
2403     return NULL;
2404 }
2405
2406 static const char *set_limit_req_fieldsize(cmd_parms *cmd, void *dummy,
2407                                            const char *arg)
2408 {
2409     const char *err = ap_check_cmd_context(cmd,
2410                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2411     int lim;
2412
2413     if (err != NULL) {
2414         return err;
2415     }
2416     lim = atoi(arg);
2417     if (lim < 0) {
2418         return apr_pstrcat(cmd->temp_pool, "LimitRequestFieldsize \"", arg, 
2419                           "\" must be a non-negative integer (0 = no limit)",
2420                           NULL);
2421     }
2422     if (lim > DEFAULT_LIMIT_REQUEST_FIELDSIZE) {
2423         return apr_psprintf(cmd->temp_pool, "LimitRequestFieldsize \"%s\" "
2424                           "must not exceed the precompiled maximum of %d",
2425                            arg, DEFAULT_LIMIT_REQUEST_FIELDSIZE);
2426     }
2427     cmd->server->limit_req_fieldsize = lim;
2428     return NULL;
2429 }
2430
2431 static const char *set_limit_req_fields(cmd_parms *cmd, void *dummy,
2432                                         const char *arg)
2433 {
2434     const char *err = ap_check_cmd_context(cmd,
2435                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2436     int lim;
2437
2438     if (err != NULL) {
2439         return err;
2440     }
2441     lim = atoi(arg);
2442     if (lim < 0) {
2443         return apr_pstrcat(cmd->temp_pool, "LimitRequestFields \"", arg, 
2444                           "\" must be a non-negative integer (0 = no limit)",
2445                           NULL);
2446     }
2447     cmd->server->limit_req_fields = lim;
2448     return NULL;
2449 }
2450
2451 static const char *set_limit_req_body(cmd_parms *cmd, void *conf_,
2452                                       const char *arg) 
2453 {
2454     core_dir_config *conf=conf_;
2455     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2456     if (err != NULL) {
2457         return err;
2458     }
2459
2460     /* WTF: If strtoul is not portable, then write a replacement.
2461      *      Instead we have an idiotic define in httpd.h that prevents
2462      *      it from being used even when it is available. Sheesh.
2463      */
2464     conf->limit_req_body = (unsigned long)strtol(arg, (char **)NULL, 10);
2465     return NULL;
2466 }
2467
2468 static const char *set_limit_xml_req_body(cmd_parms *cmd, void *conf_,
2469                                           const char *arg) 
2470 {
2471     core_dir_config *conf = conf_;
2472     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2473     if (err != NULL) {
2474         return err;
2475     }
2476
2477     conf->limit_xml_body = atol(arg);
2478     if (conf->limit_xml_body < 0)
2479         return "LimitXMLRequestBody requires a non-negative integer.";
2480
2481     return NULL;
2482 }
2483
2484 AP_DECLARE(size_t) ap_get_limit_xml_body(const request_rec *r)
2485 {
2486     core_dir_config *conf;
2487
2488     conf = ap_get_module_config(r->per_dir_config, &core_module);
2489     if (conf->limit_xml_body == AP_LIMIT_UNSET)
2490         return AP_DEFAULT_LIMIT_XML_BODY;
2491     return (size_t)conf->limit_xml_body;
2492 }
2493
2494 #ifdef WIN32
2495 static const char *set_interpreter_source(cmd_parms *cmd, core_dir_config *d,
2496                                                 char *arg)
2497 {
2498     if (!strcasecmp(arg, "registry")) {
2499         d->script_interpreter_source = INTERPRETER_SOURCE_REGISTRY;
2500     } else if (!strcasecmp(arg, "registry-strict")) {
2501         d->script_interpreter_source = INTERPRETER_SOURCE_REGISTRY_STRICT;
2502     } else if (!strcasecmp(arg, "script")) {
2503         d->script_interpreter_source = INTERPRETER_SOURCE_SHEBANG;
2504     } else {
2505         return apr_pstrcat(cmd->temp_pool, "ScriptInterpreterSource \"", arg, 
2506                           "\" must be \"registry\", \"registry-strict\" or "
2507                           "\"script\"", NULL);
2508     }
2509     return NULL;
2510 }
2511 #endif
2512
2513 #if !defined (RLIMIT_CPU) || !(defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)) || !defined (RLIMIT_NPROC)
2514 static const char *no_set_limit(cmd_parms *cmd, void *conf_,
2515                                 const char *arg, const char *arg2)
2516 {
2517     ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, cmd->server,
2518                 "%s not supported on this platform", cmd->cmd->name);
2519     return NULL;
2520 }
2521 #endif
2522
2523 #ifdef RLIMIT_CPU
2524 static const char *set_limit_cpu(cmd_parms *cmd, void *conf_,
2525                                  const char *arg, const char *arg2)
2526 {
2527     core_dir_config *conf=conf_;
2528
2529     unixd_set_rlimit(cmd, &conf->limit_cpu, arg, arg2, RLIMIT_CPU);
2530     return NULL;
2531 }
2532 #endif
2533
2534 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)
2535 static const char *set_limit_mem(cmd_parms *cmd, void *conf_,
2536                                  const char *arg, const char * arg2)
2537 {
2538     core_dir_config *conf=conf_;
2539
2540 #if defined(RLIMIT_AS)
2541     unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2 ,RLIMIT_AS);
2542 #elif defined(RLIMIT_DATA)
2543     unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_DATA);
2544 #elif defined(RLIMIT_VMEM)
2545     unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_VMEM);
2546 #endif
2547     return NULL;
2548 }
2549 #endif
2550
2551 #ifdef RLIMIT_NPROC
2552 static const char *set_limit_nproc(cmd_parms *cmd, void *conf_,
2553                                    const char *arg, const char * arg2)
2554 {
2555     core_dir_config *conf=conf_;
2556
2557     unixd_set_rlimit(cmd, &conf->limit_nproc, arg, arg2, RLIMIT_NPROC);
2558     return NULL;
2559 }
2560 #endif
2561
2562 static apr_status_t writev_it_all(apr_socket_t *s, struct iovec *vec, int nvec, 
2563                                   apr_ssize_t len, apr_ssize_t *nbytes)
2564 {
2565     apr_size_t bytes_written = 0;
2566     apr_status_t rv;
2567     apr_ssize_t n = len;
2568     apr_ssize_t i = 0;
2569
2570     *nbytes = 0;
2571
2572     /* XXX handle checking for non-blocking socket */
2573     while (bytes_written != len) {
2574         rv = apr_sendv(s, vec + i, nvec - i, &n);
2575         bytes_written += n;
2576         if (rv != APR_SUCCESS)
2577             return rv;
2578         *nbytes += n;
2579
2580         /* If the write did not complete, adjust the iovecs and issue
2581          * apr_sendv again
2582          */
2583         if (bytes_written < len) {
2584             /* Skip over the vectors that have already been written */
2585             apr_size_t cnt = vec[i].iov_len;
2586             while (n >= cnt && i + 1 < nvec) {
2587                 i++;
2588                 cnt += vec[i].iov_len;
2589             }
2590             if (n < cnt) {
2591                 /* Handle partial write of vec i */
2592                 vec[i].iov_base = (char *) vec[i].iov_base + 
2593                     (vec[i].iov_len - (cnt - n));
2594                 vec[i].iov_len = cnt -n;
2595             }
2596         }
2597         n = len - bytes_written;
2598     }
2599
2600     return APR_SUCCESS;
2601 }
2602 /*
2603  * send_the_file()
2604  * Sends the contents of file fd along with header/trailer bytes, if any,
2605  * to the network. send_the_file will return only when all the bytes have been
2606  * sent (i.e., it handles partial writes) or on a network error condition.
2607  */
2608 static apr_status_t send_the_file(conn_rec *c, apr_file_t *fd, 
2609                                   apr_hdtr_t *hdtr, apr_off_t offset, 
2610                                   apr_ssize_t length, apr_ssize_t *nbytes) 
2611 {
2612     apr_status_t rv = APR_SUCCESS;
2613     apr_int32_t togo;         /* Remaining number of bytes in the file to send */
2614     apr_ssize_t sendlen = 0;
2615     apr_ssize_t bytes_sent;
2616     apr_int32_t i;
2617     apr_off_t o;              /* Track the file offset for partial writes */
2618     char buffer[8192];
2619
2620     *nbytes = 0;
2621
2622     /* Send the headers 
2623      * writev_it_all handles partial writes.
2624      * XXX: optimization... if headers are less than MIN_WRITE_SIZE, copy 
2625      * them into buffer
2626      */
2627     if ( hdtr && hdtr->numheaders > 0 ) {
2628         for (i = 0; i < hdtr->numheaders; i++) {
2629             sendlen += hdtr->headers[i].iov_len;
2630         }
2631         rv = writev_it_all(c->client_socket, hdtr->headers, hdtr->numheaders,
2632                            sendlen, &bytes_sent);
2633         if (rv == APR_SUCCESS)
2634             *nbytes += bytes_sent;     /* track total bytes sent */
2635     }
2636
2637     /* Seek the file to 'offset' */
2638     if (offset != 0 && rv == APR_SUCCESS) {
2639         rv = apr_seek(fd, APR_SET, &offset);
2640     }
2641
2642     /* Send the file, making sure to handle partial writes */
2643     togo = length;
2644     while (rv == APR_SUCCESS && togo) {
2645         sendlen = togo > sizeof(buffer) ? sizeof(buffer) : togo;
2646         o = 0;
2647         rv = apr_read(fd, buffer, &sendlen);
2648         while (rv == APR_SUCCESS && sendlen) {
2649             bytes_sent = sendlen;
2650             rv = apr_send(c->client_socket, &buffer[o], &bytes_sent);
2651             if (rv == APR_SUCCESS) {
2652                 sendlen -= bytes_sent; /* sendlen != bytes_sent ==> partial write */
2653                 o += bytes_sent;       /* o is where we are in the buffer */
2654                 *nbytes += bytes_sent;
2655                 togo -= bytes_sent;    /* track how much of the file we've sent */
2656             }
2657         }
2658     }
2659
2660     /* Send the trailers 
2661      * XXX: optimization... if it will fit, send this on the last send in the 
2662      * loop above
2663      */
2664     sendlen = 0;
2665     if ( rv == APR_SUCCESS && hdtr && hdtr->numtrailers > 0 ) {
2666         for (i = 0; i < hdtr->numtrailers; i++) {
2667             sendlen += hdtr->trailers[i].iov_len;
2668         }
2669         rv = writev_it_all(c->client_socket, hdtr->trailers, hdtr->numtrailers,
2670                            sendlen, &bytes_sent);
2671         if (rv == APR_SUCCESS)
2672             *nbytes += bytes_sent;
2673     }
2674
2675     return rv;
2676 }
2677
2678 /* Note --- ErrorDocument will now work from .htaccess files.  
2679  * The AllowOverride of Fileinfo allows webmasters to turn it off
2680  */
2681
2682 static const command_rec core_cmds[] = {
2683
2684 /* Old access config file commands */
2685
2686 AP_INIT_RAW_ARGS("<Directory", dirsection, NULL, RSRC_CONF, 
2687   "Container for directives affecting resources located in the specified "
2688   "directories"),
2689 AP_INIT_RAW_ARGS("<Location", urlsection, NULL, RSRC_CONF,
2690   "Container for directives affecting resources accessed through the "
2691   "specified URL paths"),
2692 AP_INIT_RAW_ARGS("<VirtualHost", virtualhost_section, NULL, RSRC_CONF,
2693   "Container to map directives to a particular virtual host, takes one or "
2694   "more host addresses"),
2695 AP_INIT_RAW_ARGS("<Files", filesection, NULL, OR_ALL,
2696   "Container for directives affecting files matching specified patterns"),
2697 AP_INIT_RAW_ARGS("<Limit", ap_limit_section, NULL, OR_ALL,
2698   "Container for authentication directives when accessed using specified HTTP "
2699   "methods"),
2700 AP_INIT_RAW_ARGS("<LimitExcept", ap_limit_section, (void*)1, OR_ALL,
2701   "Container for authentication directives to be applied when any HTTP "
2702   "method other than those specified is used to access the resource"),
2703 AP_INIT_TAKE1("<IfModule", start_ifmod, NULL, EXEC_ON_READ | OR_ALL,
2704   "Container for directives based on existance of specified modules"),
2705 AP_INIT_TAKE1("<IfDefine", start_ifdefine, NULL, EXEC_ON_READ | OR_ALL,
2706   "Container for directives based on existance of command line defines"),
2707 AP_INIT_RAW_ARGS("<DirectoryMatch", dirsection, (void*)1, RSRC_CONF,
2708   "Container for directives affecting resources located in the "
2709   "specified directories"),
2710 AP_INIT_RAW_ARGS("<LocationMatch", urlsection, (void*)1, RSRC_CONF,
2711   "Container for directives affecting resources accessed through the "
2712   "specified URL paths"),
2713 AP_INIT_RAW_ARGS("<FilesMatch", filesection, (void*)1, OR_ALL,
2714   "Container for directives affecting files matching specified patterns"),
2715 AP_INIT_TAKE1("AuthType", ap_set_string_slot,
2716   (void*)XtOffsetOf(core_dir_config, ap_auth_type), OR_AUTHCFG, 
2717   "An HTTP authorization type (e.g., \"Basic\")"),
2718 AP_INIT_TAKE1("AuthName", set_authname, NULL, OR_AUTHCFG,
2719   "The authentication realm (e.g. \"Members Only\")"),
2720 AP_INIT_RAW_ARGS("Require", require, NULL, OR_AUTHCFG,
2721   "Selects which authenticated users or groups may access a protected space"),
2722 AP_INIT_TAKE1("Satisfy", satisfy, NULL, OR_AUTHCFG,
2723   "access policy if both allow and require used ('all' or 'any')"),
2724 #ifdef GPROF
2725 AP_INIT_TAKE1("GprofDir", set_gprof_dir, NULL, RSRC_CONF,
2726   "Directory to plop gmon.out files"),
2727 #endif
2728 AP_INIT_TAKE1("AddDefaultCharset", set_add_default_charset, NULL, OR_FILEINFO, 
2729   "The name of the default charset to add to any Content-Type without one or 'Off' to disable"),
2730
2731 /* Old resource config file commands */
2732   
2733 AP_INIT_RAW_ARGS("AccessFileName", set_access_name, NULL, RSRC_CONF,
2734   "Name(s) of per-directory config files (default: .htaccess)"),
2735 AP_INIT_TAKE1("DocumentRoot", set_document_root, NULL, RSRC_CONF,
2736   "Root directory of the document tree"),
2737 AP_INIT_TAKE2("ErrorDocument", set_error_document, NULL, OR_FILEINFO,
2738   "Change responses for HTTP errors"),
2739 AP_INIT_RAW_ARGS("AllowOverride", set_override, NULL, ACCESS_CONF,
2740   "Controls what groups of directives can be configured by per-directory "
2741   "config files"),
2742 AP_INIT_RAW_ARGS("Options", set_options, NULL, OR_OPTIONS,
2743   "Set a number of attributes for a given directory"),
2744 AP_INIT_TAKE1("DefaultType", ap_set_string_slot,
2745   (void*)XtOffsetOf (core_dir_config, ap_default_type),
2746   OR_FILEINFO, "the default MIME type for untypable files"),
2747
2748 /* Old server config file commands */
2749
2750 AP_INIT_TAKE1("Port", server_port, NULL, RSRC_CONF, "A TCP port number"),
2751 AP_INIT_TAKE1("HostnameLookups", set_hostname_lookups, NULL,
2752   ACCESS_CONF|RSRC_CONF,
2753   "\"on\" to enable, \"off\" to disable reverse DNS lookups, or \"double\" to "
2754   "enable double-reverse DNS lookups"),
2755 AP_INIT_TAKE1("ServerAdmin", set_server_string_slot,
2756   (void *)XtOffsetOf (server_rec, server_admin), RSRC_CONF,
2757   "The email address of the server administrator"),
2758 AP_INIT_TAKE1("ServerName", set_server_string_slot,
2759   (void *)XtOffsetOf (server_rec, server_hostname), RSRC_CONF,
2760   "The hostname of the server"),
2761 AP_INIT_TAKE1("ServerSignature", set_signature_flag, NULL, OR_ALL,
2762   "En-/disable server signature (on|off|email)"),
2763 AP_INIT_TAKE1("ServerRoot", set_server_root, NULL, RSRC_CONF,
2764   "Common directory of server-related files (logs, confs, etc.)"),
2765 AP_INIT_TAKE1("ErrorLog", set_server_string_slot,
2766   (void *)XtOffsetOf (server_rec, error_fname), RSRC_CONF,
2767   "The filename of the error log"),
2768 AP_INIT_RAW_ARGS("ServerAlias", set_server_alias, NULL, RSRC_CONF,
2769   "A name or names alternately used to access the server"),
2770 AP_INIT_TAKE1("ServerPath", set_serverpath, NULL, RSRC_CONF,
2771   "The pathname the server can be reached at"),
2772 AP_INIT_TAKE1("Timeout", set_timeout, NULL, RSRC_CONF,
2773   "Timeout duration (sec)"),
2774 AP_INIT_TAKE1("KeepAliveTimeout", set_keep_alive_timeout, NULL, RSRC_CONF,
2775   "Keep-Alive timeout duration (sec)"),
2776 AP_INIT_TAKE1("MaxKeepAliveRequests", set_keep_alive_max, NULL, RSRC_CONF,
2777   "Maximum number of Keep-Alive requests per connection, or 0 for infinite"),
2778 AP_INIT_TAKE1("KeepAlive", set_keep_alive, NULL, RSRC_CONF,
2779   "Whether persistent connections should be On or Off"),
2780 AP_INIT_FLAG("IdentityCheck", set_idcheck, NULL, RSRC_CONF|ACCESS_CONF,
2781   "Enable identd (RFC 1413) user lookups - SLOW"),
2782 AP_INIT_FLAG("ContentDigest", set_content_md5, NULL, OR_OPTIONS,
2783   "whether or not to send a Content-MD5 header with each request"),
2784 AP_INIT_TAKE1("UseCanonicalName", set_use_canonical_name, NULL,
2785   RSRC_CONF|ACCESS_CONF,
2786   "How to work out the ServerName : Port when constructing URLs"),
2787 /* TODO: RlimitFoo should all be part of mod_cgi, not in the core */
2788 AP_INIT_ITERATE("AddModule", add_module_command, NULL,
2789   RSRC_CONF, "The name of a module"),
2790 AP_INIT_NO_ARGS("ClearModuleList", clear_module_list_command, NULL,
2791   RSRC_CONF, NULL),
2792 /* TODO: ListenBacklog in MPM */
2793 AP_INIT_TAKE1("Include", include_config, NULL,
2794   (RSRC_CONF | ACCESS_CONF | EXEC_ON_READ),
2795   "Name of the config file to be included"),
2796 AP_INIT_TAKE1("LogLevel", set_loglevel, NULL, RSRC_CONF,
2797   "Level of verbosity in error logging"),
2798 AP_INIT_TAKE1("NameVirtualHost", ap_set_name_virtual_host, NULL, RSRC_CONF,
2799   "A numeric IP address:port, or the name of a host"),
2800 #ifdef _OSD_POSIX
2801 AP_INIT_TAKE1("BS2000Account", set_bs2000_account, NULL, RSRC_CONF,
2802   "Name of server User's bs2000 logon account name"),
2803 #endif
2804 #ifdef WIN32
2805 AP_INIT_TAKE1("ScriptInterpreterSource", set_interpreter_source, NULL,
2806   OR_FILEINFO,
2807   "Where to find interpreter to run Win32 scripts (Registry or script shebang line)"),
2808 #endif
2809 AP_INIT_TAKE1("ServerTokens", set_serv_tokens, NULL, RSRC_CONF,
2810   "Determine tokens displayed in the Server: header - Min(imal), OS or Full"),
2811 AP_INIT_TAKE1("LimitRequestLine", set_limit_req_line, NULL, RSRC_CONF,
2812   "Limit on maximum size of an HTTP request line"),
2813 AP_INIT_TAKE1("LimitRequestFieldsize", set_limit_req_fieldsize, NULL,
2814   RSRC_CONF,
2815   "Limit on maximum size of an HTTP request header field"),
2816 AP_INIT_TAKE1("LimitRequestFields", set_limit_req_fields, NULL, RSRC_CONF,
2817   "Limit (0 = unlimited) on max number of header fields in a request message"),
2818 AP_INIT_TAKE1("LimitRequestBody", set_limit_req_body,
2819   (void*)XtOffsetOf(core_dir_config, limit_req_body), OR_ALL,
2820   "Limit (in bytes) on maximum size of request message body"),
2821 AP_INIT_TAKE1("LimitXMLRequestBody", set_limit_xml_req_body, NULL, OR_ALL,
2822               "Limit (in bytes) on maximum size of an XML-based request "
2823               "body"),
2824
2825 /* System Resource Controls */
2826 #ifdef RLIMIT_CPU
2827 AP_INIT_TAKE12("RLimitCPU", set_limit_cpu,
2828   (void*)XtOffsetOf(core_dir_config, limit_cpu),
2829   OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
2830 #else
2831 AP_INIT_TAKE12("RLimitCPU", no_set_limit, NULL,
2832   OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
2833 #endif
2834 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined (RLIMIT_AS)
2835 AP_INIT_TAKE12("RLimitMEM", set_limit_mem,
2836   (void*)XtOffsetOf(core_dir_config, limit_mem),
2837   OR_ALL, "Soft/hard limits for max memory usage per process"),
2838 #else
2839 AP_INIT_TAKE12("RLimitMEM", no_set_limit, NULL,
2840   OR_ALL, "Soft/hard limits for max memory usage per process"),
2841 #endif
2842 #ifdef RLIMIT_NPROC
2843 AP_INIT_TAKE12("RLimitNPROC", set_limit_nproc,
2844   (void*)XtOffsetOf(core_dir_config, limit_nproc),
2845   OR_ALL, "soft/hard limits for max number of processes per uid"),
2846 #else
2847 AP_INIT_TAKE12("RLimitNPROC", no_set_limit, NULL,
2848    OR_ALL, "soft/hard limits for max number of processes per uid"),
2849 #endif
2850 /* XXX These should be allowable in .htaccess files, but currently it won't
2851  * play well with the Options stuff.  Until that is fixed, I would prefer
2852  * to leave it just in the conf file.  Other should feel free to disagree
2853  * with me.  Rbb.
2854  */
2855 AP_INIT_ITERATE("AddOutputFilter", add_filter, NULL, ACCESS_CONF,
2856    "filters to be run"),
2857 AP_INIT_ITERATE("AddInputFilter", add_input_filter, NULL, ACCESS_CONF,
2858    "filters to be run on the request body"),
2859 { NULL }
2860 };
2861
2862 /*****************************************************************
2863  *
2864  * Core handlers for various phases of server operation...
2865  */
2866
2867 AP_DECLARE_NONSTD(int) ap_core_translate(request_rec *r)
2868 {
2869     void *sconf = r->server->module_config;
2870     core_server_config *conf = ap_get_module_config(sconf, &core_module);
2871   
2872     if (r->proxyreq) {
2873         return HTTP_FORBIDDEN;
2874     }
2875     if ((r->uri[0] != '/') && strcmp(r->uri, "*")) {
2876         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2877                      "Invalid URI in request %s", r->the_request);
2878         return HTTP_BAD_REQUEST;
2879     }
2880     
2881     if (r->server->path 
2882         && !strncmp(r->uri, r->server->path, r->server->pathlen)
2883         && (r->server->path[r->server->pathlen - 1] == '/'
2884             || r->uri[r->server->pathlen] == '/'
2885             || r->uri[r->server->pathlen] == '\0')) {
2886         r->filename = apr_pstrcat(r->pool, conf->ap_document_root,
2887                                  (r->uri + r->server->pathlen), NULL);
2888     }
2889     else {
2890         /*
2891          * Make sure that we do not mess up the translation by adding two
2892          * /'s in a row.  This happens under windows when the document
2893          * root ends with a /
2894          */
2895         if ((conf->ap_document_root[strlen(conf->ap_document_root)-1] == '/')
2896             && (*(r->uri) == '/')) {
2897             r->filename = apr_pstrcat(r->pool, conf->ap_document_root, r->uri+1,
2898                                      NULL);
2899         }
2900         else {
2901             r->filename = apr_pstrcat(r->pool, conf->ap_document_root, r->uri,
2902                                      NULL);
2903         }
2904     }
2905
2906     return OK;
2907 }
2908
2909 static int do_nothing(request_rec *r) { return OK; }
2910
2911 static int default_handler(request_rec *r)
2912 {
2913     core_dir_config *d =
2914             (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
2915     int rangestatus, errstatus;
2916     apr_file_t *fd = NULL;
2917     apr_status_t status;
2918 #ifdef AP_USE_MMAP_FILES
2919     apr_mmap_t *mm = NULL;
2920 #endif
2921     /* XXX if/when somebody writes a content-md5 filter we either need to
2922      *     remove this support or coordinate when to use the filter vs.
2923      *     when to use this code
2924      *     The current choice of when to compute the md5 here matches the 1.3
2925      *     support fairly closely (unlike 1.3, we don't handle computing md5
2926      *     when the charset is translated).
2927      */
2928     int bld_content_md5 = 
2929         (d->content_md5 & 1) && r->output_filters->frec->ftype != AP_FTYPE_CONTENT;
2930
2931     ap_allow_methods(r, MERGE_ALLOW, "GET", "OPTIONS", "POST", NULL);
2932
2933     if ((errstatus = ap_discard_request_body(r)) != OK) {
2934         return errstatus;
2935     }
2936     
2937     if (r->method_number == M_INVALID) {
2938         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2939                     "Invalid method in request %s", r->the_request);
2940         return HTTP_NOT_IMPLEMENTED;
2941     }
2942     if (r->method_number == M_OPTIONS) {
2943         return ap_send_http_options(r);
2944     }
2945     if (r->method_number == M_PUT) {
2946         return HTTP_METHOD_NOT_ALLOWED;
2947     }
2948     if (r->finfo.protection == 0 || (r->path_info && *r->path_info)) {
2949         ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r,
2950                       "File does not exist: %s",r->path_info ?
2951                       apr_pstrcat(r->pool, r->filename, r->path_info, NULL)
2952                       : r->filename);
2953         return HTTP_NOT_FOUND;
2954     }
2955     
2956     if (r->method_number != M_GET && r->method_number != M_POST) {
2957         return HTTP_METHOD_NOT_ALLOWED;
2958     }
2959         
2960     if ((status = apr_open(&fd, r->filename, APR_READ | APR_BINARY, 0, r->pool)) != APR_SUCCESS) {
2961         ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r,
2962                      "file permissions deny server access: %s", r->filename);
2963         return HTTP_FORBIDDEN;
2964     }
2965     ap_update_mtime(r, r->finfo.mtime);
2966     ap_set_last_modified(r);
2967     ap_set_etag(r);
2968     apr_table_setn(r->headers_out, "Accept-Ranges", "bytes");
2969     if (((errstatus = ap_meets_conditions(r)) != OK)
2970         || (errstatus = ap_set_content_length(r, r->finfo.size))) {
2971         apr_close(fd);
2972         return errstatus;
2973     }
2974
2975 #ifdef AP_USE_MMAP_FILES
2976     if ((r->finfo.size >= MMAP_THRESHOLD)
2977         && (r->finfo.size < MMAP_LIMIT)
2978         && (!r->header_only || bld_content_md5)) {
2979         /* we need to protect ourselves in case we die while we've got the
2980          * file mmapped */
2981         apr_status_t status;
2982         if ((status = apr_mmap_create(&mm, fd, 0, r->finfo.size, r->pool)) != APR_SUCCESS) {
2983             ap_log_rerror(APLOG_MARK, APLOG_CRIT, status, r,
2984                          "default_handler: mmap failed: %s", r->filename);
2985             mm = NULL;
2986         }
2987     }
2988     else {
2989         mm = NULL;
2990     }
2991
2992     if (mm == NULL) {
2993 #endif
2994
2995         if (bld_content_md5) {
2996             apr_table_setn(r->headers_out, "Content-MD5",
2997                            ap_md5digest(r->pool, fd));
2998         }
2999
3000         rangestatus = ap_set_byterange(r);
3001
3002         ap_send_http_header(r);
3003         
3004         if (!r->header_only) {
3005             apr_size_t length = r->finfo.size;
3006             apr_off_t  offset = 0;
3007             apr_size_t nbytes = 0;
3008
3009             if (!rangestatus) {
3010                 ap_send_fd(fd, r, offset, length, &nbytes);
3011             }
3012             else {
3013                 while (ap_each_byterange(r, &offset, &length)) {
3014                     if ((status = ap_send_fd(fd, r, offset, length, &nbytes)) != APR_SUCCESS) {
3015                         ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
3016                                   "error byteserving file: %s", r->filename);
3017                         return HTTP_INTERNAL_SERVER_ERROR;
3018                     }
3019                 }
3020             }
3021         }
3022
3023 #ifdef AP_USE_MMAP_FILES
3024     }
3025     else {
3026         unsigned char *addr;
3027         apr_mmap_offset((void**)&addr, mm ,0);
3028
3029         if (bld_content_md5) {
3030             apr_md5_ctx_t context;
3031             
3032             apr_MD5Init(&context);
3033             apr_MD5Update(&context, addr, (unsigned int)r->finfo.size);
3034             apr_table_setn(r->headers_out, "Content-MD5",
3035                           ap_md5contextTo64(r->pool, &context));
3036         }
3037
3038         rangestatus = ap_set_byterange(r);
3039         ap_send_http_header(r);
3040         
3041         if (!r->header_only) {
3042             if (!rangestatus) {
3043                 ap_send_mmap(mm, r, 0, r->finfo.size);
3044             }
3045             else {
3046                 apr_off_t offset;
3047                 apr_size_t length;
3048                 while (ap_each_byterange(r, &offset, &length)) {
3049                     ap_send_mmap(mm, r, offset, length);
3050                 }
3051             }
3052         }
3053     }
3054 #endif
3055
3056     apr_close(fd);
3057     return OK;
3058 }
3059 /*
3060  * coalesce_filter()
3061  * This is a simple filter to coalesce many small buckets into one large
3062  * bucket. 
3063  *
3064  * Note:
3065  * This implementation of coalesce_filter will only coalesce a single
3066  * contiguous string of coalesable buckets. It will not coalesce multiple
3067  * non-contiguous buckets. For example, if a brigade contains 10 small 
3068  * buckets followed by a large bucket (or a pipe or file bucket) followed 
3069  * by more small buckets, only the first 10 buckets will be coalesced.
3070  */
3071 typedef struct COALESCE_FILTER_CTX {
3072     char *buf;           /* Start of buffer */
3073     char *cur;           /* Pointer to next location to write */
3074     apr_ssize_t cnt;     /* Number of bytes put in buf */
3075     apr_ssize_t avail;   /* Number of bytes available in the buf */
3076 } coalesce_filter_ctx_t;
3077 #define FILTER_BUFF_SIZE 8192
3078 #define MIN_BUCKET_SIZE 200
3079 static apr_status_t coalesce_filter(ap_filter_t *f, ap_bucket_brigade *b)
3080 {
3081     apr_status_t rv;
3082     apr_pool_t *p = f->r->pool;
3083     ap_bucket *e, *insert_before = NULL, *destroy_me = NULL;
3084     coalesce_filter_ctx_t *ctx = f->ctx;
3085     int pass_the_brigade = 0, insert_first = 0;
3086
3087     if (ctx == NULL) {
3088         f->ctx = ctx = apr_pcalloc(p, sizeof(coalesce_filter_ctx_t));
3089         ctx->avail = FILTER_BUFF_SIZE;
3090     }
3091
3092     if (ctx->cnt) {
3093         insert_first = 1;
3094     }
3095
3096     /* Iterate across the buckets, coalescing the small buckets into a 
3097      * single buffer 
3098      */
3099     AP_BRIGADE_FOREACH(e, b) {
3100         if (destroy_me) {
3101             ap_bucket_destroy(destroy_me);
3102             destroy_me = NULL;
3103         }
3104         if (AP_BUCKET_IS_EOS(e)  || AP_BUCKET_IS_FILE(e) ||
3105             AP_BUCKET_IS_PIPE(e) || AP_BUCKET_IS_FLUSH(e)) {
3106             pass_the_brigade = 1;
3107         }
3108         else {
3109             const char *str;
3110             apr_ssize_t n;
3111             rv = ap_bucket_read(e, &str, &n, AP_BLOCK_READ);
3112             if (rv != APR_SUCCESS) {
3113                 /* XXX: log error */
3114                 return rv;
3115             }
3116             if ((n < MIN_BUCKET_SIZE) && (n < ctx->avail)) {
3117                 /* Coalesce this bucket into the buffer */
3118                 if (ctx->buf == NULL) {
3119                     ctx->buf = apr_palloc(p, FILTER_BUFF_SIZE);
3120                     ctx->cur = ctx->buf;
3121                     ctx->cnt = 0;
3122                 }
3123                 memcpy(ctx->cur, str, n);
3124                 ctx->cnt += n;
3125                 ctx->cur += n;
3126                 ctx->avail -= n;
3127                 /* If this is the first bucket to be coalesced, don't remove it 
3128                  * from the brigade. Save it as a marker for where to insert 
3129                  * ctx->buf into the brigade when we're done.
3130                  */
3131                 if (insert_before || insert_first){
3132                     AP_BUCKET_REMOVE(e);
3133                     destroy_me = e;
3134                 }
3135                 else {
3136                     insert_before = e;
3137                 }
3138             } 
3139             else if (insert_before || insert_first) {
3140                 /* This bucket was not able to be coalesced because it either
3141                  * exceeds MIN_BUCKET_SIZE or its contents will not fit into
3142                  * buf. We're done...
3143                  */
3144                 pass_the_brigade = 1;
3145                 break;
3146             }
3147             else {
3148                 /* If there is even a single bucket that cannot be coalesced, 
3149                  * then we must pass the brigade down to the next filter.
3150                  */
3151                 pass_the_brigade = 1;
3152             }
3153         }
3154     }
3155
3156     if (destroy_me) {
3157         ap_bucket_destroy(destroy_me);
3158         destroy_me = NULL;
3159     }
3160
3161     if (pass_the_brigade) {
3162         /* Insert ctx->buf into the correct spotin the brigade */
3163         if (insert_first) {
3164             e = ap_bucket_create_pool(ctx->buf, ctx->cnt, p);
3165             AP_BRIGADE_INSERT_HEAD(b, e);
3166         } 
3167         else if (insert_before) {
3168             e = ap_bucket_create_pool(ctx->buf, ctx->cnt, p);
3169             AP_BUCKET_INSERT_BEFORE(e, insert_before);
3170             AP_BUCKET_REMOVE(insert_before);
3171             ap_bucket_destroy(insert_before);
3172             insert_before = NULL;
3173         }
3174         rv = ap_pass_brigade(f->next, b);
3175         if (rv != APR_SUCCESS) {
3176             /* XXX: Log the error */
3177             return rv;
3178         }
3179         /* Get ctx->buf ready for the next brigade */
3180         if (ctx) {
3181             ctx->cur = ctx->buf;
3182             ctx->cnt = 0;
3183             ctx->avail = FILTER_BUFF_SIZE;
3184         }
3185     }
3186     else {
3187         if (insert_before) {
3188             AP_BUCKET_REMOVE(insert_before);
3189             ap_bucket_destroy(insert_before);
3190         }
3191         /* The brigade should be empty now because all the buckets
3192          * were coalesced into the coalesce_filter buf
3193          */
3194     }
3195
3196     return APR_SUCCESS;
3197 }
3198 /*
3199  * HTTP/1.1 chunked transfer encoding filter.
3200  */
3201 static apr_status_t chunk_filter(ap_filter_t *f, ap_bucket_brigade *b)
3202 {
3203 #define ASCII_CRLF  "\015\012"
3204 #define ASCII_ZERO  "\060"
3205     ap_bucket_brigade *more = NULL;
3206     ap_bucket *e;
3207     apr_status_t rv;
3208
3209     for (more = NULL; b; b = more, more = NULL) {
3210         apr_off_t bytes = 0;
3211         ap_bucket *eos = NULL;
3212         char chunk_hdr[20]; /* enough space for the snprintf below */
3213
3214         AP_BRIGADE_FOREACH(e, b) {
3215             if (AP_BUCKET_IS_EOS(e)) {
3216                 /* there shouldn't be anything after the eos */
3217                 eos = e;
3218                 break;
3219             }
3220             else if (e->length == -1) {
3221                 /* unknown amount of data (e.g. a pipe) */
3222                 const char *data;
3223                 apr_ssize_t len;
3224
3225                 rv = ap_bucket_read(e, &data, &len, AP_BLOCK_READ);
3226                 if (rv != APR_SUCCESS) {
3227                     return rv;
3228                 }
3229                 if (len > 0) {
3230                     /*
3231                      * There may be a new next bucket representing the
3232                      * rest of the data stream on which a read() may
3233                      * block so we pass down what we have so far.
3234                      */
3235                     bytes += len;
3236                     more = ap_brigade_split(b, AP_BUCKET_NEXT(e));
3237                     break;
3238                 }
3239                 else {
3240                     /* If there was nothing in this bucket then we can
3241                      * safely move on to the next one without pausing
3242                      * to pass down what we have counted up so far.
3243                      */
3244                     continue;
3245                 }
3246             }
3247             else {
3248                 bytes += e->length;
3249             }
3250         }
3251
3252         /*
3253          * XXX: if there aren't very many bytes at this point it may
3254          * be a good idea to set them aside and return for more,
3255          * unless we haven't finished counting this brigade yet.
3256          */
3257
3258         /* if there are content bytes, then wrap them in a chunk */
3259         if (bytes > 0) {
3260             apr_size_t hdr_len;
3261
3262             /*
3263              * Insert the chunk header, specifying the number of bytes in
3264              * the chunk.
3265              */
3266             /* XXX might be nice to have APR_OFF_T_FMT_HEX */
3267             hdr_len = apr_snprintf(chunk_hdr, sizeof(chunk_hdr),
3268                                    "%qx" CRLF, (apr_uint64_t)bytes);
3269             ap_xlate_proto_to_ascii(chunk_hdr, hdr_len);
3270             e = ap_bucket_create_transient(chunk_hdr, hdr_len);
3271             AP_BRIGADE_INSERT_HEAD(b, e);
3272
3273             /*
3274              * Insert the end-of-chunk CRLF before the EOS bucket, or
3275              * appended to the brigade
3276              */
3277             e = ap_bucket_create_immortal(ASCII_CRLF, 2);
3278             if (eos != NULL) {
3279                 AP_BUCKET_INSERT_BEFORE(eos, e);
3280             }
3281             else {
3282                 AP_BRIGADE_INSERT_TAIL(b, e);
3283             }
3284         }
3285
3286         /* RFC 2616, Section 3.6.1
3287          *
3288          * If there is an EOS bucket, then prefix it with:
3289          *   1) the last-chunk marker ("0" CRLF)
3290          *   2) the trailer
3291          *   3) the end-of-chunked body CRLF
3292          *
3293          * If there is no EOS bucket, then do nothing.
3294          *
3295          * XXX: it would be nice to combine this with the end-of-chunk
3296          * marker above, but this is a bit more straight-forward for
3297          * now.
3298          */
3299         if (eos != NULL) {
3300             /* XXX: (2) trailers ... does not yet exist */
3301             e = ap_bucket_create_immortal(ASCII_ZERO ASCII_CRLF /* <trailers> */ ASCII_CRLF, 5);
3302             AP_BUCKET_INSERT_BEFORE(eos, e);
3303         }
3304
3305         /* pass the brigade to the next filter. */
3306         rv = ap_pass_brigade(f->next, b);
3307         if (rv != APR_SUCCESS || eos != NULL) {
3308             return rv;
3309         }
3310     }
3311
3312     return APR_SUCCESS;
3313 }
3314
3315 static int core_input_filter(ap_filter_t *f, ap_bucket_brigade *b, ap_input_mode_t mode)
3316 {
3317     ap_bucket *e;
3318     
3319     if (!f->ctx) {    /* If we haven't passed up the socket yet... */
3320         f->ctx = (void *)1;
3321         e = ap_bucket_create_socket(f->c->client_socket);
3322         AP_BRIGADE_INSERT_TAIL(b, e);
3323         return APR_SUCCESS;
3324     }
3325     else {            
3326         /* Either some code lost track of the socket
3327          * bucket or we already found out that the
3328          * client closed.
3329          */
3330         return APR_EOF;
3331     }
3332 }
3333
3334 /* Default filter.  This filter should almost always be used.  Its only job
3335  * is to send the headers if they haven't already been sent, and then send
3336  * the actual data.
3337  */
3338 typedef struct CORE_OUTPUT_FILTER_CTX {
3339     ap_bucket_brigade *b;
3340 } core_output_filter_ctx_t;
3341 #define MAX_IOVEC_TO_WRITE 16
3342 static apr_status_t core_output_filter(ap_filter_t *f, ap_bucket_brigade *b)
3343 {
3344     apr_status_t rv;
3345     ap_bucket_brigade *more = NULL;
3346     apr_ssize_t bytes_sent = 0, nbytes;
3347     ap_bucket *e;
3348     conn_rec *c = f->c;
3349     core_output_filter_ctx_t *ctx = f->ctx;
3350
3351     apr_ssize_t nvec = 0;
3352     apr_ssize_t nvec_trailers= 0;
3353     struct iovec vec[MAX_IOVEC_TO_WRITE];
3354     struct iovec vec_trailers[MAX_IOVEC_TO_WRITE];
3355
3356     apr_file_t *fd = NULL;
3357     apr_ssize_t flen = 0;
3358     apr_off_t foffset = 0;
3359
3360     if (ctx == NULL) {
3361         f->ctx = ctx = apr_pcalloc(c->pool, sizeof(core_output_filter_ctx_t));
3362     }
3363     /* If we have a saved brigade, concatenate the new brigade to it */
3364     if (ctx->b) {
3365         AP_BRIGADE_CONCAT(ctx->b, b);
3366         b = ctx->b;
3367         ctx->b = NULL;
3368     }
3369
3370     /* Iterate over the brigade collecting iovecs */
3371     while (b) {
3372         nbytes = 0; /* in case more points to another brigade */
3373         more = NULL;
3374         AP_BRIGADE_FOREACH(e, b) {
3375             if (AP_BUCKET_IS_EOS(e) || AP_BUCKET_IS_FLUSH(e)) {
3376                 break;
3377             }
3378             else if (AP_BUCKET_IS_FILE(e)) {
3379                 ap_bucket_file *a = e->data;
3380                 /* Assume there is at most one AP_BUCKET_FILE in the brigade */
3381                 fd = a->fd;
3382                 flen = e->length;
3383                 foffset = a->offset;
3384             }
3385             else {
3386                 const char *str;
3387                 apr_ssize_t n;
3388                 rv = ap_bucket_read(e, &str, &n, AP_BLOCK_READ);
3389                 if (n) {
3390                     nbytes += n;
3391                     if (!fd) {
3392                         vec[nvec].iov_base = (char*) str;
3393                         vec[nvec].iov_len = n;
3394                         nvec++;
3395                     }
3396                     else {
3397                         /* The bucket is a trailer to a file bucket */
3398                         vec_trailers[nvec_trailers].iov_base = (char*) str;
3399                         vec_trailers[nvec_trailers].iov_len = n;
3400                         nvec_trailers++;
3401                     }
3402                 }
3403             }
3404
3405             if ((nvec == MAX_IOVEC_TO_WRITE) || (nvec_trailers == MAX_IOVEC_TO_WRITE)) {
3406                 /* Split the brigade and break */
3407                 if (AP_BUCKET_NEXT(e) != AP_BRIGADE_SENTINEL(b)) {
3408                     more = ap_brigade_split(b, AP_BUCKET_NEXT(e));
3409                 }
3410                 break;
3411             }
3412         }
3413
3414         /* Completed iterating over the brigades, now determine if we want to
3415          * buffer the brigade or send the brigade out on the network
3416          */
3417         if (!fd && (!more) && (nbytes < MIN_SIZE_TO_WRITE) && !AP_BUCKET_IS_EOS(e) && !AP_BUCKET_IS_FLUSH(e)) {
3418             ap_save_brigade(f, &ctx->b, &b);
3419             return APR_SUCCESS;
3420         }
3421         if (fd) {
3422             apr_hdtr_t hdtr;
3423 #if APR_HAS_SENDFILE
3424             apr_int32_t flags = 0;
3425 #endif
3426
3427             memset(&hdtr, '\0', sizeof(hdtr));
3428             if (nvec) {
3429                 hdtr.numheaders = nvec;
3430                 hdtr.headers = vec;
3431             }
3432             if (nvec_trailers) {
3433                 hdtr.numtrailers = nvec_trailers;
3434                 hdtr.trailers = vec_trailers;
3435             }
3436 #if APR_HAS_SENDFILE
3437             if (!c->keepalive) {
3438                 /* Prepare the socket to be reused */
3439                 flags |= APR_SENDFILE_DISCONNECT_SOCKET;
3440             }
3441             nbytes = flen;
3442             rv = apr_sendfile(c->client_socket, 
3443                               fd,       /* The file to send */
3444                               &hdtr,    /* Header and trailer iovecs */
3445                               &foffset, /* Offset in file to begin sending from */
3446                               &nbytes,
3447                               flags);
3448             bytes_sent = nbytes;
3449
3450             /* If apr_sendfile() returns APR_ENOTIMPL, call send_the_file() to
3451              * loop on apr_read/apr_send to send the file. Our Windows binary 
3452              * distributions (which work on Windows 9x/NT) are compiled on 
3453              * Windows NT. TransmitFile is not available on Windows 95/98 and
3454              * we discover this at runtime when apr_sendfile() returns 
3455              * APR_ENOTIMPL. Having apr_sendfile() return APR_ENOTIMPL seems
3456              * the cleanest way to handle this case.
3457              */
3458             if (rv == APR_ENOTIMPL) {
3459 #endif
3460
3461                 rv = send_the_file(c, fd, &hdtr, foffset, flen, &bytes_sent);
3462
3463 #if APR_HAS_SENDFILE
3464             }
3465 #endif
3466         }
3467         else {
3468             rv = writev_it_all(c->client_socket, 
3469                                vec, nvec, 
3470                                nbytes, &bytes_sent);
3471         }
3472
3473         ap_brigade_destroy(b);
3474         if (rv != APR_SUCCESS) {
3475             /* XXX: log the error */
3476             if (more)
3477                 ap_brigade_destroy(more);
3478             return rv;
3479         }
3480         nvec = 0;
3481         nvec_trailers = 0;
3482
3483         b = more;
3484     }  /* end while () */
3485
3486     return APR_SUCCESS;
3487 }
3488
3489 static const handler_rec core_handlers[] = {
3490 { "*/*", default_handler },
3491 { "default-handler", default_handler },
3492 { NULL, NULL }
3493 };
3494
3495 static void core_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
3496 {
3497     ap_init_bucket_types(pconf);
3498 }
3499
3500 static void core_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
3501 {
3502     ap_set_version(pconf);
3503 }
3504
3505 static void core_open_logs(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
3506 {
3507     ap_open_logs(s, pconf);
3508 }
3509
3510 static const char *core_method(const request_rec *r)
3511     { return "http"; }
3512
3513 static unsigned short core_port(const request_rec *r)
3514     { return DEFAULT_HTTP_PORT; }
3515
3516 static void core_insert_filter(request_rec *r)
3517 {
3518     int i;
3519     core_dir_config *conf = (core_dir_config *)
3520                             ap_get_module_config(r->per_dir_config,
3521                                                    &core_module); 
3522     char **items = (char **)conf->output_filters->elts;
3523
3524     for (i = 0; i < conf->output_filters->nelts; i++) {
3525         char *foobar = items[i];
3526         ap_add_output_filter(foobar, NULL, r, r->connection);
3527     }
3528
3529     items = (char **)conf->input_filters->elts;
3530     for (i = 0; i < conf->input_filters->nelts; i++) {
3531         char *foobar = items[i];
3532         ap_add_input_filter(foobar, NULL, r, r->connection);
3533     }
3534 }
3535
3536 static void register_hooks(void)
3537 {
3538     ap_hook_pre_config(core_pre_config, NULL, NULL, AP_HOOK_REALLY_FIRST);
3539     ap_hook_post_config(core_post_config,NULL,NULL,AP_HOOK_REALLY_FIRST);
3540     ap_hook_translate_name(ap_core_translate,NULL,NULL,AP_HOOK_REALLY_LAST);
3541     ap_hook_pre_connection(ap_pre_http_connection,NULL,NULL,
3542                                AP_HOOK_REALLY_LAST);
3543     ap_hook_process_connection(ap_process_http_connection,NULL,NULL,
3544                                AP_HOOK_REALLY_LAST);
3545     ap_hook_http_method(core_method,NULL,NULL,AP_HOOK_REALLY_LAST);
3546     ap_hook_default_port(core_port,NULL,NULL,AP_HOOK_REALLY_LAST);
3547     ap_hook_open_logs(core_open_logs,NULL,NULL,AP_HOOK_MIDDLE);
3548     /* FIXME: I suspect we can eliminate the need for these - Ben */
3549     ap_hook_type_checker(do_nothing,NULL,NULL,AP_HOOK_REALLY_LAST);
3550     ap_hook_access_checker(do_nothing,NULL,NULL,AP_HOOK_REALLY_LAST);
3551
3552     /* register the core's insert_filter hook and register core-provided
3553      * filters
3554      */
3555     ap_hook_insert_filter(core_insert_filter, NULL, NULL, AP_HOOK_MIDDLE);
3556     ap_register_input_filter("HTTP_IN", ap_http_filter, AP_FTYPE_CONNECTION);
3557     ap_register_input_filter("DECHUNK", ap_dechunk_filter, AP_FTYPE_TRANSCODE);
3558     ap_register_input_filter("CORE_IN", core_input_filter, AP_FTYPE_NETWORK);
3559     ap_register_output_filter("HTTP_HEADER", ap_http_header_filter, AP_FTYPE_HTTP_HEADER);
3560     ap_register_output_filter("CONTENT_LENGTH", ap_content_length_filter, 
3561                               AP_FTYPE_HTTP_HEADER);
3562     ap_register_output_filter("CORE", core_output_filter, AP_FTYPE_NETWORK);
3563     ap_register_output_filter("SUBREQ_CORE", ap_sub_req_output_filter, 
3564                               AP_FTYPE_CONTENT);
3565     ap_register_output_filter("CHUNK", chunk_filter, AP_FTYPE_TRANSCODE);
3566     ap_register_output_filter("COALESCE", coalesce_filter, AP_FTYPE_CONNECTION);
3567 }
3568
3569 AP_DECLARE_DATA module core_module = {
3570     STANDARD20_MODULE_STUFF,
3571     create_core_dir_config,     /* create per-directory config structure */
3572     merge_core_dir_configs,     /* merge per-directory config structures */
3573     create_core_server_config,  /* create per-server config structure */
3574     merge_core_server_configs,  /* merge per-server config structures */
3575     core_cmds,                  /* command apr_table_t */
3576     core_handlers,              /* handlers */
3577     register_hooks              /* register hooks */
3578 };