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