]> granicus.if.org Git - apache/blob - server/request.c
. unwind MORE redundant code [wasn't I just here six months ago???]
[apache] / server / request.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2001 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  *    if any, must include the following acknowledgment:
21  *       "This product includes software developed by the
22  *        Apache Software Foundation (http://www.apache.org/)."
23  *    Alternately, this acknowledgment may appear in the software itself,
24  *    if and wherever such third-party acknowledgments normally appear.
25  *
26  * 4. The names "Apache" and "Apache Software Foundation" must
27  *    not be used to endorse or promote products derived from this
28  *    software without prior written permission. For written
29  *    permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache",
32  *    nor may "Apache" appear in their name, without prior written
33  *    permission of the Apache Software Foundation.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation.  For more
51  * information on the Apache Software Foundation, please see
52  * <http://www.apache.org/>.
53  *
54  * Portions of this software are based upon public domain software
55  * originally written at the National Center for Supercomputing Applications,
56  * University of Illinois, Urbana-Champaign.
57  */
58
59 /*
60  * http_request.c: functions to get and process requests
61  *
62  * Rob McCool 3/21/93
63  *
64  * Thoroughly revamped by rst for Apache.  NB this file reads
65  * best from the bottom up.
66  *
67  */
68
69 #include "apr_strings.h"
70 #include "apr_file_io.h"
71 #include "apr_fnmatch.h"
72
73 #define APR_WANT_STRFUNC
74 #include "apr_want.h"
75
76 #define CORE_PRIVATE
77 #include "ap_config.h"
78 #include "httpd.h"
79 #include "http_config.h"
80 #include "http_request.h"
81 #include "http_core.h"
82 #include "http_protocol.h"
83 #include "http_log.h"
84 #include "http_main.h"
85 #include "util_filter.h"
86 #include "util_charset.h"
87
88 #include "mod_core.h"
89
90 #if APR_HAVE_STDARG_H
91 #include <stdarg.h>
92 #endif
93
94 APR_HOOK_STRUCT(
95     APR_HOOK_LINK(translate_name)
96     APR_HOOK_LINK(map_to_storage)
97     APR_HOOK_LINK(check_user_id)
98     APR_HOOK_LINK(fixups)
99     APR_HOOK_LINK(type_checker)
100     APR_HOOK_LINK(access_checker)
101     APR_HOOK_LINK(auth_checker)
102     APR_HOOK_LINK(insert_filter)
103     APR_HOOK_LINK(create_request)
104 )
105
106 AP_IMPLEMENT_HOOK_RUN_FIRST(int,translate_name,
107                             (request_rec *r),(r),DECLINED)
108 AP_IMPLEMENT_HOOK_RUN_FIRST(int,map_to_storage,
109                             (request_rec *r),(r),DECLINED)
110 AP_IMPLEMENT_HOOK_RUN_FIRST(int,check_user_id,
111                             (request_rec *r),(r),DECLINED)
112 AP_IMPLEMENT_HOOK_RUN_ALL(int,fixups,
113                           (request_rec *r),(r),OK,DECLINED)
114 AP_IMPLEMENT_HOOK_RUN_FIRST(int,type_checker,
115                             (request_rec *r),(r),DECLINED)
116 AP_IMPLEMENT_HOOK_RUN_ALL(int,access_checker,
117                           (request_rec *r),(r),OK,DECLINED)
118 AP_IMPLEMENT_HOOK_RUN_FIRST(int,auth_checker,
119                             (request_rec *r),(r),DECLINED)
120 AP_IMPLEMENT_HOOK_VOID(insert_filter, (request_rec *r), (r))
121 AP_IMPLEMENT_HOOK_RUN_ALL(int,create_request,(request_rec *r),(r),OK,DECLINED)
122
123
124 static int decl_die(int status, char *phase, request_rec *r)
125 {
126     if (status == DECLINED) {
127         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_CRIT, 0, r,
128                       "configuration error:  couldn't %s: %s", phase, r->uri);
129         return HTTP_INTERNAL_SERVER_ERROR;
130     }
131     else {
132         return status;
133     }
134 }
135
136 /* This is the master logic for processing requests.  Do NOT duplicate
137  * this logic elsewhere, or the security model will be broken by future
138  * API changes.  Each phase must be individually optimized to pick up
139  * redundant/duplicate calls by subrequests, and redirects.
140  */
141 AP_DECLARE(int) ap_process_request_internal(request_rec *r)
142 {
143     int file_req = (r->main && r->filename);
144     int access_status;
145
146     /* Ignore embedded %2F's in path for proxy requests */
147     if (!r->proxyreq && r->parsed_uri.path) {
148         access_status = ap_unescape_url(r->parsed_uri.path);
149         if (access_status) {
150             return access_status;
151         }
152     }
153
154     ap_getparents(r->uri);     /* OK --- shrinking transformations... */
155
156     /* All file subrequests are a huge pain... they cannot bubble through the 
157      * next several steps.  Only file subrequests are allowed an empty uri, 
158      * otherwise let translate_name kill the request.
159      */
160     if (!file_req) {
161         if ((access_status = ap_location_walk(r))) {
162             return access_status;
163         }
164
165         if ((access_status = ap_run_translate_name(r))) {
166             return decl_die(access_status, "translate", r);
167         }
168     }
169
170     /* Reset to the server default config prior to running map_to_storage 
171      */
172     r->per_dir_config = r->server->lookup_defaults;
173
174     if ((access_status = ap_run_map_to_storage(r))) {
175         /* This request wasn't in storage (e.g. TRACE) */
176         return access_status;
177     }
178
179     /* Excluding file-specific requests with no 'true' URI...
180      */
181     if (!file_req) {
182         /* Rerun the location walk, which overrides any map_to_storage config.
183          */
184         if ((access_status = ap_location_walk(r))) {
185             return access_status;
186         }
187     }
188
189     /* Only on the main request! */
190     if (r->main == NULL) {
191         if ((access_status = ap_run_header_parser(r))) {
192             return access_status;
193         }
194     }
195
196     /* Skip authn/authz if the parent or prior request passed the authn/authz,
197      * and that configuration didn't change (this requires optimized _walk()
198      * functions in map_to_storage that use the same merge results given
199      * identical input.)  If the config changes, we must re-auth.
200      */
201     if (r->main && (r->main->per_dir_config == r->per_dir_config)) {
202         r->user = r->main->user;        
203         r->ap_auth_type = r->main->ap_auth_type;
204     } 
205     else if (r->prev && (r->prev->per_dir_config == r->per_dir_config)) {
206         r->user = r->prev->user;        
207         r->ap_auth_type = r->prev->ap_auth_type;
208     }
209     else {
210         switch (ap_satisfies(r)) {
211         case SATISFY_ALL:
212         case SATISFY_NOSPEC:
213             if ((access_status = ap_run_access_checker(r)) != 0) {
214                 return decl_die(access_status, "check access", r);
215             }
216             if (ap_some_auth_required(r)) {
217                 if (((access_status = ap_run_check_user_id(r)) != 0)
218                     || !ap_auth_type(r)) {
219                     return decl_die(access_status, ap_auth_type(r)
220                                   ? "check user.  No user file?"
221                                   : "perform authentication. AuthType not set!",
222                                   r);
223                 }
224                 if (((access_status = ap_run_auth_checker(r)) != 0)
225                     || !ap_auth_type(r)) {
226                     return decl_die(access_status, ap_auth_type(r)
227                                   ? "check access.  No groups file?"
228                                   : "perform authentication. AuthType not set!",
229                                    r);
230                 }
231             }
232             break;
233         case SATISFY_ANY:
234             if (((access_status = ap_run_access_checker(r)) != 0) || 
235                 !ap_auth_type(r)) {
236                 if (!ap_some_auth_required(r)) {
237                     return decl_die(access_status, ap_auth_type(r)
238                                   ? "check access"
239                                   : "perform authentication. AuthType not set!",
240                                   r);
241                 }
242                 if (((access_status = ap_run_check_user_id(r)) != 0)
243                     || !ap_auth_type(r)) {
244                     return decl_die(access_status, ap_auth_type(r)
245                                   ? "check user.  No user file?"
246                                   : "perform authentication. AuthType not set!",
247                                   r);
248                 }
249                 if (((access_status = ap_run_auth_checker(r)) != 0)
250                     || !ap_auth_type(r)) {
251                     return decl_die(access_status, ap_auth_type(r)
252                                   ? "check access.  No groups file?"
253                                   : "perform authentication. AuthType not set!",
254                                   r);
255                 }
256             }
257             break;
258         }
259     }
260     /* XXX Must make certain the ap_run_type_checker short circuits mime
261      * in mod-proxy for r->proxyreq && r->parsed_uri.scheme 
262      *                              && !strcmp(r->parsed_uri.scheme, "http")
263      */
264     if ((access_status = ap_run_type_checker(r)) != 0) {
265         return decl_die(access_status, "find types", r);
266     }
267
268     if ((access_status = ap_run_fixups(r)) != 0) {
269         return access_status;
270     }
271
272     /* The new insert_filter stage makes sense here IMHO.  We are sure that
273      * we are going to run the request now, so we may as well insert filters
274      * if any are available.  Since the goal of this phase is to allow all
275      * modules to insert a filter if they want to, this filter returns
276      * void.  I just can't see any way that this filter can reasonably
277      * fail, either your modules inserts something or it doesn't.  rbb
278      */
279     ap_run_insert_filter(r);
280
281     return OK;
282 }
283
284
285 /* Useful caching structures to repeat _walk/merge sequences as required
286  * when a subrequest or redirect reuses substantially the same config.
287  *
288  * Directive order in the httpd.conf file and its Includes significantly
289  * impact this optimization.  Grouping common blocks at the front of the
290  * config that are less likely to change between a request and 
291  * its subrequests, or between a request and its redirects reduced
292  * the work of these functions significantly.
293  */
294
295 typedef struct walk_walked_t {
296     ap_conf_vector_t *matched; /* A dir_conf sections we matched */
297     ap_conf_vector_t *merged;  /* The dir_conf merged result */
298 } walk_walked_t;
299
300 typedef struct walk_cache_t {
301     const char         *cached;         /* The identifier we matched */
302     ap_conf_vector_t  **dir_conf_tested;/* The sections we matched against */
303     ap_conf_vector_t   *dir_conf_merged;/* Base per_dir_config */
304     ap_conf_vector_t   *per_dir_result; /* per_dir_config += walked result */
305     apr_array_header_t *walked;         /* The list of walk_walked_t results */
306 } walk_cache_t;
307
308 static walk_cache_t *prep_walk_cache(const char *cache_name, request_rec *r)
309 {
310     walk_cache_t *cache;
311
312     /* Find the most relevant, recent entry to work from.  That would be
313      * this request (on the second call), or the parent request of a
314      * subrequest, or the prior request of an internal redirect.  Provide
315      * this _walk()er with a copy it is allowed to munge.  If there is no
316      * parent or prior cached request, then create a new walk cache.
317      */
318     if ((apr_pool_userdata_get((void **)&cache, cache_name, r->pool)
319                 != APR_SUCCESS)
320         || !cache) {
321         if ((r->main && (apr_pool_userdata_get((void **)&cache, 
322                                                cache_name,
323                                                r->main->pool)
324                          == APR_SUCCESS) && cache)
325          || (r->prev && (apr_pool_userdata_get((void **)&cache, 
326                                                cache_name,
327                                                r->prev->pool)
328                          == APR_SUCCESS) && cache)) {
329             cache = apr_pmemdup(r->pool, cache, sizeof(*cache));
330             cache->walked = apr_array_copy(r->pool, cache->walked);
331         }
332         else {
333             cache = apr_pcalloc(r->pool, sizeof(*cache));
334             cache->walked = apr_array_make(r->pool, 4, sizeof(walk_walked_t));
335         }
336         apr_pool_userdata_setn(cache, cache_name, NULL, r->pool);
337     }
338     return cache;
339 }
340
341 /*****************************************************************
342  *
343  * Getting and checking directory configuration.  Also checks the
344  * FollowSymlinks and FollowSymOwner stuff, since this is really the
345  * only place that can happen (barring a new mid_dir_walk callout).
346  *
347  * We can't do it as an access_checker module function which gets
348  * called with the final per_dir_config, since we could have a directory
349  * with FollowSymLinks disabled, which contains a symlink to another
350  * with a .htaccess file which turns FollowSymLinks back on --- and
351  * access in such a case must be denied.  So, whatever it is that
352  * checks FollowSymLinks needs to know the state of the options as
353  * they change, all the way down.
354  */
355
356 /*
357  * We don't want people able to serve up pipes, or unix sockets, or other
358  * scary things.  Note that symlink tests are performed later.
359  */
360 static int check_safe_file(request_rec *r)
361 {
362
363     if (r->finfo.filetype == 0      /* doesn't exist */
364         || r->finfo.filetype == APR_DIR
365         || r->finfo.filetype == APR_REG
366         || r->finfo.filetype == APR_LNK) {
367         return OK;
368     }
369
370     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
371                   "object is not a file, directory or symlink: %s",
372                   r->filename);
373     return HTTP_FORBIDDEN;
374 }
375
376 /*
377  * resolve_symlink must _always_ be called on an APR_LNK file type!
378  * It will resolve the actual target file type, modification date, etc, 
379  * and provide any processing required for symlink evaluation.
380  * Path must already be cleaned, no trailing slash, no multi-slashes,
381  * and don't call this on the root!
382  *
383  * Simply, the number of times we deref a symlink are minimal compared
384  * to the number of times we had an extra lstat() since we 'weren't sure'.
385  *
386  * To optimize, we stat() anything when given (opts & OPT_SYM_LINKS), otherwise
387  * we start off with an lstat().  Every lstat() must be dereferenced in case 
388  * it points at a 'nasty' - we must always rerun check_safe_file (or similar.)
389  */
390 static int resolve_symlink(char *d, apr_finfo_t *lfi, int opts, apr_pool_t *p)
391 {
392     apr_finfo_t fi;
393     int res;
394
395     if (!(opts & (OPT_SYM_OWNER | OPT_SYM_LINKS))) {
396         return HTTP_FORBIDDEN;
397     }
398
399     if (opts & OPT_SYM_LINKS) {
400         if ((res = apr_stat(&fi, d, lfi->valid, p)) != APR_SUCCESS) {
401             return HTTP_FORBIDDEN;
402         }
403
404         /* Give back the target */
405         memcpy(lfi, &fi, sizeof(fi));
406         return OK;
407     }
408
409     /* OPT_SYM_OWNER only works if we can get the owner of 
410      * both the file and symlink.  First fill in a missing
411      * owner of the symlink, then get the info of the target.
412      */
413     if (!(lfi->valid & APR_FINFO_OWNER)) {
414         if ((res = apr_lstat(&fi, d, lfi->valid | APR_FINFO_OWNER, p))
415             != APR_SUCCESS) {
416             return HTTP_FORBIDDEN;
417         }
418     }
419
420     if ((res = apr_stat(&fi, d, lfi->valid, p)) != APR_SUCCESS) {
421         return HTTP_FORBIDDEN;
422     }
423
424     if (apr_compare_users(fi.user, lfi->user) != APR_SUCCESS) {
425         return HTTP_FORBIDDEN;
426     }
427
428     /* Give back the target */
429     memcpy(lfi, &fi, sizeof(fi));
430     return OK;
431 }
432
433
434 /*****************************************************************
435  *
436  * Getting and checking directory configuration.  Also checks the
437  * FollowSymlinks and FollowSymOwner stuff, since this is really the
438  * only place that can happen (barring a new mid_dir_walk callout).
439  *
440  * We can't do it as an access_checker module function which gets
441  * called with the final per_dir_config, since we could have a directory
442  * with FollowSymLinks disabled, which contains a symlink to another
443  * with a .htaccess file which turns FollowSymLinks back on --- and
444  * access in such a case must be denied.  So, whatever it is that
445  * checks FollowSymLinks needs to know the state of the options as
446  * they change, all the way down.
447  */
448
449 AP_DECLARE(int) ap_directory_walk(request_rec *r)
450 {
451     ap_conf_vector_t *now_merged = NULL;
452     core_server_config *sconf = ap_get_module_config(r->server->module_config,
453                                                      &core_module);
454     ap_conf_vector_t **sec_ent = (ap_conf_vector_t **) sconf->sec_dir->elts;
455     int num_sec = sconf->sec_dir->nelts;
456     walk_cache_t *cache;
457     char *entry_dir;
458     apr_status_t rv;
459
460     /* XXX: Better (faster) tests needed!!!
461      *
462      * "OK" as a response to a real problem is not _OK_, but to allow broken 
463      * modules to proceed, we will permit the not-a-path filename to pass here.
464      * We must catch it later if it's heading for the core handler.  Leave an 
465      * INFO note here for module debugging.
466      */
467     if (r->filename == NULL || !ap_os_is_path_absolute(r->pool, r->filename)) {
468         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r,
469                       "Module bug?  Request filename path %s is missing "
470                       "or not absolute for uri %s", 
471                       r->filename ? r->filename : "<NULL>", r->uri);
472        return OK;
473     }
474
475     /* Canonicalize the file path without resolving filename case or aliases
476      * so we can begin by checking the cache for a recent directory walk.
477      * This call will ensure we have an absolute path in the same pass.
478      */
479     if ((rv = apr_filepath_merge(&entry_dir, NULL, r->filename, 
480                                  APR_FILEPATH_NOTRELATIVE, r->pool)) 
481                   != APR_SUCCESS) {
482         ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, r,
483                       "Module bug?  Request filename path %s is invalid or "
484                       "or not absolute for uri %s", 
485                       r->filename, r->uri);
486         return OK;
487     }
488
489     /* XXX Notice that this forces path_info to be canonical.  That might
490      * not be desired by all apps.  However, some of those same apps likely
491      * have significant security holes.
492      */
493     r->filename = entry_dir;
494
495     cache = prep_walk_cache("ap_directory_walk::cache", r);
496
497     /* If this is not a dirent subrequest with a preconstructed 
498      * r->finfo value, then we can simply stat the filename to
499      * save burning mega-cycles with unneeded stats - if this is
500      * an exact file match.  We don't care about failure... we
501      * will stat by component failing this meager attempt.
502      *
503      * It would be nice to distinguish APR_ENOENT from other
504      * types of failure, such as APR_ENOTDIR.  We can do something
505      * with APR_ENOENT, knowing that the path is good.
506      */
507     if (!r->finfo.filetype || r->finfo.filetype == APR_LNK) {
508         apr_stat(&r->finfo, r->filename, APR_FINFO_MIN, r->pool);
509     }
510
511     if (r->finfo.filetype == APR_REG) {
512         entry_dir = ap_make_dirstr_parent(r->pool, entry_dir);
513     }
514     else if (r->filename[strlen(r->filename) - 1] != '/') {
515         entry_dir = apr_pstrcat(r->pool, r->filename, "/", NULL);
516     }
517
518     /* If we have a file already matches the path of r->filename,
519      * and the vhost's list of directory sections hasn't changed, 
520      * we can skip rewalking the directory_walk entries.
521      */
522     if (cache->cached && ((r->finfo.filetype == APR_REG)
523                           || (r->finfo.filetype == APR_DIR))
524         && (cache->dir_conf_tested == sec_ent) 
525         && (strcmp(entry_dir, cache->cached) == 0)) {
526         /* Well this looks really familiar!  If our end-result (per_dir_result)
527          * didn't change, we have absolutely nothing to do :)  
528          * Otherwise (as is the case with most dir_merged/file_merged requests)
529          * we must merge our dir_conf_merged onto this new r->per_dir_config.
530          */
531         if (r->per_dir_config == cache->per_dir_result) {
532             return OK;
533         }
534         if (r->per_dir_config == cache->dir_conf_merged) {
535             r->per_dir_config = cache->per_dir_result;
536             return OK;
537         }
538         if (cache->walked->nelts) {
539             now_merged = ((walk_walked_t*)cache->walked->elts)
540                 [cache->walked->nelts - 1].merged;
541         }
542     }
543     else {
544         /* We start now_merged from NULL since we want to build 
545          * a locations list that can be merged to any vhost.
546          */
547         int sec_idx;
548         int matches = cache->walked->nelts;
549         walk_walked_t *last_walk = (walk_walked_t*)cache->walked->elts;
550         core_dir_config *this_dir;
551         allow_options_t opts;
552         allow_options_t opts_add;
553         allow_options_t opts_remove;
554         overrides_t override;
555
556         apr_finfo_t thisinfo;
557         char *save_path_info;
558         apr_size_t buflen;
559         char *buf;
560         unsigned int seg, startseg;
561
562         /* Invariant: from the first time filename_len is set until
563          * it goes out of scope, filename_len==strlen(r->filename)
564          */
565         apr_size_t filename_len;
566
567         /*
568          * We must play our own mimi-merge game here, for the few 
569          * running dir_config values we care about within dir_walk.
570          * We didn't start the merge from r->per_dir_config, so we
571          * accumulate opts and override as we merge, from the globals.
572          */
573         this_dir = ap_get_module_config(r->per_dir_config, &core_module);
574         opts = this_dir->opts;
575         opts_add = this_dir->opts_add;
576         opts_remove = this_dir->opts_remove;
577         override = this_dir->override;
578
579         /* Save path_info to merge back onto path_info later. If this
580          * isn't really path_info, what would it be doing here?
581          */
582         save_path_info = r->path_info;
583
584         /* Now begin to build r->filename from components, set aside the
585          * segments we have yet to work with in r->path_info (where they
586          * will stay when the current element resolves to a regular file.)
587          *
588          * r->path_info tracks the remaining source path.
589          * r->filename  tracks the path as we build it.
590          */
591         r->path_info = r->filename;
592         rv = apr_filepath_root((const char **)&r->filename,
593                                (const char **)&r->path_info,
594                                APR_FILEPATH_TRUENAME, r->pool);
595         filename_len = strlen(r->filename);
596         /* Space for terminating null and an extra / is required. */
597         buflen = filename_len + strlen(r->path_info) + 2;
598         buf = apr_palloc(r->pool, buflen);
599         memcpy(buf, r->filename, filename_len + 1);
600         r->filename = buf;
601         thisinfo.valid = APR_FINFO_TYPE;
602         thisinfo.filetype = APR_DIR; /* It's the root, of course it's a dir */
603
604         /*
605          * seg keeps track of which segment we've copied.
606          * sec_idx keeps track of which section we're on, since sections are
607          *     ordered by number of segments. See core_reorder_directories 
608          */
609         startseg = seg = ap_count_dirs(r->filename);
610         sec_idx = 0;
611
612         /*
613          * Go down the directory hierarchy.  Where we have to check for 
614          * symlinks, do so.  Where a .htaccess file has permission to 
615          * override anything, try to find one.
616          */
617         do {
618             int res;
619             char *seg_name;
620             char *delim;
621             int temp_slash=0;
622         
623             /* We have no trailing slash, but we sure would appreciate one...
624              */
625             if (sec_idx && r->filename[filename_len-1] != '/') {
626                 r->filename[filename_len++] = '/';
627                 r->filename[filename_len] = 0;
628                 temp_slash=1;
629             }
630
631             /* Begin *this* level by looking for matching <Directory> sections
632              * from the server config.
633              */
634             for (; sec_idx < num_sec; ++sec_idx) {
635
636                 ap_conf_vector_t *entry_config = sec_ent[sec_idx];
637                 core_dir_config *entry_core;
638                 entry_core = ap_get_module_config(entry_config, &core_module);
639
640                 /* No more possible matches for this many segments? 
641                  * We are done when we find relative/regex/longer components.
642                  */
643                 if (entry_core->r || entry_core->d_components > seg) {
644                     break;
645                 }
646
647                 /* We will never skip '0' element components, e.g. plain old
648                  * <Directory >, and <Directory "/"> are classified as zero 
649                  * so that Win32/Netware/OS2 etc all pick them up.
650                  * Otherwise, skip over the mismatches.
651                  */
652                 if (entry_core->d_components
653                       && (entry_core->d_is_fnmatch
654                             ? (apr_fnmatch(entry_core->d, r->filename, 
655                                            FNM_PATHNAME) != APR_SUCCESS)
656                             : (strcmp(r->filename, entry_core->d) != 0))) {
657                     continue;
658                 }
659
660                 /* If we merged this same section last time, reuse it
661                  */
662                 if (matches) {
663                     if (last_walk->matched == sec_ent[sec_idx]) {
664                         now_merged = last_walk->merged;
665                         ++last_walk;
666                         --matches;
667                         goto minimerge;
668                     }
669                     /* We fell out of sync.  This is our own copy of walked,
670                      * so truncate the remaining matches and reset remaining.
671                      */
672                     cache->walked->nelts -= matches;
673                     matches = 0;
674                 }
675
676                 if (now_merged) {
677                     now_merged = ap_merge_per_dir_configs(r->pool, 
678                                                           now_merged,
679                                                           sec_ent[sec_idx]);
680                 }
681                 else {
682                     now_merged = sec_ent[sec_idx];
683                 }
684
685                 last_walk = (walk_walked_t*)apr_array_push(cache->walked);
686                 last_walk->matched = sec_ent[sec_idx];
687                 last_walk->merged = now_merged;
688
689                 /* Do a mini-merge to our globally-based running calculations of
690                  * core_dir->override and core_dir->opts, since now_merged
691                  * never considered the global config.  Of course, if there is 
692                  * no core config at this level, continue without a thought.
693                  * See core.c::merge_core_dir_configs() for explanation.
694                  */
695 minimerge:
696                 this_dir = ap_get_module_config(sec_ent[sec_idx], &core_module);
697
698                 if (!this_dir) {
699                     continue;
700                 }
701
702                 if (this_dir->opts & OPT_UNSET) {
703                     opts_add = (opts_add & ~this_dir->opts_remove) 
704                                | this_dir->opts_add;
705                     opts_remove = (opts_remove & ~this_dir->opts_add)
706                                 | this_dir->opts_remove;
707                     opts = (opts & ~opts_remove) | opts_add;
708                 }
709                 else {
710                     opts = this_dir->opts;
711                     opts_add = this_dir->opts_add;
712                     opts_remove = this_dir->opts_remove;
713                 }
714                 if (!(this_dir->override & OR_UNSET)) {
715                     override = this_dir->override;
716                 }
717             }
718
719             /* If .htaccess files are enabled, check for one, provided we
720              * have reached a real path.
721              */
722             if (seg >= startseg && override) {
723                 ap_conf_vector_t *htaccess_conf = NULL;
724
725                 res = ap_parse_htaccess(&htaccess_conf, r, override,
726                                         apr_pstrdup(r->pool, r->filename),
727                                         sconf->access_name);
728                 if (res) {
729                     return res;
730                 }
731
732                 if (htaccess_conf) {
733
734                     /* If we merged this same htaccess last time, reuse it...
735                      * this wouldn't work except that we cache the htaccess
736                      * sections for the lifetime of the request, so we match 
737                      * the same conf.  Good planning (no, pure luck ;)
738                      */
739                     if (matches) {
740                         if (last_walk->matched == htaccess_conf) {
741                             now_merged = last_walk->merged;
742                             ++last_walk;
743                             --matches;
744                             goto minimerge2;
745                         }
746                         /* We fell out of sync.  This is our own copy of walked,
747                          * so truncate the remaining matches and reset 
748                          * remaining.
749                          */
750                         cache->walked->nelts -= matches;
751                         matches = 0;
752                     }
753
754                     if (now_merged) {
755                         now_merged = ap_merge_per_dir_configs(r->pool, 
756                                                               now_merged,
757                                                               htaccess_conf);
758                     }
759                     else {
760                         now_merged = htaccess_conf;
761                     }
762
763                     last_walk = (walk_walked_t*)apr_array_push(cache->walked);
764                     last_walk->matched = htaccess_conf;
765                     last_walk->merged = now_merged;
766
767                     /* Do a mini-merge to our globally-based running 
768                      * calculations of core_dir->override and core_dir->opts,
769                      * since now_merged never considered the global config.
770                      * Of course, if there is no core config at this level, 
771                      * continue without a thought.
772                      * See core.c::merge_core_dir_configs() for explanation.
773                      */
774 minimerge2:
775                     this_dir = ap_get_module_config(htaccess_conf,
776                                                     &core_module);
777
778                     if (this_dir) {
779                         if (this_dir->opts & OPT_UNSET) {
780                             opts_add = (opts_add & ~this_dir->opts_remove)
781                                 | this_dir->opts_add;
782                             opts_remove = (opts_remove & ~this_dir->opts_add)
783                                 | this_dir->opts_remove;
784                             opts = (opts & ~opts_remove) | opts_add;
785                         }
786                         else {
787                             opts = this_dir->opts;
788                             opts_add = this_dir->opts_add;
789                             opts_remove = this_dir->opts_remove;
790                         }
791                         if (!(this_dir->override & OR_UNSET)) {
792                             override = this_dir->override;
793                         }
794                     }
795                 }
796             }
797
798             /* That temporary trailing slash was useful, now drop it.
799              */
800             if (temp_slash) {
801                 r->filename[--filename_len] = '\0';
802             }
803
804             /* Time for all good things to come to an end?
805              */
806             if (!r->path_info || !*r->path_info) {
807                 break;
808             }
809
810             /* Now it's time for the next segment... 
811              * We will assume the next element is an end node, and fix it up
812              * below as necessary...
813              */
814         
815             seg_name = r->filename + filename_len;
816             delim = strchr(r->path_info + (*r->path_info == '/' ? 1 : 0), '/');
817             if (delim) {
818                 size_t path_info_len = delim - r->path_info;
819                 *delim = '\0';
820                 memcpy(seg_name, r->path_info, path_info_len + 1);
821                 filename_len += path_info_len;
822                 r->path_info = delim;
823                 *delim = '/';
824             }
825             else {
826                 size_t path_info_len = strlen(r->path_info);
827                 memcpy(seg_name, r->path_info, path_info_len + 1);
828                 filename_len += path_info_len;
829                 r->path_info += path_info_len;
830             }
831             if (*seg_name == '/') 
832                 ++seg_name;
833         
834             /* If nothing remained but a '/' string, we are finished
835              */
836             if (!*seg_name) {
837                 break;
838             }
839
840             /* First optimization;
841              * If...we knew r->filename was a file, and
842              * if...we have strict (case-sensitive) filenames, or
843              *      we know the canonical_filename matches to _this_ name, and
844              * if...we have allowed symlinks
845              * skip the lstat and dummy up an APR_DIR value for thisinfo.
846              */
847             if (r->finfo.filetype 
848 #ifdef CASE_BLIND_FILESYSTEM
849                 && (r->canonical_filename 
850                     && (strncmp(r->filename, 
851                                 r->canonical_filename, filename_len) == 0))
852 #endif
853                 && ((opts & (OPT_SYM_OWNER | OPT_SYM_LINKS)) == OPT_SYM_LINKS)) 
854             {
855
856                 thisinfo.filetype = APR_DIR;
857                 ++seg;
858                 continue;
859             }
860
861             /* We choose apr_lstat here, rather that apr_stat, so that we
862              * capture this path object rather than its target.  We will
863              * replace the info with our target's info below.  We especially
864              * want the name of this 'link' object, not the name of its
865              * target, if we are fixing the filename case/resolving aliases.
866              */
867             rv = apr_lstat(&thisinfo, r->filename,
868                            APR_FINFO_MIN | APR_FINFO_NAME, r->pool);
869
870             if (APR_STATUS_IS_ENOENT(rv)) {
871                 /* Nothing?  That could be nice.  But our directory
872                  * walk is done.
873                  */
874                 thisinfo.filetype = APR_NOFILE;
875                 break;
876             }
877             else if (APR_STATUS_IS_EACCES(rv)) {
878                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
879                               "access to %s denied", r->uri);
880                 return r->status = HTTP_FORBIDDEN;
881             }
882             else if ((rv != APR_SUCCESS && rv != APR_INCOMPLETE) 
883                      || !(thisinfo.valid & APR_FINFO_TYPE)) {
884                 /* If we hit ENOTDIR, we must have over-optimized, deny 
885                  * rather than assume not found.
886                  */
887                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
888                               "access to %s failed", r->uri);
889                 return r->status = HTTP_FORBIDDEN;
890             }
891
892             if ((res = check_safe_file(r))) {
893                 r->status = res;
894                 return res;
895             }
896
897             /* Fix up the path now if we have a name, and they don't agree
898              */
899             if ((thisinfo.valid & APR_FINFO_NAME) 
900                 && strcmp(seg_name, thisinfo.name)) {
901                 /* TODO: provide users an option that an internal/external
902                  * redirect is required here?  We need to walk the URI and
903                  * filename in tandem to properly correlate these.
904                  */
905                 strcpy(seg_name, thisinfo.name);
906                 filename_len = strlen(r->filename);
907             }
908
909             if (thisinfo.filetype == APR_LNK) {
910                 /* Is this a possibly acceptable symlink?
911                  */
912                 if ((res = resolve_symlink(r->filename, &thisinfo, 
913                                            opts, r->pool)) != OK) {
914                     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
915                                   "Symbolic link not allowed: %s",
916                                   r->filename);
917                     return r->status = res;
918                 }
919
920                 /* Ok, we are done with the link's info, test the real target
921                  */
922                 if (thisinfo.filetype == APR_REG) {
923                     /* That was fun, nothing left for us here
924                      */
925                     break;
926                 }
927                 else if (thisinfo.filetype != APR_DIR) {
928                     ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
929                              "symlink doesn't point to a file or directory: %s",
930                              r->filename);
931                     return r->status = HTTP_FORBIDDEN;
932                 }
933             }
934
935             ++seg;
936         } while (thisinfo.filetype == APR_DIR);
937
938         /* If we have _not_ optimized, this is the time to recover
939          * the final stat result.
940          */
941         if (!r->finfo.filetype || r->finfo.filetype == APR_LNK) {
942             r->finfo = thisinfo;
943         }
944
945         /* Now splice the saved path_info back onto any new path_info
946          */
947         if (save_path_info) {
948             if (r->path_info && *r->path_info) {
949                 r->path_info = ap_make_full_path(r->pool, r->path_info, 
950                                                  save_path_info);
951             }
952             else {
953                 r->path_info = save_path_info;
954             }
955         }
956
957         /*
958          * Now we'll deal with the regexes, note we pick up sec_idx
959          * where we left off (we gave up after we hit entry_core->r)
960          */
961         for (; sec_idx < num_sec; ++sec_idx) {
962
963             core_dir_config *entry_core; 
964             entry_core = ap_get_module_config(sec_ent[sec_idx], &core_module);
965
966             if (!entry_core->r) {
967                 continue;
968             }
969
970             if (ap_regexec(entry_core->r, r->filename, 0, NULL, REG_NOTEOL)) {
971                 continue;
972             }
973
974             /* If we merged this same section last time, reuse it
975              */
976             if (matches) {
977                 if (last_walk->matched == sec_ent[sec_idx]) {
978                     now_merged = last_walk->merged;
979                     ++last_walk;
980                     --matches;
981                     goto minimerge;
982                 }
983                 /* We fell out of sync.  This is our own copy of walked,
984                  * so truncate the remaining matches and reset remaining.
985                  */
986                 cache->walked->nelts -= matches;
987                 matches = 0;
988             }
989
990             if (now_merged) {
991                 now_merged = ap_merge_per_dir_configs(r->pool, 
992                                                       now_merged,
993                                                       sec_ent[sec_idx]);
994             }
995             else {
996                 now_merged = sec_ent[sec_idx];
997             }
998
999             last_walk = (walk_walked_t*)apr_array_push(cache->walked);
1000             last_walk->matched = sec_ent[sec_idx];
1001             last_walk->merged = now_merged;
1002         }
1003
1004         /* Whoops - everything matched in sequence, but the original walk
1005          * found some additional matches.  Truncate them.
1006          */
1007         if (matches) {
1008             cache->walked->nelts -= matches;
1009         }
1010     }
1011
1012 /* It seems this shouldn't be needed anymore.  We translated the
1013  x symlink above into a real resource, and should have died up there.
1014  x Even if we keep this, it needs more thought (maybe an r->file_is_symlink)
1015  x perhaps it should actually happen in file_walk, so we catch more
1016  x obscure cases in autoindex sub requests, etc.
1017  x
1018  x    * Symlink permissions are determined by the parent.  If the request is
1019  x    * for a directory then applying the symlink test here would use the
1020  x    * permissions of the directory as opposed to its parent.  Consider a
1021  x    * symlink pointing to a dir with a .htaccess disallowing symlinks.  If
1022  x    * you access /symlink (or /symlink/) you would get a 403 without this
1023  x    * APR_DIR test.  But if you accessed /symlink/index.html, for example,
1024  x    * you would *not* get the 403.
1025  x
1026  x   if (r->finfo.filetype != APR_DIR
1027  x       && (res = resolve_symlink(r->filename, r->info, ap_allow_options(r),
1028  x                                 r->pool))) {
1029  x       ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
1030  x                     "Symbolic link not allowed: %s", r->filename);
1031  x       return res;
1032  x   }
1033  */
1034
1035     if (r->finfo.filetype == APR_DIR) {
1036         cache->cached = r->filename;
1037     }
1038     else {
1039         cache->cached = ap_make_dirstr_parent(r->pool, r->filename);
1040     }
1041
1042     cache->dir_conf_tested = sec_ent;
1043     cache->dir_conf_merged = r->per_dir_config;
1044
1045     /* Merge our cache->dir_conf_merged construct with the r->per_dir_configs,
1046      * and note the end result to (potentially) skip this step next time.
1047      */
1048     if (now_merged) {
1049         r->per_dir_config = ap_merge_per_dir_configs(r->pool,
1050                                                      r->per_dir_config,
1051                                                      now_merged);
1052     }
1053     cache->per_dir_result = r->per_dir_config;
1054
1055     return OK;
1056 }
1057
1058
1059 AP_DECLARE(int) ap_location_walk(request_rec *r)
1060 {
1061     ap_conf_vector_t *now_merged = NULL;
1062     core_server_config *sconf = ap_get_module_config(r->server->module_config,
1063                                                      &core_module);
1064     ap_conf_vector_t **sec_ent = (ap_conf_vector_t **) sconf->sec_url->elts;
1065     int num_sec = sconf->sec_url->nelts;
1066     walk_cache_t *cache;
1067     const char *entry_uri;
1068
1069     cache = prep_walk_cache("ap_location_walk::cache", r);
1070     
1071     /* No tricks here, there are no <Locations > to parse in this vhost.
1072      * We won't destroy the cache, just in case _this_ redirect is later
1073      * redirected again to a vhost with <Location > blocks to optimize.
1074      */
1075     if (!num_sec) {
1076         return OK;
1077     }
1078
1079     /* Location and LocationMatch differ on their behaviour w.r.t. multiple
1080      * slashes.  Location matches multiple slashes with a single slash,
1081      * LocationMatch doesn't.  An exception, for backwards brokenness is
1082      * absoluteURIs... in which case neither match multiple slashes.
1083      */
1084     if (r->uri[0] != '/') {
1085         entry_uri = r->uri;
1086     }
1087     else {
1088         char *uri = apr_pstrdup(r->pool, r->uri);
1089         ap_no2slash(uri);
1090         entry_uri = uri;
1091     }
1092
1093     /* If we have an cache->cached location that matches r->uri,
1094      * and the vhost's list of locations hasn't changed, we can skip
1095      * rewalking the location_walk entries.
1096      */
1097     if (cache->cached
1098         && (cache->dir_conf_tested == sec_ent) 
1099         && (strcmp(entry_uri, cache->cached) == 0)) {
1100         /* Well this looks really familiar!  If our end-result (per_dir_result)
1101          * didn't change, we have absolutely nothing to do :)  
1102          * Otherwise (as is the case with most dir_merged/file_merged requests)
1103          * we must merge our dir_conf_merged onto this new r->per_dir_config.
1104          */
1105         if (r->per_dir_config == cache->per_dir_result) {
1106             return OK;
1107         }
1108         if (r->per_dir_config == cache->dir_conf_merged) {
1109             r->per_dir_config = cache->per_dir_result;
1110             return OK;
1111         }
1112         if (cache->walked->nelts) {
1113             now_merged = ((walk_walked_t*)cache->walked->elts)
1114                                             [cache->walked->nelts - 1].merged;
1115         }
1116     }
1117     else {
1118         /* We start now_merged from NULL since we want to build 
1119          * a locations list that can be merged to any vhost.
1120          */
1121         int len, sec_idx;
1122         int matches = cache->walked->nelts;
1123         walk_walked_t *last_walk = (walk_walked_t*)cache->walked->elts;
1124         cache->cached = entry_uri;
1125
1126         /* Go through the location entries, and check for matches.
1127          * We apply the directive sections in given order, we should
1128          * really try them with the most general first.
1129          */
1130         for (sec_idx = 0; sec_idx < num_sec; ++sec_idx) {
1131
1132             core_dir_config *entry_core; 
1133             entry_core = ap_get_module_config(sec_ent[sec_idx], &core_module);
1134             
1135             /* ### const strlen can be optimized in location config parsing */
1136             len = strlen(entry_core->d);
1137
1138             /* Test the regex, fnmatch or string as appropriate.
1139              * If it's a strcmp, and the <Location > pattern was 
1140              * not slash terminated, then this uri must be slash
1141              * terminated (or at the end of the string) to match.
1142              */
1143             if (entry_core->r 
1144                 ? ap_regexec(entry_core->r, r->uri, 0, NULL, 0)
1145                 : (entry_core->d_is_fnmatch
1146                    ? apr_fnmatch(entry_core->d, cache->cached, FNM_PATHNAME)
1147                    : (strncmp(entry_core->d, cache->cached, len)
1148                       ||   (entry_core->d[len - 1] != '/'
1149                             && cache->cached[len] != '/' 
1150                             && cache->cached[len] != '\0')))) {
1151                 continue;
1152             }
1153
1154             /* If we merged this same section last time, reuse it
1155              */
1156             if (matches) {
1157                 if (last_walk->matched == sec_ent[sec_idx]) {
1158                     now_merged = last_walk->merged;
1159                     ++last_walk;
1160                     --matches;
1161                     continue;
1162                 }
1163                 /* We fell out of sync.  This is our own copy of walked,
1164                  * so truncate the remaining matches and reset remaining.
1165                  */
1166                 cache->walked->nelts -= matches;
1167                 matches = 0;
1168             }
1169
1170             if (now_merged) {
1171                 now_merged = ap_merge_per_dir_configs(r->pool, 
1172                                                       now_merged,
1173                                                       sec_ent[sec_idx]);
1174             }
1175             else {
1176                 now_merged = sec_ent[sec_idx];
1177             }
1178
1179             last_walk = (walk_walked_t*)apr_array_push(cache->walked);
1180             last_walk->matched = sec_ent[sec_idx];
1181             last_walk->merged = now_merged;
1182         }
1183         /* Whoops - everything matched in sequence, but the original walk
1184          * found some additional matches.  Truncate them.
1185          */
1186         if (matches) {
1187             cache->walked->nelts -= matches;
1188         }
1189     }
1190
1191     cache->dir_conf_tested = sec_ent;
1192     cache->dir_conf_merged = r->per_dir_config;
1193
1194     /* Merge our cache->dir_conf_merged construct with the r->per_dir_configs,
1195      * and note the end result to (potentially) skip this step next time.
1196      */
1197     if (now_merged) {
1198         r->per_dir_config = ap_merge_per_dir_configs(r->pool,
1199                                                      r->per_dir_config,
1200                                                      now_merged);
1201     }
1202     cache->per_dir_result = r->per_dir_config;
1203
1204     return OK;
1205 }
1206
1207 AP_DECLARE(int) ap_file_walk(request_rec *r)
1208 {
1209     ap_conf_vector_t *now_merged = NULL;
1210     core_dir_config *dconf = ap_get_module_config(r->per_dir_config,
1211                                                   &core_module);
1212     ap_conf_vector_t **sec_ent = (ap_conf_vector_t **) dconf->sec_file->elts;
1213     int num_sec = dconf->sec_file->nelts;
1214     walk_cache_t *cache;
1215     const char *test_file;
1216
1217     /* To allow broken modules to proceed, we allow missing filenames to pass.
1218      * We will catch it later if it's heading for the core handler.  
1219      * directory_walk already posted an INFO note for module debugging.
1220      */
1221      if (r->filename == NULL) {
1222         return OK;
1223     }
1224
1225     cache = prep_walk_cache("ap_file_walk::cache", r);
1226
1227     /* No tricks here, there are just no <Files > to parse in this context.
1228      * We won't destroy the cache, just in case _this_ redirect is later
1229      * redirected again to a context containing the same or similar <Files >.
1230      */
1231     if (!num_sec) {
1232         return OK;
1233     }
1234
1235     /* Get the basename .. and copy for the cache just 
1236      * in case r->filename is munged by another module
1237      */
1238     test_file = strrchr(r->filename, '/');
1239     if (test_file == NULL) {
1240         test_file = apr_pstrdup(r->pool, r->filename);
1241     }
1242     else {
1243         test_file = apr_pstrdup(r->pool, ++test_file);
1244     }
1245
1246     /* If we have an cache->cached file name that matches test_file,
1247      * and the directory's list of file sections hasn't changed, we 
1248      * can skip rewalking the file_walk entries.
1249      */
1250     if (cache->cached
1251         && (cache->dir_conf_tested == sec_ent) 
1252         && (strcmp(test_file, cache->cached) == 0)) {
1253         /* Well this looks really familiar!  If our end-result (per_dir_result)
1254          * didn't change, we have absolutely nothing to do :)  
1255          * Otherwise (as is the case with most dir_merged requests)
1256          * we must merge our dir_conf_merged onto this new r->per_dir_config.
1257          */
1258         if (r->per_dir_config == cache->per_dir_result) {
1259             return OK;
1260         }
1261         if (r->per_dir_config == cache->dir_conf_merged) {
1262             r->per_dir_config = cache->per_dir_result;
1263             return OK;
1264         }
1265         if (cache->walked->nelts) {
1266             now_merged = ((walk_walked_t*)cache->walked->elts)
1267                 [cache->walked->nelts - 1].merged;
1268         }
1269     }
1270     else {
1271         /* We start now_merged from NULL since we want to build 
1272          * a file section list that can be merged to any dir_walk.
1273          */
1274         int sec_idx;
1275         int matches = cache->walked->nelts;
1276         walk_walked_t *last_walk = (walk_walked_t*)cache->walked->elts;
1277         cache->cached = test_file;
1278
1279         /* Go through the location entries, and check for matches.
1280          * We apply the directive sections in given order, we should
1281          * really try them with the most general first.
1282          */
1283         for (sec_idx = 0; sec_idx < num_sec; ++sec_idx) {
1284         
1285             core_dir_config *entry_core;
1286             entry_core = ap_get_module_config(sec_ent[sec_idx], &core_module);
1287
1288             if (entry_core->r
1289                 ? ap_regexec(entry_core->r, cache->cached , 0, NULL, 0)
1290                 : (entry_core->d_is_fnmatch
1291                    ? apr_fnmatch(entry_core->d, cache->cached, FNM_PATHNAME)
1292                    : strcmp(entry_core->d, cache->cached))) {
1293                 continue;
1294             }
1295
1296             /* If we merged this same section last time, reuse it
1297              */
1298             if (matches) {
1299                 if (last_walk->matched == sec_ent[sec_idx]) {
1300                     now_merged = last_walk->merged;
1301                     ++last_walk;
1302                     --matches;
1303                     continue;
1304                 }
1305                 /* We fell out of sync.  This is our own copy of walked,
1306                  * so truncate the remaining matches and reset remaining.
1307                  */
1308                 cache->walked->nelts -= matches;
1309                 matches = 0;
1310             }
1311
1312             if (now_merged) {
1313                 now_merged = ap_merge_per_dir_configs(r->pool, 
1314                                                       now_merged,
1315                                                       sec_ent[sec_idx]);
1316             }
1317             else {
1318                 now_merged = sec_ent[sec_idx];
1319             }
1320
1321             last_walk = (walk_walked_t*)apr_array_push(cache->walked);
1322             last_walk->matched = sec_ent[sec_idx];
1323             last_walk->merged = now_merged;
1324         }
1325         /* Whoops - everything matched in sequence, but the original walk
1326          * found some additional matches.  Truncate them.
1327          */
1328         if (matches) {
1329             cache->walked->nelts -= matches;
1330         }
1331     }
1332
1333     cache->dir_conf_tested = sec_ent;
1334     cache->dir_conf_merged = r->per_dir_config;
1335
1336     /* Merge our cache->dir_conf_merged construct with the r->per_dir_configs,
1337      * and note the end result to (potentially) skip this step next time.
1338      */
1339     if (now_merged) {
1340         r->per_dir_config = ap_merge_per_dir_configs(r->pool,
1341                                                      r->per_dir_config,
1342                                                      now_merged);
1343     }
1344     cache->per_dir_result = r->per_dir_config;
1345
1346     return OK;
1347 }
1348
1349 /*****************************************************************
1350  *
1351  * The sub_request mechanism.
1352  *
1353  * Fns to look up a relative URI from, e.g., a map file or SSI document.
1354  * These do all access checks, etc., but don't actually run the transaction
1355  * ... use run_sub_req below for that.  Also, be sure to use destroy_sub_req
1356  * as appropriate if you're likely to be creating more than a few of these.
1357  * (An early Apache version didn't destroy the sub_reqs used in directory
1358  * indexing.  The result, when indexing a directory with 800-odd files in
1359  * it, was massively excessive storage allocation).
1360  *
1361  * Note more manipulation of protocol-specific vars in the request
1362  * structure...
1363  */
1364
1365 static request_rec *make_sub_request(const request_rec *r, 
1366                                      ap_filter_t *next_filter)
1367 {
1368     apr_pool_t *rrp;
1369     request_rec *rnew;
1370     
1371     apr_pool_create(&rrp, r->pool);
1372     rnew = apr_pcalloc(rrp, sizeof(request_rec));
1373     rnew->pool = rrp;
1374
1375     rnew->hostname       = r->hostname;
1376     rnew->request_time   = r->request_time;
1377     rnew->connection     = r->connection;
1378     rnew->server         = r->server;
1379
1380     rnew->request_config = ap_create_request_config(rnew->pool);
1381
1382     /* Start a clean config from this subrequest's vhost.  Optimization in
1383      * Location/File/Dir walks from the parent request assure that if the
1384      * config blocks of the subrequest match the parent request, no merges
1385      * will actually occur (and generally a minimal number of merges are 
1386      * required, even if the parent and subrequest aren't quite identical.)
1387      */
1388     rnew->per_dir_config = r->server->lookup_defaults;
1389
1390     rnew->htaccess       = r->htaccess;
1391     rnew->allowed_methods = ap_make_method_list(rnew->pool, 2);
1392
1393     /* make a copy of the allowed-methods list */
1394     ap_copy_method_list(rnew->allowed_methods, r->allowed_methods);
1395
1396     /* start with the same set of output filters */
1397     if (next_filter) {
1398         rnew->output_filters = next_filter;
1399     }
1400     else {
1401         rnew->output_filters = r->output_filters;
1402     }
1403     ap_add_output_filter("SUBREQ_CORE", NULL, rnew, rnew->connection); 
1404
1405     /* no input filters for a subrequest */
1406
1407     ap_set_sub_req_protocol(rnew, r);
1408
1409     /* We have to run this after we fill in sub req vars, 
1410      * or the r->main pointer won't be setup
1411      */
1412     ap_run_create_request(rnew);
1413
1414     return rnew;
1415 }
1416
1417 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_sub_req_output_filter(ap_filter_t *f,
1418                                                               apr_bucket_brigade *bb)
1419 {
1420     apr_bucket *e = APR_BRIGADE_LAST(bb);
1421
1422     if (APR_BUCKET_IS_EOS(e)) {
1423         apr_bucket_delete(e);
1424     }
1425     if (!APR_BRIGADE_EMPTY(bb)) {
1426         return ap_pass_brigade(f->next, bb);
1427     }
1428     else {
1429         return APR_SUCCESS;
1430     }
1431 }
1432
1433  
1434 AP_DECLARE(int) ap_some_auth_required(request_rec *r)
1435 {
1436     /* Is there a require line configured for the type of *this* req? */
1437  
1438     const apr_array_header_t *reqs_arr = ap_requires(r);
1439     require_line *reqs;
1440     int i;
1441  
1442     if (!reqs_arr) {
1443         return 0;
1444     }
1445  
1446     reqs = (require_line *) reqs_arr->elts;
1447  
1448     for (i = 0; i < reqs_arr->nelts; ++i) {
1449         if (reqs[i].method_mask & (AP_METHOD_BIT << r->method_number)) {
1450             return 1;
1451         }
1452     }
1453  
1454     return 0;
1455
1456
1457
1458 AP_DECLARE(request_rec *) ap_sub_req_method_uri(const char *method,
1459                                                 const char *new_file,
1460                                                 const request_rec *r,
1461                                                 ap_filter_t *next_filter)
1462 {
1463     request_rec *rnew;
1464     int res;
1465     char *udir;
1466
1467     rnew = make_sub_request(r, next_filter);
1468
1469     /* would be nicer to pass "method" to ap_set_sub_req_protocol */
1470     rnew->method = method;
1471     rnew->method_number = ap_method_number_of(method);
1472
1473     if (new_file[0] == '/') {
1474         ap_parse_uri(rnew, new_file);
1475     }
1476     else {
1477         udir = ap_make_dirstr_parent(rnew->pool, r->uri);
1478         udir = ap_escape_uri(rnew->pool, udir);    /* re-escape it */
1479         ap_parse_uri(rnew, ap_make_full_path(rnew->pool, udir, new_file));
1480     }
1481
1482     if ((res = ap_process_request_internal(rnew))) {
1483         rnew->status = res;
1484     }
1485
1486     return rnew;
1487 }
1488
1489 AP_DECLARE(request_rec *) ap_sub_req_lookup_uri(const char *new_file,
1490                                                 const request_rec *r,
1491                                                 ap_filter_t *next_filter)
1492 {
1493     return ap_sub_req_method_uri("GET", new_file, r, next_filter);
1494 }
1495
1496 AP_DECLARE(request_rec *) ap_sub_req_lookup_dirent(const apr_finfo_t *dirent,
1497                                                    const request_rec *r,
1498                                                    ap_filter_t *next_filter)
1499 {
1500     request_rec *rnew;
1501     int res;
1502     char *fdir;
1503     char *udir;
1504
1505     rnew = make_sub_request(r, next_filter);
1506
1507     /* Special case: we are looking at a relative lookup in the same directory. 
1508      * This is 100% safe, since dirent->name just came from the filesystem.
1509      */
1510     udir = ap_make_dirstr_parent(rnew->pool, r->uri);
1511     rnew->uri = ap_make_full_path(rnew->pool, udir, dirent->name);
1512     fdir = ap_make_dirstr_parent(rnew->pool, r->filename);
1513     rnew->filename = ap_make_full_path(rnew->pool, fdir, dirent->name);
1514     if (r->canonical_filename == r->filename) {
1515         rnew->canonical_filename = rnew->filename;
1516     }
1517     
1518     /* XXX This is now less relevant; we will do a full location walk
1519      * these days for this case.  Preserve the apr_stat results, and 
1520      * perhaps we also tag that symlinks were tested and/or found for 
1521      * r->filename.
1522      */
1523     rnew->per_dir_config = r->server->lookup_defaults;
1524
1525     if ((dirent->valid & APR_FINFO_MIN) != APR_FINFO_MIN) {
1526         /*
1527          * apr_dir_read isn't very complete on this platform, so
1528          * we need another apr_lstat (or simply apr_stat if we allow
1529          * all symlinks here.)  If this is an APR_LNK that resolves 
1530          * to an APR_DIR, then we will rerun everything anyways... 
1531          * this should be safe.
1532          */
1533         apr_status_t rv;
1534         if (ap_allow_options(rnew) & OPT_SYM_LINKS) {
1535             if (((rv = apr_stat(&rnew->finfo, rnew->filename,
1536                                 APR_FINFO_MIN, rnew->pool)) != APR_SUCCESS)
1537                 && (rv != APR_INCOMPLETE)) {
1538                 rnew->finfo.filetype = 0;
1539             }
1540         }
1541         else {
1542             if (((rv = apr_lstat(&rnew->finfo, rnew->filename,
1543                                  APR_FINFO_MIN, rnew->pool)) != APR_SUCCESS)
1544                 && (rv != APR_INCOMPLETE)) {
1545                 rnew->finfo.filetype = 0;
1546             }
1547         }
1548     }
1549     else {
1550         memcpy(&rnew->finfo, dirent, sizeof(apr_finfo_t));
1551     }
1552
1553     if (rnew->finfo.filetype == APR_LNK) {
1554         /*
1555          * Resolve this symlink.  We should tie this back to dir_walk's cache
1556          */
1557         if ((res = resolve_symlink(rnew->filename, &rnew->finfo, 
1558                                    ap_allow_options(rnew), rnew->pool))
1559             != OK) {
1560             rnew->status = res;
1561             return rnew;
1562         }
1563     }
1564
1565     if (rnew->finfo.filetype == APR_DIR) {
1566         /* ### Would be real nice if apr_make_full_path overallocated 
1567          * the buffer by one character instead of a complete copy.
1568          */
1569         rnew->filename = apr_pstrcat(rnew->pool, rnew->filename, "/", NULL);
1570         rnew->uri = apr_pstrcat(rnew->pool, rnew->uri, "/", NULL);
1571         if (r->canonical_filename == r->filename) {
1572             rnew->canonical_filename = rnew->filename;
1573         }
1574     }
1575
1576     ap_parse_uri(rnew, rnew->uri);    /* fill in parsed_uri values */
1577
1578     if ((res = ap_process_request_internal(rnew))) {
1579         rnew->status = res;
1580     }
1581
1582     return rnew;
1583 }
1584
1585 AP_DECLARE(request_rec *) ap_sub_req_lookup_file(const char *new_file,
1586                                                  const request_rec *r,
1587                                                  ap_filter_t *next_filter)
1588 {
1589     request_rec *rnew;
1590     int res;
1591     char *fdir;
1592     apr_size_t fdirlen;
1593
1594     rnew = make_sub_request(r, next_filter);
1595
1596     fdir = ap_make_dirstr_parent(rnew->pool, r->filename);
1597     fdirlen = strlen(fdir);
1598
1599     /* Translate r->filename, if it was canonical, it stays canonical
1600      */
1601     if (r->canonical_filename == r->filename) {
1602         rnew->canonical_filename = (char*)(1);
1603     }
1604     if (apr_filepath_merge(&rnew->filename, fdir, new_file,
1605                            APR_FILEPATH_TRUENAME, rnew->pool) != APR_SUCCESS) {
1606         rnew->status = HTTP_FORBIDDEN;
1607         return rnew;
1608     }
1609     if (rnew->canonical_filename) {
1610         rnew->canonical_filename = rnew->filename;
1611     }
1612
1613     /*
1614      * Check for a special case... if there are no '/' characters in new_file
1615      * at all, and the path was the same, then we are looking at a relative 
1616      * lookup in the same directory.  Fixup the URI to match.
1617      */
1618
1619     if (strncmp(rnew->filename, fdir, fdirlen) == 0
1620         && rnew->filename[fdirlen] 
1621         && ap_strchr_c(rnew->filename + fdirlen, '/') == NULL) {
1622         apr_status_t rv;
1623         if (ap_allow_options(rnew) & OPT_SYM_LINKS) {
1624             if (((rv = apr_stat(&rnew->finfo, rnew->filename,
1625                                 APR_FINFO_MIN, rnew->pool)) != APR_SUCCESS)
1626                 && (rv != APR_INCOMPLETE)) {
1627                 rnew->finfo.filetype = 0;
1628             }
1629         }
1630         else {
1631             if (((rv = apr_lstat(&rnew->finfo, rnew->filename,
1632                                  APR_FINFO_MIN, rnew->pool)) != APR_SUCCESS)
1633                 && (rv != APR_INCOMPLETE)) {
1634                 rnew->finfo.filetype = 0;
1635             }
1636         }
1637
1638         if (r->uri && *r->uri) {
1639             char *udir = ap_make_dirstr_parent(rnew->pool, r->uri);
1640             rnew->uri = ap_make_full_path(rnew->pool, udir,
1641                                           rnew->filename + fdirlen);
1642             ap_parse_uri(rnew, rnew->uri);    /* fill in parsed_uri values */
1643         }
1644         else {
1645             ap_parse_uri(rnew, new_file);        /* fill in parsed_uri values */
1646             rnew->uri = apr_pstrdup(rnew->pool, "");
1647         }
1648     }
1649     else {
1650         /* XXX: @@@: What should be done with the parsed_uri values?
1651          * We would be better off stripping down to the 'common' elements
1652          * of the path, then reassembling the URI as best as we can.
1653          */
1654         ap_parse_uri(rnew, new_file);        /* fill in parsed_uri values */
1655         /*
1656          * XXX: this should be set properly like it is in the same-dir case
1657          * but it's actually sometimes to impossible to do it... because the
1658          * file may not have a uri associated with it -djg
1659          */
1660         rnew->uri = apr_pstrdup(rnew->pool, "");
1661     }
1662
1663     if ((res = ap_process_request_internal(rnew))) {
1664         rnew->status = res;
1665     }
1666
1667     return rnew;
1668 }
1669
1670 AP_DECLARE(int) ap_run_sub_req(request_rec *r)
1671 {
1672     int retval;
1673
1674     retval = ap_invoke_handler(r);
1675     ap_finalize_sub_req_protocol(r);
1676     return retval;
1677 }
1678
1679 AP_DECLARE(void) ap_destroy_sub_req(request_rec *r)
1680 {
1681     /* Reclaim the space */
1682     apr_pool_destroy(r->pool);
1683 }
1684
1685 /*
1686  * Function to set the r->mtime field to the specified value if it's later
1687  * than what's already there.
1688  */
1689 AP_DECLARE(void) ap_update_mtime(request_rec *r, apr_time_t dependency_mtime)
1690 {
1691     if (r->mtime < dependency_mtime) {
1692         r->mtime = dependency_mtime;
1693     }
1694 }
1695
1696 /*
1697  * Is it the initial main request, which we only get *once* per HTTP request?
1698  */
1699 AP_DECLARE(int) ap_is_initial_req(request_rec *r)
1700 {
1701     return
1702         (r->main == NULL)       /* otherwise, this is a sub-request */
1703         &&
1704         (r->prev == NULL);      /* otherwise, this is an internal redirect */
1705
1706