]> granicus.if.org Git - apache/blob - server/config.c
properly merge directory configs in mod_include
[apache] / server / config.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * http_config.c: once was auxillary functions for reading httpd's config
19  * file and converting filenames into a namespace
20  *
21  * Rob McCool
22  *
23  * Wall-to-wall rewrite for Apache... commands which are part of the
24  * server core can now be found next door in "http_core.c".  Now contains
25  * general command loop, and functions which do bookkeeping for the new
26  * Apache config stuff (modules and configuration vectors).
27  *
28  * rst
29  *
30  */
31
32 #include "apr.h"
33 #include "apr_strings.h"
34 #include "apr_portable.h"
35 #include "apr_file_io.h"
36 #include "apr_fnmatch.h"
37
38 #define APR_WANT_STDIO
39 #define APR_WANT_STRFUNC
40 #include "apr_want.h"
41
42 #include "ap_config.h"
43 #include "httpd.h"
44 #include "http_config.h"
45 #include "http_protocol.h"
46 #include "http_core.h"
47 #include "http_log.h"      /* for errors in parse_htaccess */
48 #include "http_request.h"  /* for default_handler (see invoke_handler) */
49 #include "http_main.h"
50 #include "http_vhost.h"
51 #include "util_cfgtree.h"
52 #include "mpm_common.h"
53
54 #define APLOG_UNSET   (APLOG_NO_MODULE - 1)
55 APLOG_USE_MODULE(core);
56
57 AP_DECLARE_DATA const char *ap_server_argv0 = NULL;
58 AP_DECLARE_DATA const char *ap_server_root = NULL;
59 AP_DECLARE_DATA server_rec *ap_server_conf = NULL;
60 AP_DECLARE_DATA apr_pool_t *ap_pglobal = NULL;
61
62 AP_DECLARE_DATA apr_array_header_t *ap_server_pre_read_config = NULL;
63 AP_DECLARE_DATA apr_array_header_t *ap_server_post_read_config = NULL;
64 AP_DECLARE_DATA apr_array_header_t *ap_server_config_defines = NULL;
65
66 AP_DECLARE_DATA ap_directive_t *ap_conftree = NULL;
67
68 APR_HOOK_STRUCT(
69            APR_HOOK_LINK(header_parser)
70            APR_HOOK_LINK(pre_config)
71            APR_HOOK_LINK(check_config)
72            APR_HOOK_LINK(post_config)
73            APR_HOOK_LINK(open_logs)
74            APR_HOOK_LINK(child_init)
75            APR_HOOK_LINK(handler)
76            APR_HOOK_LINK(quick_handler)
77            APR_HOOK_LINK(optional_fn_retrieve)
78            APR_HOOK_LINK(test_config)
79 )
80
81 AP_IMPLEMENT_HOOK_RUN_ALL(int, header_parser,
82                           (request_rec *r), (r), OK, DECLINED)
83
84 AP_IMPLEMENT_HOOK_RUN_ALL(int, pre_config,
85                           (apr_pool_t *pconf, apr_pool_t *plog,
86                            apr_pool_t *ptemp),
87                           (pconf, plog, ptemp), OK, DECLINED)
88
89 AP_IMPLEMENT_HOOK_RUN_ALL(int, check_config,
90                           (apr_pool_t *pconf, apr_pool_t *plog,
91                            apr_pool_t *ptemp, server_rec *s),
92                           (pconf, plog, ptemp, s), OK, DECLINED)
93
94 AP_IMPLEMENT_HOOK_VOID(test_config,
95                        (apr_pool_t *pconf, server_rec *s),
96                        (pconf, s))
97
98 AP_IMPLEMENT_HOOK_RUN_ALL(int, post_config,
99                           (apr_pool_t *pconf, apr_pool_t *plog,
100                            apr_pool_t *ptemp, server_rec *s),
101                           (pconf, plog, ptemp, s), OK, DECLINED)
102
103 /* During the course of debugging I expanded this macro out, so
104  * rather than remove all the useful information there is in the
105  * following lines, I'm going to leave it here in case anyone
106  * else finds it useful.
107  *
108  * Ben has looked at it and thinks it correct :)
109  *
110 AP_DECLARE(int) ap_hook_post_config(ap_HOOK_post_config_t *pf,
111                                     const char * const *aszPre,
112                                     const char * const *aszSucc,
113                                     int nOrder)
114 {
115     ap_LINK_post_config_t *pHook;
116
117     if (!_hooks.link_post_config) {
118         _hooks.link_post_config = apr_array_make(apr_hook_global_pool, 1,
119                                                  sizeof(ap_LINK_post_config_t));
120         apr_hook_sort_register("post_config", &_hooks.link_post_config);
121     }
122
123     pHook = apr_array_push(_hooks.link_post_config);
124     pHook->pFunc = pf;
125     pHook->aszPredecessors = aszPre;
126     pHook->aszSuccessors = aszSucc;
127     pHook->nOrder = nOrder;
128     pHook->szName = apr_hook_debug_current;
129
130     if (apr_hook_debug_enabled)
131         apr_hook_debug_show("post_config", aszPre, aszSucc);
132 }
133
134 AP_DECLARE(apr_array_header_t *) ap_hook_get_post_config(void) {
135     return _hooks.link_post_config;
136 }
137
138 AP_DECLARE(int) ap_run_post_config(apr_pool_t *pconf,
139                                    apr_pool_t *plog,
140                                    apr_pool_t *ptemp,
141                                    server_rec *s)
142 {
143     ap_LINK_post_config_t *pHook;
144     int n;
145
146     if(!_hooks.link_post_config)
147         return;
148
149     pHook = (ap_LINK_post_config_t *)_hooks.link_post_config->elts;
150     for (n = 0; n < _hooks.link_post_config->nelts; ++n)
151         pHook[n].pFunc (pconf, plog, ptemp, s);
152 }
153  */
154
155 AP_IMPLEMENT_HOOK_RUN_ALL(int, open_logs,
156                           (apr_pool_t *pconf, apr_pool_t *plog,
157                            apr_pool_t *ptemp, server_rec *s),
158                           (pconf, plog, ptemp, s), OK, DECLINED)
159
160 AP_IMPLEMENT_HOOK_VOID(child_init,
161                        (apr_pool_t *pchild, server_rec *s),
162                        (pchild, s))
163
164 AP_IMPLEMENT_HOOK_RUN_FIRST(int, handler, (request_rec *r),
165                             (r), DECLINED)
166
167 AP_IMPLEMENT_HOOK_RUN_FIRST(int, quick_handler, (request_rec *r, int lookup),
168                             (r, lookup), DECLINED)
169
170 /* hooks with no args are implemented last, after disabling APR hook probes */
171 #if defined(APR_HOOK_PROBES_ENABLED)
172 #undef APR_HOOK_PROBES_ENABLED
173 #undef APR_HOOK_PROBE_ENTRY
174 #define APR_HOOK_PROBE_ENTRY(ud,ns,name,args)
175 #undef APR_HOOK_PROBE_RETURN
176 #define APR_HOOK_PROBE_RETURN(ud,ns,name,rv,args)
177 #undef APR_HOOK_PROBE_INVOKE
178 #define APR_HOOK_PROBE_INVOKE(ud,ns,name,src,args)
179 #undef APR_HOOK_PROBE_COMPLETE
180 #define APR_HOOK_PROBE_COMPLETE(ud,ns,name,src,rv,args)
181 #undef APR_HOOK_INT_DCL_UD
182 #define APR_HOOK_INT_DCL_UD
183 #endif
184 AP_IMPLEMENT_HOOK_VOID(optional_fn_retrieve, (void), ())
185
186 /****************************************************************
187  *
188  * We begin with the functions which deal with the linked list
189  * of modules which control just about all of the server operation.
190  */
191
192 /* total_modules is the number of modules that have been linked
193  * into the server.
194  */
195 static int total_modules = 0;
196
197 /* dynamic_modules is the number of modules that have been added
198  * after the pre-loaded ones have been set up. It shouldn't be larger
199  * than DYNAMIC_MODULE_LIMIT.
200  */
201 static int dynamic_modules = 0;
202
203 /* The maximum possible value for total_modules, i.e. number of static
204  * modules plus DYNAMIC_MODULE_LIMIT.
205  */
206 static int max_modules = 0;
207
208 /* The number of elements we need to alloc for config vectors. Before loading
209  * of dynamic modules, we must be liberal and set this to max_modules. After
210  * loading of dynamic modules, we can trim it down to total_modules. On
211  * restart, reset to max_modules.
212  */
213 static int conf_vector_length = 0;
214
215 static int reserved_module_slots = 0;
216
217 AP_DECLARE_DATA module *ap_top_module = NULL;
218 AP_DECLARE_DATA module **ap_loaded_modules=NULL;
219
220 static apr_hash_t *ap_config_hash = NULL;
221
222 /* a list of the module symbol names with the trailing "_module"removed */
223 static char **ap_module_short_names = NULL;
224
225 typedef int (*handler_func)(request_rec *);
226 typedef void *(*dir_maker_func)(apr_pool_t *, char *);
227 typedef void *(*merger_func)(apr_pool_t *, void *, void *);
228
229 /* A list of the merge_dir_config functions of all loaded modules, sorted
230  * by module_index.
231  * Using this list in ap_merge_per_dir_configs() is faster than following
232  * the module->next linked list because of better memory locality (resulting
233  * in better cache usage).
234  */
235 static merger_func *merger_func_cache;
236
237 /* maximum nesting level for config directories */
238 #ifndef AP_MAX_INCLUDE_DIR_DEPTH
239 #define AP_MAX_INCLUDE_DIR_DEPTH (128)
240 #endif
241
242 /* Dealing with config vectors.  These are associated with per-directory,
243  * per-server, and per-request configuration, and have a void* pointer for
244  * each modules.  The nature of the structure pointed to is private to the
245  * module in question... the core doesn't (and can't) know.  However, there
246  * are defined interfaces which allow it to create instances of its private
247  * per-directory and per-server structures, and to merge the per-directory
248  * structures of a directory and its subdirectory (producing a new one in
249  * which the defaults applying to the base directory have been properly
250  * overridden).
251  */
252
253 static ap_conf_vector_t *create_empty_config(apr_pool_t *p)
254 {
255     void *conf_vector = apr_pcalloc(p, sizeof(void *) * conf_vector_length);
256     return conf_vector;
257 }
258
259 static ap_conf_vector_t *create_default_per_dir_config(apr_pool_t *p)
260 {
261     void **conf_vector = apr_pcalloc(p, sizeof(void *) * conf_vector_length);
262     module *modp;
263
264     for (modp = ap_top_module; modp; modp = modp->next) {
265         dir_maker_func df = modp->create_dir_config;
266
267         if (df)
268             conf_vector[modp->module_index] = (*df)(p, NULL);
269     }
270
271     return (ap_conf_vector_t *)conf_vector;
272 }
273
274 AP_CORE_DECLARE(ap_conf_vector_t *) ap_merge_per_dir_configs(apr_pool_t *p,
275                                            ap_conf_vector_t *base,
276                                            ap_conf_vector_t *new_conf)
277 {
278     void **conf_vector = apr_palloc(p, sizeof(void *) * conf_vector_length);
279     void **base_vector = (void **)base;
280     void **new_vector = (void **)new_conf;
281     int i;
282
283     for (i = 0; i < total_modules; i++) {
284         if (!new_vector[i]) {
285             conf_vector[i] = base_vector[i];
286         }
287         else {
288             const merger_func df = merger_func_cache[i];
289             if (df && base_vector[i]) {
290                 conf_vector[i] = (*df)(p, base_vector[i], new_vector[i]);
291             }
292             else
293                 conf_vector[i] = new_vector[i];
294         }
295     }
296
297     return (ap_conf_vector_t *)conf_vector;
298 }
299
300 static ap_conf_vector_t *create_server_config(apr_pool_t *p, server_rec *s)
301 {
302     void **conf_vector = apr_pcalloc(p, sizeof(void *) * conf_vector_length);
303     module *modp;
304
305     for (modp = ap_top_module; modp; modp = modp->next) {
306         if (modp->create_server_config)
307             conf_vector[modp->module_index] = (*modp->create_server_config)(p, s);
308     }
309
310     return (ap_conf_vector_t *)conf_vector;
311 }
312
313 static void merge_server_configs(apr_pool_t *p, ap_conf_vector_t *base,
314                                  ap_conf_vector_t *virt)
315 {
316     /* Can reuse the 'virt' vector for the spine of it, since we don't
317      * have to deal with the moral equivalent of .htaccess files here...
318      */
319
320     void **base_vector = (void **)base;
321     void **virt_vector = (void **)virt;
322     module *modp;
323
324     for (modp = ap_top_module; modp; modp = modp->next) {
325         merger_func df = modp->merge_server_config;
326         int i = modp->module_index;
327
328         if (!virt_vector[i])
329             virt_vector[i] = base_vector[i];
330         else if (df)
331             virt_vector[i] = (*df)(p, base_vector[i], virt_vector[i]);
332     }
333 }
334
335 AP_CORE_DECLARE(ap_conf_vector_t *) ap_create_request_config(apr_pool_t *p)
336 {
337     return create_empty_config(p);
338 }
339
340 AP_CORE_DECLARE(ap_conf_vector_t *) ap_create_conn_config(apr_pool_t *p)
341 {
342     return create_empty_config(p);
343 }
344
345 AP_CORE_DECLARE(ap_conf_vector_t *) ap_create_per_dir_config(apr_pool_t *p)
346 {
347     return create_empty_config(p);
348 }
349
350 /* Invoke the filter_init_func for all filters with FILTERS where f->r
351  * matches R.  Restricting to a matching R avoids re-running init
352  * functions for filters configured for r->main where r is a
353  * subrequest.  */
354 static int invoke_filter_init(request_rec *r, ap_filter_t *filters)
355 {
356     while (filters) {
357         if (filters->frec->filter_init_func && filters->r == r) {
358             int result = filters->frec->filter_init_func(filters);
359             if (result != OK) {
360                 return result;
361             }
362         }
363         filters = filters->next;
364     }
365     return OK;
366 }
367
368 /*
369  * TODO: Move this to an appropriate include file and possibly prefix it
370  * with AP_.
371  */
372 #define DEFAULT_HANDLER_NAME ""
373
374 AP_CORE_DECLARE(int) ap_invoke_handler(request_rec *r)
375 {
376     const char *handler;
377     const char *p;
378     int result;
379     const char *old_handler = r->handler;
380     const char *ignore;
381
382     /*
383      * The new insert_filter stage makes the most sense here.  We only use
384      * it when we are going to run the request, so we must insert filters
385      * if any are available.  Since the goal of this phase is to allow all
386      * modules to insert a filter if they want to, this filter returns
387      * void.  I just can't see any way that this filter can reasonably
388      * fail, either your modules inserts something or it doesn't.  rbb
389      */
390     ap_run_insert_filter(r);
391
392     /* Before continuing, allow each filter that is in the two chains to
393      * run their init function to let them do any magic before we could
394      * start generating data.
395      */
396     result = invoke_filter_init(r, r->input_filters);
397     if (result != OK) {
398         return result;
399     }
400     result = invoke_filter_init(r, r->output_filters);
401     if (result != OK) {
402         return result;
403     }
404
405     if (!r->handler) {
406         if (r->content_type) {
407             handler = r->content_type;
408             if ((p=ap_strchr_c(handler, ';')) != NULL) {
409                 char *new_handler = (char *)apr_pmemdup(r->pool, handler,
410                                                         p - handler + 1);
411                 char *p2 = new_handler + (p - handler);
412                 handler = new_handler;
413
414                 /* exclude media type arguments */
415                 while (p2 > handler && p2[-1] == ' ')
416                     --p2; /* strip trailing spaces */
417
418                 *p2='\0';
419             }
420         }
421         else {
422             handler = DEFAULT_HANDLER_NAME;
423         }
424
425         r->handler = handler;
426     }
427
428     result = ap_run_handler(r);
429
430     r->handler = old_handler;
431
432     if (result == DECLINED && r->handler && r->filename) {
433         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
434             "handler \"%s\" not found for: %s", r->handler, r->filename);
435     }
436     if ((result != OK) && (result != DONE) && (result != DECLINED) && (result != SUSPENDED)
437         && (result != AP_FILTER_ERROR) /* ap_die() knows about this specifically */
438         && !ap_is_HTTP_VALID_RESPONSE(result)) {
439         /* If a module is deliberately returning something else
440          * (request_rec in non-HTTP or proprietary extension?)
441          * let it set a note to allow it explicitly.
442          * Otherwise, a return code that is neither reserved nor HTTP
443          * is a bug, as in PR#31759.
444          */
445         ignore = apr_table_get(r->notes, "HTTP_IGNORE_RANGE");
446         if (!ignore) {
447             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
448                           "Handler for %s returned invalid result code %d",
449                           r->handler, result);
450             result = HTTP_INTERNAL_SERVER_ERROR;
451         }
452     }
453
454     return result == DECLINED ? HTTP_INTERNAL_SERVER_ERROR : result;
455 }
456
457 AP_DECLARE(int) ap_method_is_limited(cmd_parms *cmd, const char *method)
458 {
459     int methnum;
460
461     methnum = ap_method_number_of(method);
462
463     /*
464      * A method number either hardcoded into apache or
465      * added by a module and registered.
466      */
467     if (methnum != M_INVALID) {
468         return (cmd->limited & (AP_METHOD_BIT << methnum)) ? 1 : 0;
469     }
470
471     return 0; /* not found */
472 }
473
474 AP_DECLARE(void) ap_register_hooks(module *m, apr_pool_t *p)
475 {
476     if (m->register_hooks) {
477         if (getenv("SHOW_HOOKS")) {
478             printf("Registering hooks for %s\n", m->name);
479             apr_hook_debug_enabled = 1;
480         }
481
482         apr_hook_debug_current = m->name;
483         m->register_hooks(p);
484     }
485 }
486
487 static void ap_add_module_commands(module *m, apr_pool_t *p);
488
489 typedef struct ap_mod_list_struct ap_mod_list;
490 struct ap_mod_list_struct {
491     struct ap_mod_list_struct *next;
492     module *m;
493     const command_rec *cmd;
494 };
495
496 static void rebuild_conf_hash(apr_pool_t *p, int add_prelinked)
497 {
498     module **m;
499
500     ap_config_hash = apr_hash_make(p);
501
502     apr_pool_cleanup_register(p, &ap_config_hash, ap_pool_cleanup_set_null,
503                               apr_pool_cleanup_null);
504     if (add_prelinked) {
505         for (m = ap_prelinked_modules; *m != NULL; m++) {
506             ap_add_module_commands(*m, p);
507         }
508     }
509 }
510
511 static void ap_add_module_commands(module *m, apr_pool_t *p)
512 {
513     apr_pool_t *tpool;
514     ap_mod_list *mln;
515     const command_rec *cmd;
516     char *dir;
517
518     cmd = m->cmds;
519
520     if (ap_config_hash == NULL) {
521         rebuild_conf_hash(p, 0);
522     }
523
524     tpool = apr_hash_pool_get(ap_config_hash);
525
526     while (cmd && cmd->name) {
527         mln = apr_palloc(tpool, sizeof(ap_mod_list));
528         mln->cmd = cmd;
529         mln->m = m;
530         dir = apr_pstrdup(tpool, cmd->name);
531
532         ap_str_tolower(dir);
533
534         mln->next = apr_hash_get(ap_config_hash, dir, APR_HASH_KEY_STRING);
535         apr_hash_set(ap_config_hash, dir, APR_HASH_KEY_STRING, mln);
536         ++cmd;
537     }
538 }
539
540
541 /* One-time setup for precompiled modules --- NOT to be done on restart */
542
543 AP_DECLARE(const char *) ap_add_module(module *m, apr_pool_t *p,
544                                        const char *sym_name)
545 {
546     ap_module_symbol_t *sym = ap_prelinked_module_symbols;
547
548     /* This could be called from a LoadModule httpd.conf command,
549      * after the file has been linked and the module structure within it
550      * teased out...
551      */
552
553     if (m->version != MODULE_MAGIC_NUMBER_MAJOR) {
554         return apr_psprintf(p, "Module \"%s\" is not compatible with this "
555                             "version of Apache (found %d, need %d). Please "
556                             "contact the vendor for the correct version.",
557                             m->name, m->version, MODULE_MAGIC_NUMBER_MAJOR);
558     }
559
560     if (m->module_index == -1) {
561         if (dynamic_modules >= DYNAMIC_MODULE_LIMIT) {
562             return apr_psprintf(p, "Module \"%s\" could not be loaded, "
563                                 "because the dynamic module limit was "
564                                 "reached. Please increase "
565                                 "DYNAMIC_MODULE_LIMIT and recompile.", m->name);
566         }
567         /*
568          * If this fails some module forgot to call ap_reserve_module_slots*.
569          */
570         ap_assert(total_modules < conf_vector_length);
571
572         m->module_index = total_modules++;
573         dynamic_modules++;
574
575     }
576     else if (!sym_name) {
577         while (sym->modp != NULL) {
578             if (sym->modp == m) {
579                 sym_name = sym->name;
580                 break;
581             }
582             sym++;
583         }
584     }
585
586     if (m->next == NULL) {
587         m->next = ap_top_module;
588         ap_top_module = m;
589     }
590
591     if (sym_name) {
592         int len = strlen(sym_name);
593         int slen = strlen("_module");
594         if (len > slen && !strcmp(sym_name + len - slen, "_module")) {
595             len -= slen;
596         }
597
598         ap_module_short_names[m->module_index] = strdup(sym_name);
599         ap_module_short_names[m->module_index][len] = '\0';
600         merger_func_cache[m->module_index] = m->merge_dir_config;
601     }
602
603
604     /* Some C compilers put a complete path into __FILE__, but we want
605      * only the filename (e.g. mod_includes.c). So check for path
606      * components (Unix and DOS), and remove them.
607      */
608
609     if (ap_strrchr_c(m->name, '/'))
610         m->name = 1 + ap_strrchr_c(m->name, '/');
611
612     if (ap_strrchr_c(m->name, '\\'))
613         m->name = 1 + ap_strrchr_c(m->name, '\\');
614
615 #ifdef _OSD_POSIX
616     /* __FILE__ =
617      * "*POSIX(/home/martin/apache/src/modules/standard/mod_info.c)"
618      */
619
620     /* We cannot fix the string in-place, because it's const */
621     if (m->name[strlen(m->name)-1] == ')') {
622         char *tmp = strdup(m->name); /* FIXME: memory leak, albeit a small one */
623         tmp[strlen(tmp)-1] = '\0';
624         m->name = tmp;
625     }
626 #endif /*_OSD_POSIX*/
627
628     ap_add_module_commands(m, p);
629     /*  FIXME: is this the right place to call this?
630      *  It doesn't appear to be
631      */
632     ap_register_hooks(m, p);
633
634     return NULL;
635 }
636
637 /*
638  * remove_module undoes what add_module did. There are some caveats:
639  * when the module is removed, its slot is lost so all the current
640  * per-dir and per-server configurations are invalid. So we should
641  * only ever call this function when you are invalidating almost
642  * all our current data. I.e. when doing a restart.
643  */
644
645 AP_DECLARE(void) ap_remove_module(module *m)
646 {
647     module *modp;
648
649     modp = ap_top_module;
650     if (modp == m) {
651         /* We are the top module, special case */
652         ap_top_module = modp->next;
653         m->next = NULL;
654     }
655     else {
656         /* Not the top module, find use. When found modp will
657          * point to the module _before_ us in the list
658          */
659
660         while (modp && modp->next != m) {
661             modp = modp->next;
662         }
663
664         if (!modp) {
665             /* Uh-oh, this module doesn't exist */
666             ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL,
667                          "Cannot remove module %s: not found in module list",
668                          m->name);
669             return;
670         }
671
672         /* Eliminate us from the module list */
673         modp->next = modp->next->next;
674     }
675
676     free(ap_module_short_names[m->module_index]);
677     ap_module_short_names[m->module_index] = NULL;
678     merger_func_cache[m->module_index] = NULL;
679
680     m->module_index = -1; /* simulate being unloaded, should
681                            * be unnecessary */
682     dynamic_modules--;
683     total_modules--;
684 }
685
686 AP_DECLARE(const char *) ap_add_loaded_module(module *mod, apr_pool_t *p,
687                                               const char *short_name)
688 {
689     module **m;
690     const char *error;
691
692     /*
693      *  Add module pointer to top of chained module list
694      */
695     error = ap_add_module(mod, p, short_name);
696     if (error) {
697         return error;
698     }
699
700     /*
701      *  And module pointer to list of loaded modules
702      *
703      *  Notes: 1. ap_add_module() would already complain if no more space
704      *            exists for adding a dynamically loaded module
705      *         2. ap_add_module() accepts double inclusion, so we have
706      *            to accept this, too.
707      */
708     for (m = ap_loaded_modules; *m != NULL; m++)
709         ;
710     *m++ = mod;
711     *m = NULL;
712
713     return NULL;
714 }
715
716 AP_DECLARE(void) ap_remove_loaded_module(module *mod)
717 {
718     module **m;
719     module **m2;
720     int done;
721
722     /*
723      *  Remove module pointer from chained module list
724      */
725     ap_remove_module(mod);
726
727     /*
728      *  Remove module pointer from list of loaded modules
729      *
730      *  Note: 1. We cannot determine if the module was successfully
731      *           removed by ap_remove_module().
732      *        2. We have not to complain explicity when the module
733      *           is not found because ap_remove_module() did it
734      *           for us already.
735      */
736     for (m = m2 = ap_loaded_modules, done = 0; *m2 != NULL; m2++) {
737         if (*m2 == mod && done == 0)
738             done = 1;
739         else
740             *m++ = *m2;
741     }
742
743     *m = NULL;
744 }
745
746 AP_DECLARE(const char *) ap_setup_prelinked_modules(process_rec *process)
747 {
748     module **m;
749     module **m2;
750     const char *error;
751
752     apr_hook_global_pool=process->pconf;
753
754     rebuild_conf_hash(process->pconf, 0);
755
756     /*
757      *  Initialise total_modules variable and module indices
758      */
759     total_modules = 0;
760     for (m = ap_preloaded_modules; *m != NULL; m++)
761         (*m)->module_index = total_modules++;
762
763     max_modules = total_modules + DYNAMIC_MODULE_LIMIT + 1;
764     conf_vector_length = max_modules;
765
766     /*
767      *  Initialise list of loaded modules and short names
768      */
769     ap_loaded_modules = (module **)apr_palloc(process->pool,
770         sizeof(module *) * conf_vector_length);
771     if (!ap_module_short_names)
772         ap_module_short_names = calloc(sizeof(char *), conf_vector_length);
773
774     if (!merger_func_cache)
775         merger_func_cache = calloc(sizeof(merger_func), conf_vector_length);
776
777     if (ap_loaded_modules == NULL || ap_module_short_names == NULL
778         || merger_func_cache == NULL)
779         return "Ouch! Out of memory in ap_setup_prelinked_modules()!";
780
781     for (m = ap_preloaded_modules, m2 = ap_loaded_modules; *m != NULL; )
782         *m2++ = *m++;
783
784     *m2 = NULL;
785
786     /*
787      *   Initialize chain of linked (=activate) modules
788      */
789     for (m = ap_prelinked_modules; *m != NULL; m++) {
790         error = ap_add_module(*m, process->pconf, NULL);
791         if (error) {
792             return error;
793         }
794     }
795
796     apr_hook_sort_all();
797
798     return NULL;
799 }
800
801 AP_DECLARE(const char *) ap_find_module_name(module *m)
802 {
803     return m->name;
804 }
805
806 AP_DECLARE(const char *) ap_find_module_short_name(int module_index)
807 {
808         if (module_index < 0 || module_index >= conf_vector_length)
809                 return NULL;
810         return ap_module_short_names[module_index];
811 }
812
813 AP_DECLARE(module *) ap_find_linked_module(const char *name)
814 {
815     module *modp;
816
817     for (modp = ap_top_module; modp; modp = modp->next) {
818         if (strcmp(modp->name, name) == 0)
819             return modp;
820     }
821
822     return NULL;
823 }
824
825 /*****************************************************************
826  *
827  * Resource, access, and .htaccess config files now parsed by a common
828  * command loop.
829  *
830  * Let's begin with the basics; parsing the line and
831  * invoking the function...
832  */
833
834 #define AP_MAX_ARGC 64
835
836 static const char *invoke_cmd(const command_rec *cmd, cmd_parms *parms,
837                               void *mconfig, const char *args)
838 {
839     char *w, *w2, *w3;
840     const char *errmsg = NULL;
841
842     if ((parms->override & cmd->req_override) == 0)
843         return apr_pstrcat(parms->pool, cmd->name, " not allowed here", NULL);
844
845     parms->info = cmd->cmd_data;
846     parms->cmd = cmd;
847
848     switch (cmd->args_how) {
849     case RAW_ARGS:
850 #ifdef RESOLVE_ENV_PER_TOKEN
851         args = ap_resolve_env(parms->pool,args);
852 #endif
853         return cmd->AP_RAW_ARGS(parms, mconfig, args);
854
855     case TAKE_ARGV:
856         {
857             char *argv[AP_MAX_ARGC];
858             int argc = 0;
859
860             do {
861                 w = ap_getword_conf(parms->pool, &args);
862                 if (*w == '\0' && *args == '\0') {
863                     break;
864                 }
865                 argv[argc] = w;
866                 argc++;
867             } while (argc < AP_MAX_ARGC && *args != '\0');
868
869             return cmd->AP_TAKE_ARGV(parms, mconfig, argc, argv);
870         }
871
872     case NO_ARGS:
873         if (*args != 0)
874             return apr_pstrcat(parms->pool, cmd->name, " takes no arguments",
875                                NULL);
876
877         return cmd->AP_NO_ARGS(parms, mconfig);
878
879     case TAKE1:
880         w = ap_getword_conf(parms->pool, &args);
881
882         if (*w == '\0' || *args != 0)
883             return apr_pstrcat(parms->pool, cmd->name, " takes one argument",
884                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
885
886         return cmd->AP_TAKE1(parms, mconfig, w);
887
888     case TAKE2:
889         w = ap_getword_conf(parms->pool, &args);
890         w2 = ap_getword_conf(parms->pool, &args);
891
892         if (*w == '\0' || *w2 == '\0' || *args != 0)
893             return apr_pstrcat(parms->pool, cmd->name, " takes two arguments",
894                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
895
896         return cmd->AP_TAKE2(parms, mconfig, w, w2);
897
898     case TAKE12:
899         w = ap_getword_conf(parms->pool, &args);
900         w2 = ap_getword_conf(parms->pool, &args);
901
902         if (*w == '\0' || *args != 0)
903             return apr_pstrcat(parms->pool, cmd->name, " takes 1-2 arguments",
904                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
905
906         return cmd->AP_TAKE2(parms, mconfig, w, *w2 ? w2 : NULL);
907
908     case TAKE3:
909         w = ap_getword_conf(parms->pool, &args);
910         w2 = ap_getword_conf(parms->pool, &args);
911         w3 = ap_getword_conf(parms->pool, &args);
912
913         if (*w == '\0' || *w2 == '\0' || *w3 == '\0' || *args != 0)
914             return apr_pstrcat(parms->pool, cmd->name, " takes three arguments",
915                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
916
917         return cmd->AP_TAKE3(parms, mconfig, w, w2, w3);
918
919     case TAKE23:
920         w = ap_getword_conf(parms->pool, &args);
921         w2 = ap_getword_conf(parms->pool, &args);
922         w3 = *args ? ap_getword_conf(parms->pool, &args) : NULL;
923
924         if (*w == '\0' || *w2 == '\0' || *args != 0)
925             return apr_pstrcat(parms->pool, cmd->name,
926                                " takes two or three arguments",
927                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
928
929         return cmd->AP_TAKE3(parms, mconfig, w, w2, w3);
930
931     case TAKE123:
932         w = ap_getword_conf(parms->pool, &args);
933         w2 = *args ? ap_getword_conf(parms->pool, &args) : NULL;
934         w3 = *args ? ap_getword_conf(parms->pool, &args) : NULL;
935
936         if (*w == '\0' || *args != 0)
937             return apr_pstrcat(parms->pool, cmd->name,
938                                " takes one, two or three arguments",
939                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
940
941         return cmd->AP_TAKE3(parms, mconfig, w, w2, w3);
942
943     case TAKE13:
944         w = ap_getword_conf(parms->pool, &args);
945         w2 = *args ? ap_getword_conf(parms->pool, &args) : NULL;
946         w3 = *args ? ap_getword_conf(parms->pool, &args) : NULL;
947
948         if (*w == '\0' || (w2 && *w2 && !w3) || *args != 0)
949             return apr_pstrcat(parms->pool, cmd->name,
950                                " takes one or three arguments",
951                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
952
953         return cmd->AP_TAKE3(parms, mconfig, w, w2, w3);
954
955     case ITERATE:
956         while (*(w = ap_getword_conf(parms->pool, &args)) != '\0') {
957
958             errmsg = cmd->AP_TAKE1(parms, mconfig, w);
959
960             if (errmsg && strcmp(errmsg, DECLINE_CMD) != 0)
961                 return errmsg;
962         }
963
964         return errmsg;
965
966     case ITERATE2:
967         w = ap_getword_conf(parms->pool, &args);
968
969         if (*w == '\0' || *args == 0)
970             return apr_pstrcat(parms->pool, cmd->name,
971                                " requires at least two arguments",
972                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
973
974         while (*(w2 = ap_getword_conf(parms->pool, &args)) != '\0') {
975
976             errmsg = cmd->AP_TAKE2(parms, mconfig, w, w2);
977
978             if (errmsg && strcmp(errmsg, DECLINE_CMD) != 0)
979                 return errmsg;
980         }
981
982         return errmsg;
983
984     case FLAG:
985         w = ap_getword_conf(parms->pool, &args);
986
987         if (*w == '\0' || (strcasecmp(w, "on") && strcasecmp(w, "off")))
988             return apr_pstrcat(parms->pool, cmd->name, " must be On or Off",
989                                NULL);
990
991         return cmd->AP_FLAG(parms, mconfig, strcasecmp(w, "off") != 0);
992
993     default:
994         return apr_pstrcat(parms->pool, cmd->name,
995                            " is improperly configured internally (server bug)",
996                            NULL);
997     }
998 }
999
1000 AP_CORE_DECLARE(const command_rec *) ap_find_command(const char *name,
1001                                                      const command_rec *cmds)
1002 {
1003     while (cmds->name) {
1004         if (!strcasecmp(name, cmds->name))
1005             return cmds;
1006
1007         ++cmds;
1008     }
1009
1010     return NULL;
1011 }
1012
1013 AP_CORE_DECLARE(const command_rec *) ap_find_command_in_modules(
1014                                           const char *cmd_name, module **mod)
1015 {
1016     const command_rec *cmdp;
1017     module *modp;
1018
1019     for (modp = *mod; modp; modp = modp->next) {
1020         if (modp->cmds && (cmdp = ap_find_command(cmd_name, modp->cmds))) {
1021             *mod = modp;
1022             return cmdp;
1023         }
1024     }
1025
1026     return NULL;
1027 }
1028
1029 AP_CORE_DECLARE(void *) ap_set_config_vectors(server_rec *server,
1030                                               ap_conf_vector_t *section_vector,
1031                                               const char *section,
1032                                               module *mod, apr_pool_t *pconf)
1033 {
1034     void *section_config = ap_get_module_config(section_vector, mod);
1035     void *server_config = ap_get_module_config(server->module_config, mod);
1036
1037     if (!section_config && mod->create_dir_config) {
1038         /* ### need to fix the create_dir_config functions' prototype... */
1039         section_config = (*mod->create_dir_config)(pconf, (char *)section);
1040         ap_set_module_config(section_vector, mod, section_config);
1041     }
1042
1043     if (!server_config && mod->create_server_config) {
1044         server_config = (*mod->create_server_config)(pconf, server);
1045         ap_set_module_config(server->module_config, mod, server_config);
1046     }
1047
1048     return section_config;
1049 }
1050
1051 static const char *execute_now(char *cmd_line, const char *args,
1052                                cmd_parms *parms,
1053                                apr_pool_t *p, apr_pool_t *ptemp,
1054                                ap_directive_t **sub_tree,
1055                                ap_directive_t *parent);
1056
1057 static const char *ap_build_config_sub(apr_pool_t *p, apr_pool_t *temp_pool,
1058                                        const char *l, cmd_parms *parms,
1059                                        ap_directive_t **current,
1060                                        ap_directive_t **curr_parent,
1061                                        ap_directive_t **conftree)
1062 {
1063     const char *retval = NULL;
1064     const char *args;
1065     char *cmd_name;
1066     ap_directive_t *newdir;
1067     module *mod = ap_top_module;
1068     const command_rec *cmd;
1069
1070     if (*l == '#' || *l == '\0')
1071         return NULL;
1072
1073 #if RESOLVE_ENV_PER_TOKEN
1074     args = l;
1075 #else
1076     args = ap_resolve_env(temp_pool, l);
1077 #endif
1078
1079     cmd_name = ap_getword_conf(p, &args);
1080     if (*cmd_name == '\0') {
1081         /* Note: this branch should not occur. An empty line should have
1082          * triggered the exit further above.
1083          */
1084         return NULL;
1085     }
1086
1087     if (cmd_name[1] != '/') {
1088         char *lastc = cmd_name + strlen(cmd_name) - 1;
1089         if (*lastc == '>') {
1090             *lastc = '\0' ;
1091         }
1092         if (cmd_name[0] == '<' && *args == '\0') {
1093             args = ">";
1094         }
1095     }
1096
1097     newdir = apr_pcalloc(p, sizeof(ap_directive_t));
1098     newdir->filename = parms->config_file->name;
1099     newdir->line_num = parms->config_file->line_number;
1100     newdir->directive = cmd_name;
1101     newdir->args = apr_pstrdup(p, args);
1102
1103     if ((cmd = ap_find_command_in_modules(cmd_name, &mod)) != NULL) {
1104         if (cmd->req_override & EXEC_ON_READ) {
1105             ap_directive_t *sub_tree = NULL;
1106
1107             parms->err_directive = newdir;
1108             retval = execute_now(cmd_name, args, parms, p, temp_pool,
1109                                  &sub_tree, *curr_parent);
1110             if (*current) {
1111                 (*current)->next = sub_tree;
1112             }
1113             else {
1114                 *current = sub_tree;
1115                 if (*curr_parent) {
1116                     (*curr_parent)->first_child = (*current);
1117                 }
1118                 if (*current) {
1119                     (*current)->parent = (*curr_parent);
1120                 }
1121             }
1122             if (*current) {
1123                 if (!*conftree) {
1124                     /* Before walking *current to the end of the list,
1125                      * set the head to *current.
1126                      */
1127                     *conftree = *current;
1128                 }
1129                 while ((*current)->next != NULL) {
1130                     (*current) = (*current)->next;
1131                     (*current)->parent = (*curr_parent);
1132                 }
1133             }
1134             return retval;
1135         }
1136     }
1137
1138     if (cmd_name[0] == '<') {
1139         if (cmd_name[1] != '/') {
1140             (*current) = ap_add_node(curr_parent, *current, newdir, 1);
1141         }
1142         else if (*curr_parent == NULL) {
1143             parms->err_directive = newdir;
1144             return apr_pstrcat(p, cmd_name,
1145                                " without matching <", cmd_name + 2,
1146                                " section", NULL);
1147         }
1148         else {
1149             char *bracket = cmd_name + strlen(cmd_name) - 1;
1150
1151             if (*bracket != '>') {
1152                 parms->err_directive = newdir;
1153                 return apr_pstrcat(p, cmd_name,
1154                                    "> directive missing closing '>'", NULL);
1155             }
1156
1157             *bracket = '\0';
1158
1159             if (strcasecmp(cmd_name + 2,
1160                            (*curr_parent)->directive + 1) != 0) {
1161                 parms->err_directive = newdir;
1162                 return apr_pstrcat(p, "Expected </",
1163                                    (*curr_parent)->directive + 1, "> but saw ",
1164                                    cmd_name, ">", NULL);
1165             }
1166
1167             *bracket = '>';
1168
1169             /* done with this section; move up a level */
1170             *current = *curr_parent;
1171             *curr_parent = (*current)->parent;
1172         }
1173     }
1174     else {
1175         *current = ap_add_node(curr_parent, *current, newdir, 0);
1176     }
1177
1178     return retval;
1179 }
1180
1181 AP_DECLARE(const char *) ap_build_cont_config(apr_pool_t *p,
1182                                               apr_pool_t *temp_pool,
1183                                               cmd_parms *parms,
1184                                               ap_directive_t **current,
1185                                               ap_directive_t **curr_parent,
1186                                               char *orig_directive)
1187 {
1188     char *l;
1189     char *bracket;
1190     const char *retval;
1191     ap_directive_t *sub_tree = NULL;
1192     apr_status_t rc;
1193
1194     /* Since this function can be called recursively, allocate
1195      * the temporary 8k string buffer from the temp_pool rather
1196      * than the stack to avoid over-running a fixed length stack.
1197      */
1198     l = apr_palloc(temp_pool, MAX_STRING_LEN);
1199
1200     bracket = apr_pstrcat(temp_pool, orig_directive + 1, ">", NULL);
1201     while ((rc = ap_cfg_getline(l, MAX_STRING_LEN, parms->config_file))
1202            == APR_SUCCESS) {
1203         if (!memcmp(l, "</", 2)
1204             && (strcasecmp(l + 2, bracket) == 0)
1205             && (*curr_parent == NULL)) {
1206             break;
1207         }
1208         retval = ap_build_config_sub(p, temp_pool, l, parms, current,
1209                                      curr_parent, &sub_tree);
1210         if (retval != NULL)
1211             return retval;
1212
1213         if (sub_tree == NULL) {
1214             sub_tree = *curr_parent;
1215         }
1216
1217         if (sub_tree == NULL) {
1218             sub_tree = *current;
1219         }
1220     }
1221     if (rc != APR_EOF && rc != APR_SUCCESS)
1222         return ap_pcfg_strerror(temp_pool, parms->config_file, rc);
1223
1224     *current = sub_tree;
1225     return NULL;
1226 }
1227
1228 static const char *ap_walk_config_sub(const ap_directive_t *current,
1229                                       cmd_parms *parms,
1230                                       ap_conf_vector_t *section_vector)
1231 {
1232     const command_rec *cmd;
1233     ap_mod_list *ml;
1234     char *dir = apr_pstrdup(parms->pool, current->directive);
1235
1236     ap_str_tolower(dir);
1237
1238     ml = apr_hash_get(ap_config_hash, dir, APR_HASH_KEY_STRING);
1239
1240     if (ml == NULL) {
1241         parms->err_directive = current;
1242         return apr_pstrcat(parms->pool, "Invalid command '",
1243                            current->directive,
1244                            "', perhaps misspelled or defined by a module "
1245                            "not included in the server configuration",
1246                            NULL);
1247     }
1248
1249     for ( ; ml != NULL; ml = ml->next) {
1250         void *dir_config = ap_set_config_vectors(parms->server,
1251                                                  section_vector,
1252                                                  parms->path,
1253                                                  ml->m,
1254                                                  parms->pool);
1255         const char *retval;
1256         cmd = ml->cmd;
1257
1258         /* Once was enough? */
1259         if (cmd->req_override & EXEC_ON_READ) {
1260             continue;
1261         }
1262
1263         retval = invoke_cmd(cmd, parms, dir_config, current->args);
1264
1265         if (retval != NULL && strcmp(retval, DECLINE_CMD) != 0) {
1266             /* If the directive in error has already been set, don't
1267              * replace it.  Otherwise, an error inside a container
1268              * will be reported as occuring on the first line of the
1269              * container.
1270              */
1271             if (!parms->err_directive) {
1272                 parms->err_directive = current;
1273             }
1274             return retval;
1275         }
1276     }
1277
1278     return NULL;
1279 }
1280
1281 AP_DECLARE(const char *) ap_walk_config(ap_directive_t *current,
1282                                         cmd_parms *parms,
1283                                         ap_conf_vector_t *section_vector)
1284 {
1285     ap_conf_vector_t *oldconfig = parms->context;
1286
1287     parms->context = section_vector;
1288
1289     /* scan through all directives, executing each one */
1290     for (; current != NULL; current = current->next) {
1291         const char *errmsg;
1292
1293         parms->directive = current;
1294
1295         /* actually parse the command and execute the correct function */
1296         errmsg = ap_walk_config_sub(current, parms, section_vector);
1297         if (errmsg != NULL) {
1298             /* restore the context (just in case) */
1299             parms->context = oldconfig;
1300             return errmsg;
1301         }
1302     }
1303
1304     parms->context = oldconfig;
1305     return NULL;
1306 }
1307
1308 AP_DECLARE(const char *) ap_build_config(cmd_parms *parms,
1309                                          apr_pool_t *p, apr_pool_t *temp_pool,
1310                                          ap_directive_t **conftree)
1311 {
1312     ap_directive_t *current = *conftree;
1313     ap_directive_t *curr_parent = NULL;
1314     char *l = apr_palloc (temp_pool, MAX_STRING_LEN);
1315     const char *errmsg;
1316     ap_directive_t **last_ptr = NULL;
1317     apr_status_t rc;
1318
1319     if (current != NULL) {
1320         /* If we have to traverse the whole tree again for every included
1321          * config file, the required time grows as O(n^2) with the number of
1322          * files. This can be a significant delay for large configurations.
1323          * Therefore we cache a pointer to the last node.
1324          */
1325         last_ptr = &(current->last);
1326
1327         if(last_ptr && *last_ptr) {
1328             current = *last_ptr;
1329         }
1330
1331         while (current->next) {
1332             current = current->next;
1333         }
1334
1335         if(last_ptr) {
1336             /* update cached pointer to last node */
1337             *last_ptr = current;
1338         }
1339     }
1340
1341     while ((rc = ap_cfg_getline(l, MAX_STRING_LEN, parms->config_file))
1342            == APR_SUCCESS) {
1343         errmsg = ap_build_config_sub(p, temp_pool, l, parms,
1344                                      &current, &curr_parent, conftree);
1345         if (errmsg != NULL)
1346             return errmsg;
1347
1348         if (*conftree == NULL && curr_parent != NULL) {
1349             *conftree = curr_parent;
1350         }
1351
1352         if (*conftree == NULL && current != NULL) {
1353             *conftree = current;
1354         }
1355     }
1356     if (rc != APR_EOF && rc != APR_SUCCESS)
1357         return ap_pcfg_strerror(temp_pool, parms->config_file, rc);
1358
1359     if (curr_parent != NULL) {
1360         errmsg = "";
1361
1362         while (curr_parent != NULL) {
1363             errmsg = apr_psprintf(p, "%s%s%s:%u: %s> was not closed.",
1364                                   errmsg,
1365                                   *errmsg == '\0' ? "" : APR_EOL_STR,
1366                                   curr_parent->filename,
1367                                   curr_parent->line_num,
1368                                   curr_parent->directive);
1369
1370             parms->err_directive = curr_parent;
1371             curr_parent = curr_parent->parent;
1372         }
1373
1374         return errmsg;
1375     }
1376
1377     return NULL;
1378 }
1379
1380 /*
1381  * Generic command functions...
1382  */
1383
1384 AP_DECLARE_NONSTD(const char *) ap_set_string_slot(cmd_parms *cmd,
1385                                                    void *struct_ptr,
1386                                                    const char *arg)
1387 {
1388     int offset = (int)(long)cmd->info;
1389
1390     *(const char **)((char *)struct_ptr + offset) = arg;
1391
1392     return NULL;
1393 }
1394
1395 AP_DECLARE_NONSTD(const char *) ap_set_int_slot(cmd_parms *cmd,
1396                                                 void *struct_ptr,
1397                                                 const char *arg)
1398 {
1399     char *endptr;
1400     char *error_str = NULL;
1401     int offset = (int)(long)cmd->info;
1402
1403     *(int *)((char*)struct_ptr + offset) = strtol(arg, &endptr, 10);
1404
1405     if ((*arg == '\0') || (*endptr != '\0')) {
1406         error_str = apr_psprintf(cmd->pool,
1407                      "Invalid value for directive %s, expected integer",
1408                      cmd->directive->directive);
1409     }
1410
1411     return error_str;
1412 }
1413
1414 AP_DECLARE_NONSTD(const char *) ap_set_string_slot_lower(cmd_parms *cmd,
1415                                                          void *struct_ptr,
1416                                                          const char *arg_)
1417 {
1418     char *arg = apr_pstrdup(cmd->pool,arg_);
1419     int offset = (int)(long)cmd->info;
1420
1421     ap_str_tolower(arg);
1422     *(char **)((char *)struct_ptr + offset) = arg;
1423
1424     return NULL;
1425 }
1426
1427 AP_DECLARE_NONSTD(const char *) ap_set_flag_slot(cmd_parms *cmd,
1428                                                  void *struct_ptr_v, int arg)
1429 {
1430     int offset = (int)(long)cmd->info;
1431     char *struct_ptr = (char *)struct_ptr_v;
1432
1433     *(int *)(struct_ptr + offset) = arg ? 1 : 0;
1434
1435     return NULL;
1436 }
1437
1438 AP_DECLARE_NONSTD(const char *) ap_set_flag_slot_char(cmd_parms *cmd,
1439                                                       void *struct_ptr_v, int arg)
1440 {
1441     int offset = (int)(long)cmd->info;
1442     char *struct_ptr = (char *)struct_ptr_v;
1443
1444     *(struct_ptr + offset) = arg ? 1 : 0;
1445
1446     return NULL;
1447 }
1448
1449
1450 AP_DECLARE_NONSTD(const char *) ap_set_file_slot(cmd_parms *cmd, void *struct_ptr,
1451                                                  const char *arg)
1452 {
1453     /* Prepend server_root to relative arg.
1454      * This allows most args to be independent of server_root,
1455      * so the server can be moved or mirrored with less pain.
1456      */
1457     const char *path;
1458     int offset = (int)(long)cmd->info;
1459
1460     path = ap_server_root_relative(cmd->pool, arg);
1461
1462     if (!path) {
1463         return apr_pstrcat(cmd->pool, "Invalid file path ",
1464                            arg, NULL);
1465     }
1466
1467     *(const char **) ((char*)struct_ptr + offset) = path;
1468
1469     return NULL;
1470 }
1471
1472 AP_DECLARE_NONSTD(const char *) ap_set_deprecated(cmd_parms *cmd,
1473                                                   void *struct_ptr,
1474                                                   const char *arg)
1475 {
1476     return cmd->cmd->errmsg;
1477 }
1478
1479 AP_DECLARE(void) ap_reset_module_loglevels(struct ap_logconf *l, int val)
1480 {
1481     if (l->module_levels)
1482         memset(l->module_levels, val, conf_vector_length);
1483 }
1484
1485 AP_DECLARE(void) ap_set_module_loglevel(apr_pool_t *pool, struct ap_logconf *l,
1486                                         int index, int level)
1487 {
1488     if (!l->module_levels) {
1489         l->module_levels = apr_palloc(pool, conf_vector_length);
1490         if (l->level == APLOG_UNSET) {
1491                 ap_reset_module_loglevels(l, APLOG_UNSET);
1492         }
1493         else {
1494                 ap_reset_module_loglevels(l, APLOG_NO_MODULE);
1495         }
1496     }
1497
1498     l->module_levels[index] = level;
1499 }
1500
1501 /*****************************************************************
1502  *
1503  * Reading whole config files...
1504  */
1505
1506 static cmd_parms default_parms =
1507 {NULL, 0, 0, -1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
1508
1509 AP_DECLARE(char *) ap_server_root_relative(apr_pool_t *p, const char *file)
1510 {
1511     char *newpath = NULL;
1512     apr_status_t rv;
1513     rv = apr_filepath_merge(&newpath, ap_server_root, file,
1514                             APR_FILEPATH_TRUENAME, p);
1515     if (newpath && (rv == APR_SUCCESS || APR_STATUS_IS_EPATHWILD(rv)
1516                                       || APR_STATUS_IS_ENOENT(rv)
1517                                       || APR_STATUS_IS_ENOTDIR(rv))) {
1518         return newpath;
1519     }
1520     else {
1521         return NULL;
1522     }
1523 }
1524
1525 AP_DECLARE(const char *) ap_soak_end_container(cmd_parms *cmd, char *directive)
1526 {
1527     char l[MAX_STRING_LEN];
1528     const char *args;
1529     char *cmd_name;
1530     apr_status_t rc;
1531
1532     while((rc = ap_cfg_getline(l, MAX_STRING_LEN, cmd->config_file))
1533           == APR_SUCCESS) {
1534 #if RESOLVE_ENV_PER_TOKEN
1535         args = l;
1536 #else
1537         args = ap_resolve_env(cmd->temp_pool, l);
1538 #endif
1539
1540         cmd_name = ap_getword_conf(cmd->temp_pool, &args);
1541         if (cmd_name[0] == '<') {
1542             if (cmd_name[1] == '/') {
1543                 cmd_name[strlen(cmd_name) - 1] = '\0';
1544
1545                 if (strcasecmp(cmd_name + 2, directive + 1) != 0) {
1546                     return apr_pstrcat(cmd->pool, "Expected </",
1547                                        directive + 1, "> but saw ",
1548                                        cmd_name, ">", NULL);
1549                 }
1550
1551                 return NULL; /* found end of container */
1552             }
1553             else {
1554                 const char *msg;
1555
1556                 if (*args == '\0' && cmd_name[strlen(cmd_name) - 1] == '>') {
1557                     cmd_name[strlen(cmd_name) - 1] = '\0';
1558                 }
1559
1560                 if ((msg = ap_soak_end_container(cmd, cmd_name)) != NULL) {
1561                     return msg;
1562                 }
1563             }
1564         }
1565     }
1566     if (rc != APR_EOF && rc != APR_SUCCESS)
1567         return ap_pcfg_strerror(cmd->temp_pool, cmd->config_file, rc);
1568
1569     return apr_pstrcat(cmd->pool, "Expected </",
1570                        directive + 1, "> before end of configuration",
1571                        NULL);
1572 }
1573
1574 static const char *execute_now(char *cmd_line, const char *args,
1575                                cmd_parms *parms,
1576                                apr_pool_t *p, apr_pool_t *ptemp,
1577                                ap_directive_t **sub_tree,
1578                                ap_directive_t *parent)
1579 {
1580     const command_rec *cmd;
1581     ap_mod_list *ml;
1582     char *dir = apr_pstrdup(parms->temp_pool, cmd_line);
1583
1584     ap_str_tolower(dir);
1585
1586     ml = apr_hash_get(ap_config_hash, dir, APR_HASH_KEY_STRING);
1587
1588     if (ml == NULL) {
1589         return apr_pstrcat(parms->pool, "Invalid command '",
1590                            cmd_line,
1591                            "', perhaps misspelled or defined by a module "
1592                            "not included in the server configuration",
1593                            NULL);
1594     }
1595
1596     for ( ; ml != NULL; ml = ml->next) {
1597         const char *retval;
1598         cmd = ml->cmd;
1599
1600         retval = invoke_cmd(cmd, parms, sub_tree, args);
1601
1602         if (retval != NULL) {
1603             return retval;
1604         }
1605     }
1606
1607     return NULL;
1608 }
1609
1610 /* This structure and the following functions are needed for the
1611  * table-based config file reading. They are passed to the
1612  * cfg_open_custom() routine.
1613  */
1614
1615 /* Structure to be passed to cfg_open_custom(): it contains an
1616  * index which is incremented from 0 to nelts on each call to
1617  * cfg_getline() (which in turn calls arr_elts_getstr())
1618  * and an apr_array_header_t pointer for the string array.
1619  */
1620 typedef struct {
1621     apr_array_header_t *array;
1622     int curr_idx;
1623 } arr_elts_param_t;
1624
1625
1626 /* arr_elts_getstr() returns the next line from the string array. */
1627 static apr_status_t arr_elts_getstr(void *buf, size_t bufsiz, void *param)
1628 {
1629     arr_elts_param_t *arr_param = (arr_elts_param_t *)param;
1630     char *elt;
1631
1632     /* End of array reached? */
1633     if (++arr_param->curr_idx > arr_param->array->nelts)
1634         return APR_EOF;
1635
1636     /* return the line */
1637     elt = ((char **)arr_param->array->elts)[arr_param->curr_idx - 1];
1638     if (apr_cpystrn(buf, elt, bufsiz) - (char *)buf >= bufsiz - 1)
1639         return APR_ENOSPC;
1640     return APR_SUCCESS;
1641 }
1642
1643
1644 /* arr_elts_close(): dummy close routine (makes sure no more lines can be read) */
1645 static apr_status_t arr_elts_close(void *param)
1646 {
1647     arr_elts_param_t *arr_param = (arr_elts_param_t *)param;
1648
1649     arr_param->curr_idx = arr_param->array->nelts;
1650
1651     return APR_SUCCESS;
1652 }
1653
1654 static const char *process_command_config(server_rec *s,
1655                                           apr_array_header_t *arr,
1656                                           ap_directive_t **conftree,
1657                                           apr_pool_t *p,
1658                                           apr_pool_t *ptemp)
1659 {
1660     const char *errmsg;
1661     cmd_parms parms;
1662     arr_elts_param_t arr_parms;
1663
1664     arr_parms.curr_idx = 0;
1665     arr_parms.array = arr;
1666
1667     if (ap_config_hash == NULL) {
1668         rebuild_conf_hash(s->process->pconf, 1);
1669     }
1670
1671     parms = default_parms;
1672     parms.pool = p;
1673     parms.temp_pool = ptemp;
1674     parms.server = s;
1675     parms.override = (RSRC_CONF | OR_ALL) & ~(OR_AUTHCFG | OR_LIMIT);
1676     parms.override_opts = OPT_ALL | OPT_SYM_OWNER | OPT_MULTI;
1677
1678     parms.config_file = ap_pcfg_open_custom(p, "-c/-C directives",
1679                                             &arr_parms, NULL,
1680                                             arr_elts_getstr, arr_elts_close);
1681
1682     errmsg = ap_build_config(&parms, p, ptemp, conftree);
1683     ap_cfg_closefile(parms.config_file);
1684
1685     if (errmsg) {
1686         return apr_pstrcat(p, "Syntax error in -C/-c directive: ", errmsg,
1687                            NULL);
1688     }
1689
1690     return NULL;
1691 }
1692
1693 typedef struct {
1694     const char *fname;
1695 } fnames;
1696
1697 static int fname_alphasort(const void *fn1, const void *fn2)
1698 {
1699     const fnames *f1 = fn1;
1700     const fnames *f2 = fn2;
1701
1702     return strcmp(f1->fname,f2->fname);
1703 }
1704
1705 AP_DECLARE(const char *) ap_process_resource_config(server_rec *s,
1706                                                     const char *fname,
1707                                                     ap_directive_t **conftree,
1708                                                     apr_pool_t *p,
1709                                                     apr_pool_t *ptemp)
1710 {
1711     ap_configfile_t *cfp;
1712     cmd_parms parms;
1713     apr_status_t rv;
1714     const char *error;
1715
1716     parms = default_parms;
1717     parms.pool = p;
1718     parms.temp_pool = ptemp;
1719     parms.server = s;
1720     parms.override = (RSRC_CONF | OR_ALL) & ~(OR_AUTHCFG | OR_LIMIT);
1721     parms.override_opts = OPT_ALL | OPT_SYM_OWNER | OPT_MULTI;
1722
1723     rv = ap_pcfg_openfile(&cfp, p, fname);
1724     if (rv != APR_SUCCESS) {
1725         char errmsg[120];
1726         return apr_psprintf(p, "Could not open configuration file %s: %s",
1727                             fname, apr_strerror(rv, errmsg, sizeof errmsg));
1728     }
1729
1730     parms.config_file = cfp;
1731     error = ap_build_config(&parms, p, ptemp, conftree);
1732     ap_cfg_closefile(cfp);
1733
1734     if (error) {
1735         if (parms.err_directive)
1736             return apr_psprintf(p, "Syntax error on line %d of %s: %s",
1737                                 parms.err_directive->line_num,
1738                                 parms.err_directive->filename, error);
1739         else
1740             return error;
1741     }
1742
1743     return NULL;
1744 }
1745
1746 static const char *process_resource_config_nofnmatch(server_rec *s,
1747                                                      const char *fname,
1748                                                      ap_directive_t **conftree,
1749                                                      apr_pool_t *p,
1750                                                      apr_pool_t *ptemp,
1751                                                      unsigned depth,
1752                                                      int optional)
1753 {
1754     const char *error;
1755     apr_status_t rv;
1756
1757     if (ap_is_directory(ptemp, fname)) {
1758         apr_dir_t *dirp;
1759         apr_finfo_t dirent;
1760         int current;
1761         apr_array_header_t *candidates = NULL;
1762         fnames *fnew;
1763         char *path = apr_pstrdup(ptemp, fname);
1764
1765         if (++depth > AP_MAX_INCLUDE_DIR_DEPTH) {
1766             return apr_psprintf(p, "Directory %s exceeds the maximum include "
1767                                 "directory nesting level of %u. You have "
1768                                 "probably a recursion somewhere.", path,
1769                                 AP_MAX_INCLUDE_DIR_DEPTH);
1770         }
1771
1772         /*
1773          * first course of business is to grok all the directory
1774          * entries here and store 'em away. Recall we need full pathnames
1775          * for this.
1776          */
1777         rv = apr_dir_open(&dirp, path, ptemp);
1778         if (rv != APR_SUCCESS) {
1779             char errmsg[120];
1780             return apr_psprintf(p, "Could not open config directory %s: %s",
1781                                 path, apr_strerror(rv, errmsg, sizeof errmsg));
1782         }
1783
1784         candidates = apr_array_make(ptemp, 1, sizeof(fnames));
1785         while (apr_dir_read(&dirent, APR_FINFO_DIRENT, dirp) == APR_SUCCESS) {
1786             /* strip out '.' and '..' */
1787             if (strcmp(dirent.name, ".")
1788                 && strcmp(dirent.name, "..")) {
1789                 fnew = (fnames *) apr_array_push(candidates);
1790                 fnew->fname = ap_make_full_path(ptemp, path, dirent.name);
1791             }
1792         }
1793
1794         apr_dir_close(dirp);
1795         if (candidates->nelts != 0) {
1796             qsort((void *) candidates->elts, candidates->nelts,
1797                   sizeof(fnames), fname_alphasort);
1798
1799             /*
1800              * Now recurse these... we handle errors and subdirectories
1801              * via the recursion, which is nice
1802              */
1803             for (current = 0; current < candidates->nelts; ++current) {
1804                 fnew = &((fnames *) candidates->elts)[current];
1805                 error = process_resource_config_nofnmatch(s, fnew->fname,
1806                                                           conftree, p, ptemp,
1807                                                           depth, optional);
1808                 if (error) {
1809                     return error;
1810                 }
1811             }
1812         }
1813
1814         return NULL;
1815     }
1816
1817     return ap_process_resource_config(s, fname, conftree, p, ptemp);
1818 }
1819
1820 static const char *process_resource_config_fnmatch(server_rec *s,
1821                                                    const char *path,
1822                                                    const char *fname,
1823                                                    ap_directive_t **conftree,
1824                                                    apr_pool_t *p,
1825                                                    apr_pool_t *ptemp,
1826                                                    unsigned depth,
1827                                                    int optional)
1828 {
1829     const char *rest;
1830     apr_status_t rv;
1831     apr_dir_t *dirp;
1832     apr_finfo_t dirent;
1833     apr_array_header_t *candidates = NULL;
1834     fnames *fnew;
1835     int current;
1836
1837     /* find the first part of the filename */
1838     rest = ap_strchr_c(fname, '/');
1839     if (rest) {
1840         fname = apr_pstrndup(ptemp, fname, rest - fname);
1841         rest++;
1842     }
1843
1844     /* optimisation - if the filename isn't a wildcard, process it directly */
1845     if (!apr_fnmatch_test(fname)) {
1846         path = ap_make_full_path(ptemp, path, fname);
1847         if (!rest) {
1848             return process_resource_config_nofnmatch(s, path,
1849                                                      conftree, p,
1850                                                      ptemp, 0, optional);
1851         }
1852         else {
1853             return process_resource_config_fnmatch(s, path, rest,
1854                                                    conftree, p,
1855                                                    ptemp, 0, optional);
1856         }
1857     }
1858
1859     /*
1860      * first course of business is to grok all the directory
1861      * entries here and store 'em away. Recall we need full pathnames
1862      * for this.
1863      */
1864     rv = apr_dir_open(&dirp, path, ptemp);
1865     if (rv != APR_SUCCESS) {
1866         char errmsg[120];
1867         return apr_psprintf(p, "Could not open config directory %s: %s",
1868                             path, apr_strerror(rv, errmsg, sizeof errmsg));
1869     }
1870
1871     candidates = apr_array_make(ptemp, 1, sizeof(fnames));
1872     while (apr_dir_read(&dirent, APR_FINFO_DIRENT | APR_FINFO_TYPE, dirp) == APR_SUCCESS) {
1873         /* strip out '.' and '..' */
1874         if (strcmp(dirent.name, ".")
1875             && strcmp(dirent.name, "..")
1876             && (apr_fnmatch(fname, dirent.name,
1877                             APR_FNM_PERIOD) == APR_SUCCESS)) {
1878             const char *full_path = ap_make_full_path(ptemp, path, dirent.name);
1879             /* If matching internal to path, and we happen to match something
1880              * other than a directory, skip it
1881              */
1882             if (rest && (rv == APR_SUCCESS) && (dirent.filetype != APR_DIR)) {
1883                 continue;
1884             }
1885             fnew = (fnames *) apr_array_push(candidates);
1886             fnew->fname = full_path;
1887         }
1888     }
1889
1890     apr_dir_close(dirp);
1891     if (candidates->nelts != 0) {
1892         const char *error;
1893
1894         qsort((void *) candidates->elts, candidates->nelts,
1895               sizeof(fnames), fname_alphasort);
1896
1897         /*
1898          * Now recurse these... we handle errors and subdirectories
1899          * via the recursion, which is nice
1900          */
1901         for (current = 0; current < candidates->nelts; ++current) {
1902             fnew = &((fnames *) candidates->elts)[current];
1903             if (!rest) {
1904                 error = process_resource_config_nofnmatch(s, fnew->fname,
1905                                                           conftree, p,
1906                                                           ptemp, 0, optional);
1907             }
1908             else {
1909                 error = process_resource_config_fnmatch(s, fnew->fname, rest,
1910                                                         conftree, p,
1911                                                         ptemp, 0, optional);
1912             }
1913             if (error) {
1914                 return error;
1915             }
1916         }
1917     }
1918     else {
1919
1920         if (!optional) {
1921             return apr_psprintf(p, "No matches for the wildcard '%s' in '%s', failing "
1922                                    "(use IncludeOptional if required)", fname, path);
1923         }
1924     }
1925
1926     return NULL;
1927 }
1928
1929 AP_DECLARE(const char *) ap_process_fnmatch_configs(server_rec *s,
1930                                                     const char *fname,
1931                                                     ap_directive_t **conftree,
1932                                                     apr_pool_t *p,
1933                                                     apr_pool_t *ptemp,
1934                                                     int optional)
1935 {
1936     /* XXX: lstat() won't work on the wildcard pattern...
1937      */
1938
1939     /* don't require conf/httpd.conf if we have a -C or -c switch */
1940     if ((ap_server_pre_read_config->nelts
1941         || ap_server_post_read_config->nelts)
1942         && !(strcmp(fname, ap_server_root_relative(ptemp, SERVER_CONFIG_FILE)))) {
1943         apr_finfo_t finfo;
1944
1945         if (apr_stat(&finfo, fname, APR_FINFO_LINK | APR_FINFO_TYPE, ptemp) != APR_SUCCESS)
1946             return NULL;
1947     }
1948
1949     if (!apr_fnmatch_test(fname)) {
1950         return ap_process_resource_config(s, fname, conftree, p, ptemp);
1951     }
1952     else {
1953         apr_status_t status;
1954         const char *rootpath, *filepath = fname;
1955
1956         /* locate the start of the directories proper */
1957         status = apr_filepath_root(&rootpath, &filepath, APR_FILEPATH_TRUENAME, ptemp);
1958
1959         /* we allow APR_SUCCESS and APR_EINCOMPLETE */
1960         if (APR_ERELATIVE == status) {
1961             return apr_pstrcat(p, "Include must have an absolute path, ", fname, NULL);
1962         }
1963         else if (APR_EBADPATH == status) {
1964             return apr_pstrcat(p, "Include has a bad path, ", fname, NULL);
1965         }
1966
1967         /* walk the filepath */
1968         return process_resource_config_fnmatch(s, rootpath, filepath, conftree, p, ptemp,
1969                                                0, optional);
1970
1971     }
1972
1973     return NULL;
1974 }
1975
1976 AP_DECLARE(int) ap_process_config_tree(server_rec *s,
1977                                        ap_directive_t *conftree,
1978                                        apr_pool_t *p,
1979                                        apr_pool_t *ptemp)
1980 {
1981     const char *errmsg;
1982     cmd_parms parms;
1983
1984     parms = default_parms;
1985     parms.pool = p;
1986     parms.temp_pool = ptemp;
1987     parms.server = s;
1988     parms.override = (RSRC_CONF | OR_ALL) & ~(OR_AUTHCFG | OR_LIMIT);
1989     parms.override_opts = OPT_ALL | OPT_SYM_OWNER | OPT_MULTI;
1990     parms.limited = -1;
1991
1992     errmsg = ap_walk_config(conftree, &parms, s->lookup_defaults);
1993     if (errmsg) {
1994         if (parms.err_directive)
1995             ap_log_perror(APLOG_MARK, APLOG_STARTUP, 0, p,
1996                           "Syntax error on line %d of %s:",
1997                           parms.err_directive->line_num,
1998                           parms.err_directive->filename);
1999         ap_log_perror(APLOG_MARK, APLOG_STARTUP, 0, p,
2000                      "%s", errmsg);
2001         return HTTP_INTERNAL_SERVER_ERROR;
2002     }
2003
2004     return OK;
2005 }
2006
2007 AP_CORE_DECLARE(int) ap_parse_htaccess(ap_conf_vector_t **result,
2008                                        request_rec *r, int override,
2009                                        int override_opts,
2010                                        const char *d, const char *access_name)
2011 {
2012     ap_configfile_t *f = NULL;
2013     cmd_parms parms;
2014     char *filename = NULL;
2015     const struct htaccess_result *cache;
2016     struct htaccess_result *new;
2017     ap_conf_vector_t *dc = NULL;
2018     apr_status_t status;
2019
2020     /* firstly, search cache */
2021     for (cache = r->htaccess; cache != NULL; cache = cache->next) {
2022         if (cache->override == override && strcmp(cache->dir, d) == 0) {
2023             *result = cache->htaccess;
2024             return OK;
2025         }
2026     }
2027
2028     parms = default_parms;
2029     parms.override = override;
2030     parms.override_opts = override_opts;
2031     parms.pool = r->pool;
2032     parms.temp_pool = r->pool;
2033     parms.server = r->server;
2034     parms.path = apr_pstrdup(r->pool, d);
2035
2036     /* loop through the access names and find the first one */
2037     while (access_name[0]) {
2038         /* AFAICT; there is no use of the actual 'filename' against
2039          * any canonicalization, so we will simply take the given
2040          * name, ignoring case sensitivity and aliases
2041          */
2042         filename = ap_make_full_path(r->pool, d,
2043                                      ap_getword_conf(r->pool, &access_name));
2044         status = ap_pcfg_openfile(&f, r->pool, filename);
2045
2046         if (status == APR_SUCCESS) {
2047             const char *errmsg;
2048             ap_directive_t *temptree = NULL;
2049
2050             dc = ap_create_per_dir_config(r->pool);
2051
2052             parms.config_file = f;
2053             errmsg = ap_build_config(&parms, r->pool, r->pool, &temptree);
2054             if (errmsg == NULL)
2055                 errmsg = ap_walk_config(temptree, &parms, dc);
2056
2057             ap_cfg_closefile(f);
2058
2059             if (errmsg) {
2060                 ap_log_rerror(APLOG_MARK, APLOG_ALERT, 0, r,
2061                               "%s: %s", filename, errmsg);
2062                 return HTTP_INTERNAL_SERVER_ERROR;
2063             }
2064
2065             *result = dc;
2066             break;
2067         }
2068         else {
2069             if (!APR_STATUS_IS_ENOENT(status)
2070                 && !APR_STATUS_IS_ENOTDIR(status)) {
2071                 ap_log_rerror(APLOG_MARK, APLOG_CRIT, status, r,
2072                               "%s pcfg_openfile: unable to check htaccess file, "
2073                               "ensure it is readable and that '%s' " 
2074                               "is executable",
2075                               filename, d);
2076                 apr_table_setn(r->notes, "error-notes",
2077                                "Server unable to read htaccess file, denying "
2078                                "access to be safe");
2079                 return HTTP_FORBIDDEN;
2080             }
2081         }
2082     }
2083
2084     /* cache it */
2085     new = apr_palloc(r->pool, sizeof(struct htaccess_result));
2086     new->dir = parms.path;
2087     new->override = override;
2088     new->override_opts = override_opts;
2089     new->htaccess = dc;
2090
2091     /* add to head of list */
2092     new->next = r->htaccess;
2093     r->htaccess = new;
2094
2095     return OK;
2096 }
2097
2098 AP_CORE_DECLARE(const char *) ap_init_virtual_host(apr_pool_t *p,
2099                                                    const char *hostname,
2100                                                    server_rec *main_server,
2101                                                    server_rec **ps)
2102 {
2103     server_rec *s = (server_rec *) apr_pcalloc(p, sizeof(server_rec));
2104
2105     /* TODO: this crap belongs in http_core */
2106     s->process = main_server->process;
2107     s->server_admin = NULL;
2108     s->server_hostname = NULL;
2109     s->server_scheme = NULL;
2110     s->error_fname = NULL;
2111     s->timeout = 0;
2112     s->keep_alive_timeout = 0;
2113     s->keep_alive = -1;
2114     s->keep_alive_max = -1;
2115     s->error_log = main_server->error_log;
2116     s->log.level = APLOG_UNSET;
2117     s->log.module_levels = NULL;
2118     /* useful default, otherwise we get a port of 0 on redirects */
2119     s->port = main_server->port;
2120     s->next = NULL;
2121
2122     s->is_virtual = 1;
2123     s->names = apr_array_make(p, 4, sizeof(char **));
2124     s->wild_names = apr_array_make(p, 4, sizeof(char **));
2125
2126     s->module_config = create_empty_config(p);
2127     s->lookup_defaults = ap_create_per_dir_config(p);
2128
2129     s->limit_req_line = main_server->limit_req_line;
2130     s->limit_req_fieldsize = main_server->limit_req_fieldsize;
2131     s->limit_req_fields = main_server->limit_req_fields;
2132
2133     *ps = s;
2134
2135     return ap_parse_vhost_addrs(p, hostname, s);
2136 }
2137
2138 AP_DECLARE(struct ap_logconf *) ap_new_log_config(apr_pool_t *p,
2139                                                   const struct ap_logconf *old)
2140 {
2141     struct ap_logconf *l = apr_pcalloc(p, sizeof(struct ap_logconf));
2142     if (old) {
2143         l->level = old->level;
2144         if (old->module_levels) {
2145             l->module_levels =
2146                 apr_pmemdup(p, old->module_levels, conf_vector_length);
2147         }
2148     }
2149     else {
2150         l->level = APLOG_UNSET;
2151     }
2152     return l;
2153 }
2154
2155 AP_DECLARE(void) ap_merge_log_config(const struct ap_logconf *old_conf,
2156                                      struct ap_logconf *new_conf)
2157 {
2158     if (new_conf->level != APLOG_UNSET) {
2159         /* Setting the main loglevel resets all per-module log levels.
2160          * I.e. if new->level has been set, we must ignore old->module_levels.
2161          */
2162         return;
2163     }
2164
2165     new_conf->level = old_conf->level;
2166     if (new_conf->module_levels == NULL) {
2167         new_conf->module_levels = old_conf->module_levels;
2168     }
2169     else if (old_conf->module_levels != NULL) {
2170         int i;
2171         for (i = 0; i < conf_vector_length; i++) {
2172             if (new_conf->module_levels[i] == APLOG_UNSET)
2173                 new_conf->module_levels[i] = old_conf->module_levels[i];
2174         }
2175     }
2176 }
2177
2178 AP_DECLARE(void) ap_fixup_virtual_hosts(apr_pool_t *p, server_rec *main_server)
2179 {
2180     server_rec *virt;
2181     core_dir_config *dconf = ap_get_module_config(main_server->lookup_defaults,
2182                                                   &core_module);
2183     dconf->log = &main_server->log;
2184
2185     for (virt = main_server->next; virt; virt = virt->next) {
2186         merge_server_configs(p, main_server->module_config,
2187                              virt->module_config);
2188
2189         virt->lookup_defaults =
2190             ap_merge_per_dir_configs(p, main_server->lookup_defaults,
2191                                      virt->lookup_defaults);
2192
2193         if (virt->server_admin == NULL)
2194             virt->server_admin = main_server->server_admin;
2195
2196         if (virt->timeout == 0)
2197             virt->timeout = main_server->timeout;
2198
2199         if (virt->keep_alive_timeout == 0)
2200             virt->keep_alive_timeout = main_server->keep_alive_timeout;
2201
2202         if (virt->keep_alive == -1)
2203             virt->keep_alive = main_server->keep_alive;
2204
2205         if (virt->keep_alive_max == -1)
2206             virt->keep_alive_max = main_server->keep_alive_max;
2207
2208         ap_merge_log_config(&main_server->log, &virt->log);
2209
2210         dconf = ap_get_module_config(virt->lookup_defaults, &core_module);
2211         dconf->log = &virt->log;
2212
2213         /* XXX: this is really something that should be dealt with by a
2214          * post-config api phase
2215          */
2216         ap_core_reorder_directories(p, virt);
2217     }
2218
2219     ap_core_reorder_directories(p, main_server);
2220 }
2221
2222 /*****************************************************************
2223  *
2224  * Getting *everything* configured...
2225  */
2226
2227 static void init_config_globals(apr_pool_t *p)
2228 {
2229     /* Global virtual host hash bucket pointers.  Init to null. */
2230     ap_init_vhost_config(p);
2231 }
2232
2233 static server_rec *init_server_config(process_rec *process, apr_pool_t *p)
2234 {
2235     apr_status_t rv;
2236     server_rec *s = (server_rec *) apr_pcalloc(p, sizeof(server_rec));
2237
2238     apr_file_open_stderr(&s->error_log, p);
2239     s->process = process;
2240     s->port = 0;
2241     s->server_admin = DEFAULT_ADMIN;
2242     s->server_hostname = NULL;
2243     s->server_scheme = NULL;
2244     s->error_fname = DEFAULT_ERRORLOG;
2245     s->log.level = DEFAULT_LOGLEVEL;
2246     s->log.module_levels = NULL;
2247     s->limit_req_line = DEFAULT_LIMIT_REQUEST_LINE;
2248     s->limit_req_fieldsize = DEFAULT_LIMIT_REQUEST_FIELDSIZE;
2249     s->limit_req_fields = DEFAULT_LIMIT_REQUEST_FIELDS;
2250     s->timeout = apr_time_from_sec(DEFAULT_TIMEOUT);
2251     s->keep_alive_timeout = apr_time_from_sec(DEFAULT_KEEPALIVE_TIMEOUT);
2252     s->keep_alive_max = DEFAULT_KEEPALIVE;
2253     s->keep_alive = 1;
2254     s->next = NULL;
2255     s->addrs = apr_pcalloc(p, sizeof(server_addr_rec));
2256
2257     /* NOT virtual host; don't match any real network interface */
2258     rv = apr_sockaddr_info_get(&s->addrs->host_addr,
2259                                NULL, APR_INET, 0, 0, p);
2260     if (rv != APR_SUCCESS) {
2261         /* should we test here for rv being an EAIERR? */
2262         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT, rv, NULL,
2263                      "initialisation: bug or getaddrinfo fail");
2264         return NULL;
2265     }
2266
2267     s->addrs->host_port = 0; /* matches any port */
2268     s->addrs->virthost = ""; /* must be non-NULL */
2269     s->names = s->wild_names = NULL;
2270
2271     s->module_config = create_server_config(p, s);
2272     s->lookup_defaults = create_default_per_dir_config(p);
2273
2274     return s;
2275 }
2276
2277
2278 static apr_status_t reset_conf_vector_length(void *dummy)
2279 {
2280     reserved_module_slots = 0;
2281     conf_vector_length = max_modules;
2282     return APR_SUCCESS;
2283 }
2284
2285 static int conf_vector_length_pre_config(apr_pool_t *pconf, apr_pool_t *plog,
2286                                          apr_pool_t *ptemp)
2287 {
2288     /*
2289      * We have loaded all modules that are loaded by EXEC_ON_READ directives.
2290      * From now on we reduce the size of the config vectors to what we need,
2291      * plus what has been reserved (e.g. by mod_perl) for additional modules
2292      * loaded later on.
2293      * If max_modules is too small, ap_add_module() will abort.
2294      */
2295     if (total_modules + reserved_module_slots < max_modules) {
2296         conf_vector_length = total_modules + reserved_module_slots;
2297     }
2298     apr_pool_cleanup_register(pconf, NULL, reset_conf_vector_length,
2299                               apr_pool_cleanup_null);
2300     return OK;
2301 }
2302
2303
2304 AP_CORE_DECLARE(void) ap_register_config_hooks(apr_pool_t *p)
2305 {
2306     ap_hook_pre_config(conf_vector_length_pre_config, NULL, NULL,
2307                        APR_HOOK_REALLY_LAST);
2308 }
2309
2310 AP_DECLARE(server_rec*) ap_read_config(process_rec *process, apr_pool_t *ptemp,
2311                                        const char *filename,
2312                                        ap_directive_t **conftree)
2313 {
2314     const char *confname, *error;
2315     apr_pool_t *p = process->pconf;
2316     server_rec *s = init_server_config(process, p);
2317     if (s == NULL) {
2318         return s;
2319     }
2320
2321     init_config_globals(p);
2322
2323     /* All server-wide config files now have the SAME syntax... */
2324     error = process_command_config(s, ap_server_pre_read_config, conftree,
2325                                    p, ptemp);
2326     if (error) {
2327         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT, 0, NULL, "%s: %s",
2328                      ap_server_argv0, error);
2329         return NULL;
2330     }
2331
2332     /* process_command_config may change the ServerRoot so
2333      * compute this config file name afterwards.
2334      */
2335     confname = ap_server_root_relative(p, filename);
2336
2337     if (!confname) {
2338         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT,
2339                      APR_EBADPATH, NULL, "Invalid config file path %s",
2340                      filename);
2341         return NULL;
2342     }
2343
2344     error = ap_process_resource_config(s, confname, conftree, p, ptemp);
2345     if (error) {
2346         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT, 0, NULL,
2347                      "%s: %s", ap_server_argv0, error);
2348         return NULL;
2349     }
2350
2351     error = ap_check_mpm();
2352     if (error) {
2353         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT, 0, NULL,
2354                      "%s: Configuration error: %s", ap_server_argv0, error);
2355         return NULL;
2356     }
2357
2358     error = process_command_config(s, ap_server_post_read_config, conftree,
2359                                    p, ptemp);
2360
2361     if (error) {
2362         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT, 0, NULL, "%s: %s",
2363                      ap_server_argv0, error);
2364         return NULL;
2365     }
2366
2367     return s;
2368 }
2369
2370 AP_DECLARE(void) ap_single_module_configure(apr_pool_t *p, server_rec *s,
2371                                             module *m)
2372 {
2373     if (m->create_server_config)
2374         ap_set_module_config(s->module_config, m,
2375                              (*m->create_server_config)(p, s));
2376
2377     if (m->create_dir_config)
2378         ap_set_module_config(s->lookup_defaults, m,
2379                              (*m->create_dir_config)(p, NULL));
2380 }
2381
2382 AP_DECLARE(void) ap_run_rewrite_args(process_rec *process)
2383 {
2384     module *m;
2385
2386     for (m = ap_top_module; m; m = m->next) {
2387         if (m->rewrite_args) {
2388             (*m->rewrite_args)(process);
2389         }
2390     }
2391 }
2392
2393 /********************************************************************
2394  * Configuration directives are restricted in terms of where they may
2395  * appear in the main configuration files and/or .htaccess files according
2396  * to the bitmask req_override in the command_rec structure.
2397  * If any of the overrides set in req_override are also allowed in the
2398  * context in which the command is read, then the command is allowed.
2399  * The context is determined as follows:
2400  *
2401  *    inside *.conf --> override = (RSRC_CONF|OR_ALL)&~(OR_AUTHCFG|OR_LIMIT);
2402  *    within <Directory> or <Location> --> override = OR_ALL|ACCESS_CONF;
2403  *    within .htaccess --> override = AllowOverride for current directory;
2404  *
2405  * the result is, well, a rather confusing set of possibilities for when
2406  * a particular directive is allowed to be used.  This procedure prints
2407  * in English where the given (pc) directive can be used.
2408  */
2409 static void show_overrides(const command_rec *pc, module *pm)
2410 {
2411     int n = 0;
2412
2413     printf("\tAllowed in *.conf ");
2414     if ((pc->req_override & (OR_OPTIONS | OR_FILEINFO | OR_INDEXES))
2415         || ((pc->req_override & RSRC_CONF)
2416         && ((pc->req_override & (ACCESS_CONF | OR_AUTHCFG | OR_LIMIT))))) {
2417         printf("anywhere");
2418     }
2419     else if (pc->req_override & RSRC_CONF) {
2420         printf("only outside <Directory>, <Files> or <Location>");
2421     }
2422     else {
2423         printf("only inside <Directory>, <Files> or <Location>");
2424     }
2425
2426     /* Warn if the directive is allowed inside <Directory> or .htaccess
2427      * but module doesn't support per-dir configuration
2428      */
2429     if ((pc->req_override & (OR_ALL | ACCESS_CONF)) && !pm->create_dir_config)
2430         printf(" [no per-dir config]");
2431
2432     if (pc->req_override & OR_ALL) {
2433         printf(" and in .htaccess\n\twhen AllowOverride");
2434
2435         if ((pc->req_override & OR_ALL) == OR_ALL) {
2436             printf(" isn't None");
2437         }
2438         else {
2439             printf(" includes ");
2440
2441             if (pc->req_override & OR_AUTHCFG) {
2442                 if (n++)
2443                     printf(" or ");
2444
2445                 printf("AuthConfig");
2446             }
2447
2448             if (pc->req_override & OR_LIMIT) {
2449                 if (n++)
2450                     printf(" or ");
2451
2452                 printf("Limit");
2453             }
2454
2455             if (pc->req_override & OR_OPTIONS) {
2456                 if (n++)
2457                     printf(" or ");
2458
2459                 printf("Options");
2460             }
2461
2462             if (pc->req_override & OR_FILEINFO) {
2463                 if (n++)
2464                     printf(" or ");
2465
2466                 printf("FileInfo");
2467             }
2468
2469             if (pc->req_override & OR_INDEXES) {
2470                 if (n++)
2471                     printf(" or ");
2472
2473                 printf("Indexes");
2474             }
2475         }
2476     }
2477
2478     printf("\n");
2479 }
2480
2481 /* Show the preloaded configuration directives, the help string explaining
2482  * the directive arguments, in what module they are handled, and in
2483  * what parts of the configuration they are allowed.  Used for httpd -L.
2484  */
2485 AP_DECLARE(void) ap_show_directives(void)
2486 {
2487     const command_rec *pc;
2488     int n;
2489
2490     for (n = 0; ap_loaded_modules[n]; ++n) {
2491         for (pc = ap_loaded_modules[n]->cmds; pc && pc->name; ++pc) {
2492             printf("%s (%s)\n", pc->name, ap_loaded_modules[n]->name);
2493
2494             if (pc->errmsg)
2495                 printf("\t%s\n", pc->errmsg);
2496
2497             show_overrides(pc, ap_loaded_modules[n]);
2498         }
2499     }
2500 }
2501
2502 /* Show the preloaded module names.  Used for httpd -l. */
2503 AP_DECLARE(void) ap_show_modules(void)
2504 {
2505     int n;
2506
2507     printf("Compiled in modules:\n");
2508     for (n = 0; ap_loaded_modules[n]; ++n)
2509         printf("  %s\n", ap_loaded_modules[n]->name);
2510 }
2511
2512 AP_DECLARE(void *) ap_retained_data_get(const char *key)
2513 {
2514     void *retained;
2515
2516     apr_pool_userdata_get((void *)&retained, key, ap_pglobal);
2517     return retained;
2518 }
2519
2520 AP_DECLARE(void *) ap_retained_data_create(const char *key, apr_size_t size)
2521 {
2522     void *retained;
2523
2524     retained = apr_pcalloc(ap_pglobal, size);
2525     apr_pool_userdata_set((const void *)retained, key, apr_pool_cleanup_null, ap_pglobal);
2526     return retained;
2527 }
2528
2529 static int count_directives_sub(const char *directive, ap_directive_t *current)
2530 {
2531     int count = 0;
2532     while (current != NULL) {
2533         if (current->first_child != NULL)
2534             count += count_directives_sub(directive, current->first_child);
2535         if (strcasecmp(current->directive, directive) == 0)
2536             count++;
2537         current = current->next;
2538     }
2539     return count;
2540 }
2541
2542 AP_DECLARE(void) ap_reserve_module_slots(int count)
2543 {
2544     reserved_module_slots += count;
2545 }
2546
2547 AP_DECLARE(void) ap_reserve_module_slots_directive(const char *directive)
2548 {
2549     ap_reserve_module_slots(count_directives_sub(directive, ap_conftree));
2550 }