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