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