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