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