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