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