1 /* $MirOS: src/usr.sbin/httpd/src/main/http_config.c,v 1.7 2008/12/03 11:22:59 tg Exp $ */
2 /* $OpenBSD: http_config.c,v 1.18 2007/11/19 14:59:10 robert Exp $ */
3 
4 /* ====================================================================
5  * The Apache Software License, Version 1.1
6  *
7  * Copyright (c) 2000-2003 The Apache Software Foundation.  All rights
8  * reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  *
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  *
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in
19  *    the documentation and/or other materials provided with the
20  *    distribution.
21  *
22  * 3. The end-user documentation included with the redistribution,
23  *    if any, must include the following acknowledgment:
24  *       "This product includes software developed by the
25  *        Apache Software Foundation (http://www.apache.org/)."
26  *    Alternately, this acknowledgment may appear in the software itself,
27  *    if and wherever such third-party acknowledgments normally appear.
28  *
29  * 4. The names "Apache" and "Apache Software Foundation" must
30  *    not be used to endorse or promote products derived from this
31  *    software without prior written permission. For written
32  *    permission, please contact apache@apache.org.
33  *
34  * 5. Products derived from this software may not be called "Apache",
35  *    nor may "Apache" appear in their name, without prior written
36  *    permission of the Apache Software Foundation.
37  *
38  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
39  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
40  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
41  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
42  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
43  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
44  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
45  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
46  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
47  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
48  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
49  * SUCH DAMAGE.
50  * ====================================================================
51  *
52  * This software consists of voluntary contributions made by many
53  * individuals on behalf of the Apache Software Foundation.  For more
54  * information on the Apache Software Foundation, please see
55  * <http://www.apache.org/>.
56  *
57  * Portions of this software are based upon public domain software
58  * originally written at the National Center for Supercomputing Applications,
59  * University of Illinois, Urbana-Champaign.
60  */
61 
62 /*
63  * http_config.c: once was auxillary functions for reading httpd's config
64  * file and converting filenames into a namespace
65  *
66  * Rob McCool
67  *
68  * Wall-to-wall rewrite for Apache... commands which are part of the
69  * server core can now be found next door in "http_core.c".  Now contains
70  * general command loop, and functions which do bookkeeping for the new
71  * Apache config stuff (modules and configuration vectors).
72  *
73  * rst
74  *
75  */
76 
77 #define CORE_PRIVATE
78 
79 #include "httpd.h"
80 #include "http_config.h"
81 #include "http_core.h"
82 #include "http_log.h"		/* for errors in parse_htaccess */
83 #include "http_main.h"
84 #include "http_request.h"	/* for default_handler (see invoke_handler) */
85 #include "http_conf_globals.h"	/* Sigh... */
86 #include "http_vhost.h"
87 #include "explain.h"
88 #include "fnmatch.h"
89 
90 __RCSID("$MirOS: src/usr.sbin/httpd/src/main/http_config.c,v 1.7 2008/12/03 11:22:59 tg Exp $");
91 
92 DEF_Explain
93 
94 /****************************************************************
95  *
96  * We begin with the functions which deal with the linked list
97  * of modules which control just about all of the server operation.
98  */
99 
100 /* total_modules is the number of modules that have been linked
101  * into the server.
102  */
103 static int total_modules = 0;
104 /* dynamic_modules is the number of modules that have been added
105  * after the pre-loaded ones have been set up. It shouldn't be larger
106  * than DYNAMIC_MODULE_LIMIT.
107  */
108 static int dynamic_modules = 0;
109 API_VAR_EXPORT module *top_module = NULL;
110 API_VAR_EXPORT module **ap_loaded_modules=NULL;
111 
112 typedef int (*handler_func) (request_rec *);
113 typedef void *(*dir_maker_func) (pool *, char *);
114 typedef void *(*merger_func) (pool *, void *, void *);
115 
116 /* Dealing with config vectors.  These are associated with per-directory,
117  * per-server, and per-request configuration, and have a void* pointer for
118  * each modules.  The nature of the structure pointed to is private to the
119  * module in question... the core doesn't (and can't) know.  However, there
120  * are defined interfaces which allow it to create instances of its private
121  * per-directory and per-server structures, and to merge the per-directory
122  * structures of a directory and its subdirectory (producing a new one in
123  * which the defaults applying to the base directory have been properly
124  * overridden).
125  */
126 
127 #ifndef ap_get_module_config
ap_get_module_config(void * conf_vector,module * m)128 API_EXPORT(void *) ap_get_module_config(void *conf_vector, module *m)
129 {
130     void **confv = (void **) conf_vector;
131     return confv[m->module_index];
132 }
133 #endif
134 
135 #ifndef ap_set_module_config
ap_set_module_config(void * conf_vector,module * m,void * val)136 API_EXPORT(void) ap_set_module_config(void *conf_vector, module *m, void *val)
137 {
138     void **confv = (void **) conf_vector;
139     confv[m->module_index] = val;
140 }
141 #endif
142 
create_empty_config(pool * p)143 static void *create_empty_config(pool *p)
144 {
145     void **conf_vector = (void **) ap_pcalloc(p, sizeof(void *) *
146 				    (total_modules + DYNAMIC_MODULE_LIMIT));
147     return (void *) conf_vector;
148 }
149 
create_default_per_dir_config(pool * p)150 static void *create_default_per_dir_config(pool *p)
151 {
152     void **conf_vector = (void **) ap_pcalloc(p, sizeof(void *) * (total_modules + DYNAMIC_MODULE_LIMIT));
153     module *modp;
154 
155     for (modp = top_module; modp; modp = modp->next) {
156 	dir_maker_func df = modp->create_dir_config;
157 
158 	if (df)
159 	    conf_vector[modp->module_index] = (*df) (p, NULL);
160     }
161 
162     return (void *) conf_vector;
163 }
164 
165 CORE_EXPORT(void *)
ap_merge_per_dir_configs(pool * p,void * base,void * new)166      ap_merge_per_dir_configs(pool *p, void *base, void *new)
167 {
168     void **conf_vector = (void **) ap_palloc(p, sizeof(void *) * total_modules);
169     void **base_vector = (void **) base;
170     void **new_vector = (void **) new;
171     module *modp;
172 
173     for (modp = top_module; modp; modp = modp->next) {
174 	merger_func df = modp->merge_dir_config;
175 	int i = modp->module_index;
176 
177 	if (df && new_vector[i])
178 	    conf_vector[i] = (*df) (p, base_vector[i], new_vector[i]);
179 	else
180 	    conf_vector[i] = new_vector[i] ? new_vector[i] : base_vector[i];
181     }
182 
183     return (void *) conf_vector;
184 }
185 
create_server_config(pool * p,server_rec * s)186 static void *create_server_config(pool *p, server_rec *s)
187 {
188     void **conf_vector = (void **) ap_pcalloc(p, sizeof(void *) * (total_modules + DYNAMIC_MODULE_LIMIT));
189     module *modp;
190 
191     for (modp = top_module; modp; modp = modp->next) {
192 	if (modp->create_server_config)
193 	    conf_vector[modp->module_index] = (*modp->create_server_config) (p, s);
194     }
195 
196     return (void *) conf_vector;
197 }
198 
merge_server_configs(pool * p,void * base,void * virt)199 static void merge_server_configs(pool *p, void *base, void *virt)
200 {
201     /* Can reuse the 'virt' vector for the spine of it, since we don't
202      * have to deal with the moral equivalent of .htaccess files here...
203      */
204 
205     void **base_vector = (void **) base;
206     void **virt_vector = (void **) virt;
207     module *modp;
208 
209     for (modp = top_module; modp; modp = modp->next) {
210 	merger_func df = modp->merge_server_config;
211 	int i = modp->module_index;
212 
213 	if (!virt_vector[i])
214 	    virt_vector[i] = base_vector[i];
215 	else if (df)
216 	    virt_vector[i] = (*df) (p, base_vector[i], virt_vector[i]);
217     }
218 }
219 
ap_create_request_config(pool * p)220 CORE_EXPORT(void *) ap_create_request_config(pool *p)
221 {
222     return create_empty_config(p);
223 }
224 
ap_create_per_dir_config(pool * p)225 CORE_EXPORT(void *) ap_create_per_dir_config(pool *p)
226 {
227     return create_empty_config(p);
228 }
229 
230 #ifdef EXPLAIN
231 
232 struct {
233     int offset;
234     char *method;
235 } aMethods[] =
236 
237 {
238 #define m(meth)	{ XtOffsetOf(module,meth),#meth }
239     m(translate_handler),
240     m(ap_check_user_id),
241     m(auth_checker),
242     m(type_checker),
243     m(fixer_upper),
244     m(logger),
245     { -1, "?" },
246 #undef m
247 };
248 
ShowMethod(module * modp,int offset)249 char *ShowMethod(module *modp, int offset)
250 {
251     int n;
252     static char buf[200];
253 
254     for (n = 0; aMethods[n].offset >= 0; ++n)
255 	if (aMethods[n].offset == offset)
256 	    break;
257     snprintf(buf, sizeof(buf), "%s:%s", modp->name, aMethods[n].method);
258     return buf;
259 }
260 #else
261 #define ShowMethod(modp,offset)
262 #endif
263 
264 /****************************************************************
265  *
266  * Dispatch through the modules to find handlers for various phases
267  * of request handling.  These are invoked by http_request.c to actually
268  * do the dirty work of slogging through the module structures.
269  */
270 
271 /*
272  * Optimized run_method routines.  The observation here is that many modules
273  * have NULL for most of the methods.  So we build optimized lists of
274  * everything.  If you think about it, this is really just like a sparse array
275  * implementation to avoid scanning the zero entries.
276  */
277 static const int method_offsets[] =
278 {
279     XtOffsetOf(module, translate_handler),
280     XtOffsetOf(module, ap_check_user_id),
281     XtOffsetOf(module, auth_checker),
282     XtOffsetOf(module, access_checker),
283     XtOffsetOf(module, type_checker),
284     XtOffsetOf(module, fixer_upper),
285     XtOffsetOf(module, logger),
286     XtOffsetOf(module, header_parser),
287     XtOffsetOf(module, post_read_request)
288 };
289 #define NMETHODS	(sizeof (method_offsets)/sizeof (method_offsets[0]))
290 
291 static struct {
292     int translate_handler;
293     int ap_check_user_id;
294     int auth_checker;
295     int access_checker;
296     int type_checker;
297     int fixer_upper;
298     int logger;
299     int header_parser;
300     int post_read_request;
301 } offsets_into_method_ptrs;
302 
303 /*
304  * This is just one big array of method_ptrs.  It's constructed such that,
305  * for example, method_ptrs[ offsets_into_method_ptrs.logger ] is the first
306  * logger function.  You go one-by-one from there until you hit a NULL.
307  * This structure was designed to hopefully maximize cache-coolness.
308  */
309 static handler_func *method_ptrs;
310 
311 
ap_cleanup_method_ptrs()312 void ap_cleanup_method_ptrs()
313 {
314     if (method_ptrs) {
315         free(method_ptrs);
316     }
317 }
318 
319 /* routine to reconstruct all these shortcuts... called after every
320  * add_module.
321  * XXX: this breaks if modules dink with their methods pointers
322  */
build_method_shortcuts(void)323 static void build_method_shortcuts(void)
324 {
325     module *modp;
326     int how_many_ptrs;
327     int i;
328     int next_ptr;
329     handler_func fp;
330 
331     if (method_ptrs) {
332 	/* free up any previous set of method_ptrs */
333 	free(method_ptrs);
334     }
335 
336     /* first we count how many functions we have */
337     how_many_ptrs = 0;
338     for (modp = top_module; modp; modp = modp->next) {
339 	for (i = 0; i < NMETHODS; ++i) {
340 	    if (*(handler_func *) (method_offsets[i] + (char *) modp)) {
341 		++how_many_ptrs;
342 	    }
343 	}
344     }
345     method_ptrs = malloc((how_many_ptrs + NMETHODS) * sizeof(handler_func));
346     if (method_ptrs == NULL) {
347 	fprintf(stderr, "Ouch!  Out of memory in build_method_shortcuts()!\n");
348     }
349     next_ptr = 0;
350     for (i = 0; i < NMETHODS; ++i) {
351 	/* XXX: This is an itsy bit presumptuous about the alignment
352 	 * constraints on offsets_into_method_ptrs.  I can't remember if
353 	 * ANSI says this has to be true... -djg */
354 	((int *) &offsets_into_method_ptrs)[i] = next_ptr;
355 	for (modp = top_module; modp; modp = modp->next) {
356 	    fp = *(handler_func *) (method_offsets[i] + (char *) modp);
357 	    if (fp) {
358 		method_ptrs[next_ptr++] = fp;
359 	    }
360 	}
361 	method_ptrs[next_ptr++] = NULL;
362     }
363 }
364 
365 
run_method(request_rec * r,int offset,int run_all)366 static int run_method(request_rec *r, int offset, int run_all)
367 {
368     int i;
369 
370     for (i = offset; method_ptrs[i]; ++i) {
371 	handler_func mod_handler = method_ptrs[i];
372 
373 	if (mod_handler) {
374 	    int result;
375 
376 	    result = (*mod_handler) (r);
377 
378 	    if (result != DECLINED && (!run_all || result != OK))
379 		return result;
380 	}
381     }
382 
383     return run_all ? OK : DECLINED;
384 }
385 
ap_translate_name(request_rec * r)386 API_EXPORT(int) ap_translate_name(request_rec *r)
387 {
388     return run_method(r, offsets_into_method_ptrs.translate_handler, 0);
389 }
390 
ap_check_access(request_rec * r)391 API_EXPORT(int) ap_check_access(request_rec *r)
392 {
393     return run_method(r, offsets_into_method_ptrs.access_checker, 1);
394 }
395 
ap_find_types(request_rec * r)396 API_EXPORT(int) ap_find_types(request_rec *r)
397 {
398     return run_method(r, offsets_into_method_ptrs.type_checker, 0);
399 }
400 
ap_run_fixups(request_rec * r)401 API_EXPORT(int) ap_run_fixups(request_rec *r)
402 {
403     return run_method(r, offsets_into_method_ptrs.fixer_upper, 1);
404 }
405 
ap_log_transaction(request_rec * r)406 API_EXPORT(int) ap_log_transaction(request_rec *r)
407 {
408     return run_method(r, offsets_into_method_ptrs.logger, 1);
409 }
410 
ap_header_parse(request_rec * r)411 API_EXPORT(int) ap_header_parse(request_rec *r)
412 {
413     return run_method(r, offsets_into_method_ptrs.header_parser, 1);
414 }
415 
ap_run_post_read_request(request_rec * r)416 API_EXPORT(int) ap_run_post_read_request(request_rec *r)
417 {
418     return run_method(r, offsets_into_method_ptrs.post_read_request, 1);
419 }
420 
421 /* Auth stuff --- anything that defines one of these will presumably
422  * want to define something for the other.  Note that check_auth is
423  * separate from check_access to make catching some config errors easier.
424  */
425 
ap_check_user_id(request_rec * r)426 API_EXPORT(int) ap_check_user_id(request_rec *r)
427 {
428     return run_method(r, offsets_into_method_ptrs.ap_check_user_id, 0);
429 }
430 
ap_check_auth(request_rec * r)431 API_EXPORT(int) ap_check_auth(request_rec *r)
432 {
433     return run_method(r, offsets_into_method_ptrs.auth_checker, 0);
434 }
435 
436 /*
437  * For speed/efficiency we generate a compact list of all the handlers
438  * and wildcard handlers.  This means we won't have to scan the entire
439  * module list looking for handlers... where we'll find a whole whack
440  * of NULLs.
441  */
442 typedef struct {
443     handler_rec hr;
444     size_t len;
445 } fast_handler_rec;
446 
447 static fast_handler_rec *handlers;
448 static fast_handler_rec *wildhandlers;
449 
init_handlers(pool * p)450 static void init_handlers(pool *p)
451 {
452     module *modp;
453     int nhandlers = 0;
454     int nwildhandlers = 0;
455     const handler_rec *handp;
456     fast_handler_rec *ph, *pw;
457     char *starp;
458 
459     for (modp = top_module; modp; modp = modp->next) {
460 	if (!modp->handlers)
461 	    continue;
462 	for (handp = modp->handlers; handp->content_type; ++handp) {
463 	    if (strchr(handp->content_type, '*')) {
464                 nwildhandlers ++;
465             } else {
466                 nhandlers ++;
467             }
468         }
469     }
470     ph = handlers = ap_palloc(p, sizeof(*ph)*(nhandlers + 1));
471     pw = wildhandlers = ap_palloc(p, sizeof(*pw)*(nwildhandlers + 1));
472     for (modp = top_module; modp; modp = modp->next) {
473 	if (!modp->handlers)
474 	    continue;
475 	for (handp = modp->handlers; handp->content_type; ++handp) {
476 	    if ((starp = strchr(handp->content_type, '*'))) {
477                 pw->hr.content_type = handp->content_type;
478                 pw->hr.handler = handp->handler;
479 		pw->len = starp - handp->content_type;
480                 pw ++;
481             } else {
482                 ph->hr.content_type = handp->content_type;
483                 ph->hr.handler = handp->handler;
484 		ph->len = strlen(handp->content_type);
485                 ph ++;
486             }
487         }
488     }
489     pw->hr.content_type = NULL;
490     pw->hr.handler = NULL;
491     ph->hr.content_type = NULL;
492     ph->hr.handler = NULL;
493 }
494 
ap_invoke_handler(request_rec * r)495 API_EXPORT(int) ap_invoke_handler(request_rec *r)
496 {
497     fast_handler_rec *handp;
498     const char *handler;
499     char *p;
500     size_t handler_len;
501     int result = HTTP_INTERNAL_SERVER_ERROR;
502 
503     if (r->handler) {
504 	handler = r->handler;
505 	handler_len = strlen(handler);
506     }
507     else {
508 	handler = r->content_type ? r->content_type : ap_default_type(r);
509 	if ((p = strchr(handler, ';')) != NULL) { /* MIME type arguments */
510 	    while (p > handler && p[-1] == ' ')
511 		--p;		/* strip trailing spaces */
512 	    handler_len = p - handler;
513 	}
514 	else {
515 	    handler_len = strlen(handler);
516 	}
517     }
518 
519     /* Pass one --- direct matches */
520 
521     for (handp = handlers; handp->hr.content_type; ++handp) {
522 	if (handler_len == handp->len
523 	    && !strncmp(handler, handp->hr.content_type, handler_len)) {
524             result = (*handp->hr.handler) (r);
525 
526             if (result != DECLINED)
527                 return result;
528         }
529     }
530 
531     /* Pass two --- wildcard matches */
532 
533     for (handp = wildhandlers; handp->hr.content_type; ++handp) {
534 	if (handler_len >= handp->len
535 	    && !strncmp(handler, handp->hr.content_type, handp->len)) {
536              result = (*handp->hr.handler) (r);
537 
538              if (result != DECLINED)
539                  return result;
540          }
541     }
542 
543     if (result == HTTP_INTERNAL_SERVER_ERROR && r->handler && r->filename) {
544         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, r,
545             "handler \"%s\" not found for: %s", r->handler, r->filename);
546     }
547     return HTTP_INTERNAL_SERVER_ERROR;
548 }
549 
550 /* One-time setup for precompiled modules --- NOT to be done on restart */
551 
ap_add_module(module * m)552 API_EXPORT(void) ap_add_module(module *m)
553 {
554     /* This could be called from an AddModule httpd.conf command,
555      * after the file has been linked and the module structure within it
556      * teased out...
557      */
558 
559     if (m->version != MODULE_MAGIC_NUMBER_MAJOR) {
560 	fprintf(stderr, "%s: module \"%s\" is not compatible with this "
561 		"version of Apache.\n", ap_server_argv0, m->name);
562 	fprintf(stderr, "Please contact the vendor for the correct version.\n");
563 	exit(1);
564     }
565 
566     if (m->next == NULL) {
567 	m->next = top_module;
568 	top_module = m;
569     }
570     if (m->module_index == -1) {
571 	m->module_index = total_modules++;
572 	dynamic_modules++;
573 
574 	if (dynamic_modules > DYNAMIC_MODULE_LIMIT) {
575 	    fprintf(stderr, "%s: module \"%s\" could not be loaded, because"
576 		    " the dynamic\n", ap_server_argv0, m->name);
577 	    fprintf(stderr, "module limit was reached. Please increase "
578 		    "DYNAMIC_MODULE_LIMIT and recompile.\n");
579 	    exit(1);
580 	}
581     }
582 
583     /* Some C compilers put a complete path into __FILE__, but we want
584      * only the filename (e.g. mod_includes.c). So check for path
585      * components (Unix and DOS), and remove them.
586      */
587 
588     if (strrchr(m->name, '/'))
589 	m->name = 1 + strrchr(m->name, '/');
590     if (strrchr(m->name, '\\'))
591 	m->name = 1 + strrchr(m->name, '\\');
592 
593     /*
594      * Invoke the `add_module' hook inside the now existing set
595      * of modules to let them all now that this module was added.
596      */
597     {
598         module *m2;
599         for (m2 = top_module; m2 != NULL; m2 = m2->next)
600             if (m2->magic == MODULE_MAGIC_COOKIE_EAPI)
601                 if (m2->add_module != NULL)
602                     (*m2->add_module)(m);
603     }
604 }
605 
606 /*
607  * remove_module undoes what add_module did. There are some caveats:
608  * when the module is removed, its slot is lost so all the current
609  * per-dir and per-server configurations are invalid. So we should
610  * only ever call this function when you are invalidating almost
611  * all our current data. I.e. when doing a restart.
612  */
613 
ap_remove_module(module * m)614 API_EXPORT(void) ap_remove_module(module *m)
615 {
616     module *modp;
617 
618     /*
619      * Invoke the `remove_module' hook inside the now existing
620      * set of modules to let them all now that this module is
621      * beeing removed.
622      */
623     {
624         module *m2;
625         for (m2 = top_module; m2 != NULL; m2 = m2->next)
626             if (m2->magic == MODULE_MAGIC_COOKIE_EAPI)
627                 if (m2->remove_module != NULL)
628                     (*m2->remove_module)(m);
629     }
630 
631     modp = top_module;
632     if (modp == m) {
633 	/* We are the top module, special case */
634 	top_module = modp->next;
635 	m->next = NULL;
636     }
637     else {
638 	/* Not the top module, find use. When found modp will
639 	 * point to the module _before_ us in the list
640 	 */
641 
642 	while (modp && modp->next != m) {
643 	    modp = modp->next;
644 	}
645 	if (!modp) {
646 	    /* Uh-oh, this module doesn't exist */
647 	    ap_log_error(APLOG_MARK, APLOG_ERR|APLOG_NOERRNO, NULL,
648 		"Cannot remove module %s: not found in module list",
649 		m->name);
650 	    return;
651 	}
652 	/* Eliminate us from the module list */
653 	modp->next = modp->next->next;
654     }
655 
656     m->module_index = -1;	/* simulate being unloaded, should
657 				 * be unnecessary */
658     dynamic_modules--;
659     total_modules--;
660 }
661 
ap_add_loaded_module(module * mod)662 API_EXPORT(void) ap_add_loaded_module(module *mod)
663 {
664     module **m;
665 
666     /*
667      *  Add module pointer to top of chained module list
668      */
669     ap_add_module(mod);
670 
671     /*
672      *  And module pointer to list of loaded modules
673      *
674      *  Notes: 1. ap_add_module() would already complain if no more space
675      *            exists for adding a dynamically loaded module
676      *         2. ap_add_module() accepts double-inclusion, so we have
677      *            to accept this, too.
678      */
679     for (m = ap_loaded_modules; *m != NULL; m++)
680         ;
681     *m++ = mod;
682     *m = NULL;
683 }
684 
ap_remove_loaded_module(module * mod)685 API_EXPORT(void) ap_remove_loaded_module(module *mod)
686 {
687     module **m;
688     module **m2;
689     int done;
690 
691     /*
692      *  Remove module pointer from chained module list
693      */
694     ap_remove_module(mod);
695 
696     /*
697      *  Remove module pointer from list of loaded modules
698      *
699      *  Note: 1. We cannot determine if the module was successfully
700      *           removed by ap_remove_module().
701      *        2. We have not to complain explicity when the module
702      *           is not found because ap_remove_module() did it
703      *           for us already.
704      */
705     for (m = m2 = ap_loaded_modules, done = 0; *m2 != NULL; m2++) {
706         if (*m2 == mod && done == 0)
707             done = 1;
708         else
709             *m++ = *m2;
710     }
711     *m = NULL;
712 }
713 
ap_setup_prelinked_modules(void)714 API_EXPORT(void) ap_setup_prelinked_modules(void)
715 {
716     module **m;
717     module **m2;
718 
719     /*
720      *  Initialise total_modules variable and module indices
721      */
722     total_modules = 0;
723     for (m = ap_preloaded_modules; *m != NULL; m++)
724         (*m)->module_index = total_modules++;
725 
726     /*
727      *  Initialise list of loaded modules
728      */
729     ap_loaded_modules = (module **)malloc(
730         sizeof(module *)*(total_modules+DYNAMIC_MODULE_LIMIT+1));
731     if (ap_loaded_modules == NULL) {
732 	fprintf(stderr, "Ouch!  Out of memory in ap_setup_prelinked_modules()!\n");
733 	exit(1);
734     }
735     for (m = ap_preloaded_modules, m2 = ap_loaded_modules; *m != NULL; )
736         *m2++ = *m++;
737     *m2 = NULL;
738 
739     /*
740      *   Initialize chain of linked (=activate) modules
741      */
742     for (m = ap_prelinked_modules; *m != NULL; m++)
743         ap_add_module(*m);
744 }
745 
ap_find_module_name(module * m)746 API_EXPORT(const char *) ap_find_module_name(module *m)
747 {
748     return m->name;
749 }
750 
ap_find_linked_module(const char * name)751 API_EXPORT(module *) ap_find_linked_module(const char *name)
752 {
753     module *modp;
754 
755     for (modp = top_module; modp; modp = modp->next) {
756 	if (strcmp(modp->name, name) == 0)
757 	    return modp;
758     }
759     return NULL;
760 }
761 
762 /* Add a named module.  Returns 1 if module found, 0 otherwise.  */
ap_add_named_module(const char * name)763 API_EXPORT(int) ap_add_named_module(const char *name)
764 {
765     module *modp;
766     int i = 0;
767 
768     for (modp = ap_loaded_modules[i]; modp; modp = ap_loaded_modules[++i]) {
769 	if (strcmp(modp->name, name) == 0) {
770 	    /* Only add modules that are not already enabled.  */
771 	    if (modp->next == NULL) {
772 		ap_add_module(modp);
773 	    }
774 	    return 1;
775 	}
776     }
777 
778     return 0;
779 }
780 
781 /* Clear the internal list of modules, in preparation for starting over. */
ap_clear_module_list()782 API_EXPORT(void) ap_clear_module_list()
783 {
784     module **m = &top_module;
785     module **next_m;
786 
787     while (*m) {
788 	next_m = &((*m)->next);
789 	*m = NULL;
790 	m = next_m;
791     }
792 
793     /* This is required; so we add it always.  */
794     ap_add_named_module("http_core.c");
795 }
796 
797 /*****************************************************************
798  *
799  * Resource, access, and .htaccess config files now parsed by a common
800  * command loop.
801  *
802  * Let's begin with the basics; parsing the line and
803  * invoking the function...
804  */
805 
invoke_cmd(const command_rec * cmd,cmd_parms * parms,void * mconfig,const char * args)806 static const char *invoke_cmd(const command_rec *cmd, cmd_parms *parms,
807 			    void *mconfig, const char *args)
808 {
809     char *w, *w2, *w3;
810     const char *errmsg;
811 
812     if ((parms->override & cmd->req_override) == 0)
813 	return ap_pstrcat(parms->pool, cmd->name, " not allowed here", NULL);
814 
815     parms->info = cmd->cmd_data;
816     parms->cmd = cmd;
817 
818     switch (cmd->args_how) {
819     case RAW_ARGS:
820 	return ((const char *(*)(cmd_parms *, void *, const char *))
821 		(cmd->func)) (parms, mconfig, args);
822 
823     case NO_ARGS:
824 	if (*args != 0)
825 	    return ap_pstrcat(parms->pool, cmd->name, " takes no arguments",
826 			   NULL);
827 
828 	return ((const char *(*)(cmd_parms *, void *))
829 		(cmd->func)) (parms, mconfig);
830 
831     case TAKE1:
832 	w = ap_getword_conf(parms->pool, &args);
833 
834 	if (*w == '\0' || *args != 0)
835 	    return ap_pstrcat(parms->pool, cmd->name, " takes one argument",
836 			    cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
837 
838 	return ((const char *(*)(cmd_parms *, void *, const char *))
839 		(cmd->func)) (parms, mconfig, w);
840 
841     case TAKE2:
842 
843 	w = ap_getword_conf(parms->pool, &args);
844 	w2 = ap_getword_conf(parms->pool, &args);
845 
846 	if (*w == '\0' || *w2 == '\0' || *args != 0)
847 	    return ap_pstrcat(parms->pool, cmd->name, " takes two arguments",
848 			    cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
849 
850 	return ((const char *(*)(cmd_parms *, void *, const char *,
851 			const char *)) (cmd->func)) (parms, mconfig, w, w2);
852 
853     case TAKE12:
854 
855 	w = ap_getword_conf(parms->pool, &args);
856 	w2 = ap_getword_conf(parms->pool, &args);
857 
858 	if (*w == '\0' || *args != 0)
859 	    return ap_pstrcat(parms->pool, cmd->name, " takes 1-2 arguments",
860 			    cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
861 
862 	return ((const char *(*)(cmd_parms *, void *, const char *,
863 			    const char *)) (cmd->func)) (parms, mconfig, w,
864 							    *w2 ? w2 : NULL);
865 
866     case TAKE3:
867 
868 	w = ap_getword_conf(parms->pool, &args);
869 	w2 = ap_getword_conf(parms->pool, &args);
870 	w3 = ap_getword_conf(parms->pool, &args);
871 
872 	if (*w == '\0' || *w2 == '\0' || *w3 == '\0' || *args != 0)
873 	    return ap_pstrcat(parms->pool, cmd->name, " takes three arguments",
874 			    cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
875 
876 	return ((const char *(*)(cmd_parms *, void *, const char *,
877 			    const char *, const char *)) (cmd->func)) (parms,
878 							mconfig, w, w2, w3);
879 
880     case TAKE23:
881 
882 	w = ap_getword_conf(parms->pool, &args);
883 	w2 = ap_getword_conf(parms->pool, &args);
884 	w3 = *args ? ap_getword_conf(parms->pool, &args) : NULL;
885 
886 	if (*w == '\0' || *w2 == '\0' || *args != 0)
887 	    return ap_pstrcat(parms->pool, cmd->name,
888 			    " takes two or three arguments",
889 			    cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
890 
891 	return ((const char *(*)(cmd_parms *, void *, const char *,
892 			    const char *, const char *)) (cmd->func)) (parms,
893 							mconfig, w, w2, w3);
894 
895     case TAKE123:
896 
897 	w = ap_getword_conf(parms->pool, &args);
898 	w2 = *args ? ap_getword_conf(parms->pool, &args) : NULL;
899 	w3 = *args ? ap_getword_conf(parms->pool, &args) : NULL;
900 
901 	if (*w == '\0' || *args != 0)
902 	    return ap_pstrcat(parms->pool, cmd->name,
903 			    " takes one, two or three arguments",
904 			    cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
905 
906 	return ((const char *(*)(cmd_parms *, void *, const char *,
907 			    const char *, const char *)) (cmd->func)) (parms,
908 							mconfig, w, w2, w3);
909 
910     case TAKE13:
911 
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' || (w2 && *w2 && !w3) || *args != 0)
917 	    return ap_pstrcat(parms->pool, cmd->name,
918 			    " takes one or three arguments",
919 			    cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
920 
921 	return ((const char *(*)(cmd_parms *, void *, const char *,
922 			    const char *, const char *)) (cmd->func)) (parms,
923 							mconfig, w, w2, w3);
924 
925     case ITERATE:
926 
927 	while (*(w = ap_getword_conf(parms->pool, &args)) != '\0')
928 	if   ((errmsg = ((const char *(*)(cmd_parms *, void *,
929 			const char *)) (cmd->func)) (parms, mconfig, w)))
930 		    return errmsg;
931 
932 	return NULL;
933 
934     case ITERATE2:
935 
936 	w = ap_getword_conf(parms->pool, &args);
937 
938 	if (*w == '\0' || *args == 0)
939 	    return ap_pstrcat(parms->pool, cmd->name,
940 			    " requires at least two arguments",
941 			    cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
942 
943 
944 	while (*(w2 = ap_getword_conf(parms->pool, &args)) != '\0')
945 	    if   ((errmsg = ((const char *(*)(cmd_parms *, void *,
946 			    const char *, const char *)) (cmd->func)) (parms,
947 							    mconfig, w, w2)))
948 			return errmsg;
949 
950 	return NULL;
951 
952     case FLAG:
953 
954 	w = ap_getword_conf(parms->pool, &args);
955 
956 	if (*w == '\0' || (strcasecmp(w, "on") && strcasecmp(w, "off")))
957 	    return ap_pstrcat(parms->pool, cmd->name, " must be On or Off",
958 			    NULL);
959 
960 	return ((const char *(*)(cmd_parms *, void *, int))
961 		(cmd->func)) (parms, mconfig, strcasecmp(w, "off") != 0);
962 
963     default:
964 
965 	return ap_pstrcat(parms->pool, cmd->name,
966 		    " is improperly configured internally (server bug)",
967 			NULL);
968     }
969 }
970 
ap_find_command(const char * name,const command_rec * cmds)971 CORE_EXPORT(const command_rec *) ap_find_command(const char *name, const command_rec *cmds)
972 {
973     while (cmds->name)
974 	if (!strcasecmp(name, cmds->name))
975 	    return cmds;
976 	else
977 	    ++cmds;
978 
979     return NULL;
980 }
981 
ap_find_command_in_modules(const char * cmd_name,module ** mod)982 CORE_EXPORT(const command_rec *) ap_find_command_in_modules(const char *cmd_name, module **mod)
983 {
984     const command_rec *cmdp;
985     module *modp;
986 
987     for (modp = *mod; modp; modp = modp->next)
988 	if (modp->cmds && (cmdp = ap_find_command(cmd_name, modp->cmds))) {
989 	    *mod = modp;
990 	    return cmdp;
991 	}
992 
993     return NULL;
994 }
995 
ap_set_config_vectors(cmd_parms * parms,void * config,module * mod)996 CORE_EXPORT(void *) ap_set_config_vectors(cmd_parms *parms, void *config, module *mod)
997 {
998     void *mconfig = ap_get_module_config(config, mod);
999     void *sconfig = ap_get_module_config(parms->server->module_config, mod);
1000 
1001     if (!mconfig && mod->create_dir_config) {
1002 	mconfig = (*mod->create_dir_config) (parms->pool, parms->path);
1003 	ap_set_module_config(config, mod, mconfig);
1004     }
1005 
1006     if (!sconfig && mod->create_server_config) {
1007 	sconfig = (*mod->create_server_config) (parms->pool, parms->server);
1008 	ap_set_module_config(parms->server->module_config, mod, sconfig);
1009     }
1010     return mconfig;
1011 }
1012 
ap_handle_command(cmd_parms * parms,void * config,const char * l)1013 CORE_EXPORT(const char *) ap_handle_command(cmd_parms *parms, void *config, const char *l)
1014 {
1015     void *oldconfig;
1016     const char *args, *cmd_name, *retval;
1017     const command_rec *cmd;
1018     module *mod = top_module;
1019 
1020     /*
1021      * Invoke the `rewrite_command' of modules to allow
1022      * they to rewrite the directive line before we
1023      * process it.
1024      */
1025     {
1026         module *m;
1027         char *cp;
1028         for (m = top_module; m != NULL; m = m->next) {
1029             if (m->magic == MODULE_MAGIC_COOKIE_EAPI) {
1030                 if (m->rewrite_command != NULL) {
1031                     cp = (m->rewrite_command)(parms, config, l);
1032                     if (cp != NULL)
1033                         l = cp;
1034                 }
1035             }
1036         }
1037     }
1038 
1039     if ((l[0] == '#') || (!l[0]))
1040 	return NULL;
1041 
1042     args = l;
1043     cmd_name = ap_getword_conf(parms->temp_pool, &args);
1044     if (*cmd_name == '\0')
1045 	return NULL;
1046 
1047     oldconfig = parms->context;
1048     parms->context = config;
1049     do {
1050 	if (!(cmd = ap_find_command_in_modules(cmd_name, &mod))) {
1051             errno = EINVAL;
1052             return ap_pstrcat(parms->pool, "Invalid command '", cmd_name,
1053                            "', perhaps mis-spelled or defined by a module "
1054                            "not included in the server configuration", NULL);
1055 	}
1056 	else {
1057 	    void *mconfig = ap_set_config_vectors(parms,config, mod);
1058 
1059 	    retval = invoke_cmd(cmd, parms, mconfig, args);
1060 	    mod = mod->next;	/* Next time around, skip this one */
1061 	}
1062     } while (retval && !strcmp(retval, DECLINE_CMD));
1063     parms->context = oldconfig;
1064 
1065     return retval;
1066 }
1067 
ap_srm_command_loop(cmd_parms * parms,void * config)1068 API_EXPORT(const char *) ap_srm_command_loop(cmd_parms *parms, void *config)
1069 {
1070     char l[MAX_STRING_LEN];
1071 
1072     while (!(ap_cfg_getline(l, MAX_STRING_LEN, parms->config_file))) {
1073 	const char *errmsg = ap_handle_command(parms, config, l);
1074         if (errmsg) {
1075 	    return errmsg;
1076 	}
1077     }
1078 
1079     return NULL;
1080 }
1081 
1082 /*
1083  * Generic command functions...
1084  */
1085 
ap_set_string_slot(cmd_parms * cmd,char * struct_ptr,char * arg)1086 API_EXPORT_NONSTD(const char *) ap_set_string_slot(cmd_parms *cmd,
1087 						char *struct_ptr, char *arg)
1088 {
1089     /* This one's pretty generic... */
1090 
1091     int offset = (int) (long) cmd->info;
1092     *(char **) (struct_ptr + offset) = arg;
1093     return NULL;
1094 }
1095 
ap_set_string_slot_lower(cmd_parms * cmd,char * struct_ptr,char * arg)1096 API_EXPORT_NONSTD(const char *) ap_set_string_slot_lower(cmd_parms *cmd,
1097 						char *struct_ptr, char *arg)
1098 {
1099     /* This one's pretty generic... */
1100 
1101     int offset = (int) (long) cmd->info;
1102     ap_str_tolower(arg);
1103     *(char **) (struct_ptr + offset) = arg;
1104     return NULL;
1105 }
1106 
ap_set_flag_slot(cmd_parms * cmd,char * struct_ptr,int arg)1107 API_EXPORT_NONSTD(const char *) ap_set_flag_slot(cmd_parms *cmd,
1108 					      char *struct_ptr, int arg)
1109 {
1110     /* This one's pretty generic too... */
1111 
1112     int offset = (int) (long) cmd->info;
1113     *(int *) (struct_ptr + offset) = arg ? 1 : 0;
1114     return NULL;
1115 }
1116 
ap_set_file_slot(cmd_parms * cmd,char * struct_ptr,char * arg)1117 API_EXPORT_NONSTD(const char *) ap_set_file_slot(cmd_parms *cmd, char *struct_ptr, char *arg)
1118 {
1119     /* Prepend server_root to relative arg.
1120        This allows .htaccess to be independent of server_root,
1121        so the server can be moved or mirrored with less pain.  */
1122     char *p;
1123     int offset = (int) (long) cmd->info;
1124     arg = ap_os_canonical_filename(cmd->pool, arg);
1125     if (ap_os_is_path_absolute(arg))
1126 	p = arg;
1127     else
1128 	p = ap_make_full_path(cmd->pool, ap_server_root, arg);
1129     *(char **) (struct_ptr + offset) = p;
1130     return NULL;
1131 }
1132 
1133 /*****************************************************************
1134  *
1135  * Reading whole config files...
1136  */
1137 
1138 static cmd_parms default_parms =
1139 {NULL, 0, -1, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
1140 
ap_server_root_relative(pool * p,char * file)1141 API_EXPORT(char *) ap_server_root_relative(pool *p, char *file)
1142 {
1143     file = ap_os_canonical_filename(p, file);
1144     if(ap_os_is_path_absolute(file))
1145 	return file;
1146     return ap_make_full_path(p, ap_server_root, file);
1147 }
1148 
1149 
1150 /* This structure and the following functions are needed for the
1151  * table-based config file reading. They are passed to the
1152  * cfg_open_custom() routine.
1153  */
1154 
1155 /* Structure to be passed to cfg_open_custom(): it contains an
1156  * index which is incremented from 0 to nelts on each call to
1157  * cfg_getline() (which in turn calls arr_elts_getstr())
1158  * and an array_header pointer for the string array.
1159  */
1160 typedef struct {
1161     array_header *array;
1162     int curr_idx;
1163 } arr_elts_param_t;
1164 
1165 
1166 /* arr_elts_getstr() returns the next line from the string array. */
arr_elts_getstr(void * buf,size_t bufsiz,void * param)1167 static void *arr_elts_getstr(void *buf, size_t bufsiz, void *param)
1168 {
1169     arr_elts_param_t *arr_param = (arr_elts_param_t *) param;
1170 
1171     /* End of array reached? */
1172     if (++arr_param->curr_idx > arr_param->array->nelts)
1173         return NULL;
1174 
1175     /* return the line */
1176     ap_cpystrn(buf, ((char **) arr_param->array->elts)[arr_param->curr_idx - 1], bufsiz);
1177 
1178     return buf;
1179 }
1180 
1181 
1182 /* arr_elts_close(): dummy close routine (makes sure no more lines can be read) */
arr_elts_close(void * param)1183 static int arr_elts_close(void *param)
1184 {
1185     arr_elts_param_t *arr_param = (arr_elts_param_t *) param;
1186     arr_param->curr_idx = arr_param->array->nelts;
1187     return 0;
1188 }
1189 
process_command_config(server_rec * s,array_header * arr,pool * p,pool * ptemp)1190 static void process_command_config(server_rec *s, array_header *arr, pool *p,
1191 				    pool *ptemp)
1192 {
1193     const char *errmsg;
1194     cmd_parms parms;
1195     arr_elts_param_t arr_parms;
1196 
1197     arr_parms.curr_idx = 0;
1198     arr_parms.array = arr;
1199 
1200     parms = default_parms;
1201     parms.pool = p;
1202     parms.temp_pool = ptemp;
1203     parms.server = s;
1204     parms.override = (RSRC_CONF | OR_ALL) & ~(OR_AUTHCFG | OR_LIMIT);
1205     parms.config_file = ap_pcfg_open_custom(p, "-c/-C directives",
1206                                          &arr_parms, NULL,
1207                                          arr_elts_getstr, arr_elts_close);
1208 
1209     errmsg = ap_srm_command_loop(&parms, s->lookup_defaults);
1210 
1211     if (errmsg) {
1212         fprintf(stderr, "Syntax error in -C/-c directive:\n%s\n", errmsg);
1213         exit(1);
1214     }
1215 
1216     ap_cfg_closefile(parms.config_file);
1217 }
1218 
1219 typedef struct {
1220     char *fname;
1221 } fnames;
1222 
fname_alphasort(const void * fn1,const void * fn2)1223 static int fname_alphasort(const void *fn1, const void *fn2)
1224 {
1225     const fnames *f1 = fn1;
1226     const fnames *f2 = fn2;
1227 
1228     return strcmp(f1->fname,f2->fname);
1229 }
1230 
ap_process_resource_config(server_rec * s,char * fname,pool * p,pool * ptemp)1231 CORE_EXPORT(void) ap_process_resource_config(server_rec *s, char *fname, pool *p, pool *ptemp)
1232 {
1233     const char *errmsg;
1234     cmd_parms parms;
1235     struct stat finfo;
1236     int ispatt;
1237     fname = ap_server_root_relative(p, fname);
1238 
1239     if (!(strcmp(fname, ap_server_root_relative(p, RESOURCE_CONFIG_FILE))) ||
1240 	!(strcmp(fname, ap_server_root_relative(p, ACCESS_CONFIG_FILE)))) {
1241 	if (stat(fname, &finfo) == -1)
1242 	    return;
1243     }
1244 
1245     /* if we are already chrooted here, it's a restart. strip chroot then. */
1246     ap_server_strip_chroot(fname, 0);
1247 
1248     /* don't require conf/httpd.conf if we have a -C or -c switch */
1249     if((ap_server_pre_read_config->nelts || ap_server_post_read_config->nelts) &&
1250        !(strcmp(fname, ap_server_root_relative(p, SERVER_CONFIG_FILE)))) {
1251 	if (stat(fname, &finfo) == -1)
1252 	    return;
1253     }
1254 
1255     /*
1256      * here we want to check if the candidate file is really a
1257      * directory, and most definitely NOT a symlink (to prevent
1258      * horrible loops).  If so, let's recurse and toss it back into
1259      * the function.
1260      */
1261     ispatt = ap_is_fnmatch(fname);
1262     if (ispatt || ap_is_rdirectory(fname)) {
1263 	DIR *dirp;
1264 	struct DIR_TYPE *dir_entry;
1265 	int current;
1266 	array_header *candidates = NULL;
1267 	fnames *fnew;
1268 	char *path = ap_pstrdup(p,fname);
1269 	char *pattern = NULL;
1270 
1271         if(ispatt && (pattern = strrchr(path, '/')) != NULL) {
1272             *pattern++ = '\0';
1273             if (ap_is_fnmatch(path)) {
1274                 fprintf(stderr, "%s: wildcard patterns not allowed in Include "
1275                         "%s\n", ap_server_argv0, fname);
1276                 exit(1);
1277             }
1278 
1279             if (!ap_is_rdirectory(path)){
1280                 fprintf(stderr, "%s: Include directory '%s' not found",
1281                         ap_server_argv0, path);
1282                 exit(1);
1283             }
1284             if (!ap_is_fnmatch(pattern)) {
1285                 fprintf(stderr, "%s: must include a wildcard pattern "
1286                         "for Include %s\n", ap_server_argv0, fname);
1287                 exit(1);
1288             }
1289         }
1290 
1291 
1292 	/*
1293 	 * first course of business is to grok all the directory
1294 	 * entries here and store 'em away. Recall we need full pathnames
1295 	 * for this.
1296 	 */
1297 	if (ap_configtestonly)
1298 		fprintf(stdout, "Processing config directory: %s\n", fname);
1299 	dirp = ap_popendir(p, path);
1300 	if (dirp == NULL) {
1301 	    perror("fopen");
1302 	    fprintf(stderr, "%s: could not open config directory %s\n",
1303 		ap_server_argv0, path);
1304 	    exit(1);
1305 	}
1306 	candidates = ap_make_array(p, 1, sizeof(fnames));
1307 	while ((dir_entry = readdir(dirp)) != NULL) {
1308 	    /* strip out '.' and '..' */
1309 	    if (strcmp(dir_entry->d_name, ".") &&
1310 		strcmp(dir_entry->d_name, "..") &&
1311                 (!ispatt ||
1312                  !ap_fnmatch(pattern,dir_entry->d_name, FNM_PERIOD)) ) {
1313 		fnew = (fnames *) ap_push_array(candidates);
1314 		fnew->fname = ap_make_full_path(p, path, dir_entry->d_name);
1315 	    }
1316 	}
1317 	ap_pclosedir(p, dirp);
1318 	if (candidates->nelts != 0) {
1319             qsort((void *) candidates->elts, candidates->nelts,
1320               sizeof(fnames), fname_alphasort);
1321 	    /*
1322 	     * Now recurse these... we handle errors and subdirectories
1323 	     * via the recursion, which is nice
1324 	     */
1325 	    for (current = 0; current < candidates->nelts; ++current) {
1326 	        fnew = &((fnames *) candidates->elts)[current];
1327 		if (ap_configtestonly)
1328 			fprintf(stdout, " Processing config file: %s\n", fnew->fname);
1329 		ap_process_resource_config(s, fnew->fname, p, ptemp);
1330 	    }
1331 	}
1332 	return;
1333     }
1334 
1335     /* GCC's initialization extensions are soooo nice here... */
1336 
1337     parms = default_parms;
1338     parms.pool = p;
1339     parms.temp_pool = ptemp;
1340     parms.server = s;
1341     parms.override = (RSRC_CONF | OR_ALL) & ~(OR_AUTHCFG | OR_LIMIT);
1342 
1343     if (!(parms.config_file = ap_pcfg_openfile(p,fname))) {
1344 	perror("fopen");
1345 	fprintf(stderr, "%s: could not open document config file %s\n",
1346 		ap_server_argv0, fname);
1347 	exit(1);
1348     }
1349 
1350     errmsg = ap_srm_command_loop(&parms, s->lookup_defaults);
1351 
1352     if (errmsg) {
1353 	fprintf(stderr, "Syntax error on line %d of %s:\n",
1354 		parms.config_file->line_number, parms.config_file->name);
1355 	fprintf(stderr, "%s\n", errmsg);
1356 	exit(1);
1357     }
1358 
1359     ap_cfg_closefile(parms.config_file);
1360 }
1361 
ap_parse_htaccess(void ** result,request_rec * r,int override,const char * d,const char * access_name)1362 CORE_EXPORT(int) ap_parse_htaccess(void **result, request_rec *r, int override,
1363 		   const char *d, const char *access_name)
1364 {
1365     configfile_t *f = NULL;
1366     cmd_parms parms;
1367     const char *errmsg;
1368     char *filename = NULL;
1369     const struct htaccess_result *cache;
1370     struct htaccess_result *new;
1371     void *dc = NULL;
1372 
1373 /* firstly, search cache */
1374     for (cache = r->htaccess; cache != NULL; cache = cache->next)
1375 	if (cache->override == override && strcmp(cache->dir, d) == 0) {
1376 	    if (cache->htaccess != NULL)
1377 		*result = cache->htaccess;
1378 	    return OK;
1379 	}
1380 
1381     parms = default_parms;
1382     parms.override = override;
1383     parms.pool = r->pool;
1384     parms.temp_pool = r->pool;
1385     parms.server = r->server;
1386     parms.path = ap_pstrdup(r->pool, d);
1387 
1388     /* loop through the access names and find the first one */
1389 
1390     while (access_name[0]) {
1391         filename = ap_make_full_path(r->pool, d,
1392                                      ap_getword_conf(r->pool, &access_name));
1393 
1394         if ((f = ap_pcfg_openfile(r->pool, filename)) != NULL) {
1395 
1396             dc = ap_create_per_dir_config(r->pool);
1397 
1398             parms.config_file = f;
1399 
1400             errmsg = ap_srm_command_loop(&parms, dc);
1401 
1402             ap_cfg_closefile(f);
1403 
1404             if (errmsg) {
1405                 ap_log_rerror(APLOG_MARK, APLOG_ALERT|APLOG_NOERRNO, r,
1406                               "%s: %s", filename, errmsg);
1407                 return HTTP_INTERNAL_SERVER_ERROR;
1408             }
1409             *result = dc;
1410             break;
1411         }
1412         else if (errno != ENOENT && errno != ENOTDIR) {
1413             ap_log_rerror(APLOG_MARK, APLOG_CRIT, r,
1414                           "%s pcfg_openfile: unable to check htaccess file, "
1415                           "ensure it is readable",
1416                           filename);
1417             ap_table_setn(r->notes, "error-notes",
1418                           "Server unable to read htaccess file, denying "
1419                           "access to be safe");
1420             return HTTP_FORBIDDEN;
1421         }
1422     }
1423 
1424 /* cache it */
1425     new = ap_palloc(r->pool, sizeof(struct htaccess_result));
1426     new->dir = parms.path;
1427     new->override = override;
1428     new->htaccess = dc;
1429 /* add to head of list */
1430     new->next = r->htaccess;
1431     r->htaccess = new;
1432 
1433     return OK;
1434 }
1435 
1436 
ap_init_virtual_host(pool * p,const char * hostname,server_rec * main_server,server_rec ** ps)1437 CORE_EXPORT(const char *) ap_init_virtual_host(pool *p, const char *hostname,
1438 			      server_rec *main_server, server_rec **ps)
1439 {
1440     server_rec *s = (server_rec *) ap_pcalloc(p, sizeof(server_rec));
1441 
1442     struct rlimit limits;
1443 
1444     getrlimit(RLIMIT_NOFILE, &limits);
1445     if (limits.rlim_cur < limits.rlim_max) {
1446 	limits.rlim_cur += 2;
1447 	if (setrlimit(RLIMIT_NOFILE, &limits) < 0) {
1448 	    perror("setrlimit(RLIMIT_NOFILE)");
1449 	    fprintf(stderr, "Cannot exceed hard limit for open files");
1450 	}
1451     }
1452 
1453     s->server_admin = NULL;
1454     s->server_hostname = NULL;
1455     s->error_fname = NULL;
1456     s->srm_confname = NULL;
1457     s->access_confname = NULL;
1458     s->timeout = 0;
1459     s->keep_alive_timeout = 0;
1460     s->keep_alive = -1;
1461     s->keep_alive_max = -1;
1462     s->error_log = main_server->error_log;
1463     s->loglevel = main_server->loglevel;
1464     /* useful default, otherwise we get a port of 0 on redirects */
1465     s->port = main_server->port;
1466     s->next = NULL;
1467 
1468     s->is_virtual = 1;
1469     s->names = ap_make_array(p, 4, sizeof(char **));
1470     s->wild_names = ap_make_array(p, 4, sizeof(char **));
1471 
1472     s->module_config = create_empty_config(p);
1473     s->lookup_defaults = ap_create_per_dir_config(p);
1474 
1475     s->server_uid = ap_user_id;
1476     s->server_gid = ap_group_id;
1477 
1478     s->limit_req_line = main_server->limit_req_line;
1479     s->limit_req_fieldsize = main_server->limit_req_fieldsize;
1480     s->limit_req_fields = main_server->limit_req_fields;
1481 
1482     s->ctx = ap_ctx_new(p);
1483 
1484     *ps = s;
1485 
1486     return ap_parse_vhost_addrs(p, hostname, s);
1487 }
1488 
1489 
fixup_virtual_hosts(pool * p,server_rec * main_server)1490 static void fixup_virtual_hosts(pool *p, server_rec *main_server)
1491 {
1492     server_rec *virt;
1493 
1494     for (virt = main_server->next; virt; virt = virt->next) {
1495 	merge_server_configs(p, main_server->module_config,
1496 			     virt->module_config);
1497 
1498 	virt->lookup_defaults =
1499 	    ap_merge_per_dir_configs(p, main_server->lookup_defaults,
1500 				  virt->lookup_defaults);
1501 
1502 	if (virt->server_admin == NULL)
1503 	    virt->server_admin = main_server->server_admin;
1504 
1505 	if (virt->srm_confname == NULL)
1506 	    virt->srm_confname = main_server->srm_confname;
1507 
1508 	if (virt->access_confname == NULL)
1509 	    virt->access_confname = main_server->access_confname;
1510 
1511 	if (virt->timeout == 0)
1512 	    virt->timeout = main_server->timeout;
1513 
1514 	if (virt->keep_alive_timeout == 0)
1515 	    virt->keep_alive_timeout = main_server->keep_alive_timeout;
1516 
1517 	if (virt->keep_alive == -1)
1518 	    virt->keep_alive = main_server->keep_alive;
1519 
1520 	if (virt->keep_alive_max == -1)
1521 	    virt->keep_alive_max = main_server->keep_alive_max;
1522 
1523 	if (virt->send_buffer_size == 0)
1524 	    virt->send_buffer_size = main_server->send_buffer_size;
1525 
1526 	/* XXX: this is really something that should be dealt with by a
1527 	 * post-config api phase */
1528 	ap_core_reorder_directories(p, virt);
1529     }
1530     ap_core_reorder_directories(p, main_server);
1531 }
1532 
1533 /*****************************************************************
1534  *
1535  * Getting *everything* configured...
1536  */
1537 
init_config_globals(pool * p)1538 static void init_config_globals(pool *p)
1539 {
1540     /* ServerRoot, server_confname set in httpd.c */
1541 
1542     ap_standalone = 1;
1543     ap_user_name = DEFAULT_USER;
1544     if (!ap_server_is_chrooted()) {
1545 	/* can't work, just keep old setting */
1546 	ap_user_id = ap_uname2id(DEFAULT_USER);
1547 	ap_group_id = ap_gname2id(DEFAULT_GROUP);
1548     }
1549     ap_daemons_to_start = DEFAULT_START_DAEMON;
1550     ap_daemons_min_free = DEFAULT_MIN_FREE_DAEMON;
1551     ap_daemons_max_free = DEFAULT_MAX_FREE_DAEMON;
1552     ap_daemons_limit = HARD_SERVER_LIMIT;
1553     ap_pid_fname = DEFAULT_PIDLOG;
1554     ap_scoreboard_fname = DEFAULT_SCOREBOARD;
1555     ap_lock_fname = DEFAULT_LOCKFILE;
1556     ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1557     ap_max_cpu_per_child = DEFAULT_MAX_CPU_PER_CHILD;
1558     ap_max_data_per_child = DEFAULT_MAX_DATA_PER_CHILD;
1559     ap_max_nofile_per_child = DEFAULT_MAX_NOFILE_PER_CHILD;
1560     ap_max_rss_per_child = DEFAULT_MAX_RSS_PER_CHILD;
1561     ap_max_stack_per_child = DEFAULT_MAX_STACK_PER_CHILD;
1562 #ifdef RLIMIT_TIME
1563     ap_max_time_per_child = DEFAULT_MAX_TIME_PER_CHILD;
1564 #endif
1565     ap_listeners = NULL;
1566     ap_listenbacklog = DEFAULT_LISTENBACKLOG;
1567     ap_extended_status = 0;
1568 
1569     /* Global virtual host hash bucket pointers.  Init to null. */
1570     ap_init_vhost_config(p);
1571 
1572     ap_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1573 }
1574 
init_server_config(pool * p)1575 static server_rec *init_server_config(pool *p)
1576 {
1577     server_rec *s = (server_rec *) ap_pcalloc(p, sizeof(server_rec));
1578 
1579     s->port = 0;
1580     s->server_admin = DEFAULT_ADMIN;
1581     s->server_hostname = NULL;
1582     s->error_fname = DEFAULT_ERRORLOG;
1583     s->error_log = stderr;
1584     s->loglevel = DEFAULT_LOGLEVEL;
1585     s->srm_confname = RESOURCE_CONFIG_FILE;
1586     s->access_confname = ACCESS_CONFIG_FILE;
1587     s->limit_req_line = DEFAULT_LIMIT_REQUEST_LINE;
1588     s->limit_req_fieldsize = DEFAULT_LIMIT_REQUEST_FIELDSIZE;
1589     s->limit_req_fields = DEFAULT_LIMIT_REQUEST_FIELDS;
1590     s->timeout = DEFAULT_TIMEOUT;
1591     s->keep_alive_timeout = DEFAULT_KEEPALIVE_TIMEOUT;
1592     s->keep_alive_max = DEFAULT_KEEPALIVE;
1593     s->keep_alive = 1;
1594     s->next = NULL;
1595     s->addrs = ap_pcalloc(p, sizeof(server_addr_rec));
1596     /* NOT virtual host; don't match any real network interface */
1597     memset(&s->addrs->host_addr, 0, sizeof(s->addrs->host_addr));
1598 #if 0
1599     s->addrs->host_addr.ss_family = ap_default_family; /* XXX: needed?, XXX: PF_xxx can be different from AF_xxx */
1600 #endif
1601 #ifdef HAVE_SOCKADDR_LEN
1602     s->addrs->host_addr.ss_len = (u_int8_t)sizeof(s->addrs->host_addr); /* XXX: needed ? */
1603 #endif
1604     s->addrs->host_port = 0;	/* matches any port */
1605     s->addrs->virthost = "";	/* must be non-NULL */
1606     s->names = s->wild_names = NULL;
1607 
1608     s->module_config = create_server_config(p, s);
1609     s->lookup_defaults = create_default_per_dir_config(p);
1610 
1611     s->ctx = ap_ctx_new(p);
1612 
1613     return s;
1614 }
1615 
1616 
default_listeners(pool * p,server_rec * s)1617 static void default_listeners(pool *p, server_rec *s)
1618 {
1619     listen_rec *new;
1620     struct addrinfo hints, *res0;
1621     int gai;
1622     char servbuf[NI_MAXSERV];
1623 
1624     if (ap_listeners != NULL) {
1625 	return;
1626     }
1627     snprintf(servbuf, sizeof(servbuf), "%d", s->port ? s->port : DEFAULT_HTTP_PORT);
1628     memset (&hints, 0, sizeof(hints));
1629     hints.ai_family = ap_default_family;
1630     hints.ai_socktype = SOCK_STREAM;
1631     hints.ai_flags = AI_PASSIVE;
1632     gai = getaddrinfo(NULL, servbuf, &hints, &res0);
1633     if (gai){
1634 	fprintf(stderr, "default_listeners(): getaddrinfo(PASSIVE) for family %u: %s\n",
1635 		ap_default_family, gai_strerror(gai));
1636 	exit (1);
1637     }
1638     /* allocate a default listener */
1639     new = ap_pcalloc(p, sizeof(listen_rec));
1640     memcpy(&new->local_addr, res0->ai_addr, res0->ai_addrlen);
1641     new->fd = -1;
1642     new->used = 0;
1643     new->next = NULL;
1644     ap_listeners = new;
1645 
1646     freeaddrinfo(res0);
1647 }
1648 
1649 
ap_read_config(pool * p,pool * ptemp,char * confname)1650 API_EXPORT(server_rec *) ap_read_config(pool *p, pool *ptemp, char *confname)
1651 {
1652     server_rec *s = init_server_config(p);
1653 
1654     init_config_globals(p);
1655 
1656     /* All server-wide config files now have the SAME syntax... */
1657 
1658     process_command_config(s, ap_server_pre_read_config, p, ptemp);
1659 
1660     ap_process_resource_config(s, confname, p, ptemp);
1661     ap_process_resource_config(s, s->srm_confname, p, ptemp);
1662     ap_process_resource_config(s, s->access_confname, p, ptemp);
1663 
1664     process_command_config(s, ap_server_post_read_config, p, ptemp);
1665 
1666     fixup_virtual_hosts(p, s);
1667     default_listeners(p, s);
1668     ap_fini_vhost_config(p, s);
1669 
1670     return s;
1671 }
1672 
ap_single_module_configure(pool * p,server_rec * s,module * m)1673 API_EXPORT(void) ap_single_module_configure(pool *p, server_rec *s, module *m)
1674 {
1675     if (m->create_server_config)
1676         ap_set_module_config(s->module_config, m,
1677                              (*m->create_server_config)(p, s));
1678     if (m->create_dir_config)
1679         ap_set_module_config(s->lookup_defaults, m,
1680                              (*m->create_dir_config)(p, NULL));
1681 }
1682 
ap_init_modules(pool * p,server_rec * s)1683 API_EXPORT(void) ap_init_modules(pool *p, server_rec *s)
1684 {
1685     module *m;
1686 
1687     for (m = top_module; m; m = m->next)
1688 	if (m->init)
1689 	    (*m->init) (s, p);
1690     build_method_shortcuts();
1691     init_handlers(p);
1692 }
1693 
ap_child_init_modules(pool * p,server_rec * s)1694 API_EXPORT(void) ap_child_init_modules(pool *p, server_rec *s)
1695 {
1696     module *m;
1697 
1698     for (m = top_module; m; m = m->next)
1699 	if (m->child_init)
1700 	    (*m->child_init) (s, p);
1701 }
1702 
ap_child_exit_modules(pool * p,server_rec * s)1703 API_EXPORT(void) ap_child_exit_modules(pool *p, server_rec *s)
1704 {
1705     module *m;
1706 
1707     signal(SIGHUP, SIG_IGN);
1708     signal(SIGUSR1, SIG_IGN);
1709 
1710     for (m = top_module; m; m = m->next)
1711 	if (m->child_exit)
1712 	    (*m->child_exit) (s, p);
1713 
1714 }
1715 
1716 /********************************************************************
1717  * Configuration directives are restricted in terms of where they may
1718  * appear in the main configuration files and/or .htaccess files according
1719  * to the bitmask req_override in the command_rec structure.
1720  * If any of the overrides set in req_override are also allowed in the
1721  * context in which the command is read, then the command is allowed.
1722  * The context is determined as follows:
1723  *
1724  *    inside *.conf --> override = (RSRC_CONF|OR_ALL)&~(OR_AUTHCFG|OR_LIMIT);
1725  *    within <Directory> or <Location> --> override = OR_ALL|ACCESS_CONF;
1726  *    within .htaccess --> override = AllowOverride for current directory;
1727  *
1728  * the result is, well, a rather confusing set of possibilities for when
1729  * a particular directive is allowed to be used.  This procedure prints
1730  * in English where the given (pc) directive can be used.
1731  */
show_overrides(const command_rec * pc,module * pm)1732 static void show_overrides(const command_rec *pc, module *pm)
1733 {
1734     int n = 0;
1735 
1736     printf("\tAllowed in *.conf ");
1737     if ((pc->req_override & (OR_OPTIONS | OR_FILEINFO | OR_INDEXES)) ||
1738 	((pc->req_override & RSRC_CONF) &&
1739 	 ((pc->req_override & (ACCESS_CONF | OR_AUTHCFG | OR_LIMIT)))))
1740 	printf("anywhere");
1741     else if (pc->req_override & RSRC_CONF)
1742 	printf("only outside <Directory>, <Files> or <Location>");
1743     else
1744 	printf("only inside <Directory>, <Files> or <Location>");
1745 
1746     /* Warn if the directive is allowed inside <Directory> or .htaccess
1747      * but module doesn't support per-dir configuration */
1748 
1749     if ((pc->req_override & (OR_ALL | ACCESS_CONF)) && !pm->create_dir_config)
1750 	printf(" [no per-dir config]");
1751 
1752     if (pc->req_override & OR_ALL) {
1753 	printf(" and in .htaccess\n\twhen AllowOverride");
1754 
1755 	if ((pc->req_override & OR_ALL) == OR_ALL)
1756 	    printf(" isn't None");
1757 	else {
1758 	    printf(" includes ");
1759 
1760 	    if (pc->req_override & OR_AUTHCFG) {
1761 		if (n++)
1762 		    printf(" or ");
1763 		printf("AuthConfig");
1764 	    }
1765 	    if (pc->req_override & OR_LIMIT) {
1766 		if (n++)
1767 		    printf(" or ");
1768 		printf("Limit");
1769 	    }
1770 	    if (pc->req_override & OR_OPTIONS) {
1771 		if (n++)
1772 		    printf(" or ");
1773 		printf("Options");
1774 	    }
1775 	    if (pc->req_override & OR_FILEINFO) {
1776 		if (n++)
1777 		    printf(" or ");
1778 		printf("FileInfo");
1779 	    }
1780 	    if (pc->req_override & OR_INDEXES) {
1781 		if (n++)
1782 		    printf(" or ");
1783 		printf("Indexes");
1784 	    }
1785 	}
1786     }
1787     printf("\n");
1788 }
1789 
1790 /* Show the preloaded configuration directives, the help string explaining
1791  * the directive arguments, in what module they are handled, and in
1792  * what parts of the configuration they are allowed.  Used for httpd -L.
1793  */
ap_show_directives(void)1794 API_EXPORT(void) ap_show_directives(void)
1795 {
1796     const command_rec *pc;
1797     int n;
1798 
1799     for (n = 0; ap_loaded_modules[n]; ++n)
1800 	for (pc = ap_loaded_modules[n]->cmds; pc && pc->name; ++pc) {
1801 	    printf("%s (%s)\n", pc->name, ap_loaded_modules[n]->name);
1802 	    if (pc->errmsg)
1803 		printf("\t%s\n", pc->errmsg);
1804 	    show_overrides(pc, ap_loaded_modules[n]);
1805 	}
1806 }
1807 
1808 /* Show the preloaded module names.  Used for httpd -l. */
ap_show_modules(void)1809 API_EXPORT(void) ap_show_modules(void)
1810 {
1811     int n;
1812 
1813     printf("Compiled-in modules:\n");
1814     for (n = 0; ap_loaded_modules[n]; ++n) {
1815 	printf("  %s\n", ap_loaded_modules[n]->name);
1816     }
1817     printf("suexec: %s\n",
1818 	   ap_suexec_enabled
1819 	       ? "enabled; valid wrapper " SUEXEC_BIN
1820 	       : "disabled; invalid wrapper " SUEXEC_BIN);
1821 }
1822 
ap_get_server_built(void)1823 API_EXPORT(const char *) ap_get_server_built(void)
1824 {
1825     return "unknown";
1826 }
1827