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