bottleneck testcase based on rubbos
[bottlenecks.git] / rubbos / app / httpd-2.0.64 / 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 #define CORE_PRIVATE
43
44 #include "ap_config.h"
45 #include "httpd.h"
46 #include "http_config.h"
47 #include "http_protocol.h"
48 #include "http_core.h"
49 #include "http_log.h"           /* for errors in parse_htaccess */
50 #include "http_request.h"       /* for default_handler (see invoke_handler) */
51 #include "http_main.h"
52 #include "http_vhost.h"
53 #include "util_cfgtree.h"
54 #include "mpm.h"
55
56
57 AP_DECLARE_DATA const char *ap_server_argv0 = NULL;
58
59 AP_DECLARE_DATA const char *ap_server_root = NULL;
60
61 AP_DECLARE_DATA apr_array_header_t *ap_server_pre_read_config = NULL;
62 AP_DECLARE_DATA apr_array_header_t *ap_server_post_read_config = NULL;
63 AP_DECLARE_DATA apr_array_header_t *ap_server_config_defines = NULL;
64
65 AP_DECLARE_DATA ap_directive_t *ap_conftree = NULL;
66
67 APR_HOOK_STRUCT(
68            APR_HOOK_LINK(header_parser)
69            APR_HOOK_LINK(pre_config)
70            APR_HOOK_LINK(post_config)
71            APR_HOOK_LINK(open_logs)
72            APR_HOOK_LINK(child_init)
73            APR_HOOK_LINK(handler)
74            APR_HOOK_LINK(quick_handler)
75            APR_HOOK_LINK(optional_fn_retrieve)
76 )
77
78 AP_IMPLEMENT_HOOK_RUN_ALL(int, header_parser,
79                           (request_rec *r), (r), OK, DECLINED)
80
81 AP_IMPLEMENT_HOOK_RUN_ALL(int, pre_config,
82                           (apr_pool_t *pconf, apr_pool_t *plog,
83                            apr_pool_t *ptemp),
84                           (pconf, plog, ptemp), OK, DECLINED)
85
86 AP_IMPLEMENT_HOOK_RUN_ALL(int, post_config,
87                           (apr_pool_t *pconf, apr_pool_t *plog,
88                            apr_pool_t *ptemp, server_rec *s),
89                           (pconf, plog, ptemp, s), OK, DECLINED)
90
91 /* During the course of debugging I expanded this macro out, so
92  * rather than remove all the useful information there is in the
93  * following lines, I'm going to leave it here in case anyone
94  * else finds it useful.
95  *
96  * Ben has looked at it and thinks it correct :)
97  *
98 AP_DECLARE(int) ap_hook_post_config(ap_HOOK_post_config_t *pf,
99                                     const char * const *aszPre,
100                                     const char * const *aszSucc,
101                                     int nOrder)
102 {
103     ap_LINK_post_config_t *pHook;
104
105     if (!_hooks.link_post_config) {
106         _hooks.link_post_config = apr_array_make(apr_hook_global_pool, 1,
107                                                  sizeof(ap_LINK_post_config_t));
108         apr_hook_sort_register("post_config", &_hooks.link_post_config);
109     }
110
111     pHook = apr_array_push(_hooks.link_post_config);
112     pHook->pFunc = pf;
113     pHook->aszPredecessors = aszPre;
114     pHook->aszSuccessors = aszSucc;
115     pHook->nOrder = nOrder;
116     pHook->szName = apr_hook_debug_current;
117
118     if (apr_hook_debug_enabled)
119         apr_hook_debug_show("post_config", aszPre, aszSucc);
120 }
121
122 AP_DECLARE(apr_array_header_t *) ap_hook_get_post_config(void) {
123     return _hooks.link_post_config;
124 }
125
126 AP_DECLARE(int) ap_run_post_config(apr_pool_t *pconf,
127                                    apr_pool_t *plog,
128                                    apr_pool_t *ptemp,
129                                    server_rec *s)
130 {
131     ap_LINK_post_config_t *pHook;
132     int n;
133
134     if(!_hooks.link_post_config)
135         return;
136
137     pHook = (ap_LINK_post_config_t *)_hooks.link_post_config->elts;
138     for (n = 0; n < _hooks.link_post_config->nelts; ++n)
139         pHook[n].pFunc (pconf, plog, ptemp, s);
140 }
141  */
142
143 AP_IMPLEMENT_HOOK_RUN_ALL(int, open_logs,
144                           (apr_pool_t *pconf, apr_pool_t *plog,
145                            apr_pool_t *ptemp, server_rec *s),
146                           (pconf, plog, ptemp, s), OK, DECLINED)
147
148 AP_IMPLEMENT_HOOK_VOID(child_init,
149                        (apr_pool_t *pchild, server_rec *s),
150                        (pchild, s))
151
152 AP_IMPLEMENT_HOOK_RUN_FIRST(int, handler, (request_rec *r),
153                             (r), DECLINED)
154
155 AP_IMPLEMENT_HOOK_RUN_FIRST(int, quick_handler, (request_rec *r, int lookup),
156                             (r, lookup), DECLINED)
157
158 AP_IMPLEMENT_HOOK_VOID(optional_fn_retrieve, (void), ())
159
160 /****************************************************************
161  *
162  * We begin with the functions which deal with the linked list
163  * of modules which control just about all of the server operation.
164  */
165
166 /* total_modules is the number of modules that have been linked
167  * into the server.
168  */
169 static int total_modules = 0;
170
171 /* dynamic_modules is the number of modules that have been added
172  * after the pre-loaded ones have been set up. It shouldn't be larger
173  * than DYNAMIC_MODULE_LIMIT.
174  */
175 static int dynamic_modules = 0;
176
177 AP_DECLARE_DATA module *ap_top_module = NULL;
178 AP_DECLARE_DATA module **ap_loaded_modules=NULL;
179
180 typedef int (*handler_func)(request_rec *);
181 typedef void *(*dir_maker_func)(apr_pool_t *, char *);
182 typedef void *(*merger_func)(apr_pool_t *, void *, void *);
183
184 /* maximum nesting level for config directories */
185 #ifndef AP_MAX_INCLUDE_DIR_DEPTH
186 #define AP_MAX_INCLUDE_DIR_DEPTH (128)
187 #endif
188
189 /* Dealing with config vectors.  These are associated with per-directory,
190  * per-server, and per-request configuration, and have a void* pointer for
191  * each modules.  The nature of the structure pointed to is private to the
192  * module in question... the core doesn't (and can't) know.  However, there
193  * are defined interfaces which allow it to create instances of its private
194  * per-directory and per-server structures, and to merge the per-directory
195  * structures of a directory and its subdirectory (producing a new one in
196  * which the defaults applying to the base directory have been properly
197  * overridden).
198  */
199
200 static ap_conf_vector_t *create_empty_config(apr_pool_t *p)
201 {
202     void *conf_vector = apr_pcalloc(p, sizeof(void *) *
203                                     (total_modules + DYNAMIC_MODULE_LIMIT));
204     return conf_vector;
205 }
206
207 static ap_conf_vector_t *create_default_per_dir_config(apr_pool_t *p)
208 {
209     void **conf_vector = apr_pcalloc(p, sizeof(void *) *
210                                      (total_modules + DYNAMIC_MODULE_LIMIT));
211     module *modp;
212
213     for (modp = ap_top_module; modp; modp = modp->next) {
214         dir_maker_func df = modp->create_dir_config;
215
216         if (df)
217             conf_vector[modp->module_index] = (*df)(p, NULL);
218     }
219
220     return (ap_conf_vector_t *)conf_vector;
221 }
222
223 AP_CORE_DECLARE(ap_conf_vector_t *) ap_merge_per_dir_configs(apr_pool_t *p,
224                                            ap_conf_vector_t *base,
225                                            ap_conf_vector_t *new_conf)
226 {
227     void **conf_vector = apr_palloc(p, sizeof(void *) * total_modules);
228     void **base_vector = (void **)base;
229     void **new_vector = (void **)new_conf;
230     module *modp;
231
232     for (modp = ap_top_module; modp; modp = modp->next) {
233         int i = modp->module_index;
234
235         if (!new_vector[i]) {
236             conf_vector[i] = base_vector[i];
237         }
238         else {
239             merger_func df = modp->merge_dir_config;
240             if (df && base_vector[i]) {
241                 conf_vector[i] = (*df)(p, base_vector[i], new_vector[i]);
242             }
243             else
244                 conf_vector[i] = new_vector[i];
245         }
246     }
247
248     return (ap_conf_vector_t *)conf_vector;
249 }
250
251 static ap_conf_vector_t *create_server_config(apr_pool_t *p, server_rec *s)
252 {
253     void **conf_vector = apr_pcalloc(p, sizeof(void *) *
254                                      (total_modules + DYNAMIC_MODULE_LIMIT));
255     module *modp;
256
257     for (modp = ap_top_module; modp; modp = modp->next) {
258         if (modp->create_server_config)
259             conf_vector[modp->module_index] = (*modp->create_server_config)(p, s);
260     }
261
262     return (ap_conf_vector_t *)conf_vector;
263 }
264
265 static void merge_server_configs(apr_pool_t *p, ap_conf_vector_t *base,
266                                  ap_conf_vector_t *virt)
267 {
268     /* Can reuse the 'virt' vector for the spine of it, since we don't
269      * have to deal with the moral equivalent of .htaccess files here...
270      */
271
272     void **base_vector = (void **)base;
273     void **virt_vector = (void **)virt;
274     module *modp;
275
276     for (modp = ap_top_module; modp; modp = modp->next) {
277         merger_func df = modp->merge_server_config;
278         int i = modp->module_index;
279
280         if (!virt_vector[i])
281             virt_vector[i] = base_vector[i];
282         else if (df)
283             virt_vector[i] = (*df)(p, base_vector[i], virt_vector[i]);
284     }
285 }
286
287 AP_CORE_DECLARE(ap_conf_vector_t *) ap_create_request_config(apr_pool_t *p)
288 {
289     return create_empty_config(p);
290 }
291
292 AP_CORE_DECLARE(ap_conf_vector_t *) ap_create_conn_config(apr_pool_t *p)
293 {
294     return create_empty_config(p);
295 }
296
297 AP_CORE_DECLARE(ap_conf_vector_t *) ap_create_per_dir_config(apr_pool_t *p)
298 {
299     return create_empty_config(p);
300 }
301
302 static int ap_invoke_filter_init(ap_filter_t *filters)
303 {
304     while (filters) {
305         if (filters->frec->filter_init_func) {
306             int result = filters->frec->filter_init_func(filters);
307             if (result != OK) {
308                 return result;
309             }
310         }
311         filters = filters->next;
312     } 
313     return OK;
314 }
315
316 AP_CORE_DECLARE(int) ap_invoke_handler(request_rec *r)
317 {
318     const char *handler;
319     const char *p;
320     int result;
321     const char *old_handler = r->handler;
322
323     /*
324      * The new insert_filter stage makes the most sense here.  We only use
325      * it when we are going to run the request, so we must insert filters
326      * if any are available.  Since the goal of this phase is to allow all
327      * modules to insert a filter if they want to, this filter returns
328      * void.  I just can't see any way that this filter can reasonably
329      * fail, either your modules inserts something or it doesn't.  rbb
330      */
331     ap_run_insert_filter(r);
332
333     /* Before continuing, allow each filter that is in the two chains to
334      * run their init function to let them do any magic before we could
335      * start generating data.
336      */
337     result = ap_invoke_filter_init(r->input_filters);
338     if (result != OK) {
339         return result;
340     }
341     result = ap_invoke_filter_init(r->output_filters);
342     if (result != OK) {
343         return result;
344     }
345
346     if (!r->handler) {
347         handler = r->content_type ? r->content_type : ap_default_type(r);
348         if ((p=ap_strchr_c(handler, ';')) != NULL) {
349             char *new_handler = (char *)apr_pmemdup(r->pool, handler,
350                                                     p - handler + 1);
351             char *p2 = new_handler + (p - handler);
352             handler = new_handler;
353
354             /* MIME type arguments */
355             while (p2 > handler && p2[-1] == ' ')
356                 --p2; /* strip trailing spaces */
357
358             *p2='\0';
359         }
360
361         r->handler = handler;
362     }
363
364     result = ap_run_handler(r);
365
366     r->handler = old_handler;
367
368     if (result == DECLINED && r->handler && r->filename) {
369         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
370             "handler \"%s\" not found for: %s", r->handler, r->filename);
371     }
372
373     return result == DECLINED ? HTTP_INTERNAL_SERVER_ERROR : result;
374 }
375
376 AP_DECLARE(int) ap_method_is_limited(cmd_parms *cmd, const char *method)
377 {
378     int methnum;
379
380     methnum = ap_method_number_of(method);
381
382     /*
383      * A method number either hardcoded into apache or
384      * added by a module and registered.
385      */
386     if (methnum != M_INVALID) {
387         return (cmd->limited & (AP_METHOD_BIT << methnum)) ? 1 : 0;
388     }
389
390     return 0; /* not found */
391 }
392
393 AP_DECLARE(void) ap_register_hooks(module *m, apr_pool_t *p)
394 {
395     if (m->register_hooks) {
396         if (getenv("SHOW_HOOKS")) {
397             printf("Registering hooks for %s\n", m->name);
398             apr_hook_debug_enabled = 1;
399         }
400
401         apr_hook_debug_current = m->name;
402         m->register_hooks(p);
403     }
404 }
405
406 /* One-time setup for precompiled modules --- NOT to be done on restart */
407
408 AP_DECLARE(void) ap_add_module(module *m, apr_pool_t *p)
409 {
410     /* This could be called from an AddModule httpd.conf command,
411      * after the file has been linked and the module structure within it
412      * teased out...
413      */
414
415     if (m->version != MODULE_MAGIC_NUMBER_MAJOR) {
416         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
417                      "%s: module \"%s\" is not compatible with this "
418                      "version of Apache (found %d, need %d).",
419                      ap_server_argv0, m->name, m->version,
420                      MODULE_MAGIC_NUMBER_MAJOR);
421         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
422                      "Please contact the vendor for the correct version.");
423         exit(1);
424     }
425
426     if (m->next == NULL) {
427         m->next = ap_top_module;
428         ap_top_module = m;
429     }
430
431     if (m->module_index == -1) {
432         m->module_index = total_modules++;
433         dynamic_modules++;
434
435         if (dynamic_modules > DYNAMIC_MODULE_LIMIT) {
436             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
437                          "%s: module \"%s\" could not be loaded, because"
438                          " the dynamic", ap_server_argv0, m->name);
439             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
440                          "module limit was reached. Please increase "
441                          "DYNAMIC_MODULE_LIMIT and recompile.");
442             exit(1);
443         }
444     }
445
446     /* Some C compilers put a complete path into __FILE__, but we want
447      * only the filename (e.g. mod_includes.c). So check for path
448      * components (Unix and DOS), and remove them.
449      */
450
451     if (ap_strrchr_c(m->name, '/'))
452         m->name = 1 + ap_strrchr_c(m->name, '/');
453
454     if (ap_strrchr_c(m->name, '\\'))
455         m->name = 1 + ap_strrchr_c(m->name, '\\');
456
457 #ifdef _OSD_POSIX
458     /* __FILE__ =
459      * "*POSIX(/home/martin/apache/src/modules/standard/mod_info.c)"
460      */
461
462     /* We cannot fix the string in-place, because it's const */
463     if (m->name[strlen(m->name)-1] == ')') {
464         char *tmp = strdup(m->name); /* FIXME: memory leak, albeit a small one */
465         tmp[strlen(tmp)-1] = '\0';
466         m->name = tmp;
467     }
468 #endif /*_OSD_POSIX*/
469
470     /*  FIXME: is this the right place to call this?
471      *  It doesn't appear to be
472      */
473     ap_register_hooks(m, p);
474 }
475
476 /*
477  * remove_module undoes what add_module did. There are some caveats:
478  * when the module is removed, its slot is lost so all the current
479  * per-dir and per-server configurations are invalid. So we should
480  * only ever call this function when you are invalidating almost
481  * all our current data. I.e. when doing a restart.
482  */
483
484 AP_DECLARE(void) ap_remove_module(module *m)
485 {
486     module *modp;
487
488     modp = ap_top_module;
489     if (modp == m) {
490         /* We are the top module, special case */
491         ap_top_module = modp->next;
492         m->next = NULL;
493     }
494     else {
495         /* Not the top module, find use. When found modp will
496          * point to the module _before_ us in the list
497          */
498
499         while (modp && modp->next != m) {
500             modp = modp->next;
501         }
502
503         if (!modp) {
504             /* Uh-oh, this module doesn't exist */
505             ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL,
506                          "Cannot remove module %s: not found in module list",
507                          m->name);
508             return;
509         }
510
511         /* Eliminate us from the module list */
512         modp->next = modp->next->next;
513     }
514
515     m->module_index = -1; /* simulate being unloaded, should
516                            * be unnecessary */
517     dynamic_modules--;
518     total_modules--;
519 }
520
521 AP_DECLARE(void) ap_add_loaded_module(module *mod, apr_pool_t *p)
522 {
523     module **m;
524
525     /*
526      *  Add module pointer to top of chained module list
527      */
528     ap_add_module(mod, p);
529
530     /*
531      *  And module pointer to list of loaded modules
532      *
533      *  Notes: 1. ap_add_module() would already complain if no more space
534      *            exists for adding a dynamically loaded module
535      *         2. ap_add_module() accepts double inclusion, so we have
536      *            to accept this, too.
537      */
538     for (m = ap_loaded_modules; *m != NULL; m++)
539         ;
540     *m++ = mod;
541     *m = NULL;
542 }
543
544 AP_DECLARE(void) ap_remove_loaded_module(module *mod)
545 {
546     module **m;
547     module **m2;
548     int done;
549
550     /*
551      *  Remove module pointer from chained module list
552      */
553     ap_remove_module(mod);
554
555     /*
556      *  Remove module pointer from list of loaded modules
557      *
558      *  Note: 1. We cannot determine if the module was successfully
559      *           removed by ap_remove_module().
560      *        2. We have not to complain explicity when the module
561      *           is not found because ap_remove_module() did it
562      *           for us already.
563      */
564     for (m = m2 = ap_loaded_modules, done = 0; *m2 != NULL; m2++) {
565         if (*m2 == mod && done == 0)
566             done = 1;
567         else
568             *m++ = *m2;
569     }
570
571     *m = NULL;
572 }
573
574 AP_DECLARE(void) ap_setup_prelinked_modules(process_rec *process)
575 {
576     module **m;
577     module **m2;
578
579     apr_hook_global_pool=process->pconf;
580
581     /*
582      *  Initialise total_modules variable and module indices
583      */
584     total_modules = 0;
585     for (m = ap_preloaded_modules; *m != NULL; m++)
586         (*m)->module_index = total_modules++;
587
588     /*
589      *  Initialise list of loaded modules
590      */
591     ap_loaded_modules = (module **)apr_palloc(process->pool,
592         sizeof(module *) * (total_modules + DYNAMIC_MODULE_LIMIT + 1));
593
594     if (ap_loaded_modules == NULL) {
595         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
596                      "Ouch!  Out of memory in ap_setup_prelinked_modules()!");
597     }
598
599     for (m = ap_preloaded_modules, m2 = ap_loaded_modules; *m != NULL; )
600         *m2++ = *m++;
601
602     *m2 = NULL;
603
604     /*
605      *   Initialize chain of linked (=activate) modules
606      */
607     for (m = ap_prelinked_modules; *m != NULL; m++)
608         ap_add_module(*m, process->pconf);
609
610     apr_hook_sort_all();
611 }
612
613 AP_DECLARE(const char *) ap_find_module_name(module *m)
614 {
615     return m->name;
616 }
617
618 AP_DECLARE(module *) ap_find_linked_module(const char *name)
619 {
620     module *modp;
621
622     for (modp = ap_top_module; modp; modp = modp->next) {
623         if (strcmp(modp->name, name) == 0)
624             return modp;
625     }
626
627     return NULL;
628 }
629
630 /* Add a named module.  Returns 1 if module found, 0 otherwise.  */
631 AP_DECLARE(int) ap_add_named_module(const char *name, apr_pool_t *p)
632 {
633     module *modp;
634     int i = 0;
635
636     for (modp = ap_loaded_modules[i]; modp; modp = ap_loaded_modules[++i]) {
637         if (strcmp(modp->name, name) == 0) {
638             /* Only add modules that are not already enabled.  */
639             if (modp->next == NULL) {
640                 ap_add_module(modp, p);
641             }
642
643             return 1;
644         }
645     }
646
647     return 0;
648 }
649
650 /*****************************************************************
651  *
652  * Resource, access, and .htaccess config files now parsed by a common
653  * command loop.
654  *
655  * Let's begin with the basics; parsing the line and
656  * invoking the function...
657  */
658
659 static const char *invoke_cmd(const command_rec *cmd, cmd_parms *parms,
660                               void *mconfig, const char *args)
661 {
662     char *w, *w2, *w3;
663     const char *errmsg = NULL;
664
665     if ((parms->override & cmd->req_override) == 0)
666         return apr_pstrcat(parms->pool, cmd->name, " not allowed here", NULL);
667
668     parms->info = cmd->cmd_data;
669     parms->cmd = cmd;
670
671     switch (cmd->args_how) {
672     case RAW_ARGS:
673 #ifdef RESOLVE_ENV_PER_TOKEN
674         args = ap_resolve_env(parms->pool,args);
675 #endif
676         return cmd->AP_RAW_ARGS(parms, mconfig, args);
677
678     case NO_ARGS:
679         if (*args != 0)
680             return apr_pstrcat(parms->pool, cmd->name, " takes no arguments",
681                                NULL);
682
683         return cmd->AP_NO_ARGS(parms, mconfig);
684
685     case TAKE1:
686         w = ap_getword_conf(parms->pool, &args);
687
688         if (*w == '\0' || *args != 0)
689             return apr_pstrcat(parms->pool, cmd->name, " takes one argument",
690                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
691
692         return cmd->AP_TAKE1(parms, mconfig, w);
693
694     case TAKE2:
695         w = ap_getword_conf(parms->pool, &args);
696         w2 = ap_getword_conf(parms->pool, &args);
697
698         if (*w == '\0' || *w2 == '\0' || *args != 0)
699             return apr_pstrcat(parms->pool, cmd->name, " takes two arguments",
700                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
701
702         return cmd->AP_TAKE2(parms, mconfig, w, w2);
703
704     case TAKE12:
705         w = ap_getword_conf(parms->pool, &args);
706         w2 = ap_getword_conf(parms->pool, &args);
707
708         if (*w == '\0' || *args != 0)
709             return apr_pstrcat(parms->pool, cmd->name, " takes 1-2 arguments",
710                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
711
712         return cmd->AP_TAKE2(parms, mconfig, w, *w2 ? w2 : NULL);
713
714     case TAKE3:
715         w = ap_getword_conf(parms->pool, &args);
716         w2 = ap_getword_conf(parms->pool, &args);
717         w3 = ap_getword_conf(parms->pool, &args);
718
719         if (*w == '\0' || *w2 == '\0' || *w3 == '\0' || *args != 0)
720             return apr_pstrcat(parms->pool, cmd->name, " takes three arguments",
721                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
722
723         return cmd->AP_TAKE3(parms, mconfig, w, w2, w3);
724
725     case TAKE23:
726         w = ap_getword_conf(parms->pool, &args);
727         w2 = ap_getword_conf(parms->pool, &args);
728         w3 = *args ? ap_getword_conf(parms->pool, &args) : NULL;
729
730         if (*w == '\0' || *w2 == '\0' || *args != 0)
731             return apr_pstrcat(parms->pool, cmd->name,
732                                " takes two or three arguments",
733                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
734
735         return cmd->AP_TAKE3(parms, mconfig, w, w2, w3);
736
737     case TAKE123:
738         w = ap_getword_conf(parms->pool, &args);
739         w2 = *args ? ap_getword_conf(parms->pool, &args) : NULL;
740         w3 = *args ? ap_getword_conf(parms->pool, &args) : NULL;
741
742         if (*w == '\0' || *args != 0)
743             return apr_pstrcat(parms->pool, cmd->name,
744                                " takes one, two or three arguments",
745                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
746
747         return cmd->AP_TAKE3(parms, mconfig, w, w2, w3);
748
749     case TAKE13:
750         w = ap_getword_conf(parms->pool, &args);
751         w2 = *args ? ap_getword_conf(parms->pool, &args) : NULL;
752         w3 = *args ? ap_getword_conf(parms->pool, &args) : NULL;
753
754         if (*w == '\0' || (w2 && *w2 && !w3) || *args != 0)
755             return apr_pstrcat(parms->pool, cmd->name,
756                                " takes one or three arguments",
757                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
758
759         return cmd->AP_TAKE3(parms, mconfig, w, w2, w3);
760
761     case ITERATE:
762         while (*(w = ap_getword_conf(parms->pool, &args)) != '\0') {
763
764             errmsg = cmd->AP_TAKE1(parms, mconfig, w);
765
766             if (errmsg && strcmp(errmsg, DECLINE_CMD) != 0)
767                 return errmsg;
768         }
769
770         return errmsg;
771
772     case ITERATE2:
773         w = ap_getword_conf(parms->pool, &args);
774
775         if (*w == '\0' || *args == 0)
776             return apr_pstrcat(parms->pool, cmd->name,
777                                " requires at least two arguments",
778                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
779
780         while (*(w2 = ap_getword_conf(parms->pool, &args)) != '\0') {
781
782             errmsg = cmd->AP_TAKE2(parms, mconfig, w, w2);
783
784             if (errmsg && strcmp(errmsg, DECLINE_CMD) != 0)
785                 return errmsg;
786         }
787
788         return errmsg;
789
790     case FLAG:
791         w = ap_getword_conf(parms->pool, &args);
792
793         if (*w == '\0' || (strcasecmp(w, "on") && strcasecmp(w, "off")))
794             return apr_pstrcat(parms->pool, cmd->name, " must be On or Off",
795                                NULL);
796
797         return cmd->AP_FLAG(parms, mconfig, strcasecmp(w, "off") != 0);
798
799     default:
800         return apr_pstrcat(parms->pool, cmd->name,
801                            " is improperly configured internally (server bug)",
802                            NULL);
803     }
804 }
805
806 AP_CORE_DECLARE(const command_rec *) ap_find_command(const char *name,
807                                                      const command_rec *cmds)
808 {
809     while (cmds->name) {
810         if (!strcasecmp(name, cmds->name))
811             return cmds;
812
813         ++cmds;
814     }
815
816     return NULL;
817 }
818
819 AP_CORE_DECLARE(const command_rec *) ap_find_command_in_modules(
820                                           const char *cmd_name, module **mod)
821 {
822     const command_rec *cmdp;
823     module *modp;
824
825     for (modp = *mod; modp; modp = modp->next) {
826         if (modp->cmds && (cmdp = ap_find_command(cmd_name, modp->cmds))) {
827             *mod = modp;
828             return cmdp;
829         }
830     }
831
832     return NULL;
833 }
834
835 AP_CORE_DECLARE(void *) ap_set_config_vectors(server_rec *server,
836                                               ap_conf_vector_t *section_vector,
837                                               const char *section,
838                                               module *mod, apr_pool_t *pconf)
839 {
840     void *section_config = ap_get_module_config(section_vector, mod);
841     void *server_config = ap_get_module_config(server->module_config, mod);
842
843     if (!section_config && mod->create_dir_config) {
844         /* ### need to fix the create_dir_config functions' prototype... */
845         section_config = (*mod->create_dir_config)(pconf, (char *)section);
846         ap_set_module_config(section_vector, mod, section_config);
847     }
848
849     if (!server_config && mod->create_server_config) {
850         server_config = (*mod->create_server_config)(pconf, server);
851         ap_set_module_config(server->module_config, mod, server_config);
852     }
853
854     return section_config;
855 }
856
857 static const char *execute_now(char *cmd_line, const char *args,
858                                cmd_parms *parms,
859                                apr_pool_t *p, apr_pool_t *ptemp,
860                                ap_directive_t **sub_tree,
861                                ap_directive_t *parent);
862
863 static const char *ap_build_config_sub(apr_pool_t *p, apr_pool_t *temp_pool,
864                                        const char *l, cmd_parms *parms,
865                                        ap_directive_t **current,
866                                        ap_directive_t **curr_parent,
867                                        ap_directive_t **conftree)
868 {
869     const char *retval = NULL;
870     const char *args;
871     char *cmd_name;
872     ap_directive_t *newdir;
873     module *mod = ap_top_module;
874     const command_rec *cmd;
875
876     if (*l == '#' || *l == '\0')
877         return NULL;
878
879 #if RESOLVE_ENV_PER_TOKEN
880     args = l;
881 #else
882     args = ap_resolve_env(temp_pool, l);
883 #endif
884
885     cmd_name = ap_getword_conf(p, &args);
886     if (*cmd_name == '\0') {
887         /* Note: this branch should not occur. An empty line should have
888          * triggered the exit further above.
889          */
890         return NULL;
891     }
892
893     if (cmd_name[1] != '/') {
894         char *lastc = cmd_name + strlen(cmd_name) - 1;
895         if (*lastc == '>') {
896             *lastc = '\0' ;
897         }
898         if (cmd_name[0] == '<' && *args == '\0') {
899             args = ">";
900         }
901     }
902
903     newdir = apr_pcalloc(p, sizeof(ap_directive_t));
904     newdir->filename = parms->config_file->name;
905     newdir->line_num = parms->config_file->line_number;
906     newdir->directive = cmd_name;
907     newdir->args = apr_pstrdup(p, args);
908
909     if ((cmd = ap_find_command_in_modules(cmd_name, &mod)) != NULL) {
910         if (cmd->req_override & EXEC_ON_READ) {
911             ap_directive_t *sub_tree = NULL;
912
913             parms->err_directive = newdir;
914             retval = execute_now(cmd_name, args, parms, p, temp_pool,
915                                  &sub_tree, *curr_parent);
916             if (*current) {
917                 (*current)->next = sub_tree;
918             }
919             else {
920                 *current = sub_tree;
921                 if (*curr_parent) {
922                     (*curr_parent)->first_child = (*current);
923                 }
924                 if (*current) {
925                     (*current)->parent = (*curr_parent);
926                 }
927             }
928             if (*current) {
929                 if (!*conftree) {
930                     /* Before walking *current to the end of the list,
931                      * set the head to *current.
932                      */
933                     *conftree = *current;
934                 }
935                 while ((*current)->next != NULL) {
936                     (*current) = (*current)->next;
937                     (*current)->parent = (*curr_parent);
938                 }
939             }
940             return retval;
941         }
942     }
943
944     if (cmd_name[0] == '<') {
945         if (cmd_name[1] != '/') {
946             (*current) = ap_add_node(curr_parent, *current, newdir, 1);
947         }
948         else if (*curr_parent == NULL) {
949             parms->err_directive = newdir;
950             return apr_pstrcat(p, cmd_name,
951                                " without matching <", cmd_name + 2,
952                                " section", NULL);
953         }
954         else {
955             char *bracket = cmd_name + strlen(cmd_name) - 1;
956
957             if (*bracket != '>') {
958                 parms->err_directive = newdir;
959                 return apr_pstrcat(p, cmd_name,
960                                    "> directive missing closing '>'", NULL);
961             }
962
963             *bracket = '\0';
964
965             if (strcasecmp(cmd_name + 2,
966                            (*curr_parent)->directive + 1) != 0) {
967                 parms->err_directive = newdir;
968                 return apr_pstrcat(p, "Expected </",
969                                    (*curr_parent)->directive + 1, "> but saw ",
970                                    cmd_name, ">", NULL);
971             }
972
973             *bracket = '>';
974
975             /* done with this section; move up a level */
976             *current = *curr_parent;
977             *curr_parent = (*current)->parent;
978         }
979     }
980     else {
981         *current = ap_add_node(curr_parent, *current, newdir, 0);
982     }
983
984     return retval;
985 }
986
987 AP_DECLARE(const char *) ap_build_cont_config(apr_pool_t *p,
988                                               apr_pool_t *temp_pool,
989                                               cmd_parms *parms,
990                                               ap_directive_t **current,
991                                               ap_directive_t **curr_parent,
992                                               char *orig_directive)
993 {
994     char *l;
995     char *bracket;
996     const char *retval;
997     ap_directive_t *sub_tree = NULL;
998
999     /* Since this function can be called recursively, allocate
1000      * the temporary 8k string buffer from the temp_pool rather 
1001      * than the stack to avoid over-running a fixed length stack.
1002      */
1003     l = apr_palloc(temp_pool, MAX_STRING_LEN);
1004
1005     bracket = apr_pstrcat(p, orig_directive + 1, ">", NULL);
1006     while (!(ap_cfg_getline(l, MAX_STRING_LEN, parms->config_file))) {
1007         if (!memcmp(l, "</", 2)
1008             && (strcasecmp(l + 2, bracket) == 0)
1009             && (*curr_parent == NULL)) {
1010             break;
1011         }
1012         retval = ap_build_config_sub(p, temp_pool, l, parms, current,
1013                                      curr_parent, &sub_tree);
1014         if (retval != NULL)
1015             return retval;
1016
1017         if (sub_tree == NULL && curr_parent != NULL) {
1018             sub_tree = *curr_parent;
1019         }
1020
1021         if (sub_tree == NULL && current != NULL) {
1022             sub_tree = *current;
1023         }
1024     }
1025
1026     *current = sub_tree;
1027     return NULL;
1028 }
1029
1030 static const char *ap_walk_config_sub(const ap_directive_t *current,
1031                                       cmd_parms *parms,
1032                                       ap_conf_vector_t *section_vector)
1033 {
1034     module *mod = ap_top_module;
1035
1036     while (1) {
1037         const command_rec *cmd;
1038
1039         if (!(cmd = ap_find_command_in_modules(current->directive, &mod))) {
1040             parms->err_directive = current;
1041             return apr_pstrcat(parms->pool, "Invalid command '",
1042                                current->directive,
1043                                "', perhaps mis-spelled or defined by a module "
1044                                "not included in the server configuration",
1045                                NULL);
1046         }
1047         else {
1048             void *dir_config = ap_set_config_vectors(parms->server,
1049                                                      section_vector,
1050                                                      parms->path,
1051                                                      mod,
1052                                                      parms->pool);
1053             const char *retval;
1054
1055             /* Once was enough? */
1056             if (cmd->req_override & EXEC_ON_READ) {
1057                 return NULL;
1058             }
1059
1060             retval = invoke_cmd(cmd, parms, dir_config, current->args);
1061             if (retval == NULL) {
1062                 return NULL;
1063             }
1064
1065             if (strcmp(retval, DECLINE_CMD) != 0) {
1066                 /* If the directive in error has already been set, don't
1067                  * replace it.  Otherwise, an error inside a container 
1068                  * will be reported as occuring on the first line of the
1069                  * container.
1070                  */
1071                 if (!parms->err_directive) {
1072                     parms->err_directive = current;
1073                 }
1074
1075                 return retval;
1076             }
1077
1078             mod = mod->next; /* Next time around, skip this one */
1079         }
1080     }
1081     /* NOTREACHED */
1082 }
1083
1084 AP_DECLARE(const char *) ap_walk_config(ap_directive_t *current,
1085                                         cmd_parms *parms,
1086                                         ap_conf_vector_t *section_vector)
1087 {
1088     ap_conf_vector_t *oldconfig = parms->context;
1089
1090     parms->context = section_vector;
1091
1092     /* scan through all directives, executing each one */
1093     for (; current != NULL; current = current->next) {
1094         const char *errmsg;
1095
1096         parms->directive = current;
1097
1098         /* actually parse the command and execute the correct function */
1099         errmsg = ap_walk_config_sub(current, parms, section_vector);
1100         if (errmsg != NULL) {
1101             /* restore the context (just in case) */
1102             parms->context = oldconfig;
1103             return errmsg;
1104         }
1105     }
1106
1107     parms->context = oldconfig;
1108     return NULL;
1109 }
1110
1111 AP_DECLARE(const char *) ap_build_config(cmd_parms *parms,
1112                                          apr_pool_t *p, apr_pool_t *temp_pool,
1113                                          ap_directive_t **conftree)
1114 {
1115     ap_directive_t *current = *conftree;
1116     ap_directive_t *curr_parent = NULL;
1117     char *l = apr_palloc (temp_pool, MAX_STRING_LEN);
1118     const char *errmsg;
1119
1120     if (current != NULL) {
1121         while (current->next) {
1122             current = current->next;
1123         }
1124     }
1125
1126     while (!(ap_cfg_getline(l, MAX_STRING_LEN, parms->config_file))) {
1127         errmsg = ap_build_config_sub(p, temp_pool, l, parms,
1128                                      &current, &curr_parent, conftree);
1129         if (errmsg != NULL)
1130             return errmsg;
1131
1132         if (*conftree == NULL && curr_parent != NULL) {
1133             *conftree = curr_parent;
1134         }
1135
1136         if (*conftree == NULL && current != NULL) {
1137             *conftree = current;
1138         }
1139     }
1140
1141     if (curr_parent != NULL) {
1142         errmsg = "";
1143
1144         while (curr_parent != NULL) {
1145             errmsg = apr_psprintf(p, "%s%s%s:%u: %s> was not closed.",
1146                                   errmsg,
1147                                   *errmsg == '\0' ? "" : APR_EOL_STR,
1148                                   curr_parent->filename,
1149                                   curr_parent->line_num,
1150                                   curr_parent->directive);
1151
1152             parms->err_directive = curr_parent;
1153             curr_parent = curr_parent->parent;
1154         }
1155
1156         return errmsg;
1157     }
1158
1159     return NULL;
1160 }
1161
1162 /*
1163  * Generic command functions...
1164  */
1165
1166 AP_DECLARE_NONSTD(const char *) ap_set_string_slot(cmd_parms *cmd,
1167                                                    void *struct_ptr,
1168                                                    const char *arg)
1169 {
1170     int offset = (int)(long)cmd->info;
1171
1172     *(const char **)((char *)struct_ptr + offset) = arg;
1173
1174     return NULL;
1175 }
1176
1177 AP_DECLARE_NONSTD(const char *) ap_set_int_slot(cmd_parms *cmd,
1178                                                 void *struct_ptr,
1179                                                 const char *arg)
1180 {
1181     char *endptr;
1182     char *error_str = NULL;
1183     int offset = (int)(long)cmd->info;
1184
1185     *(int *)((char*)struct_ptr + offset) = strtol(arg, &endptr, 10);
1186
1187     if ((*arg == '\0') || (*endptr != '\0')) {
1188         error_str = apr_psprintf(cmd->pool,
1189                      "Invalid value for directive %s, expected integer",
1190                      cmd->directive->directive);
1191     }
1192
1193     return error_str;
1194 }
1195
1196 AP_DECLARE_NONSTD(const char *) ap_set_string_slot_lower(cmd_parms *cmd,
1197                                                          void *struct_ptr,
1198                                                          const char *arg_)
1199 {
1200     char *arg = apr_pstrdup(cmd->pool,arg_);
1201     int offset = (int)(long)cmd->info;
1202
1203     ap_str_tolower(arg);
1204     *(char **)((char *)struct_ptr + offset) = arg;
1205
1206     return NULL;
1207 }
1208
1209 AP_DECLARE_NONSTD(const char *) ap_set_flag_slot(cmd_parms *cmd,
1210                                                  void *struct_ptr_v, int arg)
1211 {
1212     int offset = (int)(long)cmd->info;
1213     char *struct_ptr = (char *)struct_ptr_v;
1214
1215     *(int *)(struct_ptr + offset) = arg ? 1 : 0;
1216
1217     return NULL;
1218 }
1219
1220 AP_DECLARE_NONSTD(const char *) ap_set_file_slot(cmd_parms *cmd, void *struct_ptr,
1221                                                  const char *arg)
1222 {
1223     /* Prepend server_root to relative arg.
1224      * This allows most args to be independent of server_root,
1225      * so the server can be moved or mirrored with less pain.
1226      */
1227     const char *path;
1228     int offset = (int)(long)cmd->info;
1229
1230     path = ap_server_root_relative(cmd->pool, arg);
1231
1232     if (!path) {
1233         return apr_pstrcat(cmd->pool, "Invalid file path ",
1234                            arg, NULL);
1235     }
1236
1237     *(const char **) ((char*)struct_ptr + offset) = path;
1238
1239     return NULL;
1240 }
1241
1242 AP_DECLARE_NONSTD(const char *) ap_set_deprecated(cmd_parms *cmd,
1243                                                   void *struct_ptr,
1244                                                   const char *arg)
1245 {
1246     return cmd->cmd->errmsg;
1247 }
1248
1249 /*****************************************************************
1250  *
1251  * Reading whole config files...
1252  */
1253
1254 static cmd_parms default_parms =
1255 {NULL, 0, -1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
1256
1257 AP_DECLARE(char *) ap_server_root_relative(apr_pool_t *p, const char *file)
1258 {
1259     char *newpath = NULL;
1260     apr_status_t rv;
1261     rv = apr_filepath_merge(&newpath, ap_server_root, file,
1262                             APR_FILEPATH_TRUENAME, p);
1263     if (newpath && (rv == APR_SUCCESS || APR_STATUS_IS_EPATHWILD(rv) 
1264                                       || APR_STATUS_IS_ENOENT(rv)
1265                                       || APR_STATUS_IS_ENOTDIR(rv))) {
1266         return newpath;
1267     }
1268     else {
1269         return NULL;
1270     }
1271 }
1272
1273 AP_DECLARE(const char *) ap_soak_end_container(cmd_parms *cmd, char *directive)
1274 {
1275     char l[MAX_STRING_LEN];
1276     const char *args;
1277     char *cmd_name;
1278
1279     while(!(ap_cfg_getline(l, MAX_STRING_LEN, cmd->config_file))) {
1280 #if RESOLVE_ENV_PER_TOKEN
1281         args = l;
1282 #else
1283         args = ap_resolve_env(cmd->temp_pool, l);
1284 #endif
1285
1286         cmd_name = ap_getword_conf(cmd->pool, &args);
1287         if (cmd_name[0] == '<') {
1288             if (cmd_name[1] == '/') {
1289                 cmd_name[strlen(cmd_name) - 1] = '\0';
1290
1291                 if (strcasecmp(cmd_name + 2, directive + 1) != 0) {
1292                     return apr_pstrcat(cmd->pool, "Expected </",
1293                                        directive + 1, "> but saw ",
1294                                        cmd_name, ">", NULL);
1295                 }
1296
1297                 return NULL; /* found end of container */
1298             }
1299             else {
1300                 const char *msg;
1301
1302                 if (*args == '\0' && cmd_name[strlen(cmd_name) - 1] == '>') {
1303                     cmd_name[strlen(cmd_name) - 1] = '\0';
1304                 }
1305
1306                 if ((msg = ap_soak_end_container(cmd, cmd_name)) != NULL) {
1307                     return msg;
1308                 }
1309             }
1310         }
1311     }
1312
1313     return apr_pstrcat(cmd->pool, "Expected </",
1314                        directive + 1, "> before end of configuration",
1315                        NULL);
1316 }
1317
1318 static const char *execute_now(char *cmd_line, const char *args,
1319                                cmd_parms *parms,
1320                                apr_pool_t *p, apr_pool_t *ptemp,
1321                                ap_directive_t **sub_tree,
1322                                ap_directive_t *parent)
1323 {
1324     module *mod = ap_top_module;
1325     const command_rec *cmd;
1326
1327     if (!(cmd = ap_find_command_in_modules(cmd_line, &mod))) {
1328         return apr_pstrcat(parms->pool, "Invalid command '",
1329                            cmd_line,
1330                            "', perhaps mis-spelled or defined by a module "
1331                            "not included in the server configuration",
1332                            NULL);
1333     }
1334     else {
1335         return invoke_cmd(cmd, parms, sub_tree, args);
1336     }
1337 }
1338
1339 /* This structure and the following functions are needed for the
1340  * table-based config file reading. They are passed to the
1341  * cfg_open_custom() routine.
1342  */
1343
1344 /* Structure to be passed to cfg_open_custom(): it contains an
1345  * index which is incremented from 0 to nelts on each call to
1346  * cfg_getline() (which in turn calls arr_elts_getstr())
1347  * and an apr_array_header_t pointer for the string array.
1348  */
1349 typedef struct {
1350     apr_array_header_t *array;
1351     int curr_idx;
1352 } arr_elts_param_t;
1353
1354
1355 /* arr_elts_getstr() returns the next line from the string array. */
1356 static void *arr_elts_getstr(void *buf, size_t bufsiz, void *param)
1357 {
1358     arr_elts_param_t *arr_param = (arr_elts_param_t *)param;
1359
1360     /* End of array reached? */
1361     if (++arr_param->curr_idx > arr_param->array->nelts)
1362         return NULL;
1363
1364     /* return the line */
1365     apr_cpystrn(buf,
1366                 ((char **)arr_param->array->elts)[arr_param->curr_idx - 1],
1367                 bufsiz);
1368
1369     return buf;
1370 }
1371
1372
1373 /* arr_elts_close(): dummy close routine (makes sure no more lines can be read) */
1374 static int arr_elts_close(void *param)
1375 {
1376     arr_elts_param_t *arr_param = (arr_elts_param_t *)param;
1377
1378     arr_param->curr_idx = arr_param->array->nelts;
1379
1380     return 0;
1381 }
1382
1383 static void process_command_config(server_rec *s, apr_array_header_t *arr,
1384                                    ap_directive_t **conftree, apr_pool_t *p,
1385                                    apr_pool_t *ptemp)
1386 {
1387     const char *errmsg;
1388     cmd_parms parms;
1389     arr_elts_param_t arr_parms;
1390
1391     arr_parms.curr_idx = 0;
1392     arr_parms.array = arr;
1393
1394     parms = default_parms;
1395     parms.pool = p;
1396     parms.temp_pool = ptemp;
1397     parms.server = s;
1398     parms.override = (RSRC_CONF | OR_ALL) & ~(OR_AUTHCFG | OR_LIMIT);
1399
1400     parms.config_file = ap_pcfg_open_custom(p, "-c/-C directives",
1401                                             &arr_parms, NULL,
1402                                             arr_elts_getstr, arr_elts_close);
1403
1404     errmsg = ap_build_config(&parms, p, ptemp, conftree);
1405     if (errmsg) {
1406         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1407                      "Syntax error in -C/-c directive:");
1408         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1409                      "%s", errmsg);
1410         exit(1);
1411     }
1412
1413     ap_cfg_closefile(parms.config_file);
1414 }
1415
1416 typedef struct {
1417     char *fname;
1418 } fnames;
1419
1420 static int fname_alphasort(const void *fn1, const void *fn2)
1421 {
1422     const fnames *f1 = fn1;
1423     const fnames *f2 = fn2;
1424
1425     return strcmp(f1->fname,f2->fname);
1426 }
1427
1428 static void process_resource_config_nofnmatch(server_rec *s, const char *fname,
1429                                               ap_directive_t **conftree,
1430                                               apr_pool_t *p,
1431                                               apr_pool_t *ptemp,
1432                                               unsigned depth)
1433 {
1434     cmd_parms parms;
1435     ap_configfile_t *cfp;
1436     const char *errmsg;
1437
1438     if (ap_is_directory(p, fname)) {
1439         apr_dir_t *dirp;
1440         apr_finfo_t dirent;
1441         int current;
1442         apr_array_header_t *candidates = NULL;
1443         fnames *fnew;
1444         apr_status_t rv;
1445         char errmsg[120], *path = apr_pstrdup(p, fname);
1446
1447         if (++depth > AP_MAX_INCLUDE_DIR_DEPTH) {
1448             fprintf(stderr, "%s: Directory %s exceeds the maximum include "
1449                     "directory nesting level of %u. You have probably a "
1450                     "recursion somewhere.\n", ap_server_argv0, path,
1451                     AP_MAX_INCLUDE_DIR_DEPTH);
1452             exit(1);
1453         }
1454
1455         /*
1456          * first course of business is to grok all the directory
1457          * entries here and store 'em away. Recall we need full pathnames
1458          * for this.
1459          */
1460         rv = apr_dir_open(&dirp, path, p);
1461         if (rv != APR_SUCCESS) {
1462             fprintf(stderr, "%s: could not open config directory %s: %s\n",
1463                     ap_server_argv0, path,
1464                     apr_strerror(rv, errmsg, sizeof errmsg));
1465             exit(1);
1466         }
1467
1468         candidates = apr_array_make(p, 1, sizeof(fnames));
1469         while (apr_dir_read(&dirent, APR_FINFO_DIRENT, dirp) == APR_SUCCESS) {
1470             /* strip out '.' and '..' */
1471             if (strcmp(dirent.name, ".")
1472                 && strcmp(dirent.name, "..")) {
1473                 fnew = (fnames *) apr_array_push(candidates);
1474                 fnew->fname = ap_make_full_path(p, path, dirent.name);
1475             }
1476         }
1477
1478         apr_dir_close(dirp);
1479         if (candidates->nelts != 0) {
1480             qsort((void *) candidates->elts, candidates->nelts,
1481                   sizeof(fnames), fname_alphasort);
1482
1483             /*
1484              * Now recurse these... we handle errors and subdirectories
1485              * via the recursion, which is nice
1486              */
1487             for (current = 0; current < candidates->nelts; ++current) {
1488                 fnew = &((fnames *) candidates->elts)[current];
1489                 process_resource_config_nofnmatch(s, fnew->fname, conftree, p,
1490                                                   ptemp, depth);
1491             }
1492         }
1493
1494         return;
1495     }
1496
1497     /* GCC's initialization extensions are soooo nice here... */
1498     parms = default_parms;
1499     parms.pool = p;
1500     parms.temp_pool = ptemp;
1501     parms.server = s;
1502     parms.override = (RSRC_CONF | OR_ALL) & ~(OR_AUTHCFG | OR_LIMIT);
1503
1504     if (ap_pcfg_openfile(&cfp, p, fname) != APR_SUCCESS) {
1505         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1506                      "%s: could not open document config file %s",
1507                      ap_server_argv0, fname);
1508         exit(1);
1509     }
1510
1511     parms.config_file = cfp;
1512
1513     errmsg = ap_build_config(&parms, p, ptemp, conftree);
1514
1515     if (errmsg != NULL) {
1516         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1517                      "Syntax error on line %d of %s:",
1518                      parms.err_directive->line_num,
1519                      parms.err_directive->filename);
1520         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1521                      "%s", errmsg);
1522         exit(1);
1523     }
1524
1525     ap_cfg_closefile(cfp);
1526
1527     return;
1528 }
1529
1530 AP_DECLARE(void) ap_process_resource_config(server_rec *s, const char *fname,
1531                                             ap_directive_t **conftree,
1532                                             apr_pool_t *p,
1533                                             apr_pool_t *ptemp)
1534 {
1535     /* XXX: lstat() won't work on the wildcard pattern...
1536      */
1537
1538     /* don't require conf/httpd.conf if we have a -C or -c switch */
1539     if ((ap_server_pre_read_config->nelts
1540         || ap_server_post_read_config->nelts)
1541         && !(strcmp(fname, ap_server_root_relative(p, SERVER_CONFIG_FILE)))) {
1542         apr_finfo_t finfo;
1543
1544         if (apr_lstat(&finfo, fname, APR_FINFO_TYPE, p) != APR_SUCCESS)
1545             return;
1546     }
1547
1548     if (!apr_fnmatch_test(fname)) {
1549         process_resource_config_nofnmatch(s, fname, conftree, p, ptemp, 0);
1550     }
1551     else {
1552         apr_dir_t *dirp;
1553         apr_finfo_t dirent;
1554         int current;
1555         apr_array_header_t *candidates = NULL;
1556         fnames *fnew;
1557         apr_status_t rv;
1558         char errmsg[120], *path = apr_pstrdup(p, fname), *pattern = NULL;
1559
1560         pattern = ap_strrchr(path, '/');
1561
1562         AP_DEBUG_ASSERT(pattern != NULL); /* path must be absolute. */
1563
1564         *pattern++ = '\0';
1565
1566         if (apr_fnmatch_test(path)) {
1567             fprintf(stderr, "%s: wildcard patterns not allowed in Include "
1568                     "%s\n", ap_server_argv0, fname);
1569             exit(1);
1570         }
1571
1572         if (!ap_is_directory(p, path)){ 
1573             fprintf(stderr, "%s: Include directory '%s' not found",
1574                     ap_server_argv0, path);
1575             exit(1);
1576         }
1577
1578         if (!apr_fnmatch_test(pattern)) {
1579             fprintf(stderr, "%s: must include a wildcard pattern "
1580                     "for Include %s\n", ap_server_argv0, fname);
1581             exit(1);
1582         }
1583
1584         /*
1585          * first course of business is to grok all the directory
1586          * entries here and store 'em away. Recall we need full pathnames
1587          * for this.
1588          */
1589         rv = apr_dir_open(&dirp, path, p);
1590         if (rv != APR_SUCCESS) {
1591             fprintf(stderr, "%s: could not open config directory %s: %s\n",
1592                     ap_server_argv0, path,
1593                     apr_strerror(rv, errmsg, sizeof errmsg));
1594             exit(1);
1595         }
1596
1597         candidates = apr_array_make(p, 1, sizeof(fnames));
1598         while (apr_dir_read(&dirent, APR_FINFO_DIRENT, dirp) == APR_SUCCESS) {
1599             /* strip out '.' and '..' */
1600             if (strcmp(dirent.name, ".")
1601                 && strcmp(dirent.name, "..")
1602                 && (apr_fnmatch(pattern, dirent.name,
1603                                 FNM_PERIOD) == APR_SUCCESS)) {
1604                 fnew = (fnames *) apr_array_push(candidates);
1605                 fnew->fname = ap_make_full_path(p, path, dirent.name);
1606             }
1607         }
1608
1609         apr_dir_close(dirp);
1610         if (candidates->nelts != 0) {
1611             qsort((void *) candidates->elts, candidates->nelts,
1612                   sizeof(fnames), fname_alphasort);
1613
1614             /*
1615              * Now recurse these... we handle errors and subdirectories
1616              * via the recursion, which is nice
1617              */
1618             for (current = 0; current < candidates->nelts; ++current) {
1619                 fnew = &((fnames *) candidates->elts)[current];
1620                 process_resource_config_nofnmatch(s, fnew->fname, conftree, p,
1621                                                   ptemp, 0);
1622             }
1623         }
1624     }
1625
1626     return;
1627 }
1628
1629 AP_DECLARE(void) ap_process_config_tree(server_rec *s,
1630                                         ap_directive_t *conftree,
1631                                         apr_pool_t *p, apr_pool_t *ptemp)
1632 {
1633     const char *errmsg;
1634     cmd_parms parms;
1635
1636     parms = default_parms;
1637     parms.pool = p;
1638     parms.temp_pool = ptemp;
1639     parms.server = s;
1640     parms.override = (RSRC_CONF | OR_ALL) & ~(OR_AUTHCFG | OR_LIMIT);
1641     parms.limited = -1;
1642
1643     errmsg = ap_walk_config(conftree, &parms, s->lookup_defaults);
1644     if (errmsg) {
1645         ap_log_perror(APLOG_MARK, APLOG_STARTUP, 0, p,
1646                      "Syntax error on line %d of %s:",
1647                      parms.err_directive->line_num,
1648                      parms.err_directive->filename);
1649         ap_log_perror(APLOG_MARK, APLOG_STARTUP, 0, p,
1650                      "%s", errmsg);
1651         exit(1);
1652     }
1653 }
1654
1655 AP_CORE_DECLARE(int) ap_parse_htaccess(ap_conf_vector_t **result,
1656                                        request_rec *r, int override,
1657                                        const char *d, const char *access_name)
1658 {
1659     ap_configfile_t *f = NULL;
1660     cmd_parms parms;
1661     char *filename = NULL;
1662     const struct htaccess_result *cache;
1663     struct htaccess_result *new;
1664     ap_conf_vector_t *dc = NULL;
1665     apr_status_t status;
1666
1667     /* firstly, search cache */
1668     for (cache = r->htaccess; cache != NULL; cache = cache->next) {
1669         if (cache->override == override && strcmp(cache->dir, d) == 0) {
1670             *result = cache->htaccess;
1671             return OK;
1672         }
1673     }
1674
1675     parms = default_parms;
1676     parms.override = override;
1677     parms.pool = r->pool;
1678     parms.temp_pool = r->pool;
1679     parms.server = r->server;
1680     parms.path = apr_pstrdup(r->pool, d);
1681
1682     /* loop through the access names and find the first one */
1683     while (access_name[0]) {
1684         /* AFAICT; there is no use of the actual 'filename' against
1685          * any canonicalization, so we will simply take the given
1686          * name, ignoring case sensitivity and aliases
1687          */
1688         filename = ap_make_full_path(r->pool, d,
1689                                      ap_getword_conf(r->pool, &access_name));
1690         status = ap_pcfg_openfile(&f, r->pool, filename);
1691
1692         if (status == APR_SUCCESS) {
1693             const char *errmsg;
1694             ap_directive_t *temptree = NULL;
1695
1696             dc = ap_create_per_dir_config(r->pool);
1697
1698             parms.config_file = f;
1699             errmsg = ap_build_config(&parms, r->pool, r->pool, &temptree);
1700             if (errmsg == NULL)
1701                 errmsg = ap_walk_config(temptree, &parms, dc);
1702
1703             ap_cfg_closefile(f);
1704
1705             if (errmsg) {
1706                 ap_log_rerror(APLOG_MARK, APLOG_ALERT, 0, r,
1707                               "%s: %s", filename, errmsg);
1708                 return HTTP_INTERNAL_SERVER_ERROR;
1709             }
1710
1711             *result = dc;
1712             break;
1713         }
1714         else {
1715             if (!APR_STATUS_IS_ENOENT(status)
1716                 && !APR_STATUS_IS_ENOTDIR(status)) {
1717                 ap_log_rerror(APLOG_MARK, APLOG_CRIT, status, r,
1718                               "%s pcfg_openfile: unable to check htaccess file, "
1719                               "ensure it is readable",
1720                               filename);
1721                 apr_table_setn(r->notes, "error-notes",
1722                                "Server unable to read htaccess file, denying "
1723                                "access to be safe");
1724                 return HTTP_FORBIDDEN;
1725             }
1726         }
1727     }
1728
1729     /* cache it */
1730     new = apr_palloc(r->pool, sizeof(struct htaccess_result));
1731     new->dir = parms.path;
1732     new->override = override;
1733     new->htaccess = dc;
1734
1735     /* add to head of list */
1736     new->next = r->htaccess;
1737     r->htaccess = new;
1738
1739     return OK;
1740 }
1741
1742 AP_CORE_DECLARE(const char *) ap_init_virtual_host(apr_pool_t *p,
1743                                                    const char *hostname,
1744                                                    server_rec *main_server,
1745                                                    server_rec **ps)
1746 {
1747     server_rec *s = (server_rec *) apr_pcalloc(p, sizeof(server_rec));
1748
1749     /* TODO: this crap belongs in http_core */
1750     s->process = main_server->process;
1751     s->server_admin = NULL;
1752     s->server_hostname = NULL;
1753     s->error_fname = NULL;
1754     s->timeout = 0;
1755     s->keep_alive_timeout = 0;
1756     s->keep_alive = -1;
1757     s->keep_alive_max = -1;
1758     s->error_log = main_server->error_log;
1759     s->loglevel = main_server->loglevel;
1760     /* useful default, otherwise we get a port of 0 on redirects */
1761     s->port = main_server->port;
1762     s->next = NULL;
1763
1764     s->is_virtual = 1;
1765     s->names = apr_array_make(p, 4, sizeof(char **));
1766     s->wild_names = apr_array_make(p, 4, sizeof(char **));
1767
1768     s->module_config = create_empty_config(p);
1769     s->lookup_defaults = ap_create_per_dir_config(p);
1770
1771     s->limit_req_line = main_server->limit_req_line;
1772     s->limit_req_fieldsize = main_server->limit_req_fieldsize;
1773     s->limit_req_fields = main_server->limit_req_fields;
1774
1775     *ps = s;
1776
1777     return ap_parse_vhost_addrs(p, hostname, s);
1778 }
1779
1780
1781 AP_DECLARE(void) ap_fixup_virtual_hosts(apr_pool_t *p, server_rec *main_server)
1782 {
1783     server_rec *virt;
1784
1785     for (virt = main_server->next; virt; virt = virt->next) {
1786         merge_server_configs(p, main_server->module_config,
1787                              virt->module_config);
1788
1789         virt->lookup_defaults =
1790             ap_merge_per_dir_configs(p, main_server->lookup_defaults,
1791                                      virt->lookup_defaults);
1792
1793         if (virt->server_admin == NULL)
1794             virt->server_admin = main_server->server_admin;
1795
1796         if (virt->timeout == 0)
1797             virt->timeout = main_server->timeout;
1798
1799         if (virt->keep_alive_timeout == 0)
1800             virt->keep_alive_timeout = main_server->keep_alive_timeout;
1801
1802         if (virt->keep_alive == -1)
1803             virt->keep_alive = main_server->keep_alive;
1804
1805         if (virt->keep_alive_max == -1)
1806             virt->keep_alive_max = main_server->keep_alive_max;
1807
1808         /* XXX: this is really something that should be dealt with by a
1809          * post-config api phase
1810          */
1811         ap_core_reorder_directories(p, virt);
1812     }
1813
1814     ap_core_reorder_directories(p, main_server);
1815 }
1816
1817 /*****************************************************************
1818  *
1819  * Getting *everything* configured...
1820  */
1821
1822 static void init_config_globals(apr_pool_t *p)
1823 {
1824     /* Global virtual host hash bucket pointers.  Init to null. */
1825     ap_init_vhost_config(p);
1826 }
1827
1828 static server_rec *init_server_config(process_rec *process, apr_pool_t *p)
1829 {
1830     apr_status_t rv;
1831     server_rec *s = (server_rec *) apr_pcalloc(p, sizeof(server_rec));
1832
1833     apr_file_open_stderr(&s->error_log, p);
1834     s->process = process;
1835     s->port = 0;
1836     s->server_admin = DEFAULT_ADMIN;
1837     s->server_hostname = NULL;
1838     s->error_fname = DEFAULT_ERRORLOG;
1839     s->loglevel = DEFAULT_LOGLEVEL;
1840     s->limit_req_line = DEFAULT_LIMIT_REQUEST_LINE;
1841     s->limit_req_fieldsize = DEFAULT_LIMIT_REQUEST_FIELDSIZE;
1842     s->limit_req_fields = DEFAULT_LIMIT_REQUEST_FIELDS;
1843     s->timeout = apr_time_from_sec(DEFAULT_TIMEOUT);
1844     s->keep_alive_timeout = apr_time_from_sec(DEFAULT_KEEPALIVE_TIMEOUT);
1845     s->keep_alive_max = DEFAULT_KEEPALIVE;
1846     s->keep_alive = 1;
1847     s->next = NULL;
1848     s->addrs = apr_pcalloc(p, sizeof(server_addr_rec));
1849
1850     /* NOT virtual host; don't match any real network interface */
1851     rv = apr_sockaddr_info_get(&s->addrs->host_addr,
1852                                NULL, APR_INET, 0, 0, p);
1853     ap_assert(rv == APR_SUCCESS); /* otherwise: bug or no storage */
1854
1855     s->addrs->host_port = 0; /* matches any port */
1856     s->addrs->virthost = ""; /* must be non-NULL */
1857     s->names = s->wild_names = NULL;
1858
1859     s->module_config = create_server_config(p, s);
1860     s->lookup_defaults = create_default_per_dir_config(p);
1861
1862     return s;
1863 }
1864
1865
1866 AP_DECLARE(server_rec*) ap_read_config(process_rec *process, apr_pool_t *ptemp,
1867                                        const char *filename,
1868                                        ap_directive_t **conftree)
1869 {
1870     const char *confname;
1871     apr_pool_t *p = process->pconf;
1872     server_rec *s = init_server_config(process, p);
1873
1874     init_config_globals(p);
1875
1876     /* All server-wide config files now have the SAME syntax... */
1877     process_command_config(s, ap_server_pre_read_config, conftree,
1878                            p, ptemp);
1879
1880     /* process_command_config may change the ServerRoot so
1881      * compute this config file name afterwards.
1882      */
1883     confname = ap_server_root_relative(p, filename);
1884
1885     if (!confname) {
1886         ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_CRIT,
1887                      APR_EBADPATH, NULL, "Invalid config file path %s",
1888                      filename);
1889         exit(1);
1890     }
1891
1892     ap_process_resource_config(s, confname, conftree, p, ptemp);
1893
1894     process_command_config(s, ap_server_post_read_config, conftree,
1895                            p, ptemp);
1896
1897     return s;
1898 }
1899
1900 AP_DECLARE(void) ap_single_module_configure(apr_pool_t *p, server_rec *s,
1901                                             module *m)
1902 {
1903     if (m->create_server_config)
1904         ap_set_module_config(s->module_config, m,
1905                              (*m->create_server_config)(p, s));
1906
1907     if (m->create_dir_config)
1908         ap_set_module_config(s->lookup_defaults, m,
1909                              (*m->create_dir_config)(p, NULL));
1910 }
1911
1912 AP_DECLARE(void) ap_run_rewrite_args(process_rec *process)
1913 {
1914     module *m;
1915
1916     for (m = ap_top_module; m; m = m->next) {
1917         if (m->rewrite_args) {
1918             (*m->rewrite_args)(process);
1919         }
1920     }
1921 }
1922
1923 /********************************************************************
1924  * Configuration directives are restricted in terms of where they may
1925  * appear in the main configuration files and/or .htaccess files according
1926  * to the bitmask req_override in the command_rec structure.
1927  * If any of the overrides set in req_override are also allowed in the
1928  * context in which the command is read, then the command is allowed.
1929  * The context is determined as follows:
1930  *
1931  *    inside *.conf --> override = (RSRC_CONF|OR_ALL)&~(OR_AUTHCFG|OR_LIMIT);
1932  *    within <Directory> or <Location> --> override = OR_ALL|ACCESS_CONF;
1933  *    within .htaccess --> override = AllowOverride for current directory;
1934  *
1935  * the result is, well, a rather confusing set of possibilities for when
1936  * a particular directive is allowed to be used.  This procedure prints
1937  * in English where the given (pc) directive can be used.
1938  */
1939 static void show_overrides(const command_rec *pc, module *pm)
1940 {
1941     int n = 0;
1942
1943     printf("\tAllowed in *.conf ");
1944     if ((pc->req_override & (OR_OPTIONS | OR_FILEINFO | OR_INDEXES))
1945         || ((pc->req_override & RSRC_CONF)
1946         && ((pc->req_override & (ACCESS_CONF | OR_AUTHCFG | OR_LIMIT))))) {
1947         printf("anywhere");
1948     }
1949     else if (pc->req_override & RSRC_CONF) {
1950         printf("only outside <Directory>, <Files> or <Location>");
1951     }
1952     else {
1953         printf("only inside <Directory>, <Files> or <Location>");
1954     }
1955
1956     /* Warn if the directive is allowed inside <Directory> or .htaccess
1957      * but module doesn't support per-dir configuration
1958      */
1959     if ((pc->req_override & (OR_ALL | ACCESS_CONF)) && !pm->create_dir_config)
1960         printf(" [no per-dir config]");
1961
1962     if (pc->req_override & OR_ALL) {
1963         printf(" and in .htaccess\n\twhen AllowOverride");
1964
1965         if ((pc->req_override & OR_ALL) == OR_ALL) {
1966             printf(" isn't None");
1967         }
1968         else {
1969             printf(" includes ");
1970
1971             if (pc->req_override & OR_AUTHCFG) {
1972                 if (n++)
1973                     printf(" or ");
1974
1975                 printf("AuthConfig");
1976             }
1977
1978             if (pc->req_override & OR_LIMIT) {
1979                 if (n++)
1980                     printf(" or ");
1981
1982                 printf("Limit");
1983             }
1984
1985             if (pc->req_override & OR_OPTIONS) {
1986                 if (n++)
1987                     printf(" or ");
1988
1989                 printf("Options");
1990             }
1991
1992             if (pc->req_override & OR_FILEINFO) {
1993                 if (n++)
1994                     printf(" or ");
1995
1996                 printf("FileInfo");
1997             }
1998
1999             if (pc->req_override & OR_INDEXES) {
2000                 if (n++)
2001                     printf(" or ");
2002
2003                 printf("Indexes");
2004             }
2005         }
2006     }
2007
2008     printf("\n");
2009 }
2010
2011 /* Show the preloaded configuration directives, the help string explaining
2012  * the directive arguments, in what module they are handled, and in
2013  * what parts of the configuration they are allowed.  Used for httpd -L.
2014  */
2015 AP_DECLARE(void) ap_show_directives(void)
2016 {
2017     const command_rec *pc;
2018     int n;
2019
2020     for (n = 0; ap_loaded_modules[n]; ++n) {
2021         for (pc = ap_loaded_modules[n]->cmds; pc && pc->name; ++pc) {
2022             printf("%s (%s)\n", pc->name, ap_loaded_modules[n]->name);
2023
2024             if (pc->errmsg)
2025                 printf("\t%s\n", pc->errmsg);
2026
2027             show_overrides(pc, ap_loaded_modules[n]);
2028         }
2029     }
2030 }
2031
2032 /* Show the preloaded module names.  Used for httpd -l. */
2033 AP_DECLARE(void) ap_show_modules(void)
2034 {
2035     int n;
2036
2037     printf("Compiled in modules:\n");
2038     for (n = 0; ap_loaded_modules[n]; ++n)
2039         printf("  %s\n", ap_loaded_modules[n]->name);
2040 }
2041
2042 AP_DECLARE(const char *) ap_show_mpm(void)
2043 {
2044     return MPM_NAME;
2045 }