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