]> granicus.if.org Git - apache/blob - server/core.c
79779e7add5b924ce87b06a98be0aa2ef53db910
[apache] / server / core.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2003 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  *    if any, must include the following acknowledgment:
21  *       "This product includes software developed by the
22  *        Apache Software Foundation (http://www.apache.org/)."
23  *    Alternately, this acknowledgment may appear in the software itself,
24  *    if and wherever such third-party acknowledgments normally appear.
25  *
26  * 4. The names "Apache" and "Apache Software Foundation" must
27  *    not be used to endorse or promote products derived from this
28  *    software without prior written permission. For written
29  *    permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache",
32  *    nor may "Apache" appear in their name, without prior written
33  *    permission of the Apache Software Foundation.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation.  For more
51  * information on the Apache Software Foundation, please see
52  * <http://www.apache.org/>.
53  *
54  * Portions of this software are based upon public domain software
55  * originally written at the National Center for Supercomputing Applications,
56  * University of Illinois, Urbana-Champaign.
57  */
58
59 #include "apr.h"
60 #include "apr_strings.h"
61 #include "apr_lib.h"
62 #include "apr_fnmatch.h"
63 #include "apr_hash.h"
64 #include "apr_thread_proc.h"    /* for RLIMIT stuff */
65 #include "apr_hooks.h"
66
67 #define APR_WANT_IOVEC
68 #define APR_WANT_STRFUNC
69 #define APR_WANT_MEMFUNC
70 #include "apr_want.h"
71
72 #define CORE_PRIVATE
73 #include "ap_config.h"
74 #include "httpd.h"
75 #include "http_config.h"
76 #include "http_core.h"
77 #include "http_protocol.h" /* For index_of_response().  Grump. */
78 #include "http_request.h"
79 #include "http_vhost.h"
80 #include "http_main.h"     /* For the default_handler below... */
81 #include "http_log.h"
82 #include "util_md5.h"
83 #include "http_connection.h"
84 #include "apr_buckets.h"
85 #include "util_filter.h"
86 #include "util_ebcdic.h"
87 #include "mpm.h"
88 #include "mpm_common.h"
89 #include "scoreboard.h"
90 #include "mod_core.h"
91 #include "mod_proxy.h"
92 #include "ap_listen.h"
93
94 /* LimitXMLRequestBody handling */
95 #define AP_LIMIT_UNSET                  ((long) -1)
96 #define AP_DEFAULT_LIMIT_XML_BODY       ((size_t)1000000)
97
98 #define AP_MIN_SENDFILE_BYTES           (256)
99
100 APR_HOOK_STRUCT(
101     APR_HOOK_LINK(get_mgmt_items)
102 )
103
104 AP_IMPLEMENT_HOOK_RUN_ALL(int, get_mgmt_items,
105                           (apr_pool_t *p, const char *val, apr_hash_t *ht),
106                           (p, val, ht), OK, DECLINED)
107
108 /* Server core module... This module provides support for really basic
109  * server operations, including options and commands which control the
110  * operation of other modules.  Consider this the bureaucracy module.
111  *
112  * The core module also defines handlers, etc., do handle just enough
113  * to allow a server with the core module ONLY to actually serve documents
114  * (though it slaps DefaultType on all of 'em); this was useful in testing,
115  * but may not be worth preserving.
116  *
117  * This file could almost be mod_core.c, except for the stuff which affects
118  * the http_conf_globals.
119  */
120
121 /* Handles for core filters */
122 AP_DECLARE_DATA ap_filter_rec_t *ap_subreq_core_filter_handle;
123 AP_DECLARE_DATA ap_filter_rec_t *ap_core_output_filter_handle;
124 AP_DECLARE_DATA ap_filter_rec_t *ap_content_length_filter_handle;
125 AP_DECLARE_DATA ap_filter_rec_t *ap_net_time_filter_handle;
126 AP_DECLARE_DATA ap_filter_rec_t *ap_core_input_filter_handle;
127
128 static void *create_core_dir_config(apr_pool_t *a, char *dir)
129 {
130     core_dir_config *conf;
131
132     conf = (core_dir_config *)apr_pcalloc(a, sizeof(core_dir_config));
133
134     /* conf->r and conf->d[_*] are initialized by dirsection() or left NULL */
135
136     conf->opts = dir ? OPT_UNSET : OPT_UNSET|OPT_ALL;
137     conf->opts_add = conf->opts_remove = OPT_NONE;
138     conf->override = dir ? OR_UNSET : OR_UNSET|OR_ALL;
139
140     conf->content_md5 = 2;
141     conf->accept_path_info = 3;
142
143     conf->use_canonical_name = USE_CANONICAL_NAME_UNSET;
144
145     conf->hostname_lookups = HOSTNAME_LOOKUP_UNSET;
146     conf->satisfy = SATISFY_NOSPEC;
147
148 #ifdef RLIMIT_CPU
149     conf->limit_cpu = NULL;
150 #endif
151 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
152     conf->limit_mem = NULL;
153 #endif
154 #ifdef RLIMIT_NPROC
155     conf->limit_nproc = NULL;
156 #endif
157
158     conf->limit_req_body = 0;
159     conf->limit_xml_body = AP_LIMIT_UNSET;
160     conf->sec_file = apr_array_make(a, 2, sizeof(ap_conf_vector_t *));
161
162     conf->server_signature = srv_sig_unset;
163
164     conf->add_default_charset = ADD_DEFAULT_CHARSET_UNSET;
165     conf->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
166
167     /* Overriding all negotiation
168      */
169     conf->mime_type = NULL;
170     conf->handler = NULL;
171     conf->output_filters = NULL;
172     conf->input_filters = NULL;
173
174     /*
175      * Flag for use of inodes in ETags.
176      */
177     conf->etag_bits = ETAG_UNSET;
178     conf->etag_add = ETAG_UNSET;
179     conf->etag_remove = ETAG_UNSET;
180
181     conf->enable_mmap = ENABLE_MMAP_UNSET;
182     conf->enable_sendfile = ENABLE_SENDFILE_UNSET;
183     conf->allow_encoded_slashes = 0;
184
185     return (void *)conf;
186 }
187
188 /*
189  * Overlay one hash table of ct_output_filters onto another
190  */
191 static void *merge_ct_filters(apr_pool_t *p,
192                               const void *key,
193                               apr_ssize_t klen,
194                               const void *overlay_val,
195                               const void *base_val,
196                               const void *data)
197 {
198     ap_filter_rec_t *cur;
199     const ap_filter_rec_t *overlay_info = (const ap_filter_rec_t *)overlay_val;
200     const ap_filter_rec_t *base_info = (const ap_filter_rec_t *)base_val;
201
202     cur = NULL;
203
204     while (overlay_info) {
205         ap_filter_rec_t *new;
206
207         new = apr_pcalloc(p, sizeof(ap_filter_rec_t));
208         new->name = apr_pstrdup(p, overlay_info->name);
209         new->next = cur;
210         cur = new;
211         overlay_info = overlay_info->next;
212     }
213
214     while (base_info) {
215         ap_filter_rec_t *f;
216         int found = 0;
217
218         /* We can't have dups. */
219         f = cur;
220         while (f) {
221             if (!strcasecmp(base_info->name, f->name)) {
222                 found = 1;
223                 break;
224             }
225
226             f = f->next;
227         }
228
229         if (!found) {
230             f = apr_pcalloc(p, sizeof(ap_filter_rec_t));
231             f->name = apr_pstrdup(p, base_info->name);
232             f->next = cur;
233             cur = f;
234         }
235
236         base_info = base_info->next;
237     }
238
239     return cur;
240 }
241
242 static void *merge_core_dir_configs(apr_pool_t *a, void *basev, void *newv)
243 {
244     core_dir_config *base = (core_dir_config *)basev;
245     core_dir_config *new = (core_dir_config *)newv;
246     core_dir_config *conf;
247     int i;
248
249     /* Create this conf by duplicating the base, replacing elements
250      * (or creating copies for merging) where new-> values exist.
251      */
252     conf = (core_dir_config *)apr_palloc(a, sizeof(core_dir_config));
253     memcpy(conf, base, sizeof(core_dir_config));
254
255     conf->d = new->d;
256     conf->d_is_fnmatch = new->d_is_fnmatch;
257     conf->d_components = new->d_components;
258     conf->r = new->r;
259
260     if (new->opts & OPT_UNSET) {
261         /* there was no explicit setting of new->opts, so we merge
262          * preserve the invariant (opts_add & opts_remove) == 0
263          */
264         conf->opts_add = (conf->opts_add & ~new->opts_remove) | new->opts_add;
265         conf->opts_remove = (conf->opts_remove & ~new->opts_add)
266                             | new->opts_remove;
267         conf->opts = (conf->opts & ~conf->opts_remove) | conf->opts_add;
268         if ((base->opts & OPT_INCNOEXEC) && (new->opts & OPT_INCLUDES)) {
269             conf->opts = (conf->opts & ~OPT_INCNOEXEC) | OPT_INCLUDES;
270         }
271     }
272     else {
273         /* otherwise we just copy, because an explicit opts setting
274          * overrides all earlier +/- modifiers
275          */
276         conf->opts = new->opts;
277         conf->opts_add = new->opts_add;
278         conf->opts_remove = new->opts_remove;
279     }
280
281     if (!(new->override & OR_UNSET)) {
282         conf->override = new->override;
283     }
284
285     if (new->ap_default_type) {
286         conf->ap_default_type = new->ap_default_type;
287     }
288
289     if (new->ap_auth_type) {
290         conf->ap_auth_type = new->ap_auth_type;
291     }
292
293     if (new->ap_auth_name) {
294         conf->ap_auth_name = new->ap_auth_name;
295     }
296
297     if (new->ap_requires) {
298         conf->ap_requires = new->ap_requires;
299     }
300
301     if (conf->response_code_strings == NULL) {
302         conf->response_code_strings = new->response_code_strings;
303     }
304     else if (new->response_code_strings != NULL) {
305         /* If we merge, the merge-result must have it's own array
306          */
307         conf->response_code_strings = apr_palloc(a,
308             sizeof(*conf->response_code_strings) * RESPONSE_CODES);
309         memcpy(conf->response_code_strings, base->response_code_strings,
310                sizeof(*conf->response_code_strings) * RESPONSE_CODES);
311
312         for (i = 0; i < RESPONSE_CODES; ++i) {
313             if (new->response_code_strings[i] != NULL) {
314                 conf->response_code_strings[i] = new->response_code_strings[i];
315             }
316         }
317     }
318     /* Otherwise we simply use the base->response_code_strings array
319      */
320
321     if (new->hostname_lookups != HOSTNAME_LOOKUP_UNSET) {
322         conf->hostname_lookups = new->hostname_lookups;
323     }
324
325     if ((new->content_md5 & 2) == 0) {
326         conf->content_md5 = new->content_md5;
327     }
328
329     if (new->accept_path_info != 3) {
330         conf->accept_path_info = new->accept_path_info;
331     }
332
333     if (new->use_canonical_name != USE_CANONICAL_NAME_UNSET) {
334         conf->use_canonical_name = new->use_canonical_name;
335     }
336
337 #ifdef RLIMIT_CPU
338     if (new->limit_cpu) {
339         conf->limit_cpu = new->limit_cpu;
340     }
341 #endif
342
343 #if defined(RLIMIT_DATA) || defined(RLIMIT_VMEM) || defined(RLIMIT_AS)
344     if (new->limit_mem) {
345         conf->limit_mem = new->limit_mem;
346     }
347 #endif
348
349 #ifdef RLIMIT_NPROC
350     if (new->limit_nproc) {
351         conf->limit_nproc = new->limit_nproc;
352     }
353 #endif
354
355     if (new->limit_req_body) {
356         conf->limit_req_body = new->limit_req_body;
357     }
358
359     if (new->limit_xml_body != AP_LIMIT_UNSET)
360         conf->limit_xml_body = new->limit_xml_body;
361     else
362         conf->limit_xml_body = base->limit_xml_body;
363
364     if (!conf->sec_file) {
365         conf->sec_file = new->sec_file;
366     }
367     else if (new->sec_file) {
368         /* If we merge, the merge-result must have it's own array
369          */
370         conf->sec_file = apr_array_append(a, base->sec_file, new->sec_file);
371     }
372     /* Otherwise we simply use the base->sec_file array
373      */
374
375     if (new->satisfy != SATISFY_NOSPEC) {
376         conf->satisfy = new->satisfy;
377     }
378
379     if (new->server_signature != srv_sig_unset) {
380         conf->server_signature = new->server_signature;
381     }
382
383     if (new->add_default_charset != ADD_DEFAULT_CHARSET_UNSET) {
384         conf->add_default_charset = new->add_default_charset;
385         conf->add_default_charset_name = new->add_default_charset_name;
386     }
387
388     /* Overriding all negotiation
389      */
390     if (new->mime_type) {
391         conf->mime_type = new->mime_type;
392     }
393
394     if (new->handler) {
395         conf->handler = new->handler;
396     }
397
398     if (new->output_filters) {
399         conf->output_filters = new->output_filters;
400     }
401
402     if (new->input_filters) {
403         conf->input_filters = new->input_filters;
404     }
405
406     if (conf->ct_output_filters && new->ct_output_filters) {
407         conf->ct_output_filters = apr_hash_merge(a,
408                                                  new->ct_output_filters,
409                                                  conf->ct_output_filters,
410                                                  merge_ct_filters,
411                                                  NULL);
412     }
413     else if (new->ct_output_filters) {
414         conf->ct_output_filters = apr_hash_copy(a, new->ct_output_filters);
415     }
416     else if (conf->ct_output_filters) {
417         /* That memcpy above isn't enough. */
418         conf->ct_output_filters = apr_hash_copy(a, base->ct_output_filters);
419     }
420
421     /*
422      * Now merge the setting of the FileETag directive.
423      */
424     if (new->etag_bits == ETAG_UNSET) {
425         conf->etag_add =
426             (conf->etag_add & (~ new->etag_remove)) | new->etag_add;
427         conf->etag_remove =
428             (conf->opts_remove & (~ new->etag_add)) | new->etag_remove;
429         conf->etag_bits =
430             (conf->etag_bits & (~ conf->etag_remove)) | conf->etag_add;
431     }
432     else {
433         conf->etag_bits = new->etag_bits;
434         conf->etag_add = new->etag_add;
435         conf->etag_remove = new->etag_remove;
436     }
437
438     if (conf->etag_bits != ETAG_NONE) {
439         conf->etag_bits &= (~ ETAG_NONE);
440     }
441
442     if (new->enable_mmap != ENABLE_MMAP_UNSET) {
443         conf->enable_mmap = new->enable_mmap;
444     }
445
446     if (new->enable_sendfile != ENABLE_SENDFILE_UNSET) {
447         conf->enable_sendfile = new->enable_sendfile;
448     }
449
450     conf->allow_encoded_slashes = new->allow_encoded_slashes;
451     
452     return (void*)conf;
453 }
454
455 static void *create_core_server_config(apr_pool_t *a, server_rec *s)
456 {
457     core_server_config *conf;
458     int is_virtual = s->is_virtual;
459
460     conf = (core_server_config *)apr_pcalloc(a, sizeof(core_server_config));
461
462 #ifdef GPROF
463     conf->gprof_dir = NULL;
464 #endif
465
466     conf->access_name = is_virtual ? NULL : DEFAULT_ACCESS_FNAME;
467     conf->ap_document_root = is_virtual ? NULL : DOCUMENT_LOCATION;
468     conf->sec_dir = apr_array_make(a, 40, sizeof(ap_conf_vector_t *));
469     conf->sec_url = apr_array_make(a, 40, sizeof(ap_conf_vector_t *));
470
471     /* recursion stopper */
472     conf->redirect_limit = 0; /* 0 == unset */
473     conf->subreq_limit = 0;
474
475     return (void *)conf;
476 }
477
478 static void *merge_core_server_configs(apr_pool_t *p, void *basev, void *virtv)
479 {
480     core_server_config *base = (core_server_config *)basev;
481     core_server_config *virt = (core_server_config *)virtv;
482     core_server_config *conf;
483
484     conf = (core_server_config *)apr_palloc(p, sizeof(core_server_config));
485     memcpy(conf, virt, sizeof(core_server_config));
486
487     if (!conf->access_name) {
488         conf->access_name = base->access_name;
489     }
490
491     if (!conf->ap_document_root) {
492         conf->ap_document_root = base->ap_document_root;
493     }
494
495     conf->sec_dir = apr_array_append(p, base->sec_dir, virt->sec_dir);
496     conf->sec_url = apr_array_append(p, base->sec_url, virt->sec_url);
497
498     conf->redirect_limit = virt->redirect_limit
499                            ? virt->redirect_limit
500                            : base->redirect_limit;
501
502     conf->subreq_limit = virt->subreq_limit
503                          ? virt->subreq_limit
504                          : base->subreq_limit;
505
506     return conf;
507 }
508
509 /* Add per-directory configuration entry (for <directory> section);
510  * these are part of the core server config.
511  */
512
513 AP_CORE_DECLARE(void) ap_add_per_dir_conf(server_rec *s, void *dir_config)
514 {
515     core_server_config *sconf = ap_get_module_config(s->module_config,
516                                                      &core_module);
517     void **new_space = (void **)apr_array_push(sconf->sec_dir);
518
519     *new_space = dir_config;
520 }
521
522 AP_CORE_DECLARE(void) ap_add_per_url_conf(server_rec *s, void *url_config)
523 {
524     core_server_config *sconf = ap_get_module_config(s->module_config,
525                                                      &core_module);
526     void **new_space = (void **)apr_array_push(sconf->sec_url);
527
528     *new_space = url_config;
529 }
530
531 AP_CORE_DECLARE(void) ap_add_file_conf(core_dir_config *conf, void *url_config)
532 {
533     void **new_space = (void **)apr_array_push(conf->sec_file);
534
535     *new_space = url_config;
536 }
537
538 /* We need to do a stable sort, qsort isn't stable.  So to make it stable
539  * we'll be maintaining the original index into the list, and using it
540  * as the minor key during sorting.  The major key is the number of
541  * components (where the root component is zero).
542  */
543 struct reorder_sort_rec {
544     ap_conf_vector_t *elt;
545     int orig_index;
546 };
547
548 static int reorder_sorter(const void *va, const void *vb)
549 {
550     const struct reorder_sort_rec *a = va;
551     const struct reorder_sort_rec *b = vb;
552     core_dir_config *core_a;
553     core_dir_config *core_b;
554
555     core_a = ap_get_module_config(a->elt, &core_module);
556     core_b = ap_get_module_config(b->elt, &core_module);
557
558     /* a regex always sorts after a non-regex
559      */
560     if (!core_a->r && core_b->r) {
561         return -1;
562     }
563     else if (core_a->r && !core_b->r) {
564         return 1;
565     }
566
567     /* we always sort next by the number of components
568      */
569     if (core_a->d_components < core_b->d_components) {
570         return -1;
571     }
572     else if (core_a->d_components > core_b->d_components) {
573         return 1;
574     }
575
576     /* They have the same number of components, we now have to compare
577      * the minor key to maintain the original order (from the config.)
578      */
579     return a->orig_index - b->orig_index;
580 }
581
582 void ap_core_reorder_directories(apr_pool_t *p, server_rec *s)
583 {
584     core_server_config *sconf;
585     apr_array_header_t *sec_dir;
586     struct reorder_sort_rec *sortbin;
587     int nelts;
588     ap_conf_vector_t **elts;
589     int i;
590     apr_pool_t *tmp;
591
592     sconf = ap_get_module_config(s->module_config, &core_module);
593     sec_dir = sconf->sec_dir;
594     nelts = sec_dir->nelts;
595     elts = (ap_conf_vector_t **)sec_dir->elts;
596
597     if (!nelts) {
598         /* simple case of already being sorted... */
599         /* We're not checking this condition to be fast... we're checking
600          * it to avoid trying to palloc zero bytes, which can trigger some
601          * memory debuggers to barf
602          */
603         return;
604     }
605
606     /* we have to allocate tmp space to do a stable sort */
607     apr_pool_create(&tmp, p);
608     sortbin = apr_palloc(tmp, sec_dir->nelts * sizeof(*sortbin));
609     for (i = 0; i < nelts; ++i) {
610         sortbin[i].orig_index = i;
611         sortbin[i].elt = elts[i];
612     }
613
614     qsort(sortbin, nelts, sizeof(*sortbin), reorder_sorter);
615
616     /* and now copy back to the original array */
617     for (i = 0; i < nelts; ++i) {
618         elts[i] = sortbin[i].elt;
619     }
620
621     apr_pool_destroy(tmp);
622 }
623
624 /*****************************************************************
625  *
626  * There are some elements of the core config structures in which
627  * other modules have a legitimate interest (this is ugly, but necessary
628  * to preserve NCSA back-compatibility).  So, we have a bunch of accessors
629  * here...
630  */
631
632 AP_DECLARE(int) ap_allow_options(request_rec *r)
633 {
634     core_dir_config *conf =
635       (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
636
637     return conf->opts;
638 }
639
640 AP_DECLARE(int) ap_allow_overrides(request_rec *r)
641 {
642     core_dir_config *conf;
643     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
644                                                    &core_module);
645
646     return conf->override;
647 }
648
649 AP_DECLARE(const char *) ap_auth_type(request_rec *r)
650 {
651     core_dir_config *conf;
652
653     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
654                                                    &core_module);
655
656     return conf->ap_auth_type;
657 }
658
659 AP_DECLARE(const char *) ap_auth_name(request_rec *r)
660 {
661     core_dir_config *conf;
662
663     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
664                                                    &core_module);
665
666     return conf->ap_auth_name;
667 }
668
669 AP_DECLARE(const char *) ap_default_type(request_rec *r)
670 {
671     core_dir_config *conf;
672
673     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
674                                                    &core_module);
675
676     return conf->ap_default_type
677                ? conf->ap_default_type
678                : DEFAULT_CONTENT_TYPE;
679 }
680
681 AP_DECLARE(const char *) ap_document_root(request_rec *r) /* Don't use this! */
682 {
683     core_server_config *conf;
684
685     conf = (core_server_config *)ap_get_module_config(r->server->module_config,
686                                                       &core_module);
687
688     return conf->ap_document_root;
689 }
690
691 AP_DECLARE(const apr_array_header_t *) ap_requires(request_rec *r)
692 {
693     core_dir_config *conf;
694
695     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
696                                                    &core_module);
697
698     return conf->ap_requires;
699 }
700
701 AP_DECLARE(int) ap_satisfies(request_rec *r)
702 {
703     core_dir_config *conf;
704
705     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
706                                                    &core_module);
707
708     return conf->satisfy;
709 }
710
711 /* Should probably just get rid of this... the only code that cares is
712  * part of the core anyway (and in fact, it isn't publicised to other
713  * modules).
714  */
715
716 char *ap_response_code_string(request_rec *r, int error_index)
717 {
718     core_dir_config *conf;
719
720     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
721                                                    &core_module);
722
723     if (conf->response_code_strings == NULL) {
724         return NULL;
725     }
726
727     return conf->response_code_strings[error_index];
728 }
729
730
731 /* Code from Harald Hanche-Olsen <hanche@imf.unit.no> */
732 static APR_INLINE void do_double_reverse (conn_rec *conn)
733 {
734     apr_sockaddr_t *sa;
735     apr_status_t rv;
736
737     if (conn->double_reverse) {
738         /* already done */
739         return;
740     }
741
742     if (conn->remote_host == NULL || conn->remote_host[0] == '\0') {
743         /* single reverse failed, so don't bother */
744         conn->double_reverse = -1;
745         return;
746     }
747
748     rv = apr_sockaddr_info_get(&sa, conn->remote_host, APR_UNSPEC, 0, 0, conn->pool);
749     if (rv == APR_SUCCESS) {
750         while (sa) {
751             if (apr_sockaddr_equal(sa, conn->remote_addr)) {
752                 conn->double_reverse = 1;
753                 return;
754             }
755
756             sa = sa->next;
757         }
758     }
759
760     conn->double_reverse = -1;
761 }
762
763 AP_DECLARE(const char *) ap_get_remote_host(conn_rec *conn, void *dir_config,
764                                             int type, int *str_is_ip)
765 {
766     int hostname_lookups;
767
768     if (str_is_ip) { /* if caller wants to know */
769         *str_is_ip = 0;
770     }
771
772     /* If we haven't checked the host name, and we want to */
773     if (dir_config) {
774         hostname_lookups =
775             ((core_dir_config *)ap_get_module_config(dir_config, &core_module))
776             ->hostname_lookups;
777
778         if (hostname_lookups == HOSTNAME_LOOKUP_UNSET) {
779             hostname_lookups = HOSTNAME_LOOKUP_OFF;
780         }
781     }
782     else {
783         /* the default */
784         hostname_lookups = HOSTNAME_LOOKUP_OFF;
785     }
786
787     if (type != REMOTE_NOLOOKUP
788         && conn->remote_host == NULL
789         && (type == REMOTE_DOUBLE_REV
790         || hostname_lookups != HOSTNAME_LOOKUP_OFF)) {
791
792         if (apr_getnameinfo(&conn->remote_host, conn->remote_addr, 0)
793             == APR_SUCCESS) {
794             ap_str_tolower(conn->remote_host);
795
796             if (hostname_lookups == HOSTNAME_LOOKUP_DOUBLE) {
797                 do_double_reverse(conn);
798                 if (conn->double_reverse != 1) {
799                     conn->remote_host = NULL;
800                 }
801             }
802         }
803
804         /* if failed, set it to the NULL string to indicate error */
805         if (conn->remote_host == NULL) {
806             conn->remote_host = "";
807         }
808     }
809
810     if (type == REMOTE_DOUBLE_REV) {
811         do_double_reverse(conn);
812         if (conn->double_reverse == -1) {
813             return NULL;
814         }
815     }
816
817     /*
818      * Return the desired information; either the remote DNS name, if found,
819      * or either NULL (if the hostname was requested) or the IP address
820      * (if any identifier was requested).
821      */
822     if (conn->remote_host != NULL && conn->remote_host[0] != '\0') {
823         return conn->remote_host;
824     }
825     else {
826         if (type == REMOTE_HOST || type == REMOTE_DOUBLE_REV) {
827             return NULL;
828         }
829         else {
830             if (str_is_ip) { /* if caller wants to know */
831                 *str_is_ip = 1;
832             }
833
834             return conn->remote_ip;
835         }
836     }
837 }
838
839 /*
840  * Optional function coming from mod_ident, used for looking up ident user
841  */
842 static APR_OPTIONAL_FN_TYPE(ap_ident_lookup) *ident_lookup;
843
844 AP_DECLARE(const char *) ap_get_remote_logname(request_rec *r)
845 {
846     if (r->connection->remote_logname != NULL) {
847         return r->connection->remote_logname;
848     }
849
850     if (ident_lookup) {
851         return ident_lookup(r);
852     }
853
854     return NULL;
855 }
856
857 /* There are two options regarding what the "name" of a server is.  The
858  * "canonical" name as defined by ServerName and Port, or the "client's
859  * name" as supplied by a possible Host: header or full URI.  We never
860  * trust the port passed in the client's headers, we always use the
861  * port of the actual socket.
862  *
863  * The DNS option to UseCanonicalName causes this routine to do a
864  * reverse lookup on the local IP address of the connection and use
865  * that for the ServerName. This makes its value more reliable while
866  * at the same time allowing Demon's magic virtual hosting to work.
867  * The assumption is that DNS lookups are sufficiently quick...
868  * -- fanf 1998-10-03
869  */
870 AP_DECLARE(const char *) ap_get_server_name(request_rec *r)
871 {
872     conn_rec *conn = r->connection;
873     core_dir_config *d;
874
875     d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
876                                                 &core_module);
877
878     if (d->use_canonical_name == USE_CANONICAL_NAME_OFF) {
879         return r->hostname ? r->hostname : r->server->server_hostname;
880     }
881
882     if (d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
883         if (conn->local_host == NULL) {
884             if (apr_getnameinfo(&conn->local_host,
885                                 conn->local_addr, 0) != APR_SUCCESS)
886                 conn->local_host = apr_pstrdup(conn->pool,
887                                                r->server->server_hostname);
888             else {
889                 ap_str_tolower(conn->local_host);
890             }
891         }
892
893         return conn->local_host;
894     }
895
896     /* default */
897     return r->server->server_hostname;
898 }
899
900 /*
901  * Get the current server name from the request for the purposes
902  * of using in a URL.  If the server name is an IPv6 literal
903  * address, it will be returned in URL format (e.g., "[fe80::1]").
904  */
905 static const char *get_server_name_for_url(request_rec *r)
906 {
907     const char *plain_server_name = ap_get_server_name(r);
908
909 #if APR_HAVE_IPV6
910     if (ap_strchr_c(plain_server_name, ':')) { /* IPv6 literal? */
911         return apr_psprintf(r->pool, "[%s]", plain_server_name);
912     }
913 #endif
914     return plain_server_name;
915 }
916
917 AP_DECLARE(apr_port_t) ap_get_server_port(const request_rec *r)
918 {
919     apr_port_t port;
920     core_dir_config *d =
921       (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
922
923     if (d->use_canonical_name == USE_CANONICAL_NAME_OFF
924         || d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
925
926         /* With UseCanonicalName off Apache will form self-referential
927          * URLs using the hostname and port supplied by the client if
928          * any are supplied (otherwise it will use the canonical name).
929          */
930         port = r->parsed_uri.port ? r->parsed_uri.port :
931                r->server->port ? r->server->port :
932                ap_default_port(r);
933     }
934     else { /* d->use_canonical_name == USE_CANONICAL_NAME_ON */
935
936         /* With UseCanonicalName on (and in all versions prior to 1.3)
937          * Apache will use the hostname and port specified in the
938          * ServerName directive to construct a canonical name for the
939          * server. (If no port was specified in the ServerName
940          * directive, Apache uses the port supplied by the client if
941          * any is supplied, and finally the default port for the protocol
942          * used.
943          */
944         port = r->server->port ? r->server->port :
945                r->connection->local_addr->port ? r->connection->local_addr->port :
946                ap_default_port(r);
947     }
948
949     /* default */
950     return port;
951 }
952
953 AP_DECLARE(char *) ap_construct_url(apr_pool_t *p, const char *uri,
954                                     request_rec *r)
955 {
956     unsigned port = ap_get_server_port(r);
957     const char *host = get_server_name_for_url(r);
958
959     if (ap_is_default_port(port, r)) {
960         return apr_pstrcat(p, ap_http_method(r), "://", host, uri, NULL);
961     }
962
963     return apr_psprintf(p, "%s://%s:%u%s", ap_http_method(r), host, port, uri);
964 }
965
966 AP_DECLARE(apr_off_t) ap_get_limit_req_body(const request_rec *r)
967 {
968     core_dir_config *d =
969       (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
970
971     return d->limit_req_body;
972 }
973
974
975 /*****************************************************************
976  *
977  * Commands... this module handles almost all of the NCSA httpd.conf
978  * commands, but most of the old srm.conf is in the the modules.
979  */
980
981
982 /* returns a parent if it matches the given directive */
983 static const ap_directive_t * find_parent(const ap_directive_t *dirp,
984                                           const char *what)
985 {
986     while (dirp->parent != NULL) {
987         dirp = dirp->parent;
988
989         /* ### it would be nice to have atom-ized directives */
990         if (strcasecmp(dirp->directive, what) == 0)
991             return dirp;
992     }
993
994     return NULL;
995 }
996
997 AP_DECLARE(const char *) ap_check_cmd_context(cmd_parms *cmd,
998                                               unsigned forbidden)
999 {
1000     const char *gt = (cmd->cmd->name[0] == '<'
1001                       && cmd->cmd->name[strlen(cmd->cmd->name)-1] != '>')
1002                          ? ">" : "";
1003     const ap_directive_t *found;
1004
1005     if ((forbidden & NOT_IN_VIRTUALHOST) && cmd->server->is_virtual) {
1006         return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1007                            " cannot occur within <VirtualHost> section", NULL);
1008     }
1009
1010     if ((forbidden & NOT_IN_LIMIT) && cmd->limited != -1) {
1011         return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1012                            " cannot occur within <Limit> section", NULL);
1013     }
1014
1015     if ((forbidden & NOT_IN_DIR_LOC_FILE) == NOT_IN_DIR_LOC_FILE) {
1016         if (cmd->path != NULL) {
1017             return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1018                             " cannot occur within <Directory/Location/Files> "
1019                             "section", NULL);
1020         }
1021         if (cmd->cmd->req_override & EXEC_ON_READ) {
1022             /* EXEC_ON_READ must be NOT_IN_DIR_LOC_FILE, if not, it will
1023              * (deliberately) segfault below in the individual tests...
1024              */
1025             return NULL;
1026         }
1027     }
1028     
1029     if (((forbidden & NOT_IN_DIRECTORY)
1030          && ((found = find_parent(cmd->directive, "<Directory"))
1031              || (found = find_parent(cmd->directive, "<DirectoryMatch"))))
1032         || ((forbidden & NOT_IN_LOCATION)
1033             && ((found = find_parent(cmd->directive, "<Location"))
1034                 || (found = find_parent(cmd->directive, "<LocationMatch"))))
1035         || ((forbidden & NOT_IN_FILES)
1036             && ((found = find_parent(cmd->directive, "<Files"))
1037                 || (found = find_parent(cmd->directive, "<FilesMatch"))))) {
1038         return apr_pstrcat(cmd->pool, cmd->cmd->name, gt,
1039                            " cannot occur within ", found->directive,
1040                            "> section", NULL);
1041     }
1042
1043     return NULL;
1044 }
1045
1046 static const char *set_access_name(cmd_parms *cmd, void *dummy,
1047                                    const char *arg)
1048 {
1049     void *sconf = cmd->server->module_config;
1050     core_server_config *conf = ap_get_module_config(sconf, &core_module);
1051
1052     const char *err = ap_check_cmd_context(cmd,
1053                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1054     if (err != NULL) {
1055         return err;
1056     }
1057
1058     conf->access_name = apr_pstrdup(cmd->pool, arg);
1059     return NULL;
1060 }
1061
1062 #ifdef GPROF
1063 static const char *set_gprof_dir(cmd_parms *cmd, void *dummy, const char *arg)
1064 {
1065     void *sconf = cmd->server->module_config;
1066     core_server_config *conf = ap_get_module_config(sconf, &core_module);
1067
1068     const char *err = ap_check_cmd_context(cmd,
1069                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1070     if (err != NULL) {
1071         return err;
1072     }
1073
1074     conf->gprof_dir = apr_pstrdup(cmd->pool, arg);
1075     return NULL;
1076 }
1077 #endif /*GPROF*/
1078
1079 static const char *set_add_default_charset(cmd_parms *cmd,
1080                                            void *d_, const char *arg)
1081 {
1082     core_dir_config *d = d_;
1083
1084     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1085     if (err != NULL) {
1086         return err;
1087     }
1088
1089     if (!strcasecmp(arg, "Off")) {
1090        d->add_default_charset = ADD_DEFAULT_CHARSET_OFF;
1091     }
1092     else if (!strcasecmp(arg, "On")) {
1093        d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1094        d->add_default_charset_name = DEFAULT_ADD_DEFAULT_CHARSET_NAME;
1095     }
1096     else {
1097        d->add_default_charset = ADD_DEFAULT_CHARSET_ON;
1098        d->add_default_charset_name = arg;
1099     }
1100
1101     return NULL;
1102 }
1103
1104 static const char *set_document_root(cmd_parms *cmd, void *dummy,
1105                                      const char *arg)
1106 {
1107     void *sconf = cmd->server->module_config;
1108     core_server_config *conf = ap_get_module_config(sconf, &core_module);
1109
1110     const char *err = ap_check_cmd_context(cmd,
1111                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1112     if (err != NULL) {
1113         return err;
1114     }
1115
1116     /* Make it absolute, relative to ServerRoot */
1117     arg = ap_server_root_relative(cmd->pool, arg);
1118
1119     /* TODO: ap_configtestonly && ap_docrootcheck && */
1120     if (apr_filepath_merge((char**)&conf->ap_document_root, NULL, arg,
1121                            APR_FILEPATH_TRUENAME, cmd->pool) != APR_SUCCESS
1122         || !ap_is_directory(cmd->pool, arg)) {
1123         if (cmd->server->is_virtual) {
1124             ap_log_perror(APLOG_MARK, APLOG_STARTUP, 0,
1125                           cmd->pool,
1126                           "Warning: DocumentRoot [%s] does not exist",
1127                           arg);
1128             conf->ap_document_root = arg;
1129         }
1130         else {
1131             return "DocumentRoot must be a directory";
1132         }
1133     }
1134     return NULL;
1135 }
1136
1137 AP_DECLARE(void) ap_custom_response(request_rec *r, int status,
1138                                     const char *string)
1139 {
1140     core_dir_config *conf =
1141         ap_get_module_config(r->per_dir_config, &core_module);
1142     int idx;
1143
1144     if(conf->response_code_strings == NULL) {
1145         conf->response_code_strings =
1146             apr_pcalloc(r->pool,
1147                         sizeof(*conf->response_code_strings) * RESPONSE_CODES);
1148     }
1149
1150     idx = ap_index_of_response(status);
1151
1152     conf->response_code_strings[idx] =
1153        ((ap_is_url(string) || (*string == '/')) && (*string != '"')) ?
1154        apr_pstrdup(r->pool, string) : apr_pstrcat(r->pool, "\"", string, NULL);
1155 }
1156
1157 static const char *set_error_document(cmd_parms *cmd, void *conf_,
1158                                       const char *errno_str, const char *msg)
1159 {
1160     core_dir_config *conf = conf_;
1161     int error_number, index_number, idx500;
1162     enum { MSG, LOCAL_PATH, REMOTE_PATH } what = MSG;
1163
1164     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1165     if (err != NULL) {
1166         return err;
1167     }
1168
1169     /* 1st parameter should be a 3 digit number, which we recognize;
1170      * convert it into an array index
1171      */
1172     error_number = atoi(errno_str);
1173     idx500 = ap_index_of_response(HTTP_INTERNAL_SERVER_ERROR);
1174
1175     if (error_number == HTTP_INTERNAL_SERVER_ERROR) {
1176         index_number = idx500;
1177     }
1178     else if ((index_number = ap_index_of_response(error_number)) == idx500) {
1179         return apr_pstrcat(cmd->pool, "Unsupported HTTP response code ",
1180                            errno_str, NULL);
1181     }
1182
1183     /* Heuristic to determine second argument. */
1184     if (ap_strchr_c(msg,' '))
1185         what = MSG;
1186     else if (msg[0] == '/')
1187         what = LOCAL_PATH;
1188     else if (ap_is_url(msg))
1189         what = REMOTE_PATH;
1190     else
1191         what = MSG;
1192
1193     /* The entry should be ignored if it is a full URL for a 401 error */
1194
1195     if (error_number == 401 && what == REMOTE_PATH) {
1196         ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, cmd->server,
1197                      "cannot use a full URL in a 401 ErrorDocument "
1198                      "directive --- ignoring!");
1199     }
1200     else { /* Store it... */
1201         if (conf->response_code_strings == NULL) {
1202             conf->response_code_strings =
1203                 apr_pcalloc(cmd->pool,
1204                             sizeof(*conf->response_code_strings) *
1205                             RESPONSE_CODES);
1206         }
1207
1208         /* hack. Prefix a " if it is a msg; as that is what
1209          * http_protocol.c relies on to distinguish between
1210          * a msg and a (local) path.
1211          */
1212         conf->response_code_strings[index_number] = (what == MSG) ?
1213                 apr_pstrcat(cmd->pool, "\"",msg,NULL) :
1214                 apr_pstrdup(cmd->pool, msg);
1215     }
1216
1217     return NULL;
1218 }
1219
1220 static const char *set_override(cmd_parms *cmd, void *d_, const char *l)
1221 {
1222     core_dir_config *d = d_;
1223     char *w;
1224
1225     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1226     if (err != NULL) {
1227         return err;
1228     }
1229
1230     /* Throw a warning if we're in <Location> or <Files> */
1231     if (ap_check_cmd_context(cmd, NOT_IN_LOCATION | NOT_IN_FILES)) {
1232         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
1233                      "Useless use of AllowOverride in line %d.",
1234                      cmd->directive->line_num);
1235     }
1236
1237     d->override = OR_NONE;
1238     while (l[0]) {
1239         w = ap_getword_conf(cmd->pool, &l);
1240         if (!strcasecmp(w, "Limit")) {
1241             d->override |= OR_LIMIT;
1242         }
1243         else if (!strcasecmp(w, "Options")) {
1244             d->override |= OR_OPTIONS;
1245         }
1246         else if (!strcasecmp(w, "FileInfo")) {
1247             d->override |= OR_FILEINFO;
1248         }
1249         else if (!strcasecmp(w, "AuthConfig")) {
1250             d->override |= OR_AUTHCFG;
1251         }
1252         else if (!strcasecmp(w, "Indexes")) {
1253             d->override |= OR_INDEXES;
1254         }
1255         else if (!strcasecmp(w, "None")) {
1256             d->override = OR_NONE;
1257         }
1258         else if (!strcasecmp(w, "All")) {
1259             d->override = OR_ALL;
1260         }
1261         else {
1262             return apr_pstrcat(cmd->pool, "Illegal override option ", w, NULL);
1263         }
1264
1265         d->override &= ~OR_UNSET;
1266     }
1267
1268     return NULL;
1269 }
1270
1271 static const char *set_options(cmd_parms *cmd, void *d_, const char *l)
1272 {
1273     core_dir_config *d = d_;
1274     allow_options_t opt;
1275     int first = 1;
1276     char action;
1277
1278     while (l[0]) {
1279         char *w = ap_getword_conf(cmd->pool, &l);
1280         action = '\0';
1281
1282         if (*w == '+' || *w == '-') {
1283             action = *(w++);
1284         }
1285         else if (first) {
1286               d->opts = OPT_NONE;
1287             first = 0;
1288         }
1289
1290         if (!strcasecmp(w, "Indexes")) {
1291             opt = OPT_INDEXES;
1292         }
1293         else if (!strcasecmp(w, "Includes")) {
1294             opt = OPT_INCLUDES;
1295         }
1296         else if (!strcasecmp(w, "IncludesNOEXEC")) {
1297             opt = (OPT_INCLUDES | OPT_INCNOEXEC);
1298         }
1299         else if (!strcasecmp(w, "FollowSymLinks")) {
1300             opt = OPT_SYM_LINKS;
1301         }
1302         else if (!strcasecmp(w, "SymLinksIfOwnerMatch")) {
1303             opt = OPT_SYM_OWNER;
1304         }
1305         else if (!strcasecmp(w, "execCGI")) {
1306             opt = OPT_EXECCGI;
1307         }
1308         else if (!strcasecmp(w, "MultiViews")) {
1309             opt = OPT_MULTI;
1310         }
1311         else if (!strcasecmp(w, "RunScripts")) { /* AI backcompat. Yuck */
1312             opt = OPT_MULTI|OPT_EXECCGI;
1313         }
1314         else if (!strcasecmp(w, "None")) {
1315             opt = OPT_NONE;
1316         }
1317         else if (!strcasecmp(w, "All")) {
1318             opt = OPT_ALL;
1319         }
1320         else {
1321             return apr_pstrcat(cmd->pool, "Illegal option ", w, NULL);
1322         }
1323
1324         /* we ensure the invariant (d->opts_add & d->opts_remove) == 0 */
1325         if (action == '-') {
1326             d->opts_remove |= opt;
1327             d->opts_add &= ~opt;
1328             d->opts &= ~opt;
1329         }
1330         else if (action == '+') {
1331             d->opts_add |= opt;
1332             d->opts_remove &= ~opt;
1333             d->opts |= opt;
1334         }
1335         else {
1336             d->opts |= opt;
1337         }
1338     }
1339
1340     return NULL;
1341 }
1342
1343 /*
1344  * Note what data should be used when forming file ETag values.
1345  * It would be nicer to do this as an ITERATE, but then we couldn't
1346  * remember the +/- state properly.
1347  */
1348 static const char *set_etag_bits(cmd_parms *cmd, void *mconfig,
1349                                  const char *args_p)
1350 {
1351     core_dir_config *cfg;
1352     etag_components_t bit;
1353     char action;
1354     char *token;
1355     const char *args;
1356     int valid;
1357     int first;
1358     int explicit;
1359
1360     cfg = (core_dir_config *)mconfig;
1361
1362     args = args_p;
1363     first = 1;
1364     explicit = 0;
1365     while (args[0] != '\0') {
1366         action = '*';
1367         bit = ETAG_UNSET;
1368         valid = 1;
1369         token = ap_getword_conf(cmd->pool, &args);
1370         if ((*token == '+') || (*token == '-')) {
1371             action = *token;
1372             token++;
1373         }
1374         else {
1375             /*
1376              * The occurrence of an absolute setting wipes
1377              * out any previous relative ones.  The first such
1378              * occurrence forgets any inherited ones, too.
1379              */
1380             if (first) {
1381                 cfg->etag_bits = ETAG_UNSET;
1382                 cfg->etag_add = ETAG_UNSET;
1383                 cfg->etag_remove = ETAG_UNSET;
1384                 first = 0;
1385             }
1386         }
1387
1388         if (strcasecmp(token, "None") == 0) {
1389             if (action != '*') {
1390                 valid = 0;
1391             }
1392             else {
1393                 cfg->etag_bits = bit = ETAG_NONE;
1394                 explicit = 1;
1395             }
1396         }
1397         else if (strcasecmp(token, "All") == 0) {
1398             if (action != '*') {
1399                 valid = 0;
1400             }
1401             else {
1402                 explicit = 1;
1403                 cfg->etag_bits = bit = ETAG_ALL;
1404             }
1405         }
1406         else if (strcasecmp(token, "Size") == 0) {
1407             bit = ETAG_SIZE;
1408         }
1409         else if ((strcasecmp(token, "LMTime") == 0)
1410                  || (strcasecmp(token, "MTime") == 0)
1411                  || (strcasecmp(token, "LastModified") == 0)) {
1412             bit = ETAG_MTIME;
1413         }
1414         else if (strcasecmp(token, "INode") == 0) {
1415             bit = ETAG_INODE;
1416         }
1417         else {
1418             return apr_pstrcat(cmd->pool, "Unknown keyword '",
1419                                token, "' for ", cmd->cmd->name,
1420                                " directive", NULL);
1421         }
1422
1423         if (! valid) {
1424             return apr_pstrcat(cmd->pool, cmd->cmd->name, " keyword '",
1425                                token, "' cannot be used with '+' or '-'",
1426                                NULL);
1427         }
1428
1429         if (action == '+') {
1430             /*
1431              * Make sure it's in the 'add' list and absent from the
1432              * 'subtract' list.
1433              */
1434             cfg->etag_add |= bit;
1435             cfg->etag_remove &= (~ bit);
1436         }
1437         else if (action == '-') {
1438             cfg->etag_remove |= bit;
1439             cfg->etag_add &= (~ bit);
1440         }
1441         else {
1442             /*
1443              * Non-relative values wipe out any + or - values
1444              * accumulated so far.
1445              */
1446             cfg->etag_bits |= bit;
1447             cfg->etag_add = ETAG_UNSET;
1448             cfg->etag_remove = ETAG_UNSET;
1449             explicit = 1;
1450         }
1451     }
1452
1453     /*
1454      * Any setting at all will clear the 'None' and 'Unset' bits.
1455      */
1456
1457     if (cfg->etag_add != ETAG_UNSET) {
1458         cfg->etag_add &= (~ ETAG_UNSET);
1459     }
1460
1461     if (cfg->etag_remove != ETAG_UNSET) {
1462         cfg->etag_remove &= (~ ETAG_UNSET);
1463     }
1464
1465     if (explicit) {
1466         cfg->etag_bits &= (~ ETAG_UNSET);
1467
1468         if ((cfg->etag_bits & ETAG_NONE) != ETAG_NONE) {
1469             cfg->etag_bits &= (~ ETAG_NONE);
1470         }
1471     }
1472
1473     return NULL;
1474 }
1475
1476 static const char *set_enable_mmap(cmd_parms *cmd, void *d_,
1477                                    const char *arg)
1478 {
1479     core_dir_config *d = d_;
1480     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1481
1482     if (err != NULL) {
1483         return err;
1484     }
1485
1486     if (strcasecmp(arg, "on") == 0) {
1487         d->enable_mmap = ENABLE_MMAP_ON;
1488     }
1489     else if (strcasecmp(arg, "off") == 0) {
1490         d->enable_mmap = ENABLE_MMAP_OFF;
1491     }
1492     else {
1493         return "parameter must be 'on' or 'off'";
1494     }
1495
1496     return NULL;
1497 }
1498
1499 static const char *set_enable_sendfile(cmd_parms *cmd, void *d_,
1500                                    const char *arg)
1501 {
1502     core_dir_config *d = d_;
1503     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1504
1505     if (err != NULL) {
1506         return err;
1507     }
1508
1509     if (strcasecmp(arg, "on") == 0) {
1510         d->enable_sendfile = ENABLE_SENDFILE_ON;
1511     }
1512     else if (strcasecmp(arg, "off") == 0) {
1513         d->enable_sendfile = ENABLE_SENDFILE_OFF;
1514     }
1515     else {
1516         return "parameter must be 'on' or 'off'";
1517     }
1518
1519     return NULL;
1520 }
1521
1522 static const char *satisfy(cmd_parms *cmd, void *c_, const char *arg)
1523 {
1524     core_dir_config *c = c_;
1525
1526     if (!strcasecmp(arg, "all")) {
1527         c->satisfy = SATISFY_ALL;
1528     }
1529     else if (!strcasecmp(arg, "any")) {
1530         c->satisfy = SATISFY_ANY;
1531     }
1532     else {
1533         return "Satisfy either 'any' or 'all'.";
1534     }
1535
1536     return NULL;
1537 }
1538
1539 static const char *require(cmd_parms *cmd, void *c_, const char *arg)
1540 {
1541     require_line *r;
1542     core_dir_config *c = c_;
1543
1544     if (!c->ap_requires) {
1545         c->ap_requires = apr_array_make(cmd->pool, 2, sizeof(require_line));
1546     }
1547
1548     r = (require_line *)apr_array_push(c->ap_requires);
1549     r->requirement = apr_pstrdup(cmd->pool, arg);
1550     r->method_mask = cmd->limited;
1551
1552     return NULL;
1553 }
1554
1555 AP_CORE_DECLARE_NONSTD(const char *) ap_limit_section(cmd_parms *cmd,
1556                                                       void *dummy,
1557                                                       const char *arg)
1558 {
1559     const char *limited_methods = ap_getword(cmd->pool, &arg, '>');
1560     void *tog = cmd->cmd->cmd_data;
1561     apr_int64_t limited = 0;
1562     const char *errmsg;
1563
1564     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1565     if (err != NULL) {
1566         return err;
1567     }
1568
1569     while (limited_methods[0]) {
1570         char *method = ap_getword_conf(cmd->pool, &limited_methods);
1571         int methnum;
1572
1573         /* check for builtin or module registered method number */
1574         methnum = ap_method_number_of(method);
1575
1576         if (methnum == M_TRACE && !tog) {
1577             return "TRACE cannot be controlled by <Limit>";
1578         }
1579         else if (methnum == M_INVALID) {
1580             /* method has not been registered yet, but resorce restriction
1581              * is always checked before method handling, so register it.
1582              */
1583             methnum = ap_method_register(cmd->pool, method);
1584         }
1585
1586         limited |= (AP_METHOD_BIT << methnum);
1587     }
1588
1589     /* Killing two features with one function,
1590      * if (tog == NULL) <Limit>, else <LimitExcept>
1591      */
1592     cmd->limited = tog ? ~limited : limited;
1593
1594     errmsg = ap_walk_config(cmd->directive->first_child, cmd, cmd->context);
1595
1596     cmd->limited = -1;
1597
1598     return errmsg;
1599 }
1600
1601 /* XXX: Bogus - need to do this differently (at least OS2/Netware suffer
1602  * the same problem!!!
1603  * We use this in <DirectoryMatch> and <FilesMatch>, to ensure that
1604  * people don't get bitten by wrong-cased regex matches
1605  */
1606
1607 #ifdef WIN32
1608 #define USE_ICASE REG_ICASE
1609 #else
1610 #define USE_ICASE 0
1611 #endif
1612
1613 /*
1614  * Report a missing-'>' syntax error.
1615  */
1616 static char *unclosed_directive(cmd_parms *cmd)
1617 {
1618     return apr_pstrcat(cmd->pool, cmd->cmd->name,
1619                        "> directive missing closing '>'", NULL);
1620 }
1621
1622 static const char *dirsection(cmd_parms *cmd, void *mconfig, const char *arg)
1623 {
1624     const char *errmsg;
1625     const char *endp = ap_strrchr_c(arg, '>');
1626     int old_overrides = cmd->override;
1627     char *old_path = cmd->path;
1628     core_dir_config *conf;
1629     ap_conf_vector_t *new_dir_conf = ap_create_per_dir_config(cmd->pool);
1630     regex_t *r = NULL;
1631     const command_rec *thiscmd = cmd->cmd;
1632
1633     const char *err = ap_check_cmd_context(cmd,
1634                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1635     if (err != NULL) {
1636         return err;
1637     }
1638
1639     if (endp == NULL) {
1640         return unclosed_directive(cmd);
1641     }
1642
1643     arg = apr_pstrndup(cmd->pool, arg, endp - arg);
1644
1645     if (!arg) {
1646         if (thiscmd->cmd_data)
1647             return "<DirectoryMatch > block must specify a path";
1648         else
1649             return "<Directory > block must specify a path";
1650     }
1651
1652     cmd->path = ap_getword_conf(cmd->pool, &arg);
1653     cmd->override = OR_ALL|ACCESS_CONF;
1654
1655     if (!strcmp(cmd->path, "~")) {
1656         cmd->path = ap_getword_conf(cmd->pool, &arg);
1657         if (!cmd->path)
1658             return "<Directory ~ > block must specify a path";
1659         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1660     }
1661     else if (thiscmd->cmd_data) { /* <DirectoryMatch> */
1662         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1663     }
1664     else if (!strcmp(cmd->path, "/") == 0)
1665     {
1666         char *newpath;
1667
1668         /*
1669          * Ensure that the pathname is canonical, and append the trailing /
1670          */
1671         apr_status_t rv = apr_filepath_merge(&newpath, NULL, cmd->path,
1672                                              APR_FILEPATH_TRUENAME, cmd->pool);
1673         if (rv != APR_SUCCESS && rv != APR_EPATHWILD) {
1674             return apr_pstrcat(cmd->pool, "<Directory \"", cmd->path,
1675                                "\"> path is invalid.", NULL);
1676         }
1677
1678         cmd->path = newpath;
1679         if (cmd->path[strlen(cmd->path) - 1] != '/')
1680             cmd->path = apr_pstrcat(cmd->pool, cmd->path, "/", NULL);
1681     }
1682
1683     /* initialize our config and fetch it */
1684     conf = ap_set_config_vectors(cmd->server, new_dir_conf, cmd->path,
1685                                  &core_module, cmd->pool);
1686
1687     errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_dir_conf);
1688     if (errmsg != NULL)
1689         return errmsg;
1690
1691     conf->r = r;
1692     conf->d = cmd->path;
1693     conf->d_is_fnmatch = (apr_fnmatch_test(conf->d) != 0);
1694
1695     /* Make this explicit - the "/" root has 0 elements, that is, we
1696      * will always merge it, and it will always sort and merge first.
1697      * All others are sorted and tested by the number of slashes.
1698      */
1699     if (strcmp(conf->d, "/") == 0)
1700         conf->d_components = 0;
1701     else
1702         conf->d_components = ap_count_dirs(conf->d);
1703
1704     ap_add_per_dir_conf(cmd->server, new_dir_conf);
1705
1706     if (*arg != '\0') {
1707         return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1708                            "> arguments not (yet) supported.", NULL);
1709     }
1710
1711     cmd->path = old_path;
1712     cmd->override = old_overrides;
1713
1714     return NULL;
1715 }
1716
1717 static const char *urlsection(cmd_parms *cmd, void *mconfig, const char *arg)
1718 {
1719     const char *errmsg;
1720     const char *endp = ap_strrchr_c(arg, '>');
1721     int old_overrides = cmd->override;
1722     char *old_path = cmd->path;
1723     core_dir_config *conf;
1724     regex_t *r = NULL;
1725     const command_rec *thiscmd = cmd->cmd;
1726     ap_conf_vector_t *new_url_conf = ap_create_per_dir_config(cmd->pool);
1727     const char *err = ap_check_cmd_context(cmd,
1728                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1729     if (err != NULL) {
1730         return err;
1731     }
1732
1733     if (endp == NULL) {
1734         return unclosed_directive(cmd);
1735     }
1736
1737     arg = apr_pstrndup(cmd->pool, arg, endp - arg);
1738
1739     cmd->path = ap_getword_conf(cmd->pool, &arg);
1740     cmd->override = OR_ALL|ACCESS_CONF;
1741
1742     if (thiscmd->cmd_data) { /* <LocationMatch> */
1743         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1744     }
1745     else if (!strcmp(cmd->path, "~")) {
1746         cmd->path = ap_getword_conf(cmd->pool, &arg);
1747         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1748     }
1749
1750     /* initialize our config and fetch it */
1751     conf = ap_set_config_vectors(cmd->server, new_url_conf, cmd->path,
1752                                  &core_module, cmd->pool);
1753
1754     errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_url_conf);
1755     if (errmsg != NULL)
1756         return errmsg;
1757
1758     conf->d = apr_pstrdup(cmd->pool, cmd->path);     /* No mangling, please */
1759     conf->d_is_fnmatch = apr_fnmatch_test(conf->d) != 0;
1760     conf->r = r;
1761
1762     ap_add_per_url_conf(cmd->server, new_url_conf);
1763
1764     if (*arg != '\0') {
1765         return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1766                            "> arguments not (yet) supported.", NULL);
1767     }
1768
1769     cmd->path = old_path;
1770     cmd->override = old_overrides;
1771
1772     return NULL;
1773 }
1774
1775 static const char *filesection(cmd_parms *cmd, void *mconfig, const char *arg)
1776 {
1777     const char *errmsg;
1778     const char *endp = ap_strrchr_c(arg, '>');
1779     int old_overrides = cmd->override;
1780     char *old_path = cmd->path;
1781     core_dir_config *conf;
1782     regex_t *r = NULL;
1783     const command_rec *thiscmd = cmd->cmd;
1784     core_dir_config *c = mconfig;
1785     ap_conf_vector_t *new_file_conf = ap_create_per_dir_config(cmd->pool);
1786     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT|NOT_IN_LOCATION);
1787
1788     if (err != NULL) {
1789         return err;
1790     }
1791
1792     if (endp == NULL) {
1793         return unclosed_directive(cmd);
1794     }
1795
1796     arg = apr_pstrndup(cmd->pool, arg, endp - arg);
1797
1798     cmd->path = ap_getword_conf(cmd->pool, &arg);
1799     /* Only if not an .htaccess file */
1800     if (!old_path) {
1801         cmd->override = OR_ALL|ACCESS_CONF;
1802     }
1803
1804     if (thiscmd->cmd_data) { /* <FilesMatch> */
1805         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1806     }
1807     else if (!strcmp(cmd->path, "~")) {
1808         cmd->path = ap_getword_conf(cmd->pool, &arg);
1809         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1810     }
1811     else {
1812         char *newpath;
1813         /* Ensure that the pathname is canonical, but we
1814          * can't test the case/aliases without a fixed path */
1815         if (apr_filepath_merge(&newpath, "", cmd->path,
1816                                0, cmd->pool) != APR_SUCCESS)
1817                 return apr_pstrcat(cmd->pool, "<Files \"", cmd->path,
1818                                "\"> is invalid.", NULL);
1819         cmd->path = newpath;
1820     }
1821
1822     /* initialize our config and fetch it */
1823     conf = ap_set_config_vectors(cmd->server, new_file_conf, cmd->path,
1824                                  &core_module, cmd->pool);
1825
1826     errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_file_conf);
1827     if (errmsg != NULL)
1828         return errmsg;
1829
1830     conf->d = cmd->path;
1831     conf->d_is_fnmatch = apr_fnmatch_test(conf->d) != 0;
1832     conf->r = r;
1833
1834     ap_add_file_conf(c, new_file_conf);
1835
1836     if (*arg != '\0') {
1837         return apr_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1838                            "> arguments not (yet) supported.", NULL);
1839     }
1840
1841     cmd->path = old_path;
1842     cmd->override = old_overrides;
1843
1844     return NULL;
1845 }
1846
1847 static const char *start_ifmod(cmd_parms *cmd, void *mconfig, const char *arg)
1848 {
1849     const char *endp = ap_strrchr_c(arg, '>');
1850     int not = (arg[0] == '!');
1851     module *found;
1852
1853     if (endp == NULL) {
1854         return unclosed_directive(cmd);
1855     }
1856
1857     arg = apr_pstrndup(cmd->pool, arg, endp - arg);
1858
1859     if (not) {
1860         arg++;
1861     }
1862
1863     found = ap_find_linked_module(arg);
1864
1865     if ((!not && found) || (not && !found)) {
1866         ap_directive_t *parent = NULL;
1867         ap_directive_t *current = NULL;
1868         const char *retval;
1869
1870         retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd,
1871                                       &current, &parent, "<IfModule");
1872         *(ap_directive_t **)mconfig = current;
1873         return retval;
1874     }
1875     else {
1876         *(ap_directive_t **)mconfig = NULL;
1877         return ap_soak_end_container(cmd, "<IfModule");
1878     }
1879 }
1880
1881 AP_DECLARE(int) ap_exists_config_define(const char *name)
1882 {
1883     char **defines;
1884     int i;
1885
1886     defines = (char **)ap_server_config_defines->elts;
1887     for (i = 0; i < ap_server_config_defines->nelts; i++) {
1888         if (strcmp(defines[i], name) == 0) {
1889             return 1;
1890         }
1891     }
1892
1893     return 0;
1894 }
1895
1896 static const char *start_ifdefine(cmd_parms *cmd, void *dummy, const char *arg)
1897 {
1898     const char *endp;
1899     int defined;
1900     int not = 0;
1901
1902     endp = ap_strrchr_c(arg, '>');
1903     if (endp == NULL) {
1904         return unclosed_directive(cmd);
1905     }
1906
1907     arg = apr_pstrndup(cmd->pool, arg, endp - arg);
1908
1909     if (arg[0] == '!') {
1910         not = 1;
1911         arg++;
1912     }
1913
1914     defined = ap_exists_config_define(arg);
1915     if ((!not && defined) || (not && !defined)) {
1916         ap_directive_t *parent = NULL;
1917         ap_directive_t *current = NULL;
1918         const char *retval;
1919
1920         retval = ap_build_cont_config(cmd->pool, cmd->temp_pool, cmd,
1921                                       &current, &parent, "<IfDefine");
1922         *(ap_directive_t **)dummy = current;
1923         return retval;
1924     }
1925     else {
1926         *(ap_directive_t **)dummy = NULL;
1927         return ap_soak_end_container(cmd, "<IfDefine");
1928     }
1929 }
1930
1931 /* httpd.conf commands... beginning with the <VirtualHost> business */
1932
1933 static const char *virtualhost_section(cmd_parms *cmd, void *dummy,
1934                                        const char *arg)
1935 {
1936     server_rec *main_server = cmd->server, *s;
1937     const char *errmsg;
1938     const char *endp = ap_strrchr_c(arg, '>');
1939     apr_pool_t *p = cmd->pool;
1940
1941     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1942     if (err != NULL) {
1943         return err;
1944     }
1945
1946     if (endp == NULL) {
1947         return unclosed_directive(cmd);
1948     }
1949
1950     arg = apr_pstrndup(cmd->pool, arg, endp - arg);
1951
1952     /* FIXME: There's another feature waiting to happen here -- since you
1953         can now put multiple addresses/names on a single <VirtualHost>
1954         you might want to use it to group common definitions and then
1955         define other "subhosts" with their individual differences.  But
1956         personally I'd rather just do it with a macro preprocessor. -djg */
1957     if (main_server->is_virtual) {
1958         return "<VirtualHost> doesn't nest!";
1959     }
1960
1961     errmsg = ap_init_virtual_host(p, arg, main_server, &s);
1962     if (errmsg) {
1963         return errmsg;
1964     }
1965
1966     s->next = main_server->next;
1967     main_server->next = s;
1968
1969     s->defn_name = cmd->directive->filename;
1970     s->defn_line_number = cmd->directive->line_num;
1971
1972     cmd->server = s;
1973
1974     errmsg = ap_walk_config(cmd->directive->first_child, cmd,
1975                             s->lookup_defaults);
1976
1977     cmd->server = main_server;
1978
1979     return errmsg;
1980 }
1981
1982 static const char *set_server_alias(cmd_parms *cmd, void *dummy,
1983                                     const char *arg)
1984 {
1985     if (!cmd->server->names) {
1986         return "ServerAlias only used in <VirtualHost>";
1987     }
1988
1989     while (*arg) {
1990         char **item, *name = ap_getword_conf(cmd->pool, &arg);
1991
1992         if (ap_is_matchexp(name)) {
1993             item = (char **)apr_array_push(cmd->server->wild_names);
1994         }
1995         else {
1996             item = (char **)apr_array_push(cmd->server->names);
1997         }
1998
1999         *item = name;
2000     }
2001
2002     return NULL;
2003 }
2004
2005 static const char *set_server_string_slot(cmd_parms *cmd, void *dummy,
2006                                           const char *arg)
2007 {
2008     /* This one's pretty generic... */
2009
2010     int offset = (int)(long)cmd->info;
2011     char *struct_ptr = (char *)cmd->server;
2012
2013     const char *err = ap_check_cmd_context(cmd,
2014                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2015     if (err != NULL) {
2016         return err;
2017     }
2018
2019     *(const char **)(struct_ptr + offset) = arg;
2020     return NULL;
2021 }
2022
2023 static const char *server_hostname_port(cmd_parms *cmd, void *dummy, const char *arg)
2024 {
2025     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2026     const char *portstr;
2027     int port;
2028
2029     if (err != NULL) {
2030         return err;
2031     }
2032
2033     portstr = ap_strchr_c(arg, ':');
2034     if (portstr) {
2035         cmd->server->server_hostname = apr_pstrndup(cmd->pool, arg,
2036                                                     portstr - arg);
2037         portstr++;
2038         port = atoi(portstr);
2039         if (port <= 0 || port >= 65536) { /* 65536 == 1<<16 */
2040             return apr_pstrcat(cmd->temp_pool, "The port number \"", arg,
2041                           "\" is outside the appropriate range "
2042                           "(i.e., 1..65535).", NULL);
2043         }
2044     }
2045     else {
2046         cmd->server->server_hostname = apr_pstrdup(cmd->pool, arg);
2047         port = 0;
2048     }
2049
2050     cmd->server->port = port;
2051     return NULL;
2052 }
2053
2054 static const char *set_signature_flag(cmd_parms *cmd, void *d_,
2055                                       const char *arg)
2056 {
2057     core_dir_config *d = d_;
2058     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2059
2060     if (err != NULL) {
2061         return err;
2062     }
2063
2064     if (strcasecmp(arg, "On") == 0) {
2065         d->server_signature = srv_sig_on;
2066     }
2067     else if (strcasecmp(arg, "Off") == 0) {
2068         d->server_signature = srv_sig_off;
2069     }
2070     else if (strcasecmp(arg, "EMail") == 0) {
2071         d->server_signature = srv_sig_withmail;
2072     }
2073     else {
2074         return "ServerSignature: use one of: off | on | email";
2075     }
2076
2077     return NULL;
2078 }
2079
2080 static const char *set_server_root(cmd_parms *cmd, void *dummy,
2081                                    const char *arg)
2082 {
2083     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2084
2085     if (err != NULL) {
2086         return err;
2087     }
2088
2089     if ((apr_filepath_merge((char**)&ap_server_root, NULL, arg,
2090                             APR_FILEPATH_TRUENAME, cmd->pool) != APR_SUCCESS)
2091         || !ap_is_directory(cmd->pool, ap_server_root)) {
2092         return "ServerRoot must be a valid directory";
2093     }
2094
2095     return NULL;
2096 }
2097
2098 static const char *set_timeout(cmd_parms *cmd, void *dummy, const char *arg)
2099 {
2100     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2101
2102     if (err != NULL) {
2103         return err;
2104     }
2105
2106     cmd->server->timeout = apr_time_from_sec(atoi(arg));
2107     return NULL;
2108 }
2109
2110 static const char *set_allow2f(cmd_parms *cmd, void *d_, int arg)
2111 {
2112     core_dir_config *d = d_;
2113     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2114
2115     if (err != NULL) {
2116         return err;
2117     }
2118
2119     d->allow_encoded_slashes = arg != 0;
2120     return NULL;
2121 }
2122
2123 static const char *set_hostname_lookups(cmd_parms *cmd, void *d_,
2124                                         const char *arg)
2125 {
2126     core_dir_config *d = d_;
2127     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2128
2129     if (err != NULL) {
2130         return err;
2131     }
2132
2133     if (!strcasecmp(arg, "on")) {
2134         d->hostname_lookups = HOSTNAME_LOOKUP_ON;
2135     }
2136     else if (!strcasecmp(arg, "off")) {
2137         d->hostname_lookups = HOSTNAME_LOOKUP_OFF;
2138     }
2139     else if (!strcasecmp(arg, "double")) {
2140         d->hostname_lookups = HOSTNAME_LOOKUP_DOUBLE;
2141     }
2142     else {
2143         return "parameter must be 'on', 'off', or 'double'";
2144     }
2145
2146     return NULL;
2147 }
2148
2149 static const char *set_serverpath(cmd_parms *cmd, void *dummy,
2150                                   const char *arg)
2151 {
2152     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2153
2154     if (err != NULL) {
2155         return err;
2156     }
2157
2158     cmd->server->path = arg;
2159     cmd->server->pathlen = strlen(arg);
2160     return NULL;
2161 }
2162
2163 static const char *set_content_md5(cmd_parms *cmd, void *d_, int arg)
2164 {
2165     core_dir_config *d = d_;
2166     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2167
2168     if (err != NULL) {
2169         return err;
2170     }
2171
2172     d->content_md5 = arg != 0;
2173     return NULL;
2174 }
2175
2176 static const char *set_accept_path_info(cmd_parms *cmd, void *d_, const char *arg)
2177 {
2178     core_dir_config *d = d_;
2179
2180     if (strcasecmp(arg, "on") == 0) {
2181         d->accept_path_info = AP_REQ_ACCEPT_PATH_INFO;
2182     }
2183     else if (strcasecmp(arg, "off") == 0) {
2184         d->accept_path_info = AP_REQ_REJECT_PATH_INFO;
2185     }
2186     else if (strcasecmp(arg, "default") == 0) {
2187         d->accept_path_info = AP_REQ_DEFAULT_PATH_INFO;
2188     }
2189     else {
2190         return "AcceptPathInfo must be set to on, off or default";
2191     }
2192
2193     return NULL;
2194 }
2195
2196 static const char *set_use_canonical_name(cmd_parms *cmd, void *d_,
2197                                           const char *arg)
2198 {
2199     core_dir_config *d = d_;
2200     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2201
2202     if (err != NULL) {
2203         return err;
2204     }
2205
2206     if (strcasecmp(arg, "on") == 0) {
2207         d->use_canonical_name = USE_CANONICAL_NAME_ON;
2208     }
2209     else if (strcasecmp(arg, "off") == 0) {
2210         d->use_canonical_name = USE_CANONICAL_NAME_OFF;
2211     }
2212     else if (strcasecmp(arg, "dns") == 0) {
2213         d->use_canonical_name = USE_CANONICAL_NAME_DNS;
2214     }
2215     else {
2216         return "parameter must be 'on', 'off', or 'dns'";
2217     }
2218
2219     return NULL;
2220 }
2221
2222
2223 static const char *include_config (cmd_parms *cmd, void *dummy,
2224                                    const char *name)
2225 {
2226     ap_directive_t *conftree = NULL;
2227     const char* conffile = ap_server_root_relative(cmd->pool, name);
2228
2229     if (!conffile) {
2230         return apr_pstrcat(cmd->pool, "Invalid Include path ", 
2231                            name, NULL);
2232     }
2233
2234     ap_process_resource_config(cmd->server, conffile,
2235                                &conftree, cmd->pool, cmd->temp_pool);
2236     *(ap_directive_t **)dummy = conftree;
2237     return NULL;
2238 }
2239
2240 static const char *set_loglevel(cmd_parms *cmd, void *dummy, const char *arg)
2241 {
2242     char *str;
2243
2244     const char *err = ap_check_cmd_context(cmd,
2245                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2246     if (err != NULL) {
2247         return err;
2248     }
2249
2250     if ((str = ap_getword_conf(cmd->pool, &arg))) {
2251         if (!strcasecmp(str, "emerg")) {
2252             cmd->server->loglevel = APLOG_EMERG;
2253         }
2254         else if (!strcasecmp(str, "alert")) {
2255             cmd->server->loglevel = APLOG_ALERT;
2256         }
2257         else if (!strcasecmp(str, "crit")) {
2258             cmd->server->loglevel = APLOG_CRIT;
2259         }
2260         else if (!strcasecmp(str, "error")) {
2261             cmd->server->loglevel = APLOG_ERR;
2262         }
2263         else if (!strcasecmp(str, "warn")) {
2264             cmd->server->loglevel = APLOG_WARNING;
2265         }
2266         else if (!strcasecmp(str, "notice")) {
2267             cmd->server->loglevel = APLOG_NOTICE;
2268         }
2269         else if (!strcasecmp(str, "info")) {
2270             cmd->server->loglevel = APLOG_INFO;
2271         }
2272         else if (!strcasecmp(str, "debug")) {
2273             cmd->server->loglevel = APLOG_DEBUG;
2274         }
2275         else {
2276             return "LogLevel requires level keyword: one of "
2277                    "emerg/alert/crit/error/warn/notice/info/debug";
2278         }
2279     }
2280     else {
2281         return "LogLevel requires level keyword";
2282     }
2283
2284     return NULL;
2285 }
2286
2287 AP_DECLARE(const char *) ap_psignature(const char *prefix, request_rec *r)
2288 {
2289     char sport[20];
2290     core_dir_config *conf;
2291
2292     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
2293                                                    &core_module);
2294     if ((conf->server_signature == srv_sig_off)
2295             || (conf->server_signature == srv_sig_unset)) {
2296         return "";
2297     }
2298
2299     apr_snprintf(sport, sizeof sport, "%u", (unsigned) ap_get_server_port(r));
2300
2301     if (conf->server_signature == srv_sig_withmail) {
2302         return apr_pstrcat(r->pool, prefix, "<address>", 
2303                            ap_get_server_version(),
2304                            " Server at <a href=\"mailto:",
2305                            r->server->server_admin, "\">",
2306                            ap_escape_html(r->pool, ap_get_server_name(r)),
2307                            "</a> Port ", sport,
2308                            "</address>\n", NULL);
2309     }
2310
2311     return apr_pstrcat(r->pool, prefix, "<address>", ap_get_server_version(),
2312                        " Server at ",
2313                        ap_escape_html(r->pool, ap_get_server_name(r)),
2314                        " Port ", sport,
2315                        "</address>\n", NULL);
2316 }
2317
2318 /*
2319  * Load an authorisation realm into our location configuration, applying the
2320  * usual rules that apply to realms.
2321  */
2322 static const char *set_authname(cmd_parms *cmd, void *mconfig,
2323                                 const char *word1)
2324 {
2325     core_dir_config *aconfig = (core_dir_config *)mconfig;
2326
2327     aconfig->ap_auth_name = ap_escape_quotes(cmd->pool, word1);
2328     return NULL;
2329 }
2330
2331 /*
2332  * Handle a request to include the server's OS platform in the Server
2333  * response header field (the ServerTokens directive).  Unfortunately
2334  * this requires a new global in order to communicate the setting back to
2335  * http_main so it can insert the information in the right place in the
2336  * string.
2337  */
2338
2339 static char *server_version = NULL;
2340 static int version_locked = 0;
2341
2342 enum server_token_type {
2343     SrvTk_MAJOR,        /* eg: Apache/2 */
2344     SrvTk_MINOR,        /* eg. Apache/2.0 */
2345     SrvTk_MINIMAL,      /* eg: Apache/2.0.41 */
2346     SrvTk_OS,           /* eg: Apache/2.0.41 (UNIX) */
2347     SrvTk_FULL,         /* eg: Apache/2.0.41 (UNIX) PHP/4.2.2 FooBar/1.2b */
2348     SrvTk_PRODUCT_ONLY  /* eg: Apache */
2349 };
2350 static enum server_token_type ap_server_tokens = SrvTk_FULL;
2351
2352 static apr_status_t reset_version(void *dummy)
2353 {
2354     version_locked = 0;
2355     ap_server_tokens = SrvTk_FULL;
2356     server_version = NULL;
2357     return APR_SUCCESS;
2358 }
2359
2360 AP_DECLARE(const char *) ap_get_server_version(void)
2361 {
2362     return (server_version ? server_version : AP_SERVER_BASEVERSION);
2363 }
2364
2365 AP_DECLARE(void) ap_add_version_component(apr_pool_t *pconf, const char *component)
2366 {
2367     if (! version_locked) {
2368         /*
2369          * If the version string is null, register our cleanup to reset the
2370          * pointer on pool destruction. We also know that, if NULL,
2371          * we are adding the original SERVER_BASEVERSION string.
2372          */
2373         if (server_version == NULL) {
2374             apr_pool_cleanup_register(pconf, NULL, reset_version,
2375                                       apr_pool_cleanup_null);
2376             server_version = apr_pstrdup(pconf, component);
2377         }
2378         else {
2379             /*
2380              * Tack the given component identifier to the end of
2381              * the existing string.
2382              */
2383             server_version = apr_pstrcat(pconf, server_version, " ",
2384                                          component, NULL);
2385         }
2386     }
2387 }
2388
2389 /*
2390  * This routine adds the real server base identity to the version string,
2391  * and then locks out changes until the next reconfig.
2392  */
2393 static void ap_set_version(apr_pool_t *pconf)
2394 {
2395     if (ap_server_tokens == SrvTk_PRODUCT_ONLY) {
2396         ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT);
2397     }
2398     else if (ap_server_tokens == SrvTk_MINIMAL) {
2399         ap_add_version_component(pconf, AP_SERVER_BASEVERSION);
2400     }
2401     else if (ap_server_tokens == SrvTk_MINOR) {
2402         ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT "/" AP_SERVER_MINORREVISION);
2403     }
2404     else if (ap_server_tokens == SrvTk_MAJOR) {
2405         ap_add_version_component(pconf, AP_SERVER_BASEPRODUCT "/" AP_SERVER_MAJORVERSION);
2406     }
2407     else {
2408         ap_add_version_component(pconf, AP_SERVER_BASEVERSION " (" PLATFORM ")");
2409     }
2410
2411     /*
2412      * Lock the server_version string if we're not displaying
2413      * the full set of tokens
2414      */
2415     if (ap_server_tokens != SrvTk_FULL) {
2416         version_locked++;
2417     }
2418 }
2419
2420 static const char *set_serv_tokens(cmd_parms *cmd, void *dummy,
2421                                    const char *arg)
2422 {
2423     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2424
2425     if (err != NULL) {
2426         return err;
2427     }
2428
2429     if (!strcasecmp(arg, "OS")) {
2430         ap_server_tokens = SrvTk_OS;
2431     }
2432     else if (!strcasecmp(arg, "Min") || !strcasecmp(arg, "Minimal")) {
2433         ap_server_tokens = SrvTk_MINIMAL;
2434     }
2435     else if (!strcasecmp(arg, "Major")) {
2436         ap_server_tokens = SrvTk_MAJOR;
2437     }
2438     else if (!strcasecmp(arg, "Minor") ) {
2439         ap_server_tokens = SrvTk_MINOR;
2440     }
2441     else if (!strcasecmp(arg, "Prod") || !strcasecmp(arg, "ProductOnly")) {
2442         ap_server_tokens = SrvTk_PRODUCT_ONLY;
2443     }
2444     else {
2445         ap_server_tokens = SrvTk_FULL;
2446     }
2447
2448     return NULL;
2449 }
2450
2451 static const char *set_limit_req_line(cmd_parms *cmd, void *dummy,
2452                                       const char *arg)
2453 {
2454     const char *err = ap_check_cmd_context(cmd,
2455                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2456     int lim;
2457
2458     if (err != NULL) {
2459         return err;
2460     }
2461
2462     lim = atoi(arg);
2463     if (lim < 0) {
2464         return apr_pstrcat(cmd->temp_pool, "LimitRequestLine \"", arg,
2465                            "\" must be a non-negative integer", NULL);
2466     }
2467
2468     if (lim > DEFAULT_LIMIT_REQUEST_LINE) {
2469         return apr_psprintf(cmd->temp_pool, "LimitRequestLine \"%s\" "
2470                             "must not exceed the precompiled maximum of %d",
2471                             arg, DEFAULT_LIMIT_REQUEST_LINE);
2472     }
2473
2474     cmd->server->limit_req_line = lim;
2475     return NULL;
2476 }
2477
2478 static const char *set_limit_req_fieldsize(cmd_parms *cmd, void *dummy,
2479                                            const char *arg)
2480 {
2481     const char *err = ap_check_cmd_context(cmd,
2482                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2483     int lim;
2484
2485     if (err != NULL) {
2486         return err;
2487     }
2488
2489     lim = atoi(arg);
2490     if (lim < 0) {
2491         return apr_pstrcat(cmd->temp_pool, "LimitRequestFieldsize \"", arg,
2492                           "\" must be a non-negative integer (0 = no limit)",
2493                           NULL);
2494     }
2495
2496     if (lim > DEFAULT_LIMIT_REQUEST_FIELDSIZE) {
2497         return apr_psprintf(cmd->temp_pool, "LimitRequestFieldsize \"%s\" "
2498                            "must not exceed the precompiled maximum of %d",
2499                             arg, DEFAULT_LIMIT_REQUEST_FIELDSIZE);
2500     }
2501
2502     cmd->server->limit_req_fieldsize = lim;
2503     return NULL;
2504 }
2505
2506 static const char *set_limit_req_fields(cmd_parms *cmd, void *dummy,
2507                                         const char *arg)
2508 {
2509     const char *err = ap_check_cmd_context(cmd,
2510                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2511     int lim;
2512
2513     if (err != NULL) {
2514         return err;
2515     }
2516
2517     lim = atoi(arg);
2518     if (lim < 0) {
2519         return apr_pstrcat(cmd->temp_pool, "LimitRequestFields \"", arg,
2520                            "\" must be a non-negative integer (0 = no limit)",
2521                            NULL);
2522     }
2523
2524     cmd->server->limit_req_fields = lim;
2525     return NULL;
2526 }
2527
2528 static const char *set_limit_req_body(cmd_parms *cmd, void *conf_,
2529                                       const char *arg)
2530 {
2531     core_dir_config *conf = conf_;
2532     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2533     char *errp;
2534
2535     if (err != NULL) {
2536         return err;
2537     }
2538
2539     /* WTF: If strtoul is not portable, then write a replacement.
2540      *      Instead we have an idiotic define in httpd.h that prevents
2541      *      it from being used even when it is available. Sheesh.
2542      */
2543     conf->limit_req_body = (apr_off_t)strtol(arg, &errp, 10);
2544     if (*errp != '\0') {
2545         return "LimitRequestBody requires a non-negative integer.";
2546     }
2547
2548     return NULL;
2549 }
2550
2551 static const char *set_limit_xml_req_body(cmd_parms *cmd, void *conf_,
2552                                           const char *arg)
2553 {
2554     core_dir_config *conf = conf_;
2555     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2556
2557     if (err != NULL) {
2558         return err;
2559     }
2560
2561     conf->limit_xml_body = atol(arg);
2562     if (conf->limit_xml_body < 0)
2563         return "LimitXMLRequestBody requires a non-negative integer.";
2564
2565     return NULL;
2566 }
2567
2568 AP_DECLARE(size_t) ap_get_limit_xml_body(const request_rec *r)
2569 {
2570     core_dir_config *conf;
2571
2572     conf = ap_get_module_config(r->per_dir_config, &core_module);
2573     if (conf->limit_xml_body == AP_LIMIT_UNSET)
2574         return AP_DEFAULT_LIMIT_XML_BODY;
2575
2576     return (size_t)conf->limit_xml_body;
2577 }
2578
2579 #if !defined (RLIMIT_CPU) || !(defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)) || !defined (RLIMIT_NPROC)
2580 static const char *no_set_limit(cmd_parms *cmd, void *conf_,
2581                                 const char *arg, const char *arg2)
2582 {
2583     ap_log_error(APLOG_MARK, APLOG_ERR, 0, cmd->server,
2584                 "%s not supported on this platform", cmd->cmd->name);
2585
2586     return NULL;
2587 }
2588 #endif
2589
2590 #ifdef RLIMIT_CPU
2591 static const char *set_limit_cpu(cmd_parms *cmd, void *conf_,
2592                                  const char *arg, const char *arg2)
2593 {
2594     core_dir_config *conf = conf_;
2595
2596     unixd_set_rlimit(cmd, &conf->limit_cpu, arg, arg2, RLIMIT_CPU);
2597     return NULL;
2598 }
2599 #endif
2600
2601 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined(RLIMIT_AS)
2602 static const char *set_limit_mem(cmd_parms *cmd, void *conf_,
2603                                  const char *arg, const char * arg2)
2604 {
2605     core_dir_config *conf = conf_;
2606
2607 #if defined(RLIMIT_AS)
2608     unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2 ,RLIMIT_AS);
2609 #elif defined(RLIMIT_DATA)
2610     unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_DATA);
2611 #elif defined(RLIMIT_VMEM)
2612     unixd_set_rlimit(cmd, &conf->limit_mem, arg, arg2, RLIMIT_VMEM);
2613 #endif
2614
2615     return NULL;
2616 }
2617 #endif
2618
2619 #ifdef RLIMIT_NPROC
2620 static const char *set_limit_nproc(cmd_parms *cmd, void *conf_,
2621                                    const char *arg, const char * arg2)
2622 {
2623     core_dir_config *conf = conf_;
2624
2625     unixd_set_rlimit(cmd, &conf->limit_nproc, arg, arg2, RLIMIT_NPROC);
2626     return NULL;
2627 }
2628 #endif
2629
2630 static const char *set_recursion_limit(cmd_parms *cmd, void *dummy,
2631                                        const char *arg1, const char *arg2)
2632 {
2633     core_server_config *conf = ap_get_module_config(cmd->server->module_config,
2634                                                     &core_module);
2635     int limit = atoi(arg1);
2636
2637     if (limit <= 0) {
2638         return "The recursion limit must be greater than zero.";
2639     }
2640     if (limit < 4) {
2641         ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
2642                      "Limiting internal redirects to very low numbers may "
2643                      "cause normal requests to fail.");
2644     }
2645
2646     conf->redirect_limit = limit;
2647
2648     if (arg2) {
2649         limit = atoi(arg2);
2650
2651         if (limit <= 0) {
2652             return "The recursion limit must be greater than zero.";
2653         }
2654         if (limit < 4) {
2655             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server,
2656                          "Limiting the subrequest depth to a very low level may"
2657                          " cause normal requests to fail.");
2658         }
2659     }
2660
2661     conf->subreq_limit = limit;
2662
2663     return NULL;
2664 }
2665
2666 static void log_backtrace(const request_rec *r)
2667 {
2668     const request_rec *top = r;
2669
2670     ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
2671                   "r->uri = %s", r->uri ? r->uri : "(unexpectedly NULL)");
2672
2673     while (top && (top->prev || top->main)) {
2674         if (top->prev) {
2675             top = top->prev;
2676             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
2677                           "redirected from r->uri = %s",
2678                           top->uri ? top->uri : "(unexpectedly NULL)");
2679         }
2680
2681         if (!top->prev && top->main) {
2682             top = top->main;
2683             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
2684                           "subrequested from r->uri = %s",
2685                           top->uri ? top->uri : "(unexpectedly NULL)");
2686         }
2687     }
2688 }
2689
2690 /*
2691  * check whether redirect limit is reached
2692  */
2693 AP_DECLARE(int) ap_is_recursion_limit_exceeded(const request_rec *r)
2694 {
2695     core_server_config *conf = ap_get_module_config(r->server->module_config,
2696                                                     &core_module);
2697     const request_rec *top = r;
2698     int redirects = 0, subreqs = 0;
2699     int rlimit = conf->redirect_limit
2700                  ? conf->redirect_limit
2701                  : AP_DEFAULT_MAX_INTERNAL_REDIRECTS;
2702     int slimit = conf->subreq_limit
2703                  ? conf->subreq_limit
2704                  : AP_DEFAULT_MAX_SUBREQ_DEPTH;
2705
2706
2707     while (top->prev || top->main) {
2708         if (top->prev) {
2709             if (++redirects >= rlimit) {
2710                 /* uuh, too much. */
2711                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
2712                               "Request exceeded the limit of %d internal "
2713                               "redirects due to probable configuration error. "
2714                               "Use 'LimitInternalRecursion' to increase the "
2715                               "limit if necessary. Use 'LogLevel debug' to get "
2716                               "a backtrace.", rlimit);
2717
2718                 /* post backtrace */
2719                 log_backtrace(r);
2720
2721                 /* return failure */
2722                 return 1;
2723             }
2724
2725             top = top->prev;
2726         }
2727
2728         if (!top->prev && top->main) {
2729             if (++subreqs >= slimit) {
2730                 /* uuh, too much. */
2731                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
2732                               "Request exceeded the limit of %d subrequest "
2733                               "nesting levels due to probable confguration "
2734                               "error. Use 'LimitInternalRecursion' to increase "
2735                               "the limit if necessary. Use 'LogLevel debug' to "
2736                               "get a backtrace.", slimit);
2737
2738                 /* post backtrace */
2739                 log_backtrace(r);
2740
2741                 /* return failure */
2742                 return 1;
2743             }
2744
2745             top = top->main;
2746         }
2747     }
2748
2749     /* recursion state: ok */
2750     return 0;
2751 }
2752
2753 static const char *add_ct_output_filters(cmd_parms *cmd, void *conf_,
2754                                          const char *arg, const char *arg2)
2755 {
2756     core_dir_config *conf = conf_;
2757     ap_filter_rec_t *old, *new = NULL;
2758     const char *filter_name;
2759
2760     if (!conf->ct_output_filters) {
2761         conf->ct_output_filters = apr_hash_make(cmd->pool);
2762         old = NULL;
2763     }
2764     else {
2765         old = (ap_filter_rec_t*) apr_hash_get(conf->ct_output_filters, arg2,
2766                                               APR_HASH_KEY_STRING);
2767         /* find last entry */
2768         if (old) {
2769             while (old->next) {
2770                 old = old->next;
2771             }
2772         }
2773     }
2774
2775     while (*arg &&
2776            (filter_name = ap_getword(cmd->pool, &arg, ';')) &&
2777            strcmp(filter_name, "")) {
2778         new = apr_pcalloc(cmd->pool, sizeof(ap_filter_rec_t));
2779         new->name = filter_name;
2780
2781         /* We found something, so let's append it.  */
2782         if (old) {
2783             old->next = new;
2784         }
2785         else {
2786             apr_hash_set(conf->ct_output_filters, arg2,
2787                          APR_HASH_KEY_STRING, new);
2788         }
2789         old = new;
2790     }
2791
2792     if (!new) {
2793         return "invalid filter name";
2794     }
2795     
2796     return NULL;
2797 }
2798 /* 
2799  * Insert filters requested by the AddOutputFilterByType 
2800  * configuration directive. We cannot add filters based 
2801  * on content-type until after the handler has started 
2802  * to run. Only then do we reliably know the content-type.
2803  */
2804 void ap_add_output_filters_by_type(request_rec *r)
2805 {
2806     core_dir_config *conf;
2807     const char *ctype;
2808
2809     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
2810                                                    &core_module);
2811
2812     /* We can't do anything with proxy requests, no content-types or if
2813      * we don't have a filter configured.
2814      */
2815     if (r->proxyreq != PROXYREQ_NONE || !r->content_type ||
2816         !conf->ct_output_filters) {
2817         return;
2818     }
2819
2820     /* remove c-t decoration */
2821     ctype = ap_field_noparam(r->pool, r->content_type);
2822     if (ctype) {
2823         ap_filter_rec_t *ct_filter;
2824         ct_filter = apr_hash_get(conf->ct_output_filters, ctype,
2825                                  APR_HASH_KEY_STRING);
2826         while (ct_filter) {
2827             ap_add_output_filter(ct_filter->name, NULL, r, r->connection);
2828             ct_filter = ct_filter->next;
2829         }
2830     }
2831
2832     return;
2833 }
2834
2835 static apr_status_t writev_it_all(apr_socket_t *s,
2836                                   struct iovec *vec, int nvec,
2837                                   apr_size_t len, apr_size_t *nbytes)
2838 {
2839     apr_size_t bytes_written = 0;
2840     apr_status_t rv;
2841     apr_size_t n = len;
2842     int i = 0;
2843
2844     *nbytes = 0;
2845
2846     /* XXX handle checking for non-blocking socket */
2847     while (bytes_written != len) {
2848         rv = apr_sendv(s, vec + i, nvec - i, &n);
2849         bytes_written += n;
2850         if (rv != APR_SUCCESS)
2851             return rv;
2852
2853         *nbytes += n;
2854
2855         /* If the write did not complete, adjust the iovecs and issue
2856          * apr_sendv again
2857          */
2858         if (bytes_written < len) {
2859             /* Skip over the vectors that have already been written */
2860             apr_size_t cnt = vec[i].iov_len;
2861             while (n >= cnt && i + 1 < nvec) {
2862                 i++;
2863                 cnt += vec[i].iov_len;
2864             }
2865
2866             if (n < cnt) {
2867                 /* Handle partial write of vec i */
2868                 vec[i].iov_base = (char *) vec[i].iov_base +
2869                     (vec[i].iov_len - (cnt - n));
2870                 vec[i].iov_len = cnt -n;
2871             }
2872         }
2873
2874         n = len - bytes_written;
2875     }
2876
2877     return APR_SUCCESS;
2878 }
2879
2880 /* sendfile_it_all()
2881  *  send the entire file using sendfile()
2882  *  handle partial writes
2883  *  return only when all bytes have been sent or an error is encountered.
2884  */
2885
2886 #if APR_HAS_SENDFILE
2887 static apr_status_t sendfile_it_all(core_net_rec *c,
2888                                     apr_file_t *fd,
2889                                     apr_hdtr_t *hdtr,
2890                                     apr_off_t   file_offset,
2891                                     apr_size_t  file_bytes_left,
2892                                     apr_size_t  total_bytes_left,
2893                                     apr_size_t  *bytes_sent,
2894                                     apr_int32_t flags)
2895 {
2896     apr_status_t rv;
2897 #ifdef AP_DEBUG
2898     apr_interval_time_t timeout = 0;
2899 #endif
2900
2901     AP_DEBUG_ASSERT((apr_socket_timeout_get(c->client_socket, &timeout) 
2902                          == APR_SUCCESS)
2903                     && timeout > 0);  /* socket must be in timeout mode */
2904
2905     /* Reset the bytes_sent field */
2906     *bytes_sent = 0;
2907
2908     do {
2909         apr_size_t tmplen = file_bytes_left;
2910
2911         rv = apr_sendfile(c->client_socket, fd, hdtr, &file_offset, &tmplen,
2912                           flags);
2913         *bytes_sent += tmplen;
2914         total_bytes_left -= tmplen;
2915         if (!total_bytes_left || rv != APR_SUCCESS) {
2916             return rv;        /* normal case & error exit */
2917         }
2918
2919         AP_DEBUG_ASSERT(total_bytes_left > 0 && tmplen > 0);
2920
2921         /* partial write, oooh noooo...
2922          * Skip over any header data which was written
2923          */
2924         while (tmplen && hdtr->numheaders) {
2925             if (tmplen >= hdtr->headers[0].iov_len) {
2926                 tmplen -= hdtr->headers[0].iov_len;
2927                 --hdtr->numheaders;
2928                 ++hdtr->headers;
2929             }
2930             else {
2931                 char *iov_base = (char *)hdtr->headers[0].iov_base;
2932
2933                 hdtr->headers[0].iov_len -= tmplen;
2934                 iov_base += tmplen;
2935                 hdtr->headers[0].iov_base = iov_base;
2936                 tmplen = 0;
2937             }
2938         }
2939
2940         /* Skip over any file data which was written */
2941
2942         if (tmplen <= file_bytes_left) {
2943             file_offset += tmplen;
2944             file_bytes_left -= tmplen;
2945             continue;
2946         }
2947
2948         tmplen -= file_bytes_left;
2949         file_bytes_left = 0;
2950         file_offset = 0;
2951
2952         /* Skip over any trailer data which was written */
2953
2954         while (tmplen && hdtr->numtrailers) {
2955             if (tmplen >= hdtr->trailers[0].iov_len) {
2956                 tmplen -= hdtr->trailers[0].iov_len;
2957                 --hdtr->numtrailers;
2958                 ++hdtr->trailers;
2959             }
2960             else {
2961                 char *iov_base = (char *)hdtr->trailers[0].iov_base;
2962
2963                 hdtr->trailers[0].iov_len -= tmplen;
2964                 iov_base += tmplen;
2965                 hdtr->trailers[0].iov_base = iov_base;
2966                 tmplen = 0;
2967             }
2968         }
2969     } while (1);
2970 }
2971 #endif
2972
2973 /*
2974  * emulate_sendfile()
2975  * Sends the contents of file fd along with header/trailer bytes, if any,
2976  * to the network. emulate_sendfile will return only when all the bytes have been
2977  * sent (i.e., it handles partial writes) or on a network error condition.
2978  */
2979 static apr_status_t emulate_sendfile(core_net_rec *c, apr_file_t *fd,
2980                                      apr_hdtr_t *hdtr, apr_off_t offset,
2981                                      apr_size_t length, apr_size_t *nbytes)
2982 {
2983     apr_status_t rv = APR_SUCCESS;
2984     apr_int32_t togo;        /* Remaining number of bytes in the file to send */
2985     apr_size_t sendlen = 0;
2986     apr_size_t bytes_sent;
2987     apr_int32_t i;
2988     apr_off_t o;             /* Track the file offset for partial writes */
2989     char buffer[8192];
2990
2991     *nbytes = 0;
2992
2993     /* Send the headers
2994      * writev_it_all handles partial writes.
2995      * XXX: optimization... if headers are less than MIN_WRITE_SIZE, copy
2996      * them into buffer
2997      */
2998     if (hdtr && hdtr->numheaders > 0 ) {
2999         for (i = 0; i < hdtr->numheaders; i++) {
3000             sendlen += hdtr->headers[i].iov_len;
3001         }
3002
3003         rv = writev_it_all(c->client_socket, hdtr->headers, hdtr->numheaders,
3004                            sendlen, &bytes_sent);
3005         if (rv == APR_SUCCESS)
3006             *nbytes += bytes_sent;     /* track total bytes sent */
3007     }
3008
3009     /* Seek the file to 'offset' */
3010     if (offset != 0 && rv == APR_SUCCESS) {
3011         rv = apr_file_seek(fd, APR_SET, &offset);
3012     }
3013
3014     /* Send the file, making sure to handle partial writes */
3015     togo = length;
3016     while (rv == APR_SUCCESS && togo) {
3017         sendlen = togo > sizeof(buffer) ? sizeof(buffer) : togo;
3018         o = 0;
3019         rv = apr_file_read(fd, buffer, &sendlen);
3020         while (rv == APR_SUCCESS && sendlen) {
3021             bytes_sent = sendlen;
3022             rv = apr_send(c->client_socket, &buffer[o], &bytes_sent);
3023             if (rv == APR_SUCCESS) {
3024                 sendlen -= bytes_sent; /* sendlen != bytes_sent ==> partial write */
3025                 o += bytes_sent;       /* o is where we are in the buffer */
3026                 *nbytes += bytes_sent;
3027                 togo -= bytes_sent;    /* track how much of the file we've sent */
3028             }
3029         }
3030     }
3031
3032     /* Send the trailers
3033      * XXX: optimization... if it will fit, send this on the last send in the
3034      * loop above
3035      */
3036     sendlen = 0;
3037     if ( rv == APR_SUCCESS && hdtr && hdtr->numtrailers > 0 ) {
3038         for (i = 0; i < hdtr->numtrailers; i++) {
3039             sendlen += hdtr->trailers[i].iov_len;
3040         }
3041         rv = writev_it_all(c->client_socket, hdtr->trailers, hdtr->numtrailers,
3042                            sendlen, &bytes_sent);
3043         if (rv == APR_SUCCESS)
3044             *nbytes += bytes_sent;
3045     }
3046
3047     return rv;
3048 }
3049
3050 /* Note --- ErrorDocument will now work from .htaccess files.
3051  * The AllowOverride of Fileinfo allows webmasters to turn it off
3052  */
3053
3054 static const command_rec core_cmds[] = {
3055
3056 /* Old access config file commands */
3057
3058 AP_INIT_RAW_ARGS("<Directory", dirsection, NULL, RSRC_CONF,
3059   "Container for directives affecting resources located in the specified "
3060   "directories"),
3061 AP_INIT_RAW_ARGS("<Location", urlsection, NULL, RSRC_CONF,
3062   "Container for directives affecting resources accessed through the "
3063   "specified URL paths"),
3064 AP_INIT_RAW_ARGS("<VirtualHost", virtualhost_section, NULL, RSRC_CONF,
3065   "Container to map directives to a particular virtual host, takes one or "
3066   "more host addresses"),
3067 AP_INIT_RAW_ARGS("<Files", filesection, NULL, OR_ALL,
3068   "Container for directives affecting files matching specified patterns"),
3069 AP_INIT_RAW_ARGS("<Limit", ap_limit_section, NULL, OR_ALL,
3070   "Container for authentication directives when accessed using specified HTTP "
3071   "methods"),
3072 AP_INIT_RAW_ARGS("<LimitExcept", ap_limit_section, (void*)1, OR_ALL,
3073   "Container for authentication directives to be applied when any HTTP "
3074   "method other than those specified is used to access the resource"),
3075 AP_INIT_TAKE1("<IfModule", start_ifmod, NULL, EXEC_ON_READ | OR_ALL,
3076   "Container for directives based on existance of specified modules"),
3077 AP_INIT_TAKE1("<IfDefine", start_ifdefine, NULL, EXEC_ON_READ | OR_ALL,
3078   "Container for directives based on existance of command line defines"),
3079 AP_INIT_RAW_ARGS("<DirectoryMatch", dirsection, (void*)1, RSRC_CONF,
3080   "Container for directives affecting resources located in the "
3081   "specified directories"),
3082 AP_INIT_RAW_ARGS("<LocationMatch", urlsection, (void*)1, RSRC_CONF,
3083   "Container for directives affecting resources accessed through the "
3084   "specified URL paths"),
3085 AP_INIT_RAW_ARGS("<FilesMatch", filesection, (void*)1, OR_ALL,
3086   "Container for directives affecting files matching specified patterns"),
3087 AP_INIT_TAKE1("AuthType", ap_set_string_slot,
3088   (void*)APR_OFFSETOF(core_dir_config, ap_auth_type), OR_AUTHCFG,
3089   "An HTTP authorization type (e.g., \"Basic\")"),
3090 AP_INIT_TAKE1("AuthName", set_authname, NULL, OR_AUTHCFG,
3091   "The authentication realm (e.g. \"Members Only\")"),
3092 AP_INIT_RAW_ARGS("Require", require, NULL, OR_AUTHCFG,
3093   "Selects which authenticated users or groups may access a protected space"),
3094 AP_INIT_TAKE1("Satisfy", satisfy, NULL, OR_AUTHCFG,
3095   "access policy if both allow and require used ('all' or 'any')"),
3096 #ifdef GPROF
3097 AP_INIT_TAKE1("GprofDir", set_gprof_dir, NULL, RSRC_CONF,
3098   "Directory to plop gmon.out files"),
3099 #endif
3100 AP_INIT_TAKE1("AddDefaultCharset", set_add_default_charset, NULL, OR_FILEINFO,
3101   "The name of the default charset to add to any Content-Type without one or 'Off' to disable"),
3102 AP_INIT_TAKE1("AcceptPathInfo", set_accept_path_info, NULL, OR_FILEINFO,
3103   "Set to on or off for PATH_INFO to be accepted by handlers, or default for the per-handler preference"),
3104
3105 /* Old resource config file commands */
3106
3107 AP_INIT_RAW_ARGS("AccessFileName", set_access_name, NULL, RSRC_CONF,
3108   "Name(s) of per-directory config files (default: .htaccess)"),
3109 AP_INIT_TAKE1("DocumentRoot", set_document_root, NULL, RSRC_CONF,
3110   "Root directory of the document tree"),
3111 AP_INIT_TAKE2("ErrorDocument", set_error_document, NULL, OR_FILEINFO,
3112   "Change responses for HTTP errors"),
3113 AP_INIT_RAW_ARGS("AllowOverride", set_override, NULL, ACCESS_CONF,
3114   "Controls what groups of directives can be configured by per-directory "
3115   "config files"),
3116 AP_INIT_RAW_ARGS("Options", set_options, NULL, OR_OPTIONS,
3117   "Set a number of attributes for a given directory"),
3118 AP_INIT_TAKE1("DefaultType", ap_set_string_slot,
3119   (void*)APR_OFFSETOF(core_dir_config, ap_default_type),
3120   OR_FILEINFO, "the default MIME type for untypable files"),
3121 AP_INIT_RAW_ARGS("FileETag", set_etag_bits, NULL, OR_FILEINFO,
3122   "Specify components used to construct a file's ETag"),
3123 AP_INIT_TAKE1("EnableMMAP", set_enable_mmap, NULL, OR_FILEINFO,
3124   "Controls whether memory-mapping may be used to read files"),
3125 AP_INIT_TAKE1("EnableSendfile", set_enable_sendfile, NULL, OR_FILEINFO,
3126   "Controls whether sendfile may be used to transmit files"),
3127
3128 /* Old server config file commands */
3129
3130 AP_INIT_TAKE1("Port", ap_set_deprecated, NULL, RSRC_CONF,
3131   "Port was replaced with Listen in Apache 2.0"),
3132 AP_INIT_TAKE1("HostnameLookups", set_hostname_lookups, NULL,
3133   ACCESS_CONF|RSRC_CONF,
3134   "\"on\" to enable, \"off\" to disable reverse DNS lookups, or \"double\" to "
3135   "enable double-reverse DNS lookups"),
3136 AP_INIT_TAKE1("ServerAdmin", set_server_string_slot,
3137   (void *)APR_OFFSETOF(server_rec, server_admin), RSRC_CONF,
3138   "The email address of the server administrator"),
3139 AP_INIT_TAKE1("ServerName", server_hostname_port, NULL, RSRC_CONF,
3140   "The hostname and port of the server"),
3141 AP_INIT_TAKE1("ServerSignature", set_signature_flag, NULL, OR_ALL,
3142   "En-/disable server signature (on|off|email)"),
3143 AP_INIT_TAKE1("ServerRoot", set_server_root, NULL, RSRC_CONF | EXEC_ON_READ,
3144   "Common directory of server-related files (logs, confs, etc.)"),
3145 AP_INIT_TAKE1("ErrorLog", set_server_string_slot,
3146   (void *)APR_OFFSETOF(server_rec, error_fname), RSRC_CONF,
3147   "The filename of the error log"),
3148 AP_INIT_RAW_ARGS("ServerAlias", set_server_alias, NULL, RSRC_CONF,
3149   "A name or names alternately used to access the server"),
3150 AP_INIT_TAKE1("ServerPath", set_serverpath, NULL, RSRC_CONF,
3151   "The pathname the server can be reached at"),
3152 AP_INIT_TAKE1("Timeout", set_timeout, NULL, RSRC_CONF,
3153   "Timeout duration (sec)"),
3154 AP_INIT_FLAG("ContentDigest", set_content_md5, NULL, OR_OPTIONS,
3155   "whether or not to send a Content-MD5 header with each request"),
3156 AP_INIT_TAKE1("UseCanonicalName", set_use_canonical_name, NULL,
3157   RSRC_CONF|ACCESS_CONF,
3158   "How to work out the ServerName : Port when constructing URLs"),
3159 /* TODO: RlimitFoo should all be part of mod_cgi, not in the core */
3160 /* TODO: ListenBacklog in MPM */
3161 AP_INIT_TAKE1("Include", include_config, NULL,
3162   (RSRC_CONF | ACCESS_CONF | EXEC_ON_READ),
3163   "Name of the config file to be included"),
3164 AP_INIT_TAKE1("LogLevel", set_loglevel, NULL, RSRC_CONF,
3165   "Level of verbosity in error logging"),
3166 AP_INIT_TAKE1("NameVirtualHost", ap_set_name_virtual_host, NULL, RSRC_CONF,
3167   "A numeric IP address:port, or the name of a host"),
3168 AP_INIT_TAKE1("ServerTokens", set_serv_tokens, NULL, RSRC_CONF,
3169   "Determine tokens displayed in the Server: header - Min(imal), OS or Full"),
3170 AP_INIT_TAKE1("LimitRequestLine", set_limit_req_line, NULL, RSRC_CONF,
3171   "Limit on maximum size of an HTTP request line"),
3172 AP_INIT_TAKE1("LimitRequestFieldsize", set_limit_req_fieldsize, NULL,
3173   RSRC_CONF,
3174   "Limit on maximum size of an HTTP request header field"),
3175 AP_INIT_TAKE1("LimitRequestFields", set_limit_req_fields, NULL, RSRC_CONF,
3176   "Limit (0 = unlimited) on max number of header fields in a request message"),
3177 AP_INIT_TAKE1("LimitRequestBody", set_limit_req_body,
3178   (void*)APR_OFFSETOF(core_dir_config, limit_req_body), OR_ALL,
3179   "Limit (in bytes) on maximum size of request message body"),
3180 AP_INIT_TAKE1("LimitXMLRequestBody", set_limit_xml_req_body, NULL, OR_ALL,
3181               "Limit (in bytes) on maximum size of an XML-based request "
3182               "body"),
3183
3184 /* System Resource Controls */
3185 #ifdef RLIMIT_CPU
3186 AP_INIT_TAKE12("RLimitCPU", set_limit_cpu,
3187   (void*)APR_OFFSETOF(core_dir_config, limit_cpu),
3188   OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
3189 #else
3190 AP_INIT_TAKE12("RLimitCPU", no_set_limit, NULL,
3191   OR_ALL, "Soft/hard limits for max CPU usage in seconds"),
3192 #endif
3193 #if defined (RLIMIT_DATA) || defined (RLIMIT_VMEM) || defined (RLIMIT_AS)
3194 AP_INIT_TAKE12("RLimitMEM", set_limit_mem,
3195   (void*)APR_OFFSETOF(core_dir_config, limit_mem),
3196   OR_ALL, "Soft/hard limits for max memory usage per process"),
3197 #else
3198 AP_INIT_TAKE12("RLimitMEM", no_set_limit, NULL,
3199   OR_ALL, "Soft/hard limits for max memory usage per process"),
3200 #endif
3201 #ifdef RLIMIT_NPROC
3202 AP_INIT_TAKE12("RLimitNPROC", set_limit_nproc,
3203   (void*)APR_OFFSETOF(core_dir_config, limit_nproc),
3204   OR_ALL, "soft/hard limits for max number of processes per uid"),
3205 #else
3206 AP_INIT_TAKE12("RLimitNPROC", no_set_limit, NULL,
3207    OR_ALL, "soft/hard limits for max number of processes per uid"),
3208 #endif
3209
3210 /* internal recursion stopper */
3211 AP_INIT_TAKE12("LimitInternalRecursion", set_recursion_limit, NULL, RSRC_CONF,
3212               "maximum recursion depth of internal redirects and subrequests"),
3213
3214 AP_INIT_TAKE1("ForceType", ap_set_string_slot_lower,
3215        (void *)APR_OFFSETOF(core_dir_config, mime_type), OR_FILEINFO,
3216      "a mime type that overrides other configured type"),
3217 AP_INIT_TAKE1("SetHandler", ap_set_string_slot_lower,
3218        (void *)APR_OFFSETOF(core_dir_config, handler), OR_FILEINFO,
3219    "a handler name that overrides any other configured handler"),
3220 AP_INIT_TAKE1("SetOutputFilter", ap_set_string_slot,
3221        (void *)APR_OFFSETOF(core_dir_config, output_filters), OR_FILEINFO,
3222    "filter (or ; delimited list of filters) to be run on the request content"),
3223 AP_INIT_TAKE1("SetInputFilter", ap_set_string_slot,
3224        (void *)APR_OFFSETOF(core_dir_config, input_filters), OR_FILEINFO,
3225    "filter (or ; delimited list of filters) to be run on the request body"),
3226 AP_INIT_ITERATE2("AddOutputFilterByType", add_ct_output_filters,
3227        (void *)APR_OFFSETOF(core_dir_config, ct_output_filters), OR_FILEINFO,
3228      "output filter name followed by one or more content-types"),
3229 AP_INIT_FLAG("AllowEncodedSlashes", set_allow2f, NULL, RSRC_CONF,
3230              "Allow URLs containing '/' encoded as '%2F'"),
3231
3232 /*
3233  * These are default configuration directives that mpms can/should
3234  * pay attention to. If an mpm wishes to use these, they should
3235  * #defined them in mpm.h.
3236  */
3237 #ifdef AP_MPM_WANT_SET_PIDFILE
3238 AP_INIT_TAKE1("PidFile",  ap_mpm_set_pidfile, NULL, RSRC_CONF,
3239               "A file for logging the server process ID"),
3240 #endif
3241 #ifdef AP_MPM_WANT_SET_SCOREBOARD
3242 AP_INIT_TAKE1("ScoreBoardFile", ap_mpm_set_scoreboard, NULL, RSRC_CONF,
3243               "A file for Apache to maintain runtime process management information"),
3244 #endif
3245 #ifdef AP_MPM_WANT_SET_LOCKFILE
3246 AP_INIT_TAKE1("LockFile",  ap_mpm_set_lockfile, NULL, RSRC_CONF,
3247               "The lockfile used when Apache needs to lock the accept() call"),
3248 #endif
3249 #ifdef AP_MPM_WANT_SET_MAX_REQUESTS
3250 AP_INIT_TAKE1("MaxRequestsPerChild", ap_mpm_set_max_requests, NULL, RSRC_CONF,
3251               "Maximum number of requests a particular child serves before dying."),
3252 #endif
3253 #ifdef AP_MPM_WANT_SET_COREDUMPDIR
3254 AP_INIT_TAKE1("CoreDumpDirectory", ap_mpm_set_coredumpdir, NULL, RSRC_CONF,
3255               "The location of the directory Apache changes to before dumping core"),
3256 #endif
3257 #ifdef AP_MPM_WANT_SET_ACCEPT_LOCK_MECH
3258 AP_INIT_TAKE1("AcceptMutex", ap_mpm_set_accept_lock_mech, NULL, RSRC_CONF,
3259               ap_valid_accept_mutex_string),
3260 #endif
3261 #ifdef AP_MPM_WANT_SET_MAX_MEM_FREE
3262 AP_INIT_TAKE1("MaxMemFree", ap_mpm_set_max_mem_free, NULL, RSRC_CONF,
3263               "Maximum number of 1k blocks a particular childs allocator may hold."),
3264 #endif
3265 { NULL }
3266 };
3267
3268 /*****************************************************************
3269  *
3270  * Core handlers for various phases of server operation...
3271  */
3272
3273 AP_DECLARE_NONSTD(int) ap_core_translate(request_rec *r)
3274 {
3275     void *sconf = r->server->module_config;
3276     core_server_config *conf = ap_get_module_config(sconf, &core_module);
3277
3278     /* XXX this seems too specific, this should probably become
3279      * some general-case test
3280      */
3281     if (r->proxyreq) {
3282         return HTTP_FORBIDDEN;
3283     }
3284     if (!r->uri || ((r->uri[0] != '/') && strcmp(r->uri, "*"))) {
3285         ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3286                      "Invalid URI in request %s", r->the_request);
3287         return HTTP_BAD_REQUEST;
3288     }
3289
3290     if (r->server->path
3291         && !strncmp(r->uri, r->server->path, r->server->pathlen)
3292         && (r->server->path[r->server->pathlen - 1] == '/'
3293             || r->uri[r->server->pathlen] == '/'
3294             || r->uri[r->server->pathlen] == '\0')) 
3295     {
3296         /* skip all leading /'s (e.g. http://localhost///foo) 
3297          * so we are looking at only the relative path.
3298          */
3299         char *path = r->uri + r->server->pathlen;
3300         while (*path == '/') {
3301             ++path;
3302         }
3303         if (apr_filepath_merge(&r->filename, conf->ap_document_root, path,
3304                                APR_FILEPATH_TRUENAME
3305                              | APR_FILEPATH_SECUREROOT, r->pool)
3306                     != APR_SUCCESS) {
3307             return HTTP_FORBIDDEN;
3308         }
3309         r->canonical_filename = r->filename;
3310     }
3311     else {
3312         /*
3313          * Make sure that we do not mess up the translation by adding two
3314          * /'s in a row.  This happens under windows when the document
3315          * root ends with a /
3316          */
3317         /* skip all leading /'s (e.g. http://localhost///foo) 
3318          * so we are looking at only the relative path.
3319          */
3320         char *path = r->uri;
3321         while (*path == '/') {
3322             ++path;
3323         }
3324         if (apr_filepath_merge(&r->filename, conf->ap_document_root, path,
3325                                APR_FILEPATH_TRUENAME
3326                              | APR_FILEPATH_SECUREROOT, r->pool)
3327                     != APR_SUCCESS) {
3328             return HTTP_FORBIDDEN;
3329         }
3330         r->canonical_filename = r->filename;
3331     }
3332
3333     return OK;
3334 }
3335
3336 /*****************************************************************
3337  *
3338  * Test the filesystem name through directory_walk and file_walk
3339  */
3340 static int core_map_to_storage(request_rec *r)
3341 {
3342     int access_status;
3343
3344     if ((access_status = ap_directory_walk(r))) {
3345         return access_status;
3346     }
3347
3348     if ((access_status = ap_file_walk(r))) {
3349         return access_status;
3350     }
3351
3352     return OK;
3353 }
3354
3355
3356 static int do_nothing(request_rec *r) { return OK; }
3357
3358
3359 static int core_override_type(request_rec *r)
3360 {
3361     core_dir_config *conf =
3362         (core_dir_config *)ap_get_module_config(r->per_dir_config,
3363                                                 &core_module);
3364
3365     /* Check for overrides with ForceType / SetHandler
3366      */
3367     if (conf->mime_type && strcmp(conf->mime_type, "none"))
3368         ap_set_content_type(r, (char*) conf->mime_type);
3369
3370     if (conf->handler && strcmp(conf->handler, "none"))
3371         r->handler = conf->handler;
3372
3373     /* Deal with the poor soul who is trying to force path_info to be
3374      * accepted within the core_handler, where they will let the subreq
3375      * address its contents.  This is toggled by the user in the very
3376      * beginning of the fixup phase, so modules should override the user's
3377      * discretion in their own module fixup phase.  It is tristate, if
3378      * the user doesn't specify, the result is 2 (which the module may
3379      * interpret to its own customary behavior.)  It won't be touched
3380      * if the value is no longer undefined (2), so any module changing
3381      * the value prior to the fixup phase OVERRIDES the user's choice.
3382      */
3383     if ((r->used_path_info == AP_REQ_DEFAULT_PATH_INFO)
3384         && (conf->accept_path_info != 3)) {
3385         r->used_path_info = conf->accept_path_info;
3386     }
3387
3388     return OK;
3389 }
3390
3391
3392
3393 static int default_handler(request_rec *r)
3394 {
3395     conn_rec *c = r->connection;
3396     apr_bucket_brigade *bb;
3397     apr_bucket *e;
3398     core_dir_config *d;
3399     int errstatus;
3400     apr_file_t *fd = NULL;
3401     apr_status_t status;
3402     /* XXX if/when somebody writes a content-md5 filter we either need to
3403      *     remove this support or coordinate when to use the filter vs.
3404      *     when to use this code
3405      *     The current choice of when to compute the md5 here matches the 1.3
3406      *     support fairly closely (unlike 1.3, we don't handle computing md5
3407      *     when the charset is translated).
3408      */
3409     int bld_content_md5;
3410
3411     d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
3412                                                 &core_module);
3413     bld_content_md5 = (d->content_md5 & 1)
3414                       && r->output_filters->frec->ftype != AP_FTYPE_RESOURCE;
3415
3416     ap_allow_standard_methods(r, MERGE_ALLOW, M_GET, M_OPTIONS, M_POST, -1);
3417
3418     /* If filters intend to consume the request body, they must
3419      * register an InputFilter to slurp the contents of the POST
3420      * data from the POST input stream.  It no longer exists when
3421      * the output filters are invoked by the default handler.
3422      */
3423     if ((errstatus = ap_discard_request_body(r)) != OK) {
3424         return errstatus;
3425     }
3426
3427     if (r->method_number == M_GET || r->method_number == M_POST) {
3428         if (r->finfo.filetype == 0) {
3429             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3430                           "File does not exist: %s", r->filename);
3431             return HTTP_NOT_FOUND;
3432         }
3433
3434         /* Don't try to serve a dir.  Some OSs do weird things with
3435          * raw I/O on a dir.
3436          */
3437         if (r->finfo.filetype == APR_DIR) {
3438             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3439                           "Attempt to serve directory: %s", r->filename);
3440             return HTTP_NOT_FOUND;
3441         }
3442
3443         if ((r->used_path_info != AP_REQ_ACCEPT_PATH_INFO) &&
3444             r->path_info && *r->path_info)
3445         {
3446             /* default to reject */
3447             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3448                           "File does not exist: %s",
3449                           apr_pstrcat(r->pool, r->filename, r->path_info, NULL));
3450             return HTTP_NOT_FOUND;
3451         }
3452
3453         /* We understood the (non-GET) method, but it might not be legal for
3454            this particular resource. Check to see if the 'deliver_script'
3455            flag is set. If so, then we go ahead and deliver the file since
3456            it isn't really content (only GET normally returns content).
3457
3458            Note: based on logic further above, the only possible non-GET
3459            method at this point is POST. In the future, we should enable
3460            script delivery for all methods.  */
3461         if (r->method_number != M_GET) {
3462             core_request_config *req_cfg;
3463
3464             req_cfg = ap_get_module_config(r->request_config, &core_module);
3465             if (!req_cfg->deliver_script) {
3466                 /* The flag hasn't been set for this request. Punt. */
3467                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3468                               "This resource does not accept the %s method.",
3469                               r->method);
3470                 return HTTP_METHOD_NOT_ALLOWED;
3471             }
3472         }
3473
3474
3475         if ((status = apr_file_open(&fd, r->filename, APR_READ | APR_BINARY
3476 #if APR_HAS_SENDFILE
3477                             | ((d->enable_sendfile == ENABLE_SENDFILE_OFF) 
3478                                                 ? 0 : APR_SENDFILE_ENABLED)
3479 #endif
3480                                     , 0, r->pool)) != APR_SUCCESS) {
3481             ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r,
3482                           "file permissions deny server access: %s", r->filename);
3483             return HTTP_FORBIDDEN;
3484         }
3485
3486         ap_update_mtime(r, r->finfo.mtime);
3487         ap_set_last_modified(r);
3488         ap_set_etag(r);
3489         apr_table_setn(r->headers_out, "Accept-Ranges", "bytes");
3490         ap_set_content_length(r, r->finfo.size);
3491         if ((errstatus = ap_meets_conditions(r)) != OK) {
3492             apr_file_close(fd);
3493             return errstatus;
3494         }
3495
3496         if (bld_content_md5) {
3497             apr_table_setn(r->headers_out, "Content-MD5",
3498                            ap_md5digest(r->pool, fd));
3499         }
3500
3501         bb = apr_brigade_create(r->pool, c->bucket_alloc);
3502 #if APR_HAS_SENDFILE && APR_HAS_LARGE_FILES
3503         if ((d->enable_sendfile != ENABLE_SENDFILE_OFF) &&
3504             (r->finfo.size > AP_MAX_SENDFILE)) {
3505             /* APR_HAS_LARGE_FILES issue; must split into mutiple buckets,
3506              * no greater than MAX(apr_size_t), and more granular than that
3507              * in case the brigade code/filters attempt to read it directly.
3508              */
3509             apr_off_t fsize = r->finfo.size;
3510             e = apr_bucket_file_create(fd, 0, AP_MAX_SENDFILE, r->pool,
3511                                        c->bucket_alloc);
3512             while (fsize > AP_MAX_SENDFILE) {
3513                 apr_bucket *ce;
3514                 apr_bucket_copy(e, &ce);
3515                 APR_BRIGADE_INSERT_TAIL(bb, ce);
3516                 e->start += AP_MAX_SENDFILE;
3517                 fsize -= AP_MAX_SENDFILE;
3518             }
3519             e->length = (apr_size_t)fsize; /* Resize just the last bucket */
3520         }
3521         else
3522 #endif
3523             e = apr_bucket_file_create(fd, 0, (apr_size_t)r->finfo.size,
3524                                        r->pool, c->bucket_alloc);
3525
3526 #if APR_HAS_MMAP
3527         if (d->enable_mmap == ENABLE_MMAP_OFF) {
3528             (void)apr_bucket_file_enable_mmap(e, 0);
3529         }
3530 #endif
3531         APR_BRIGADE_INSERT_TAIL(bb, e);
3532         e = apr_bucket_eos_create(c->bucket_alloc);
3533         APR_BRIGADE_INSERT_TAIL(bb, e);
3534
3535         return ap_pass_brigade(r->output_filters, bb);
3536     }
3537     else {              /* unusual method (not GET or POST) */
3538         if (r->method_number == M_INVALID) {
3539             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
3540                           "Invalid method in request %s", r->the_request);
3541             return HTTP_NOT_IMPLEMENTED;
3542         }
3543
3544         if (r->method_number == M_OPTIONS) {
3545             return ap_send_http_options(r);
3546         }
3547         return HTTP_METHOD_NOT_ALLOWED;
3548     }
3549 }
3550
3551 typedef struct net_time_filter_ctx {
3552     apr_socket_t *csd;
3553     int           first_line;
3554 } net_time_filter_ctx_t;
3555 static int net_time_filter(ap_filter_t *f, apr_bucket_brigade *b,
3556                            ap_input_mode_t mode, apr_read_type_e block,
3557                            apr_off_t readbytes)
3558 {
3559     net_time_filter_ctx_t *ctx = f->ctx;
3560     int keptalive = f->c->keepalive == AP_CONN_KEEPALIVE;
3561
3562     if (!ctx) {
3563         f->ctx = ctx = apr_palloc(f->r->pool, sizeof(*ctx));
3564         ctx->first_line = 1;
3565         ctx->csd = ap_get_module_config(f->c->conn_config, &core_module);        
3566     }
3567
3568     if (mode != AP_MODE_INIT && mode != AP_MODE_EATCRLF) {
3569         if (ctx->first_line) {
3570             apr_socket_timeout_set(ctx->csd, 
3571                                    keptalive
3572                                       ? f->c->base_server->keep_alive_timeout
3573                                       : f->c->base_server->timeout);
3574             ctx->first_line = 0;
3575         }
3576         else {
3577             if (keptalive) {
3578                 apr_socket_timeout_set(ctx->csd, f->c->base_server->timeout);
3579             }
3580         }
3581     }
3582     return ap_get_brigade(f->next, b, mode, block, readbytes);
3583 }
3584
3585 /**
3586  * Remove all zero length buckets from the brigade.
3587  */
3588 #define BRIGADE_NORMALIZE(b) \
3589 do { \
3590     apr_bucket *e = APR_BRIGADE_FIRST(b); \
3591     do {  \
3592         if (e->length == 0 && !APR_BUCKET_IS_METADATA(e)) { \
3593             apr_bucket *d; \
3594             d = APR_BUCKET_NEXT(e); \
3595             apr_bucket_delete(e); \
3596             e = d; \
3597         } \
3598         e = APR_BUCKET_NEXT(e); \
3599     } while (!APR_BRIGADE_EMPTY(b) && (e != APR_BRIGADE_SENTINEL(b))); \
3600 } while (0)
3601
3602 static int core_input_filter(ap_filter_t *f, apr_bucket_brigade *b,
3603                              ap_input_mode_t mode, apr_read_type_e block,
3604                              apr_off_t readbytes)
3605 {
3606     apr_bucket *e;
3607     apr_status_t rv;
3608     core_net_rec *net = f->ctx;
3609     core_ctx_t *ctx = net->in_ctx;
3610     const char *str;
3611     apr_size_t len;
3612
3613     if (mode == AP_MODE_INIT) {
3614         /*
3615          * this mode is for filters that might need to 'initialize'
3616          * a connection before reading request data from a client.
3617          * NNTP over SSL for example needs to handshake before the
3618          * server sends the welcome message.
3619          * such filters would have changed the mode before this point
3620          * is reached.  however, protocol modules such as NNTP should
3621          * not need to know anything about SSL.  given the example, if
3622          * SSL is not in the filter chain, AP_MODE_INIT is a noop.
3623          */
3624         return APR_SUCCESS;
3625     }
3626
3627     if (!ctx)
3628     {
3629         ctx = apr_pcalloc(f->c->pool, sizeof(*ctx));
3630         ctx->b = apr_brigade_create(f->c->pool, f->c->bucket_alloc);
3631
3632         /* seed the brigade with the client socket. */
3633         e = apr_bucket_socket_create(net->client_socket, f->c->bucket_alloc);
3634         APR_BRIGADE_INSERT_TAIL(ctx->b, e);
3635         net->in_ctx = ctx;
3636     }
3637     else if (APR_BRIGADE_EMPTY(ctx->b)) {
3638         return APR_EOF;
3639     }
3640
3641     /* ### This is bad. */
3642     BRIGADE_NORMALIZE(ctx->b);
3643
3644     /* check for empty brigade again *AFTER* BRIGADE_NORMALIZE()
3645      * If we have lost our socket bucket (see above), we are EOF.
3646      *
3647      * Ideally, this should be returning SUCCESS with EOS bucket, but
3648      * some higher-up APIs (spec. read_request_line via ap_rgetline)
3649      * want an error code. */
3650     if (APR_BRIGADE_EMPTY(ctx->b)) {
3651         return APR_EOF;
3652     }
3653
3654     if (mode == AP_MODE_GETLINE) {
3655         /* we are reading a single LF line, e.g. the HTTP headers */
3656         rv = apr_brigade_split_line(b, ctx->b, block, HUGE_STRING_LEN);
3657         /* We should treat EAGAIN here the same as we do for EOF (brigade is
3658          * empty).  We do this by returning whatever we have read.  This may
3659          * or may not be bogus, but is consistent (for now) with EOF logic.
3660          */
3661         if (APR_STATUS_IS_EAGAIN(rv)) {
3662             rv = APR_SUCCESS;
3663         }
3664         return rv;
3665     }
3666
3667     /* ### AP_MODE_PEEK is a horrific name for this mode because we also
3668      * eat any CRLFs that we see.  That's not the obvious intention of
3669      * this mode.  Determine whether anyone actually uses this or not. */
3670     if (mode == AP_MODE_EATCRLF) {
3671         apr_bucket *e;
3672         const char *c;
3673
3674         /* The purpose of this loop is to ignore any CRLF (or LF) at the end
3675          * of a request.  Many browsers send extra lines at the end of POST
3676          * requests.  We use the PEEK method to determine if there is more
3677          * data on the socket, so that we know if we should delay sending the
3678          * end of one request until we have served the second request in a
3679          * pipelined situation.  We don't want to actually delay sending a
3680          * response if the server finds a CRLF (or LF), becuause that doesn't
3681          * mean that there is another request, just a blank line.
3682          */
3683         while (1) {
3684             if (APR_BRIGADE_EMPTY(ctx->b))
3685                 return APR_EOF;
3686
3687             e = APR_BRIGADE_FIRST(ctx->b);
3688
3689             rv = apr_bucket_read(e, &str, &len, APR_NONBLOCK_READ);
3690
3691             if (rv != APR_SUCCESS)
3692                 return rv;
3693
3694             c = str;
3695             while (c < str + len) {
3696                 if (*c == APR_ASCII_LF)
3697                     c++;
3698                 else if (*c == APR_ASCII_CR && *(c + 1) == APR_ASCII_LF)
3699                     c += 2;
3700                 else
3701                     return APR_SUCCESS;
3702             }
3703
3704             /* If we reach here, we were a bucket just full of CRLFs, so
3705              * just toss the bucket. */
3706             /* FIXME: Is this the right thing to do in the core? */
3707             apr_bucket_delete(e);
3708         }
3709         return APR_SUCCESS;
3710     }
3711
3712     /* If mode is EXHAUSTIVE, we want to just read everything until the end
3713      * of the brigade, which in this case means the end of the socket.
3714      * To do this, we attach the brigade that has currently been setaside to
3715      * the brigade that was passed down, and send that brigade back.
3716      *
3717      * NOTE:  This is VERY dangerous to use, and should only be done with
3718      * extreme caution.  However, the Perchild MPM needs this feature
3719      * if it is ever going to work correctly again.  With this, the Perchild
3720      * MPM can easily request the socket and all data that has been read,
3721      * which means that it can pass it to the correct child process.
3722      */
3723     if (mode == AP_MODE_EXHAUSTIVE) {
3724         apr_bucket *e;
3725
3726         /* Tack on any buckets that were set aside. */
3727         APR_BRIGADE_CONCAT(b, ctx->b);
3728
3729         /* Since we've just added all potential buckets (which will most
3730          * likely simply be the socket bucket) we know this is the end,
3731          * so tack on an EOS too. */
3732         /* We have read until the brigade was empty, so we know that we
3733          * must be EOS. */
3734         e = apr_bucket_eos_create(f->c->bucket_alloc);
3735         APR_BRIGADE_INSERT_TAIL(b, e);
3736         return APR_SUCCESS;
3737     }
3738
3739     /* read up to the amount they specified. */
3740     if (mode == AP_MODE_READBYTES || mode == AP_MODE_SPECULATIVE) {
3741         apr_bucket *e;
3742         apr_bucket_brigade *newbb;
3743
3744         AP_DEBUG_ASSERT(readbytes > 0);
3745
3746         e = APR_BRIGADE_FIRST(ctx->b);
3747         rv = apr_bucket_read(e, &str, &len, block);
3748
3749         if (APR_STATUS_IS_EAGAIN(rv)) {
3750             return APR_SUCCESS;
3751         }
3752         else if (rv != APR_SUCCESS) {
3753             return rv;
3754         }
3755         else if (block == APR_BLOCK_READ && len == 0) {
3756             /* We wanted to read some bytes in blocking mode.  We read
3757              * 0 bytes.  Hence, we now assume we are EOS.
3758              *
3759              * When we are in normal mode, return an EOS bucket to the
3760              * caller.
3761              * When we are in speculative mode, leave ctx->b empty, so
3762              * that the next call returns an EOS bucket.
3763              */
3764             apr_bucket_delete(e);
3765
3766             if (mode == AP_MODE_READBYTES) {
3767                 e = apr_bucket_eos_create(f->c->bucket_alloc);
3768                 APR_BRIGADE_INSERT_TAIL(b, e);
3769             }
3770             return APR_SUCCESS;
3771         }
3772
3773         /* We can only return at most what we read. */
3774         if (len < readbytes) {
3775             readbytes = len;
3776         }
3777
3778         rv = apr_brigade_partition(ctx->b, readbytes, &e);
3779         if (rv != APR_SUCCESS) {
3780             return rv;
3781         }
3782
3783         /* Must do split before CONCAT */
3784         newbb = apr_brigade_split(ctx->b, e);
3785
3786         if (mode == AP_MODE_READBYTES) {
3787             APR_BRIGADE_CONCAT(b, ctx->b);
3788         }
3789         else if (mode == AP_MODE_SPECULATIVE) {
3790             apr_bucket *copy_bucket;
3791             APR_BRIGADE_FOREACH(e, ctx->b) {
3792                 rv = apr_bucket_copy(e, &copy_bucket);
3793                 if (rv != APR_SUCCESS) {
3794                     return rv;
3795                 }
3796                 APR_BRIGADE_INSERT_TAIL(b, copy_bucket);
3797             }
3798         }
3799
3800         /* Take what was originally there and place it back on ctx->b */
3801         APR_BRIGADE_CONCAT(ctx->b, newbb);
3802     }
3803     return APR_SUCCESS;
3804 }
3805
3806 /* Default filter.  This filter should almost always be used.  Its only job
3807  * is to send the headers if they haven't already been sent, and then send
3808  * the actual data.
3809  */
3810 #define MAX_IOVEC_TO_WRITE 16
3811
3812 /* Optional function coming from mod_logio, used for logging of output
3813  * traffic
3814  */
3815 static APR_OPTIONAL_FN_TYPE(ap_logio_add_bytes_out) *logio_add_bytes_out;
3816
3817 static apr_status_t core_output_filter(ap_filter_t *f, apr_bucket_brigade *b)
3818 {
3819     apr_status_t rv;
3820     apr_bucket_brigade *more;
3821     conn_rec *c = f->c;
3822     core_net_rec *net = f->ctx;
3823     core_output_filter_ctx_t *ctx = net->out_ctx;
3824     apr_read_type_e eblock = APR_NONBLOCK_READ;
3825     apr_pool_t *input_pool = b->p;
3826
3827     if (ctx == NULL) {
3828         ctx = apr_pcalloc(c->pool, sizeof(*ctx));
3829         net->out_ctx = ctx;
3830     }
3831
3832     /* If we have a saved brigade, concatenate the new brigade to it */
3833     if (ctx->b) {
3834         APR_BRIGADE_CONCAT(ctx->b, b);
3835         b = ctx->b;
3836         ctx->b = NULL;
3837     }
3838
3839     /* Perform multiple passes over the brigade, sending batches of output
3840        to the connection. */
3841     while (b && !APR_BRIGADE_EMPTY(b)) {
3842         apr_size_t nbytes = 0;
3843         apr_bucket *last_e = NULL; /* initialized for debugging */
3844         apr_bucket *e;
3845
3846         /* one group of iovecs per pass over the brigade */
3847         apr_size_t nvec = 0;
3848         apr_size_t nvec_trailers = 0;
3849         struct iovec vec[MAX_IOVEC_TO_WRITE];
3850         struct iovec vec_trailers[MAX_IOVEC_TO_WRITE];
3851
3852         /* one file per pass over the brigade */
3853         apr_file_t *fd = NULL;
3854         apr_size_t flen = 0;
3855         apr_off_t foffset = 0;
3856
3857         /* keep track of buckets that we've concatenated
3858          * to avoid small writes
3859          */
3860         apr_bucket *last_merged_bucket = NULL;
3861
3862         /* tail of brigade if we need another pass */
3863         more = NULL;
3864
3865         /* Iterate over the brigade: collect iovecs and/or a file */
3866         APR_BRIGADE_FOREACH(e, b) {
3867             /* keep track of the last bucket processed */
3868             last_e = e;
3869             if (APR_BUCKET_IS_EOS(e)) {
3870                 break;
3871             }
3872             if (APR_BUCKET_IS_FLUSH(e)) {
3873                 if (e != APR_BRIGADE_LAST(b)) {
3874                     more = apr_brigade_split(b, APR_BUCKET_NEXT(e));
3875                 }
3876                 break;
3877             }
3878
3879             /* It doesn't make any sense to use sendfile for a file bucket
3880              * that represents 10 bytes.
3881              */
3882             else if (APR_BUCKET_IS_FILE(e)
3883                      && (e->length >= AP_MIN_SENDFILE_BYTES)) {
3884                 apr_bucket_file *a = e->data;
3885
3886                 /* We can't handle more than one file bucket at a time
3887                  * so we split here and send the file we have already
3888                  * found.
3889                  */
3890                 if (fd) {
3891                     more = apr_brigade_split(b, e);
3892                     break;
3893                 }
3894
3895                 fd = a->fd;
3896                 flen = e->length;
3897                 foffset = e->start;
3898             }
3899             else {
3900                 const char *str;
3901                 apr_size_t n;
3902
3903                 rv = apr_bucket_read(e, &str, &n, eblock);
3904                 if (APR_STATUS_IS_EAGAIN(rv)) {
3905                     /* send what we have so far since we shouldn't expect more
3906                      * output for a while...  next time we read, block
3907                      */
3908                     more = apr_brigade_split(b, e);
3909                     eblock = APR_BLOCK_READ;
3910                     break;
3911                 }
3912                 eblock = APR_NONBLOCK_READ;
3913                 if (n) {
3914                     if (!fd) {
3915                         if (nvec == MAX_IOVEC_TO_WRITE) {
3916                             /* woah! too many. buffer them up, for use later. */
3917                             apr_bucket *temp, *next;
3918                             apr_bucket_brigade *temp_brig;
3919
3920                             if (nbytes >= AP_MIN_BYTES_TO_WRITE) {
3921                                 /* We have enough data in the iovec
3922                                  * to justify doing a writev
3923                                  */
3924                                 more = apr_brigade_split(b, e);
3925                                 break;
3926                             }
3927
3928                             /* Create a temporary brigade as a means
3929                              * of concatenating a bunch of buckets together
3930                              */
3931                             if (last_merged_bucket) {
3932                                 /* If we've concatenated together small
3933                                  * buckets already in a previous pass,
3934                                  * the initial buckets in this brigade
3935                                  * are heap buckets that may have extra
3936                                  * space left in them (because they
3937                                  * were created by apr_brigade_write()).
3938                                  * We can take advantage of this by
3939                                  * building the new temp brigade out of
3940                                  * these buckets, so that the content
3941                                  * in them doesn't have to be copied again.
3942                                  */
3943                                 apr_bucket_brigade *bb;
3944                                 bb = apr_brigade_split(b,
3945                                          APR_BUCKET_NEXT(last_merged_bucket));
3946                                 temp_brig = b;
3947                                 b = bb;
3948                             }
3949                             else {
3950                                 temp_brig = apr_brigade_create(f->c->pool,
3951                                                            f->c->bucket_alloc);
3952                             }
3953
3954                             temp = APR_BRIGADE_FIRST(b);
3955                             while (temp != e) {
3956                                 apr_bucket *d;
3957                                 rv = apr_bucket_read(temp, &str, &n, APR_BLOCK_READ);
3958                                 apr_brigade_write(temp_brig, NULL, NULL, str, n);
3959                                 d = temp;
3960                                 temp = APR_BUCKET_NEXT(temp);
3961                                 apr_bucket_delete(d);
3962                             }
3963
3964                             nvec = 0;
3965                             nbytes = 0;
3966                             temp = APR_BRIGADE_FIRST(temp_brig);
3967                             APR_BUCKET_REMOVE(temp);
3968                             APR_BRIGADE_INSERT_HEAD(b, temp);
3969                             apr_bucket_read(temp, &str, &n, APR_BLOCK_READ);
3970                             vec[nvec].iov_base = (char*) str;
3971                             vec[nvec].iov_len = n;
3972                             nvec++;
3973
3974                             /* Just in case the temporary brigade has
3975                              * multiple buckets, recover the rest of
3976                              * them and put them in the brigade that
3977                              * we're sending.
3978                              */
3979                             for (next = APR_BRIGADE_FIRST(temp_brig);
3980                                  next != APR_BRIGADE_SENTINEL(temp_brig);
3981                                  next = APR_BRIGADE_FIRST(temp_brig)) {
3982                                 APR_BUCKET_REMOVE(next);
3983                                 APR_BUCKET_INSERT_AFTER(temp, next);
3984                                 temp = next;
3985                                 apr_bucket_read(next, &str, &n,
3986                                                 APR_BLOCK_READ);
3987                                 vec[nvec].iov_base = (char*) str;
3988                                 vec[nvec].iov_len = n;
3989                                 nvec++;
3990                             }
3991
3992                             apr_brigade_destroy(temp_brig);
3993
3994                             last_merged_bucket = temp;
3995                             e = temp;
3996                             last_e = e;
3997                         }
3998                         else {
3999                             vec[nvec].iov_base = (char*) str;
4000                             vec[nvec].iov_len = n;
4001                             nvec++;
4002                         }
4003                     }
4004                     else {
4005                         /* The bucket is a trailer to a file bucket */
4006
4007                         if (nvec_trailers == MAX_IOVEC_TO_WRITE) {
4008                             /* woah! too many. stop now. */
4009                             more = apr_brigade_split(b, e);
4010                             break;
4011                         }
4012
4013                         vec_trailers[nvec_trailers].iov_base = (char*) str;
4014                         vec_trailers[nvec_trailers].iov_len = n;
4015                         nvec_trailers++;
4016                     }
4017
4018                     nbytes += n;
4019                 }
4020             }
4021         }
4022
4023
4024         /* Completed iterating over the brigade, now determine if we want
4025          * to buffer the brigade or send the brigade out on the network.
4026          *
4027          * Save if we haven't accumulated enough bytes to send, and:
4028          *
4029          *   1) we didn't see a file, we don't have more passes over the
4030          *      brigade to perform,  AND we didn't stop at a FLUSH bucket.
4031          *      (IOW, we will save plain old bytes such as HTTP headers)
4032          * or
4033          *   2) we hit the EOS and have a keep-alive connection
4034          *      (IOW, this response is a bit more complex, but we save it
4035          *       with the hope of concatenating with another response)
4036          */
4037         if (nbytes + flen < AP_MIN_BYTES_TO_WRITE
4038             && ((!fd && !more && !APR_BUCKET_IS_FLUSH(last_e))
4039                 || (APR_BUCKET_IS_EOS(last_e)
4040                     && c->keepalive == AP_CONN_KEEPALIVE))) {
4041
4042             /* NEVER save an EOS in here.  If we are saving a brigade with
4043              * an EOS bucket, then we are doing keepalive connections, and
4044              * we want to process to second request fully.
4045              */
4046             if (APR_BUCKET_IS_EOS(last_e)) {
4047                 apr_bucket *bucket;
4048                 int file_bucket_saved = 0;
4049                 apr_bucket_delete(last_e);
4050                 for (bucket = APR_BRIGADE_FIRST(b);
4051                      bucket != APR_BRIGADE_SENTINEL(b);
4052                      bucket = APR_BUCKET_NEXT(bucket)) {
4053
4054                     /* Do a read on each bucket to pull in the
4055                      * data from pipe and socket buckets, so
4056                      * that we don't leave their file descriptors
4057                      * open indefinitely.  Do the same for file
4058                      * buckets, with one exception: allow the
4059                      * first file bucket in the brigade to remain
4060                      * a file bucket, so that we don't end up
4061                      * doing an mmap+memcpy every time a client
4062                      * requests a <8KB file over a keepalive
4063                      * connection.
4064                      */
4065                     if (APR_BUCKET_IS_FILE(bucket) && !file_bucket_saved) {
4066                         file_bucket_saved = 1;
4067                     }
4068                     else {
4069                         const char *buf;
4070                         apr_size_t len = 0;
4071                         rv = apr_bucket_read(bucket, &buf, &len,
4072                                              APR_BLOCK_READ);
4073                         if (rv != APR_SUCCESS) {
4074                             ap_log_error(APLOG_MARK, APLOG_ERR, rv,
4075                                          c->base_server, "core_output_filter:"
4076                                          " Error reading from bucket.");
4077                             return HTTP_INTERNAL_SERVER_ERROR;
4078                         }
4079                     }
4080                 }
4081             }
4082             if (!ctx->deferred_write_pool) {
4083                 apr_pool_create(&ctx->deferred_write_pool, c->pool);
4084             }
4085             ap_save_brigade(f, &ctx->b, &b, ctx->deferred_write_pool);
4086
4087             return APR_SUCCESS;
4088         }
4089
4090         if (fd) {
4091             apr_hdtr_t hdtr;
4092             apr_size_t bytes_sent;
4093
4094 #if APR_HAS_SENDFILE
4095             apr_int32_t flags = 0;
4096 #endif
4097
4098             memset(&hdtr, '\0', sizeof(hdtr));
4099             if (nvec) {
4100                 hdtr.numheaders = nvec;
4101                 hdtr.headers = vec;
4102             }
4103
4104             if (nvec_trailers) {
4105                 hdtr.numtrailers = nvec_trailers;
4106                 hdtr.trailers = vec_trailers;
4107             }
4108
4109 #if APR_HAS_SENDFILE
4110             if (apr_file_flags_get(fd) & APR_SENDFILE_ENABLED) {
4111
4112                 if (c->keepalive == AP_CONN_CLOSE && APR_BUCKET_IS_EOS(last_e)) {
4113                     /* Prepare the socket to be reused */
4114                     flags |= APR_SENDFILE_DISCONNECT_SOCKET;
4115                 }
4116
4117                 rv = sendfile_it_all(net,      /* the network information   */
4118                                      fd,       /* the file to send          */
4119                                      &hdtr,    /* header and trailer iovecs */
4120                                      foffset,  /* offset in the file to begin
4121                                                   sending from              */
4122                                      flen,     /* length of file            */
4123                                      nbytes + flen, /* total length including
4124                                                        headers              */
4125                                      &bytes_sent,   /* how many bytes were
4126                                                        sent                 */
4127                                      flags);   /* apr_sendfile flags        */
4128
4129                 if (logio_add_bytes_out && bytes_sent > 0)
4130                     logio_add_bytes_out(c, bytes_sent);
4131             }
4132             else
4133 #endif
4134             {
4135                 rv = emulate_sendfile(net, fd, &hdtr, foffset, flen,
4136                                       &bytes_sent);
4137
4138                 if (logio_add_bytes_out && bytes_sent > 0)
4139                     logio_add_bytes_out(c, bytes_sent);
4140             }
4141
4142             fd = NULL;
4143         }
4144         else {
4145             apr_size_t bytes_sent;
4146
4147             rv = writev_it_all(net->client_socket,
4148                                vec, nvec,
4149                                nbytes, &bytes_sent);
4150
4151             if (logio_add_bytes_out && bytes_sent > 0)
4152                 logio_add_bytes_out(c, bytes_sent);
4153         }
4154
4155         apr_brigade_destroy(b);
4156         
4157         /* drive cleanups for resources which were set aside 
4158          * this may occur before or after termination of the request which
4159          * created the resource
4160          */
4161         if (ctx->deferred_write_pool) {
4162             if (more && more->p == ctx->deferred_write_pool) {
4163                 /* "more" belongs to the deferred_write_pool,
4164                  * which is about to be cleared.
4165                  */
4166                 if (APR_BRIGADE_EMPTY(more)) {
4167                     more = NULL;
4168                 }
4169                 else {
4170                     /* uh oh... change more's lifetime 
4171                      * to the input brigade's lifetime 
4172                      */
4173                     apr_bucket_brigade *tmp_more = more;
4174                     more = NULL;
4175                     ap_save_brigade(f, &more, &tmp_more, input_pool);
4176                 }
4177             }
4178             apr_pool_clear(ctx->deferred_write_pool);  
4179         }
4180
4181         if (rv != APR_SUCCESS) {
4182             ap_log_error(APLOG_MARK, APLOG_INFO, rv, c->base_server,
4183                          "core_output_filter: writing data to the network");
4184
4185             if (more)
4186                 apr_brigade_destroy(more);
4187
4188             /* No need to check for SUCCESS, we did that above. */
4189             if (!APR_STATUS_IS_EAGAIN(rv)) {
4190                 c->aborted = 1;
4191             }
4192
4193             /* The client has aborted, but the request was successful. We
4194              * will report success, and leave it to the access and error
4195              * logs to note that the connection was aborted.
4196              */
4197             return APR_SUCCESS;
4198         }
4199
4200         b = more;
4201         more = NULL;
4202     }  /* end while () */
4203
4204     return APR_SUCCESS;
4205 }
4206
4207 static int core_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
4208 {
4209     logio_add_bytes_out = APR_RETRIEVE_OPTIONAL_FN(ap_logio_add_bytes_out);
4210     ident_lookup = APR_RETRIEVE_OPTIONAL_FN(ap_ident_lookup);
4211
4212     ap_set_version(pconf);
4213     ap_setup_make_content_type(pconf);
4214     return OK;
4215 }
4216
4217 static void core_insert_filter(request_rec *r)
4218 {
4219     core_dir_config *conf = (core_dir_config *)
4220                             ap_get_module_config(r->per_dir_config,
4221                                                  &core_module);
4222     const char *filter, *filters = conf->output_filters;
4223
4224     if (filters) {
4225         while (*filters && (filter = ap_getword(r->pool, &filters, ';'))) {
4226             ap_add_output_filter(filter, NULL, r, r->connection);
4227         }
4228     }
4229
4230     filters = conf->input_filters;
4231     if (filters) {
4232         while (*filters && (filter = ap_getword(r->pool, &filters, ';'))) {
4233             ap_add_input_filter(filter, NULL, r, r->connection);
4234         }
4235     }
4236 }
4237
4238 static apr_size_t num_request_notes = AP_NUM_STD_NOTES;
4239
4240 static apr_status_t reset_request_notes(void *dummy)
4241 {
4242     num_request_notes = AP_NUM_STD_NOTES;
4243     return APR_SUCCESS;
4244 }
4245
4246 AP_DECLARE(apr_size_t) ap_register_request_note(void)
4247 {
4248     apr_pool_cleanup_register(apr_hook_global_pool, NULL, reset_request_notes,
4249                               apr_pool_cleanup_null);
4250     return num_request_notes++;
4251 }
4252
4253 AP_DECLARE(void **) ap_get_request_note(request_rec *r, apr_size_t note_num)
4254 {
4255     core_request_config *req_cfg;
4256
4257     if (note_num >= num_request_notes) {
4258         return NULL;
4259     }
4260
4261     req_cfg = (core_request_config *)
4262         ap_get_module_config(r->request_config, &core_module);
4263
4264     if (!req_cfg) {
4265         return NULL;
4266     }
4267
4268     return &(req_cfg->notes[note_num]);
4269 }
4270
4271 static int core_create_req(request_rec *r)
4272 {
4273     /* Alloc the config struct and the array of request notes in
4274      * a single block for efficiency
4275      */
4276     core_request_config *req_cfg;
4277
4278     req_cfg = apr_pcalloc(r->pool, sizeof(core_request_config) +
4279                           sizeof(void *) * num_request_notes);
4280     req_cfg->notes = (void **)((char *)req_cfg + sizeof(core_request_config));
4281
4282     /* ### temporarily enable script delivery as the default */
4283     req_cfg->deliver_script = 1;
4284
4285     if (r->main) {
4286         core_request_config *main_req_cfg = (core_request_config *)
4287             ap_get_module_config(r->main->request_config, &core_module);
4288         req_cfg->bb = main_req_cfg->bb;
4289     }
4290     else {
4291         req_cfg->bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
4292         if (!r->prev) {
4293             ap_add_input_filter_handle(ap_net_time_filter_handle,
4294                                        NULL, r, r->connection);
4295         }
4296     }
4297
4298     ap_set_module_config(r->request_config, &core_module, req_cfg);
4299
4300     /* Begin by presuming any module can make its own path_info assumptions,
4301      * until some module interjects and changes the value.
4302      */
4303     r->used_path_info = AP_REQ_DEFAULT_PATH_INFO;
4304
4305     return OK;
4306 }
4307
4308 static int core_create_proxy_req(request_rec *r, request_rec *pr)
4309 {
4310     return core_create_req(pr);
4311 }
4312
4313 static conn_rec *core_create_conn(apr_pool_t *ptrans, server_rec *server,
4314                                   apr_socket_t *csd, long id, void *sbh,
4315                                   apr_bucket_alloc_t *alloc)
4316 {
4317     apr_status_t rv;
4318     conn_rec *c = (conn_rec *) apr_pcalloc(ptrans, sizeof(conn_rec));
4319
4320     c->sbh = sbh;
4321     (void)ap_update_child_status(c->sbh, SERVER_BUSY_READ, (request_rec *)NULL);
4322
4323     /* Got a connection structure, so initialize what fields we can
4324      * (the rest are zeroed out by pcalloc).
4325      */
4326     c->conn_config = ap_create_conn_config(ptrans);
4327     c->notes = apr_table_make(ptrans, 5);
4328
4329     c->pool = ptrans;
4330     if ((rv = apr_socket_addr_get(&c->local_addr, APR_LOCAL, csd))
4331         != APR_SUCCESS) {
4332         ap_log_error(APLOG_MARK, APLOG_INFO, rv, server,
4333                      "apr_socket_addr_get(APR_LOCAL)");
4334         apr_socket_close(csd);
4335         return NULL;
4336     }
4337
4338     apr_sockaddr_ip_get(&c->local_ip, c->local_addr);
4339     if ((rv = apr_socket_addr_get(&c->remote_addr, APR_REMOTE, csd))
4340         != APR_SUCCESS) {
4341         ap_log_error(APLOG_MARK, APLOG_INFO, rv, server,
4342                      "apr_socket_addr_get(APR_REMOTE)");
4343         apr_socket_close(csd);
4344         return NULL;
4345     }
4346
4347     apr_sockaddr_ip_get(&c->remote_ip, c->remote_addr);
4348     c->base_server = server;
4349
4350     c->id = id;
4351     c->bucket_alloc = alloc;
4352
4353     return c;
4354 }
4355
4356 static int core_pre_connection(conn_rec *c, void *csd)
4357 {
4358     core_net_rec *net = apr_palloc(c->pool, sizeof(*net));
4359
4360 #ifdef AP_MPM_DISABLE_NAGLE_ACCEPTED_SOCK
4361     /* BillS says perhaps this should be moved to the MPMs. Some OSes
4362      * allow listening socket attributes to be inherited by the
4363      * accept sockets which means this call only needs to be made
4364      * once on the listener
4365      */
4366     ap_sock_disable_nagle(csd);
4367 #endif
4368     net->c = c;
4369     net->in_ctx = NULL;
4370     net->out_ctx = NULL;
4371     net->client_socket = csd;
4372
4373     ap_set_module_config(net->c->conn_config, &core_module, csd);
4374     ap_add_input_filter_handle(ap_core_input_filter_handle, net, NULL, net->c);
4375     ap_add_output_filter_handle(ap_core_output_filter_handle, net, NULL, net->c);
4376     return DONE;
4377 }
4378
4379 static void register_hooks(apr_pool_t *p)
4380 {
4381     /* create_connection and install_transport_filters are
4382      * hooks that should always be APR_HOOK_REALLY_LAST to give other
4383      * modules the opportunity to install alternate network transports
4384      * and stop other functions from being run.
4385      */
4386     ap_hook_create_connection(core_create_conn, NULL, NULL,
4387                               APR_HOOK_REALLY_LAST);
4388     ap_hook_pre_connection(core_pre_connection, NULL, NULL,
4389                            APR_HOOK_REALLY_LAST);
4390
4391     ap_hook_post_config(core_post_config,NULL,NULL,APR_HOOK_REALLY_FIRST);
4392     ap_hook_translate_name(ap_core_translate,NULL,NULL,APR_HOOK_REALLY_LAST);
4393     ap_hook_map_to_storage(core_map_to_storage,NULL,NULL,APR_HOOK_REALLY_LAST);
4394     ap_hook_open_logs(ap_open_logs,NULL,NULL,APR_HOOK_REALLY_FIRST);
4395     ap_hook_handler(default_handler,NULL,NULL,APR_HOOK_REALLY_LAST);
4396     /* FIXME: I suspect we can eliminate the need for these do_nothings - Ben */
4397     ap_hook_type_checker(do_nothing,NULL,NULL,APR_HOOK_REALLY_LAST);
4398     ap_hook_fixups(core_override_type,NULL,NULL,APR_HOOK_REALLY_FIRST);
4399     ap_hook_access_checker(do_nothing,NULL,NULL,APR_HOOK_REALLY_LAST);
4400     ap_hook_create_request(core_create_req, NULL, NULL, APR_HOOK_MIDDLE);
4401     APR_OPTIONAL_HOOK(proxy, create_req, core_create_proxy_req, NULL, NULL,
4402                       APR_HOOK_MIDDLE);
4403     ap_hook_pre_mpm(ap_create_scoreboard, NULL, NULL, APR_HOOK_MIDDLE);
4404
4405     /* register the core's insert_filter hook and register core-provided
4406      * filters
4407      */
4408     ap_hook_insert_filter(core_insert_filter, NULL, NULL, APR_HOOK_MIDDLE);
4409
4410     ap_core_input_filter_handle =
4411         ap_register_input_filter("CORE_IN", core_input_filter,
4412                                  NULL, AP_FTYPE_NETWORK);
4413     ap_net_time_filter_handle =
4414         ap_register_input_filter("NET_TIME", net_time_filter,
4415                                  NULL, AP_FTYPE_PROTOCOL);
4416     ap_content_length_filter_handle =
4417         ap_register_output_filter("CONTENT_LENGTH", ap_content_length_filter,
4418                                   NULL, AP_FTYPE_PROTOCOL);
4419     ap_core_output_filter_handle =
4420         ap_register_output_filter("CORE", core_output_filter,
4421                                   NULL, AP_FTYPE_NETWORK);
4422     ap_subreq_core_filter_handle =
4423         ap_register_output_filter("SUBREQ_CORE", ap_sub_req_output_filter,
4424                                   NULL, AP_FTYPE_CONTENT_SET);
4425     ap_old_write_func =
4426         ap_register_output_filter("OLD_WRITE", ap_old_write_filter,
4427                                   NULL, AP_FTYPE_RESOURCE - 10);
4428 }
4429
4430 AP_DECLARE_DATA module core_module = {
4431     STANDARD20_MODULE_STUFF,
4432     create_core_dir_config,       /* create per-directory config structure */
4433     merge_core_dir_configs,       /* merge per-directory config structures */
4434     create_core_server_config,    /* create per-server config structure */
4435     merge_core_server_configs,    /* merge per-server config structures */
4436     core_cmds,                    /* command apr_table_t */
4437     register_hooks                /* register hooks */
4438 };
4439