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