]> granicus.if.org Git - apache/blob - server/config.c
Limit length of lines in .htaccess to 8K again, to reduce DoS potential.
[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, APLOGNO(00523)
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, APLOGNO(00524)
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, APLOGNO(00525)
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     apr_size_t max_len = VARBUF_MAX_LEN;
1206     if (p == temp_pool)
1207         max_len = HUGE_STRING_LEN; /* lower limit for .htaccess */
1208
1209     bracket = apr_pstrcat(temp_pool, orig_directive + 1, ">", NULL);
1210     ap_varbuf_init(temp_pool, &vb, VARBUF_INIT_LEN);
1211
1212     while ((rc = ap_varbuf_cfg_getline(&vb, parms->config_file, max_len))
1213            == APR_SUCCESS) {
1214         if (!memcmp(vb.buf, "</", 2)
1215             && (strcasecmp(vb.buf + 2, bracket) == 0)
1216             && (*curr_parent == NULL)) {
1217             break;
1218         }
1219         retval = ap_build_config_sub(p, temp_pool, vb.buf, parms, current,
1220                                      curr_parent, &sub_tree);
1221         if (retval != NULL)
1222             return retval;
1223
1224         if (sub_tree == NULL) {
1225             sub_tree = *curr_parent;
1226         }
1227
1228         if (sub_tree == NULL) {
1229             sub_tree = *current;
1230         }
1231     }
1232     ap_varbuf_free(&vb);
1233     if (rc != APR_EOF && rc != APR_SUCCESS)
1234         return ap_pcfg_strerror(temp_pool, parms->config_file, rc);
1235
1236     *current = sub_tree;
1237     return NULL;
1238 }
1239
1240 static const char *ap_walk_config_sub(const ap_directive_t *current,
1241                                       cmd_parms *parms,
1242                                       ap_conf_vector_t *section_vector)
1243 {
1244     const command_rec *cmd;
1245     ap_mod_list *ml;
1246     char *dir = apr_pstrdup(parms->temp_pool, current->directive);
1247
1248     ap_str_tolower(dir);
1249
1250     ml = apr_hash_get(ap_config_hash, dir, APR_HASH_KEY_STRING);
1251
1252     if (ml == NULL) {
1253         parms->err_directive = current;
1254         return apr_pstrcat(parms->pool, "Invalid command '",
1255                            current->directive,
1256                            "', perhaps misspelled or defined by a module "
1257                            "not included in the server configuration",
1258                            NULL);
1259     }
1260
1261     for ( ; ml != NULL; ml = ml->next) {
1262         void *dir_config = ap_set_config_vectors(parms->server,
1263                                                  section_vector,
1264                                                  parms->path,
1265                                                  ml->m,
1266                                                  parms->pool);
1267         const char *retval;
1268         cmd = ml->cmd;
1269
1270         /* Once was enough? */
1271         if (cmd->req_override & EXEC_ON_READ) {
1272             continue;
1273         }
1274
1275         retval = invoke_cmd(cmd, parms, dir_config, current->args);
1276
1277         if (retval != NULL && strcmp(retval, DECLINE_CMD) != 0) {
1278             /* If the directive in error has already been set, don't
1279              * replace it.  Otherwise, an error inside a container
1280              * will be reported as occuring on the first line of the
1281              * container.
1282              */
1283             if (!parms->err_directive) {
1284                 parms->err_directive = current;
1285             }
1286             return retval;
1287         }
1288     }
1289
1290     return NULL;
1291 }
1292
1293 AP_DECLARE(const char *) ap_walk_config(ap_directive_t *current,
1294                                         cmd_parms *parms,
1295                                         ap_conf_vector_t *section_vector)
1296 {
1297     ap_conf_vector_t *oldconfig = parms->context;
1298
1299     parms->context = section_vector;
1300
1301     /* scan through all directives, executing each one */
1302     for (; current != NULL; current = current->next) {
1303         const char *errmsg;
1304
1305         parms->directive = current;
1306
1307         /* actually parse the command and execute the correct function */
1308         errmsg = ap_walk_config_sub(current, parms, section_vector);
1309         if (errmsg != NULL) {
1310             /* restore the context (just in case) */
1311             parms->context = oldconfig;
1312             return errmsg;
1313         }
1314     }
1315
1316     parms->context = oldconfig;
1317     return NULL;
1318 }
1319
1320 AP_DECLARE(const char *) ap_build_config(cmd_parms *parms,
1321                                          apr_pool_t *p, apr_pool_t *temp_pool,
1322                                          ap_directive_t **conftree)
1323 {
1324     ap_directive_t *current = *conftree;
1325     ap_directive_t *curr_parent = NULL;
1326     const char *errmsg;
1327     ap_directive_t **last_ptr = NULL;
1328     apr_status_t rc;
1329     struct ap_varbuf vb;
1330     apr_size_t max_len = VARBUF_MAX_LEN;
1331     if (p == temp_pool)
1332         max_len = HUGE_STRING_LEN; /* lower limit for .htaccess */
1333
1334     ap_varbuf_init(temp_pool, &vb, VARBUF_INIT_LEN);
1335
1336     if (current != NULL) {
1337         /* If we have to traverse the whole tree again for every included
1338          * config file, the required time grows as O(n^2) with the number of
1339          * files. This can be a significant delay for large configurations.
1340          * Therefore we cache a pointer to the last node.
1341          */
1342         last_ptr = &(current->last);
1343
1344         if(last_ptr && *last_ptr) {
1345             current = *last_ptr;
1346         }
1347
1348         while (current->next) {
1349             current = current->next;
1350         }
1351
1352         if(last_ptr) {
1353             /* update cached pointer to last node */
1354             *last_ptr = current;
1355         }
1356     }
1357
1358     while ((rc = ap_varbuf_cfg_getline(&vb, parms->config_file, max_len))
1359            == APR_SUCCESS) {
1360         errmsg = ap_build_config_sub(p, temp_pool, vb.buf, parms,
1361                                      &current, &curr_parent, conftree);
1362         if (errmsg != NULL)
1363             return errmsg;
1364
1365         if (*conftree == NULL && curr_parent != NULL) {
1366             *conftree = curr_parent;
1367         }
1368
1369         if (*conftree == NULL && current != NULL) {
1370             *conftree = current;
1371         }
1372     }
1373     ap_varbuf_free(&vb);
1374     if (rc != APR_EOF && rc != APR_SUCCESS)
1375         return ap_pcfg_strerror(temp_pool, parms->config_file, rc);
1376
1377     if (curr_parent != NULL) {
1378         errmsg = "";
1379
1380         while (curr_parent != NULL) {
1381             errmsg = apr_psprintf(p, "%s%s%s:%u: %s> was not closed.",
1382                                   errmsg,
1383                                   *errmsg == '\0' ? "" : APR_EOL_STR,
1384                                   curr_parent->filename,
1385                                   curr_parent->line_num,
1386                                   curr_parent->directive);
1387
1388             parms->err_directive = curr_parent;
1389             curr_parent = curr_parent->parent;
1390         }
1391
1392         return errmsg;
1393     }
1394
1395     return NULL;
1396 }
1397
1398 /*
1399  * Generic command functions...
1400  */
1401
1402 AP_DECLARE_NONSTD(const char *) ap_set_string_slot(cmd_parms *cmd,
1403                                                    void *struct_ptr,
1404                                                    const char *arg)
1405 {
1406     int offset = (int)(long)cmd->info;
1407
1408     *(const char **)((char *)struct_ptr + offset) = arg;
1409
1410     return NULL;
1411 }
1412
1413 AP_DECLARE_NONSTD(const char *) ap_set_int_slot(cmd_parms *cmd,
1414                                                 void *struct_ptr,
1415                                                 const char *arg)
1416 {
1417     char *endptr;
1418     char *error_str = NULL;
1419     int offset = (int)(long)cmd->info;
1420
1421     *(int *)((char*)struct_ptr + offset) = strtol(arg, &endptr, 10);
1422
1423     if ((*arg == '\0') || (*endptr != '\0')) {
1424         error_str = apr_psprintf(cmd->pool,
1425                      "Invalid value for directive %s, expected integer",
1426                      cmd->directive->directive);
1427     }
1428
1429     return error_str;
1430 }
1431
1432 AP_DECLARE_NONSTD(const char *) ap_set_string_slot_lower(cmd_parms *cmd,
1433                                                          void *struct_ptr,
1434                                                          const char *arg_)
1435 {
1436     char *arg = apr_pstrdup(cmd->pool,arg_);
1437     int offset = (int)(long)cmd->info;
1438
1439     ap_str_tolower(arg);
1440     *(char **)((char *)struct_ptr + offset) = arg;
1441
1442     return NULL;
1443 }
1444
1445 AP_DECLARE_NONSTD(const char *) ap_set_flag_slot(cmd_parms *cmd,
1446                                                  void *struct_ptr_v, int arg)
1447 {
1448     int offset = (int)(long)cmd->info;
1449     char *struct_ptr = (char *)struct_ptr_v;
1450
1451     *(int *)(struct_ptr + offset) = arg ? 1 : 0;
1452
1453     return NULL;
1454 }
1455
1456 AP_DECLARE_NONSTD(const char *) ap_set_flag_slot_char(cmd_parms *cmd,
1457                                                       void *struct_ptr_v, int arg)
1458 {
1459     int offset = (int)(long)cmd->info;
1460     char *struct_ptr = (char *)struct_ptr_v;
1461
1462     *(struct_ptr + offset) = arg ? 1 : 0;
1463
1464     return NULL;
1465 }
1466
1467
1468 AP_DECLARE_NONSTD(const char *) ap_set_file_slot(cmd_parms *cmd, void *struct_ptr,
1469                                                  const char *arg)
1470 {
1471     /* Prepend server_root to relative arg.
1472      * This allows most args to be independent of server_root,
1473      * so the server can be moved or mirrored with less pain.
1474      */
1475     const char *path;
1476     int offset = (int)(long)cmd->info;
1477
1478     path = ap_server_root_relative(cmd->pool, arg);
1479
1480     if (!path) {
1481         return apr_pstrcat(cmd->pool, "Invalid file path ",
1482                            arg, NULL);
1483     }
1484
1485     *(const char **) ((char*)struct_ptr + offset) = path;
1486
1487     return NULL;
1488 }
1489
1490 AP_DECLARE_NONSTD(const char *) ap_set_deprecated(cmd_parms *cmd,
1491                                                   void *struct_ptr,
1492                                                   const char *arg)
1493 {
1494     return cmd->cmd->errmsg;
1495 }
1496
1497 AP_DECLARE(void) ap_reset_module_loglevels(struct ap_logconf *l, int val)
1498 {
1499     if (l->module_levels)
1500         memset(l->module_levels, val, conf_vector_length);
1501 }
1502
1503 AP_DECLARE(void) ap_set_module_loglevel(apr_pool_t *pool, struct ap_logconf *l,
1504                                         int index, int level)
1505 {
1506     if (!l->module_levels) {
1507         l->module_levels = apr_palloc(pool, conf_vector_length);
1508         if (l->level == APLOG_UNSET) {
1509                 ap_reset_module_loglevels(l, APLOG_UNSET);
1510         }
1511         else {
1512                 ap_reset_module_loglevels(l, APLOG_NO_MODULE);
1513         }
1514     }
1515
1516     l->module_levels[index] = level;
1517 }
1518
1519 /*****************************************************************
1520  *
1521  * Reading whole config files...
1522  */
1523
1524 static cmd_parms default_parms =
1525 {NULL, 0, 0, NULL, -1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
1526
1527 AP_DECLARE(char *) ap_server_root_relative(apr_pool_t *p, const char *file)
1528 {
1529     char *newpath = NULL;
1530     apr_status_t rv;
1531     rv = apr_filepath_merge(&newpath, ap_server_root, file,
1532                             APR_FILEPATH_TRUENAME, p);
1533     if (newpath && (rv == APR_SUCCESS || APR_STATUS_IS_EPATHWILD(rv)
1534                                       || APR_STATUS_IS_ENOENT(rv)
1535                                       || APR_STATUS_IS_ENOTDIR(rv))) {
1536         return newpath;
1537     }
1538     else {
1539         return NULL;
1540     }
1541 }
1542
1543 AP_DECLARE(const char *) ap_soak_end_container(cmd_parms *cmd, char *directive)
1544 {
1545     struct ap_varbuf vb;
1546     const char *args;
1547     char *cmd_name;
1548     apr_status_t rc;
1549     apr_size_t max_len = VARBUF_MAX_LEN;
1550     if (cmd->pool == cmd->temp_pool)
1551         max_len = HUGE_STRING_LEN; /* lower limit for .htaccess */
1552
1553     ap_varbuf_init(cmd->temp_pool, &vb, VARBUF_INIT_LEN);
1554
1555     while((rc = ap_varbuf_cfg_getline(&vb, cmd->config_file, max_len))
1556           == APR_SUCCESS) {
1557 #if RESOLVE_ENV_PER_TOKEN
1558         args = vb.buf;
1559 #else
1560         args = ap_resolve_env(cmd->temp_pool, vb.buf);
1561 #endif
1562
1563         cmd_name = ap_getword_conf(cmd->temp_pool, &args);
1564         if (cmd_name[0] == '<') {
1565             if (cmd_name[1] == '/') {
1566                 cmd_name[strlen(cmd_name) - 1] = '\0';
1567
1568                 if (strcasecmp(cmd_name + 2, directive + 1) != 0) {
1569                     return apr_pstrcat(cmd->pool, "Expected </",
1570                                        directive + 1, "> but saw ",
1571                                        cmd_name, ">", NULL);
1572                 }
1573
1574                 ap_varbuf_free(&vb);
1575                 return NULL; /* found end of container */
1576             }
1577             else {
1578                 const char *msg;
1579
1580                 if (*args == '\0' && cmd_name[strlen(cmd_name) - 1] == '>') {
1581                     cmd_name[strlen(cmd_name) - 1] = '\0';
1582                 }
1583
1584                 if ((msg = ap_soak_end_container(cmd, cmd_name)) != NULL) {
1585                     return msg;
1586                 }
1587             }
1588         }
1589     }
1590     if (rc != APR_EOF && rc != APR_SUCCESS)
1591         return ap_pcfg_strerror(cmd->temp_pool, cmd->config_file, rc);
1592
1593     return apr_pstrcat(cmd->pool, "Expected </",
1594                        directive + 1, "> before end of configuration",
1595                        NULL);
1596 }
1597
1598 static const char *execute_now(char *cmd_line, const char *args,
1599                                cmd_parms *parms,
1600                                apr_pool_t *p, apr_pool_t *ptemp,
1601                                ap_directive_t **sub_tree,
1602                                ap_directive_t *parent)
1603 {
1604     const command_rec *cmd;
1605     ap_mod_list *ml;
1606     char *dir = apr_pstrdup(parms->temp_pool, cmd_line);
1607
1608     ap_str_tolower(dir);
1609
1610     ml = apr_hash_get(ap_config_hash, dir, APR_HASH_KEY_STRING);
1611
1612     if (ml == NULL) {
1613         return apr_pstrcat(parms->pool, "Invalid command '",
1614                            cmd_line,
1615                            "', perhaps misspelled or defined by a module "
1616                            "not included in the server configuration",
1617                            NULL);
1618     }
1619
1620     for ( ; ml != NULL; ml = ml->next) {
1621         const char *retval;
1622         cmd = ml->cmd;
1623
1624         retval = invoke_cmd(cmd, parms, sub_tree, args);
1625
1626         if (retval != NULL) {
1627             return retval;
1628         }
1629     }
1630
1631     return NULL;
1632 }
1633
1634 /* This structure and the following functions are needed for the
1635  * table-based config file reading. They are passed to the
1636  * cfg_open_custom() routine.
1637  */
1638
1639 /* Structure to be passed to cfg_open_custom(): it contains an
1640  * index which is incremented from 0 to nelts on each call to
1641  * cfg_getline() (which in turn calls arr_elts_getstr())
1642  * and an apr_array_header_t pointer for the string array.
1643  */
1644 typedef struct {
1645     apr_array_header_t *array;
1646     int curr_idx;
1647 } arr_elts_param_t;
1648
1649
1650 /* arr_elts_getstr() returns the next line from the string array. */
1651 static apr_status_t arr_elts_getstr(void *buf, size_t bufsiz, void *param)
1652 {
1653     arr_elts_param_t *arr_param = (arr_elts_param_t *)param;
1654     char *elt;
1655
1656     /* End of array reached? */
1657     if (++arr_param->curr_idx > arr_param->array->nelts)
1658         return APR_EOF;
1659
1660     /* return the line */
1661     elt = ((char **)arr_param->array->elts)[arr_param->curr_idx - 1];
1662     if (apr_cpystrn(buf, elt, bufsiz) - (char *)buf >= bufsiz - 1)
1663         return APR_ENOSPC;
1664     return APR_SUCCESS;
1665 }
1666
1667
1668 /* arr_elts_close(): dummy close routine (makes sure no more lines can be read) */
1669 static apr_status_t arr_elts_close(void *param)
1670 {
1671     arr_elts_param_t *arr_param = (arr_elts_param_t *)param;
1672
1673     arr_param->curr_idx = arr_param->array->nelts;
1674
1675     return APR_SUCCESS;
1676 }
1677
1678 static const char *process_command_config(server_rec *s,
1679                                           apr_array_header_t *arr,
1680                                           ap_directive_t **conftree,
1681                                           apr_pool_t *p,
1682                                           apr_pool_t *ptemp)
1683 {
1684     const char *errmsg;
1685     cmd_parms parms;
1686     arr_elts_param_t arr_parms;
1687
1688     arr_parms.curr_idx = 0;
1689     arr_parms.array = arr;
1690
1691     if (ap_config_hash == NULL) {
1692         rebuild_conf_hash(s->process->pconf, 1);
1693     }
1694
1695     parms = default_parms;
1696     parms.pool = p;
1697     parms.temp_pool = ptemp;
1698     parms.server = s;
1699     parms.override = (RSRC_CONF | OR_ALL) & ~(OR_AUTHCFG | OR_LIMIT);
1700     parms.override_opts = OPT_ALL | OPT_SYM_OWNER | OPT_MULTI;
1701
1702     parms.config_file = ap_pcfg_open_custom(p, "-c/-C directives",
1703                                             &arr_parms, NULL,
1704                                             arr_elts_getstr, arr_elts_close);
1705
1706     errmsg = ap_build_config(&parms, p, ptemp, conftree);
1707     ap_cfg_closefile(parms.config_file);
1708
1709     if (errmsg) {
1710         return apr_pstrcat(p, "Syntax error in -C/-c directive: ", errmsg,
1711                            NULL);
1712     }
1713
1714     return NULL;
1715 }
1716
1717 typedef struct {
1718     const char *fname;
1719 } fnames;
1720
1721 static int fname_alphasort(const void *fn1, const void *fn2)
1722 {
1723     const fnames *f1 = fn1;
1724     const fnames *f2 = fn2;
1725
1726     return strcmp(f1->fname,f2->fname);
1727 }
1728
1729 AP_DECLARE(const char *) ap_process_resource_config(server_rec *s,
1730                                                     const char *fname,
1731                                                     ap_directive_t **conftree,
1732                                                     apr_pool_t *p,
1733                                                     apr_pool_t *ptemp)
1734 {
1735     ap_configfile_t *cfp;
1736     cmd_parms parms;
1737     apr_status_t rv;
1738     const char *error;
1739
1740     parms = default_parms;
1741     parms.pool = p;
1742     parms.temp_pool = ptemp;
1743     parms.server = s;
1744     parms.override = (RSRC_CONF | OR_ALL) & ~(OR_AUTHCFG | OR_LIMIT);
1745     parms.override_opts = OPT_ALL | OPT_SYM_OWNER | OPT_MULTI;
1746
1747     rv = ap_pcfg_openfile(&cfp, p, fname);
1748     if (rv != APR_SUCCESS) {
1749         char errmsg[120];
1750         return apr_psprintf(p, "Could not open configuration file %s: %s",
1751                             fname, apr_strerror(rv, errmsg, sizeof errmsg));
1752     }
1753
1754     parms.config_file = cfp;
1755     error = ap_build_config(&parms, p, ptemp, conftree);
1756     ap_cfg_closefile(cfp);
1757
1758     if (error) {
1759         if (parms.err_directive)
1760             return apr_psprintf(p, "Syntax error on line %d of %s: %s",
1761                                 parms.err_directive->line_num,
1762                                 parms.err_directive->filename, error);
1763         else
1764             return error;
1765     }
1766
1767     return NULL;
1768 }
1769
1770 static const char *process_resource_config_nofnmatch(server_rec *s,
1771                                                      const char *fname,
1772                                                      ap_directive_t **conftree,
1773                                                      apr_pool_t *p,
1774                                                      apr_pool_t *ptemp,
1775                                                      unsigned depth,
1776                                                      int optional)
1777 {
1778     const char *error;
1779     apr_status_t rv;
1780
1781     if (ap_is_directory(ptemp, fname)) {
1782         apr_dir_t *dirp;
1783         apr_finfo_t dirent;
1784         int current;
1785         apr_array_header_t *candidates = NULL;
1786         fnames *fnew;
1787         char *path = apr_pstrdup(ptemp, fname);
1788
1789         if (++depth > AP_MAX_INCLUDE_DIR_DEPTH) {
1790             return apr_psprintf(p, "Directory %s exceeds the maximum include "
1791                                 "directory nesting level of %u. You have "
1792                                 "probably a recursion somewhere.", path,
1793                                 AP_MAX_INCLUDE_DIR_DEPTH);
1794         }
1795
1796         /*
1797          * first course of business is to grok all the directory
1798          * entries here and store 'em away. Recall we need full pathnames
1799          * for this.
1800          */
1801         rv = apr_dir_open(&dirp, path, ptemp);
1802         if (rv != APR_SUCCESS) {
1803             char errmsg[120];
1804             return apr_psprintf(p, "Could not open config directory %s: %s",
1805                                 path, apr_strerror(rv, errmsg, sizeof errmsg));
1806         }
1807
1808         candidates = apr_array_make(ptemp, 1, sizeof(fnames));
1809         while (apr_dir_read(&dirent, APR_FINFO_DIRENT, dirp) == APR_SUCCESS) {
1810             /* strip out '.' and '..' */
1811             if (strcmp(dirent.name, ".")
1812                 && strcmp(dirent.name, "..")) {
1813                 fnew = (fnames *) apr_array_push(candidates);
1814                 fnew->fname = ap_make_full_path(ptemp, path, dirent.name);
1815             }
1816         }
1817
1818         apr_dir_close(dirp);
1819         if (candidates->nelts != 0) {
1820             qsort((void *) candidates->elts, candidates->nelts,
1821                   sizeof(fnames), fname_alphasort);
1822
1823             /*
1824              * Now recurse these... we handle errors and subdirectories
1825              * via the recursion, which is nice
1826              */
1827             for (current = 0; current < candidates->nelts; ++current) {
1828                 fnew = &((fnames *) candidates->elts)[current];
1829                 error = process_resource_config_nofnmatch(s, fnew->fname,
1830                                                           conftree, p, ptemp,
1831                                                           depth, optional);
1832                 if (error) {
1833                     return error;
1834                 }
1835             }
1836         }
1837
1838         return NULL;
1839     }
1840
1841     return ap_process_resource_config(s, fname, conftree, p, ptemp);
1842 }
1843
1844 static const char *process_resource_config_fnmatch(server_rec *s,
1845                                                    const char *path,
1846                                                    const char *fname,
1847                                                    ap_directive_t **conftree,
1848                                                    apr_pool_t *p,
1849                                                    apr_pool_t *ptemp,
1850                                                    unsigned depth,
1851                                                    int optional)
1852 {
1853     const char *rest;
1854     apr_status_t rv;
1855     apr_dir_t *dirp;
1856     apr_finfo_t dirent;
1857     apr_array_header_t *candidates = NULL;
1858     fnames *fnew;
1859     int current;
1860
1861     /* find the first part of the filename */
1862     rest = ap_strchr_c(fname, '/');
1863     if (rest) {
1864         fname = apr_pstrndup(ptemp, fname, rest - fname);
1865         rest++;
1866     }
1867
1868     /* optimisation - if the filename isn't a wildcard, process it directly */
1869     if (!apr_fnmatch_test(fname)) {
1870         path = ap_make_full_path(ptemp, path, fname);
1871         if (!rest) {
1872             return process_resource_config_nofnmatch(s, path,
1873                                                      conftree, p,
1874                                                      ptemp, 0, optional);
1875         }
1876         else {
1877             return process_resource_config_fnmatch(s, path, rest,
1878                                                    conftree, p,
1879                                                    ptemp, 0, optional);
1880         }
1881     }
1882
1883     /*
1884      * first course of business is to grok all the directory
1885      * entries here and store 'em away. Recall we need full pathnames
1886      * for this.
1887      */
1888     rv = apr_dir_open(&dirp, path, ptemp);
1889     if (rv != APR_SUCCESS) {
1890         char errmsg[120];
1891         return apr_psprintf(p, "Could not open config directory %s: %s",
1892                             path, apr_strerror(rv, errmsg, sizeof errmsg));
1893     }
1894
1895     candidates = apr_array_make(ptemp, 1, sizeof(fnames));
1896     while (apr_dir_read(&dirent, APR_FINFO_DIRENT | APR_FINFO_TYPE, dirp) == APR_SUCCESS) {
1897         /* strip out '.' and '..' */
1898         if (strcmp(dirent.name, ".")
1899             && strcmp(dirent.name, "..")
1900             && (apr_fnmatch(fname, dirent.name,
1901                             APR_FNM_PERIOD) == APR_SUCCESS)) {
1902             const char *full_path = ap_make_full_path(ptemp, path, dirent.name);
1903             /* If matching internal to path, and we happen to match something
1904              * other than a directory, skip it
1905              */
1906             if (rest && (rv == APR_SUCCESS) && (dirent.filetype != APR_DIR)) {
1907                 continue;
1908             }
1909             fnew = (fnames *) apr_array_push(candidates);
1910             fnew->fname = full_path;
1911         }
1912     }
1913
1914     apr_dir_close(dirp);
1915     if (candidates->nelts != 0) {
1916         const char *error;
1917
1918         qsort((void *) candidates->elts, candidates->nelts,
1919               sizeof(fnames), fname_alphasort);
1920
1921         /*
1922          * Now recurse these... we handle errors and subdirectories
1923          * via the recursion, which is nice
1924          */
1925         for (current = 0; current < candidates->nelts; ++current) {
1926             fnew = &((fnames *) candidates->elts)[current];
1927             if (!rest) {
1928                 error = process_resource_config_nofnmatch(s, fnew->fname,
1929                                                           conftree, p,
1930                                                           ptemp, 0, optional);
1931             }
1932             else {
1933                 error = process_resource_config_fnmatch(s, fnew->fname, rest,
1934                                                         conftree, p,
1935                                                         ptemp, 0, optional);
1936             }
1937             if (error) {
1938                 return error;
1939             }
1940         }
1941     }
1942     else {
1943
1944         if (!optional) {
1945             return apr_psprintf(p, "No matches for the wildcard '%s' in '%s', failing "
1946                                    "(use IncludeOptional if required)", fname, path);
1947         }
1948     }
1949
1950     return NULL;
1951 }
1952
1953 AP_DECLARE(const char *) ap_process_fnmatch_configs(server_rec *s,
1954                                                     const char *fname,
1955                                                     ap_directive_t **conftree,
1956                                                     apr_pool_t *p,
1957                                                     apr_pool_t *ptemp,
1958                                                     int optional)
1959 {
1960     /* XXX: lstat() won't work on the wildcard pattern...
1961      */
1962
1963     /* don't require conf/httpd.conf if we have a -C or -c switch */
1964     if ((ap_server_pre_read_config->nelts
1965         || ap_server_post_read_config->nelts)
1966         && !(strcmp(fname, ap_server_root_relative(ptemp, SERVER_CONFIG_FILE)))) {
1967         apr_finfo_t finfo;
1968
1969         if (apr_stat(&finfo, fname, APR_FINFO_LINK | APR_FINFO_TYPE, ptemp) != APR_SUCCESS)
1970             return NULL;
1971     }
1972
1973     if (!apr_fnmatch_test(fname)) {
1974         return ap_process_resource_config(s, fname, conftree, p, ptemp);
1975     }
1976     else {
1977         apr_status_t status;
1978         const char *rootpath, *filepath = fname;
1979
1980         /* locate the start of the directories proper */
1981         status = apr_filepath_root(&rootpath, &filepath, APR_FILEPATH_TRUENAME, ptemp);
1982
1983         /* we allow APR_SUCCESS and APR_EINCOMPLETE */
1984         if (APR_ERELATIVE == status) {
1985             return apr_pstrcat(p, "Include must have an absolute path, ", fname, NULL);
1986         }
1987         else if (APR_EBADPATH == status) {
1988             return apr_pstrcat(p, "Include has a bad path, ", fname, NULL);
1989         }
1990
1991         /* walk the filepath */
1992         return process_resource_config_fnmatch(s, rootpath, filepath, conftree, p, ptemp,
1993                                                0, optional);
1994     }
1995 }
1996
1997 AP_DECLARE(int) ap_process_config_tree(server_rec *s,
1998                                        ap_directive_t *conftree,
1999                                        apr_pool_t *p,
2000                                        apr_pool_t *ptemp)
2001 {
2002     const char *errmsg;
2003     cmd_parms parms;
2004
2005     parms = default_parms;
2006     parms.pool = p;
2007     parms.temp_pool = ptemp;
2008     parms.server = s;
2009     parms.override = (RSRC_CONF | OR_ALL) & ~(OR_AUTHCFG | OR_LIMIT);
2010     parms.override_opts = OPT_ALL | OPT_SYM_OWNER | OPT_MULTI;
2011     parms.limited = -1;
2012
2013     errmsg = ap_walk_config(conftree, &parms, s->lookup_defaults);
2014     if (errmsg) {
2015         if (parms.err_directive)
2016             ap_log_perror(APLOG_MARK, APLOG_STARTUP, 0, p, APLOGNO(00526)
2017                           "Syntax error on line %d of %s:",
2018                           parms.err_directive->line_num,
2019                           parms.err_directive->filename);
2020         ap_log_perror(APLOG_MARK, APLOG_STARTUP, 0, p, "%s", errmsg);
2021         return HTTP_INTERNAL_SERVER_ERROR;
2022     }
2023
2024     return OK;
2025 }
2026
2027 AP_CORE_DECLARE(int) ap_parse_htaccess(ap_conf_vector_t **result,
2028                                        request_rec *r, int override,
2029                                        int override_opts, apr_table_t *override_list,
2030                                        const char *d, const char *access_name)
2031 {
2032     ap_configfile_t *f = NULL;
2033     cmd_parms parms;
2034     char *filename = NULL;
2035     const struct htaccess_result *cache;
2036     struct htaccess_result *new;
2037     ap_conf_vector_t *dc = NULL;
2038     apr_status_t status;
2039
2040     /* firstly, search cache */
2041     for (cache = r->htaccess; cache != NULL; cache = cache->next) {
2042         if (cache->override == override && strcmp(cache->dir, d) == 0) {
2043             *result = cache->htaccess;
2044             return OK;
2045         }
2046     }
2047
2048     parms = default_parms;
2049     parms.override = override;
2050     parms.override_opts = override_opts;
2051     parms.override_list = override_list;
2052     parms.pool = r->pool;
2053     parms.temp_pool = r->pool;
2054     parms.server = r->server;
2055     parms.path = apr_pstrdup(r->pool, d);
2056
2057     /* loop through the access names and find the first one */
2058     while (access_name[0]) {
2059         /* AFAICT; there is no use of the actual 'filename' against
2060          * any canonicalization, so we will simply take the given
2061          * name, ignoring case sensitivity and aliases
2062          */
2063         filename = ap_make_full_path(r->pool, d,
2064                                      ap_getword_conf(r->pool, &access_name));
2065         status = ap_pcfg_openfile(&f, r->pool, filename);
2066
2067         if (status == APR_SUCCESS) {
2068             const char *errmsg;
2069             ap_directive_t *temptree = NULL;
2070
2071             dc = ap_create_per_dir_config(r->pool);
2072
2073             parms.config_file = f;
2074             errmsg = ap_build_config(&parms, r->pool, r->pool, &temptree);
2075             if (errmsg == NULL)
2076                 errmsg = ap_walk_config(temptree, &parms, dc);
2077
2078             ap_cfg_closefile(f);
2079
2080             if (errmsg) {
2081                 ap_log_rerror(APLOG_MARK, APLOG_ALERT, 0, r,
2082                               "%s: %s", filename, errmsg);
2083                 return HTTP_INTERNAL_SERVER_ERROR;
2084             }
2085
2086             *result = dc;
2087             break;
2088         }
2089         else {
2090             if (!APR_STATUS_IS_ENOENT(status)
2091                 && !APR_STATUS_IS_ENOTDIR(status)) {
2092                 ap_log_rerror(APLOG_MARK, APLOG_CRIT, status, r, APLOGNO(00529)
2093                               "%s pcfg_openfile: unable to check htaccess file, "
2094                               "ensure it is readable and that '%s' "
2095                               "is executable",
2096                               filename, d);
2097                 apr_table_setn(r->notes, "error-notes",
2098                                "Server unable to read htaccess file, denying "
2099                                "access to be safe");
2100                 return HTTP_FORBIDDEN;
2101             }
2102         }
2103     }
2104
2105     /* cache it */
2106     new = apr_palloc(r->pool, sizeof(struct htaccess_result));
2107     new->dir = parms.path;
2108     new->override = override;
2109     new->override_opts = override_opts;
2110     new->htaccess = dc;
2111
2112     /* add to head of list */
2113     new->next = r->htaccess;
2114     r->htaccess = new;
2115
2116     return OK;
2117 }
2118
2119 AP_CORE_DECLARE(const char *) ap_init_virtual_host(apr_pool_t *p,
2120                                                    const char *hostname,
2121                                                    server_rec *main_server,
2122                                                    server_rec **ps)
2123 {
2124     server_rec *s = (server_rec *) apr_pcalloc(p, sizeof(server_rec));
2125
2126     /* TODO: this crap belongs in http_core */
2127     s->process = main_server->process;
2128     s->server_admin = NULL;
2129     s->server_hostname = NULL;
2130     s->server_scheme = NULL;
2131     s->error_fname = NULL;
2132     s->timeout = 0;
2133     s->keep_alive_timeout = 0;
2134     s->keep_alive = -1;
2135     s->keep_alive_max = -1;
2136     s->error_log = main_server->error_log;
2137     s->log.level = APLOG_UNSET;
2138     s->log.module_levels = NULL;
2139     /* useful default, otherwise we get a port of 0 on redirects */
2140     s->port = main_server->port;
2141     s->next = NULL;
2142
2143     s->is_virtual = 1;
2144     s->names = apr_array_make(p, 4, sizeof(char **));
2145     s->wild_names = apr_array_make(p, 4, sizeof(char **));
2146
2147     s->module_config = create_empty_config(p);
2148     s->lookup_defaults = ap_create_per_dir_config(p);
2149
2150     s->limit_req_line = main_server->limit_req_line;
2151     s->limit_req_fieldsize = main_server->limit_req_fieldsize;
2152     s->limit_req_fields = main_server->limit_req_fields;
2153
2154     *ps = s;
2155
2156     return ap_parse_vhost_addrs(p, hostname, s);
2157 }
2158
2159 AP_DECLARE(struct ap_logconf *) ap_new_log_config(apr_pool_t *p,
2160                                                   const struct ap_logconf *old)
2161 {
2162     struct ap_logconf *l = apr_pcalloc(p, sizeof(struct ap_logconf));
2163     if (old) {
2164         l->level = old->level;
2165         if (old->module_levels) {
2166             l->module_levels =
2167                 apr_pmemdup(p, old->module_levels, conf_vector_length);
2168         }
2169     }
2170     else {
2171         l->level = APLOG_UNSET;
2172     }
2173     return l;
2174 }
2175
2176 AP_DECLARE(void) ap_merge_log_config(const struct ap_logconf *old_conf,
2177                                      struct ap_logconf *new_conf)
2178 {
2179     if (new_conf->level != APLOG_UNSET) {
2180         /* Setting the main loglevel resets all per-module log levels.
2181          * I.e. if new->level has been set, we must ignore old->module_levels.
2182          */
2183         return;
2184     }
2185
2186     new_conf->level = old_conf->level;
2187     if (new_conf->module_levels == NULL) {
2188         new_conf->module_levels = old_conf->module_levels;
2189     }
2190     else if (old_conf->module_levels != NULL) {
2191         int i;
2192         for (i = 0; i < conf_vector_length; i++) {
2193             if (new_conf->module_levels[i] == APLOG_UNSET)
2194                 new_conf->module_levels[i] = old_conf->module_levels[i];
2195         }
2196     }
2197 }
2198
2199 AP_DECLARE(void) ap_fixup_virtual_hosts(apr_pool_t *p, server_rec *main_server)
2200 {
2201     server_rec *virt;
2202     core_dir_config *dconf =
2203         ap_get_core_module_config(main_server->lookup_defaults);
2204     dconf->log = &main_server->log;
2205
2206     for (virt = main_server->next; virt; virt = virt->next) {
2207         merge_server_configs(p, main_server->module_config,
2208                              virt->module_config);
2209
2210         virt->lookup_defaults =
2211             ap_merge_per_dir_configs(p, main_server->lookup_defaults,
2212                                      virt->lookup_defaults);
2213
2214         if (virt->server_admin == NULL)
2215             virt->server_admin = main_server->server_admin;
2216
2217         if (virt->timeout == 0)
2218             virt->timeout = main_server->timeout;
2219
2220         if (virt->keep_alive_timeout == 0)
2221             virt->keep_alive_timeout = main_server->keep_alive_timeout;
2222
2223         if (virt->keep_alive == -1)
2224             virt->keep_alive = main_server->keep_alive;
2225
2226         if (virt->keep_alive_max == -1)
2227             virt->keep_alive_max = main_server->keep_alive_max;
2228
2229         ap_merge_log_config(&main_server->log, &virt->log);
2230
2231         dconf = ap_get_core_module_config(virt->lookup_defaults);
2232         dconf->log = &virt->log;
2233
2234         /* XXX: this is really something that should be dealt with by a
2235          * post-config api phase
2236          */
2237         ap_core_reorder_directories(p, virt);
2238     }
2239
2240     ap_core_reorder_directories(p, main_server);
2241 }
2242
2243 /*****************************************************************
2244  *
2245  * Getting *everything* configured...
2246  */
2247
2248 static void init_config_globals(apr_pool_t *p)
2249 {
2250     /* Global virtual host hash bucket pointers.  Init to null. */
2251     ap_init_vhost_config(p);
2252 }
2253
2254 static server_rec *init_server_config(process_rec *process, apr_pool_t *p)
2255 {
2256     apr_status_t rv;
2257     server_rec *s = (server_rec *) apr_pcalloc(p, sizeof(server_rec));
2258
2259     apr_file_open_stderr(&s->error_log, p);
2260     s->process = process;
2261     s->port = 0;
2262     s->server_admin = DEFAULT_ADMIN;
2263     s->server_hostname = NULL;
2264     s->server_scheme = NULL;
2265     s->error_fname = DEFAULT_ERRORLOG;
2266     s->log.level = DEFAULT_LOGLEVEL;
2267     s->log.module_levels = NULL;
2268     s->limit_req_line = DEFAULT_LIMIT_REQUEST_LINE;
2269     s->limit_req_fieldsize = DEFAULT_LIMIT_REQUEST_FIELDSIZE;
2270     s->limit_req_fields = DEFAULT_LIMIT_REQUEST_FIELDS;
2271     s->timeout = apr_time_from_sec(DEFAULT_TIMEOUT);
2272     s->keep_alive_timeout = apr_time_from_sec(DEFAULT_KEEPALIVE_TIMEOUT);
2273     s->keep_alive_max = DEFAULT_KEEPALIVE;
2274     s->keep_alive = 1;
2275     s->next = NULL;
2276     s->addrs = apr_pcalloc(p, sizeof(server_addr_rec));
2277
2278     /* NOT virtual host; don't match any real network interface */
2279     rv = apr_sockaddr_info_get(&s->addrs->host_addr,
2280                                NULL, APR_UNSPEC, 0, 0, p);
2281     if (rv != APR_SUCCESS) {
2282         /* should we test here for rv being an EAIERR? */
2283         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT, rv, NULL, APLOGNO(00530)
2284                      "initialisation: bug or getaddrinfo fail");
2285         return NULL;
2286     }
2287
2288     s->addrs->host_port = 0; /* matches any port */
2289     s->addrs->virthost = ""; /* must be non-NULL */
2290     s->names = s->wild_names = NULL;
2291
2292     s->module_config = create_server_config(p, s);
2293     s->lookup_defaults = create_default_per_dir_config(p);
2294
2295     return s;
2296 }
2297
2298
2299 static apr_status_t reset_conf_vector_length(void *dummy)
2300 {
2301     reserved_module_slots = 0;
2302     conf_vector_length = max_modules;
2303     return APR_SUCCESS;
2304 }
2305
2306 static int conf_vector_length_pre_config(apr_pool_t *pconf, apr_pool_t *plog,
2307                                          apr_pool_t *ptemp)
2308 {
2309     /*
2310      * We have loaded all modules that are loaded by EXEC_ON_READ directives.
2311      * From now on we reduce the size of the config vectors to what we need,
2312      * plus what has been reserved (e.g. by mod_perl) for additional modules
2313      * loaded later on.
2314      * If max_modules is too small, ap_add_module() will abort.
2315      */
2316     if (total_modules + reserved_module_slots < max_modules) {
2317         conf_vector_length = total_modules + reserved_module_slots;
2318     }
2319     apr_pool_cleanup_register(pconf, NULL, reset_conf_vector_length,
2320                               apr_pool_cleanup_null);
2321     return OK;
2322 }
2323
2324
2325 AP_CORE_DECLARE(void) ap_register_config_hooks(apr_pool_t *p)
2326 {
2327     ap_hook_pre_config(conf_vector_length_pre_config, NULL, NULL,
2328                        APR_HOOK_REALLY_LAST);
2329 }
2330
2331 AP_DECLARE(server_rec*) ap_read_config(process_rec *process, apr_pool_t *ptemp,
2332                                        const char *filename,
2333                                        ap_directive_t **conftree)
2334 {
2335     const char *confname, *error;
2336     apr_pool_t *p = process->pconf;
2337     server_rec *s = init_server_config(process, p);
2338     if (s == NULL) {
2339         return s;
2340     }
2341
2342     init_config_globals(p);
2343
2344     /* All server-wide config files now have the SAME syntax... */
2345     error = process_command_config(s, ap_server_pre_read_config, conftree,
2346                                    p, ptemp);
2347     if (error) {
2348         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT, 0, NULL, "%s: %s",
2349                      ap_server_argv0, error);
2350         return NULL;
2351     }
2352
2353     /* process_command_config may change the ServerRoot so
2354      * compute this config file name afterwards.
2355      */
2356     confname = ap_server_root_relative(p, filename);
2357
2358     if (!confname) {
2359         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT,
2360                      APR_EBADPATH, NULL, APLOGNO(00532) "Invalid config file path %s",
2361                      filename);
2362         return NULL;
2363     }
2364
2365     error = ap_process_resource_config(s, confname, conftree, p, ptemp);
2366     if (error) {
2367         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT, 0, NULL,
2368                      "%s: %s", ap_server_argv0, error);
2369         return NULL;
2370     }
2371
2372     error = ap_check_mpm();
2373     if (error) {
2374         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT, 0, NULL, APLOGNO(00534)
2375                      "%s: Configuration error: %s", ap_server_argv0, error);
2376         return NULL;
2377     }
2378
2379     error = process_command_config(s, ap_server_post_read_config, conftree,
2380                                    p, ptemp);
2381
2382     if (error) {
2383         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT, 0, NULL, "%s: %s",
2384                      ap_server_argv0, error);
2385         return NULL;
2386     }
2387
2388     return s;
2389 }
2390
2391 AP_DECLARE(void) ap_single_module_configure(apr_pool_t *p, server_rec *s,
2392                                             module *m)
2393 {
2394     if (m->create_server_config)
2395         ap_set_module_config(s->module_config, m,
2396                              (*m->create_server_config)(p, s));
2397
2398     if (m->create_dir_config)
2399         ap_set_module_config(s->lookup_defaults, m,
2400                              (*m->create_dir_config)(p, NULL));
2401 }
2402
2403 AP_DECLARE(void) ap_run_rewrite_args(process_rec *process)
2404 {
2405     module *m;
2406
2407     for (m = ap_top_module; m; m = m->next) {
2408         if (m->rewrite_args) {
2409             (*m->rewrite_args)(process);
2410         }
2411     }
2412 }
2413
2414 /********************************************************************
2415  * Configuration directives are restricted in terms of where they may
2416  * appear in the main configuration files and/or .htaccess files according
2417  * to the bitmask req_override in the command_rec structure.
2418  * If any of the overrides set in req_override are also allowed in the
2419  * context in which the command is read, then the command is allowed.
2420  * The context is determined as follows:
2421  *
2422  *    inside *.conf --> override = (RSRC_CONF|OR_ALL)&~(OR_AUTHCFG|OR_LIMIT);
2423  *    within <Directory> or <Location> --> override = OR_ALL|ACCESS_CONF;
2424  *    within .htaccess --> override = AllowOverride for current directory;
2425  *
2426  * the result is, well, a rather confusing set of possibilities for when
2427  * a particular directive is allowed to be used.  This procedure prints
2428  * in English where the given (pc) directive can be used.
2429  */
2430 static void show_overrides(const command_rec *pc, module *pm)
2431 {
2432     int n = 0;
2433
2434     printf("\tAllowed in *.conf ");
2435     if ((pc->req_override & (OR_OPTIONS | OR_FILEINFO | OR_INDEXES))
2436         || ((pc->req_override & RSRC_CONF)
2437         && ((pc->req_override & (ACCESS_CONF | OR_AUTHCFG | OR_LIMIT))))) {
2438         printf("anywhere");
2439     }
2440     else if (pc->req_override & RSRC_CONF) {
2441         printf("only outside <Directory>, <Files>, <Location>, or <If>");
2442     }
2443     else {
2444         printf("only inside <Directory>, <Files>, <Location>, or <If>");
2445     }
2446
2447     /* Warn if the directive is allowed inside <Directory> or .htaccess
2448      * but module doesn't support per-dir configuration
2449      */
2450     if ((pc->req_override & (OR_ALL | ACCESS_CONF)) && !pm->create_dir_config)
2451         printf(" [no per-dir config]");
2452
2453     if (pc->req_override & OR_ALL) {
2454         printf(" and in .htaccess\n\twhen AllowOverride");
2455
2456         if ((pc->req_override & OR_ALL) == OR_ALL) {
2457             printf(" isn't None");
2458         }
2459         else {
2460             printf(" includes ");
2461
2462             if (pc->req_override & OR_AUTHCFG) {
2463                 if (n++)
2464                     printf(" or ");
2465
2466                 printf("AuthConfig");
2467             }
2468
2469             if (pc->req_override & OR_LIMIT) {
2470                 if (n++)
2471                     printf(" or ");
2472
2473                 printf("Limit");
2474             }
2475
2476             if (pc->req_override & OR_OPTIONS) {
2477                 if (n++)
2478                     printf(" or ");
2479
2480                 printf("Options");
2481             }
2482
2483             if (pc->req_override & OR_FILEINFO) {
2484                 if (n++)
2485                     printf(" or ");
2486
2487                 printf("FileInfo");
2488             }
2489
2490             if (pc->req_override & OR_INDEXES) {
2491                 if (n++)
2492                     printf(" or ");
2493
2494                 printf("Indexes");
2495             }
2496         }
2497     }
2498
2499     printf("\n");
2500 }
2501
2502 /* Show the preloaded configuration directives, the help string explaining
2503  * the directive arguments, in what module they are handled, and in
2504  * what parts of the configuration they are allowed.  Used for httpd -L.
2505  */
2506 AP_DECLARE(void) ap_show_directives(void)
2507 {
2508     const command_rec *pc;
2509     int n;
2510
2511     for (n = 0; ap_loaded_modules[n]; ++n) {
2512         for (pc = ap_loaded_modules[n]->cmds; pc && pc->name; ++pc) {
2513             printf("%s (%s)\n", pc->name, ap_loaded_modules[n]->name);
2514
2515             if (pc->errmsg)
2516                 printf("\t%s\n", pc->errmsg);
2517
2518             show_overrides(pc, ap_loaded_modules[n]);
2519         }
2520     }
2521 }
2522
2523 /* Show the preloaded module names.  Used for httpd -l. */
2524 AP_DECLARE(void) ap_show_modules(void)
2525 {
2526     int n;
2527
2528     printf("Compiled in modules:\n");
2529     for (n = 0; ap_loaded_modules[n]; ++n)
2530         printf("  %s\n", ap_loaded_modules[n]->name);
2531 }
2532
2533 AP_DECLARE(void *) ap_retained_data_get(const char *key)
2534 {
2535     void *retained;
2536
2537     apr_pool_userdata_get((void *)&retained, key, ap_pglobal);
2538     return retained;
2539 }
2540
2541 AP_DECLARE(void *) ap_retained_data_create(const char *key, apr_size_t size)
2542 {
2543     void *retained;
2544
2545     retained = apr_pcalloc(ap_pglobal, size);
2546     apr_pool_userdata_set((const void *)retained, key, apr_pool_cleanup_null, ap_pglobal);
2547     return retained;
2548 }
2549
2550 static int count_directives_sub(const char *directive, ap_directive_t *current)
2551 {
2552     int count = 0;
2553     while (current != NULL) {
2554         if (current->first_child != NULL)
2555             count += count_directives_sub(directive, current->first_child);
2556         if (strcasecmp(current->directive, directive) == 0)
2557             count++;
2558         current = current->next;
2559     }
2560     return count;
2561 }
2562
2563 AP_DECLARE(void) ap_reserve_module_slots(int count)
2564 {
2565     reserved_module_slots += count;
2566 }
2567
2568 AP_DECLARE(void) ap_reserve_module_slots_directive(const char *directive)
2569 {
2570     ap_reserve_module_slots(count_directives_sub(directive, ap_conftree));
2571 }