]> granicus.if.org Git - apache/blob - server/config.c
Merge r1618541 from trunk:
[apache] / server / config.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * http_config.c: once was 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         args = vb.buf;
1611
1612         cmd_name = ap_getword_conf(cmd->temp_pool, &args);
1613         if (cmd_name[0] == '<') {
1614             if (cmd_name[1] == '/') {
1615                 cmd_name[strlen(cmd_name) - 1] = '\0';
1616
1617                 if (strcasecmp(cmd_name + 2, directive + 1) != 0) {
1618                     return apr_pstrcat(cmd->pool, "Expected </",
1619                                        directive + 1, "> but saw ",
1620                                        cmd_name, ">", NULL);
1621                 }
1622
1623                 ap_varbuf_free(&vb);
1624                 return NULL; /* found end of container */
1625             }
1626             else {
1627                 const char *msg;
1628
1629                 if (*args == '\0' && cmd_name[strlen(cmd_name) - 1] == '>') {
1630                     cmd_name[strlen(cmd_name) - 1] = '\0';
1631                 }
1632
1633                 if ((msg = ap_soak_end_container(cmd, cmd_name)) != NULL) {
1634                     return msg;
1635                 }
1636             }
1637         }
1638     }
1639     if (rc != APR_EOF && rc != APR_SUCCESS)
1640         return ap_pcfg_strerror(cmd->temp_pool, cmd->config_file, rc);
1641
1642     return apr_pstrcat(cmd->pool, "Expected </",
1643                        directive + 1, "> before end of configuration",
1644                        NULL);
1645 }
1646
1647 static const char *execute_now(char *cmd_line, const char *args,
1648                                cmd_parms *parms,
1649                                apr_pool_t *p, apr_pool_t *ptemp,
1650                                ap_directive_t **sub_tree,
1651                                ap_directive_t *parent)
1652 {
1653     const command_rec *cmd;
1654     ap_mod_list *ml;
1655     char *dir = apr_pstrdup(parms->temp_pool, cmd_line);
1656
1657     ap_str_tolower(dir);
1658
1659     ml = apr_hash_get(ap_config_hash, dir, APR_HASH_KEY_STRING);
1660
1661     if (ml == NULL) {
1662         return apr_pstrcat(parms->pool, "Invalid command '",
1663                            cmd_line,
1664                            "', perhaps misspelled or defined by a module "
1665                            "not included in the server configuration",
1666                            NULL);
1667     }
1668
1669     for ( ; ml != NULL; ml = ml->next) {
1670         const char *retval;
1671         cmd = ml->cmd;
1672
1673         retval = invoke_cmd(cmd, parms, sub_tree, args);
1674
1675         if (retval != NULL) {
1676             return retval;
1677         }
1678     }
1679
1680     return NULL;
1681 }
1682
1683 /* This structure and the following functions are needed for the
1684  * table-based config file reading. They are passed to the
1685  * cfg_open_custom() routine.
1686  */
1687
1688 /* Structure to be passed to cfg_open_custom(): it contains an
1689  * index which is incremented from 0 to nelts on each call to
1690  * cfg_getline() (which in turn calls arr_elts_getstr())
1691  * and an apr_array_header_t pointer for the string array.
1692  */
1693 typedef struct {
1694     apr_array_header_t *array;
1695     int curr_idx;
1696 } arr_elts_param_t;
1697
1698
1699 /* arr_elts_getstr() returns the next line from the string array. */
1700 static apr_status_t arr_elts_getstr(void *buf, apr_size_t bufsiz, void *param)
1701 {
1702     arr_elts_param_t *arr_param = (arr_elts_param_t *)param;
1703     char *elt;
1704
1705     /* End of array reached? */
1706     if (++arr_param->curr_idx > arr_param->array->nelts)
1707         return APR_EOF;
1708
1709     /* return the line */
1710     elt = ((char **)arr_param->array->elts)[arr_param->curr_idx - 1];
1711     if (apr_cpystrn(buf, elt, bufsiz) - (char *)buf >= bufsiz - 1)
1712         return APR_ENOSPC;
1713     return APR_SUCCESS;
1714 }
1715
1716
1717 /* arr_elts_close(): dummy close routine (makes sure no more lines can be read) */
1718 static apr_status_t arr_elts_close(void *param)
1719 {
1720     arr_elts_param_t *arr_param = (arr_elts_param_t *)param;
1721
1722     arr_param->curr_idx = arr_param->array->nelts;
1723
1724     return APR_SUCCESS;
1725 }
1726
1727 static const char *process_command_config(server_rec *s,
1728                                           apr_array_header_t *arr,
1729                                           ap_directive_t **conftree,
1730                                           apr_pool_t *p,
1731                                           apr_pool_t *ptemp)
1732 {
1733     const char *errmsg;
1734     cmd_parms parms;
1735     arr_elts_param_t arr_parms;
1736
1737     arr_parms.curr_idx = 0;
1738     arr_parms.array = arr;
1739
1740     if (ap_config_hash == NULL) {
1741         rebuild_conf_hash(s->process->pconf, 1);
1742     }
1743
1744     parms = default_parms;
1745     parms.pool = p;
1746     parms.temp_pool = ptemp;
1747     parms.server = s;
1748     parms.override = (RSRC_CONF | OR_ALL) & ~(OR_AUTHCFG | OR_LIMIT);
1749     parms.override_opts = OPT_ALL | OPT_SYM_OWNER | OPT_MULTI;
1750
1751     parms.config_file = ap_pcfg_open_custom(p, "-c/-C directives",
1752                                             &arr_parms, NULL,
1753                                             arr_elts_getstr, arr_elts_close);
1754
1755     errmsg = ap_build_config(&parms, p, ptemp, conftree);
1756     ap_cfg_closefile(parms.config_file);
1757
1758     if (errmsg) {
1759         return apr_pstrcat(p, "Syntax error in -C/-c directive: ", errmsg,
1760                            NULL);
1761     }
1762
1763     return NULL;
1764 }
1765
1766 typedef struct {
1767     const char *fname;
1768 } fnames;
1769
1770 static int fname_alphasort(const void *fn1, const void *fn2)
1771 {
1772     const fnames *f1 = fn1;
1773     const fnames *f2 = fn2;
1774
1775     return strcmp(f1->fname,f2->fname);
1776 }
1777
1778 AP_DECLARE(const char *) ap_process_resource_config(server_rec *s,
1779                                                     const char *fname,
1780                                                     ap_directive_t **conftree,
1781                                                     apr_pool_t *p,
1782                                                     apr_pool_t *ptemp)
1783 {
1784     ap_configfile_t *cfp;
1785     cmd_parms parms;
1786     apr_status_t rv;
1787     const char *error;
1788
1789     parms = default_parms;
1790     parms.pool = p;
1791     parms.temp_pool = ptemp;
1792     parms.server = s;
1793     parms.override = (RSRC_CONF | OR_ALL) & ~(OR_AUTHCFG | OR_LIMIT);
1794     parms.override_opts = OPT_ALL | OPT_SYM_OWNER | OPT_MULTI;
1795
1796     rv = ap_pcfg_openfile(&cfp, p, fname);
1797     if (rv != APR_SUCCESS) {
1798         return apr_psprintf(p, "Could not open configuration file %s: %pm",
1799                             fname, &rv);
1800     }
1801
1802     parms.config_file = cfp;
1803     error = ap_build_config(&parms, p, ptemp, conftree);
1804     ap_cfg_closefile(cfp);
1805
1806     if (error) {
1807         if (parms.err_directive)
1808             return apr_psprintf(p, "Syntax error on line %d of %s: %s",
1809                                 parms.err_directive->line_num,
1810                                 parms.err_directive->filename, error);
1811         else
1812             return error;
1813     }
1814
1815     return NULL;
1816 }
1817
1818 static const char *process_resource_config_nofnmatch(server_rec *s,
1819                                                      const char *fname,
1820                                                      ap_directive_t **conftree,
1821                                                      apr_pool_t *p,
1822                                                      apr_pool_t *ptemp,
1823                                                      unsigned depth,
1824                                                      int optional)
1825 {
1826     const char *error;
1827     apr_status_t rv;
1828
1829     if (ap_is_directory(ptemp, fname)) {
1830         apr_dir_t *dirp;
1831         apr_finfo_t dirent;
1832         int current;
1833         apr_array_header_t *candidates = NULL;
1834         fnames *fnew;
1835         char *path = apr_pstrdup(ptemp, fname);
1836
1837         if (++depth > AP_MAX_INCLUDE_DIR_DEPTH) {
1838             return apr_psprintf(p, "Directory %s exceeds the maximum include "
1839                                 "directory nesting level of %u. You have "
1840                                 "probably a recursion somewhere.", path,
1841                                 AP_MAX_INCLUDE_DIR_DEPTH);
1842         }
1843
1844         /*
1845          * first course of business is to grok all the directory
1846          * entries here and store 'em away. Recall we need full pathnames
1847          * for this.
1848          */
1849         rv = apr_dir_open(&dirp, path, ptemp);
1850         if (rv != APR_SUCCESS) {
1851             return apr_psprintf(p, "Could not open config directory %s: %pm",
1852                                 path, &rv);
1853         }
1854
1855         candidates = apr_array_make(ptemp, 1, sizeof(fnames));
1856         while (apr_dir_read(&dirent, APR_FINFO_DIRENT, dirp) == APR_SUCCESS) {
1857             /* strip out '.' and '..' */
1858             if (strcmp(dirent.name, ".")
1859                 && strcmp(dirent.name, "..")) {
1860                 fnew = (fnames *) apr_array_push(candidates);
1861                 fnew->fname = ap_make_full_path(ptemp, path, dirent.name);
1862             }
1863         }
1864
1865         apr_dir_close(dirp);
1866         if (candidates->nelts != 0) {
1867             qsort((void *) candidates->elts, candidates->nelts,
1868                   sizeof(fnames), fname_alphasort);
1869
1870             /*
1871              * Now recurse these... we handle errors and subdirectories
1872              * via the recursion, which is nice
1873              */
1874             for (current = 0; current < candidates->nelts; ++current) {
1875                 fnew = &((fnames *) candidates->elts)[current];
1876                 error = process_resource_config_nofnmatch(s, fnew->fname,
1877                                                           conftree, p, ptemp,
1878                                                           depth, optional);
1879                 if (error) {
1880                     return error;
1881                 }
1882             }
1883         }
1884
1885         return NULL;
1886     }
1887
1888     return ap_process_resource_config(s, fname, conftree, p, ptemp);
1889 }
1890
1891 static const char *process_resource_config_fnmatch(server_rec *s,
1892                                                    const char *path,
1893                                                    const char *fname,
1894                                                    ap_directive_t **conftree,
1895                                                    apr_pool_t *p,
1896                                                    apr_pool_t *ptemp,
1897                                                    unsigned depth,
1898                                                    int optional)
1899 {
1900     const char *rest;
1901     apr_status_t rv;
1902     apr_dir_t *dirp;
1903     apr_finfo_t dirent;
1904     apr_array_header_t *candidates = NULL;
1905     fnames *fnew;
1906     int current;
1907
1908     /* find the first part of the filename */
1909     rest = ap_strchr_c(fname, '/');
1910     if (rest) {
1911         fname = apr_pstrndup(ptemp, fname, rest - fname);
1912         rest++;
1913     }
1914
1915     /* optimisation - if the filename isn't a wildcard, process it directly */
1916     if (!apr_fnmatch_test(fname)) {
1917         path = ap_make_full_path(ptemp, path, fname);
1918         if (!rest) {
1919             return process_resource_config_nofnmatch(s, path,
1920                                                      conftree, p,
1921                                                      ptemp, 0, optional);
1922         }
1923         else {
1924             return process_resource_config_fnmatch(s, path, rest,
1925                                                    conftree, p,
1926                                                    ptemp, 0, optional);
1927         }
1928     }
1929
1930     /*
1931      * first course of business is to grok all the directory
1932      * entries here and store 'em away. Recall we need full pathnames
1933      * for this.
1934      */
1935     rv = apr_dir_open(&dirp, path, ptemp);
1936     if (rv != APR_SUCCESS) {
1937         return apr_psprintf(p, "Could not open config directory %s: %pm",
1938                             path, &rv);
1939     }
1940
1941     candidates = apr_array_make(ptemp, 1, sizeof(fnames));
1942     while (apr_dir_read(&dirent, APR_FINFO_DIRENT | APR_FINFO_TYPE, dirp) == APR_SUCCESS) {
1943         /* strip out '.' and '..' */
1944         if (strcmp(dirent.name, ".")
1945             && strcmp(dirent.name, "..")
1946             && (apr_fnmatch(fname, dirent.name,
1947                             APR_FNM_PERIOD) == APR_SUCCESS)) {
1948             const char *full_path = ap_make_full_path(ptemp, path, dirent.name);
1949             /* If matching internal to path, and we happen to match something
1950              * other than a directory, skip it
1951              */
1952             if (rest && (rv == APR_SUCCESS) && (dirent.filetype != APR_DIR)) {
1953                 continue;
1954             }
1955             fnew = (fnames *) apr_array_push(candidates);
1956             fnew->fname = full_path;
1957         }
1958     }
1959
1960     apr_dir_close(dirp);
1961     if (candidates->nelts != 0) {
1962         const char *error;
1963
1964         qsort((void *) candidates->elts, candidates->nelts,
1965               sizeof(fnames), fname_alphasort);
1966
1967         /*
1968          * Now recurse these... we handle errors and subdirectories
1969          * via the recursion, which is nice
1970          */
1971         for (current = 0; current < candidates->nelts; ++current) {
1972             fnew = &((fnames *) candidates->elts)[current];
1973             if (!rest) {
1974                 error = process_resource_config_nofnmatch(s, fnew->fname,
1975                                                           conftree, p,
1976                                                           ptemp, 0, optional);
1977             }
1978             else {
1979                 error = process_resource_config_fnmatch(s, fnew->fname, rest,
1980                                                         conftree, p,
1981                                                         ptemp, 0, optional);
1982             }
1983             if (error) {
1984                 return error;
1985             }
1986         }
1987     }
1988     else {
1989
1990         if (!optional) {
1991             return apr_psprintf(p, "No matches for the wildcard '%s' in '%s', failing "
1992                                    "(use IncludeOptional if required)", fname, path);
1993         }
1994     }
1995
1996     return NULL;
1997 }
1998
1999 AP_DECLARE(const char *) ap_process_fnmatch_configs(server_rec *s,
2000                                                     const char *fname,
2001                                                     ap_directive_t **conftree,
2002                                                     apr_pool_t *p,
2003                                                     apr_pool_t *ptemp,
2004                                                     int optional)
2005 {
2006     /* XXX: lstat() won't work on the wildcard pattern...
2007      */
2008
2009     /* don't require conf/httpd.conf if we have a -C or -c switch */
2010     if ((ap_server_pre_read_config->nelts
2011         || ap_server_post_read_config->nelts)
2012         && !(strcmp(fname, ap_server_root_relative(ptemp, SERVER_CONFIG_FILE)))) {
2013         apr_finfo_t finfo;
2014
2015         if (apr_stat(&finfo, fname, APR_FINFO_LINK | APR_FINFO_TYPE, ptemp) != APR_SUCCESS)
2016             return NULL;
2017     }
2018
2019     if (!apr_fnmatch_test(fname)) {
2020         return process_resource_config_nofnmatch(s, fname, conftree, p, ptemp, 0, optional);
2021     }
2022     else {
2023         apr_status_t status;
2024         const char *rootpath, *filepath = fname;
2025
2026         /* locate the start of the directories proper */
2027         status = apr_filepath_root(&rootpath, &filepath, APR_FILEPATH_TRUENAME, ptemp);
2028
2029         /* we allow APR_SUCCESS and APR_EINCOMPLETE */
2030         if (APR_ERELATIVE == status) {
2031             return apr_pstrcat(p, "Include must have an absolute path, ", fname, NULL);
2032         }
2033         else if (APR_EBADPATH == status) {
2034             return apr_pstrcat(p, "Include has a bad path, ", fname, NULL);
2035         }
2036
2037         /* walk the filepath */
2038         return process_resource_config_fnmatch(s, rootpath, filepath, conftree, p, ptemp,
2039                                                0, optional);
2040     }
2041 }
2042
2043 AP_DECLARE(int) ap_process_config_tree(server_rec *s,
2044                                        ap_directive_t *conftree,
2045                                        apr_pool_t *p,
2046                                        apr_pool_t *ptemp)
2047 {
2048     const char *errmsg;
2049     cmd_parms parms;
2050
2051     parms = default_parms;
2052     parms.pool = p;
2053     parms.temp_pool = ptemp;
2054     parms.server = s;
2055     parms.override = (RSRC_CONF | OR_ALL) & ~(OR_AUTHCFG | OR_LIMIT);
2056     parms.override_opts = OPT_ALL | OPT_SYM_OWNER | OPT_MULTI;
2057     parms.limited = -1;
2058
2059     errmsg = ap_walk_config(conftree, &parms, s->lookup_defaults);
2060     if (errmsg) {
2061         if (parms.err_directive)
2062             ap_log_perror(APLOG_MARK, APLOG_STARTUP, 0, p, APLOGNO(00526)
2063                           "Syntax error on line %d of %s:",
2064                           parms.err_directive->line_num,
2065                           parms.err_directive->filename);
2066         ap_log_perror(APLOG_MARK, APLOG_STARTUP, 0, p, "%s", errmsg);
2067         return HTTP_INTERNAL_SERVER_ERROR;
2068     }
2069
2070     return OK;
2071 }
2072
2073 apr_status_t ap_open_htaccess(request_rec *r, const char *dir_name,
2074                               const char *access_name,
2075                               ap_configfile_t **conffile,
2076                               const char **full_name)
2077 {
2078     *full_name = ap_make_full_path(r->pool, dir_name, access_name);
2079     return ap_pcfg_openfile(conffile, r->pool, *full_name);
2080 }
2081
2082 AP_CORE_DECLARE(int) ap_parse_htaccess(ap_conf_vector_t **result,
2083                                        request_rec *r, int override,
2084                                        int override_opts, apr_table_t *override_list,
2085                                        const char *d, const char *access_names)
2086 {
2087     ap_configfile_t *f = NULL;
2088     cmd_parms parms;
2089     const char *filename;
2090     const struct htaccess_result *cache;
2091     struct htaccess_result *new;
2092     ap_conf_vector_t *dc = NULL;
2093     apr_status_t status;
2094
2095     /* firstly, search cache */
2096     for (cache = r->htaccess; cache != NULL; cache = cache->next) {
2097         if (cache->override == override && strcmp(cache->dir, d) == 0) {
2098             *result = cache->htaccess;
2099             return OK;
2100         }
2101     }
2102
2103     parms = default_parms;
2104     parms.override = override;
2105     parms.override_opts = override_opts;
2106     parms.override_list = override_list;
2107     parms.pool = r->pool;
2108     parms.temp_pool = r->pool;
2109     parms.server = r->server;
2110     parms.path = apr_pstrdup(r->pool, d);
2111
2112     /* loop through the access names and find the first one */
2113     while (access_names[0]) {
2114         const char *access_name = ap_getword_conf(r->pool, &access_names);
2115
2116         filename = NULL;
2117         status = ap_run_open_htaccess(r, d, access_name, &f, &filename);
2118         if (status == APR_SUCCESS) {
2119             const char *errmsg;
2120             ap_directive_t *temptree = NULL;
2121
2122             dc = ap_create_per_dir_config(r->pool);
2123
2124             parms.config_file = f;
2125             errmsg = ap_build_config(&parms, r->pool, r->pool, &temptree);
2126             if (errmsg == NULL)
2127                 errmsg = ap_walk_config(temptree, &parms, dc);
2128
2129             ap_cfg_closefile(f);
2130
2131             if (errmsg) {
2132                 ap_log_rerror(APLOG_MARK, APLOG_ALERT, 0, r,
2133                               "%s: %s", filename, errmsg);
2134                 return HTTP_INTERNAL_SERVER_ERROR;
2135             }
2136
2137             *result = dc;
2138             break;
2139         }
2140         else {
2141             if (!APR_STATUS_IS_ENOENT(status)
2142                 && !APR_STATUS_IS_ENOTDIR(status)) {
2143                 ap_log_rerror(APLOG_MARK, APLOG_CRIT, status, r, APLOGNO(00529)
2144                               "%s pcfg_openfile: unable to check htaccess file, "
2145                               "ensure it is readable and that '%s' "
2146                               "is executable",
2147                               filename, d);
2148                 apr_table_setn(r->notes, "error-notes",
2149                                "Server unable to read htaccess file, denying "
2150                                "access to be safe");
2151                 return HTTP_FORBIDDEN;
2152             }
2153         }
2154     }
2155
2156     /* cache it */
2157     new = apr_palloc(r->pool, sizeof(struct htaccess_result));
2158     new->dir = parms.path;
2159     new->override = override;
2160     new->override_opts = override_opts;
2161     new->htaccess = dc;
2162
2163     /* add to head of list */
2164     new->next = r->htaccess;
2165     r->htaccess = new;
2166
2167     return OK;
2168 }
2169
2170 AP_CORE_DECLARE(const char *) ap_init_virtual_host(apr_pool_t *p,
2171                                                    const char *hostname,
2172                                                    server_rec *main_server,
2173                                                    server_rec **ps)
2174 {
2175     server_rec *s = (server_rec *) apr_pcalloc(p, sizeof(server_rec));
2176
2177     /* TODO: this crap belongs in http_core */
2178     s->process = main_server->process;
2179     s->server_admin = NULL;
2180     s->server_hostname = NULL;
2181     s->server_scheme = NULL;
2182     s->error_fname = NULL;
2183     s->timeout = 0;
2184     s->keep_alive_timeout = 0;
2185     s->keep_alive = -1;
2186     s->keep_alive_max = -1;
2187     s->error_log = main_server->error_log;
2188     s->log.level = APLOG_UNSET;
2189     s->log.module_levels = NULL;
2190     /* useful default, otherwise we get a port of 0 on redirects */
2191     s->port = main_server->port;
2192     s->next = NULL;
2193
2194     s->is_virtual = 1;
2195     s->names = apr_array_make(p, 4, sizeof(char **));
2196     s->wild_names = apr_array_make(p, 4, sizeof(char **));
2197
2198     s->module_config = create_empty_config(p);
2199     s->lookup_defaults = ap_create_per_dir_config(p);
2200
2201     s->limit_req_line = main_server->limit_req_line;
2202     s->limit_req_fieldsize = main_server->limit_req_fieldsize;
2203     s->limit_req_fields = main_server->limit_req_fields;
2204
2205     *ps = s;
2206
2207     return ap_parse_vhost_addrs(p, hostname, s);
2208 }
2209
2210 AP_DECLARE(struct ap_logconf *) ap_new_log_config(apr_pool_t *p,
2211                                                   const struct ap_logconf *old)
2212 {
2213     struct ap_logconf *l = apr_pcalloc(p, sizeof(struct ap_logconf));
2214     if (old) {
2215         l->level = old->level;
2216         if (old->module_levels) {
2217             l->module_levels =
2218                 apr_pmemdup(p, old->module_levels, conf_vector_length);
2219         }
2220     }
2221     else {
2222         l->level = APLOG_UNSET;
2223     }
2224     return l;
2225 }
2226
2227 AP_DECLARE(void) ap_merge_log_config(const struct ap_logconf *old_conf,
2228                                      struct ap_logconf *new_conf)
2229 {
2230     if (new_conf->level != APLOG_UNSET) {
2231         /* Setting the main loglevel resets all per-module log levels.
2232          * I.e. if new->level has been set, we must ignore old->module_levels.
2233          */
2234         return;
2235     }
2236
2237     new_conf->level = old_conf->level;
2238     if (new_conf->module_levels == NULL) {
2239         new_conf->module_levels = old_conf->module_levels;
2240     }
2241     else if (old_conf->module_levels != NULL) {
2242         int i;
2243         for (i = 0; i < conf_vector_length; i++) {
2244             if (new_conf->module_levels[i] == APLOG_UNSET)
2245                 new_conf->module_levels[i] = old_conf->module_levels[i];
2246         }
2247     }
2248 }
2249
2250 AP_DECLARE(void) ap_fixup_virtual_hosts(apr_pool_t *p, server_rec *main_server)
2251 {
2252     server_rec *virt;
2253     core_dir_config *dconf =
2254         ap_get_core_module_config(main_server->lookup_defaults);
2255     dconf->log = &main_server->log;
2256
2257     for (virt = main_server->next; virt; virt = virt->next) {
2258         merge_server_configs(p, main_server->module_config,
2259                              virt->module_config);
2260
2261         virt->lookup_defaults =
2262             ap_merge_per_dir_configs(p, main_server->lookup_defaults,
2263                                      virt->lookup_defaults);
2264
2265         if (virt->server_admin == NULL)
2266             virt->server_admin = main_server->server_admin;
2267
2268         if (virt->timeout == 0)
2269             virt->timeout = main_server->timeout;
2270
2271         if (virt->keep_alive_timeout == 0)
2272             virt->keep_alive_timeout = main_server->keep_alive_timeout;
2273
2274         if (virt->keep_alive == -1)
2275             virt->keep_alive = main_server->keep_alive;
2276
2277         if (virt->keep_alive_max == -1)
2278             virt->keep_alive_max = main_server->keep_alive_max;
2279
2280         ap_merge_log_config(&main_server->log, &virt->log);
2281
2282         dconf = ap_get_core_module_config(virt->lookup_defaults);
2283         dconf->log = &virt->log;
2284
2285         /* XXX: this is really something that should be dealt with by a
2286          * post-config api phase
2287          */
2288         ap_core_reorder_directories(p, virt);
2289     }
2290
2291     ap_core_reorder_directories(p, main_server);
2292 }
2293
2294 /*****************************************************************
2295  *
2296  * Getting *everything* configured...
2297  */
2298
2299 static void init_config_globals(apr_pool_t *p)
2300 {
2301     /* Global virtual host hash bucket pointers.  Init to null. */
2302     ap_init_vhost_config(p);
2303 }
2304
2305 static server_rec *init_server_config(process_rec *process, apr_pool_t *p)
2306 {
2307     apr_status_t rv;
2308     server_rec *s = (server_rec *) apr_pcalloc(p, sizeof(server_rec));
2309
2310     apr_file_open_stderr(&s->error_log, p);
2311     s->process = process;
2312     s->port = 0;
2313     s->server_admin = DEFAULT_ADMIN;
2314     s->server_hostname = NULL;
2315     s->server_scheme = NULL;
2316     s->error_fname = DEFAULT_ERRORLOG;
2317     s->log.level = DEFAULT_LOGLEVEL;
2318     s->log.module_levels = NULL;
2319     s->limit_req_line = DEFAULT_LIMIT_REQUEST_LINE;
2320     s->limit_req_fieldsize = DEFAULT_LIMIT_REQUEST_FIELDSIZE;
2321     s->limit_req_fields = DEFAULT_LIMIT_REQUEST_FIELDS;
2322     s->timeout = apr_time_from_sec(DEFAULT_TIMEOUT);
2323     s->keep_alive_timeout = apr_time_from_sec(DEFAULT_KEEPALIVE_TIMEOUT);
2324     s->keep_alive_max = DEFAULT_KEEPALIVE;
2325     s->keep_alive = 1;
2326     s->next = NULL;
2327     s->addrs = apr_pcalloc(p, sizeof(server_addr_rec));
2328
2329     /* NOT virtual host; don't match any real network interface */
2330     rv = apr_sockaddr_info_get(&s->addrs->host_addr,
2331                                NULL, APR_UNSPEC, 0, 0, p);
2332     if (rv != APR_SUCCESS) {
2333         /* should we test here for rv being an EAIERR? */
2334         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT, rv, NULL, APLOGNO(00530)
2335                      "initialisation: bug or getaddrinfo fail");
2336         return NULL;
2337     }
2338
2339     s->addrs->host_port = 0; /* matches any port */
2340     s->addrs->virthost = ""; /* must be non-NULL */
2341     s->names = s->wild_names = NULL;
2342
2343     s->module_config = create_server_config(p, s);
2344     s->lookup_defaults = create_default_per_dir_config(p);
2345
2346     return s;
2347 }
2348
2349
2350 static apr_status_t reset_conf_vector_length(void *dummy)
2351 {
2352     reserved_module_slots = 0;
2353     conf_vector_length = max_modules;
2354     return APR_SUCCESS;
2355 }
2356
2357 static int conf_vector_length_pre_config(apr_pool_t *pconf, apr_pool_t *plog,
2358                                          apr_pool_t *ptemp)
2359 {
2360     /*
2361      * We have loaded all modules that are loaded by EXEC_ON_READ directives.
2362      * From now on we reduce the size of the config vectors to what we need,
2363      * plus what has been reserved (e.g. by mod_perl) for additional modules
2364      * loaded later on.
2365      * If max_modules is too small, ap_add_module() will abort.
2366      */
2367     if (total_modules + reserved_module_slots < max_modules) {
2368         conf_vector_length = total_modules + reserved_module_slots;
2369     }
2370     apr_pool_cleanup_register(pconf, NULL, reset_conf_vector_length,
2371                               apr_pool_cleanup_null);
2372     return OK;
2373 }
2374
2375
2376 AP_CORE_DECLARE(void) ap_register_config_hooks(apr_pool_t *p)
2377 {
2378     ap_hook_pre_config(conf_vector_length_pre_config, NULL, NULL,
2379                        APR_HOOK_REALLY_LAST);
2380 }
2381
2382 AP_DECLARE(server_rec*) ap_read_config(process_rec *process, apr_pool_t *ptemp,
2383                                        const char *filename,
2384                                        ap_directive_t **conftree)
2385 {
2386     const char *confname, *error;
2387     apr_pool_t *p = process->pconf;
2388     server_rec *s = init_server_config(process, p);
2389     if (s == NULL) {
2390         return s;
2391     }
2392
2393     init_config_globals(p);
2394
2395     /* All server-wide config files now have the SAME syntax... */
2396     error = process_command_config(s, ap_server_pre_read_config, conftree,
2397                                    p, ptemp);
2398     if (error) {
2399         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT, 0, NULL, "%s: %s",
2400                      ap_server_argv0, error);
2401         return NULL;
2402     }
2403
2404     /* process_command_config may change the ServerRoot so
2405      * compute this config file name afterwards.
2406      */
2407     confname = ap_server_root_relative(p, filename);
2408
2409     if (!confname) {
2410         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT,
2411                      APR_EBADPATH, NULL, APLOGNO(00532) "Invalid config file path %s",
2412                      filename);
2413         return NULL;
2414     }
2415
2416     error = ap_process_resource_config(s, confname, conftree, p, ptemp);
2417     if (error) {
2418         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT, 0, NULL,
2419                      "%s: %s", ap_server_argv0, error);
2420         return NULL;
2421     }
2422
2423     error = ap_check_mpm();
2424     if (error) {
2425         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT, 0, NULL, APLOGNO(00534)
2426                      "%s: Configuration error: %s", ap_server_argv0, error);
2427         return NULL;
2428     }
2429
2430     error = process_command_config(s, ap_server_post_read_config, conftree,
2431                                    p, ptemp);
2432
2433     if (error) {
2434         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT, 0, NULL, "%s: %s",
2435                      ap_server_argv0, error);
2436         return NULL;
2437     }
2438
2439     return s;
2440 }
2441
2442 AP_DECLARE(void) ap_single_module_configure(apr_pool_t *p, server_rec *s,
2443                                             module *m)
2444 {
2445     if (m->create_server_config)
2446         ap_set_module_config(s->module_config, m,
2447                              (*m->create_server_config)(p, s));
2448
2449     if (m->create_dir_config)
2450         ap_set_module_config(s->lookup_defaults, m,
2451                              (*m->create_dir_config)(p, NULL));
2452 }
2453
2454 AP_DECLARE(void) ap_run_rewrite_args(process_rec *process)
2455 {
2456     module *m;
2457
2458     for (m = ap_top_module; m; m = m->next) {
2459         if (m->rewrite_args) {
2460             (*m->rewrite_args)(process);
2461         }
2462     }
2463 }
2464
2465 /********************************************************************
2466  * Configuration directives are restricted in terms of where they may
2467  * appear in the main configuration files and/or .htaccess files according
2468  * to the bitmask req_override in the command_rec structure.
2469  * If any of the overrides set in req_override are also allowed in the
2470  * context in which the command is read, then the command is allowed.
2471  * The context is determined as follows:
2472  *
2473  *    inside *.conf --> override = (RSRC_CONF|OR_ALL)&~(OR_AUTHCFG|OR_LIMIT);
2474  *    within <Directory> or <Location> --> override = OR_ALL|ACCESS_CONF;
2475  *    within .htaccess --> override = AllowOverride for current directory;
2476  *
2477  * the result is, well, a rather confusing set of possibilities for when
2478  * a particular directive is allowed to be used.  This procedure prints
2479  * in English where the given (pc) directive can be used.
2480  */
2481 static void show_overrides(const command_rec *pc, module *pm)
2482 {
2483     int n = 0;
2484
2485     printf("\tAllowed in *.conf ");
2486     if ((pc->req_override & (OR_OPTIONS | OR_FILEINFO | OR_INDEXES))
2487         || ((pc->req_override & RSRC_CONF)
2488         && ((pc->req_override & (ACCESS_CONF | OR_AUTHCFG | OR_LIMIT))))) {
2489         printf("anywhere");
2490     }
2491     else if (pc->req_override & RSRC_CONF) {
2492         printf("only outside <Directory>, <Files>, <Location>, or <If>");
2493     }
2494     else {
2495         printf("only inside <Directory>, <Files>, <Location>, or <If>");
2496     }
2497
2498     /* Warn if the directive is allowed inside <Directory> or .htaccess
2499      * but module doesn't support per-dir configuration
2500      */
2501     if ((pc->req_override & (OR_ALL | ACCESS_CONF)) && !pm->create_dir_config)
2502         printf(" [no per-dir config]");
2503
2504     if (pc->req_override & OR_ALL) {
2505         printf(" and in .htaccess\n\twhen AllowOverride");
2506
2507         if ((pc->req_override & OR_ALL) == OR_ALL) {
2508             printf(" isn't None");
2509         }
2510         else {
2511             printf(" includes ");
2512
2513             if (pc->req_override & OR_AUTHCFG) {
2514                 if (n++)
2515                     printf(" or ");
2516
2517                 printf("AuthConfig");
2518             }
2519
2520             if (pc->req_override & OR_LIMIT) {
2521                 if (n++)
2522                     printf(" or ");
2523
2524                 printf("Limit");
2525             }
2526
2527             if (pc->req_override & OR_OPTIONS) {
2528                 if (n++)
2529                     printf(" or ");
2530
2531                 printf("Options");
2532             }
2533
2534             if (pc->req_override & OR_FILEINFO) {
2535                 if (n++)
2536                     printf(" or ");
2537
2538                 printf("FileInfo");
2539             }
2540
2541             if (pc->req_override & OR_INDEXES) {
2542                 if (n++)
2543                     printf(" or ");
2544
2545                 printf("Indexes");
2546             }
2547         }
2548     }
2549
2550     printf("\n");
2551 }
2552
2553 /* Show the preloaded configuration directives, the help string explaining
2554  * the directive arguments, in what module they are handled, and in
2555  * what parts of the configuration they are allowed.  Used for httpd -L.
2556  */
2557 AP_DECLARE(void) ap_show_directives(void)
2558 {
2559     const command_rec *pc;
2560     int n;
2561
2562     for (n = 0; ap_loaded_modules[n]; ++n) {
2563         for (pc = ap_loaded_modules[n]->cmds; pc && pc->name; ++pc) {
2564             printf("%s (%s)\n", pc->name, ap_loaded_modules[n]->name);
2565
2566             if (pc->errmsg)
2567                 printf("\t%s\n", pc->errmsg);
2568
2569             show_overrides(pc, ap_loaded_modules[n]);
2570         }
2571     }
2572 }
2573
2574 /* Show the preloaded module names.  Used for httpd -l. */
2575 AP_DECLARE(void) ap_show_modules(void)
2576 {
2577     int n;
2578
2579     printf("Compiled in modules:\n");
2580     for (n = 0; ap_loaded_modules[n]; ++n)
2581         printf("  %s\n", ap_loaded_modules[n]->name);
2582 }
2583
2584 AP_DECLARE(void *) ap_retained_data_get(const char *key)
2585 {
2586     void *retained;
2587
2588     apr_pool_userdata_get((void *)&retained, key, ap_pglobal);
2589     return retained;
2590 }
2591
2592 AP_DECLARE(void *) ap_retained_data_create(const char *key, apr_size_t size)
2593 {
2594     void *retained;
2595
2596     retained = apr_pcalloc(ap_pglobal, size);
2597     apr_pool_userdata_set((const void *)retained, key, apr_pool_cleanup_null, ap_pglobal);
2598     return retained;
2599 }
2600
2601 static int count_directives_sub(const char *directive, ap_directive_t *current)
2602 {
2603     int count = 0;
2604     while (current != NULL) {
2605         if (current->first_child != NULL)
2606             count += count_directives_sub(directive, current->first_child);
2607         if (strcasecmp(current->directive, directive) == 0)
2608             count++;
2609         current = current->next;
2610     }
2611     return count;
2612 }
2613
2614 AP_DECLARE(void) ap_reserve_module_slots(int count)
2615 {
2616     reserved_module_slots += count;
2617 }
2618
2619 AP_DECLARE(void) ap_reserve_module_slots_directive(const char *directive)
2620 {
2621     ap_reserve_module_slots(count_directives_sub(directive, ap_conftree));
2622 }