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