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