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