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