]> granicus.if.org Git - apache/blob - server/request.c
mod_proxy: Fix ProxyRemoteMatch directive.
[apache] / server / request.c
1 /* Copyright 2001-2004 The 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         overrides_t override_opts;
422 } core_opts_t;
423
424 static void core_opts_merge(const ap_conf_vector_t *sec, core_opts_t *opts)
425 {
426     core_dir_config *this_dir = ap_get_module_config(sec, &core_module);
427
428     if (!this_dir) {
429         return;
430     }
431
432     if (this_dir->opts & OPT_UNSET) {
433         opts->add = (opts->add & ~this_dir->opts_remove)
434                    | this_dir->opts_add;
435         opts->remove = (opts->remove & ~this_dir->opts_add)
436                       | this_dir->opts_remove;
437         opts->opts = (opts->opts & ~opts->remove) | opts->add;
438     }
439     else {
440         opts->opts = this_dir->opts;
441         opts->add = this_dir->opts_add;
442         opts->remove = this_dir->opts_remove;
443     }
444
445     if (!(this_dir->override & OR_UNSET)) {
446         opts->override = this_dir->override;
447     }
448     if (!(this_dir->override_opts & OR_UNSET)) {
449         opts->override_opts = this_dir->override_opts;
450     }
451 }
452
453
454 /*****************************************************************
455  *
456  * Getting and checking directory configuration.  Also checks the
457  * FollowSymlinks and FollowSymOwner stuff, since this is really the
458  * only place that can happen (barring a new mid_dir_walk callout).
459  *
460  * We can't do it as an access_checker module function which gets
461  * called with the final per_dir_config, since we could have a directory
462  * with FollowSymLinks disabled, which contains a symlink to another
463  * with a .htaccess file which turns FollowSymLinks back on --- and
464  * access in such a case must be denied.  So, whatever it is that
465  * checks FollowSymLinks needs to know the state of the options as
466  * they change, all the way down.
467  */
468
469 AP_DECLARE(int) ap_directory_walk(request_rec *r)
470 {
471     ap_conf_vector_t *now_merged = NULL;
472     core_server_config *sconf = ap_get_module_config(r->server->module_config,
473                                                      &core_module);
474     ap_conf_vector_t **sec_ent = (ap_conf_vector_t **) sconf->sec_dir->elts;
475     int num_sec = sconf->sec_dir->nelts;
476     walk_cache_t *cache;
477     char *entry_dir;
478     apr_status_t rv;
479
480     /* XXX: Better (faster) tests needed!!!
481      *
482      * "OK" as a response to a real problem is not _OK_, but to allow broken
483      * modules to proceed, we will permit the not-a-path filename to pass the
484      * following two tests.  This behavior may be revoked in future versions
485      * of Apache.  We still must catch it later if it's heading for the core
486      * handler.  Leave INFO notes here for module debugging.
487      */
488     if (r->filename == NULL) {
489         ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
490                       "Module bug?  Request filename is missing for URI %s",
491                       r->uri);
492        return OK;
493     }
494
495     /* Canonicalize the file path without resolving filename case or aliases
496      * so we can begin by checking the cache for a recent directory walk.
497      * This call will ensure we have an absolute path in the same pass.
498      */
499     if ((rv = apr_filepath_merge(&entry_dir, NULL, r->filename,
500                                  APR_FILEPATH_NOTRELATIVE, r->pool))
501                   != APR_SUCCESS) {
502         ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
503                       "Module bug?  Request filename path %s is invalid or "
504                       "or not absolute for uri %s",
505                       r->filename, r->uri);
506         return OK;
507     }
508
509     /* XXX Notice that this forces path_info to be canonical.  That might
510      * not be desired by all apps.  However, some of those same apps likely
511      * have significant security holes.
512      */
513     r->filename = entry_dir;
514
515     cache = prep_walk_cache(AP_NOTE_DIRECTORY_WALK, r);
516
517     /* If this is not a dirent subrequest with a preconstructed
518      * r->finfo value, then we can simply stat the filename to
519      * save burning mega-cycles with unneeded stats - if this is
520      * an exact file match.  We don't care about failure... we
521      * will stat by component failing this meager attempt.
522      *
523      * It would be nice to distinguish APR_ENOENT from other
524      * types of failure, such as APR_ENOTDIR.  We can do something
525      * with APR_ENOENT, knowing that the path is good.
526      */
527     if (!r->finfo.filetype || r->finfo.filetype == APR_LNK) {
528         rv = apr_stat(&r->finfo, r->filename, APR_FINFO_MIN, r->pool);
529
530         /* some OSs will return APR_SUCCESS/APR_REG if we stat
531          * a regular file but we have '/' at the end of the name;
532          *
533          * other OSs will return APR_ENOTDIR for that situation;
534          *
535          * handle it the same everywhere by simulating a failure
536          * if it looks like a directory but really isn't
537          *
538          * Also reset if the stat failed, just for safety.
539          */
540         if ((rv != APR_SUCCESS) ||
541             (r->finfo.filetype &&
542              (r->finfo.filetype != APR_DIR) &&
543              (r->filename[strlen(r->filename) - 1] == '/'))) {
544              r->finfo.filetype = 0; /* forget what we learned */
545         }
546     }
547
548     if (r->finfo.filetype == APR_REG) {
549         entry_dir = ap_make_dirstr_parent(r->pool, entry_dir);
550     }
551     else if (r->filename[strlen(r->filename) - 1] != '/') {
552         entry_dir = apr_pstrcat(r->pool, r->filename, "/", NULL);
553     }
554
555     /* If we have a file already matches the path of r->filename,
556      * and the vhost's list of directory sections hasn't changed,
557      * we can skip rewalking the directory_walk entries.
558      */
559     if (cache->cached
560         && ((r->finfo.filetype == APR_REG)
561             || ((r->finfo.filetype == APR_DIR)
562                 && (!r->path_info || !*r->path_info)))
563         && (cache->dir_conf_tested == sec_ent)
564         && (strcmp(entry_dir, cache->cached) == 0)) {
565         /* Well this looks really familiar!  If our end-result (per_dir_result)
566          * didn't change, we have absolutely nothing to do :)
567          * Otherwise (as is the case with most dir_merged/file_merged requests)
568          * we must merge our dir_conf_merged onto this new r->per_dir_config.
569          */
570         if (r->per_dir_config == cache->per_dir_result) {
571             return OK;
572         }
573
574         if (r->per_dir_config == cache->dir_conf_merged) {
575             r->per_dir_config = cache->per_dir_result;
576             return OK;
577         }
578
579         if (cache->walked->nelts) {
580             now_merged = ((walk_walked_t*)cache->walked->elts)
581                 [cache->walked->nelts - 1].merged;
582         }
583     }
584     else {
585         /* We start now_merged from NULL since we want to build
586          * a locations list that can be merged to any vhost.
587          */
588         int sec_idx;
589         int matches = cache->walked->nelts;
590         walk_walked_t *last_walk = (walk_walked_t*)cache->walked->elts;
591         core_dir_config *this_dir;
592         core_opts_t opts;
593         apr_finfo_t thisinfo;
594         char *save_path_info;
595         apr_size_t buflen;
596         char *buf;
597         unsigned int seg, startseg;
598
599         /* Invariant: from the first time filename_len is set until
600          * it goes out of scope, filename_len==strlen(r->filename)
601          */
602         apr_size_t filename_len;
603 #ifdef CASE_BLIND_FILESYSTEM
604         apr_size_t canonical_len;
605 #endif
606
607         /*
608          * We must play our own mini-merge game here, for the few
609          * running dir_config values we care about within dir_walk.
610          * We didn't start the merge from r->per_dir_config, so we
611          * accumulate opts and override as we merge, from the globals.
612          */
613         this_dir = ap_get_module_config(r->per_dir_config, &core_module);
614         opts.opts = this_dir->opts;
615         opts.add = this_dir->opts_add;
616         opts.remove = this_dir->opts_remove;
617         opts.override = this_dir->override;
618
619         /* Set aside path_info to merge back onto path_info later.
620          * If r->filename is a directory, we must remerge the path_info,
621          * before we continue!  [Directories cannot, by defintion, have
622          * path info.  Either the next segment is not-found, or a file.]
623          *
624          * r->path_info tracks the unconsumed source path.
625          * r->filename  tracks the path as we process it
626          */
627         if ((r->finfo.filetype == APR_DIR) && r->path_info && *r->path_info)
628         {
629             if ((rv = apr_filepath_merge(&r->path_info, r->filename,
630                                          r->path_info,
631                                          APR_FILEPATH_NOTABOVEROOT, r->pool))
632                 != APR_SUCCESS) {
633                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
634                               "dir_walk error, path_info %s is not relative "
635                               "to the filename path %s for uri %s",
636                               r->path_info, r->filename, r->uri);
637                 return HTTP_INTERNAL_SERVER_ERROR;
638             }
639
640             save_path_info = NULL;
641         }
642         else {
643             save_path_info = r->path_info;
644             r->path_info = r->filename;
645         }
646
647 #ifdef CASE_BLIND_FILESYSTEM
648
649         canonical_len = 0;
650         while (r->canonical_filename && r->canonical_filename[canonical_len]
651                && (r->canonical_filename[canonical_len]
652                    == r->path_info[canonical_len])) {
653              ++canonical_len;
654         }
655
656         while (canonical_len
657                && ((r->canonical_filename[canonical_len - 1] != '/'
658                    && r->canonical_filename[canonical_len - 1])
659                    || (r->path_info[canonical_len - 1] != '/'
660                        && r->path_info[canonical_len - 1]))) {
661             --canonical_len;
662         }
663
664         /*
665          * Now build r->filename component by component, starting
666          * with the root (on Unix, simply "/").  We will make a huge
667          * assumption here for efficiency, that any canonical path
668          * already given included a canonical root.
669          */
670         rv = apr_filepath_root((const char **)&r->filename,
671                                (const char **)&r->path_info,
672                                canonical_len ? 0 : APR_FILEPATH_TRUENAME,
673                                r->pool);
674         filename_len = strlen(r->filename);
675
676         /*
677          * Bad assumption above?  If the root's length is longer
678          * than the canonical length, then it cannot be trusted as
679          * a truename.  So try again, this time more seriously.
680          */
681         if ((rv == APR_SUCCESS) && canonical_len
682             && (filename_len > canonical_len)) {
683             rv = apr_filepath_root((const char **)&r->filename,
684                                    (const char **)&r->path_info,
685                                    APR_FILEPATH_TRUENAME, r->pool);
686             filename_len = strlen(r->filename);
687             canonical_len = 0;
688         }
689
690 #else /* ndef CASE_BLIND_FILESYSTEM, really this simple for Unix today; */
691
692         rv = apr_filepath_root((const char **)&r->filename,
693                                (const char **)&r->path_info,
694                                0, r->pool);
695         filename_len = strlen(r->filename);
696
697 #endif
698
699         if (rv != APR_SUCCESS) {
700             ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
701                           "dir_walk error, could not determine the root "
702                           "path of filename %s%s for uri %s",
703                           r->filename, r->path_info, r->uri);
704             return HTTP_INTERNAL_SERVER_ERROR;
705         }
706
707         /* Working space for terminating null and an extra / is required.
708          */
709         buflen = filename_len + strlen(r->path_info) + 2;
710         buf = apr_palloc(r->pool, buflen);
711         memcpy(buf, r->filename, filename_len + 1);
712         r->filename = buf;
713         thisinfo.valid = APR_FINFO_TYPE;
714         thisinfo.filetype = APR_DIR; /* It's the root, of course it's a dir */
715
716         /*
717          * seg keeps track of which segment we've copied.
718          * sec_idx keeps track of which section we're on, since sections are
719          *     ordered by number of segments. See core_reorder_directories
720          * startseg tells us how many segments describe the root path
721          *     e.g. the complete path "//host/foo/" to a UNC share (4)
722          */
723         startseg = seg = ap_count_dirs(r->filename);
724         sec_idx = 0;
725
726         /*
727          * Go down the directory hierarchy.  Where we have to check for
728          * symlinks, do so.  Where a .htaccess file has permission to
729          * override anything, try to find one.
730          */
731         do {
732             int res;
733             char *seg_name;
734             char *delim;
735             int temp_slash=0;
736
737             /* We have no trailing slash, but we sure would appreciate one.
738              * However, we don't want to append a / our first time through.
739              */
740             if ((seg > startseg) && r->filename[filename_len-1] != '/') {
741                 r->filename[filename_len++] = '/';
742                 r->filename[filename_len] = 0;
743                 temp_slash=1;
744             }
745
746             /* Begin *this* level by looking for matching <Directory> sections
747              * from the server config.
748              */
749             for (; sec_idx < num_sec; ++sec_idx) {
750
751                 ap_conf_vector_t *entry_config = sec_ent[sec_idx];
752                 core_dir_config *entry_core;
753                 entry_core = ap_get_module_config(entry_config, &core_module);
754
755                 /* No more possible matches for this many segments?
756                  * We are done when we find relative/regex/longer components.
757                  */
758                 if (entry_core->r || entry_core->d_components > seg) {
759                     break;
760                 }
761
762                 /* We will never skip '0' element components, e.g. plain old
763                  * <Directory >, and <Directory "/"> are classified as zero
764                  * so that Win32/Netware/OS2 etc all pick them up.
765                  * Otherwise, skip over the mismatches.
766                  */
767                 if (entry_core->d_components
768                     && ((entry_core->d_components < seg)
769                      || (entry_core->d_is_fnmatch
770                          ? (apr_fnmatch(entry_core->d, r->filename,
771                                         APR_FNM_PATHNAME) != APR_SUCCESS)
772                          : (strcmp(r->filename, entry_core->d) != 0)))) {
773                     continue;
774                 }
775
776                 /* If we haven't continue'd above, we have a match.
777                  *
778                  * Calculate our full-context core opts & override.
779                  */
780                 core_opts_merge(sec_ent[sec_idx], &opts);
781
782                 /* If we merged this same section last time, reuse it
783                  */
784                 if (matches) {
785                     if (last_walk->matched == sec_ent[sec_idx]) {
786                         now_merged = last_walk->merged;
787                         ++last_walk;
788                         --matches;
789                         continue;
790                     }
791
792                     /* We fell out of sync.  This is our own copy of walked,
793                      * so truncate the remaining matches and reset remaining.
794                      */
795                     cache->walked->nelts -= matches;
796                     matches = 0;
797                 }
798
799                 if (now_merged) {
800                     now_merged = ap_merge_per_dir_configs(r->pool,
801                                                           now_merged,
802                                                           sec_ent[sec_idx]);
803                 }
804                 else {
805                     now_merged = sec_ent[sec_idx];
806                 }
807
808                 last_walk = (walk_walked_t*)apr_array_push(cache->walked);
809                 last_walk->matched = sec_ent[sec_idx];
810                 last_walk->merged = now_merged;
811             }
812
813             /* If .htaccess files are enabled, check for one, provided we
814              * have reached a real path.
815              */
816             do {  /* Not really a loop, just a break'able code block */
817
818                 ap_conf_vector_t *htaccess_conf = NULL;
819
820                 /* No htaccess in an incomplete root path, 
821                  * nor if it's disabled 
822                  */
823                 if (seg < startseg || !opts.override) {
824                     break;
825                 }
826
827                 res = ap_parse_htaccess(&htaccess_conf, r, opts.override,
828                                         opts.override_opts,
829                                         apr_pstrdup(r->pool, r->filename),
830                                         sconf->access_name);
831                 if (res) {
832                     return res;
833                 }
834
835                 if (!htaccess_conf) {
836                     break;
837                 }
838
839                 /* If we are still here, we found our htaccess.
840                  *
841                  * Calculate our full-context core opts & override.
842                  */
843                 core_opts_merge(htaccess_conf, &opts);
844
845                 /* If we merged this same htaccess last time, reuse it...
846                  * this wouldn't work except that we cache the htaccess
847                  * sections for the lifetime of the request, so we match
848                  * the same conf.  Good planning (no, pure luck ;)
849                  */
850                 if (matches) {
851                     if (last_walk->matched == htaccess_conf) {
852                         now_merged = last_walk->merged;
853                         ++last_walk;
854                         --matches;
855                         break;
856                     }
857
858                     /* We fell out of sync.  This is our own copy of walked,
859                      * so truncate the remaining matches and reset
860                      * remaining.
861                      */
862                     cache->walked->nelts -= matches;
863                     matches = 0;
864                 }
865
866                 if (now_merged) {
867                     now_merged = ap_merge_per_dir_configs(r->pool,
868                                                           now_merged,
869                                                           htaccess_conf);
870                 }
871                 else {
872                     now_merged = htaccess_conf;
873                 }
874
875                 last_walk = (walk_walked_t*)apr_array_push(cache->walked);
876                 last_walk->matched = htaccess_conf;
877                 last_walk->merged = now_merged;
878
879             } while (0); /* Only one htaccess, not a real loop */
880
881             /* That temporary trailing slash was useful, now drop it.
882              */
883             if (temp_slash) {
884                 r->filename[--filename_len] = '\0';
885             }
886
887             /* Time for all good things to come to an end?
888              */
889             if (!r->path_info || !*r->path_info) {
890                 break;
891             }
892
893             /* Now it's time for the next segment...
894              * We will assume the next element is an end node, and fix it up
895              * below as necessary...
896              */
897
898             seg_name = r->filename + filename_len;
899             delim = strchr(r->path_info + (*r->path_info == '/' ? 1 : 0), '/');
900             if (delim) {
901                 size_t path_info_len = delim - r->path_info;
902                 *delim = '\0';
903                 memcpy(seg_name, r->path_info, path_info_len + 1);
904                 filename_len += path_info_len;
905                 r->path_info = delim;
906                 *delim = '/';
907             }
908             else {
909                 size_t path_info_len = strlen(r->path_info);
910                 memcpy(seg_name, r->path_info, path_info_len + 1);
911                 filename_len += path_info_len;
912                 r->path_info += path_info_len;
913             }
914             if (*seg_name == '/')
915                 ++seg_name;
916
917             /* If nothing remained but a '/' string, we are finished
918              * XXX: NO WE ARE NOT!!!  Now process this puppy!!! */
919             if (!*seg_name) {
920                 break;
921             }
922
923             /* First optimization;
924              * If...we knew r->filename was a file, and
925              * if...we have strict (case-sensitive) filenames, or
926              *      we know the canonical_filename matches to _this_ name, and
927              * if...we have allowed symlinks
928              * skip the lstat and dummy up an APR_DIR value for thisinfo.
929              */
930             if (r->finfo.filetype
931 #ifdef CASE_BLIND_FILESYSTEM
932                 && (filename_len <= canonical_len)
933 #endif
934                 && ((opts.opts & (OPT_SYM_OWNER | OPT_SYM_LINKS)) == OPT_SYM_LINKS))
935             {
936
937                 thisinfo.filetype = APR_DIR;
938                 ++seg;
939                 continue;
940             }
941
942             /* We choose apr_stat with flag APR_FINFO_LINK here, rather that 
943              * plain apr_stat, so that we capture this path object rather than
944              * its target.  We will replace the info with our target's info 
945              * below.  We especially want the name of this 'link' object, not 
946              * the name of its target, if we are fixing the filename 
947              * case/resolving aliases.
948              */
949             rv = apr_stat(&thisinfo, r->filename,
950                           APR_FINFO_MIN | APR_FINFO_NAME | APR_FINFO_LINK, 
951                           r->pool);
952
953             if (APR_STATUS_IS_ENOENT(rv)) {
954                 /* Nothing?  That could be nice.  But our directory
955                  * walk is done.
956                  */
957                 thisinfo.filetype = APR_NOFILE;
958                 break;
959             }
960             else if (APR_STATUS_IS_EACCES(rv)) {
961                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
962                               "access to %s denied", r->uri);
963                 return r->status = HTTP_FORBIDDEN;
964             }
965             else if ((rv != APR_SUCCESS && rv != APR_INCOMPLETE)
966                      || !(thisinfo.valid & APR_FINFO_TYPE)) {
967                 /* If we hit ENOTDIR, we must have over-optimized, deny
968                  * rather than assume not found.
969                  */
970                 ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
971                               "access to %s failed", r->uri);
972                 return r->status = HTTP_FORBIDDEN;
973             }
974
975             /* Fix up the path now if we have a name, and they don't agree
976              */
977             if ((thisinfo.valid & APR_FINFO_NAME)
978                 && strcmp(seg_name, thisinfo.name)) {
979                 /* TODO: provide users an option that an internal/external
980                  * redirect is required here?  We need to walk the URI and
981                  * filename in tandem to properly correlate these.
982                  */
983                 strcpy(seg_name, thisinfo.name);
984                 filename_len = strlen(r->filename);
985             }
986
987             if (thisinfo.filetype == APR_LNK) {
988                 /* Is this a possibly acceptable symlink?
989                  */
990                 if ((res = resolve_symlink(r->filename, &thisinfo,
991                                            opts.opts, r->pool)) != OK) {
992                     ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
993                                   "Symbolic link not allowed: %s",
994                                   r->filename);
995                     return r->status = res;
996                 }
997             }
998
999             /* Ok, we are done with the link's info, test the real target
1000              */
1001             if (thisinfo.filetype == APR_REG || 
1002                 thisinfo.filetype == APR_NOFILE) {
1003                 /* That was fun, nothing left for us here
1004                  */
1005                 break;
1006             }
1007             else if (thisinfo.filetype != APR_DIR) {
1008                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1009                               "Forbidden: %s doesn't point to "
1010                               "a file or directory",
1011                               r->filename);
1012                 return r->status = HTTP_FORBIDDEN;
1013             }
1014
1015             ++seg;
1016         } while (thisinfo.filetype == APR_DIR);
1017
1018         /* If we have _not_ optimized, this is the time to recover
1019          * the final stat result.
1020          */
1021         if (!r->finfo.filetype || r->finfo.filetype == APR_LNK) {
1022             r->finfo = thisinfo;
1023         }
1024
1025         /* Now splice the saved path_info back onto any new path_info
1026          */
1027         if (save_path_info) {
1028             if (r->path_info && *r->path_info) {
1029                 r->path_info = ap_make_full_path(r->pool, r->path_info,
1030                                                  save_path_info);
1031             }
1032             else {
1033                 r->path_info = save_path_info;
1034             }
1035         }
1036
1037         /*
1038          * Now we'll deal with the regexes, note we pick up sec_idx
1039          * where we left off (we gave up after we hit entry_core->r)
1040          */
1041         for (; sec_idx < num_sec; ++sec_idx) {
1042
1043             core_dir_config *entry_core;
1044             entry_core = ap_get_module_config(sec_ent[sec_idx], &core_module);
1045
1046             if (!entry_core->r) {
1047                 continue;
1048             }
1049
1050             if (ap_regexec(entry_core->r, r->filename, 0, NULL, REG_NOTEOL)) {
1051                 continue;
1052             }
1053
1054             /* If we haven't already continue'd above, we have a match.
1055              *
1056              * Calculate our full-context core opts & override.
1057              */
1058             core_opts_merge(sec_ent[sec_idx], &opts);
1059
1060             /* If we merged this same section last time, reuse it
1061              */
1062             if (matches) {
1063                 if (last_walk->matched == sec_ent[sec_idx]) {
1064                     now_merged = last_walk->merged;
1065                     ++last_walk;
1066                     --matches;
1067                     continue;
1068                 }
1069
1070                 /* We fell out of sync.  This is our own copy of walked,
1071                  * so truncate the remaining matches and reset remaining.
1072                  */
1073                 cache->walked->nelts -= matches;
1074                 matches = 0;
1075             }
1076
1077             if (now_merged) {
1078                 now_merged = ap_merge_per_dir_configs(r->pool,
1079                                                       now_merged,
1080                                                       sec_ent[sec_idx]);
1081             }
1082             else {
1083                 now_merged = sec_ent[sec_idx];
1084             }
1085
1086             last_walk = (walk_walked_t*)apr_array_push(cache->walked);
1087             last_walk->matched = sec_ent[sec_idx];
1088             last_walk->merged = now_merged;
1089         }
1090
1091         /* Whoops - everything matched in sequence, but the original walk
1092          * found some additional matches.  Truncate them.
1093          */
1094         if (matches) {
1095             cache->walked->nelts -= matches;
1096         }
1097     }
1098
1099 /* It seems this shouldn't be needed anymore.  We translated the
1100  x symlink above into a real resource, and should have died up there.
1101  x Even if we keep this, it needs more thought (maybe an r->file_is_symlink)
1102  x perhaps it should actually happen in file_walk, so we catch more
1103  x obscure cases in autoindex subrequests, etc.
1104  x
1105  x    * Symlink permissions are determined by the parent.  If the request is
1106  x    * for a directory then applying the symlink test here would use the
1107  x    * permissions of the directory as opposed to its parent.  Consider a
1108  x    * symlink pointing to a dir with a .htaccess disallowing symlinks.  If
1109  x    * you access /symlink (or /symlink/) you would get a 403 without this
1110  x    * APR_DIR test.  But if you accessed /symlink/index.html, for example,
1111  x    * you would *not* get the 403.
1112  x
1113  x   if (r->finfo.filetype != APR_DIR
1114  x       && (res = resolve_symlink(r->filename, r->info, ap_allow_options(r),
1115  x                                 r->pool))) {
1116  x       ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
1117  x                     "Symbolic link not allowed: %s", r->filename);
1118  x       return res;
1119  x   }
1120  */
1121
1122     /* Save future sub-requestors much angst in processing
1123      * this subrequest.  If dir_walk couldn't canonicalize
1124      * the file path, nothing can.
1125      */
1126     r->canonical_filename = r->filename;
1127
1128     if (r->finfo.filetype == APR_DIR) {
1129         cache->cached = r->filename;
1130     }
1131     else {
1132         cache->cached = ap_make_dirstr_parent(r->pool, r->filename);
1133     }
1134
1135     cache->dir_conf_tested = sec_ent;
1136     cache->dir_conf_merged = r->per_dir_config;
1137
1138     /* Merge our cache->dir_conf_merged construct with the r->per_dir_configs,
1139      * and note the end result to (potentially) skip this step next time.
1140      */
1141     if (now_merged) {
1142         r->per_dir_config = ap_merge_per_dir_configs(r->pool,
1143                                                      r->per_dir_config,
1144                                                      now_merged);
1145     }
1146     cache->per_dir_result = r->per_dir_config;
1147
1148     return OK;
1149 }
1150
1151
1152 AP_DECLARE(int) ap_location_walk(request_rec *r)
1153 {
1154     ap_conf_vector_t *now_merged = NULL;
1155     core_server_config *sconf = ap_get_module_config(r->server->module_config,
1156                                                      &core_module);
1157     ap_conf_vector_t **sec_ent = (ap_conf_vector_t **)sconf->sec_url->elts;
1158     int num_sec = sconf->sec_url->nelts;
1159     walk_cache_t *cache;
1160     const char *entry_uri;
1161
1162     /* No tricks here, there are no <Locations > to parse in this vhost.
1163      * We won't destroy the cache, just in case _this_ redirect is later
1164      * redirected again to a vhost with <Location > blocks to optimize.
1165      */
1166     if (!num_sec) {
1167         return OK;
1168     }
1169
1170     cache = prep_walk_cache(AP_NOTE_LOCATION_WALK, r);
1171
1172     /* Location and LocationMatch differ on their behaviour w.r.t. multiple
1173      * slashes.  Location matches multiple slashes with a single slash,
1174      * LocationMatch doesn't.  An exception, for backwards brokenness is
1175      * absoluteURIs... in which case neither match multiple slashes.
1176      */
1177     if (r->uri[0] != '/') {
1178         entry_uri = r->uri;
1179     }
1180     else {
1181         char *uri = apr_pstrdup(r->pool, r->uri);
1182         ap_no2slash(uri);
1183         entry_uri = uri;
1184     }
1185
1186     /* If we have an cache->cached location that matches r->uri,
1187      * and the vhost's list of locations hasn't changed, we can skip
1188      * rewalking the location_walk entries.
1189      */
1190     if (cache->cached
1191         && (cache->dir_conf_tested == sec_ent)
1192         && (strcmp(entry_uri, cache->cached) == 0)) {
1193         /* Well this looks really familiar!  If our end-result (per_dir_result)
1194          * didn't change, we have absolutely nothing to do :)
1195          * Otherwise (as is the case with most dir_merged/file_merged requests)
1196          * we must merge our dir_conf_merged onto this new r->per_dir_config.
1197          */
1198         if (r->per_dir_config == cache->per_dir_result) {
1199             return OK;
1200         }
1201
1202         if (r->per_dir_config == cache->dir_conf_merged) {
1203             r->per_dir_config = cache->per_dir_result;
1204             return OK;
1205         }
1206
1207         if (cache->walked->nelts) {
1208             now_merged = ((walk_walked_t*)cache->walked->elts)
1209                                             [cache->walked->nelts - 1].merged;
1210         }
1211     }
1212     else {
1213         /* We start now_merged from NULL since we want to build
1214          * a locations list that can be merged to any vhost.
1215          */
1216         int len, sec_idx;
1217         int matches = cache->walked->nelts;
1218         walk_walked_t *last_walk = (walk_walked_t*)cache->walked->elts;
1219         cache->cached = entry_uri;
1220
1221         /* Go through the location entries, and check for matches.
1222          * We apply the directive sections in given order, we should
1223          * really try them with the most general first.
1224          */
1225         for (sec_idx = 0; sec_idx < num_sec; ++sec_idx) {
1226
1227             core_dir_config *entry_core;
1228             entry_core = ap_get_module_config(sec_ent[sec_idx], &core_module);
1229
1230             /* ### const strlen can be optimized in location config parsing */
1231             len = strlen(entry_core->d);
1232
1233             /* Test the regex, fnmatch or string as appropriate.
1234              * If it's a strcmp, and the <Location > pattern was
1235              * not slash terminated, then this uri must be slash
1236              * terminated (or at the end of the string) to match.
1237              */
1238             if (entry_core->r
1239                 ? ap_regexec(entry_core->r, r->uri, 0, NULL, 0)
1240                 : (entry_core->d_is_fnmatch
1241                    ? apr_fnmatch(entry_core->d, cache->cached, APR_FNM_PATHNAME)
1242                    : (strncmp(entry_core->d, cache->cached, len)
1243                       || (entry_core->d[len - 1] != '/'
1244                           && cache->cached[len] != '/'
1245                           && cache->cached[len] != '\0')))) {
1246                 continue;
1247             }
1248
1249             /* If we merged this same section last time, reuse it
1250              */
1251             if (matches) {
1252                 if (last_walk->matched == sec_ent[sec_idx]) {
1253                     now_merged = last_walk->merged;
1254                     ++last_walk;
1255                     --matches;
1256                     continue;
1257                 }
1258
1259                 /* We fell out of sync.  This is our own copy of walked,
1260                  * so truncate the remaining matches and reset remaining.
1261                  */
1262                 cache->walked->nelts -= matches;
1263                 matches = 0;
1264             }
1265
1266             if (now_merged) {
1267                 now_merged = ap_merge_per_dir_configs(r->pool,
1268                                                       now_merged,
1269                                                       sec_ent[sec_idx]);
1270             }
1271             else {
1272                 now_merged = sec_ent[sec_idx];
1273             }
1274
1275             last_walk = (walk_walked_t*)apr_array_push(cache->walked);
1276             last_walk->matched = sec_ent[sec_idx];
1277             last_walk->merged = now_merged;
1278         }
1279
1280         /* Whoops - everything matched in sequence, but the original walk
1281          * found some additional matches.  Truncate them.
1282          */
1283         if (matches) {
1284             cache->walked->nelts -= matches;
1285         }
1286     }
1287
1288     cache->dir_conf_tested = sec_ent;
1289     cache->dir_conf_merged = r->per_dir_config;
1290
1291     /* Merge our cache->dir_conf_merged construct with the r->per_dir_configs,
1292      * and note the end result to (potentially) skip this step next time.
1293      */
1294     if (now_merged) {
1295         r->per_dir_config = ap_merge_per_dir_configs(r->pool,
1296                                                      r->per_dir_config,
1297                                                      now_merged);
1298     }
1299     cache->per_dir_result = r->per_dir_config;
1300
1301     return OK;
1302 }
1303
1304 AP_DECLARE(int) ap_file_walk(request_rec *r)
1305 {
1306     ap_conf_vector_t *now_merged = NULL;
1307     core_dir_config *dconf = ap_get_module_config(r->per_dir_config,
1308                                                   &core_module);
1309     ap_conf_vector_t **sec_ent = (ap_conf_vector_t **)dconf->sec_file->elts;
1310     int num_sec = dconf->sec_file->nelts;
1311     walk_cache_t *cache;
1312     const char *test_file;
1313
1314     /* To allow broken modules to proceed, we allow missing filenames to pass.
1315      * We will catch it later if it's heading for the core handler.
1316      * directory_walk already posted an INFO note for module debugging.
1317      */
1318     if (r->filename == NULL) {
1319         return OK;
1320     }
1321
1322     cache = prep_walk_cache(AP_NOTE_FILE_WALK, r);
1323
1324     /* No tricks here, there are just no <Files > to parse in this context.
1325      * We won't destroy the cache, just in case _this_ redirect is later
1326      * redirected again to a context containing the same or similar <Files >.
1327      */
1328     if (!num_sec) {
1329         return OK;
1330     }
1331
1332     /* Get the basename .. and copy for the cache just
1333      * in case r->filename is munged by another module
1334      */
1335     test_file = strrchr(r->filename, '/');
1336     if (test_file == NULL) {
1337         test_file = apr_pstrdup(r->pool, r->filename);
1338     }
1339     else {
1340         test_file = apr_pstrdup(r->pool, ++test_file);
1341     }
1342
1343     /* If we have an cache->cached file name that matches test_file,
1344      * and the directory's list of file sections hasn't changed, we
1345      * can skip rewalking the file_walk entries.
1346      */
1347     if (cache->cached
1348         && (cache->dir_conf_tested == sec_ent)
1349         && (strcmp(test_file, cache->cached) == 0)) {
1350         /* Well this looks really familiar!  If our end-result (per_dir_result)
1351          * didn't change, we have absolutely nothing to do :)
1352          * Otherwise (as is the case with most dir_merged requests)
1353          * we must merge our dir_conf_merged onto this new r->per_dir_config.
1354          */
1355         if (r->per_dir_config == cache->per_dir_result) {
1356             return OK;
1357         }
1358
1359         if (r->per_dir_config == cache->dir_conf_merged) {
1360             r->per_dir_config = cache->per_dir_result;
1361             return OK;
1362         }
1363
1364         if (cache->walked->nelts) {
1365             now_merged = ((walk_walked_t*)cache->walked->elts)
1366                 [cache->walked->nelts - 1].merged;
1367         }
1368     }
1369     else {
1370         /* We start now_merged from NULL since we want to build
1371          * a file section list that can be merged to any dir_walk.
1372          */
1373         int sec_idx;
1374         int matches = cache->walked->nelts;
1375         walk_walked_t *last_walk = (walk_walked_t*)cache->walked->elts;
1376         cache->cached = test_file;
1377
1378         /* Go through the location entries, and check for matches.
1379          * We apply the directive sections in given order, we should
1380          * really try them with the most general first.
1381          */
1382         for (sec_idx = 0; sec_idx < num_sec; ++sec_idx) {
1383
1384             core_dir_config *entry_core;
1385             entry_core = ap_get_module_config(sec_ent[sec_idx], &core_module);
1386
1387             if (entry_core->r
1388                 ? ap_regexec(entry_core->r, cache->cached , 0, NULL, 0)
1389                 : (entry_core->d_is_fnmatch
1390                    ? apr_fnmatch(entry_core->d, cache->cached, APR_FNM_PATHNAME)
1391                    : strcmp(entry_core->d, cache->cached))) {
1392                 continue;
1393             }
1394
1395             /* If we merged this same section last time, reuse it
1396              */
1397             if (matches) {
1398                 if (last_walk->matched == sec_ent[sec_idx]) {
1399                     now_merged = last_walk->merged;
1400                     ++last_walk;
1401                     --matches;
1402                     continue;
1403                 }
1404
1405                 /* We fell out of sync.  This is our own copy of walked,
1406                  * so truncate the remaining matches and reset remaining.
1407                  */
1408                 cache->walked->nelts -= matches;
1409                 matches = 0;
1410             }
1411
1412             if (now_merged) {
1413                 now_merged = ap_merge_per_dir_configs(r->pool,
1414                                                       now_merged,
1415                                                       sec_ent[sec_idx]);
1416             }
1417             else {
1418                 now_merged = sec_ent[sec_idx];
1419             }
1420
1421             last_walk = (walk_walked_t*)apr_array_push(cache->walked);
1422             last_walk->matched = sec_ent[sec_idx];
1423             last_walk->merged = now_merged;
1424         }
1425
1426         /* Whoops - everything matched in sequence, but the original walk
1427          * found some additional matches.  Truncate them.
1428          */
1429         if (matches) {
1430             cache->walked->nelts -= matches;
1431         }
1432     }
1433
1434     cache->dir_conf_tested = sec_ent;
1435     cache->dir_conf_merged = r->per_dir_config;
1436
1437     /* Merge our cache->dir_conf_merged construct with the r->per_dir_configs,
1438      * and note the end result to (potentially) skip this step next time.
1439      */
1440     if (now_merged) {
1441         r->per_dir_config = ap_merge_per_dir_configs(r->pool,
1442                                                      r->per_dir_config,
1443                                                      now_merged);
1444     }
1445     cache->per_dir_result = r->per_dir_config;
1446
1447     return OK;
1448 }
1449
1450 /*****************************************************************
1451  *
1452  * The sub_request mechanism.
1453  *
1454  * Fns to look up a relative URI from, e.g., a map file or SSI document.
1455  * These do all access checks, etc., but don't actually run the transaction
1456  * ... use run_sub_req below for that.  Also, be sure to use destroy_sub_req
1457  * as appropriate if you're likely to be creating more than a few of these.
1458  * (An early Apache version didn't destroy the sub_reqs used in directory
1459  * indexing.  The result, when indexing a directory with 800-odd files in
1460  * it, was massively excessive storage allocation).
1461  *
1462  * Note more manipulation of protocol-specific vars in the request
1463  * structure...
1464  */
1465
1466 static request_rec *make_sub_request(const request_rec *r,
1467                                      ap_filter_t *next_filter)
1468 {
1469     apr_pool_t *rrp;
1470     request_rec *rnew;
1471
1472     apr_pool_create(&rrp, r->pool);
1473     apr_pool_tag(rrp, "subrequest");
1474     rnew = apr_pcalloc(rrp, sizeof(request_rec));
1475     rnew->pool = rrp;
1476
1477     rnew->hostname       = r->hostname;
1478     rnew->request_time   = r->request_time;
1479     rnew->connection     = r->connection;
1480     rnew->server         = r->server;
1481
1482     rnew->request_config = ap_create_request_config(rnew->pool);
1483
1484     /* Start a clean config from this subrequest's vhost.  Optimization in
1485      * Location/File/Dir walks from the parent request assure that if the
1486      * config blocks of the subrequest match the parent request, no merges
1487      * will actually occur (and generally a minimal number of merges are
1488      * required, even if the parent and subrequest aren't quite identical.)
1489      */
1490     rnew->per_dir_config = r->server->lookup_defaults;
1491
1492     rnew->htaccess = r->htaccess;
1493     rnew->allowed_methods = ap_make_method_list(rnew->pool, 2);
1494
1495     /* make a copy of the allowed-methods list */
1496     ap_copy_method_list(rnew->allowed_methods, r->allowed_methods);
1497
1498     /* start with the same set of output filters */
1499     if (next_filter) {
1500         /* while there are no input filters for a subrequest, we will
1501          * try to insert some, so if we don't have valid data, the code
1502          * will seg fault.
1503          */
1504         rnew->input_filters = r->input_filters;
1505         rnew->proto_input_filters = r->proto_input_filters;
1506         rnew->output_filters = next_filter;
1507         rnew->proto_output_filters = r->proto_output_filters;
1508         ap_add_output_filter_handle(ap_subreq_core_filter_handle,
1509                                     NULL, rnew, rnew->connection);
1510     }
1511     else {
1512         /* If NULL - we are expecting to be internal_fast_redirect'ed
1513          * to this subrequest - or this request will never be invoked.
1514          * Ignore the original request filter stack entirely, and
1515          * drill the input and output stacks back to the connection.
1516          */
1517         rnew->proto_input_filters = r->proto_input_filters;
1518         rnew->proto_output_filters = r->proto_output_filters;
1519
1520         rnew->input_filters = r->proto_input_filters;
1521         rnew->output_filters = r->proto_output_filters;
1522     }
1523
1524     /* no input filters for a subrequest */
1525
1526     ap_set_sub_req_protocol(rnew, r);
1527
1528     /* We have to run this after we fill in sub req vars,
1529      * or the r->main pointer won't be setup
1530      */
1531     ap_run_create_request(rnew);
1532
1533     return rnew;
1534 }
1535
1536 AP_CORE_DECLARE_NONSTD(apr_status_t) ap_sub_req_output_filter(ap_filter_t *f,
1537                                                               apr_bucket_brigade *bb)
1538 {
1539     apr_bucket *e = APR_BRIGADE_LAST(bb);
1540
1541     if (APR_BUCKET_IS_EOS(e)) {
1542         apr_bucket_delete(e);
1543     }
1544
1545     if (!APR_BRIGADE_EMPTY(bb)) {
1546         return ap_pass_brigade(f->next, bb);
1547     }
1548
1549     return APR_SUCCESS;
1550 }
1551
1552
1553 AP_DECLARE(int) ap_some_auth_required(request_rec *r)
1554 {
1555     /* Is there a require line configured for the type of *this* req? */
1556
1557     const apr_array_header_t *reqs_arr = ap_requires(r);
1558     require_line *reqs;
1559     int i;
1560
1561     if (!reqs_arr) {
1562         return 0;
1563     }
1564
1565     reqs = (require_line *) reqs_arr->elts;
1566
1567     for (i = 0; i < reqs_arr->nelts; ++i) {
1568         if (reqs[i].method_mask & (AP_METHOD_BIT << r->method_number)) {
1569             return 1;
1570         }
1571     }
1572
1573     return 0;
1574 }
1575
1576
1577 AP_DECLARE(request_rec *) ap_sub_req_method_uri(const char *method,
1578                                                 const char *new_uri,
1579                                                 const request_rec *r,
1580                                                 ap_filter_t *next_filter)
1581 {
1582     request_rec *rnew;
1583     int res;
1584     char *udir;
1585
1586     rnew = make_sub_request(r, next_filter);
1587
1588     /* would be nicer to pass "method" to ap_set_sub_req_protocol */
1589     rnew->method = method;
1590     rnew->method_number = ap_method_number_of(method);
1591
1592     if (new_uri[0] == '/') {
1593         ap_parse_uri(rnew, new_uri);
1594     }
1595     else {
1596         udir = ap_make_dirstr_parent(rnew->pool, r->uri);
1597         udir = ap_escape_uri(rnew->pool, udir);    /* re-escape it */
1598         ap_parse_uri(rnew, ap_make_full_path(rnew->pool, udir, new_uri));
1599     }
1600
1601     /* We cannot return NULL without violating the API. So just turn this
1602      * subrequest into a 500 to indicate the failure. */
1603     if (ap_is_recursion_limit_exceeded(r)) {
1604         rnew->status = HTTP_INTERNAL_SERVER_ERROR;
1605         return rnew;
1606     }
1607
1608     /* lookup_uri 
1609      * If the content can be served by the quick_handler, we can
1610      * safely bypass request_internal processing.
1611      */
1612     res = ap_run_quick_handler(rnew, 1);
1613
1614     if (res != OK) {
1615         if ((res = ap_process_request_internal(rnew))) {
1616             rnew->status = res;
1617         }
1618     } 
1619
1620     return rnew;
1621 }
1622
1623 AP_DECLARE(request_rec *) ap_sub_req_lookup_uri(const char *new_uri,
1624                                                 const request_rec *r,
1625                                                 ap_filter_t *next_filter)
1626 {
1627     return ap_sub_req_method_uri("GET", new_uri, r, next_filter);
1628 }
1629
1630 AP_DECLARE(request_rec *) ap_sub_req_lookup_dirent(const apr_finfo_t *dirent,
1631                                                    const request_rec *r,
1632                                                    int subtype,
1633                                                    ap_filter_t *next_filter)
1634 {
1635     request_rec *rnew;
1636     int res;
1637     char *fdir;
1638     char *udir;
1639
1640     rnew = make_sub_request(r, next_filter);
1641
1642     /* Special case: we are looking at a relative lookup in the same directory.
1643      * This is 100% safe, since dirent->name just came from the filesystem.
1644      */
1645     if (r->path_info && *r->path_info) {
1646         /* strip path_info off the end of the uri to keep it in sync
1647          * with r->filename, which has already been stripped by directory_walk,
1648          * merge the dirent->name, and then, if the caller wants us to remerge
1649          * the original path info, do so.  Note we never fix the path_info back
1650          * to r->filename, since dir_walk would do so (but we don't expect it
1651          * to happen in the usual cases)
1652          */
1653         udir = apr_pstrdup(rnew->pool, r->uri);
1654         udir[ap_find_path_info(udir, r->path_info)] = '\0';
1655         udir = ap_make_dirstr_parent(rnew->pool, udir);
1656
1657         rnew->uri = ap_make_full_path(rnew->pool, udir, dirent->name);
1658         if (subtype == AP_SUBREQ_MERGE_ARGS) {
1659             rnew->uri = ap_make_full_path(rnew->pool, rnew->uri, r->path_info + 1);
1660             rnew->path_info = apr_pstrdup(rnew->pool, r->path_info);
1661         }
1662         rnew->uri = ap_escape_uri(rnew->pool, rnew->uri);
1663     }
1664     else {
1665         udir = ap_make_dirstr_parent(rnew->pool, r->uri);
1666         rnew->uri = ap_escape_uri(rnew->pool, ap_make_full_path(rnew->pool,
1667                                                                 udir,
1668                                                                 dirent->name));
1669     }
1670
1671     fdir = ap_make_dirstr_parent(rnew->pool, r->filename);
1672     rnew->filename = ap_make_full_path(rnew->pool, fdir, dirent->name);
1673     if (r->canonical_filename == r->filename) {
1674         rnew->canonical_filename = rnew->filename;
1675     }
1676
1677     /* XXX This is now less relevant; we will do a full location walk
1678      * these days for this case.  Preserve the apr_stat results, and
1679      * perhaps we also tag that symlinks were tested and/or found for
1680      * r->filename.
1681      */
1682     rnew->per_dir_config = r->server->lookup_defaults;
1683
1684     if ((dirent->valid & APR_FINFO_MIN) != APR_FINFO_MIN) {
1685         /*
1686          * apr_dir_read isn't very complete on this platform, so
1687          * we need another apr_stat (with or without APR_FINFO_LINK
1688          * depending on whether we allow all symlinks here.)  If this 
1689          * is an APR_LNK that resolves to an APR_DIR, then we will rerun 
1690          * everything anyways... this should be safe.
1691          */
1692         apr_status_t rv;
1693         if (ap_allow_options(rnew) & OPT_SYM_LINKS) {
1694             if (((rv = apr_stat(&rnew->finfo, rnew->filename,
1695                                 APR_FINFO_MIN, rnew->pool)) != APR_SUCCESS)
1696                 && (rv != APR_INCOMPLETE)) {
1697                 rnew->finfo.filetype = 0;
1698             }
1699         }
1700         else {
1701             if (((rv = apr_stat(&rnew->finfo, rnew->filename,
1702                                 APR_FINFO_LINK | APR_FINFO_MIN, 
1703                                 rnew->pool)) != APR_SUCCESS)
1704                 && (rv != APR_INCOMPLETE)) {
1705                 rnew->finfo.filetype = 0;
1706             }
1707         }
1708     }
1709     else {
1710         memcpy(&rnew->finfo, dirent, sizeof(apr_finfo_t));
1711     }
1712
1713     if (rnew->finfo.filetype == APR_LNK) {
1714         /*
1715          * Resolve this symlink.  We should tie this back to dir_walk's cache
1716          */
1717         if ((res = resolve_symlink(rnew->filename, &rnew->finfo,
1718                                    ap_allow_options(rnew), rnew->pool))
1719             != OK) {
1720             rnew->status = res;
1721             return rnew;
1722         }
1723     }
1724
1725     if (rnew->finfo.filetype == APR_DIR) {
1726         /* ap_make_full_path overallocated the buffers
1727          * by one character to help us out here.
1728          */
1729         strcpy(rnew->filename + strlen(rnew->filename), "/");
1730         if (!rnew->path_info || !*rnew->path_info) {
1731             strcpy(rnew->uri  + strlen(rnew->uri ), "/");
1732         }
1733     }
1734
1735     /* fill in parsed_uri values
1736      */
1737     if (r->args && *r->args && (subtype == AP_SUBREQ_MERGE_ARGS)) {
1738         ap_parse_uri(rnew, apr_pstrcat(r->pool, rnew->uri, "?",
1739                                        r->args, NULL));
1740     }
1741     else {
1742         ap_parse_uri(rnew, rnew->uri);
1743     }
1744
1745     /* We cannot return NULL without violating the API. So just turn this
1746      * subrequest into a 500. */
1747     if (ap_is_recursion_limit_exceeded(r)) {
1748         rnew->status = HTTP_INTERNAL_SERVER_ERROR;
1749         return rnew;
1750     }
1751
1752     if ((res = ap_process_request_internal(rnew))) {
1753         rnew->status = res;
1754     }
1755
1756     return rnew;
1757 }
1758
1759 AP_DECLARE(request_rec *) ap_sub_req_lookup_file(const char *new_file,
1760                                                  const request_rec *r,
1761                                                  ap_filter_t *next_filter)
1762 {
1763     request_rec *rnew;
1764     int res;
1765     char *fdir;
1766     apr_size_t fdirlen;
1767
1768     rnew = make_sub_request(r, next_filter);
1769
1770     fdir = ap_make_dirstr_parent(rnew->pool, r->filename);
1771     fdirlen = strlen(fdir);
1772
1773     /* Translate r->filename, if it was canonical, it stays canonical
1774      */
1775     if (r->canonical_filename == r->filename) {
1776         rnew->canonical_filename = (char*)(1);
1777     }
1778
1779     if (apr_filepath_merge(&rnew->filename, fdir, new_file,
1780                            APR_FILEPATH_TRUENAME, rnew->pool) != APR_SUCCESS) {
1781         rnew->status = HTTP_FORBIDDEN;
1782         return rnew;
1783     }
1784
1785     if (rnew->canonical_filename) {
1786         rnew->canonical_filename = rnew->filename;
1787     }
1788
1789     /*
1790      * Check for a special case... if there are no '/' characters in new_file
1791      * at all, and the path was the same, then we are looking at a relative
1792      * lookup in the same directory.  Fixup the URI to match.
1793      */
1794
1795     if (strncmp(rnew->filename, fdir, fdirlen) == 0
1796         && rnew->filename[fdirlen]
1797         && ap_strchr_c(rnew->filename + fdirlen, '/') == NULL) {
1798         apr_status_t rv;
1799         if (ap_allow_options(rnew) & OPT_SYM_LINKS) {
1800             if (((rv = apr_stat(&rnew->finfo, rnew->filename,
1801                                 APR_FINFO_MIN, rnew->pool)) != APR_SUCCESS)
1802                 && (rv != APR_INCOMPLETE)) {
1803                 rnew->finfo.filetype = 0;
1804             }
1805         }
1806         else {
1807             if (((rv = apr_stat(&rnew->finfo, rnew->filename,
1808                                 APR_FINFO_LINK | APR_FINFO_MIN, 
1809                                 rnew->pool)) != APR_SUCCESS)
1810                 && (rv != APR_INCOMPLETE)) {
1811                 rnew->finfo.filetype = 0;
1812             }
1813         }
1814
1815         if (r->uri && *r->uri) {
1816             char *udir = ap_make_dirstr_parent(rnew->pool, r->uri);
1817             rnew->uri = ap_make_full_path(rnew->pool, udir,
1818                                           rnew->filename + fdirlen);
1819             ap_parse_uri(rnew, rnew->uri);    /* fill in parsed_uri values */
1820         }
1821         else {
1822             ap_parse_uri(rnew, new_file);        /* fill in parsed_uri values */
1823             rnew->uri = apr_pstrdup(rnew->pool, "");
1824         }
1825     }
1826     else {
1827         /* XXX: @@@: What should be done with the parsed_uri values?
1828          * We would be better off stripping down to the 'common' elements
1829          * of the path, then reassembling the URI as best as we can.
1830          */
1831         ap_parse_uri(rnew, new_file);        /* fill in parsed_uri values */
1832         /*
1833          * XXX: this should be set properly like it is in the same-dir case
1834          * but it's actually sometimes to impossible to do it... because the
1835          * file may not have a uri associated with it -djg
1836          */
1837         rnew->uri = apr_pstrdup(rnew->pool, "");
1838     }
1839
1840     /* We cannot return NULL without violating the API. So just turn this
1841      * subrequest into a 500. */
1842     if (ap_is_recursion_limit_exceeded(r)) {
1843         rnew->status = HTTP_INTERNAL_SERVER_ERROR;
1844         return rnew;
1845     }
1846
1847     if ((res = ap_process_request_internal(rnew))) {
1848         rnew->status = res;
1849     }
1850
1851     return rnew;
1852 }
1853
1854 AP_DECLARE(int) ap_run_sub_req(request_rec *r)
1855 {
1856     int retval = DECLINED;
1857     /* Run the quick handler if the subrequest is not a dirent or file 
1858      * subrequest 
1859      */
1860     if (!(r->filename && r->finfo.filetype)) {
1861         retval = ap_run_quick_handler(r, 0);
1862     }
1863     if (retval != OK) {
1864         retval = ap_invoke_handler(r);
1865         if (retval == DONE) {
1866             retval = OK;
1867         }
1868     }
1869     ap_finalize_sub_req_protocol(r);
1870     return retval;
1871 }
1872
1873 AP_DECLARE(void) ap_destroy_sub_req(request_rec *r)
1874 {
1875     /* Reclaim the space */
1876     apr_pool_destroy(r->pool);
1877 }
1878
1879 /*
1880  * Function to set the r->mtime field to the specified value if it's later
1881  * than what's already there.
1882  */
1883 AP_DECLARE(void) ap_update_mtime(request_rec *r, apr_time_t dependency_mtime)
1884 {
1885     if (r->mtime < dependency_mtime) {
1886         r->mtime = dependency_mtime;
1887     }
1888 }
1889
1890 /*
1891  * Is it the initial main request, which we only get *once* per HTTP request?
1892  */
1893 AP_DECLARE(int) ap_is_initial_req(request_rec *r)
1894 {
1895     return (r->main == NULL)       /* otherwise, this is a sub-request */
1896            && (r->prev == NULL);   /* otherwise, this is an internal redirect */
1897 }