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