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