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