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