]> granicus.if.org Git - apache/blob - modules/http/http_core.c
126920f95ca3cba9b2301b34cba494e5800a0e4d
[apache] / modules / http / http_core.c
1 /* ====================================================================
2  * Copyright (c) 1995-2000 The Apache Software Foundation.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer. 
10  *
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in
13  *    the documentation and/or other materials provided with the
14  *    distribution.
15  *
16  * 3. All advertising materials mentioning features or use of this
17  *    software must display the following acknowledgment:
18  *    "This product includes software developed by the Apache Software Foundation
19  *    for use in the Apache HTTP server project (http://www.apache.org/)."
20  *
21  * 4. The names "Apache Server" and "Apache Software Foundation" must not be used to
22  *    endorse or promote products derived from this software without
23  *    prior written permission. For written permission, please contact
24  *    apache@apache.org.
25  *
26  * 5. Products derived from this software may not be called "Apache"
27  *    nor may "Apache" appear in their names without prior written
28  *    permission of the Apache Software Foundation.
29  *
30  * 6. Redistributions of any form whatsoever must retain the following
31  *    acknowledgment:
32  *    "This product includes software developed by the Apache Software Foundation
33  *    for use in the Apache HTTP server project (http://www.apache.org/)."
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE Apache Software Foundation ``AS IS'' AND ANY
36  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
38  * PURPOSE ARE 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
41  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
42  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
43  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
44  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
46  * OF THE POSSIBILITY OF SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation and was originally based
51  * on public domain software written at the National Center for
52  * Supercomputing Applications, University of Illinois, Urbana-Champaign.
53  * For more information on the Apache Software Foundation and the Apache HTTP server
54  * project, please see <http://www.apache.org/>.
55  *
56  */
57
58 #define CORE_PRIVATE
59 #include "ap_config.h"
60 #include "apr_lib.h"
61 #include "httpd.h"
62 #include "http_config.h"
63 #include "http_core.h"
64 #include "http_protocol.h"      /* For index_of_response().  Grump. */
65 #include "http_request.h"
66 #include "http_vhost.h"
67 #include "http_main.h"          /* For the default_handler below... */
68 #include "http_log.h"
69 #include "rfc1413.h"
70 #include "util_md5.h"
71 #include "apr_fnmatch.h"
72 #include "http_connection.h"
73
74 /* Allow Apache to use ap_mmap */
75 #ifdef USE_MMAP_FILES
76 #include "apr_mmap.h"
77
78 /* mmap support for static files based on ideas from John Heidemann's
79  * patch against 1.0.5.  See
80  * <http://www.isi.edu/~johnh/SOFTWARE/APACHE/index.html>.
81  */
82
83 /* Files have to be at least this big before they're mmap()d.  This is to deal
84  * with systems where the expense of doing an mmap() and an munmap() outweighs
85  * the benefit for small files.  It shouldn't be set lower than 1.
86  */
87 #ifndef MMAP_THRESHOLD
88   #ifdef SUNOS4
89   #define MMAP_THRESHOLD                (8*1024)
90   #else
91   #define MMAP_THRESHOLD                1
92   #endif /* SUNOS4 */
93 #endif /* MMAP_THRESHOLD */
94 #ifndef MMAP_LIMIT
95 #define MMAP_LIMIT              (4*1024*1024)
96 #endif
97 #endif /* USE_MMAP_FILES */
98
99 /* Server core module... This module provides support for really basic
100  * server operations, including options and commands which control the
101  * operation of other modules.  Consider this the bureaucracy module.
102  *
103  * The core module also defines handlers, etc., do handle just enough
104  * to allow a server with the core module ONLY to actually serve documents
105  * (though it slaps DefaultType on all of 'em); this was useful in testing,
106  * but may not be worth preserving.
107  *
108  * This file could almost be mod_core.c, except for the stuff which affects
109  * the http_conf_globals.
110  */
111
112 static void *create_core_dir_config(ap_context_t *a, char *dir)
113 {
114     core_dir_config *conf;
115
116     conf = (core_dir_config *)ap_pcalloc(a, sizeof(core_dir_config));
117     if (!dir || dir[strlen(dir) - 1] == '/') {
118         conf->d = dir;
119     }
120     else if (strncmp(dir, "proxy:", 6) == 0) {
121         conf->d = ap_pstrdup(a, dir);
122     }
123     else {
124         conf->d = ap_pstrcat(a, dir, "/", NULL);
125     }
126     conf->d_is_fnmatch = conf->d ? (ap_is_fnmatch(conf->d) != 0) : 0;
127     conf->d_components = conf->d ? ap_count_dirs(conf->d) : 0;
128
129     conf->opts = dir ? OPT_UNSET : OPT_UNSET|OPT_ALL;
130     conf->opts_add = conf->opts_remove = OPT_NONE;
131     conf->override = dir ? OR_UNSET : OR_UNSET|OR_ALL;
132
133     conf->content_md5 = 2;
134
135     conf->use_canonical_name = USE_CANONICAL_NAME_UNSET;
136
137     conf->hostname_lookups = HOSTNAME_LOOKUP_UNSET;
138     conf->do_rfc1413 = DEFAULT_RFC1413 | 2; /* set bit 1 to indicate default */
139     conf->satisfy = SATISFY_NOSPEC;
140
141     conf->limit_req_body = 0;
142     conf->sec = ap_make_array(a, 2, sizeof(void *));
143 #ifdef WIN32
144     conf->script_interpreter_source = INTERPRETER_SOURCE_UNSET;
145 #endif
146
147     conf->server_signature = srv_sig_unset;
148
149     return (void *)conf;
150 }
151
152 static void *merge_core_dir_configs(ap_context_t *a, void *basev, void *newv)
153 {
154     core_dir_config *base = (core_dir_config *)basev;
155     core_dir_config *new = (core_dir_config *)newv;
156     core_dir_config *conf;
157     int i;
158   
159     conf = (core_dir_config *)ap_palloc(a, sizeof(core_dir_config));
160     memcpy((char *)conf, (const char *)base, sizeof(core_dir_config));
161     if (base->response_code_strings) {
162         conf->response_code_strings =
163             ap_palloc(a, sizeof(*conf->response_code_strings)
164                       * RESPONSE_CODES);
165         memcpy(conf->response_code_strings, base->response_code_strings,
166                sizeof(*conf->response_code_strings) * RESPONSE_CODES);
167     }
168     
169     conf->d = new->d;
170     conf->d_is_fnmatch = new->d_is_fnmatch;
171     conf->d_components = new->d_components;
172     conf->r = new->r;
173     
174     if (new->opts & OPT_UNSET) {
175         /* there was no explicit setting of new->opts, so we merge
176          * preserve the invariant (opts_add & opts_remove) == 0
177          */
178         conf->opts_add = (conf->opts_add & ~new->opts_remove) | new->opts_add;
179         conf->opts_remove = (conf->opts_remove & ~new->opts_add)
180                             | new->opts_remove;
181         conf->opts = (conf->opts & ~conf->opts_remove) | conf->opts_add;
182         if ((base->opts & OPT_INCNOEXEC) && (new->opts & OPT_INCLUDES)) {
183             conf->opts = (conf->opts & ~OPT_INCNOEXEC) | OPT_INCLUDES;
184         }
185     }
186     else {
187         /* otherwise we just copy, because an explicit opts setting
188          * overrides all earlier +/- modifiers
189          */
190         conf->opts = new->opts;
191         conf->opts_add = new->opts_add;
192         conf->opts_remove = new->opts_remove;
193     }
194
195     if (!(new->override & OR_UNSET)) {
196         conf->override = new->override;
197     }
198     if (new->ap_default_type) {
199         conf->ap_default_type = new->ap_default_type;
200     }
201     
202     if (new->ap_auth_type) {
203         conf->ap_auth_type = new->ap_auth_type;
204     }
205     if (new->ap_auth_name) {
206         conf->ap_auth_name = new->ap_auth_name;
207     }
208     if (new->ap_requires) {
209         conf->ap_requires = new->ap_requires;
210     }
211
212     if (new->response_code_strings) {
213         if (conf->response_code_strings == NULL) {
214             conf->response_code_strings = ap_palloc(a,
215                 sizeof(*conf->response_code_strings) * RESPONSE_CODES);
216             memcpy(conf->response_code_strings, new->response_code_strings,
217                    sizeof(*conf->response_code_strings) * RESPONSE_CODES);
218         }
219         else {
220             for (i = 0; i < RESPONSE_CODES; ++i) {
221                 if (new->response_code_strings[i] != NULL) {
222                     conf->response_code_strings[i]
223                         = new->response_code_strings[i];
224                 }
225             }
226         }
227     }
228     if (new->hostname_lookups != HOSTNAME_LOOKUP_UNSET) {
229         conf->hostname_lookups = new->hostname_lookups;
230     }
231     if ((new->do_rfc1413 & 2) == 0) {
232         conf->do_rfc1413 = new->do_rfc1413;
233     }
234     if ((new->content_md5 & 2) == 0) {
235         conf->content_md5 = new->content_md5;
236     }
237     if (new->use_canonical_name != USE_CANONICAL_NAME_UNSET) {
238         conf->use_canonical_name = new->use_canonical_name;
239     }
240
241     if (new->limit_req_body) {
242         conf->limit_req_body = new->limit_req_body;
243     }
244     conf->sec = ap_append_arrays(a, base->sec, new->sec);
245
246     if (new->satisfy != SATISFY_NOSPEC) {
247         conf->satisfy = new->satisfy;
248     }
249
250 #ifdef WIN32
251     if (new->script_interpreter_source != INTERPRETER_SOURCE_UNSET) {
252         conf->script_interpreter_source = new->script_interpreter_source;
253     }
254 #endif
255
256     if (new->server_signature != srv_sig_unset) {
257         conf->server_signature = new->server_signature;
258     }
259
260     return (void*)conf;
261 }
262
263 static void *create_core_server_config(ap_context_t *a, server_rec *s)
264 {
265     core_server_config *conf;
266     int is_virtual = s->is_virtual;
267   
268     conf = (core_server_config *)ap_pcalloc(a, sizeof(core_server_config));
269 #ifdef GPROF
270     conf->gprof_dir = NULL;
271 #endif
272     conf->access_name = is_virtual ? NULL : DEFAULT_ACCESS_FNAME;
273     conf->ap_document_root = is_virtual ? NULL : DOCUMENT_LOCATION;
274     conf->sec = ap_make_array(a, 40, sizeof(void *));
275     conf->sec_url = ap_make_array(a, 40, sizeof(void *));
276     
277     return (void *)conf;
278 }
279
280 static void *merge_core_server_configs(ap_context_t *p, void *basev, void *virtv)
281 {
282     core_server_config *base = (core_server_config *)basev;
283     core_server_config *virt = (core_server_config *)virtv;
284     core_server_config *conf;
285
286     conf = (core_server_config *)ap_pcalloc(p, sizeof(core_server_config));
287     *conf = *virt;
288     if (!conf->access_name) {
289         conf->access_name = base->access_name;
290     }
291     if (!conf->ap_document_root) {
292         conf->ap_document_root = base->ap_document_root;
293     }
294     conf->sec = ap_append_arrays(p, base->sec, virt->sec);
295     conf->sec_url = ap_append_arrays(p, base->sec_url, virt->sec_url);
296
297     return conf;
298 }
299
300 /* Add per-directory configuration entry (for <directory> section);
301  * these are part of the core server config.
302  */
303
304 CORE_EXPORT(void) ap_add_per_dir_conf(server_rec *s, void *dir_config)
305 {
306     core_server_config *sconf = ap_get_module_config(s->module_config,
307                                                      &core_module);
308     void **new_space = (void **)ap_push_array(sconf->sec);
309     
310     *new_space = dir_config;
311 }
312
313 CORE_EXPORT(void) ap_add_per_url_conf(server_rec *s, void *url_config)
314 {
315     core_server_config *sconf = ap_get_module_config(s->module_config,
316                                                      &core_module);
317     void **new_space = (void **)ap_push_array(sconf->sec_url);
318     
319     *new_space = url_config;
320 }
321
322 CORE_EXPORT(void) ap_add_file_conf(core_dir_config *conf, void *url_config)
323 {
324     void **new_space = (void **)ap_push_array(conf->sec);
325     
326     *new_space = url_config;
327 }
328
329 /* core_reorder_directories reorders the directory sections such that the
330  * 1-component sections come first, then the 2-component, and so on, finally
331  * followed by the "special" sections.  A section is "special" if it's a regex,
332  * or if it doesn't start with / -- consider proxy: matching.  All movements
333  * are in-order to preserve the ordering of the sections from the config files.
334  * See directory_walk().
335  */
336
337 #ifdef HAVE_DRIVE_LETTERS
338 #define IS_SPECIAL(entry_core)  \
339     ((entry_core)->r != NULL \
340         || ((entry_core)->d[0] != '/' && (entry_core)->d[1] != ':'))
341 #else
342 #define IS_SPECIAL(entry_core)  \
343     ((entry_core)->r != NULL || (entry_core)->d[0] != '/')
344 #endif
345
346 /* We need to do a stable sort, qsort isn't stable.  So to make it stable
347  * we'll be maintaining the original index into the list, and using it
348  * as the minor key during sorting.  The major key is the number of
349  * components (where a "special" section has infinite components).
350  */
351 struct reorder_sort_rec {
352     void *elt;
353     int orig_index;
354 };
355
356 static int reorder_sorter(const void *va, const void *vb)
357 {
358     const struct reorder_sort_rec *a = va;
359     const struct reorder_sort_rec *b = vb;
360     core_dir_config *core_a;
361     core_dir_config *core_b;
362
363     core_a = (core_dir_config *)ap_get_module_config(a->elt, &core_module);
364     core_b = (core_dir_config *)ap_get_module_config(b->elt, &core_module);
365     if (IS_SPECIAL(core_a)) {
366         if (!IS_SPECIAL(core_b)) {
367             return 1;
368         }
369     }
370     else if (IS_SPECIAL(core_b)) {
371         return -1;
372     }
373     else {
374         /* we know they're both not special */
375         if (core_a->d_components < core_b->d_components) {
376             return -1;
377         }
378         else if (core_a->d_components > core_b->d_components) {
379             return 1;
380         }
381     }
382     /* Either they're both special, or they're both not special and have the
383      * same number of components.  In any event, we now have to compare
384      * the minor key. */
385     return a->orig_index - b->orig_index;
386 }
387
388 void ap_core_reorder_directories(ap_context_t *p, server_rec *s)
389 {
390     core_server_config *sconf;
391     ap_array_header_t *sec;
392     struct reorder_sort_rec *sortbin;
393     int nelts;
394     void **elts;
395     int i;
396     ap_context_t *tmp;
397
398     sconf = ap_get_module_config(s->module_config, &core_module);
399     sec = sconf->sec;
400     nelts = sec->nelts;
401     elts = (void **)sec->elts;
402
403     /* we have to allocate tmp space to do a stable sort */
404     ap_create_context(&tmp, p);
405     sortbin = ap_palloc(tmp, sec->nelts * sizeof(*sortbin));
406     for (i = 0; i < nelts; ++i) {
407         sortbin[i].orig_index = i;
408         sortbin[i].elt = elts[i];
409     }
410
411     qsort(sortbin, nelts, sizeof(*sortbin), reorder_sorter);
412
413     /* and now copy back to the original array */
414     for (i = 0; i < nelts; ++i) {
415       elts[i] = sortbin[i].elt;
416     }
417
418     ap_destroy_pool(tmp);
419 }
420
421 /*****************************************************************
422  *
423  * There are some elements of the core config structures in which
424  * other modules have a legitimate interest (this is ugly, but necessary
425  * to preserve NCSA back-compatibility).  So, we have a bunch of accessors
426  * here...
427  */
428
429 API_EXPORT(int) ap_allow_options(request_rec *r)
430 {
431     core_dir_config *conf = 
432       (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module); 
433
434     return conf->opts; 
435
436
437 API_EXPORT(int) ap_allow_overrides(request_rec *r) 
438
439     core_dir_config *conf;
440     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
441                                                    &core_module); 
442
443     return conf->override; 
444
445
446 API_EXPORT(const char *) ap_auth_type(request_rec *r)
447 {
448     core_dir_config *conf;
449
450     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
451                                                    &core_module); 
452     return conf->ap_auth_type;
453 }
454
455 API_EXPORT(const char *) ap_auth_name(request_rec *r)
456 {
457     core_dir_config *conf;
458
459     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
460                                                    &core_module); 
461     return conf->ap_auth_name;
462 }
463
464 API_EXPORT(const char *) ap_default_type(request_rec *r)
465 {
466     core_dir_config *conf;
467
468     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
469                                                    &core_module); 
470     return conf->ap_default_type 
471                ? conf->ap_default_type 
472                : DEFAULT_CONTENT_TYPE;
473 }
474
475 API_EXPORT(const char *) ap_document_root(request_rec *r) /* Don't use this! */
476 {
477     core_server_config *conf;
478
479     conf = (core_server_config *)ap_get_module_config(r->server->module_config,
480                                                       &core_module); 
481     return conf->ap_document_root;
482 }
483
484 API_EXPORT(const ap_array_header_t *) ap_requires(request_rec *r)
485 {
486     core_dir_config *conf;
487
488     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
489                                                    &core_module); 
490     return conf->ap_requires;
491 }
492
493 API_EXPORT(int) ap_satisfies(request_rec *r)
494 {
495     core_dir_config *conf;
496
497     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
498                                                    &core_module);
499
500     return conf->satisfy;
501 }
502
503 /* Should probably just get rid of this... the only code that cares is
504  * part of the core anyway (and in fact, it isn't publicised to other
505  * modules).
506  */
507
508 char *ap_response_code_string(request_rec *r, int error_index)
509 {
510     core_dir_config *conf;
511
512     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
513                                                    &core_module); 
514
515     if (conf->response_code_strings == NULL) {
516         return NULL;
517     }
518     return conf->response_code_strings[error_index];
519 }
520
521
522 /* Code from Harald Hanche-Olsen <hanche@imf.unit.no> */
523 static ap_inline void do_double_reverse (conn_rec *conn)
524 {
525     struct hostent *hptr;
526
527     if (conn->double_reverse) {
528         /* already done */
529         return;
530     }
531     if (conn->remote_host == NULL || conn->remote_host[0] == '\0') {
532         /* single reverse failed, so don't bother */
533         conn->double_reverse = -1;
534         return;
535     }
536     hptr = gethostbyname(conn->remote_host);   
537     if (hptr) {          
538         char **haddr;
539
540         for (haddr = hptr->h_addr_list; *haddr; haddr++) {
541             if (((struct in_addr *)(*haddr))->s_addr
542                 == conn->remote_addr.sin_addr.s_addr) {
543                 conn->double_reverse = 1;
544                 return;
545             }
546         }
547     }
548     conn->double_reverse = -1;
549 }
550
551 API_EXPORT(const char *) ap_get_remote_host(conn_rec *conn, void *dir_config,
552                                             int type)
553 {
554     struct in_addr *iaddr;
555     struct hostent *hptr;
556     int hostname_lookups;
557
558     /* If we haven't checked the host name, and we want to */
559     if (dir_config) {
560         hostname_lookups =
561             ((core_dir_config *)ap_get_module_config(dir_config, &core_module))
562                 ->hostname_lookups;
563         if (hostname_lookups == HOSTNAME_LOOKUP_UNSET) {
564             hostname_lookups = HOSTNAME_LOOKUP_OFF;
565         }
566     }
567     else {
568         /* the default */
569         hostname_lookups = HOSTNAME_LOOKUP_OFF;
570     }
571
572     if (type != REMOTE_NOLOOKUP
573         && conn->remote_host == NULL
574         && (type == REMOTE_DOUBLE_REV
575             || hostname_lookups != HOSTNAME_LOOKUP_OFF)) {
576         iaddr = &(conn->remote_addr.sin_addr);
577         hptr = gethostbyaddr((char *)iaddr, sizeof(struct in_addr), AF_INET);
578         if (hptr != NULL) {
579             conn->remote_host = ap_pstrdup(conn->pool, (void *)hptr->h_name);
580             ap_str_tolower(conn->remote_host);
581            
582             if (hostname_lookups == HOSTNAME_LOOKUP_DOUBLE) {
583                 do_double_reverse(conn);
584                 if (conn->double_reverse != 1) {
585                     conn->remote_host = NULL;
586                 }
587             }
588         }
589         /* if failed, set it to the NULL string to indicate error */
590         if (conn->remote_host == NULL) {
591             conn->remote_host = "";
592         }
593     }
594     if (type == REMOTE_DOUBLE_REV) {
595         do_double_reverse(conn);
596         if (conn->double_reverse == -1) {
597             return NULL;
598         }
599     }
600
601 /*
602  * Return the desired information; either the remote DNS name, if found,
603  * or either NULL (if the hostname was requested) or the IP address
604  * (if any identifier was requested).
605  */
606     if (conn->remote_host != NULL && conn->remote_host[0] != '\0') {
607         return conn->remote_host;
608     }
609     else {
610         if (type == REMOTE_HOST || type == REMOTE_DOUBLE_REV) {
611             return NULL;
612         }
613         else {
614             return conn->remote_ip;
615         }
616     }
617 }
618
619 API_EXPORT(const char *) ap_get_remote_logname(request_rec *r)
620 {
621     core_dir_config *dir_conf;
622
623     if (r->connection->remote_logname != NULL) {
624         return r->connection->remote_logname;
625     }
626
627 /* If we haven't checked the identity, and we want to */
628     dir_conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
629                                                        &core_module);
630
631     if (dir_conf->do_rfc1413 & 1) {
632         return ap_rfc1413(r->connection, r->server);
633     }
634     else {
635         return NULL;
636     }
637 }
638
639 /* There are two options regarding what the "name" of a server is.  The
640  * "canonical" name as defined by ServerName and Port, or the "client's
641  * name" as supplied by a possible Host: header or full URI.  We never
642  * trust the port passed in the client's headers, we always use the
643  * port of the actual socket.
644  *
645  * The DNS option to UseCanonicalName causes this routine to do a
646  * reverse lookup on the local IP address of the connectiona and use
647  * that for the ServerName. This makes its value more reliable while
648  * at the same time allowing Demon's magic virtual hosting to work.
649  * The assumption is that DNS lookups are sufficiently quick...
650  * -- fanf 1998-10-03
651  */
652 API_EXPORT(const char *) ap_get_server_name(request_rec *r)
653 {
654     conn_rec *conn = r->connection;
655     core_dir_config *d;
656
657     d = (core_dir_config *)ap_get_module_config(r->per_dir_config,
658                                                 &core_module);
659
660     if (d->use_canonical_name == USE_CANONICAL_NAME_OFF) {
661         return r->hostname ? r->hostname : r->server->server_hostname;
662     }
663     if (d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
664         if (conn->local_host == NULL) {
665             struct in_addr *iaddr;
666             struct hostent *hptr;
667             iaddr = &(conn->local_addr.sin_addr);
668             hptr = gethostbyaddr((char *)iaddr, sizeof(struct in_addr),
669                                  AF_INET);
670             if (hptr != NULL) {
671                 conn->local_host = ap_pstrdup(conn->pool,
672                                               (void *)hptr->h_name);
673                 ap_str_tolower(conn->local_host);
674             }
675             else {
676                 conn->local_host = ap_pstrdup(conn->pool,
677                                               r->server->server_hostname);
678             }
679         }
680         return conn->local_host;
681     }
682     /* default */
683     return r->server->server_hostname;
684 }
685
686 API_EXPORT(unsigned) ap_get_server_port(const request_rec *r)
687 {
688     unsigned port;
689     core_dir_config *d =
690       (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
691     
692     port = r->server->port ? r->server->port : ap_default_port(r);
693
694     if (d->use_canonical_name == USE_CANONICAL_NAME_OFF
695         || d->use_canonical_name == USE_CANONICAL_NAME_DNS) {
696         return r->hostname ? ntohs(r->connection->local_addr.sin_port)
697                            : port;
698     }
699     /* default */
700     return port;
701 }
702
703 API_EXPORT(char *) ap_construct_url(ap_context_t *p, const char *uri,
704                                     request_rec *r)
705 {
706     unsigned port = ap_get_server_port(r);
707     const char *host = ap_get_server_name(r);
708
709     if (ap_is_default_port(port, r)) {
710         return ap_pstrcat(p, ap_http_method(r), "://", host, uri, NULL);
711     }
712     return ap_psprintf(p, "%s://%s:%u%s", ap_http_method(r), host, port, uri);
713 }
714
715 API_EXPORT(unsigned long) ap_get_limit_req_body(const request_rec *r)
716 {
717     core_dir_config *d =
718       (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
719     
720     return d->limit_req_body;
721 }
722
723 #ifdef WIN32
724 static char* get_interpreter_from_win32_registry(ap_context_t *p, const char* ext) 
725 {
726     char extension_path[] = "SOFTWARE\\Classes\\";
727     char executable_path[] = "\\SHELL\\OPEN\\COMMAND";
728
729     HKEY hkeyOpen;
730     DWORD type;
731     int size;
732     int result;
733     char *keyName;
734     char *buffer;
735     char *s;
736
737     if (!ext)
738         return NULL;
739     /* 
740      * Future optimization:
741      * When the registry is successfully searched, store the interpreter
742      * string in a ap_table_t to make subsequent look-ups faster
743      */
744
745     /* Open the key associated with the script extension */
746     keyName = ap_pstrcat(p, extension_path, ext, NULL);
747
748     result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyName, 0, KEY_QUERY_VALUE, 
749                           &hkeyOpen);
750
751     if (result != ERROR_SUCCESS) 
752         return NULL;
753
754     /* Read to NULL buffer to find value size */
755     size = 0;
756     result = RegQueryValueEx(hkeyOpen, "", NULL, &type, NULL, &size);
757
758     if (result == ERROR_SUCCESS) {
759         buffer = ap_palloc(p, size);
760         result = RegQueryValueEx(hkeyOpen, "", NULL, &type, buffer, &size);
761     }
762
763     RegCloseKey(hkeyOpen);
764
765     if (result != ERROR_SUCCESS)
766         return NULL;
767
768     /* Open the key associated with the interpreter path */
769     keyName = ap_pstrcat(p, extension_path, buffer, executable_path, NULL);
770
771     result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyName, 0, KEY_QUERY_VALUE, 
772                           &hkeyOpen);
773
774     if (result != ERROR_SUCCESS)
775         return NULL;
776
777     /* Read to NULL buffer to find value size */
778     size = 0;
779     result = RegQueryValueEx(hkeyOpen, "", 0, &type, NULL, &size);
780
781     if (result == ERROR_SUCCESS) {
782         buffer = ap_palloc(p, size);
783         result = RegQueryValueEx(hkeyOpen, "", 0, &type, buffer, &size);
784     }
785
786     RegCloseKey(hkeyOpen);
787
788     if (result != ERROR_SUCCESS)
789         return NULL;
790
791     /*
792      * The canonical way shell command entries are entered in the Win32 
793      * registry is as follows:
794      *   shell [options] "%1"
795      * where
796      *   shell - full path name to interpreter or shell to run.
797      *           E.g., c:\usr\local\ntreskit\perl\bin\perl.exe
798      *   options - optional switches
799      *              E.g., \C
800      *   "%1" - Place holder for file to run the shell against. 
801      *          Typically quoted.
802      *
803      * If we find a %1 or a quoted %1, lop it off. 
804      */
805     if (buffer && *buffer) {
806         if ((s = strstr(buffer, "\"%1")))
807             *s = '\0';
808         else if ((s = strstr(buffer, "%1"))) 
809             *s = '\0';
810     }
811
812     return buffer;
813 }
814
815 API_EXPORT (file_type_e) ap_get_win32_interpreter(const  request_rec *r, 
816                                                   char** interpreter )
817 {
818     HANDLE hFile;
819     DWORD nBytesRead;
820     BOOLEAN bResult;
821     char buffer[1024];
822     core_dir_config *d;
823     int i;
824     file_type_e fileType = eFileTypeUNKNOWN;
825     char *ext = NULL;
826     char *exename = NULL;
827
828     d = (core_dir_config *)ap_get_module_config(r->per_dir_config, 
829                                                 &core_module);
830
831     /* Find the file extension */
832     exename = strrchr(r->filename, '/');
833     if (!exename) {
834         exename = strrchr(r->filename, '\\');
835     }
836     if (!exename) {
837         exename = r->filename;
838     }
839     else {
840         exename++;
841     }
842     ext = strrchr(exename, '.');
843
844     if (ext && (!strcasecmp(ext,".bat") || !strcasecmp(ext,".cmd"))) {
845         return eFileTypeEXE32;
846     }
847
848     /* If the file has an extension and it is not .com and not .exe and
849      * we've been instructed to search the registry, then do it!
850      */
851     if (ext && strcasecmp(ext,".exe") && strcasecmp(ext,".com") &&
852         d->script_interpreter_source == INTERPRETER_SOURCE_REGISTRY) {
853          /* Check the registry */
854         *interpreter = get_interpreter_from_win32_registry(r->pool, ext);
855         if (*interpreter)
856             return eFileTypeSCRIPT;
857         else {
858             ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r->server,
859              "ScriptInterpreterSource config directive set to \"registry\".\n\t"
860              "Registry was searched but interpreter not found. Trying the shebang line.");
861         }
862     }        
863
864     /* Need to peek into the file figure out what it really is... */
865     hFile = CreateFile(r->filename, GENERIC_READ, FILE_SHARE_READ, NULL,
866                        OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
867     if (hFile == INVALID_HANDLE_VALUE) {
868         return eFileTypeUNKNOWN;
869     }
870     bResult = ReadFile(hFile, (void*) &buffer, sizeof(buffer) - 1, 
871                        &nBytesRead, NULL);
872     if (!bResult || (nBytesRead == 0)) {
873         ap_log_rerror(APLOG_MARK, APLOG_ERR, GetLastError(), r,
874                       "ReadFile(%s) failed", r->filename);
875         CloseHandle(hFile);
876         return eFileTypeUNKNOWN;
877     }
878     CloseHandle(hFile);
879     buffer[nBytesRead] = '\0';
880
881     /* Script or executable, that is the question... */
882     if ((buffer[0] == '#') && (buffer[1] == '!')) {
883         /* Assuming file is a script since it starts with a shebang */
884         fileType = eFileTypeSCRIPT;
885         for (i = 2; i < sizeof(buffer); i++) {
886             if ((buffer[i] == '\r')
887                 || (buffer[i] == '\n')) {
888                 break;
889             }
890         }
891         buffer[i] = '\0';
892         for (i = 2; buffer[i] == ' ' ; ++i)
893             ;
894         *interpreter = ap_pstrdup(r->pool, buffer + i ); 
895     }
896     else {
897         /* Not a script, is it an executable? */
898         IMAGE_DOS_HEADER *hdr = (IMAGE_DOS_HEADER*)buffer;    
899         if ((nBytesRead >= sizeof(IMAGE_DOS_HEADER)) && (hdr->e_magic == IMAGE_DOS_SIGNATURE)) {
900             if (hdr->e_lfarlc < 0x40)
901                 fileType = eFileTypeEXE16;
902             else
903                 fileType = eFileTypeEXE32;
904         }
905         else
906             fileType = eFileTypeUNKNOWN;
907     }
908
909     return fileType;
910 }
911 #endif
912
913 /*****************************************************************
914  *
915  * Commands... this module handles almost all of the NCSA httpd.conf
916  * commands, but most of the old srm.conf is in the the modules.
917  */
918
919 static const char end_directory_section[] = "</Directory>";
920 static const char end_directorymatch_section[] = "</DirectoryMatch>";
921 static const char end_location_section[] = "</Location>";
922 static const char end_locationmatch_section[] = "</LocationMatch>";
923 static const char end_files_section[] = "</Files>";
924 static const char end_filesmatch_section[] = "</FilesMatch>";
925 static const char end_virtualhost_section[] = "</VirtualHost>";
926 static const char end_ifmodule_section[] = "</IfModule>";
927 static const char end_ifdefine_section[] = "</IfDefine>";
928
929
930 API_EXPORT(const char *) ap_check_cmd_context(cmd_parms *cmd,
931                                               unsigned forbidden)
932 {
933     const char *gt = (cmd->cmd->name[0] == '<'
934                       && cmd->cmd->name[strlen(cmd->cmd->name)-1] != '>')
935                          ? ">" : "";
936
937     if ((forbidden & NOT_IN_VIRTUALHOST) && cmd->server->is_virtual) {
938         return ap_pstrcat(cmd->pool, cmd->cmd->name, gt,
939                           " cannot occur within <VirtualHost> section", NULL);
940     }
941
942     if ((forbidden & NOT_IN_LIMIT) && cmd->limited != -1) {
943         return ap_pstrcat(cmd->pool, cmd->cmd->name, gt,
944                           " cannot occur within <Limit> section", NULL);
945     }
946
947     if ((forbidden & NOT_IN_DIR_LOC_FILE) == NOT_IN_DIR_LOC_FILE
948         && cmd->path != NULL) {
949         return ap_pstrcat(cmd->pool, cmd->cmd->name, gt,
950                           " cannot occur within <Directory/Location/Files> "
951                           "section", NULL);
952     }
953     
954     if (((forbidden & NOT_IN_DIRECTORY)
955          && (cmd->end_token == end_directory_section
956              || cmd->end_token == end_directorymatch_section)) 
957         || ((forbidden & NOT_IN_LOCATION)
958             && (cmd->end_token == end_location_section
959                 || cmd->end_token == end_locationmatch_section)) 
960         || ((forbidden & NOT_IN_FILES)
961             && (cmd->end_token == end_files_section
962                 || cmd->end_token == end_filesmatch_section))) {
963         return ap_pstrcat(cmd->pool, cmd->cmd->name, gt,
964                           " cannot occur within <", cmd->end_token+2,
965                           " section", NULL);
966     }
967
968     return NULL;
969 }
970
971 static const char *set_access_name(cmd_parms *cmd, void *dummy, char *arg)
972 {
973     void *sconf = cmd->server->module_config;
974     core_server_config *conf = ap_get_module_config(sconf, &core_module);
975
976     const char *err = ap_check_cmd_context(cmd,
977                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
978     if (err != NULL) {
979         return err;
980     }
981
982     conf->access_name = ap_pstrdup(cmd->pool, arg);
983     return NULL;
984 }
985
986 #ifdef GPROF
987 static const char *set_gprof_dir(cmd_parms *cmd, void *dummy, char *arg)
988 {
989     void *sconf = cmd->server->module_config;
990     core_server_config *conf = ap_get_module_config(sconf, &core_module);
991
992     const char *err = ap_check_cmd_context(cmd,
993                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
994     if (err != NULL) {
995         return err;
996     }
997
998     conf->gprof_dir = ap_pstrdup(cmd->pool, arg);
999     return NULL;
1000 }
1001 #endif /*GPROF*/
1002
1003 static const char *set_document_root(cmd_parms *cmd, void *dummy, char *arg)
1004 {
1005     void *sconf = cmd->server->module_config;
1006     core_server_config *conf = ap_get_module_config(sconf, &core_module);
1007   
1008     const char *err = ap_check_cmd_context(cmd,
1009                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1010     if (err != NULL) {
1011         return err;
1012     }
1013
1014     arg = ap_os_canonical_filename(cmd->pool, arg);
1015     if (/* TODO: ap_configtestonly && ap_docrootcheck && */ !ap_is_directory(arg)) {
1016         if (cmd->server->is_virtual) {
1017             ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1018                          "Warning: DocumentRoot [%s] does not exist",
1019                          arg);
1020         }
1021         else {
1022             return "DocumentRoot must be a directory";
1023         }
1024     }
1025     
1026     conf->ap_document_root = arg;
1027     return NULL;
1028 }
1029
1030 API_EXPORT(void) ap_custom_response(request_rec *r, int status, char *string)
1031 {
1032     core_dir_config *conf = 
1033         ap_get_module_config(r->per_dir_config, &core_module);
1034     int idx;
1035
1036     if(conf->response_code_strings == NULL) {
1037         conf->response_code_strings = 
1038             ap_pcalloc(r->pool,
1039                     sizeof(*conf->response_code_strings) * 
1040                     RESPONSE_CODES);
1041     }
1042
1043     idx = ap_index_of_response(status);
1044
1045     conf->response_code_strings[idx] = 
1046        ((ap_is_url(string) || (*string == '/')) && (*string != '"')) ? 
1047        ap_pstrdup(r->pool, string) : ap_pstrcat(r->pool, "\"", string, NULL);
1048 }
1049
1050 static const char *set_error_document(cmd_parms *cmd, core_dir_config *conf,
1051                                       char *line)
1052 {
1053     int error_number, index_number, idx500;
1054     char *w;
1055                 
1056     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1057     if (err != NULL) {
1058         return err;
1059     }
1060
1061     /* 1st parameter should be a 3 digit number, which we recognize;
1062      * convert it into an array index
1063      */
1064   
1065     w = ap_getword_conf_nc(cmd->pool, &line);
1066     error_number = atoi(w);
1067
1068     idx500 = ap_index_of_response(HTTP_INTERNAL_SERVER_ERROR);
1069
1070     if (error_number == HTTP_INTERNAL_SERVER_ERROR) {
1071         index_number = idx500;
1072     }
1073     else if ((index_number = ap_index_of_response(error_number)) == idx500) {
1074         return ap_pstrcat(cmd->pool, "Unsupported HTTP response code ",
1075                           w, NULL);
1076     }
1077
1078     /* The entry should be ignored if it is a full URL for a 401 error */
1079
1080     if (error_number == 401 &&
1081         line[0] != '/' && line[0] != '"') { /* Ignore it... */
1082         ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, cmd->server,
1083                      "cannot use a full URL in a 401 ErrorDocument "
1084                      "directive --- ignoring!");
1085     }
1086     else { /* Store it... */
1087         if (conf->response_code_strings == NULL) {
1088             conf->response_code_strings =
1089                 ap_pcalloc(cmd->pool,
1090                            sizeof(*conf->response_code_strings) * RESPONSE_CODES);
1091         }
1092         conf->response_code_strings[index_number] = ap_pstrdup(cmd->pool, line);
1093     }   
1094
1095     return NULL;
1096 }
1097
1098 /* access.conf commands...
1099  *
1100  * The *only* thing that can appear in access.conf at top level is a
1101  * <Directory> section.  NB we need to have a way to cut the srm_command_loop
1102  * invoked by dirsection (i.e., <Directory>) short when </Directory> is seen.
1103  * We do that by returning an error, which dirsection itself recognizes and
1104  * discards as harmless.  Cheesy, but it works.
1105  */
1106
1107 static const char *set_override(cmd_parms *cmd, core_dir_config *d,
1108                                 const char *l)
1109 {
1110     char *w;
1111   
1112     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1113     if (err != NULL) {
1114         return err;
1115     }
1116
1117     d->override = OR_NONE;
1118     while (l[0]) {
1119         w = ap_getword_conf(cmd->pool, &l);
1120         if (!strcasecmp(w, "Limit")) {
1121             d->override |= OR_LIMIT;
1122         }
1123         else if (!strcasecmp(w, "Options")) {
1124             d->override |= OR_OPTIONS;
1125         }
1126         else if (!strcasecmp(w, "FileInfo")) {
1127             d->override |= OR_FILEINFO;
1128         }
1129         else if (!strcasecmp(w, "AuthConfig")) {
1130             d->override |= OR_AUTHCFG;
1131         }
1132         else if (!strcasecmp(w, "Indexes")) {
1133             d->override |= OR_INDEXES;
1134         }
1135         else if (!strcasecmp(w, "None")) {
1136             d->override = OR_NONE;
1137         }
1138         else if (!strcasecmp(w, "All")) {
1139             d->override = OR_ALL;
1140         }
1141         else {
1142             return ap_pstrcat(cmd->pool, "Illegal override option ", w, NULL);
1143         }
1144         d->override &= ~OR_UNSET;
1145     }
1146
1147     return NULL;
1148 }
1149
1150 static const char *set_options(cmd_parms *cmd, core_dir_config *d,
1151                                const char *l)
1152 {
1153     allow_options_t opt;
1154     int first = 1;
1155     char action;
1156
1157     while (l[0]) {
1158         char *w = ap_getword_conf(cmd->pool, &l);
1159         action = '\0';
1160
1161         if (*w == '+' || *w == '-') {
1162             action = *(w++);
1163         }
1164         else if (first) {
1165             d->opts = OPT_NONE;
1166             first = 0;
1167         }
1168             
1169         if (!strcasecmp(w, "Indexes")) {
1170             opt = OPT_INDEXES;
1171         }
1172         else if (!strcasecmp(w, "Includes")) {
1173             opt = OPT_INCLUDES;
1174         }
1175         else if (!strcasecmp(w, "IncludesNOEXEC")) {
1176             opt = (OPT_INCLUDES | OPT_INCNOEXEC);
1177         }
1178         else if (!strcasecmp(w, "FollowSymLinks")) {
1179             opt = OPT_SYM_LINKS;
1180         }
1181         else if (!strcasecmp(w, "SymLinksIfOwnerMatch")) {
1182             opt = OPT_SYM_OWNER;
1183         }
1184         else if (!strcasecmp(w, "execCGI")) {
1185             opt = OPT_EXECCGI;
1186         }
1187         else if (!strcasecmp(w, "MultiViews")) {
1188             opt = OPT_MULTI;
1189         }
1190         else if (!strcasecmp(w, "RunScripts")) { /* AI backcompat. Yuck */
1191             opt = OPT_MULTI|OPT_EXECCGI;
1192         }
1193         else if (!strcasecmp(w, "None")) {
1194             opt = OPT_NONE;
1195         }
1196         else if (!strcasecmp(w, "All")) {
1197             opt = OPT_ALL;
1198         }
1199         else {
1200             return ap_pstrcat(cmd->pool, "Illegal option ", w, NULL);
1201         }
1202
1203         /* we ensure the invariant (d->opts_add & d->opts_remove) == 0 */
1204         if (action == '-') {
1205             d->opts_remove |= opt;
1206             d->opts_add &= ~opt;
1207             d->opts &= ~opt;
1208         }
1209         else if (action == '+') {
1210             d->opts_add |= opt;
1211             d->opts_remove &= ~opt;
1212             d->opts |= opt;
1213         }
1214         else {
1215             d->opts |= opt;
1216         }
1217     }
1218
1219     return NULL;
1220 }
1221
1222 static const char *satisfy(cmd_parms *cmd, core_dir_config *c, char *arg)
1223 {
1224     if (!strcasecmp(arg, "all")) {
1225         c->satisfy = SATISFY_ALL;
1226     }
1227     else if (!strcasecmp(arg, "any")) {
1228         c->satisfy = SATISFY_ANY;
1229     }
1230     else {
1231         return "Satisfy either 'any' or 'all'.";
1232     }
1233     return NULL;
1234 }
1235
1236 static const char *require(cmd_parms *cmd, core_dir_config *c, char *arg)
1237 {
1238     require_line *r;
1239   
1240     if (!c->ap_requires) {
1241         c->ap_requires = ap_make_array(cmd->pool, 2, sizeof(require_line));
1242     }
1243     r = (require_line *)ap_push_array(c->ap_requires);
1244     r->requirement = ap_pstrdup(cmd->pool, arg);
1245     r->method_mask = cmd->limited;
1246     return NULL;
1247 }
1248
1249 CORE_EXPORT_NONSTD(const char *) ap_limit_section(cmd_parms *cmd, void *dummy,
1250                                                   const char *arg)
1251 {
1252     const char *limited_methods = ap_getword(cmd->pool, &arg, '>');
1253     void *tog = cmd->cmd->cmd_data;
1254     int limited = 0;
1255   
1256     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1257     if (err != NULL) {
1258         return err;
1259     }
1260
1261     /* XXX: NB: Currently, we have no way of checking
1262      * whether <Limit> or <LimitExcept> sections are closed properly.
1263      * (If we would add a srm_command_loop() here we might...)
1264      */
1265     
1266     while (limited_methods[0]) {
1267         char *method = ap_getword_conf(cmd->pool, &limited_methods);
1268         int  methnum = ap_method_number_of(method);
1269
1270         if (methnum == M_TRACE && !tog) {
1271             return "TRACE cannot be controlled by <Limit>";
1272         }
1273         else if (methnum == M_INVALID) {
1274             return ap_pstrcat(cmd->pool, "unknown method \"", method,
1275                               "\" in <Limit", tog ? "Except>" : ">", NULL);
1276         }
1277         else {
1278             limited |= (1 << methnum);
1279         }
1280     }
1281
1282     /* Killing two features with one function,
1283      * if (tog == NULL) <Limit>, else <LimitExcept>
1284      */
1285     cmd->limited = tog ? ~limited : limited;
1286     return NULL;
1287 }
1288
1289 static const char *endlimit_section(cmd_parms *cmd, void *dummy, void *dummy2)
1290 {
1291     void *tog = cmd->cmd->cmd_data;
1292
1293     if (cmd->limited == -1) {
1294         return tog ? "</LimitExcept> unexpected" : "</Limit> unexpected";
1295     }
1296     
1297     cmd->limited = -1;
1298     return NULL;
1299 }
1300
1301 /*
1302  * When a section is not closed properly when end-of-file is reached,
1303  * then an error message should be printed:
1304  */
1305 static const char *missing_endsection(cmd_parms *cmd, int nest)
1306 {
1307     if (nest < 2) {
1308         return ap_psprintf(cmd->pool, "Missing %s directive at end-of-file",
1309                            cmd->end_token);
1310     }
1311     return ap_psprintf(cmd->pool, "%d missing %s directives at end-of-file",
1312                        nest, cmd->end_token);
1313 }
1314
1315 /* We use this in <DirectoryMatch> and <FilesMatch>, to ensure that 
1316  * people don't get bitten by wrong-cased regex matches
1317  */
1318
1319 #ifdef WIN32
1320 #define USE_ICASE REG_ICASE
1321 #else
1322 #define USE_ICASE 0
1323 #endif
1324
1325 static const char *end_nested_section(cmd_parms *cmd, void *dummy)
1326 {
1327     if (cmd->end_token == NULL) {
1328         return ap_pstrcat(cmd->pool, cmd->cmd->name,
1329                           " without matching <", cmd->cmd->name + 2, 
1330                           " section", NULL);
1331     }
1332     /*
1333      * This '!=' may look weird on a string comparison, but it's correct --
1334      * it's been set up so that checking for two pointers to the same datum
1335      * is valid here.  And faster.
1336      */
1337     if (cmd->cmd->name != cmd->end_token) {
1338         return ap_pstrcat(cmd->pool, "Expected ", cmd->end_token, " but saw ",
1339                           cmd->cmd->name, NULL);
1340     }
1341     return cmd->end_token;
1342 }
1343
1344 /*
1345  * Report a missing-'>' syntax error.
1346  */
1347 static char *unclosed_directive(cmd_parms *cmd)
1348 {
1349     return ap_pstrcat(cmd->pool, cmd->cmd->name,
1350                       "> directive missing closing '>'", NULL);
1351 }
1352
1353 static const char *dirsection(cmd_parms *cmd, void *dummy, const char *arg)
1354 {
1355     const char *errmsg;
1356     char *endp = strrchr(arg, '>');
1357     int old_overrides = cmd->override;
1358     char *old_path = cmd->path;
1359     core_dir_config *conf;
1360     void *new_dir_conf = ap_create_per_dir_config(cmd->pool);
1361     regex_t *r = NULL;
1362     const char *old_end_token;
1363     const command_rec *thiscmd = cmd->cmd;
1364
1365     const char *err = ap_check_cmd_context(cmd,
1366                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1367     if (err != NULL) {
1368         return err;
1369     }
1370
1371     if (endp == NULL) {
1372         return unclosed_directive(cmd);
1373     }
1374
1375     *endp = '\0';
1376
1377     cmd->path = ap_getword_conf(cmd->pool, &arg);
1378     cmd->override = OR_ALL|ACCESS_CONF;
1379
1380     if (thiscmd->cmd_data) { /* <DirectoryMatch> */
1381         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1382     }
1383     else if (!strcmp(cmd->path, "~")) {
1384         cmd->path = ap_getword_conf(cmd->pool, &arg);
1385         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1386     }
1387     else {
1388         /* Ensure that the pathname is canonical */
1389         cmd->path = ap_os_canonical_filename(cmd->pool, cmd->path);
1390     }
1391
1392     old_end_token = cmd->end_token;
1393     cmd->end_token = thiscmd->cmd_data ? end_directorymatch_section : end_directory_section;
1394     errmsg = ap_srm_command_loop(cmd, new_dir_conf);
1395     if (errmsg == NULL) {
1396         errmsg = missing_endsection(cmd, 1);
1397     }
1398     cmd->end_token = old_end_token;
1399     if (errmsg != (thiscmd->cmd_data 
1400                        ? end_directorymatch_section 
1401                    : end_directory_section)) {
1402         return errmsg;
1403     }
1404
1405     conf = (core_dir_config *)ap_get_module_config(new_dir_conf, &core_module);
1406     conf->r = r;
1407
1408     ap_add_per_dir_conf(cmd->server, new_dir_conf);
1409
1410     if (*arg != '\0') {
1411         return ap_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1412                           "> arguments not (yet) supported.", NULL);
1413     }
1414
1415     cmd->path = old_path;
1416     cmd->override = old_overrides;
1417
1418     return NULL;
1419 }
1420
1421 static const char *urlsection(cmd_parms *cmd, void *dummy, const char *arg)
1422 {
1423     const char *errmsg;
1424     char *endp = strrchr(arg, '>');
1425     int old_overrides = cmd->override;
1426     char *old_path = cmd->path;
1427     core_dir_config *conf;
1428     regex_t *r = NULL;
1429     const char *old_end_token;
1430     const command_rec *thiscmd = cmd->cmd;
1431
1432     void *new_url_conf = ap_create_per_dir_config(cmd->pool);
1433
1434     const char *err = ap_check_cmd_context(cmd,
1435                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1436     if (err != NULL) {
1437         return err;
1438     }
1439
1440     if (endp == NULL) {
1441         return unclosed_directive(cmd);
1442     }
1443
1444     *endp = '\0';
1445
1446     cmd->path = ap_getword_conf(cmd->pool, &arg);
1447     cmd->override = OR_ALL|ACCESS_CONF;
1448
1449     if (thiscmd->cmd_data) { /* <LocationMatch> */
1450         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1451     }
1452     else if (!strcmp(cmd->path, "~")) {
1453         cmd->path = ap_getword_conf(cmd->pool, &arg);
1454         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED);
1455     }
1456
1457     old_end_token = cmd->end_token;
1458     cmd->end_token = thiscmd->cmd_data ? end_locationmatch_section
1459                                        : end_location_section;
1460     errmsg = ap_srm_command_loop(cmd, new_url_conf);
1461     if (errmsg == NULL) {
1462         errmsg = missing_endsection(cmd, 1);
1463     }
1464     cmd->end_token = old_end_token;
1465     if (errmsg != (thiscmd->cmd_data 
1466                        ? end_locationmatch_section 
1467                        : end_location_section)) {
1468         return errmsg;
1469     }
1470
1471     conf = (core_dir_config *)ap_get_module_config(new_url_conf, &core_module);
1472     conf->d = ap_pstrdup(cmd->pool, cmd->path); /* No mangling, please */
1473     conf->d_is_fnmatch = ap_is_fnmatch(conf->d) != 0;
1474     conf->r = r;
1475
1476     ap_add_per_url_conf(cmd->server, new_url_conf);
1477     
1478     if (*arg != '\0') {
1479         return ap_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1480                           "> arguments not (yet) supported.", NULL);
1481     }
1482
1483     cmd->path = old_path;
1484     cmd->override = old_overrides;
1485
1486     return NULL;
1487 }
1488
1489 static const char *filesection(cmd_parms *cmd, core_dir_config *c,
1490                                const char *arg)
1491 {
1492     const char *errmsg;
1493     char *endp = strrchr(arg, '>');
1494     int old_overrides = cmd->override;
1495     char *old_path = cmd->path;
1496     core_dir_config *conf;
1497     regex_t *r = NULL;
1498     const char *old_end_token;
1499     const command_rec *thiscmd = cmd->cmd;
1500
1501     void *new_file_conf = ap_create_per_dir_config(cmd->pool);
1502
1503     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT|NOT_IN_LOCATION);
1504     if (err != NULL) {
1505         return err;
1506     }
1507
1508     if (endp == NULL) {
1509         return unclosed_directive(cmd);
1510     }
1511
1512     *endp = '\0';
1513
1514     cmd->path = ap_getword_conf(cmd->pool, &arg);
1515     /* Only if not an .htaccess file */
1516     if (!old_path) {
1517         cmd->override = OR_ALL|ACCESS_CONF;
1518     }
1519
1520     if (thiscmd->cmd_data) { /* <FilesMatch> */
1521         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1522     }
1523     else if (!strcmp(cmd->path, "~")) {
1524         cmd->path = ap_getword_conf(cmd->pool, &arg);
1525         r = ap_pregcomp(cmd->pool, cmd->path, REG_EXTENDED|USE_ICASE);
1526     }
1527     else {
1528         /* Ensure that the pathname is canonical */
1529         cmd->path = ap_os_canonical_filename(cmd->pool, cmd->path);
1530     }
1531
1532     old_end_token = cmd->end_token;
1533     cmd->end_token = thiscmd->cmd_data ? end_filesmatch_section : end_files_section;
1534     errmsg = ap_srm_command_loop(cmd, new_file_conf);
1535     if (errmsg == NULL) {
1536         errmsg = missing_endsection(cmd, 1);
1537     }
1538     cmd->end_token = old_end_token;
1539     if (errmsg != (thiscmd->cmd_data 
1540                        ? end_filesmatch_section 
1541                    : end_files_section)) {
1542         return errmsg;
1543     }
1544
1545     conf = (core_dir_config *)ap_get_module_config(new_file_conf,
1546                                                    &core_module);
1547     conf->d = cmd->path;
1548     conf->d_is_fnmatch = ap_is_fnmatch(conf->d) != 0;
1549     conf->r = r;
1550
1551     ap_add_file_conf(c, new_file_conf);
1552
1553     if (*arg != '\0') {
1554         return ap_pstrcat(cmd->pool, "Multiple ", thiscmd->name,
1555                           "> arguments not (yet) supported.", NULL);
1556     }
1557
1558     cmd->path = old_path;
1559     cmd->override = old_overrides;
1560
1561     return NULL;
1562 }
1563
1564 /* XXX: NB: Currently, we have no way of checking
1565  * whether <IfModule> sections are closed properly.
1566  * Extra (redundant, unpaired) </IfModule> directives are
1567  * simply silently ignored.
1568  */
1569 static const char *end_ifmod(cmd_parms *cmd, void *dummy)
1570 {
1571     return NULL;
1572 }
1573
1574 static const char *start_ifmod(cmd_parms *cmd, void *dummy, char *arg)
1575 {
1576     char *endp = strrchr(arg, '>');
1577     char l[MAX_STRING_LEN];
1578     int not = (arg[0] == '!');
1579     module *found;
1580     int nest = 1;
1581
1582     if (endp == NULL) {
1583         return unclosed_directive(cmd);
1584     }
1585
1586     *endp = '\0';
1587
1588     if (not) {
1589         arg++;
1590     }
1591
1592     found = ap_find_linked_module(arg);
1593
1594     if ((!not && found) || (not && !found)) {
1595         return NULL;
1596     }
1597
1598     while (nest && !(ap_cfg_getline(l, MAX_STRING_LEN, cmd->config_file))) {
1599         if (!strncasecmp(l, "<IfModule", 9)) {
1600             nest++;
1601         }
1602         if (!strcasecmp(l, "</IfModule>")) {
1603           nest--;
1604         }
1605     }
1606
1607     if (nest) {
1608         cmd->end_token = end_ifmodule_section;
1609         return missing_endsection(cmd, nest);
1610     }
1611     return NULL;
1612 }
1613
1614 API_EXPORT(int) ap_exists_config_define(char *name)
1615 {
1616     char **defines;
1617     int i;
1618
1619     defines = (char **)ap_server_config_defines->elts;
1620     for (i = 0; i < ap_server_config_defines->nelts; i++) {
1621         if (strcmp(defines[i], name) == 0) {
1622             return 1;
1623         }
1624     }
1625     return 0;
1626 }
1627
1628 static const char *end_ifdefine(cmd_parms *cmd, void *dummy) 
1629 {
1630     return NULL;
1631 }
1632
1633 static const char *start_ifdefine(cmd_parms *cmd, void *dummy, char *arg)
1634 {
1635     char *endp;
1636     char l[MAX_STRING_LEN];
1637     int defined;
1638     int not = 0;
1639     int nest = 1;
1640
1641     endp = strrchr(arg, '>');
1642     if (endp == NULL) {
1643         return unclosed_directive(cmd);
1644     }
1645
1646     *endp = '\0';
1647
1648     if (arg[0] == '!') {
1649         not = 1;
1650         arg++;
1651     }
1652
1653     defined = ap_exists_config_define(arg);
1654
1655     if ((!not && defined) || (not && !defined)) {
1656         return NULL;
1657     }
1658
1659     while (nest && !(ap_cfg_getline(l, MAX_STRING_LEN, cmd->config_file))) {
1660         if (!strncasecmp(l, "<IfDefine", 9)) {
1661             nest++;
1662         }
1663         if (!strcasecmp(l, "</IfDefine>")) {
1664             nest--;
1665         }
1666     }
1667     if (nest) {
1668         cmd->end_token = end_ifdefine_section;
1669         return missing_endsection(cmd, nest);
1670     }
1671     return NULL;
1672 }
1673
1674 /* httpd.conf commands... beginning with the <VirtualHost> business */
1675
1676 static const char *virtualhost_section(cmd_parms *cmd, void *dummy, char *arg)
1677 {
1678     server_rec *main_server = cmd->server, *s;
1679     const char *errmsg;
1680     char *endp = strrchr(arg, '>');
1681     ap_context_t *p = cmd->pool, *ptemp = cmd->temp_pool;
1682     const char *old_end_token;
1683
1684     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1685     if (err != NULL) {
1686         return err;
1687     }
1688
1689     if (endp == NULL) {
1690         return unclosed_directive(cmd);
1691     }
1692
1693     *endp = '\0';
1694     
1695     /* FIXME: There's another feature waiting to happen here -- since you
1696         can now put multiple addresses/names on a single <VirtualHost>
1697         you might want to use it to group common definitions and then
1698         define other "subhosts" with their individual differences.  But
1699         personally I'd rather just do it with a macro preprocessor. -djg */
1700     if (main_server->is_virtual) {
1701         return "<VirtualHost> doesn't nest!";
1702     }
1703     
1704     errmsg = ap_init_virtual_host(p, arg, main_server, &s);
1705     if (errmsg) {
1706         return errmsg;
1707     }
1708
1709     s->next = main_server->next;
1710     main_server->next = s;
1711
1712     s->defn_name = cmd->config_file->name;
1713     s->defn_line_number = cmd->config_file->line_number;
1714
1715     old_end_token = cmd->end_token;
1716     cmd->end_token = end_virtualhost_section;
1717     cmd->server = s;
1718     errmsg = ap_srm_command_loop(cmd, s->lookup_defaults);
1719     cmd->server = main_server;
1720     if (errmsg == NULL) {
1721         errmsg = missing_endsection(cmd, 1);
1722     }
1723     cmd->end_token = old_end_token;
1724
1725     if (s->srm_confname) {
1726         ap_process_resource_config(s, s->srm_confname, p, ptemp);
1727     }
1728
1729     if (s->access_confname) {
1730         ap_process_resource_config(s, s->access_confname, p, ptemp);
1731     }
1732     
1733     if (errmsg == end_virtualhost_section) {
1734         return NULL;
1735     }
1736     return errmsg;
1737 }
1738
1739 static const char *set_server_alias(cmd_parms *cmd, void *dummy,
1740                                     const char *arg)
1741 {
1742     if (!cmd->server->names) {
1743         return "ServerAlias only used in <VirtualHost>";
1744     }
1745     while (*arg) {
1746         char **item, *name = ap_getword_conf(cmd->pool, &arg);
1747         if (ap_is_matchexp(name)) {
1748             item = (char **)ap_push_array(cmd->server->wild_names);
1749         }
1750         else {
1751             item = (char **)ap_push_array(cmd->server->names);
1752         }
1753         *item = name;
1754     }
1755     return NULL;
1756 }
1757
1758 static const char *add_module_command(cmd_parms *cmd, void *dummy, char *arg)
1759 {
1760     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1761     if (err != NULL) {
1762         return err;
1763     }
1764
1765     if (!ap_add_named_module(arg)) {
1766         return ap_pstrcat(cmd->pool, "Cannot add module via name '", arg, 
1767                           "': not in list of loaded modules", NULL);
1768     }
1769     return NULL;
1770 }
1771
1772 static const char *clear_module_list_command(cmd_parms *cmd, void *dummy)
1773 {
1774     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1775     if (err != NULL) {
1776         return err;
1777     }
1778
1779     ap_clear_module_list();
1780     return NULL;
1781 }
1782
1783 static const char *set_server_string_slot(cmd_parms *cmd, void *dummy,
1784                                           char *arg)
1785 {
1786     /* This one's pretty generic... */
1787   
1788     int offset = (int)(long)cmd->info;
1789     char *struct_ptr = (char *)cmd->server;
1790     
1791     const char *err = ap_check_cmd_context(cmd, 
1792                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1793     if (err != NULL) {
1794         return err;
1795     }
1796
1797     *(char **)(struct_ptr + offset) = arg;
1798     return NULL;
1799 }
1800
1801 static const char *server_port(cmd_parms *cmd, void *dummy, char *arg)
1802 {
1803     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1804     int port;
1805
1806     if (err != NULL) {
1807         return err;
1808     }
1809     port = atoi(arg);
1810     if (port <= 0 || port >= 65536) { /* 65536 == 1<<16 */
1811         return ap_pstrcat(cmd->temp_pool, "The port number \"", arg, 
1812                           "\" is outside the appropriate range "
1813                           "(i.e., 1..65535).", NULL);
1814     }
1815     cmd->server->port = port;
1816     return NULL;
1817 }
1818
1819 static const char *set_signature_flag(cmd_parms *cmd, core_dir_config *d, 
1820                                       char *arg)
1821 {
1822     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1823     if (err != NULL) {
1824         return err;
1825     }
1826
1827     if (strcasecmp(arg, "On") == 0) {
1828         d->server_signature = srv_sig_on;
1829     }
1830     else if (strcasecmp(arg, "Off") == 0) {
1831         d->server_signature = srv_sig_off;
1832     }
1833     else if (strcasecmp(arg, "EMail") == 0) {
1834         d->server_signature = srv_sig_withmail;
1835     }
1836     else {
1837         return "ServerSignature: use one of: off | on | email";
1838     }
1839     return NULL;
1840 }
1841
1842 static const char *set_server_root(cmd_parms *cmd, void *dummy, char *arg) 
1843 {
1844     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1845
1846     if (err != NULL) {
1847         return err;
1848     }
1849
1850     arg = ap_os_canonical_filename(cmd->pool, arg);
1851
1852     if (!ap_is_directory(arg)) {
1853         return "ServerRoot must be a valid directory";
1854     }
1855     ap_server_root = arg;
1856     return NULL;
1857 }
1858
1859 static const char *set_timeout(cmd_parms *cmd, void *dummy, char *arg)
1860 {
1861     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1862     if (err != NULL) {
1863         return err;
1864     }
1865
1866     cmd->server->timeout = atoi(arg);
1867     return NULL;
1868 }
1869
1870 static const char *set_keep_alive_timeout(cmd_parms *cmd, void *dummy,
1871                                           char *arg)
1872 {
1873     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1874     if (err != NULL) {
1875         return err;
1876     }
1877
1878     cmd->server->keep_alive_timeout = atoi(arg);
1879     return NULL;
1880 }
1881
1882 static const char *set_keep_alive(cmd_parms *cmd, void *dummy, char *arg) 
1883 {
1884     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1885     if (err != NULL) {
1886         return err;
1887     }
1888
1889     /* We've changed it to On/Off, but used to use numbers
1890      * so we accept anything but "Off" or "0" as "On"
1891      */
1892     if (!strcasecmp(arg, "off") || !strcmp(arg, "0")) {
1893         cmd->server->keep_alive = 0;
1894     }
1895     else {
1896         cmd->server->keep_alive = 1;
1897     }
1898     return NULL;
1899 }
1900
1901 static const char *set_keep_alive_max(cmd_parms *cmd, void *dummy, char *arg) 
1902 {
1903     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1904     if (err != NULL) {
1905         return err;
1906     }
1907
1908     cmd->server->keep_alive_max = atoi(arg);
1909     return NULL;
1910 }
1911
1912 static const char *set_idcheck(cmd_parms *cmd, core_dir_config *d, int arg) 
1913 {
1914     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1915     if (err != NULL) {
1916         return err;
1917     }
1918
1919     d->do_rfc1413 = arg != 0;
1920     return NULL;
1921 }
1922
1923 static const char *set_hostname_lookups(cmd_parms *cmd, core_dir_config *d,
1924                                         char *arg)
1925 {
1926     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1927     if (err != NULL) {
1928         return err;
1929     }
1930
1931     if (!strcasecmp(arg, "on")) {
1932         d->hostname_lookups = HOSTNAME_LOOKUP_ON;
1933     }
1934     else if (!strcasecmp(arg, "off")) {
1935         d->hostname_lookups = HOSTNAME_LOOKUP_OFF;
1936     }
1937     else if (!strcasecmp(arg, "double")) {
1938         d->hostname_lookups = HOSTNAME_LOOKUP_DOUBLE;
1939     }
1940     else {
1941         return "parameter must be 'on', 'off', or 'double'";
1942     }
1943     return NULL;
1944 }
1945
1946 static const char *set_serverpath(cmd_parms *cmd, void *dummy, char *arg) 
1947 {
1948     const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
1949     if (err != NULL) {
1950         return err;
1951     }
1952
1953     cmd->server->path = arg;
1954     cmd->server->pathlen = strlen(arg);
1955     return NULL;
1956 }
1957
1958 static const char *set_content_md5(cmd_parms *cmd, core_dir_config *d, int arg)
1959 {
1960     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1961     if (err != NULL) {
1962         return err;
1963     }
1964
1965     d->content_md5 = arg != 0;
1966     return NULL;
1967 }
1968
1969 static const char *set_use_canonical_name(cmd_parms *cmd, core_dir_config *d, 
1970                                           char *arg)
1971 {
1972     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
1973     if (err != NULL) {
1974         return err;
1975     }
1976
1977     if (strcasecmp(arg, "on") == 0) {
1978         d->use_canonical_name = USE_CANONICAL_NAME_ON;
1979     }
1980     else if (strcasecmp(arg, "off") == 0) {
1981         d->use_canonical_name = USE_CANONICAL_NAME_OFF;
1982     }
1983     else if (strcasecmp(arg, "dns") == 0) {
1984         d->use_canonical_name = USE_CANONICAL_NAME_DNS;
1985     }
1986     else {
1987         return "parameter must be 'on', 'off', or 'dns'";
1988     }
1989     return NULL;
1990 }
1991
1992
1993 static const char *include_config (cmd_parms *cmd, void *dummy, char *name)
1994 {
1995     ap_process_resource_config(cmd->server,
1996         ap_server_root_relative(cmd->pool, name),
1997         cmd->pool, cmd->temp_pool);
1998     return NULL;
1999 }
2000
2001 static const char *set_loglevel(cmd_parms *cmd, void *dummy, const char *arg) 
2002 {
2003     char *str;
2004     
2005     const char *err = ap_check_cmd_context(cmd,
2006                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2007     if (err != NULL) {
2008         return err;
2009     }
2010
2011     if ((str = ap_getword_conf(cmd->pool, &arg))) {
2012         if (!strcasecmp(str, "emerg")) {
2013             cmd->server->loglevel = APLOG_EMERG;
2014         }
2015         else if (!strcasecmp(str, "alert")) {
2016             cmd->server->loglevel = APLOG_ALERT;
2017         }
2018         else if (!strcasecmp(str, "crit")) {
2019             cmd->server->loglevel = APLOG_CRIT;
2020         }
2021         else if (!strcasecmp(str, "error")) {
2022             cmd->server->loglevel = APLOG_ERR;
2023         }
2024         else if (!strcasecmp(str, "warn")) {
2025             cmd->server->loglevel = APLOG_WARNING;
2026         }
2027         else if (!strcasecmp(str, "notice")) {
2028             cmd->server->loglevel = APLOG_NOTICE;
2029         }
2030         else if (!strcasecmp(str, "info")) {
2031             cmd->server->loglevel = APLOG_INFO;
2032         }
2033         else if (!strcasecmp(str, "debug")) {
2034             cmd->server->loglevel = APLOG_DEBUG;
2035         }
2036         else {
2037             return "LogLevel requires level keyword: one of "
2038                    "emerg/alert/crit/error/warn/notice/info/debug";
2039         }
2040     }
2041     else {
2042         return "LogLevel requires level keyword";
2043     }
2044
2045     return NULL;
2046 }
2047
2048 API_EXPORT(const char *) ap_psignature(const char *prefix, request_rec *r)
2049 {
2050     char sport[20];
2051     core_dir_config *conf;
2052
2053     conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
2054                                                    &core_module);
2055     if ((conf->server_signature == srv_sig_off)
2056             || (conf->server_signature == srv_sig_unset)) {
2057         return "";
2058     }
2059
2060     ap_snprintf(sport, sizeof sport, "%u", (unsigned) ap_get_server_port(r));
2061
2062     if (conf->server_signature == srv_sig_withmail) {
2063         return ap_pstrcat(r->pool, prefix, "<ADDRESS>" AP_SERVER_BASEVERSION
2064                           " Server at <A HREF=\"mailto:",
2065                           r->server->server_admin, "\">",
2066                           ap_get_server_name(r), "</A> Port ", sport,
2067                           "</ADDRESS>\n", NULL);
2068     }
2069     return ap_pstrcat(r->pool, prefix, "<ADDRESS>" AP_SERVER_BASEVERSION
2070                       " Server at ", ap_get_server_name(r), " Port ", sport,
2071                       "</ADDRESS>\n", NULL);
2072 }
2073
2074 /*
2075  * Load an authorisation realm into our location configuration, applying the
2076  * usual rules that apply to realms.
2077  */
2078 static const char *set_authname(cmd_parms *cmd, void *mconfig, char *word1)
2079 {
2080     core_dir_config *aconfig = (core_dir_config *)mconfig;
2081
2082     aconfig->ap_auth_name = ap_escape_quotes(cmd->pool, word1);
2083     return NULL;
2084 }
2085
2086 #ifdef _OSD_POSIX /* BS2000 Logon Passwd file */
2087 static const char *set_bs2000_account(cmd_parms *cmd, void *dummy, char *name)
2088 {
2089     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2090     if (err != NULL) {
2091         return err;
2092     }
2093
2094     return os_set_account(cmd->pool, name);
2095 }
2096 #endif /*_OSD_POSIX*/
2097
2098 /*
2099  * Handle a request to include the server's OS platform in the Server
2100  * response header field (the ServerTokens directive).  Unfortunately
2101  * this requires a new global in order to communicate the setting back to
2102  * http_main so it can insert the information in the right place in the
2103  * string.
2104  */
2105
2106 static const char *set_serv_tokens(cmd_parms *cmd, void *dummy, char *arg) 
2107 {
2108     const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
2109     if (err != NULL) {
2110         return err;
2111     }
2112
2113     /* TODO: reimplement the server token stuff. */
2114 #if 0
2115     if (!strcasecmp(arg, "OS")) {
2116         ap_server_tokens = SrvTk_OS;
2117     }
2118     else if (!strcasecmp(arg, "Min") || !strcasecmp(arg, "Minimal")) {
2119         ap_server_tokens = SrvTk_MIN;
2120     }
2121     else {
2122         ap_server_tokens = SrvTk_FULL;
2123     }
2124 #endif
2125     return NULL;
2126 }
2127
2128 static const char *set_limit_req_line(cmd_parms *cmd, void *dummy, char *arg)
2129 {
2130     const char *err = ap_check_cmd_context(cmd,
2131                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2132     int lim;
2133
2134     if (err != NULL) {
2135         return err;
2136     }
2137     lim = atoi(arg);
2138     if (lim < 0) {
2139         return ap_pstrcat(cmd->temp_pool, "LimitRequestLine \"", arg, 
2140                           "\" must be a non-negative integer", NULL);
2141     }
2142     if (lim > DEFAULT_LIMIT_REQUEST_LINE) {
2143         return ap_psprintf(cmd->temp_pool, "LimitRequestLine \"%s\" "
2144                            "must not exceed the precompiled maximum of %d",
2145                            arg, DEFAULT_LIMIT_REQUEST_LINE);
2146     }
2147     cmd->server->limit_req_line = lim;
2148     return NULL;
2149 }
2150
2151 static const char *set_limit_req_fieldsize(cmd_parms *cmd, void *dummy,
2152                                            char *arg)
2153 {
2154     const char *err = ap_check_cmd_context(cmd,
2155                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2156     int lim;
2157
2158     if (err != NULL) {
2159         return err;
2160     }
2161     lim = atoi(arg);
2162     if (lim < 0) {
2163         return ap_pstrcat(cmd->temp_pool, "LimitRequestFieldsize \"", arg, 
2164                           "\" must be a non-negative integer (0 = no limit)",
2165                           NULL);
2166     }
2167     if (lim > DEFAULT_LIMIT_REQUEST_FIELDSIZE) {
2168         return ap_psprintf(cmd->temp_pool, "LimitRequestFieldsize \"%s\" "
2169                           "must not exceed the precompiled maximum of %d",
2170                            arg, DEFAULT_LIMIT_REQUEST_FIELDSIZE);
2171     }
2172     cmd->server->limit_req_fieldsize = lim;
2173     return NULL;
2174 }
2175
2176 static const char *set_limit_req_fields(cmd_parms *cmd, void *dummy, char *arg)
2177 {
2178     const char *err = ap_check_cmd_context(cmd,
2179                                            NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
2180     int lim;
2181
2182     if (err != NULL) {
2183         return err;
2184     }
2185     lim = atoi(arg);
2186     if (lim < 0) {
2187         return ap_pstrcat(cmd->temp_pool, "LimitRequestFields \"", arg, 
2188                           "\" must be a non-negative integer (0 = no limit)",
2189                           NULL);
2190     }
2191     cmd->server->limit_req_fields = lim;
2192     return NULL;
2193 }
2194
2195 static const char *set_limit_req_body(cmd_parms *cmd, core_dir_config *conf,
2196                                       char *arg) 
2197 {
2198     const char *err = ap_check_cmd_context(cmd, NOT_IN_LIMIT);
2199     if (err != NULL) {
2200         return err;
2201     }
2202
2203     /* WTF: If strtoul is not portable, then write a replacement.
2204      *      Instead we have an idiotic define in httpd.h that prevents
2205      *      it from being used even when it is available. Sheesh.
2206      */
2207     conf->limit_req_body = (unsigned long)strtol(arg, (char **)NULL, 10);
2208     return NULL;
2209 }
2210
2211 #ifdef WIN32
2212 static const char *set_interpreter_source(cmd_parms *cmd, core_dir_config *d,
2213                                                 char *arg)
2214 {
2215     if (!strcasecmp(arg, "registry")) {
2216         d->script_interpreter_source = INTERPRETER_SOURCE_REGISTRY;
2217     } else if (!strcasecmp(arg, "script")) {
2218         d->script_interpreter_source = INTERPRETER_SOURCE_SHEBANG;
2219     } else {
2220         d->script_interpreter_source = INTERPRETER_SOURCE_SHEBANG;
2221     }
2222     return NULL;
2223 }
2224 #endif
2225
2226 /* Note --- ErrorDocument will now work from .htaccess files.  
2227  * The AllowOverride of Fileinfo allows webmasters to turn it off
2228  */
2229
2230 static const command_rec core_cmds[] = {
2231
2232 /* Old access config file commands */
2233
2234 { "<Directory", dirsection, NULL, RSRC_CONF, RAW_ARGS,
2235   "Container for directives affecting resources located in the specified "
2236   "directories" },
2237 { end_directory_section, end_nested_section, NULL, ACCESS_CONF, NO_ARGS,
2238   "Marks end of <Directory>" },
2239 { "<Location", urlsection, NULL, RSRC_CONF, RAW_ARGS,
2240   "Container for directives affecting resources accessed through the "
2241   "specified URL paths" },
2242 { end_location_section, end_nested_section, NULL, ACCESS_CONF, NO_ARGS,
2243   "Marks end of <Location>" },
2244 { "<VirtualHost", virtualhost_section, NULL, RSRC_CONF, RAW_ARGS,
2245   "Container to map directives to a particular virtual host, takes one or "
2246   "more host addresses" },
2247 { end_virtualhost_section, end_nested_section, NULL, RSRC_CONF, NO_ARGS,
2248   "Marks end of <VirtualHost>" },
2249 { "<Files", filesection, NULL, OR_ALL, RAW_ARGS, "Container for directives "
2250   "affecting files matching specified patterns" },
2251 { end_files_section, end_nested_section, NULL, OR_ALL, NO_ARGS,
2252   "Marks end of <Files>" },
2253 { "<Limit", ap_limit_section, NULL, OR_ALL, RAW_ARGS, "Container for "
2254   "authentication directives when accessed using specified HTTP methods" },
2255 { "</Limit>", endlimit_section, NULL, OR_ALL, NO_ARGS,
2256   "Marks end of <Limit>" },
2257 { "<LimitExcept", ap_limit_section, (void*)1, OR_ALL, RAW_ARGS,
2258   "Container for authentication directives to be applied when any HTTP "
2259   "method other than those specified is used to access the resource" },
2260 { "</LimitExcept>", endlimit_section, (void*)1, OR_ALL, NO_ARGS,
2261   "Marks end of <LimitExcept>" },
2262 { "<IfModule", start_ifmod, NULL, OR_ALL, TAKE1,
2263   "Container for directives based on existance of specified modules" },
2264 { end_ifmodule_section, end_ifmod, NULL, OR_ALL, NO_ARGS,
2265   "Marks end of <IfModule>" },
2266 { "<IfDefine", start_ifdefine, NULL, OR_ALL, TAKE1,
2267   "Container for directives based on existance of command line defines" },
2268 { end_ifdefine_section, end_ifdefine, NULL, OR_ALL, NO_ARGS,
2269   "Marks end of <IfDefine>" },
2270 { "<DirectoryMatch", dirsection, (void*)1, RSRC_CONF, RAW_ARGS,
2271   "Container for directives affecting resources located in the "
2272   "specified directories" },
2273 { end_directorymatch_section, end_nested_section, NULL, ACCESS_CONF, NO_ARGS,
2274   "Marks end of <DirectoryMatch>" },
2275 { "<LocationMatch", urlsection, (void*)1, RSRC_CONF, RAW_ARGS,
2276   "Container for directives affecting resources accessed through the "
2277   "specified URL paths" },
2278 { end_locationmatch_section, end_nested_section, NULL, ACCESS_CONF, NO_ARGS,
2279   "Marks end of <LocationMatch>" },
2280 { "<FilesMatch", filesection, (void*)1, OR_ALL, RAW_ARGS,
2281   "Container for directives affecting files matching specified patterns" },
2282 { end_filesmatch_section, end_nested_section, NULL, OR_ALL, NO_ARGS,
2283   "Marks end of <FilesMatch>" },
2284 { "AuthType", ap_set_string_slot,
2285   (void*)XtOffsetOf(core_dir_config, ap_auth_type), OR_AUTHCFG, TAKE1,
2286   "An HTTP authorization type (e.g., \"Basic\")" },
2287 { "AuthName", set_authname, NULL, OR_AUTHCFG, TAKE1,
2288   "The authentication realm (e.g. \"Members Only\")" },
2289 { "Require", require, NULL, OR_AUTHCFG, RAW_ARGS,
2290   "Selects which authenticated users or groups may access a protected space" },
2291 { "Satisfy", satisfy, NULL, OR_AUTHCFG, TAKE1,
2292   "access policy if both allow and require used ('all' or 'any')" },    
2293 #ifdef GPROF
2294 { "GprofDir", set_gprof_dir, NULL, RSRC_CONF, TAKE1,
2295   "Directory to plop gmon.out files" },
2296 #endif
2297
2298 /* Old resource config file commands */
2299   
2300 { "AccessFileName", set_access_name, NULL, RSRC_CONF, RAW_ARGS,
2301   "Name(s) of per-directory config files (default: .htaccess)" },
2302 { "DocumentRoot", set_document_root, NULL, RSRC_CONF, TAKE1,
2303   "Root directory of the document tree"  },
2304 { "ErrorDocument", set_error_document, NULL, OR_FILEINFO, RAW_ARGS,
2305   "Change responses for HTTP errors" },
2306 { "AllowOverride", set_override, NULL, ACCESS_CONF, RAW_ARGS,
2307   "Controls what groups of directives can be configured by per-directory "
2308   "config files" },
2309 { "Options", set_options, NULL, OR_OPTIONS, RAW_ARGS,
2310   "Set a number of attributes for a given directory" },
2311 { "DefaultType", ap_set_string_slot,
2312   (void*)XtOffsetOf (core_dir_config, ap_default_type),
2313   OR_FILEINFO, TAKE1, "the default MIME type for untypable files" },
2314
2315 /* Old server config file commands */
2316
2317 { "Port", server_port, NULL, RSRC_CONF, TAKE1, "A TCP port number"},
2318 { "HostnameLookups", set_hostname_lookups, NULL, ACCESS_CONF|RSRC_CONF, TAKE1,
2319   "\"on\" to enable, \"off\" to disable reverse DNS lookups, or \"double\" to "
2320   "enable double-reverse DNS lookups" },
2321 { "ServerAdmin", set_server_string_slot,
2322   (void *)XtOffsetOf (server_rec, server_admin), RSRC_CONF, TAKE1,
2323   "The email address of the server administrator" },
2324 { "ServerName", set_server_string_slot,
2325   (void *)XtOffsetOf (server_rec, server_hostname), RSRC_CONF, TAKE1,
2326   "The hostname of the server" },
2327 { "ServerSignature", set_signature_flag, NULL, OR_ALL, TAKE1,
2328   "En-/disable server signature (on|off|email)" },
2329 { "ServerRoot", set_server_root, NULL, RSRC_CONF, TAKE1,
2330   "Common directory of server-related files (logs, confs, etc.)" },
2331 { "ErrorLog", set_server_string_slot,
2332   (void *)XtOffsetOf (server_rec, error_fname), RSRC_CONF, TAKE1,
2333   "The filename of the error log" },
2334 { "AccessConfig", set_server_string_slot,
2335   (void *)XtOffsetOf (server_rec, access_confname), RSRC_CONF, TAKE1,
2336   "The filename of the access config file" },
2337 { "ResourceConfig", set_server_string_slot,
2338   (void *)XtOffsetOf (server_rec, srm_confname), RSRC_CONF, TAKE1,
2339   "The filename of the resource config file" },
2340 { "ServerAlias", set_server_alias, NULL, RSRC_CONF, RAW_ARGS,
2341   "A name or names alternately used to access the server" },
2342 { "ServerPath", set_serverpath, NULL, RSRC_CONF, TAKE1,
2343   "The pathname the server can be reached at" },
2344 { "Timeout", set_timeout, NULL, RSRC_CONF, TAKE1, "Timeout duration (sec)" },
2345 { "KeepAliveTimeout", set_keep_alive_timeout, NULL, RSRC_CONF, TAKE1,
2346   "Keep-Alive timeout duration (sec)"},
2347 { "MaxKeepAliveRequests", set_keep_alive_max, NULL, RSRC_CONF, TAKE1,
2348   "Maximum number of Keep-Alive requests per connection, or 0 for infinite" },
2349 { "KeepAlive", set_keep_alive, NULL, RSRC_CONF, TAKE1,
2350   "Whether persistent connections should be On or Off" },
2351 { "IdentityCheck", set_idcheck, NULL, RSRC_CONF|ACCESS_CONF, FLAG,
2352   "Enable identd (RFC 1413) user lookups - SLOW" },
2353 { "ContentDigest", set_content_md5, NULL, OR_OPTIONS,
2354   FLAG, "whether or not to send a Content-MD5 header with each request" },
2355 { "UseCanonicalName", set_use_canonical_name, NULL,
2356   RSRC_CONF|ACCESS_CONF, TAKE1,
2357   "How to work out the ServerName : Port when constructing URLs" },
2358 /* TODOC: MaxServers is deprecated */
2359 /* TODOC: ServersSafetyLimit is deprecated */
2360 /* TODO: RlimitFoo should all be part of mod_cgi, not in the core */
2361 /* TODOC: BindAddress deprecated */
2362 { "AddModule", add_module_command, NULL, RSRC_CONF, ITERATE,
2363   "The name of a module" },
2364 { "ClearModuleList", clear_module_list_command, NULL, RSRC_CONF, NO_ARGS, 
2365   NULL },
2366 /* TODO: ListenBacklog in MPM */
2367 { "Include", include_config, NULL, (RSRC_CONF | ACCESS_CONF), TAKE1,
2368   "Name of the config file to be included" },
2369 { "LogLevel", set_loglevel, NULL, RSRC_CONF, TAKE1,
2370   "Level of verbosity in error logging" },
2371 { "NameVirtualHost", ap_set_name_virtual_host, NULL, RSRC_CONF, TAKE1,
2372   "A numeric IP address:port, or the name of a host" },
2373 #ifdef _OSD_POSIX
2374 { "BS2000Account", set_bs2000_account, NULL, RSRC_CONF, TAKE1,
2375   "Name of server User's bs2000 logon account name" },
2376 #endif
2377 #ifdef WIN32
2378 { "ScriptInterpreterSource", set_interpreter_source, NULL, OR_FILEINFO, TAKE1,
2379   "Where to find interpreter to run Win32 scripts (Registry or script shebang line)" },
2380 #endif
2381 { "ServerTokens", set_serv_tokens, NULL, RSRC_CONF, TAKE1,
2382   "Determine tokens displayed in the Server: header - Min(imal), OS or Full" },
2383 { "LimitRequestLine", set_limit_req_line, NULL, RSRC_CONF, TAKE1,
2384   "Limit on maximum size of an HTTP request line"},
2385 { "LimitRequestFieldsize", set_limit_req_fieldsize, NULL, RSRC_CONF, TAKE1,
2386   "Limit on maximum size of an HTTP request header field"},
2387 { "LimitRequestFields", set_limit_req_fields, NULL, RSRC_CONF, TAKE1,
2388   "Limit (0 = unlimited) on max number of header fields in a request message"},
2389 { "LimitRequestBody", set_limit_req_body,
2390   (void*)XtOffsetOf(core_dir_config, limit_req_body),
2391   OR_ALL, TAKE1,
2392   "Limit (in bytes) on maximum size of request message body" },
2393 { NULL }
2394 };
2395
2396 /*****************************************************************
2397  *
2398  * Core handlers for various phases of server operation...
2399  */
2400
2401 static int core_translate(request_rec *r)
2402 {
2403     void *sconf = r->server->module_config;
2404     core_server_config *conf = ap_get_module_config(sconf, &core_module);
2405   
2406     if (r->proxyreq) {
2407         return HTTP_FORBIDDEN;
2408     }
2409     if ((r->uri[0] != '/') && strcmp(r->uri, "*")) {
2410         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2411                      "Invalid URI in request %s", r->the_request);
2412         return BAD_REQUEST;
2413     }
2414     
2415     if (r->server->path 
2416         && !strncmp(r->uri, r->server->path, r->server->pathlen)
2417         && (r->server->path[r->server->pathlen - 1] == '/'
2418             || r->uri[r->server->pathlen] == '/'
2419             || r->uri[r->server->pathlen] == '\0')) {
2420         r->filename = ap_pstrcat(r->pool, conf->ap_document_root,
2421                                  (r->uri + r->server->pathlen), NULL);
2422     }
2423     else {
2424         /*
2425          * Make sure that we do not mess up the translation by adding two
2426          * /'s in a row.  This happens under windows when the document
2427          * root ends with a /
2428          */
2429         if ((conf->ap_document_root[strlen(conf->ap_document_root)-1] == '/')
2430             && (*(r->uri) == '/')) {
2431             r->filename = ap_pstrcat(r->pool, conf->ap_document_root, r->uri+1,
2432                                      NULL);
2433         }
2434         else {
2435             r->filename = ap_pstrcat(r->pool, conf->ap_document_root, r->uri,
2436                                      NULL);
2437         }
2438     }
2439
2440     return OK;
2441 }
2442
2443 static int do_nothing(request_rec *r) { return OK; }
2444
2445 /*
2446  * Default handler for MIME types without other handlers.  Only GET
2447  * and OPTIONS at this point... anyone who wants to write a generic
2448  * handler for PUT or POST is free to do so, but it seems unwise to provide
2449  * any defaults yet... So, for now, we assume that this will always be
2450  * the last handler called and return 405 or 501.
2451  */
2452
2453 static int default_handler(request_rec *r)
2454 {
2455     core_dir_config *d =
2456             (core_dir_config *)ap_get_module_config(r->per_dir_config, &core_module);
2457     int rangestatus, errstatus;
2458     ap_file_t *fd = NULL;
2459     ap_status_t status;
2460 #ifdef USE_MMAP_FILES
2461     ap_mmap_t *mm = NULL;
2462 #endif
2463 #ifdef CHARSET_EBCDIC
2464     /* To make serving of "raw ASCII text" files easy (they serve faster
2465      * since they don't have to be converted from EBCDIC), a new
2466      * "magic" type prefix was invented: text/x-ascii-{plain,html,...}
2467      * If we detect one of these content types here, we simply correct
2468      * the type to the real text/{plain,html,...} type. Otherwise, we
2469      * set a flag that translation is required later on.
2470      */
2471     int convert_flag = ap_checkconv(r);
2472 #endif
2473
2474     /* This handler has no use for a request body (yet), but we still
2475      * need to read and discard it if the client sent one.
2476      */
2477     if ((errstatus = ap_discard_request_body(r)) != OK) {
2478         return errstatus;
2479     }
2480
2481     r->allowed |= (1 << M_GET) | (1 << M_OPTIONS);
2482
2483     if (r->method_number == M_INVALID) {
2484         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
2485                     "Invalid method in request %s", r->the_request);
2486         return NOT_IMPLEMENTED;
2487     }
2488     if (r->method_number == M_OPTIONS) {
2489         return ap_send_http_options(r);
2490     }
2491     if (r->method_number == M_PUT) {
2492         return METHOD_NOT_ALLOWED;
2493     }
2494     if (r->finfo.protection == 0 || (r->path_info && *r->path_info)) {
2495         ap_log_rerror(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, 0, r,
2496                       "File does not exist: %s",r->path_info ?
2497                       ap_pstrcat(r->pool, r->filename, r->path_info, NULL)
2498                       : r->filename);
2499         return HTTP_NOT_FOUND;
2500     }
2501     if (r->method_number != M_GET) {
2502         return METHOD_NOT_ALLOWED;
2503     }
2504         
2505     if ((status = ap_open(&fd, r->filename, APR_READ | APR_BINARY, 0, r->pool)) != APR_SUCCESS) {
2506         ap_log_rerror(APLOG_MARK, APLOG_ERR, status, r,
2507                      "file permissions deny server access: %s", r->filename);
2508         return FORBIDDEN;
2509     }
2510     ap_update_mtime(r, r->finfo.mtime);
2511     ap_set_last_modified(r);
2512     ap_set_etag(r);
2513     ap_table_setn(r->headers_out, "Accept-Ranges", "bytes");
2514     if (((errstatus = ap_meets_conditions(r)) != OK)
2515         || (errstatus = ap_set_content_length(r, r->finfo.size))) {
2516         ap_close(fd);
2517         return errstatus;
2518     }
2519
2520 #ifdef USE_MMAP_FILES
2521     if ((r->finfo.size >= MMAP_THRESHOLD)
2522         && (r->finfo.size < MMAP_LIMIT)
2523         && (!r->header_only || (d->content_md5 & 1))) {
2524         /* we need to protect ourselves in case we die while we've got the
2525          * file mmapped */
2526     if (ap_mmap_create(&mm, fd, 0, r->finfo.size, r->pool) != APR_SUCCESS){
2527             ap_log_rerror(APLOG_MARK, APLOG_CRIT, errno, r,
2528                          "default_handler: mmap failed: %s", r->filename);
2529             mm = NULL;
2530         }
2531     }
2532     else {
2533         mm = NULL;
2534     }
2535
2536     if (mm == NULL) {
2537 #endif
2538
2539 #ifdef CHARSET_EBCDIC
2540         if (d->content_md5 & 1) {
2541             ap_table_setn(r->headers_out, "Content-MD5",
2542                           ap_md5digest(r->pool, fd, convert_flag));
2543         }
2544 #else
2545         if (d->content_md5 & 1) {
2546             ap_table_setn(r->headers_out, "Content-MD5",
2547                           ap_md5digest(r->pool, fd));
2548         }
2549 #endif /* CHARSET_EBCDIC */
2550
2551         rangestatus = ap_set_byterange(r);
2552
2553         ap_send_http_header(r);
2554         
2555         if (!r->header_only) {
2556             if (!rangestatus) {
2557                 ap_send_fd(fd, r);
2558             }
2559             else {
2560                 long     length;
2561                 ap_off_t offset;
2562
2563                 while (ap_each_byterange(r, &offset, &length)) {
2564                     if ((status = ap_seek(fd, APR_SET, &offset)) != APR_SUCCESS) {
2565                         ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
2566                                   "error byteserving file: %s", r->filename);
2567                         ap_close(fd);
2568                         return HTTP_INTERNAL_SERVER_ERROR;
2569                     }
2570                     ap_send_fd_length(fd, r, length);
2571                 }
2572             }
2573         }
2574
2575 #ifdef USE_MMAP_FILES
2576     }
2577     else {
2578         char *addr;
2579     ap_mmap_offset((void**)&addr, mm ,0);
2580
2581         if (d->content_md5 & 1) {
2582             AP_MD5_CTX context;
2583             
2584             ap_MD5Init(&context);
2585             ap_MD5Update(&context, addr, (unsigned int)r->finfo.size);
2586             ap_table_setn(r->headers_out, "Content-MD5",
2587                           ap_md5contextTo64(r->pool, &context));
2588         }
2589
2590         rangestatus = ap_set_byterange(r);
2591         ap_send_http_header(r);
2592         
2593         if (!r->header_only) {
2594             if (!rangestatus) {
2595                 ap_send_mmap(mm, r, 0, r->finfo.size);
2596             }
2597             else {
2598                 ap_off_t offset;
2599                 long length;
2600                 while (ap_each_byterange(r, &offset, &length)) {
2601                     ap_send_mmap(mm, r, offset, length);
2602                 }
2603             }
2604         }
2605     }
2606 #endif
2607
2608     ap_close(fd);
2609     return OK;
2610 }
2611
2612 static const handler_rec core_handlers[] = {
2613 { "*/*", default_handler },
2614 { "default-handler", default_handler },
2615 { NULL, NULL }
2616 };
2617
2618 static void core_open_logs(ap_context_t *pconf, ap_context_t *plog, ap_context_t *ptemp, server_rec *s)
2619 {
2620     ap_open_logs(s, pconf);
2621 }
2622
2623 static const char *core_method(const request_rec *r)
2624     { return "http"; }
2625
2626 static unsigned short core_port(const request_rec *r)
2627     { return DEFAULT_HTTP_PORT; }
2628
2629 static void register_hooks(void)
2630 {
2631     ap_hook_translate_name(core_translate,NULL,NULL,HOOK_REALLY_LAST);
2632     ap_hook_process_connection(ap_process_http_connection,NULL,NULL,
2633                                HOOK_REALLY_LAST);
2634     ap_hook_http_method(core_method,NULL,NULL,HOOK_REALLY_LAST);
2635     ap_hook_default_port(core_port,NULL,NULL,HOOK_REALLY_LAST);
2636     ap_hook_open_logs(core_open_logs,NULL,NULL,HOOK_MIDDLE);
2637     /* FIXME: I suspect we can eliminate the need for these - Ben */
2638     ap_hook_type_checker(do_nothing,NULL,NULL,HOOK_REALLY_LAST);
2639     ap_hook_access_checker(do_nothing,NULL,NULL,HOOK_REALLY_LAST);
2640 }
2641
2642 API_VAR_EXPORT module core_module = {
2643     STANDARD20_MODULE_STUFF,
2644     create_core_dir_config,     /* create per-directory config structure */
2645     merge_core_dir_configs,     /* merge per-directory config structures */
2646     create_core_server_config,  /* create per-server config structure */
2647     merge_core_server_configs,  /* merge per-server config structures */
2648     core_cmds,                  /* command ap_table_t */
2649     core_handlers,              /* handlers */
2650     register_hooks              /* register hooks */
2651 };