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