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