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