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