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