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