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