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