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