]> granicus.if.org Git - apache/blob - server/config.c
add pre_htaccess hook; in conjunction with earlier dirwalk_stat
[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(pre_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(int, pre_htaccess, (request_rec *r, const char *filename),
176                             (r, filename), DECLINED)
177
178 /* hooks with no args are implemented last, after disabling APR hook probes */
179 #if defined(APR_HOOK_PROBES_ENABLED)
180 #undef APR_HOOK_PROBES_ENABLED
181 #undef APR_HOOK_PROBE_ENTRY
182 #define APR_HOOK_PROBE_ENTRY(ud,ns,name,args)
183 #undef APR_HOOK_PROBE_RETURN
184 #define APR_HOOK_PROBE_RETURN(ud,ns,name,rv,args)
185 #undef APR_HOOK_PROBE_INVOKE
186 #define APR_HOOK_PROBE_INVOKE(ud,ns,name,src,args)
187 #undef APR_HOOK_PROBE_COMPLETE
188 #define APR_HOOK_PROBE_COMPLETE(ud,ns,name,src,rv,args)
189 #undef APR_HOOK_INT_DCL_UD
190 #define APR_HOOK_INT_DCL_UD
191 #endif
192 AP_IMPLEMENT_HOOK_VOID(optional_fn_retrieve, (void), ())
193
194 /****************************************************************
195  *
196  * We begin with the functions which deal with the linked list
197  * of modules which control just about all of the server operation.
198  */
199
200 /* total_modules is the number of modules that have been linked
201  * into the server.
202  */
203 static int total_modules = 0;
204
205 /* dynamic_modules is the number of modules that have been added
206  * after the pre-loaded ones have been set up. It shouldn't be larger
207  * than DYNAMIC_MODULE_LIMIT.
208  */
209 static int dynamic_modules = 0;
210
211 /* The maximum possible value for total_modules, i.e. number of static
212  * modules plus DYNAMIC_MODULE_LIMIT.
213  */
214 static int max_modules = 0;
215
216 /* The number of elements we need to alloc for config vectors. Before loading
217  * of dynamic modules, we must be liberal and set this to max_modules. After
218  * loading of dynamic modules, we can trim it down to total_modules. On
219  * restart, reset to max_modules.
220  */
221 static int conf_vector_length = 0;
222
223 static int reserved_module_slots = 0;
224
225 AP_DECLARE_DATA module *ap_top_module = NULL;
226 AP_DECLARE_DATA module **ap_loaded_modules=NULL;
227
228 static apr_hash_t *ap_config_hash = NULL;
229
230 /* a list of the module symbol names with the trailing "_module"removed */
231 static char **ap_module_short_names = NULL;
232
233 typedef int (*handler_func)(request_rec *);
234 typedef void *(*dir_maker_func)(apr_pool_t *, char *);
235 typedef void *(*merger_func)(apr_pool_t *, void *, void *);
236
237 /* A list of the merge_dir_config functions of all loaded modules, sorted
238  * by module_index.
239  * Using this list in ap_merge_per_dir_configs() is faster than following
240  * the module->next linked list because of better memory locality (resulting
241  * in better cache usage).
242  */
243 static merger_func *merger_func_cache;
244
245 /* maximum nesting level for config directories */
246 #ifndef AP_MAX_INCLUDE_DIR_DEPTH
247 #define AP_MAX_INCLUDE_DIR_DEPTH (128)
248 #endif
249
250 /* Dealing with config vectors.  These are associated with per-directory,
251  * per-server, and per-request configuration, and have a void* pointer for
252  * each modules.  The nature of the structure pointed to is private to the
253  * module in question... the core doesn't (and can't) know.  However, there
254  * are defined interfaces which allow it to create instances of its private
255  * per-directory and per-server structures, and to merge the per-directory
256  * structures of a directory and its subdirectory (producing a new one in
257  * which the defaults applying to the base directory have been properly
258  * overridden).
259  */
260
261 static ap_conf_vector_t *create_empty_config(apr_pool_t *p)
262 {
263     void *conf_vector = apr_pcalloc(p, sizeof(void *) * conf_vector_length);
264     return conf_vector;
265 }
266
267 static ap_conf_vector_t *create_default_per_dir_config(apr_pool_t *p)
268 {
269     void **conf_vector = apr_pcalloc(p, sizeof(void *) * conf_vector_length);
270     module *modp;
271
272     for (modp = ap_top_module; modp; modp = modp->next) {
273         dir_maker_func df = modp->create_dir_config;
274
275         if (df)
276             conf_vector[modp->module_index] = (*df)(p, NULL);
277     }
278
279     return (ap_conf_vector_t *)conf_vector;
280 }
281
282 AP_CORE_DECLARE(ap_conf_vector_t *) ap_merge_per_dir_configs(apr_pool_t *p,
283                                            ap_conf_vector_t *base,
284                                            ap_conf_vector_t *new_conf)
285 {
286     void **conf_vector = apr_palloc(p, sizeof(void *) * conf_vector_length);
287     void **base_vector = (void **)base;
288     void **new_vector = (void **)new_conf;
289     int i;
290
291     for (i = 0; i < total_modules; i++) {
292         if (!new_vector[i]) {
293             conf_vector[i] = base_vector[i];
294         }
295         else {
296             const merger_func df = merger_func_cache[i];
297             if (df && base_vector[i]) {
298                 conf_vector[i] = (*df)(p, base_vector[i], new_vector[i]);
299             }
300             else
301                 conf_vector[i] = new_vector[i];
302         }
303     }
304
305     return (ap_conf_vector_t *)conf_vector;
306 }
307
308 static ap_conf_vector_t *create_server_config(apr_pool_t *p, server_rec *s)
309 {
310     void **conf_vector = apr_pcalloc(p, sizeof(void *) * conf_vector_length);
311     module *modp;
312
313     for (modp = ap_top_module; modp; modp = modp->next) {
314         if (modp->create_server_config)
315             conf_vector[modp->module_index] = (*modp->create_server_config)(p, s);
316     }
317
318     return (ap_conf_vector_t *)conf_vector;
319 }
320
321 static void merge_server_configs(apr_pool_t *p, ap_conf_vector_t *base,
322                                  ap_conf_vector_t *virt)
323 {
324     /* Can reuse the 'virt' vector for the spine of it, since we don't
325      * have to deal with the moral equivalent of .htaccess files here...
326      */
327
328     void **base_vector = (void **)base;
329     void **virt_vector = (void **)virt;
330     module *modp;
331
332     for (modp = ap_top_module; modp; modp = modp->next) {
333         merger_func df = modp->merge_server_config;
334         int i = modp->module_index;
335
336         if (!virt_vector[i])
337             virt_vector[i] = base_vector[i];
338         else if (df)
339             virt_vector[i] = (*df)(p, base_vector[i], virt_vector[i]);
340     }
341 }
342
343 AP_CORE_DECLARE(ap_conf_vector_t *) ap_create_request_config(apr_pool_t *p)
344 {
345     return create_empty_config(p);
346 }
347
348 AP_CORE_DECLARE(ap_conf_vector_t *) ap_create_conn_config(apr_pool_t *p)
349 {
350     return create_empty_config(p);
351 }
352
353 AP_CORE_DECLARE(ap_conf_vector_t *) ap_create_per_dir_config(apr_pool_t *p)
354 {
355     return create_empty_config(p);
356 }
357
358 /* Invoke the filter_init_func for all filters with FILTERS where f->r
359  * matches R.  Restricting to a matching R avoids re-running init
360  * functions for filters configured for r->main where r is a
361  * subrequest.  */
362 static int invoke_filter_init(request_rec *r, ap_filter_t *filters)
363 {
364     while (filters) {
365         if (filters->frec->filter_init_func && filters->r == r) {
366             int result = filters->frec->filter_init_func(filters);
367             if (result != OK) {
368                 return result;
369             }
370         }
371         filters = filters->next;
372     }
373     return OK;
374 }
375
376 /*
377  * TODO: Move this to an appropriate include file and possibly prefix it
378  * with AP_.
379  */
380 #define DEFAULT_HANDLER_NAME ""
381
382 AP_CORE_DECLARE(int) ap_invoke_handler(request_rec *r)
383 {
384     const char *handler;
385     const char *p;
386     int result;
387     const char *old_handler = r->handler;
388     const char *ignore;
389
390     /*
391      * The new insert_filter stage makes the most sense here.  We only use
392      * it when we are going to run the request, so we must insert filters
393      * if any are available.  Since the goal of this phase is to allow all
394      * modules to insert a filter if they want to, this filter returns
395      * void.  I just can't see any way that this filter can reasonably
396      * fail, either your modules inserts something or it doesn't.  rbb
397      */
398     ap_run_insert_filter(r);
399
400     /* Before continuing, allow each filter that is in the two chains to
401      * run their init function to let them do any magic before we could
402      * start generating data.
403      */
404     result = invoke_filter_init(r, r->input_filters);
405     if (result != OK) {
406         return result;
407     }
408     result = invoke_filter_init(r, r->output_filters);
409     if (result != OK) {
410         return result;
411     }
412
413     if (!r->handler) {
414         if (r->content_type) {
415             handler = r->content_type;
416             if ((p=ap_strchr_c(handler, ';')) != NULL) {
417                 char *new_handler = (char *)apr_pmemdup(r->pool, handler,
418                                                         p - handler + 1);
419                 char *p2 = new_handler + (p - handler);
420                 handler = new_handler;
421
422                 /* exclude media type arguments */
423                 while (p2 > handler && p2[-1] == ' ')
424                     --p2; /* strip trailing spaces */
425
426                 *p2='\0';
427             }
428         }
429         else {
430             handler = DEFAULT_HANDLER_NAME;
431         }
432
433         r->handler = handler;
434     }
435
436     result = ap_run_handler(r);
437
438     r->handler = old_handler;
439
440     if (result == DECLINED && r->handler && r->filename) {
441         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(00523)
442             "handler \"%s\" not found for: %s", r->handler, r->filename);
443     }
444     if ((result != OK) && (result != DONE) && (result != DECLINED) && (result != SUSPENDED)
445         && (result != AP_FILTER_ERROR) /* ap_die() knows about this specifically */
446         && !ap_is_HTTP_VALID_RESPONSE(result)) {
447         /* If a module is deliberately returning something else
448          * (request_rec in non-HTTP or proprietary extension?)
449          * let it set a note to allow it explicitly.
450          * Otherwise, a return code that is neither reserved nor HTTP
451          * is a bug, as in PR#31759.
452          */
453         ignore = apr_table_get(r->notes, "HTTP_IGNORE_RANGE");
454         if (!ignore) {
455             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00524)
456                           "Handler for %s returned invalid result code %d",
457                           r->handler, result);
458             result = HTTP_INTERNAL_SERVER_ERROR;
459         }
460     }
461
462     return result == DECLINED ? HTTP_INTERNAL_SERVER_ERROR : result;
463 }
464
465 AP_DECLARE(int) ap_method_is_limited(cmd_parms *cmd, const char *method)
466 {
467     int methnum;
468
469     methnum = ap_method_number_of(method);
470
471     /*
472      * A method number either hardcoded into apache or
473      * added by a module and registered.
474      */
475     if (methnum != M_INVALID) {
476         return (cmd->limited & (AP_METHOD_BIT << methnum)) ? 1 : 0;
477     }
478
479     return 0; /* not found */
480 }
481
482 AP_DECLARE(void) ap_register_hooks(module *m, apr_pool_t *p)
483 {
484     if (m->register_hooks) {
485         if (getenv("SHOW_HOOKS")) {
486             printf("Registering hooks for %s\n", m->name);
487             apr_hook_debug_enabled = 1;
488         }
489
490         apr_hook_debug_current = m->name;
491         m->register_hooks(p);
492     }
493 }
494
495 static void ap_add_module_commands(module *m, apr_pool_t *p);
496
497 typedef struct ap_mod_list_struct ap_mod_list;
498 struct ap_mod_list_struct {
499     struct ap_mod_list_struct *next;
500     module *m;
501     const command_rec *cmd;
502 };
503
504 static void rebuild_conf_hash(apr_pool_t *p, int add_prelinked)
505 {
506     module **m;
507
508     ap_config_hash = apr_hash_make(p);
509
510     apr_pool_cleanup_register(p, &ap_config_hash, ap_pool_cleanup_set_null,
511                               apr_pool_cleanup_null);
512     if (add_prelinked) {
513         for (m = ap_prelinked_modules; *m != NULL; m++) {
514             ap_add_module_commands(*m, p);
515         }
516     }
517 }
518
519 static void ap_add_module_commands(module *m, apr_pool_t *p)
520 {
521     apr_pool_t *tpool;
522     ap_mod_list *mln;
523     const command_rec *cmd;
524     char *dir;
525
526     cmd = m->cmds;
527
528     if (ap_config_hash == NULL) {
529         rebuild_conf_hash(p, 0);
530     }
531
532     tpool = apr_hash_pool_get(ap_config_hash);
533
534     while (cmd && cmd->name) {
535         mln = apr_palloc(tpool, sizeof(ap_mod_list));
536         mln->cmd = cmd;
537         mln->m = m;
538         dir = apr_pstrdup(tpool, cmd->name);
539
540         ap_str_tolower(dir);
541
542         mln->next = apr_hash_get(ap_config_hash, dir, APR_HASH_KEY_STRING);
543         apr_hash_set(ap_config_hash, dir, APR_HASH_KEY_STRING, mln);
544         ++cmd;
545     }
546 }
547
548
549 /* One-time setup for precompiled modules --- NOT to be done on restart */
550
551 AP_DECLARE(const char *) ap_add_module(module *m, apr_pool_t *p,
552                                        const char *sym_name)
553 {
554     ap_module_symbol_t *sym = ap_prelinked_module_symbols;
555
556     /* This could be called from a LoadModule httpd.conf command,
557      * after the file has been linked and the module structure within it
558      * teased out...
559      */
560
561     if (m->version != MODULE_MAGIC_NUMBER_MAJOR) {
562         return apr_psprintf(p, "Module \"%s\" is not compatible with this "
563                             "version of Apache (found %d, need %d). Please "
564                             "contact the vendor for the correct version.",
565                             m->name, m->version, MODULE_MAGIC_NUMBER_MAJOR);
566     }
567
568     if (m->module_index == -1) {
569         if (dynamic_modules >= DYNAMIC_MODULE_LIMIT) {
570             return apr_psprintf(p, "Module \"%s\" could not be loaded, "
571                                 "because the dynamic module limit was "
572                                 "reached. Please increase "
573                                 "DYNAMIC_MODULE_LIMIT and recompile.", m->name);
574         }
575         /*
576          * If this fails some module forgot to call ap_reserve_module_slots*.
577          */
578         ap_assert(total_modules < conf_vector_length);
579
580         m->module_index = total_modules++;
581         dynamic_modules++;
582
583     }
584     else if (!sym_name) {
585         while (sym->modp != NULL) {
586             if (sym->modp == m) {
587                 sym_name = sym->name;
588                 break;
589             }
590             sym++;
591         }
592     }
593
594     if (m->next == NULL) {
595         m->next = ap_top_module;
596         ap_top_module = m;
597     }
598
599     if (sym_name) {
600         int len = strlen(sym_name);
601         int slen = strlen("_module");
602         if (len > slen && !strcmp(sym_name + len - slen, "_module")) {
603             len -= slen;
604         }
605
606         ap_module_short_names[m->module_index] = strdup(sym_name);
607         ap_module_short_names[m->module_index][len] = '\0';
608         merger_func_cache[m->module_index] = m->merge_dir_config;
609     }
610
611
612     /* Some C compilers put a complete path into __FILE__, but we want
613      * only the filename (e.g. mod_includes.c). So check for path
614      * components (Unix and DOS), and remove them.
615      */
616
617     if (ap_strrchr_c(m->name, '/'))
618         m->name = 1 + ap_strrchr_c(m->name, '/');
619
620     if (ap_strrchr_c(m->name, '\\'))
621         m->name = 1 + ap_strrchr_c(m->name, '\\');
622
623 #ifdef _OSD_POSIX
624     /* __FILE__ =
625      * "*POSIX(/home/martin/apache/src/modules/standard/mod_info.c)"
626      */
627
628     /* We cannot fix the string in-place, because it's const */
629     if (m->name[strlen(m->name)-1] == ')') {
630         char *tmp = strdup(m->name); /* FIXME: memory leak, albeit a small one */
631         tmp[strlen(tmp)-1] = '\0';
632         m->name = tmp;
633     }
634 #endif /*_OSD_POSIX*/
635
636     ap_add_module_commands(m, p);
637     /*  FIXME: is this the right place to call this?
638      *  It doesn't appear to be
639      */
640     ap_register_hooks(m, p);
641
642     return NULL;
643 }
644
645 /*
646  * remove_module undoes what add_module did. There are some caveats:
647  * when the module is removed, its slot is lost so all the current
648  * per-dir and per-server configurations are invalid. So we should
649  * only ever call this function when you are invalidating almost
650  * all our current data. I.e. when doing a restart.
651  */
652
653 AP_DECLARE(void) ap_remove_module(module *m)
654 {
655     module *modp;
656
657     modp = ap_top_module;
658     if (modp == m) {
659         /* We are the top module, special case */
660         ap_top_module = modp->next;
661         m->next = NULL;
662     }
663     else {
664         /* Not the top module, find use. When found modp will
665          * point to the module _before_ us in the list
666          */
667
668         while (modp && modp->next != m) {
669             modp = modp->next;
670         }
671
672         if (!modp) {
673             /* Uh-oh, this module doesn't exist */
674             ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL, APLOGNO(00525)
675                          "Cannot remove module %s: not found in module list",
676                          m->name);
677             return;
678         }
679
680         /* Eliminate us from the module list */
681         modp->next = modp->next->next;
682     }
683
684     free(ap_module_short_names[m->module_index]);
685     ap_module_short_names[m->module_index] = NULL;
686     merger_func_cache[m->module_index] = NULL;
687
688     m->module_index = -1; /* simulate being unloaded, should
689                            * be unnecessary */
690     dynamic_modules--;
691     total_modules--;
692 }
693
694 AP_DECLARE(const char *) ap_add_loaded_module(module *mod, apr_pool_t *p,
695                                               const char *short_name)
696 {
697     module **m;
698     const char *error;
699
700     /*
701      *  Add module pointer to top of chained module list
702      */
703     error = ap_add_module(mod, p, short_name);
704     if (error) {
705         return error;
706     }
707
708     /*
709      *  And module pointer to list of loaded modules
710      *
711      *  Notes: 1. ap_add_module() would already complain if no more space
712      *            exists for adding a dynamically loaded module
713      *         2. ap_add_module() accepts double inclusion, so we have
714      *            to accept this, too.
715      */
716     for (m = ap_loaded_modules; *m != NULL; m++)
717         ;
718     *m++ = mod;
719     *m = NULL;
720
721     return NULL;
722 }
723
724 AP_DECLARE(void) ap_remove_loaded_module(module *mod)
725 {
726     module **m;
727     module **m2;
728     int done;
729
730     /*
731      *  Remove module pointer from chained module list
732      */
733     ap_remove_module(mod);
734
735     /*
736      *  Remove module pointer from list of loaded modules
737      *
738      *  Note: 1. We cannot determine if the module was successfully
739      *           removed by ap_remove_module().
740      *        2. We have not to complain explicity when the module
741      *           is not found because ap_remove_module() did it
742      *           for us already.
743      */
744     for (m = m2 = ap_loaded_modules, done = 0; *m2 != NULL; m2++) {
745         if (*m2 == mod && done == 0)
746             done = 1;
747         else
748             *m++ = *m2;
749     }
750
751     *m = NULL;
752 }
753
754 AP_DECLARE(const char *) ap_setup_prelinked_modules(process_rec *process)
755 {
756     module **m;
757     module **m2;
758     const char *error;
759
760     apr_hook_global_pool=process->pconf;
761
762     rebuild_conf_hash(process->pconf, 0);
763
764     /*
765      *  Initialise total_modules variable and module indices
766      */
767     total_modules = 0;
768     for (m = ap_preloaded_modules; *m != NULL; m++)
769         (*m)->module_index = total_modules++;
770
771     max_modules = total_modules + DYNAMIC_MODULE_LIMIT + 1;
772     conf_vector_length = max_modules;
773
774     /*
775      *  Initialise list of loaded modules and short names
776      */
777     ap_loaded_modules = (module **)apr_palloc(process->pool,
778         sizeof(module *) * conf_vector_length);
779     if (!ap_module_short_names)
780         ap_module_short_names = ap_calloc(sizeof(char *), conf_vector_length);
781
782     if (!merger_func_cache)
783         merger_func_cache = ap_calloc(sizeof(merger_func), conf_vector_length);
784
785     if (ap_loaded_modules == NULL || ap_module_short_names == NULL
786         || merger_func_cache == NULL)
787         return "Ouch! Out of memory in ap_setup_prelinked_modules()!";
788
789     for (m = ap_preloaded_modules, m2 = ap_loaded_modules; *m != NULL; )
790         *m2++ = *m++;
791
792     *m2 = NULL;
793
794     /*
795      *   Initialize chain of linked (=activate) modules
796      */
797     for (m = ap_prelinked_modules; *m != NULL; m++) {
798         error = ap_add_module(*m, process->pconf, NULL);
799         if (error) {
800             return error;
801         }
802     }
803
804     apr_hook_sort_all();
805
806     return NULL;
807 }
808
809 AP_DECLARE(const char *) ap_find_module_name(module *m)
810 {
811     return m->name;
812 }
813
814 AP_DECLARE(const char *) ap_find_module_short_name(int module_index)
815 {
816         if (module_index < 0 || module_index >= conf_vector_length)
817                 return NULL;
818         return ap_module_short_names[module_index];
819 }
820
821 AP_DECLARE(module *) ap_find_linked_module(const char *name)
822 {
823     module *modp;
824
825     for (modp = ap_top_module; modp; modp = modp->next) {
826         if (strcmp(modp->name, name) == 0)
827             return modp;
828     }
829
830     return NULL;
831 }
832
833 /*****************************************************************
834  *
835  * Resource, access, and .htaccess config files now parsed by a common
836  * command loop.
837  *
838  * Let's begin with the basics; parsing the line and
839  * invoking the function...
840  */
841
842 #define AP_MAX_ARGC 64
843
844 static const char *invoke_cmd(const command_rec *cmd, cmd_parms *parms,
845                               void *mconfig, const char *args)
846 {
847     int override_list_ok = 0;
848     char *w, *w2, *w3;
849     const char *errmsg = NULL;
850
851     /** Have we been provided a list of acceptable directives? */
852     if (parms->override_list != NULL) { 
853          if (apr_table_get(parms->override_list, cmd->name) != NULL) { 
854               override_list_ok = 1;
855          }
856     }
857
858     if ((parms->override & cmd->req_override) == 0 && !override_list_ok) {
859         if (parms->override & NONFATAL_OVERRIDE) {
860             ap_log_perror(APLOG_MARK, APLOG_WARNING, 0, parms->temp_pool,
861                           APLOGNO(02295)
862                           "%s in .htaccess forbidden by AllowOverride",
863                           cmd->name);
864             return NULL;
865         }
866         else {
867             return apr_pstrcat(parms->pool, cmd->name,
868                                " not allowed here", NULL);
869         }
870     }
871
872     parms->info = cmd->cmd_data;
873     parms->cmd = cmd;
874
875     switch (cmd->args_how) {
876     case RAW_ARGS:
877 #ifdef RESOLVE_ENV_PER_TOKEN
878         args = ap_resolve_env(parms->pool,args);
879 #endif
880         return cmd->AP_RAW_ARGS(parms, mconfig, args);
881
882     case TAKE_ARGV:
883         {
884             char *argv[AP_MAX_ARGC];
885             int argc = 0;
886
887             do {
888                 w = ap_getword_conf(parms->pool, &args);
889                 if (*w == '\0' && *args == '\0') {
890                     break;
891                 }
892                 argv[argc] = w;
893                 argc++;
894             } while (argc < AP_MAX_ARGC && *args != '\0');
895
896             return cmd->AP_TAKE_ARGV(parms, mconfig, argc, argv);
897         }
898
899     case NO_ARGS:
900         if (*args != 0)
901             return apr_pstrcat(parms->pool, cmd->name, " takes no arguments",
902                                NULL);
903
904         return cmd->AP_NO_ARGS(parms, mconfig);
905
906     case TAKE1:
907         w = ap_getword_conf(parms->pool, &args);
908
909         if (*w == '\0' || *args != 0)
910             return apr_pstrcat(parms->pool, cmd->name, " takes one argument",
911                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
912
913         return cmd->AP_TAKE1(parms, mconfig, w);
914
915     case TAKE2:
916         w = ap_getword_conf(parms->pool, &args);
917         w2 = ap_getword_conf(parms->pool, &args);
918
919         if (*w == '\0' || *w2 == '\0' || *args != 0)
920             return apr_pstrcat(parms->pool, cmd->name, " takes two arguments",
921                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
922
923         return cmd->AP_TAKE2(parms, mconfig, w, w2);
924
925     case TAKE12:
926         w = ap_getword_conf(parms->pool, &args);
927         w2 = ap_getword_conf(parms->pool, &args);
928
929         if (*w == '\0' || *args != 0)
930             return apr_pstrcat(parms->pool, cmd->name, " takes 1-2 arguments",
931                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
932
933         return cmd->AP_TAKE2(parms, mconfig, w, *w2 ? w2 : NULL);
934
935     case TAKE3:
936         w = ap_getword_conf(parms->pool, &args);
937         w2 = ap_getword_conf(parms->pool, &args);
938         w3 = ap_getword_conf(parms->pool, &args);
939
940         if (*w == '\0' || *w2 == '\0' || *w3 == '\0' || *args != 0)
941             return apr_pstrcat(parms->pool, cmd->name, " takes three arguments",
942                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
943
944         return cmd->AP_TAKE3(parms, mconfig, w, w2, w3);
945
946     case TAKE23:
947         w = ap_getword_conf(parms->pool, &args);
948         w2 = ap_getword_conf(parms->pool, &args);
949         w3 = *args ? ap_getword_conf(parms->pool, &args) : NULL;
950
951         if (*w == '\0' || *w2 == '\0' || *args != 0)
952             return apr_pstrcat(parms->pool, cmd->name,
953                                " takes two or three arguments",
954                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
955
956         return cmd->AP_TAKE3(parms, mconfig, w, w2, w3);
957
958     case TAKE123:
959         w = ap_getword_conf(parms->pool, &args);
960         w2 = *args ? ap_getword_conf(parms->pool, &args) : NULL;
961         w3 = *args ? ap_getword_conf(parms->pool, &args) : NULL;
962
963         if (*w == '\0' || *args != 0)
964             return apr_pstrcat(parms->pool, cmd->name,
965                                " takes one, two or three arguments",
966                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
967
968         return cmd->AP_TAKE3(parms, mconfig, w, w2, w3);
969
970     case TAKE13:
971         w = ap_getword_conf(parms->pool, &args);
972         w2 = *args ? ap_getword_conf(parms->pool, &args) : NULL;
973         w3 = *args ? ap_getword_conf(parms->pool, &args) : NULL;
974
975         if (*w == '\0' || (w2 && *w2 && !w3) || *args != 0)
976             return apr_pstrcat(parms->pool, cmd->name,
977                                " takes one or three arguments",
978                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
979
980         return cmd->AP_TAKE3(parms, mconfig, w, w2, w3);
981
982     case ITERATE:
983         while (*(w = ap_getword_conf(parms->pool, &args)) != '\0') {
984
985             errmsg = cmd->AP_TAKE1(parms, mconfig, w);
986
987             if (errmsg && strcmp(errmsg, DECLINE_CMD) != 0)
988                 return errmsg;
989         }
990
991         return errmsg;
992
993     case ITERATE2:
994         w = ap_getword_conf(parms->pool, &args);
995
996         if (*w == '\0' || *args == 0)
997             return apr_pstrcat(parms->pool, cmd->name,
998                                " requires at least two arguments",
999                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
1000
1001         while (*(w2 = ap_getword_conf(parms->pool, &args)) != '\0') {
1002
1003             errmsg = cmd->AP_TAKE2(parms, mconfig, w, w2);
1004
1005             if (errmsg && strcmp(errmsg, DECLINE_CMD) != 0)
1006                 return errmsg;
1007         }
1008
1009         return errmsg;
1010
1011     case FLAG:
1012         w = ap_getword_conf(parms->pool, &args);
1013
1014         if (*w == '\0' || (strcasecmp(w, "on") && strcasecmp(w, "off")))
1015             return apr_pstrcat(parms->pool, cmd->name, " must be On or Off",
1016                                NULL);
1017
1018         return cmd->AP_FLAG(parms, mconfig, strcasecmp(w, "off") != 0);
1019
1020     default:
1021         return apr_pstrcat(parms->pool, cmd->name,
1022                            " is improperly configured internally (server bug)",
1023                            NULL);
1024     }
1025 }
1026
1027 AP_CORE_DECLARE(const command_rec *) ap_find_command(const char *name,
1028                                                      const command_rec *cmds)
1029 {
1030     while (cmds->name) {
1031         if (!strcasecmp(name, cmds->name))
1032             return cmds;
1033
1034         ++cmds;
1035     }
1036
1037     return NULL;
1038 }
1039
1040 AP_CORE_DECLARE(const command_rec *) ap_find_command_in_modules(
1041                                           const char *cmd_name, module **mod)
1042 {
1043     const command_rec *cmdp;
1044     module *modp;
1045
1046     for (modp = *mod; modp; modp = modp->next) {
1047         if (modp->cmds && (cmdp = ap_find_command(cmd_name, modp->cmds))) {
1048             *mod = modp;
1049             return cmdp;
1050         }
1051     }
1052
1053     return NULL;
1054 }
1055
1056 AP_CORE_DECLARE(void *) ap_set_config_vectors(server_rec *server,
1057                                               ap_conf_vector_t *section_vector,
1058                                               const char *section,
1059                                               module *mod, apr_pool_t *pconf)
1060 {
1061     void *section_config = ap_get_module_config(section_vector, mod);
1062     void *server_config = ap_get_module_config(server->module_config, mod);
1063
1064     if (!section_config && mod->create_dir_config) {
1065         /* ### need to fix the create_dir_config functions' prototype... */
1066         section_config = (*mod->create_dir_config)(pconf, (char *)section);
1067         ap_set_module_config(section_vector, mod, section_config);
1068     }
1069
1070     if (!server_config && mod->create_server_config) {
1071         server_config = (*mod->create_server_config)(pconf, server);
1072         ap_set_module_config(server->module_config, mod, server_config);
1073     }
1074
1075     return section_config;
1076 }
1077
1078 static const char *execute_now(char *cmd_line, const char *args,
1079                                cmd_parms *parms,
1080                                apr_pool_t *p, apr_pool_t *ptemp,
1081                                ap_directive_t **sub_tree,
1082                                ap_directive_t *parent);
1083
1084 static const char *ap_build_config_sub(apr_pool_t *p, apr_pool_t *temp_pool,
1085                                        const char *l, cmd_parms *parms,
1086                                        ap_directive_t **current,
1087                                        ap_directive_t **curr_parent,
1088                                        ap_directive_t **conftree)
1089 {
1090     const char *retval = NULL;
1091     const char *args;
1092     char *cmd_name;
1093     ap_directive_t *newdir;
1094     module *mod = ap_top_module;
1095     const command_rec *cmd;
1096
1097     if (*l == '#' || *l == '\0')
1098         return NULL;
1099
1100 #if RESOLVE_ENV_PER_TOKEN
1101     args = l;
1102 #else
1103     args = ap_resolve_env(temp_pool, l);
1104 #endif
1105
1106     cmd_name = ap_getword_conf(p, &args);
1107     if (*cmd_name == '\0') {
1108         /* Note: this branch should not occur. An empty line should have
1109          * triggered the exit further above.
1110          */
1111         return NULL;
1112     }
1113
1114     if (cmd_name[1] != '/') {
1115         char *lastc = cmd_name + strlen(cmd_name) - 1;
1116         if (*lastc == '>') {
1117             *lastc = '\0' ;
1118         }
1119         if (cmd_name[0] == '<' && *args == '\0') {
1120             args = ">";
1121         }
1122     }
1123
1124     newdir = apr_pcalloc(p, sizeof(ap_directive_t));
1125     newdir->filename = parms->config_file->name;
1126     newdir->line_num = parms->config_file->line_number;
1127     newdir->directive = cmd_name;
1128     newdir->args = apr_pstrdup(p, args);
1129
1130     if ((cmd = ap_find_command_in_modules(cmd_name, &mod)) != NULL) {
1131         if (cmd->req_override & EXEC_ON_READ) {
1132             ap_directive_t *sub_tree = NULL;
1133
1134             parms->err_directive = newdir;
1135             retval = execute_now(cmd_name, args, parms, p, temp_pool,
1136                                  &sub_tree, *curr_parent);
1137             if (*current) {
1138                 (*current)->next = sub_tree;
1139             }
1140             else {
1141                 *current = sub_tree;
1142                 if (*curr_parent) {
1143                     (*curr_parent)->first_child = (*current);
1144                 }
1145                 if (*current) {
1146                     (*current)->parent = (*curr_parent);
1147                 }
1148             }
1149             if (*current) {
1150                 if (!*conftree) {
1151                     /* Before walking *current to the end of the list,
1152                      * set the head to *current.
1153                      */
1154                     *conftree = *current;
1155                 }
1156                 while ((*current)->next != NULL) {
1157                     (*current) = (*current)->next;
1158                     (*current)->parent = (*curr_parent);
1159                 }
1160             }
1161             return retval;
1162         }
1163     }
1164
1165     if (cmd_name[0] == '<') {
1166         if (cmd_name[1] != '/') {
1167             (*current) = ap_add_node(curr_parent, *current, newdir, 1);
1168         }
1169         else if (*curr_parent == NULL) {
1170             parms->err_directive = newdir;
1171             return apr_pstrcat(p, cmd_name,
1172                                " without matching <", cmd_name + 2,
1173                                " section", NULL);
1174         }
1175         else {
1176             char *bracket = cmd_name + strlen(cmd_name) - 1;
1177
1178             if (*bracket != '>') {
1179                 parms->err_directive = newdir;
1180                 return apr_pstrcat(p, cmd_name,
1181                                    "> directive missing closing '>'", NULL);
1182             }
1183
1184             *bracket = '\0';
1185
1186             if (strcasecmp(cmd_name + 2,
1187                            (*curr_parent)->directive + 1) != 0) {
1188                 parms->err_directive = newdir;
1189                 return apr_pstrcat(p, "Expected </",
1190                                    (*curr_parent)->directive + 1, "> but saw ",
1191                                    cmd_name, ">", NULL);
1192             }
1193
1194             *bracket = '>';
1195
1196             /* done with this section; move up a level */
1197             *current = *curr_parent;
1198             *curr_parent = (*current)->parent;
1199         }
1200     }
1201     else {
1202         *current = ap_add_node(curr_parent, *current, newdir, 0);
1203     }
1204
1205     return retval;
1206 }
1207
1208 #define VARBUF_INIT_LEN 200
1209 #define VARBUF_MAX_LEN  (16*1024*1024)
1210
1211 AP_DECLARE(const char *) ap_build_cont_config(apr_pool_t *p,
1212                                               apr_pool_t *temp_pool,
1213                                               cmd_parms *parms,
1214                                               ap_directive_t **current,
1215                                               ap_directive_t **curr_parent,
1216                                               char *orig_directive)
1217 {
1218     char *bracket;
1219     const char *retval;
1220     ap_directive_t *sub_tree = NULL;
1221     apr_status_t rc;
1222     struct ap_varbuf vb;
1223     apr_size_t max_len = VARBUF_MAX_LEN;
1224     if (p == temp_pool)
1225         max_len = HUGE_STRING_LEN; /* lower limit for .htaccess */
1226
1227     bracket = apr_pstrcat(temp_pool, orig_directive + 1, ">", NULL);
1228     ap_varbuf_init(temp_pool, &vb, VARBUF_INIT_LEN);
1229
1230     while ((rc = ap_varbuf_cfg_getline(&vb, parms->config_file, max_len))
1231            == APR_SUCCESS) {
1232         if (!memcmp(vb.buf, "</", 2)
1233             && (strcasecmp(vb.buf + 2, bracket) == 0)
1234             && (*curr_parent == NULL)) {
1235             break;
1236         }
1237         retval = ap_build_config_sub(p, temp_pool, vb.buf, parms, current,
1238                                      curr_parent, &sub_tree);
1239         if (retval != NULL)
1240             return retval;
1241
1242         if (sub_tree == NULL) {
1243             sub_tree = *curr_parent;
1244         }
1245
1246         if (sub_tree == NULL) {
1247             sub_tree = *current;
1248         }
1249     }
1250     ap_varbuf_free(&vb);
1251     if (rc != APR_EOF && rc != APR_SUCCESS)
1252         return ap_pcfg_strerror(temp_pool, parms->config_file, rc);
1253
1254     *current = sub_tree;
1255     return NULL;
1256 }
1257
1258 static const char *ap_walk_config_sub(const ap_directive_t *current,
1259                                       cmd_parms *parms,
1260                                       ap_conf_vector_t *section_vector)
1261 {
1262     const command_rec *cmd;
1263     ap_mod_list *ml;
1264     char *dir = apr_pstrdup(parms->temp_pool, current->directive);
1265
1266     ap_str_tolower(dir);
1267
1268     ml = apr_hash_get(ap_config_hash, dir, APR_HASH_KEY_STRING);
1269
1270     if (ml == NULL) {
1271         parms->err_directive = current;
1272         if (parms->override & NONFATAL_UNKNOWN) {
1273             ap_log_perror(APLOG_MARK, APLOG_WARNING, 0, parms->temp_pool,
1274                           APLOGNO(02296) "Unknown directive %s "
1275                           "perhaps misspelled or defined by a module "
1276                           "not included in the server configuration", dir);
1277             return NULL;
1278         }
1279         else {
1280             return apr_pstrcat(parms->pool, "Invalid command '",
1281                                current->directive,
1282                                "', perhaps misspelled or defined by a module "
1283                                "not included in the server configuration",
1284                                NULL);
1285         }
1286     }
1287
1288     for ( ; ml != NULL; ml = ml->next) {
1289         void *dir_config = ap_set_config_vectors(parms->server,
1290                                                  section_vector,
1291                                                  parms->path,
1292                                                  ml->m,
1293                                                  parms->pool);
1294         const char *retval;
1295         cmd = ml->cmd;
1296
1297         /* Once was enough? */
1298         if (cmd->req_override & EXEC_ON_READ) {
1299             continue;
1300         }
1301
1302         retval = invoke_cmd(cmd, parms, dir_config, current->args);
1303
1304         if (retval != NULL && strcmp(retval, DECLINE_CMD) != 0) {
1305             /* If the directive in error has already been set, don't
1306              * replace it.  Otherwise, an error inside a container
1307              * will be reported as occuring on the first line of the
1308              * container.
1309              */
1310             if (!parms->err_directive) {
1311                 parms->err_directive = current;
1312             }
1313             return retval;
1314         }
1315     }
1316
1317     return NULL;
1318 }
1319
1320 AP_DECLARE(const char *) ap_walk_config(ap_directive_t *current,
1321                                         cmd_parms *parms,
1322                                         ap_conf_vector_t *section_vector)
1323 {
1324     ap_conf_vector_t *oldconfig = parms->context;
1325
1326     parms->context = section_vector;
1327
1328     /* scan through all directives, executing each one */
1329     for (; current != NULL; current = current->next) {
1330         const char *errmsg;
1331
1332         parms->directive = current;
1333
1334         /* actually parse the command and execute the correct function */
1335         errmsg = ap_walk_config_sub(current, parms, section_vector);
1336         if (errmsg != NULL) {
1337             /* restore the context (just in case) */
1338             parms->context = oldconfig;
1339             return errmsg;
1340         }
1341     }
1342
1343     parms->context = oldconfig;
1344     return NULL;
1345 }
1346
1347 AP_DECLARE(const char *) ap_build_config(cmd_parms *parms,
1348                                          apr_pool_t *p, apr_pool_t *temp_pool,
1349                                          ap_directive_t **conftree)
1350 {
1351     ap_directive_t *current = *conftree;
1352     ap_directive_t *curr_parent = NULL;
1353     const char *errmsg;
1354     ap_directive_t **last_ptr = NULL;
1355     apr_status_t rc;
1356     struct ap_varbuf vb;
1357     apr_size_t max_len = VARBUF_MAX_LEN;
1358     if (p == temp_pool)
1359         max_len = HUGE_STRING_LEN; /* lower limit for .htaccess */
1360
1361     ap_varbuf_init(temp_pool, &vb, VARBUF_INIT_LEN);
1362
1363     if (current != NULL) {
1364         /* If we have to traverse the whole tree again for every included
1365          * config file, the required time grows as O(n^2) with the number of
1366          * files. This can be a significant delay for large configurations.
1367          * Therefore we cache a pointer to the last node.
1368          */
1369         last_ptr = &(current->last);
1370
1371         if(last_ptr && *last_ptr) {
1372             current = *last_ptr;
1373         }
1374
1375         while (current->next) {
1376             current = current->next;
1377         }
1378
1379         if(last_ptr) {
1380             /* update cached pointer to last node */
1381             *last_ptr = current;
1382         }
1383     }
1384
1385     while ((rc = ap_varbuf_cfg_getline(&vb, parms->config_file, max_len))
1386            == APR_SUCCESS) {
1387         errmsg = ap_build_config_sub(p, temp_pool, vb.buf, parms,
1388                                      &current, &curr_parent, conftree);
1389         if (errmsg != NULL)
1390             return errmsg;
1391
1392         if (*conftree == NULL && curr_parent != NULL) {
1393             *conftree = curr_parent;
1394         }
1395
1396         if (*conftree == NULL && current != NULL) {
1397             *conftree = current;
1398         }
1399     }
1400     ap_varbuf_free(&vb);
1401     if (rc != APR_EOF && rc != APR_SUCCESS)
1402         return ap_pcfg_strerror(temp_pool, parms->config_file, rc);
1403
1404     if (curr_parent != NULL) {
1405         errmsg = "";
1406
1407         while (curr_parent != NULL) {
1408             errmsg = apr_psprintf(p, "%s%s%s:%u: %s> was not closed.",
1409                                   errmsg,
1410                                   *errmsg == '\0' ? "" : APR_EOL_STR,
1411                                   curr_parent->filename,
1412                                   curr_parent->line_num,
1413                                   curr_parent->directive);
1414
1415             parms->err_directive = curr_parent;
1416             curr_parent = curr_parent->parent;
1417         }
1418
1419         return errmsg;
1420     }
1421
1422     return NULL;
1423 }
1424
1425 /*
1426  * Generic command functions...
1427  */
1428
1429 AP_DECLARE_NONSTD(const char *) ap_set_string_slot(cmd_parms *cmd,
1430                                                    void *struct_ptr,
1431                                                    const char *arg)
1432 {
1433     int offset = (int)(long)cmd->info;
1434
1435     *(const char **)((char *)struct_ptr + offset) = arg;
1436
1437     return NULL;
1438 }
1439
1440 AP_DECLARE_NONSTD(const char *) ap_set_int_slot(cmd_parms *cmd,
1441                                                 void *struct_ptr,
1442                                                 const char *arg)
1443 {
1444     char *endptr;
1445     char *error_str = NULL;
1446     int offset = (int)(long)cmd->info;
1447
1448     *(int *)((char*)struct_ptr + offset) = strtol(arg, &endptr, 10);
1449
1450     if ((*arg == '\0') || (*endptr != '\0')) {
1451         error_str = apr_psprintf(cmd->pool,
1452                      "Invalid value for directive %s, expected integer",
1453                      cmd->directive->directive);
1454     }
1455
1456     return error_str;
1457 }
1458
1459 AP_DECLARE_NONSTD(const char *) ap_set_string_slot_lower(cmd_parms *cmd,
1460                                                          void *struct_ptr,
1461                                                          const char *arg_)
1462 {
1463     char *arg = apr_pstrdup(cmd->pool,arg_);
1464     int offset = (int)(long)cmd->info;
1465
1466     ap_str_tolower(arg);
1467     *(char **)((char *)struct_ptr + offset) = arg;
1468
1469     return NULL;
1470 }
1471
1472 AP_DECLARE_NONSTD(const char *) ap_set_flag_slot(cmd_parms *cmd,
1473                                                  void *struct_ptr_v, int arg)
1474 {
1475     int offset = (int)(long)cmd->info;
1476     char *struct_ptr = (char *)struct_ptr_v;
1477
1478     *(int *)(struct_ptr + offset) = arg ? 1 : 0;
1479
1480     return NULL;
1481 }
1482
1483 AP_DECLARE_NONSTD(const char *) ap_set_flag_slot_char(cmd_parms *cmd,
1484                                                       void *struct_ptr_v, int arg)
1485 {
1486     int offset = (int)(long)cmd->info;
1487     char *struct_ptr = (char *)struct_ptr_v;
1488
1489     *(struct_ptr + offset) = arg ? 1 : 0;
1490
1491     return NULL;
1492 }
1493
1494
1495 AP_DECLARE_NONSTD(const char *) ap_set_file_slot(cmd_parms *cmd, void *struct_ptr,
1496                                                  const char *arg)
1497 {
1498     /* Prepend server_root to relative arg.
1499      * This allows most args to be independent of server_root,
1500      * so the server can be moved or mirrored with less pain.
1501      */
1502     const char *path;
1503     int offset = (int)(long)cmd->info;
1504
1505     path = ap_server_root_relative(cmd->pool, arg);
1506
1507     if (!path) {
1508         return apr_pstrcat(cmd->pool, "Invalid file path ",
1509                            arg, NULL);
1510     }
1511
1512     *(const char **) ((char*)struct_ptr + offset) = path;
1513
1514     return NULL;
1515 }
1516
1517 AP_DECLARE_NONSTD(const char *) ap_set_deprecated(cmd_parms *cmd,
1518                                                   void *struct_ptr,
1519                                                   const char *arg)
1520 {
1521     return cmd->cmd->errmsg;
1522 }
1523
1524 AP_DECLARE(void) ap_reset_module_loglevels(struct ap_logconf *l, int val)
1525 {
1526     if (l->module_levels)
1527         memset(l->module_levels, val, conf_vector_length);
1528 }
1529
1530 AP_DECLARE(void) ap_set_module_loglevel(apr_pool_t *pool, struct ap_logconf *l,
1531                                         int index, int level)
1532 {
1533     if (!l->module_levels) {
1534         l->module_levels = apr_palloc(pool, conf_vector_length);
1535         if (l->level == APLOG_UNSET) {
1536                 ap_reset_module_loglevels(l, APLOG_UNSET);
1537         }
1538         else {
1539                 ap_reset_module_loglevels(l, APLOG_NO_MODULE);
1540         }
1541     }
1542
1543     l->module_levels[index] = level;
1544 }
1545
1546 /*****************************************************************
1547  *
1548  * Reading whole config files...
1549  */
1550
1551 static cmd_parms default_parms =
1552 {NULL, 0, 0, NULL, -1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
1553
1554 AP_DECLARE(char *) ap_server_root_relative(apr_pool_t *p, const char *file)
1555 {
1556     char *newpath = NULL;
1557     apr_status_t rv;
1558     rv = apr_filepath_merge(&newpath, ap_server_root, file,
1559                             APR_FILEPATH_TRUENAME, p);
1560     if (newpath && (rv == APR_SUCCESS || APR_STATUS_IS_EPATHWILD(rv)
1561                                       || APR_STATUS_IS_ENOENT(rv)
1562                                       || APR_STATUS_IS_ENOTDIR(rv))) {
1563         return newpath;
1564     }
1565     else {
1566         return NULL;
1567     }
1568 }
1569
1570 AP_DECLARE(char *) ap_runtime_dir_relative(apr_pool_t *p, const char *file)
1571 {
1572     char *newpath = NULL;
1573     apr_status_t rv;
1574     const char *runtime_dir = ap_runtime_dir ? ap_runtime_dir : ap_server_root_relative(p, DEFAULT_REL_RUNTIMEDIR);
1575
1576     rv = apr_filepath_merge(&newpath, runtime_dir, file,
1577                             APR_FILEPATH_TRUENAME, p);
1578     if (newpath && (rv == APR_SUCCESS || APR_STATUS_IS_EPATHWILD(rv)
1579                                       || APR_STATUS_IS_ENOENT(rv)
1580                                       || APR_STATUS_IS_ENOTDIR(rv))) {
1581         return newpath;
1582     }
1583     else {
1584         return NULL;
1585     }
1586 }
1587
1588
1589 AP_DECLARE(const char *) ap_soak_end_container(cmd_parms *cmd, char *directive)
1590 {
1591     struct ap_varbuf vb;
1592     const char *args;
1593     char *cmd_name;
1594     apr_status_t rc;
1595     apr_size_t max_len = VARBUF_MAX_LEN;
1596     if (cmd->pool == cmd->temp_pool)
1597         max_len = HUGE_STRING_LEN; /* lower limit for .htaccess */
1598
1599     ap_varbuf_init(cmd->temp_pool, &vb, VARBUF_INIT_LEN);
1600
1601     while((rc = ap_varbuf_cfg_getline(&vb, cmd->config_file, max_len))
1602           == APR_SUCCESS) {
1603 #if RESOLVE_ENV_PER_TOKEN
1604         args = vb.buf;
1605 #else
1606         args = ap_resolve_env(cmd->temp_pool, vb.buf);
1607 #endif
1608
1609         cmd_name = ap_getword_conf(cmd->temp_pool, &args);
1610         if (cmd_name[0] == '<') {
1611             if (cmd_name[1] == '/') {
1612                 cmd_name[strlen(cmd_name) - 1] = '\0';
1613
1614                 if (strcasecmp(cmd_name + 2, directive + 1) != 0) {
1615                     return apr_pstrcat(cmd->pool, "Expected </",
1616                                        directive + 1, "> but saw ",
1617                                        cmd_name, ">", NULL);
1618                 }
1619
1620                 ap_varbuf_free(&vb);
1621                 return NULL; /* found end of container */
1622             }
1623             else {
1624                 const char *msg;
1625
1626                 if (*args == '\0' && cmd_name[strlen(cmd_name) - 1] == '>') {
1627                     cmd_name[strlen(cmd_name) - 1] = '\0';
1628                 }
1629
1630                 if ((msg = ap_soak_end_container(cmd, cmd_name)) != NULL) {
1631                     return msg;
1632                 }
1633             }
1634         }
1635     }
1636     if (rc != APR_EOF && rc != APR_SUCCESS)
1637         return ap_pcfg_strerror(cmd->temp_pool, cmd->config_file, rc);
1638
1639     return apr_pstrcat(cmd->pool, "Expected </",
1640                        directive + 1, "> before end of configuration",
1641                        NULL);
1642 }
1643
1644 static const char *execute_now(char *cmd_line, const char *args,
1645                                cmd_parms *parms,
1646                                apr_pool_t *p, apr_pool_t *ptemp,
1647                                ap_directive_t **sub_tree,
1648                                ap_directive_t *parent)
1649 {
1650     const command_rec *cmd;
1651     ap_mod_list *ml;
1652     char *dir = apr_pstrdup(parms->temp_pool, cmd_line);
1653
1654     ap_str_tolower(dir);
1655
1656     ml = apr_hash_get(ap_config_hash, dir, APR_HASH_KEY_STRING);
1657
1658     if (ml == NULL) {
1659         return apr_pstrcat(parms->pool, "Invalid command '",
1660                            cmd_line,
1661                            "', perhaps misspelled or defined by a module "
1662                            "not included in the server configuration",
1663                            NULL);
1664     }
1665
1666     for ( ; ml != NULL; ml = ml->next) {
1667         const char *retval;
1668         cmd = ml->cmd;
1669
1670         retval = invoke_cmd(cmd, parms, sub_tree, args);
1671
1672         if (retval != NULL) {
1673             return retval;
1674         }
1675     }
1676
1677     return NULL;
1678 }
1679
1680 /* This structure and the following functions are needed for the
1681  * table-based config file reading. They are passed to the
1682  * cfg_open_custom() routine.
1683  */
1684
1685 /* Structure to be passed to cfg_open_custom(): it contains an
1686  * index which is incremented from 0 to nelts on each call to
1687  * cfg_getline() (which in turn calls arr_elts_getstr())
1688  * and an apr_array_header_t pointer for the string array.
1689  */
1690 typedef struct {
1691     apr_array_header_t *array;
1692     int curr_idx;
1693 } arr_elts_param_t;
1694
1695
1696 /* arr_elts_getstr() returns the next line from the string array. */
1697 static apr_status_t arr_elts_getstr(void *buf, apr_size_t bufsiz, void *param)
1698 {
1699     arr_elts_param_t *arr_param = (arr_elts_param_t *)param;
1700     char *elt;
1701
1702     /* End of array reached? */
1703     if (++arr_param->curr_idx > arr_param->array->nelts)
1704         return APR_EOF;
1705
1706     /* return the line */
1707     elt = ((char **)arr_param->array->elts)[arr_param->curr_idx - 1];
1708     if (apr_cpystrn(buf, elt, bufsiz) - (char *)buf >= bufsiz - 1)
1709         return APR_ENOSPC;
1710     return APR_SUCCESS;
1711 }
1712
1713
1714 /* arr_elts_close(): dummy close routine (makes sure no more lines can be read) */
1715 static apr_status_t arr_elts_close(void *param)
1716 {
1717     arr_elts_param_t *arr_param = (arr_elts_param_t *)param;
1718
1719     arr_param->curr_idx = arr_param->array->nelts;
1720
1721     return APR_SUCCESS;
1722 }
1723
1724 static const char *process_command_config(server_rec *s,
1725                                           apr_array_header_t *arr,
1726                                           ap_directive_t **conftree,
1727                                           apr_pool_t *p,
1728                                           apr_pool_t *ptemp)
1729 {
1730     const char *errmsg;
1731     cmd_parms parms;
1732     arr_elts_param_t arr_parms;
1733
1734     arr_parms.curr_idx = 0;
1735     arr_parms.array = arr;
1736
1737     if (ap_config_hash == NULL) {
1738         rebuild_conf_hash(s->process->pconf, 1);
1739     }
1740
1741     parms = default_parms;
1742     parms.pool = p;
1743     parms.temp_pool = ptemp;
1744     parms.server = s;
1745     parms.override = (RSRC_CONF | OR_ALL) & ~(OR_AUTHCFG | OR_LIMIT);
1746     parms.override_opts = OPT_ALL | OPT_SYM_OWNER | OPT_MULTI;
1747
1748     parms.config_file = ap_pcfg_open_custom(p, "-c/-C directives",
1749                                             &arr_parms, NULL,
1750                                             arr_elts_getstr, arr_elts_close);
1751
1752     errmsg = ap_build_config(&parms, p, ptemp, conftree);
1753     ap_cfg_closefile(parms.config_file);
1754
1755     if (errmsg) {
1756         return apr_pstrcat(p, "Syntax error in -C/-c directive: ", errmsg,
1757                            NULL);
1758     }
1759
1760     return NULL;
1761 }
1762
1763 typedef struct {
1764     const char *fname;
1765 } fnames;
1766
1767 static int fname_alphasort(const void *fn1, const void *fn2)
1768 {
1769     const fnames *f1 = fn1;
1770     const fnames *f2 = fn2;
1771
1772     return strcmp(f1->fname,f2->fname);
1773 }
1774
1775 AP_DECLARE(const char *) ap_process_resource_config(server_rec *s,
1776                                                     const char *fname,
1777                                                     ap_directive_t **conftree,
1778                                                     apr_pool_t *p,
1779                                                     apr_pool_t *ptemp)
1780 {
1781     ap_configfile_t *cfp;
1782     cmd_parms parms;
1783     apr_status_t rv;
1784     const char *error;
1785
1786     parms = default_parms;
1787     parms.pool = p;
1788     parms.temp_pool = ptemp;
1789     parms.server = s;
1790     parms.override = (RSRC_CONF | OR_ALL) & ~(OR_AUTHCFG | OR_LIMIT);
1791     parms.override_opts = OPT_ALL | OPT_SYM_OWNER | OPT_MULTI;
1792
1793     rv = ap_pcfg_openfile(&cfp, p, fname);
1794     if (rv != APR_SUCCESS) {
1795         char errmsg[120];
1796         return apr_psprintf(p, "Could not open configuration file %s: %s",
1797                             fname, apr_strerror(rv, errmsg, sizeof errmsg));
1798     }
1799
1800     parms.config_file = cfp;
1801     error = ap_build_config(&parms, p, ptemp, conftree);
1802     ap_cfg_closefile(cfp);
1803
1804     if (error) {
1805         if (parms.err_directive)
1806             return apr_psprintf(p, "Syntax error on line %d of %s: %s",
1807                                 parms.err_directive->line_num,
1808                                 parms.err_directive->filename, error);
1809         else
1810             return error;
1811     }
1812
1813     return NULL;
1814 }
1815
1816 static const char *process_resource_config_nofnmatch(server_rec *s,
1817                                                      const char *fname,
1818                                                      ap_directive_t **conftree,
1819                                                      apr_pool_t *p,
1820                                                      apr_pool_t *ptemp,
1821                                                      unsigned depth,
1822                                                      int optional)
1823 {
1824     const char *error;
1825     apr_status_t rv;
1826
1827     if (ap_is_directory(ptemp, fname)) {
1828         apr_dir_t *dirp;
1829         apr_finfo_t dirent;
1830         int current;
1831         apr_array_header_t *candidates = NULL;
1832         fnames *fnew;
1833         char *path = apr_pstrdup(ptemp, fname);
1834
1835         if (++depth > AP_MAX_INCLUDE_DIR_DEPTH) {
1836             return apr_psprintf(p, "Directory %s exceeds the maximum include "
1837                                 "directory nesting level of %u. You have "
1838                                 "probably a recursion somewhere.", path,
1839                                 AP_MAX_INCLUDE_DIR_DEPTH);
1840         }
1841
1842         /*
1843          * first course of business is to grok all the directory
1844          * entries here and store 'em away. Recall we need full pathnames
1845          * for this.
1846          */
1847         rv = apr_dir_open(&dirp, path, ptemp);
1848         if (rv != APR_SUCCESS) {
1849             char errmsg[120];
1850             return apr_psprintf(p, "Could not open config directory %s: %s",
1851                                 path, apr_strerror(rv, errmsg, sizeof errmsg));
1852         }
1853
1854         candidates = apr_array_make(ptemp, 1, sizeof(fnames));
1855         while (apr_dir_read(&dirent, APR_FINFO_DIRENT, dirp) == APR_SUCCESS) {
1856             /* strip out '.' and '..' */
1857             if (strcmp(dirent.name, ".")
1858                 && strcmp(dirent.name, "..")) {
1859                 fnew = (fnames *) apr_array_push(candidates);
1860                 fnew->fname = ap_make_full_path(ptemp, path, dirent.name);
1861             }
1862         }
1863
1864         apr_dir_close(dirp);
1865         if (candidates->nelts != 0) {
1866             qsort((void *) candidates->elts, candidates->nelts,
1867                   sizeof(fnames), fname_alphasort);
1868
1869             /*
1870              * Now recurse these... we handle errors and subdirectories
1871              * via the recursion, which is nice
1872              */
1873             for (current = 0; current < candidates->nelts; ++current) {
1874                 fnew = &((fnames *) candidates->elts)[current];
1875                 error = process_resource_config_nofnmatch(s, fnew->fname,
1876                                                           conftree, p, ptemp,
1877                                                           depth, optional);
1878                 if (error) {
1879                     return error;
1880                 }
1881             }
1882         }
1883
1884         return NULL;
1885     }
1886
1887     return ap_process_resource_config(s, fname, conftree, p, ptemp);
1888 }
1889
1890 static const char *process_resource_config_fnmatch(server_rec *s,
1891                                                    const char *path,
1892                                                    const char *fname,
1893                                                    ap_directive_t **conftree,
1894                                                    apr_pool_t *p,
1895                                                    apr_pool_t *ptemp,
1896                                                    unsigned depth,
1897                                                    int optional)
1898 {
1899     const char *rest;
1900     apr_status_t rv;
1901     apr_dir_t *dirp;
1902     apr_finfo_t dirent;
1903     apr_array_header_t *candidates = NULL;
1904     fnames *fnew;
1905     int current;
1906
1907     /* find the first part of the filename */
1908     rest = ap_strchr_c(fname, '/');
1909     if (rest) {
1910         fname = apr_pstrndup(ptemp, fname, rest - fname);
1911         rest++;
1912     }
1913
1914     /* optimisation - if the filename isn't a wildcard, process it directly */
1915     if (!apr_fnmatch_test(fname)) {
1916         path = ap_make_full_path(ptemp, path, fname);
1917         if (!rest) {
1918             return process_resource_config_nofnmatch(s, path,
1919                                                      conftree, p,
1920                                                      ptemp, 0, optional);
1921         }
1922         else {
1923             return process_resource_config_fnmatch(s, path, rest,
1924                                                    conftree, p,
1925                                                    ptemp, 0, optional);
1926         }
1927     }
1928
1929     /*
1930      * first course of business is to grok all the directory
1931      * entries here and store 'em away. Recall we need full pathnames
1932      * for this.
1933      */
1934     rv = apr_dir_open(&dirp, path, ptemp);
1935     if (rv != APR_SUCCESS) {
1936         char errmsg[120];
1937         return apr_psprintf(p, "Could not open config directory %s: %s",
1938                             path, apr_strerror(rv, errmsg, sizeof errmsg));
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 ap_process_resource_config(s, fname, conftree, p, ptemp);
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 AP_CORE_DECLARE(int) ap_parse_htaccess(ap_conf_vector_t **result,
2074                                        request_rec *r, int override,
2075                                        int override_opts, apr_table_t *override_list,
2076                                        const char *d, const char *access_name)
2077 {
2078     ap_configfile_t *f = NULL;
2079     cmd_parms parms;
2080     char *filename = NULL;
2081     const struct htaccess_result *cache;
2082     struct htaccess_result *new;
2083     ap_conf_vector_t *dc = NULL;
2084     apr_status_t status;
2085     int rc;
2086
2087     /* firstly, search cache */
2088     for (cache = r->htaccess; cache != NULL; cache = cache->next) {
2089         if (cache->override == override && strcmp(cache->dir, d) == 0) {
2090             *result = cache->htaccess;
2091             return OK;
2092         }
2093     }
2094
2095     parms = default_parms;
2096     parms.override = override;
2097     parms.override_opts = override_opts;
2098     parms.override_list = override_list;
2099     parms.pool = r->pool;
2100     parms.temp_pool = r->pool;
2101     parms.server = r->server;
2102     parms.path = apr_pstrdup(r->pool, d);
2103
2104     /* loop through the access names and find the first one */
2105     while (access_name[0]) {
2106         /* AFAICT; there is no use of the actual 'filename' against
2107          * any canonicalization, so we will simply take the given
2108          * name, ignoring case sensitivity and aliases
2109          */
2110         filename = ap_make_full_path(r->pool, d,
2111                                      ap_getword_conf(r->pool, &access_name));
2112         rc = ap_run_pre_htaccess(r, filename);
2113         if (rc != DECLINED && rc != OK) {
2114             return rc;
2115         }
2116         status = ap_pcfg_openfile(&f, r->pool, filename);
2117
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 }