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