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