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