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