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